surrealql-language-server 0.6.0

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

use ls_types::{
    CodeAction, CodeActionKind, CodeActionOrCommand, CompletionItem, CompletionItemKind,
    Diagnostic, DiagnosticRelatedInformation, DiagnosticSeverity, DocumentChanges, Documentation,
    Location, MarkupContent, MarkupKind, OneOf, OptionalVersionedTextDocumentIdentifier, Position,
    Range, TextDocumentEdit, TextEdit, Uri, WorkspaceEdit,
};
use strsim::jaro_winkler;

use crate::config::{AuthContext, ServerSettings};
use crate::grammar::{
    BUILTIN_FUNCTIONS, BuiltinFunction, GENERATED_CONSTANTS, GENERATED_FUNCTION_TABLE,
    GENERATED_NAMESPACES, KEYWORDS, SPECIAL_VARIABLES, builtin_function, builtin_namespace,
    builtin_signature,
};
use crate::semantic::codes;
use crate::semantic::text::{LineIndex, compact_preview};
use crate::semantic::type_expr::TypeExpr;
use crate::semantic::type_name;
use crate::semantic::types::{
    AccessDef, AccessResult, AnalyzerDef, DocumentAnalysis, EventDef, FieldDef, FunctionDef,
    FunctionLanguage, FunctionParam, GraphIndex, IndexDef, LiveMetadataSnapshot, LookupDirection,
    MergedSemanticModel, NamedRange, ParamDef, PermissionMode, PermissionRule, QueryAction,
    QueryFact, SymbolOrigin, TableDef, TargetResolution, WorkspaceIndex,
};

impl MergedSemanticModel {
    pub fn build(workspace: &WorkspaceIndex, live: &LiveMetadataSnapshot) -> Self {
        let mut model = Self::default();
        // A failing (or partially failing) metadata fetch means remote
        // tables are missing from this model — judgments like "this
        // inferred name must be a typo" can't be trusted until the
        // connection recovers.
        model.metadata_degraded = !live.errors.is_empty();

        for analysis in workspace.documents.values() {
            model.absorb_analysis(analysis.as_ref());
        }
        for analysis in live.documents.values() {
            model.absorb_analysis(analysis.as_ref());
        }

        for analysis in workspace.documents.values() {
            for reference in &analysis.references {
                if reference.kind == ls_types::SymbolKind::FUNCTION {
                    model
                        .function_references
                        .entry(reference.name.clone())
                        .or_default()
                        .push(reference.location.clone());
                }
            }
        }

        model.reindex_target_usage();

        let function_names = model.functions.keys().cloned().collect::<Vec<_>>();
        for name in function_names {
            if let Some(function) = model.functions.get(&name) {
                for callee in &function.called_functions {
                    model
                        .function_callers
                        .entry(callee.clone())
                        .or_default()
                        .push(name.clone());
                }
            }
        }

        // Derive a return type for every `DEFINE FUNCTION` that omits `-> T`.
        // Must run last: it judges each definition against the one that won the
        // merge, so every document has to be absorbed first.
        //
        // Live documents are included deliberately. `INFO FOR DB` returns the
        // engine's own `DEFINE FUNCTION` text, body and all, and
        // `SurrealDbMetadataProvider` re-parses it through `analyze_document` —
        // so a remote function is as inferrable as a local one, and excluding
        // them would make a remote `fn::x` hover `unknown` while a byte-identical
        // local one hovers `string`.
        let documents: Vec<&DocumentAnalysis> = workspace
            .documents
            .values()
            .chain(live.documents.values())
            .map(|analysis| analysis.as_ref())
            .collect();
        crate::semantic::infer::infer_function_return_types(&documents, &mut model);
        // After the merge, so the `TYPE RELATION` half reads the definitions
        // that won it rather than ones a later document replaced.
        model.reindex_graph_edges(&documents);

        model
    }

    pub fn table_names_by_priority(&self) -> Vec<&TableDef> {
        let mut tables = self.tables.values().collect::<Vec<_>>();
        tables.sort_by(|left, right| {
            symbol_priority(right.origin)
                .cmp(&symbol_priority(left.origin))
                .then_with(|| left.name.cmp(&right.name))
        });
        tables
    }

    /// Returns *only* column (field) completion items for the given target
    /// tables. Use when the cursor is positioned in a slot that syntactically
    /// only accepts a column name (e.g. between `SELECT` and `FROM`, after
    /// `UPDATE tbl SET `, or after a `tbl.` qualifier).
    ///
    /// Mirrors the field branch of [`Self::completion_items`] but emits no
    /// keywords / functions / params / namespaces.
    pub fn column_completion_items(
        &self,
        prefix: &str,
        tables: &[String],
        multi_table_context: bool,
        _active_context: Option<&AuthContext>,
    ) -> Vec<CompletionItem> {
        let mut items = Vec::new();
        for table_name in tables {
            for implicit in self.implicit_fields(table_name) {
                let label = if multi_table_context {
                    format!("{table_name}.{implicit}")
                } else {
                    implicit.to_string()
                };
                if !(prefix.is_empty() || label.starts_with(prefix)) {
                    continue;
                }
                items.push(CompletionItem {
                    label: label.clone(),
                    kind: Some(CompletionItemKind::FIELD),
                    detail: Some(format!("table: {table_name} | source: built-in")),
                    insert_text: Some(label),
                    documentation: Some(Documentation::MarkupContent(MarkupContent {
                        kind: MarkupKind::Markdown,
                        value: implicit_field_hover(implicit, table_name),
                    })),
                    // Ranked with the defined fields rather than above them: it
                    // is a real column, but rarely the one being reached for.
                    sort_text: Some(format!("0-fld-{table_name}-{implicit}")),
                    ..CompletionItem::default()
                });
            }
            for field in self.fields_for_table(table_name) {
                let qualified_label = format!("{}.{}", field.table, field.name);
                let matches_prefix = prefix.is_empty()
                    || field.name.starts_with(prefix)
                    || (multi_table_context && qualified_label.starts_with(prefix));
                if !matches_prefix {
                    continue;
                }

                let label = if multi_table_context {
                    qualified_label.clone()
                } else {
                    field.name.clone()
                };
                let insert_text = if multi_table_context {
                    qualified_label
                } else {
                    field.name.clone()
                };
                let mut detail = vec![format!("table: {}", field.table)];
                if let Some(type_expr) = &field.type_expr {
                    detail.push(format!("type: {type_expr}"));
                }
                detail.push(format!("source: {}", origin_label(field.origin)));

                items.push(CompletionItem {
                    label,
                    kind: Some(CompletionItemKind::FIELD),
                    detail: Some(detail.join(" | ")),
                    insert_text: Some(insert_text),
                    documentation: Some(Documentation::MarkupContent(MarkupContent {
                        kind: MarkupKind::Markdown,
                        value: format_field_hover(field, self),
                    })),
                    sort_text: Some(format!("0-fld-{}-{}", field.table, field.name)),
                    ..CompletionItem::default()
                });
            }
        }
        items
    }

    /// The columns a table has without anyone declaring them.
    ///
    /// Every record carries an `id`, and every row of an edge table carries the
    /// `in` and `out` that `RELATE` wrote. No `DEFINE FIELD` mentions them, so
    /// nothing put them in the completion list — `SELECT id FROM person` is
    /// about as common as SurrealQL gets, and `id` was the one column the editor
    /// could not offer. The unknown-field check has always known about the same
    /// three names; this is the other half of that fact.
    ///
    /// A declared field of the same name wins, so a schema that spells out
    /// `DEFINE FIELD id` is not listed twice.
    pub(crate) fn implicit_fields(&self, table: &str) -> Vec<&'static str> {
        let declared = self.fields.get(table);
        let is_relation = self
            .tables
            .get(table)
            .is_some_and(|def| def.relation.is_some())
            || self.graph_edges.edge_targets.contains_key(table)
            || self.graph_edges.edge_sources.contains_key(table);

        let candidates: &[&'static str] = if is_relation {
            &["id", "in", "out"]
        } else {
            &["id"]
        };
        candidates
            .iter()
            .copied()
            .filter(|name| !declared.is_some_and(|fields| fields.contains_key(*name)))
            .collect()
    }

    /// Table-name completions for a cursor just after a graph arrow, with the
    /// tables that are actually reachable ranked to the top.
    ///
    /// `anchors` is where the hop starts. When `from_edge` is set the anchors
    /// name edge tables and the reachable set is the tables they lead to;
    /// otherwise they name ordinary tables and the reachable set is the edges
    /// leaving them.
    ///
    /// The unreachable tables are still offered, below. The graph is built from
    /// whatever the workspace happens to declare or write, so it is routinely
    /// incomplete — hiding a table because this server has not seen a `RELATE`
    /// for it would turn missing knowledge into a missing feature. Ranking says
    /// "these are the likely ones"; filtering would say "these are the only
    /// ones", which the server cannot know.
    ///
    /// With no anchor, or an anchor the graph knows nothing about, this is
    /// exactly [`Self::table_completion_items`].
    pub fn graph_completion_items(
        &self,
        prefix: &str,
        anchors: &[String],
        direction: LookupDirection,
        from_edge: bool,
        active_context: Option<&AuthContext>,
    ) -> Vec<CompletionItem> {
        let mut reachable: Vec<&str> = Vec::new();
        for anchor in anchors {
            let step = if from_edge {
                self.tables_across(anchor, direction)
            } else {
                self.edges_from(anchor, direction)
            };
            for name in step {
                if !reachable.contains(&name) {
                    reachable.push(name);
                }
            }
        }

        let mut items: Vec<CompletionItem> = reachable
            .iter()
            .filter(|name| prefix.is_empty() || name.starts_with(prefix))
            .map(|name| CompletionItem {
                label: (*name).to_string(),
                kind: Some(CompletionItemKind::STRUCT),
                detail: Some(self.graph_detail(name, anchors, direction, from_edge)),
                // `0-0-` beats every rank `table_completion_items` can produce:
                // its lowest is `0-1-`, for a builtin.
                sort_text: Some(format!("0-0-{name}")),
                data: Some(serde_json::json!({ "table": name })),
                ..CompletionItem::default()
            })
            .collect();

        items.extend(
            self.table_completion_items(prefix, active_context)
                .into_iter()
                .filter(|item| !reachable.contains(&item.label.as_str())),
        );
        items
    }

    /// The one-line description on a reachable graph completion, naming what
    /// makes it reachable.
    fn graph_detail(
        &self,
        name: &str,
        anchors: &[String],
        direction: LookupDirection,
        from_edge: bool,
    ) -> String {
        let arrow = match direction {
            LookupDirection::Right => "->",
            LookupDirection::Left => "<-",
            LookupDirection::Both => "<->",
        };
        if from_edge {
            return format!("reached by {}", anchors.join(", "));
        }
        // For an edge, the useful fact is where it goes next.
        let across = self.tables_across(name, direction);
        if across.is_empty() {
            format!("edge from {}", anchors.join(", "))
        } else {
            format!(
                "edge: {}{arrow}{name}{arrow}{}",
                anchors.join(", "),
                across.join(" | ")
            )
        }
    }

    /// Returns *only* table-name completion items (no keywords, functions,
    /// fields, params, etc). Use when the cursor is positioned in a slot
    /// that syntactically only accepts a table name (e.g. right after
    /// `SELECT * FROM `, `INSERT INTO `, `UPDATE `).
    /// `_active_context` is unused now that the hover text is built in
    /// [`Self::resolve_completion_item`], which reads the context itself. The
    /// parameter stays so the call sites keep their shape, matching
    /// [`Self::column_completion_items`].
    pub fn table_completion_items(
        &self,
        prefix: &str,
        _active_context: Option<&AuthContext>,
    ) -> Vec<CompletionItem> {
        self.table_names_by_priority()
            .into_iter()
            .filter(|table| prefix.is_empty() || table.name.starts_with(prefix))
            .map(|table| CompletionItem {
                label: table.name.clone(),
                kind: Some(CompletionItemKind::STRUCT),
                detail: Some(format!(
                    "{} schema, source: {}",
                    table
                        .schema_mode
                        .clone()
                        .unwrap_or_else(|| "inferred".to_string()),
                    origin_label(table.origin)
                )),
                // No `documentation` here. The client shows it for the one item
                // the user highlights, and asks for it through
                // `completionItem/resolve`; rendering the hover markdown for
                // every table meant a schema-sized cost on every keystroke that
                // opened the dropdown. `data` carries what resolve needs.
                data: Some(serde_json::json!({ "table": table.name })),
                sort_text: Some(format!(
                    "0-{}-{}",
                    symbol_priority(table.origin),
                    table.name
                )),
                ..CompletionItem::default()
            })
            .collect()
    }

    /// Fill in the documentation for one completion item, on demand.
    ///
    /// Returns the item unchanged when it carries no `data.table` — every other
    /// completion kind still ships whatever it was built with.
    pub fn resolve_completion_item(
        &self,
        mut item: CompletionItem,
        active_context: Option<&AuthContext>,
    ) -> CompletionItem {
        if item.documentation.is_some() {
            return item;
        }
        let table_name = item
            .data
            .as_ref()
            .and_then(|data| data.get("table"))
            .and_then(|name| name.as_str());
        let Some(table) = table_name.and_then(|name| self.tables.get(name)) else {
            return item;
        };
        item.documentation = Some(Documentation::MarkupContent(MarkupContent {
            kind: MarkupKind::Markdown,
            value: format_table_hover(table, self, active_context),
        }));
        item
    }

    /// The `DEFINE ANALYZER` names, for the slots that reference one.
    pub fn analyzer_completion_items(&self, prefix: &str) -> Vec<CompletionItem> {
        let mut items: Vec<CompletionItem> = self
            .analyzers
            .values()
            .filter(|analyzer| prefix.is_empty() || analyzer.name.starts_with(prefix))
            .map(|analyzer| CompletionItem {
                label: analyzer.name.clone(),
                kind: Some(CompletionItemKind::MODULE),
                detail: Some(format!(
                    "Analyzer, source: {}",
                    origin_label(analyzer.origin)
                )),
                sort_text: Some(format!(
                    "0-{}-{}",
                    symbol_priority(analyzer.origin),
                    analyzer.name
                )),
                ..CompletionItem::default()
            })
            .collect();
        items.sort_by(|left, right| left.label.cmp(&right.label));
        items
    }

    /// Insert or merge one field. This is the only correct way to add a field
    /// to the model — it applies the origin-priority merge.
    pub fn insert_field(&mut self, field: FieldDef) {
        self.insert_field_ref(&field);
    }

    /// [`Self::insert_field`] without an owned candidate, so the clone happens
    /// only when the candidate wins. See [`Self::insert_table_ref`].
    fn insert_field_ref(&mut self, field: &FieldDef) {
        // `entry` would clone the table name on every call. A workspace holds
        // far more fields than tables, so let only a table's first field pay
        // for the name; the rest find the inner map already there.
        if !self.fields.contains_key(&field.table) {
            self.fields.insert(field.table.clone(), HashMap::new());
        }
        let by_name = self
            .fields
            .get_mut(&field.table)
            .expect("inserted directly above when absent");
        let replace = by_name
            .get(&field.name)
            .map(|current| should_replace_field(current, field))
            .unwrap_or(true);
        if replace {
            by_name.insert(field.name.clone(), field.clone());
        }
    }

    /// Insert or merge one table, keeping
    /// [`MergedSemanticModel::explicit_tables`] in step. This is the only
    /// correct way to add a table to the model.
    ///
    /// A table's `explicit` flag only ever moves inferred → explicit — an
    /// explicit definition replaces an inferred one but never the reverse, see
    /// [`should_replace_table`] — so a name is appended at most once and never
    /// has to be removed.
    pub fn insert_table(&mut self, table: TableDef) {
        self.insert_table_ref(&table);
    }

    /// [`Self::insert_table`] without an owned candidate.
    ///
    /// A losing candidate is never cloned. `absorb_analysis` merges every
    /// definition of every document into one model, so the same table arrives
    /// once per document that mentions it, and once more from live metadata
    /// that mirrors it — most of those arrivals lose.
    fn insert_table_ref(&mut self, table: &TableDef) {
        let current = self.tables.get(&table.name);
        let replace = current
            .map(|current| should_replace_table(current, table))
            .unwrap_or(true);
        if !replace {
            return;
        }
        let was_explicit = current.is_some_and(|current| current.explicit);
        if table.explicit && !was_explicit {
            self.explicit_tables.push(table.name.clone());
        }
        self.tables.insert(table.name.clone(), table.clone());
    }

    /// Rebuild [`MergedSemanticModel::graph_edges`] from the two things that
    /// witness an edge: a `TYPE RELATION` declaration, and a `RELATE`
    /// statement.
    ///
    /// Declarations go in first because they are the stronger evidence — they
    /// state what the schema *permits*, while an observation only proves what
    /// some query happened to write. An observation that repeats a declared
    /// pair is dropped rather than duplicated.
    ///
    /// Takes the analyses rather than reading `self`, because the observations
    /// live per-document and never enter a `TableDef`. See the field's own doc
    /// comment for why they must not.
    pub fn reindex_graph_edges(&mut self, documents: &[&DocumentAnalysis]) {
        self.graph_edges = GraphIndex::default();

        for table in self.tables.values() {
            let Some(relation) = &table.relation else {
                continue;
            };
            for source in &relation.in_tables {
                push_unique(&mut self.graph_edges.outgoing, source, &table.name);
                push_unique(&mut self.graph_edges.edge_sources, &table.name, source);
            }
            for target in &relation.out_tables {
                push_unique(&mut self.graph_edges.incoming, target, &table.name);
                push_unique(&mut self.graph_edges.edge_targets, &table.name, target);
            }
        }

        for analysis in documents {
            for observation in &analysis.edge_observations {
                if let Some(from) = &observation.from {
                    push_unique(&mut self.graph_edges.outgoing, from, &observation.edge);
                    push_unique(&mut self.graph_edges.edge_sources, &observation.edge, from);
                }
                if let Some(to) = &observation.to {
                    push_unique(&mut self.graph_edges.incoming, to, &observation.edge);
                    push_unique(&mut self.graph_edges.edge_targets, &observation.edge, to);
                }
            }
        }
    }

    /// The edge tables reachable from `table` in `direction`, or an empty
    /// slice when the graph knows none.
    pub fn edges_from(&self, table: &str, direction: LookupDirection) -> Vec<&str> {
        let index = &self.graph_edges;
        let mut edges: Vec<&str> = Vec::new();
        for map in direction.maps(&index.outgoing, &index.incoming) {
            for edge in map.get(table).into_iter().flatten() {
                if !edges.contains(&edge.as_str()) {
                    edges.push(edge);
                }
            }
        }
        edges
    }

    /// The tables that `edge` reaches in `direction` — the second hop of
    /// `->edge->target`.
    pub fn tables_across(&self, edge: &str, direction: LookupDirection) -> Vec<&str> {
        let index = &self.graph_edges;
        let mut tables: Vec<&str> = Vec::new();
        for map in direction.maps(&index.edge_targets, &index.edge_sources) {
            for table in map.get(edge).into_iter().flatten() {
                if !tables.contains(&table.as_str()) {
                    tables.push(table);
                }
            }
        }
        tables
    }

    /// Recount [`MergedSemanticModel::target_usage`] from
    /// [`MergedSemanticModel::query_facts`]. One pass over the facts, run once
    /// per build rather than once per inferred target.
    pub fn reindex_target_usage(&mut self) {
        self.target_usage.clear();
        for fact in self.query_facts.values().flatten() {
            for table in &fact.target_tables {
                // `entry` would clone the name on every sighting. A repeated
                // target is the common case — counting them is the whole point
                // of this map — so only the first sighting of a name allocates.
                if let Some(count) = self.target_usage.get_mut(table) {
                    *count += 1;
                } else {
                    self.target_usage.insert(table.clone(), 1);
                }
            }
        }
    }

    pub fn fields_for_table(&self, table: &str) -> Vec<&FieldDef> {
        // Only this table's fields, rather than a filter over every field in
        // the workspace, and with no key allocated to reach them. The sort is
        // unchanged: origin priority first so a local definition outranks an
        // inferred one, then name. Name is unique within a table, so the order
        // is total and does not depend on the map's iteration order.
        let Some(by_name) = self.fields.get(table) else {
            return Vec::new();
        };
        let mut fields = by_name.values().collect::<Vec<_>>();
        fields.sort_by(|left, right| {
            symbol_priority(right.origin)
                .cmp(&symbol_priority(left.origin))
                .then_with(|| left.name.cmp(&right.name))
        });
        fields
    }

    pub fn events_for_table(&self, table: &str) -> Vec<&EventDef> {
        let mut events = self
            .events
            .values()
            .filter(|event| event.table == table)
            .collect::<Vec<_>>();
        events.sort_by(|left, right| {
            symbol_priority(right.origin)
                .cmp(&symbol_priority(left.origin))
                .then_with(|| left.name.cmp(&right.name))
        });
        events
    }

    pub fn indexes_for_table(&self, table: &str) -> Vec<&IndexDef> {
        let mut indexes = self
            .indexes
            .values()
            .filter(|index| index.table == table)
            .collect::<Vec<_>>();
        indexes.sort_by(|left, right| {
            symbol_priority(right.origin)
                .cmp(&symbol_priority(left.origin))
                .then_with(|| left.name.cmp(&right.name))
        });
        indexes
    }

    pub fn find_nearest_table(&self, unknown: &str) -> Option<&TableDef> {
        self.tables
            .values()
            .filter(|table| can_reach_near_miss_threshold(unknown, &table.name))
            .map(|table| (table, jaro_winkler(unknown, &table.name)))
            .filter(|(_, score)| *score > NEAR_MISS_THRESHOLD)
            .max_by(|left, right| {
                left.1
                    .partial_cmp(&right.1)
                    .unwrap_or(std::cmp::Ordering::Equal)
            })
            .map(|(table, _)| table)
    }

    /// Completion items for the `$variables` in scope at `position`.
    ///
    /// These were never offered before — only `SPECIAL_VARIABLES` and
    /// `DEFINE PARAM` entries reached the dropdown, so a `LET` binding two
    /// lines up was invisible.
    pub fn variable_completion_items(
        &self,
        analysis: &DocumentAnalysis,
        position: Position,
        prefix: &str,
    ) -> Vec<CompletionItem> {
        let offset = analysis.line_index.offset(&analysis.text, position);
        let bindings = crate::semantic::infer::resolve_bindings(analysis, self);
        bindings
            .visible_at(offset)
            .into_iter()
            .filter(|binding| prefix.is_empty() || binding.name.starts_with(prefix))
            .map(|binding| CompletionItem {
                label: binding.name.clone(),
                kind: Some(CompletionItemKind::VARIABLE),
                // `CompletionItemKind::VARIABLE` already says "variable";
                // the useful detail is the type it holds.
                detail: Some(binding.ty.to_string()),
                insert_text: Some(binding.name.clone()),
                sort_text: Some(format!("0-var-{}", binding.name)),
                ..CompletionItem::default()
            })
            .collect()
    }

    /// Completion items for a `value.` position: the methods that receiver
    /// accepts.
    ///
    /// SurrealQL admits both a field and a method after a `.`, so these are meant
    /// to be *added* to whatever the position already offers, never to replace
    /// it.
    ///
    /// When the receiver's type is known, only that receiver's methods are
    /// offered and they sort alongside the fields. When it is not — which is
    /// still common, since a field access or a statement result types as
    /// `unknown` — every method is offered, sorted below everything else. An
    /// empty list would read as "this feature is broken" in exactly the positions
    /// people use most.
    /// The named members legal after a `.`, read from the receiver's type.
    ///
    /// Answers for a row a query built as well as for a record that points at a
    /// declared table — `$person.` after
    /// `LET $people = (SELECT id, name, age FROM person)` offers `id`, `name`
    /// and `age`. Empty when the receiver has no named members, which leaves
    /// every other completion path exactly as it was.
    pub fn property_completion_items(
        &self,
        analysis: &DocumentAnalysis,
        position: Position,
        prefix: &str,
    ) -> Vec<CompletionItem> {
        let Some(receiver) = self.receiver_type_at(analysis, position) else {
            return Vec::new();
        };
        let bindings = crate::semantic::infer::resolve_bindings(analysis, self);
        let ctx = crate::semantic::infer::TypeCtx {
            model: self,
            source: &analysis.text,
            lines: &analysis.line_index,
            bindings: &bindings,
        };

        crate::semantic::infer::property_names(&receiver, &ctx)
            .into_iter()
            .filter(|name| prefix.is_empty() || name.starts_with(prefix))
            .map(|name| {
                let ty = crate::semantic::infer::property_type(&receiver, &name, &ctx);
                let detail = match &ty {
                    TypeExpr::Unknown => "property".to_string(),
                    known => format!("property | type: {known}"),
                };
                CompletionItem {
                    label: name.clone(),
                    kind: Some(CompletionItemKind::FIELD),
                    detail: Some(detail),
                    insert_text: Some(name.clone()),
                    // Above a method: after a `.` on a row, the author is far
                    // likelier to be reaching for one of its own columns.
                    sort_text: Some(format!("0-prp-{name}")),
                    ..CompletionItem::default()
                }
            })
            .collect()
    }

    /// The type of whatever sits immediately left of the `.` at `position`.
    ///
    /// Shared by property and method completion so the two agree about what the
    /// receiver is.
    fn receiver_type_at(
        &self,
        analysis: &DocumentAnalysis,
        position: Position,
    ) -> Option<TypeExpr> {
        let offset = analysis.line_index.offset(&analysis.text, position);
        let dot = method_dot_offset(&analysis.text, offset)?;
        let bindings = crate::semantic::infer::resolve_bindings(analysis, self);
        let ctx = crate::semantic::infer::TypeCtx {
            model: self,
            source: &analysis.text,
            lines: &analysis.line_index,
            bindings: &bindings,
        };
        // Through the idiom, so a chain resolves: `$person.address.` reads the
        // whole path up to the second dot, not just the `address` token.
        crate::semantic::infer::idiom_type_at(analysis, dot.saturating_sub(1), &ctx)
    }

    pub fn method_completion_items(
        &self,
        analysis: &DocumentAnalysis,
        position: Position,
        prefix: &str,
    ) -> Vec<CompletionItem> {
        let offset = analysis.line_index.offset(&analysis.text, position);
        let Some(dot) = method_dot_offset(&analysis.text, offset) else {
            return Vec::new();
        };

        // Type whatever sits immediately left of the dot.
        let receiver = analysis
            .tree
            .root_node()
            .named_descendant_for_byte_range(dot.saturating_sub(1), dot);
        let receiver_type = match receiver {
            Some(node) => {
                let bindings = crate::semantic::infer::resolve_bindings(analysis, self);
                let ctx = crate::semantic::infer::TypeCtx {
                    model: self,
                    source: &analysis.text,
                    lines: &analysis.line_index,
                    bindings: &bindings,
                };
                crate::semantic::infer::infer_expr_type(node, &ctx)
            }
            None => TypeExpr::Unknown,
        };

        let known = crate::semantic::method::receiver_kind(&receiver_type);
        let (methods, rank): (Vec<_>, &str) = match known {
            Some(kind) => (
                crate::semantic::method::methods_for(kind).iter().collect(),
                "0-mtd",
            ),
            None => (
                crate::grammar::GENERATED_RECEIVERS
                    .iter()
                    .flat_map(|receiver| receiver.methods.iter())
                    .collect(),
                "3-mtd",
            ),
        };

        let mut seen: Vec<&str> = Vec::new();
        let mut items = Vec::new();
        for method in methods {
            if !prefix.is_empty() && !method.method.starts_with(prefix) {
                continue;
            }
            // The fallback list draws from twelve tables, and `to_string` is on
            // all of them.
            if seen.contains(&method.method) {
                continue;
            }
            seen.push(method.method);

            let signature = builtin_signature(method.function);
            let mut detail = method.function.to_string();
            if let Some(rendered) = signature
                .as_ref()
                .and_then(|found| found.display_signature())
            {
                detail = rendered;
            }
            if let Some(target) = method.experimental {
                detail.push_str(&format!(" (experimental: {target})"));
            }

            items.push(CompletionItem {
                label: method.method.to_string(),
                kind: Some(CompletionItemKind::METHOD),
                detail: Some(detail),
                documentation: builtin_function(method.function).map(|curated| {
                    Documentation::MarkupContent(MarkupContent {
                        kind: MarkupKind::Markdown,
                        value: format_builtin_function_hover(curated, method.function),
                    })
                }),
                insert_text: Some(method.method.to_string()),
                sort_text: Some(format!("{rank}-{}", method.method)),
                ..CompletionItem::default()
            });
        }
        items
    }

    /// Position-aware hover.
    ///
    /// A `$variable` can only be resolved with a position: the same name
    /// may be bound several times in one document, and the enclosing
    /// scope decides which one is meant. Everything else is
    /// position-independent and falls through to
    /// [`Self::hover_markdown_for_token`].
    pub fn hover_markdown_at(
        &self,
        analysis: &DocumentAnalysis,
        position: Position,
        token: &str,
        active_context: Option<&AuthContext>,
        field_tables: &[String],
    ) -> Option<String> {
        let offset = analysis.line_index.offset(&analysis.text, position);

        // A method resolves through its receiver, not through the global function
        // tables. This must run before `hover_markdown_for_token`, which sees only
        // the bare word and would answer with the `AT` / `SPLIT` keyword.
        if let Some(hover) = self.method_hover(analysis, offset) {
            return Some(hover);
        }

        if token.starts_with('$') {
            let bindings = crate::semantic::infer::resolve_bindings(analysis, self);
            if let Some(binding) = bindings.at(token, offset) {
                return Some(format_binding_hover(binding));
            }
        }

        // `.age` read off a value, before the schema lookup: the value's own
        // shape decides what the member is, and it may be a row a query built
        // rather than a table anyone declared.
        if let Some(hover) = self.property_hover(analysis, offset) {
            return Some(hover);
        }

        // Before the global lookup, because a column and a table can share a
        // name and inside `SELECT name FROM person` the column is what the
        // pointer is on.
        if let Some(hover) = self.field_hover(analysis, position, field_tables) {
            return Some(hover);
        }

        self.hover_markdown_for_token(token, active_context)
    }

    /// Hover for `.name` read off a value — `$person.age`.
    ///
    /// Resolves through the *value's* type rather than the schema, so it answers
    /// for a row a query built (`LET $people = (SELECT id, name, age FROM …)`)
    /// as well as for a record that points at a declared table. Where the
    /// receiver is a record, the declared column wins: its hover carries the
    /// comment, the permissions and the indexes that a bare type cannot.
    fn property_hover(&self, analysis: &DocumentAnalysis, offset: usize) -> Option<String> {
        use crate::semantic::node_kind as k;

        // Both offsets, because the two halves of hover disagree about where a
        // cursor is: `token_at` reads the character *before* the position, while
        // a tree lookup reads the one *at* it. On the first character of a
        // segment only the former lands inside it, on the position just past the
        // last only the latter does.
        let subscript = [offset, offset.saturating_sub(1)]
            .into_iter()
            .find_map(|at| {
                let node = analysis
                    .tree
                    .root_node()
                    .named_descendant_for_byte_range(at, at)?;
                // A zero-width lookup on a segment's first character can land
                // on the segment itself rather than on its name.
                if node.kind() == k::SUBSCRIPT {
                    return Some(node);
                }
                // Only a `.name` segment, not the base and not a method call.
                let parent = node.parent()?;
                (node.kind() == k::IDENT && parent.kind() == k::SUBSCRIPT).then_some(parent)
            })?;
        let name = k::text_of(&analysis.text, k::find_child(subscript, k::IDENT)?)?;

        let bindings = crate::semantic::infer::resolve_bindings(analysis, self);
        let ctx = crate::semantic::infer::TypeCtx {
            model: self,
            source: &analysis.text,
            lines: &analysis.line_index,
            bindings: &bindings,
        };

        // The receiver is the idiom up to just before this segment.
        let receiver = crate::semantic::infer::idiom_type_at(
            analysis,
            subscript.start_byte().saturating_sub(1),
            &ctx,
        )?;

        // A record points *at* a table, so the declared column is the better
        // answer: it carries the comment, the permissions and the indexes that a
        // bare type cannot.
        //
        // Only when the receiver is itself a record, though. `record_tables()`
        // on a *row* collects the tables of every record-typed column in it, so
        // reading `name` off `SELECT name, author FROM book` would resolve
        // against `person` — whatever `author` points at — instead of `book`.
        if let Some(tables) = record_target_tables(&receiver) {
            for table in tables {
                if let Some(field) = self.fields.get(table).and_then(|by| by.get(name)) {
                    return Some(format_field_hover(field, self));
                }
                if self.implicit_fields(table).contains(&name) {
                    return Some(implicit_field_hover(name, table));
                }
            }
        }

        let ty = crate::semantic::infer::property_type(&receiver, name, &ctx);
        if matches!(ty, TypeExpr::Unknown) {
            return None;
        }
        Some(hover_block(
            format!("PROPERTY {name}"),
            None,
            vec![format!("Type: `{ty}`"), format!("Read from: `{receiver}`")],
            Vec::new(),
        ))
    }

    /// Hover for a column, resolved against the tables the statement reads.
    ///
    /// A column name means nothing on its own — `name` is a column of whichever
    /// table the statement targets — which is why this needs `field_tables`
    /// rather than working from the token alone, and why nothing resolved a
    /// column before: [`Self::hover_markdown_for_token`] only ever sees a bare
    /// word.
    fn field_hover(
        &self,
        analysis: &DocumentAnalysis,
        position: Position,
        field_tables: &[String],
    ) -> Option<String> {
        let path =
            crate::semantic::text::dotted_path_at(&analysis.text, &analysis.line_index, position)?;

        // The statement's own tables first. `person.name` written out is the
        // rarer form, and a table that happens to share a column's name must
        // not shadow the column the pointer is actually on.
        for table in field_tables {
            if let Some(field) = self
                .fields
                .get(table)
                .and_then(|by_name| by_name.get(&path))
            {
                return Some(format_field_hover(field, self));
            }
        }
        // Written as `table.column`, which names its own table.
        if let Some((head, rest)) = path.split_once('.')
            && let Some(field) = self.fields.get(head).and_then(|by_name| by_name.get(rest))
        {
            return Some(format_field_hover(field, self));
        }
        // A column every record has, that no `DEFINE FIELD` declares.
        for table in field_tables {
            if self.implicit_fields(table).contains(&path.as_str()) {
                return Some(implicit_field_hover(&path, table));
            }
        }
        None
    }

    /// Hover for a method call, resolved through the engine's receiver tables.
    fn method_hover(&self, analysis: &DocumentAnalysis, offset: usize) -> Option<String> {
        let (idiom, method) = method_at(analysis, offset)?;
        let receiver = crate::semantic::infer::method_receiver(idiom)?;

        let bindings = crate::semantic::infer::resolve_bindings(analysis, self);
        let ctx = crate::semantic::infer::TypeCtx {
            model: self,
            source: &analysis.text,
            lines: &analysis.line_index,
            bindings: &bindings,
        };
        let receiver_type = crate::semantic::infer::infer_expr_type(receiver, &ctx);
        let resolved = crate::semantic::method::resolve(&receiver_type, &method)?;

        let mut metadata = vec![format!("Resolves to `{}`", resolved.function)];
        if let Some(target) = resolved.experimental {
            metadata.push(format!("Experimental: requires `{target}`"));
        }

        let signature = builtin_signature(resolved.function)
            .and_then(|signature| signature.display_signature());
        // The signature ends in `-> type` whenever one is known, so saying it
        // again here would only repeat the title. State it when there is no
        // signature to carry it.
        if signature.is_none()
            && let Some(returns) = crate::semantic::method::return_type(resolved.function)
        {
            metadata.push(format!("Returns: `{returns}`"));
        }

        let title = signature.unwrap_or_else(|| format!("{}()", resolved.function));
        let summary =
            builtin_function(resolved.function).map(|curated| curated.summary.to_string());
        let sections = builtin_function(resolved.function)
            .map(|curated| vec![format!("[Docs]({})", curated.documentation_url)])
            .unwrap_or_default();

        Some(hover_block(
            format!(".{method}() — {title}"),
            summary,
            metadata,
            sections,
        ))
    }

    /// Like [`Self::find_nearest_table`], but only explicitly defined
    /// tables qualify as "did you mean" candidates — suggesting an
    /// inferred name would just echo another usage site back.
    fn find_nearest_explicit_table(&self, unknown: &str) -> Option<&TableDef> {
        // Over `explicit_tables`, not `tables.values()`. The candidates are a
        // contiguous run of names; the alternative walked every inferred table
        // in the workspace to discard it on the next line.
        let best = self
            .explicit_tables
            .iter()
            .filter(|name| name.as_str() != unknown)
            .filter(|name| can_reach_near_miss_threshold(unknown, name))
            .map(|name| (name, jaro_winkler(unknown, name)))
            .filter(|(_, score)| *score > NEAR_MISS_THRESHOLD)
            .max_by(|left, right| {
                left.1
                    .partial_cmp(&right.1)
                    .unwrap_or(std::cmp::Ordering::Equal)
            })
            .map(|(name, _)| name)?;
        self.tables.get(best)
    }

    /// Like [`Self::find_nearest_explicit_table`], but restricted to
    /// candidates that plausibly indicate a *typo* rather than a
    /// deliberate sibling name: bare singular/plural pairs
    /// (`orders`/`order`, `categories`/`category`) score ~0.96 on
    /// jaro-winkler yet are the most common intentional naming
    /// pattern in schemas, so they are excluded here.
    fn find_probable_typo_of_explicit_table(&self, unknown: &str) -> Option<&TableDef> {
        self.find_nearest_explicit_table(unknown)
            .filter(|candidate| !is_plural_variant(unknown, &candidate.name))
    }

    /// How many query facts across the workspace target `name`. A
    /// name used in several statements is a deliberate table, not a
    /// one-off typo.
    fn target_usage_count(&self, name: &str) -> usize {
        self.target_usage.get(name).copied().unwrap_or(0)
    }

    /// Nearest explicitly defined field on `table` — the unknown-field
    /// "did you mean" candidate.
    fn find_nearest_explicit_field(&self, table: &str, unknown: &str) -> Option<&FieldDef> {
        // Only this table's fields rather than a filter over every field in
        // the workspace — the same reason `fields_for_table` reads the group.
        self.fields
            .get(table)?
            .values()
            .filter(|field| field.name.as_str() != unknown)
            .filter(|field| can_reach_near_miss_threshold(unknown, &field.name))
            .filter(|field| field.explicit)
            .map(|field| (field, jaro_winkler(unknown, &field.name)))
            .filter(|(_, score)| *score > NEAR_MISS_THRESHOLD)
            .max_by(|left, right| {
                left.1
                    .partial_cmp(&right.1)
                    .unwrap_or(std::cmp::Ordering::Equal)
            })
            .map(|(field, _)| field)
    }

    pub fn hover_markdown_for_token(
        &self,
        token: &str,
        active_context: Option<&AuthContext>,
    ) -> Option<String> {
        let trimmed = token.trim();
        if trimmed.is_empty() {
            return None;
        }

        if let Some(table) = self.tables.get(trimmed) {
            return Some(format_table_hover(table, self, active_context));
        }
        if let Some(function) = self.functions.get(trimmed) {
            return Some(format_function_hover(
                function,
                self.inferred_function_returns.get(trimmed),
            ));
        }
        // The curated table first: its 79 entries carry prose and a docs link
        // that no generator can produce.
        if let Some(function) = builtin_function(trimmed) {
            return Some(format_builtin_function_hover(function, trimmed));
        }
        // Then the generated catalogue, which covers the other 18 namespaces.
        // Before this, hovering `math::abs` answered nothing at all.
        if let Some(signature) = builtin_signature(trimmed) {
            return Some(format_generated_function_hover(signature, trimmed));
        }
        if let Some(param) = self.params.get(trimmed) {
            return Some(format_param_hover(param));
        }
        if let Some(access) = self.accesses.get(trimmed) {
            return Some(format_access_hover(access));
        }
        let parsed_type = TypeExpr::parse(trimmed);
        let record_tables = parsed_type.record_tables();
        if record_tables.len() == 1 {
            if let Some(table) = self.tables.get(&record_tables[0]) {
                return Some(join_hover_blocks([
                    hover_block(
                        format!("`{parsed_type}`"),
                        None,
                        vec!["Source: type expression".to_string()],
                        vec!["Resolves to:".to_string()],
                    ),
                    format_table_hover(table, self, active_context),
                ]));
            }
        }
        if KEYWORDS
            .iter()
            .any(|keyword| keyword.eq_ignore_ascii_case(trimmed))
        {
            return Some(hover_block(
                format!("`{trimmed}`"),
                Some("SurrealQL keyword.".to_string()),
                vec!["Source: builtin".to_string()],
                Vec::new(),
            ));
        }
        if let Some(namespace) = builtin_namespace(trimmed) {
            return Some(hover_block(
                format!("`{}` builtin namespace", namespace.name),
                Some(namespace.summary.to_string()),
                vec!["Source: builtin".to_string()],
                vec![format!("[Docs]({})", namespace.documentation_url)],
            ));
        }
        if GENERATED_NAMESPACES
            .iter()
            .any(|namespace| namespace.eq_ignore_ascii_case(trimmed))
        {
            return Some(hover_block(
                format!("`{trimmed}` builtin namespace"),
                None,
                vec!["Source: builtin".to_string()],
                Vec::new(),
            ));
        }
        if let Some((_, description)) = SPECIAL_VARIABLES
            .iter()
            .find(|(name, _)| name.eq_ignore_ascii_case(trimmed))
        {
            return Some(hover_block(
                format!("`{trimmed}`"),
                Some((*description).to_string()),
                vec!["Source: builtin".to_string()],
                Vec::new(),
            ));
        }
        None
    }

    pub fn completion_items(
        &self,
        prefix: &str,
        record_type_context: bool,
        active_context: Option<&AuthContext>,
        statement_fact: Option<&QueryFact>,
        qualifier: Option<&str>,
    ) -> Vec<CompletionItem> {
        let mut items = Vec::new();
        let normalized = prefix.to_ascii_uppercase();
        let normalized_builtin = prefix.to_ascii_lowercase();

        if !record_type_context {
            for keyword in KEYWORDS {
                if normalized.is_empty() || keyword.starts_with(&normalized) {
                    items.push(CompletionItem {
                        label: keyword.to_string(),
                        kind: Some(CompletionItemKind::KEYWORD),
                        detail: Some("SurrealQL keyword".to_string()),
                        insert_text: Some(keyword.to_string()),
                        ..CompletionItem::default()
                    });
                }
            }

            for namespace in GENERATED_NAMESPACES {
                if prefix.is_empty() || namespace.starts_with(&normalized_builtin) {
                    items.push(CompletionItem {
                        label: namespace.to_string(),
                        kind: Some(CompletionItemKind::MODULE),
                        detail: Some("Builtin function namespace".to_string()),
                        insert_text: Some(namespace.to_string()),
                        ..CompletionItem::default()
                    });
                }
            }

            for function in self.functions.values() {
                if prefix.is_empty() || function.name.starts_with(prefix) {
                    items.push(CompletionItem {
                        label: function.name.clone(),
                        kind: Some(CompletionItemKind::FUNCTION),
                        detail: Some(function_signature_with_return(
                            function,
                            self.inferred_function_returns.get(&function.name),
                        )),
                        documentation: Some(Documentation::MarkupContent(MarkupContent {
                            kind: MarkupKind::Markdown,
                            value: format_function_hover(
                                function,
                                self.inferred_function_returns.get(&function.name),
                            ),
                        })),
                        sort_text: Some(format!("1-{}", function.name)),
                        ..CompletionItem::default()
                    });
                }
            }

            // The curated table first: its 79 entries carry prose and a docs
            // link that no generator can produce.
            for function in BUILTIN_FUNCTIONS {
                if prefix.is_empty() || function.name.starts_with(&normalized_builtin) {
                    items.push(CompletionItem {
                        label: function.name.to_string(),
                        kind: Some(CompletionItemKind::FUNCTION),
                        detail: Some(function.signature.to_string()),
                        documentation: Some(Documentation::MarkupContent(MarkupContent {
                            kind: MarkupKind::Markdown,
                            value: format_builtin_function_hover(function, function.name),
                        })),
                        sort_text: Some(format!("2-{}", function.name)),
                        ..CompletionItem::default()
                    });
                }
            }

            // Then the generated catalogue, which is the other 355. Without this
            // the dropdown only ever held `string::` and `type::` — the two
            // namespaces the curated table happens to cover — so typing `rand::`
            // offered the namespace and then nothing inside it, and the same for
            // `array::` (62 functions), `math::` (42) and `time::` (37).
            //
            // Curated entries win, so a function with prose keeps it.
            for function in GENERATED_FUNCTION_TABLE {
                if !prefix.is_empty() && !function.name.starts_with(&normalized_builtin) {
                    continue;
                }
                if builtin_function(function.name).is_some() {
                    continue;
                }
                let signature = builtin_signature(function.name);
                let detail = signature
                    .as_ref()
                    .and_then(|found| found.display_signature())
                    .unwrap_or_else(|| format!("{}(…)", function.name));
                items.push(CompletionItem {
                    label: function.name.to_string(),
                    kind: Some(CompletionItemKind::FUNCTION),
                    detail: Some(detail),
                    // A name the parser accepts that nothing implements. Offering
                    // it silently would hand the user a query that parses and
                    // then fails.
                    deprecated: Some(function.not_callable),
                    sort_text: Some(format!("2-{}", function.name)),
                    ..CompletionItem::default()
                });
            }

            // Constants such as `math::PI`. They take no arguments, so they are
            // not in `GENERATED_FUNCTIONS` at all.
            for constant in GENERATED_CONSTANTS {
                // Compared case-insensitively: a constant is spelled in upper
                // case (`math::PI`) while `normalized_builtin` is lowered, so a
                // `starts_with` on the raw names never matches.
                if prefix.is_empty()
                    || constant
                        .to_ascii_lowercase()
                        .starts_with(&normalized_builtin)
                {
                    items.push(CompletionItem {
                        label: constant.to_string(),
                        kind: Some(CompletionItemKind::CONSTANT),
                        detail: Some("Builtin constant".to_string()),
                        sort_text: Some(format!("2-{constant}")),
                        ..CompletionItem::default()
                    });
                }
            }
        }

        for table in self.table_names_by_priority() {
            if prefix.is_empty() || table.name.starts_with(prefix) {
                items.push(CompletionItem {
                    label: table.name.clone(),
                    kind: Some(if record_type_context {
                        CompletionItemKind::TYPE_PARAMETER
                    } else {
                        CompletionItemKind::STRUCT
                    }),
                    detail: Some(format!(
                        "{} schema, source: {}",
                        table
                            .schema_mode
                            .clone()
                            .unwrap_or_else(|| "inferred".to_string()),
                        origin_label(table.origin)
                    )),
                    documentation: Some(Documentation::MarkupContent(MarkupContent {
                        kind: MarkupKind::Markdown,
                        value: format_table_hover(table, self, active_context),
                    })),
                    sort_text: Some(format!(
                        "0-{}-{}",
                        symbol_priority(table.origin),
                        table.name
                    )),
                    ..CompletionItem::default()
                });
            }
        }

        if !record_type_context {
            let field_tables = field_completion_tables(statement_fact, qualifier);
            let multi_table_context = qualifier.is_none() && field_tables.len() > 1;

            for table_name in field_tables {
                for field in self.fields_for_table(&table_name) {
                    let qualified_label = format!("{}.{}", field.table, field.name);
                    let matches_prefix = prefix.is_empty()
                        || field.name.starts_with(prefix)
                        || (multi_table_context && qualified_label.starts_with(prefix));
                    if !matches_prefix {
                        continue;
                    }

                    let label = if multi_table_context {
                        qualified_label.clone()
                    } else {
                        field.name.clone()
                    };
                    let insert_text = if multi_table_context {
                        qualified_label
                    } else {
                        field.name.clone()
                    };
                    let mut detail = vec![format!("table: {}", field.table)];
                    if let Some(type_expr) = &field.type_expr {
                        detail.push(format!("type: {type_expr}"));
                    }
                    detail.push(format!("source: {}", origin_label(field.origin)));

                    items.push(CompletionItem {
                        label,
                        kind: Some(CompletionItemKind::FIELD),
                        detail: Some(detail.join(" | ")),
                        insert_text: Some(insert_text),
                        documentation: Some(Documentation::MarkupContent(MarkupContent {
                            kind: MarkupKind::Markdown,
                            value: format_field_hover(field, self),
                        })),
                        // `0-fld-...` sorts above `1-` user functions, `2-`
                        // builtin functions, and unsorted keywords so that
                        // in loose contexts (WHERE / ORDER BY / GROUP BY)
                        // the relevant column names surface first.
                        sort_text: Some(format!("0-fld-{}-{}", field.table, field.name)),
                        ..CompletionItem::default()
                    });
                }
            }
        }

        for (name, description) in SPECIAL_VARIABLES {
            if prefix.is_empty() || name.starts_with(prefix) {
                items.push(CompletionItem {
                    label: (*name).to_string(),
                    kind: Some(CompletionItemKind::VARIABLE),
                    detail: Some("Special SurrealQL variable".to_string()),
                    documentation: Some(Documentation::MarkupContent(MarkupContent {
                        kind: MarkupKind::Markdown,
                        value: (*description).to_string(),
                    })),
                    ..CompletionItem::default()
                });
            }
        }

        // `DEFINE PARAM` names. The model has held these all along — hover and
        // go-to-definition both resolve them — but nothing ever offered them,
        // so a parameter defined in another file was invisible while typing.
        for param in self.params.values() {
            if prefix.is_empty() || param.name.starts_with(prefix) {
                items.push(CompletionItem {
                    label: param.name.clone(),
                    kind: Some(CompletionItemKind::VARIABLE),
                    detail: Some(format!(
                        "DEFINE PARAM, source: {}",
                        origin_label(param.origin)
                    )),
                    documentation: Some(Documentation::MarkupContent(MarkupContent {
                        kind: MarkupKind::Markdown,
                        value: format_param_hover(param),
                    })),
                    // Above the special variables, which carry no sort text: a
                    // parameter the author defined is likelier than `$before`.
                    sort_text: Some(format!("0-1-{}", param.name)),
                    ..CompletionItem::default()
                });
            }
        }

        items.sort_by(|left, right| {
            left.sort_text
                .cmp(&right.sort_text)
                .then_with(|| left.label.cmp(&right.label))
        });
        items
    }

    /// True when `table` is a declared `SCHEMALESS` table and the active
    /// `analysis.schemalessDiagnostics` value says `code` must not be reported
    /// on it.
    ///
    /// Deliberately keyed on the **keyword**, not on SurrealDB's effective
    /// schema mode. A bare `DEFINE TABLE t` is schemaless to the engine, but it
    /// leaves `schema_mode` unset, and this setting exists to honor a signal the
    /// author wrote down. Writing `SCHEMALESS` is that signal; omitting the
    /// clause is not. Keeping the two apart also leaves the checks on a bare
    /// `DEFINE TABLE` exactly as they were before this setting existed.
    ///
    /// An unknown or inferred table answers `false`: nothing may be hidden on
    /// the strength of a schema mode nobody declared.
    pub fn schemaless_hides(&self, table: &str, code: &str, settings: &ServerSettings) -> bool {
        let Some(table_def) = self.tables.get(table) else {
            return false;
        };
        if !table_def.explicit || !is_schemaless(table_def) {
            return false;
        }
        !codes::reports_on_schemaless(code, &settings.analysis.schemaless_diagnostics)
    }

    /// Drop the diagnostics that [`Self::schemaless_hides`] covers but that no
    /// emission site could filter for itself.
    ///
    /// Only `unknown-type` needs this. It is raised by the syntax pass
    /// ([`crate::semantic::analyzer`]), which reads one document and cannot see
    /// the merged model, so it records the table it belongs to in
    /// `Diagnostic.data` and the decision is deferred to here. Every other code
    /// in [`codes::SCHEMALESS_SCOPED_CODES`] is filtered where it is emitted.
    ///
    /// This is a method on the model rather than a private helper in the server
    /// so the diagnostic tests can exercise it without an LSP round trip.
    pub fn apply_schemaless_policy(
        &self,
        diagnostics: &mut Vec<Diagnostic>,
        settings: &ServerSettings,
    ) {
        // Cheap exit on the setting that changes nothing, so the common
        // `strict` case does not walk the list at all.
        if settings.analysis.schemaless_diagnostics == "strict" {
            return;
        }
        diagnostics.retain(|diagnostic| {
            if !codes::has_code(diagnostic, codes::UNKNOWN_TYPE) {
                return true;
            }
            let Some(table) = diagnostic
                .data
                .as_ref()
                .and_then(|data| data.get("table"))
                .and_then(|value| value.as_str())
            else {
                return true;
            };
            !self.schemaless_hides(table, codes::UNKNOWN_TYPE, settings)
        });
    }

    pub fn semantic_diagnostics(
        &self,
        analysis: &DocumentAnalysis,
        settings: &ServerSettings,
    ) -> Vec<Diagnostic> {
        let mut diagnostics = crate::semantic::infer::type_diagnostics(analysis, self, settings);
        let active_context = settings.active_auth_context();

        for fact in analysis.query_facts.iter() {
            if fact.target_tables.is_empty() {
                // `$param` / expression targets are resolvable only at
                // runtime — warning about them is pure noise.
                if matches!(
                    fact.target_resolution,
                    TargetResolution::Parameter | TargetResolution::Expression
                ) {
                    continue;
                }
                diagnostics.push(Diagnostic {
                    range: fact.location.range,
                    severity: Some(DiagnosticSeverity::WARNING),
                    code: codes::as_code(codes::DYNAMIC_TARGET),
                    source: Some("surreal-language-server".to_string()),
                    message: format!(
                        "{} target could not be resolved statically.",
                        action_label(fact.action)
                    ),
                    ..Diagnostic::default()
                });
                continue;
            }

            for table in &fact.target_tables {
                let table_range = range_for_name(&fact.target_refs, table, fact.location.range);
                let table_def = match self.tables.get(table) {
                    None => {
                        let suggestion = self.find_nearest_explicit_table(table);
                        diagnostics.push(self.unknown_table_diagnostic(
                            table,
                            table_range,
                            suggestion,
                        ));
                        continue;
                    }
                    // The statement being checked is itself enough to
                    // *infer* a table, so a typo'd name always "exists"
                    // by the time we validate it. An inferred-only def
                    // is treated as a typo only when ALL of these hold:
                    //
                    // 1. Live metadata is healthy. When the DB fetch
                    //    is failing (including partial per-table INFO
                    //    errors), previously-known remote tables drop
                    //    out of the model and would light up as
                    //    near-misses in bulk — right when the
                    //    "metadata unavailable" toast already fires.
                    // 2. The name is used only once across the
                    //    workspace. Repeated usage means a deliberate
                    //    (if undeclared) table; the trade-off is that
                    //    the same typo pasted twice goes silent.
                    // 3. An explicit table is a near-miss that is NOT
                    //    a bare singular/plural sibling — `orders`
                    //    next to `order` is a naming convention, not a
                    //    typo, and the quick fix would rewrite the
                    //    query against a different real table.
                    //
                    // Everything else stays untouched — schema
                    // inference from usage is a feature, not an error.
                    Some(table_def) if !table_def.explicit => {
                        if !self.metadata_degraded && self.target_usage_count(table) <= 1 {
                            if let Some(suggestion) =
                                self.find_probable_typo_of_explicit_table(table)
                            {
                                diagnostics.push(self.unknown_table_diagnostic(
                                    table,
                                    table_range,
                                    Some(suggestion),
                                ));
                                continue;
                            }
                        }
                        table_def
                    }
                    Some(table_def) => table_def,
                };

                // SELECT and RELATE are intentionally exempt from
                // static permission checking: their permission rules
                // routinely depend on row-level state (e.g.
                // `WHERE $auth.id = id`) that can't be evaluated
                // without the actual record, so the diagnostics tend
                // to be noisy false-positives in the editor.
                if settings.analysis.enable_permission_analysis
                    && !matches!(fact.action, QueryAction::Select | QueryAction::Relate)
                {
                    let permission = self.evaluate_permissions(fact, table_def, active_context);
                    match permission.result {
                        AccessResult::Denied
                            if !self.schemaless_hides(
                                table,
                                codes::PERMISSION_DENIED,
                                settings,
                            ) =>
                        {
                            diagnostics.push(Diagnostic {
                                range: table_range,
                                severity: Some(DiagnosticSeverity::ERROR),
                                code: codes::as_code(codes::PERMISSION_DENIED),
                                source: Some("surreal-language-server".to_string()),
                                message: permission.message,
                                ..Diagnostic::default()
                            })
                        }
                        AccessResult::Unknown
                            if !self.schemaless_hides(
                                table,
                                codes::PERMISSION_UNKNOWN,
                                settings,
                            ) =>
                        {
                            diagnostics.push(Diagnostic {
                                range: table_range,
                                severity: Some(DiagnosticSeverity::WARNING),
                                code: codes::as_code(codes::PERMISSION_UNKNOWN),
                                source: Some("surreal-language-server".to_string()),
                                message: permission.message,
                                ..Diagnostic::default()
                            })
                        }
                        _ => {}
                    }
                }

                // Unknown-field only applies where the schema is
                // closed: on a SCHEMALESS (or unspecified) table any
                // ad-hoc field is legal and the warning would be a
                // false positive. RELATE is exempt as well — its
                // target list mixes the subject tables with the edge
                // table, so SET fields (which belong to the edge)
                // would be checked against the wrong schemas.
                //
                // `analysis.schemalessDiagnostics: "strict"` opts a declared
                // SCHEMALESS table into the same check. That is off by default
                // precisely because an ad-hoc field there is legal SurrealQL —
                // it exists for authors who treat their SCHEMALESS tables as
                // closed by convention.
                let closed_schema = is_schemafull(table_def)
                    || (is_schemaless(table_def)
                        && codes::reports_on_schemaless(
                            codes::UNKNOWN_FIELD,
                            &settings.analysis.schemaless_diagnostics,
                        ));
                if !(table_def.explicit && closed_schema) || fact.action == QueryAction::Relate {
                    continue;
                }
                for field in &fact.touched_fields {
                    // Builtin fields exist on every record without a
                    // DEFINE FIELD (`in`/`out` are the relation
                    // endpoints).
                    if matches!(field.as_str(), "id" | "in" | "out") {
                        continue;
                    }
                    // Same masking hazard as tables: the statement
                    // under scrutiny *infers* a field def for every
                    // name it assigns, so only an explicit definition
                    // counts as "known" on a closed schema.
                    let explicitly_defined = self
                        .fields
                        .get(table)
                        .and_then(|by_name| by_name.get(field.as_str()))
                        .is_some_and(|field_def| field_def.explicit);
                    if !explicitly_defined {
                        let range = range_for_name(&fact.field_refs, field, fact.location.range);
                        diagnostics.push(self.unknown_field_diagnostic(table, field, range));
                    }
                }
            }
        }

        diagnostics
    }

    fn unknown_table_diagnostic(
        &self,
        table: &str,
        range: Range,
        suggestion: Option<&TableDef>,
    ) -> Diagnostic {
        let message = match suggestion {
            Some(candidate) => format!(
                "Unknown table `{table}`. Did you mean `{}`?",
                candidate.name
            ),
            None => format!("Unknown table `{table}`."),
        };
        let data = match suggestion {
            Some(candidate) => {
                serde_json::json!({ "table": table, "suggestion": candidate.name })
            }
            None => serde_json::json!({ "table": table }),
        };
        Diagnostic {
            range,
            severity: Some(DiagnosticSeverity::WARNING),
            code: codes::as_code(codes::UNKNOWN_TABLE),
            source: Some("surreal-language-server".to_string()),
            message,
            data: Some(data),
            related_information: suggestion.map(|candidate| {
                vec![DiagnosticRelatedInformation {
                    location: candidate.location.clone(),
                    message: format!("`{}` is defined here.", candidate.name),
                }]
            }),
            ..Diagnostic::default()
        }
    }

    fn unknown_field_diagnostic(&self, table: &str, field: &str, range: Range) -> Diagnostic {
        let suggestion = self.find_nearest_explicit_field(table, field);
        let message = match suggestion {
            Some(candidate) => format!(
                "Unknown field `{table}.{field}`. Did you mean `{}`?",
                candidate.name
            ),
            None => format!("Unknown field `{table}.{field}`."),
        };
        let data = match suggestion {
            Some(candidate) => serde_json::json!({
                "table": table,
                "field": field,
                "suggestion": candidate.name,
            }),
            None => serde_json::json!({ "table": table, "field": field }),
        };
        Diagnostic {
            range,
            severity: Some(DiagnosticSeverity::WARNING),
            code: codes::as_code(codes::UNKNOWN_FIELD),
            source: Some("surreal-language-server".to_string()),
            message,
            data: Some(data),
            related_information: suggestion.map(|candidate| {
                vec![DiagnosticRelatedInformation {
                    location: candidate.location.clone(),
                    message: format!("`{}` is defined here.", candidate.name),
                }]
            }),
            ..Diagnostic::default()
        }
    }

    pub fn code_actions(
        &self,
        uri: &Uri,
        analysis: &DocumentAnalysis,
        diagnostics: &[Diagnostic],
    ) -> Vec<CodeActionOrCommand> {
        let mut actions = Vec::new();

        for diagnostic in diagnostics {
            if let Some((table, suggestion)) = unknown_table_payload(diagnostic) {
                let replacement =
                    suggestion.or_else(|| self.find_nearest_table(&table).map(|t| t.name.clone()));
                if let Some(replacement) = replacement {
                    actions.push(CodeActionOrCommand::CodeAction(CodeAction {
                        title: format!("Replace `{table}` with `{replacement}`"),
                        kind: Some(CodeActionKind::QUICKFIX),
                        diagnostics: Some(vec![diagnostic.clone()]),
                        edit: Some(WorkspaceEdit {
                            document_changes: Some(DocumentChanges::Operations(vec![
                                ls_types::DocumentChangeOperation::Edit(TextDocumentEdit {
                                    text_document: OptionalVersionedTextDocumentIdentifier {
                                        uri: uri.clone(),
                                        version: None,
                                    },
                                    edits: vec![OneOf::Left(TextEdit {
                                        range: diagnostic.range,
                                        new_text: replacement.clone(),
                                    })],
                                }),
                            ])),
                            ..WorkspaceEdit::default()
                        }),
                        ..CodeAction::default()
                    }));
                }
            }

            // A renamed builtin. The old name sits in the diagnostic's own
            // range, and the engine records the replacement, so the fix needs no
            // payload beyond the text already there.
            if codes::has_code(diagnostic, codes::RENAMED_FUNCTION)
                && let Some(old) =
                    text_in_range(&analysis.text, &analysis.line_index, diagnostic.range)
                && let Some(current) = crate::grammar::renamed_builtin(old.trim())
            {
                actions.push(CodeActionOrCommand::CodeAction(CodeAction {
                    title: format!("Rename `{}` to `{current}`", old.trim()),
                    kind: Some(CodeActionKind::QUICKFIX),
                    diagnostics: Some(vec![diagnostic.clone()]),
                    is_preferred: Some(true),
                    edit: Some(WorkspaceEdit {
                        document_changes: Some(DocumentChanges::Operations(vec![
                            ls_types::DocumentChangeOperation::Edit(TextDocumentEdit {
                                text_document: OptionalVersionedTextDocumentIdentifier {
                                    uri: uri.clone(),
                                    version: None,
                                },
                                edits: vec![OneOf::Left(TextEdit {
                                    range: diagnostic.range,
                                    new_text: current.to_string(),
                                })],
                            }),
                        ])),
                        ..WorkspaceEdit::default()
                    }),
                    ..CodeAction::default()
                }));
            }

            // A type SurrealQL does not have. `type_name::nearest` is a pure
            // function of the name, so the suggestion can be re-derived when a
            // client strips the `data` payload *and* the message carries none.
            if let Some((name, suggestion)) = unknown_type_payload(diagnostic)
                && let Some(replacement) =
                    suggestion.or_else(|| type_name::nearest(&name).map(str::to_string))
            {
                actions.push(CodeActionOrCommand::CodeAction(CodeAction {
                    title: format!("Replace `{name}` with `{replacement}`"),
                    kind: Some(CodeActionKind::QUICKFIX),
                    diagnostics: Some(vec![diagnostic.clone()]),
                    is_preferred: Some(true),
                    edit: Some(WorkspaceEdit {
                        document_changes: Some(DocumentChanges::Operations(vec![
                            ls_types::DocumentChangeOperation::Edit(TextDocumentEdit {
                                text_document: OptionalVersionedTextDocumentIdentifier {
                                    uri: uri.clone(),
                                    version: None,
                                },
                                edits: vec![OneOf::Left(TextEdit {
                                    range: diagnostic.range,
                                    new_text: replacement.clone(),
                                })],
                            }),
                        ])),
                        ..WorkspaceEdit::default()
                    }),
                    ..CodeAction::default()
                }));
            }
        }

        for table in analysis
            .tables
            .iter()
            .filter(|table| table.permissions.is_empty() && table.explicit)
        {
            actions.push(CodeActionOrCommand::CodeAction(CodeAction {
                title: format!("Add PERMISSIONS clause to table `{}`", table.name),
                kind: Some(CodeActionKind::REFACTOR_REWRITE),
                edit: Some(WorkspaceEdit {
                    document_changes: Some(DocumentChanges::Operations(vec![ls_types::DocumentChangeOperation::Edit(
                        TextDocumentEdit {
                            text_document: OptionalVersionedTextDocumentIdentifier {
                                uri: uri.clone(),
                                version: None,
                            },
                            edits: vec![OneOf::Left(TextEdit {
                                range: Range {
                                    start: table.location.range.end,
                                    end: table.location.range.end,
                                },
                                new_text: " PERMISSIONS FOR select FULL, create NONE, update NONE, delete NONE".to_string(),
                            })],
                        },
                    )])),
                    ..WorkspaceEdit::default()
                }),
                ..CodeAction::default()
            }));
        }

        actions
    }

    pub fn definition_for_function(&self, name: &str) -> Option<Location> {
        self.functions
            .get(name)
            .filter(|function| function.origin == SymbolOrigin::Local)
            .map(|function| Location::new(function.location.uri.clone(), function.selection_range))
    }

    pub fn definition_for_token(&self, token: &str) -> Option<Location> {
        let trimmed = token.trim();
        if trimmed.is_empty() {
            return None;
        }

        self.definition_for_function(trimmed)
            .or_else(|| {
                self.tables
                    .get(trimmed)
                    .filter(|table| table.origin == SymbolOrigin::Local)
                    .map(|table| table.location.clone())
            })
            .or_else(|| {
                self.params
                    .get(trimmed)
                    .filter(|param| param.origin == SymbolOrigin::Local)
                    .map(|param| param.location.clone())
            })
            .or_else(|| {
                let parsed_type = TypeExpr::parse(trimmed);
                let record_tables = parsed_type.record_tables();
                (record_tables.len() == 1)
                    .then(|| record_tables.into_iter().next())
                    .flatten()
                    .and_then(|table_name| {
                        self.tables
                            .get(&table_name)
                            .filter(|table| table.origin == SymbolOrigin::Local)
                            .map(|table| table.location.clone())
                    })
            })
    }

    pub fn references_for_function(&self, name: &str) -> Vec<Location> {
        self.function_references
            .get(name)
            .cloned()
            .unwrap_or_default()
    }

    pub fn rename_edits(&self, name: &str, new_name: &str) -> Option<HashMap<Uri, Vec<TextEdit>>> {
        let function = self.functions.get(name)?;
        if function.origin != SymbolOrigin::Local {
            return None;
        }

        let mut changes: HashMap<Uri, Vec<TextEdit>> = HashMap::new();
        changes
            .entry(function.location.uri.clone())
            .or_default()
            .push(TextEdit {
                range: function.selection_range,
                new_text: new_name.to_string(),
            });

        for location in self.references_for_function(name) {
            changes
                .entry(location.uri.clone())
                .or_default()
                .push(TextEdit {
                    range: location.range,
                    new_text: new_name.to_string(),
                });
        }

        Some(changes)
    }

    pub fn workspace_symbol_items(&self, query: &str) -> Vec<ls_types::SymbolInformation> {
        let needle = query.to_ascii_lowercase();
        let mut items = Vec::new();
        for table in self.tables.values() {
            if needle.is_empty() || table.name.to_ascii_lowercase().contains(&needle) {
                items.push(symbol_information(
                    &table.name,
                    ls_types::SymbolKind::STRUCT,
                    &table.location,
                ));
            }
        }
        for field in self.fields.values().flat_map(HashMap::values) {
            let label = format!("{}.{}", field.table, field.name);
            if needle.is_empty() || label.to_ascii_lowercase().contains(&needle) {
                items.push(symbol_information(
                    &label,
                    ls_types::SymbolKind::FIELD,
                    &field.location,
                ));
            }
        }
        for event in self.events.values() {
            let label = format!("{}.{}", event.table, event.name);
            if needle.is_empty() || label.to_ascii_lowercase().contains(&needle) {
                items.push(symbol_information(
                    &label,
                    ls_types::SymbolKind::EVENT,
                    &event.location,
                ));
            }
        }
        for index in self.indexes.values() {
            let label = format!("{}.{}", index.table, index.name);
            if needle.is_empty() || label.to_ascii_lowercase().contains(&needle) {
                items.push(symbol_information(
                    &label,
                    ls_types::SymbolKind::KEY,
                    &index.location,
                ));
            }
        }
        for function in self.functions.values() {
            if needle.is_empty() || function.name.to_ascii_lowercase().contains(&needle) {
                items.push(symbol_information(
                    &function.name,
                    ls_types::SymbolKind::FUNCTION,
                    &function.location,
                ));
            }
        }
        items
    }

    fn absorb_analysis(&mut self, analysis: &DocumentAnalysis) {
        self.query_facts
            .entry(analysis.uri.clone())
            .or_default()
            .extend(analysis.query_facts.iter().cloned());
        self.workspace_symbols
            .extend(analysis.document_symbols.iter().cloned());

        // Every merge below takes the candidate by reference and clones it
        // only when it actually wins over the current entry. For workspaces
        // with many overlapping definitions (saved + open + remote merged
        // together) this skips a lot of throwaway allocations.
        for table in &analysis.tables {
            self.insert_table_ref(table);
        }
        for event in &analysis.events {
            merge_event(&mut self.events, event);
        }
        for index in &analysis.indexes {
            merge_index(&mut self.indexes, index);
        }
        for field in &analysis.fields {
            self.insert_field_ref(field);
        }
        for function in &analysis.functions {
            merge_function(&mut self.functions, function);
        }
        for param in &analysis.params {
            merge_param(&mut self.params, param);
        }
        for access in &analysis.accesses {
            merge_access(&mut self.accesses, access);
        }
        for analyzer in &analysis.analyzers {
            merge_analyzer(&mut self.analyzers, analyzer);
        }
    }

    fn evaluate_permissions(
        &self,
        fact: &QueryFact,
        table: &TableDef,
        active_context: Option<&AuthContext>,
    ) -> PermissionOutcome {
        let table_rule = table
            .permissions
            .iter()
            .find(|rule| rule.actions.contains(&fact.action))
            .cloned();

        let mut field_rule = None;
        for field in &fact.touched_fields {
            if let Some(rule) = self
                .fields
                .get(table.name.as_str())
                .and_then(|by_name| by_name.get(field.as_str()))
                .and_then(|field| {
                    field
                        .permissions
                        .iter()
                        .find(|rule| rule.actions.contains(&fact.action))
                })
                .cloned()
            {
                field_rule = Some(rule);
                break;
            }
        }

        let rule = field_rule.or(table_rule);
        let Some(rule) = rule else {
            return PermissionOutcome {
                result: AccessResult::Unknown,
                message: format!(
                    "No explicit permission rule found for {} on `{}`.",
                    action_label(fact.action),
                    table.name
                ),
            };
        };

        let result = evaluate_permission_rule(&rule, active_context);
        let message = match result {
            AccessResult::Allowed => format!(
                "{} is allowed on `{}` for `{}`.",
                action_label(fact.action),
                table.name,
                active_context
                    .map(|context| context.name.as_str())
                    .unwrap_or("default")
            ),
            AccessResult::Denied => format!(
                "{} is denied on `{}` by `{}`.",
                action_label(fact.action),
                table.name,
                compact_preview(&rule.raw)
            ),
            AccessResult::Unknown => format!(
                "{} on `{}` depends on unresolved permission expression `{}`.",
                action_label(fact.action),
                table.name,
                compact_preview(&rule.raw)
            ),
        };

        PermissionOutcome { result, message }
    }
}

struct PermissionOutcome {
    result: AccessResult,
    message: String,
}

/// True when the two names are bare singular/plural forms of each
/// other (`order`/`orders`, `box`/`boxes`, `category`/`categories`),
/// in either direction and case-insensitively.
fn is_plural_variant(left: &str, right: &str) -> bool {
    fn is_plural_of(plural: &str, singular: &str) -> bool {
        if let Some(stem) = plural.strip_suffix("ies") {
            if format!("{stem}y") == singular {
                return true;
            }
        }
        if let Some(stem) = plural.strip_suffix("es")
            && stem == singular
        {
            return true;
        }
        // Bare-`s` plurals only apply when the stem doesn't itself
        // end in `s`: s-ending nouns pluralise with `es`, so
        // `address`/`addres` is a real typo, not a plural pair.
        plural
            .strip_suffix('s')
            .is_some_and(|stem| stem == singular && !stem.ends_with('s'))
    }

    let left = left.to_ascii_lowercase();
    let right = right.to_ascii_lowercase();
    is_plural_of(&left, &right) || is_plural_of(&right, &left)
}

/// Tight token range for `name`, falling back to the statement range
/// for facts recorded before ranges were tracked.
fn range_for_name(refs: &[NamedRange], name: &str, fallback: Range) -> Range {
    refs.iter()
        .find(|entry| entry.name == name)
        .map(|entry| entry.range)
        .unwrap_or(fallback)
}

/// Extract the `(table, suggested_replacement)` payload from an
/// unknown-table diagnostic. Matches on the stable `unknown-table`
/// code + `data` first; falls back to parsing the legacy message text
/// so quick fixes keep working for diagnostics cached by pre-0.3
/// clients. Remove the string fallback in 0.4.
fn unknown_table_payload(diagnostic: &Diagnostic) -> Option<(String, Option<String>)> {
    // Primary path: stable code + structured data.
    if codes::has_code(diagnostic, codes::UNKNOWN_TABLE)
        && let Some(data) = diagnostic.data.as_ref()
        && let Some(table) = data.get("table").and_then(|value| value.as_str())
    {
        let suggestion = data
            .get("suggestion")
            .and_then(|value| value.as_str())
            .map(str::to_string);
        return Some((table.to_string(), suggestion));
    }

    // Fallback: parse the message text. This keeps quick fixes alive
    // for clients that strip the non-standard `data` field (or, pre-
    // 0.3, the code too). Takes the table up to the closing backtick
    // so both "Unknown table `x`." and
    // "Unknown table `x`. Did you mean `y`?" parse.
    let rest = diagnostic.message.strip_prefix("Unknown table `")?;
    let (table, tail) = rest.split_once('`')?;
    let suggestion = tail
        .strip_prefix(". Did you mean `")
        .and_then(|tail| tail.split_once('`'))
        .map(|(suggestion, _)| suggestion.to_string());
    Some((table.to_string(), suggestion))
}

/// Extract the `(type_name, suggested_replacement)` payload from an
/// `unknown-type` diagnostic.
///
/// Same two paths as [`unknown_table_payload`]: the stable code plus structured
/// `data` first, then the message text, so the quick fix survives a client that
/// strips the non-standard `data` field.
fn unknown_type_payload(diagnostic: &Diagnostic) -> Option<(String, Option<String>)> {
    // Primary path: stable code + structured data.
    if codes::has_code(diagnostic, codes::UNKNOWN_TYPE)
        && let Some(data) = diagnostic.data.as_ref()
        && let Some(name) = data.get("type").and_then(|value| value.as_str())
    {
        let suggestion = data
            .get("suggestion")
            .and_then(|value| value.as_str())
            .map(str::to_string);
        return Some((name.to_string(), suggestion));
    }

    // Fallback: parse the message text. Takes the name up to the closing
    // backtick so both "Unknown type `x`." and
    // "Unknown type `x`. Did you mean `y`?" parse.
    let rest = diagnostic.message.strip_prefix("Unknown type `")?;
    let (name, tail) = rest.split_once('`')?;
    let suggestion = tail
        .strip_prefix(". Did you mean `")
        .and_then(|tail| tail.split_once('`'))
        .map(|(suggestion, _)| suggestion.to_string());
    Some((name.to_string(), suggestion))
}

// These two keep the `(table, name)` tuple key rather than nesting like
// `fields`: a workspace holds orders of magnitude fewer events and indexes
// than fields, so the tuple is not on a hot path. Building the key once
// instead of twice is the whole of the saving here.
fn merge_event(target: &mut HashMap<(String, String), EventDef>, candidate: &EventDef) {
    let key = (candidate.table.clone(), candidate.name.clone());
    if let Some(current) = target.get(&key) {
        if symbol_priority(candidate.origin) < symbol_priority(current.origin) {
            return;
        }
    }
    target.insert(key, candidate.clone());
}

fn merge_index(target: &mut HashMap<(String, String), IndexDef>, candidate: &IndexDef) {
    let key = (candidate.table.clone(), candidate.name.clone());
    if let Some(current) = target.get(&key) {
        if symbol_priority(candidate.origin) < symbol_priority(current.origin) {
            return;
        }
    }
    target.insert(key, candidate.clone());
}

fn merge_function(target: &mut HashMap<String, FunctionDef>, candidate: &FunctionDef) {
    let replace = target
        .get(&candidate.name)
        .map(|current| should_replace_function(current, candidate))
        .unwrap_or(true);
    if replace {
        target.insert(candidate.name.clone(), candidate.clone());
    }
}

fn merge_param(target: &mut HashMap<String, ParamDef>, candidate: &ParamDef) {
    if let Some(current) = target.get(&candidate.name) {
        if symbol_priority(candidate.origin) < symbol_priority(current.origin) {
            return;
        }
    }
    target.insert(candidate.name.clone(), candidate.clone());
}

fn merge_analyzer(target: &mut HashMap<String, AnalyzerDef>, candidate: &AnalyzerDef) {
    if let Some(current) = target.get(&candidate.name)
        && symbol_priority(candidate.origin) < symbol_priority(current.origin)
    {
        return;
    }
    target.insert(candidate.name.clone(), candidate.clone());
}

fn merge_access(target: &mut HashMap<String, AccessDef>, candidate: &AccessDef) {
    if let Some(current) = target.get(&candidate.name) {
        if symbol_priority(candidate.origin) < symbol_priority(current.origin) {
            return;
        }
    }
    target.insert(candidate.name.clone(), candidate.clone());
}

fn should_replace_table(current: &TableDef, candidate: &TableDef) -> bool {
    replacement_score(
        candidate.explicit,
        candidate.origin,
        candidate
            .inference
            .as_ref()
            .map(|fact| fact.confidence)
            .unwrap_or(1.0),
    ) >= replacement_score(
        current.explicit,
        current.origin,
        current
            .inference
            .as_ref()
            .map(|fact| fact.confidence)
            .unwrap_or(1.0),
    )
}

/// `(numerator, denominator)` of `3 * T(p) - 1`, indexed by the common-prefix
/// length `p`, as exact rationals so the prefilter needs no floating point.
///
/// `T(p)` is the Jaro score a pair must exceed for jaro-winkler to clear
/// [`NEAR_MISS_THRESHOLD`] given a prefix of `p`. See
/// [`can_reach_near_miss_threshold`] for the derivation. `p` is capped at 4
/// because that is the longest prefix Winkler rewards.
/// The jaro-winkler score a name must exceed to be offered as a "did you mean"
/// near-miss.
///
/// One constant rather than a literal per sweep: [`can_reach_near_miss_threshold`]
/// derives its pruning bound from this number, so a sweep using a different gate
/// would silently lose suggestions the prefilter had already discarded.
pub const NEAR_MISS_THRESHOLD: f64 = 0.86;

const JARO_REQUIREMENT: [(u64, u64); 5] = [
    (79, 50), // p = 0 -> T = 43/50,  3T-1 = 79/50 = 1.58
    (23, 15), // p = 1 -> T = 38/45,  3T-1 = 23/15 = 1.533
    (59, 40), // p = 2 -> T = 33/40,  3T-1 = 59/40 = 1.475
    (7, 5),   // p = 3 -> T =   4/5,  3T-1 =   7/5 = 1.4
    (13, 10), // p = 4 -> T = 23/30,  3T-1 = 13/10 = 1.3
];

/// Whether jaro-winkler *could* score two names above [`NEAR_MISS_THRESHOLD`].
///
/// Cheap, and sound: it never rejects a pair the full comparison would have
/// accepted, so it changes which suggestions are *found* not at all — only how
/// long it takes to not find them. `can_reach_near_miss_threshold_is_sound`
/// checks that against `strsim` itself over a generated corpus.
///
/// # Derivation
///
/// Winkler is `JW = J + 0.1 * p * (1 - J)` where `p = min(4, common prefix)`.
/// For a fixed `p` that is strictly increasing in `J` (the slope is
/// `1 - 0.1p >= 0.6`), so
///
/// ```text
/// JW > 0.86  <=>  J > T(p) = (0.86 - 0.1p) / (1 - 0.1p)
/// ```
///
/// Jaro is `(m/a + m/b + (m-t)/m) / 3` for `m` matches and `t` transpositions.
/// Since `t >= 0` the third term is at most 1, so a pair can only pass if
///
/// ```text
/// m * (a + b) > (3 * T(p) - 1) * a * b
/// ```
///
/// Two upper bounds on `m` make that testable without running Jaro. Both bound
/// the *maximum* matching, and `strsim`'s greedy first-match rule finds no more
/// than the maximum, so both are safe:
///
/// * `m <= min(a, b)` — the length-ratio stage, which reduces to
///   `min / max > 3 * T(p) - 2`. Cheapest, and rejects the pathological
///   two-character-against-thirty case.
/// * `m <= sum over characters of min(count_a[c], count_b[c])` — the multiset
///   stage. A Jaro match pairs equal characters and uses each position once, so
///   per character class it cannot exceed the smaller count.
///
/// # Why the prefix has to be exact
///
/// Assuming the *worst-case* prefix (`p = 4`) collapses the requirement to the
/// weakest row and makes the filter useless: it keeps 100% of a real workload
/// where the exact-`p` version keeps 0.4%. Names that share no prefix face
/// `T(0) = 0.86` rather than `T(4) = 0.767`, which is what does the pruning.
///
/// Note that a bound on the *difference* of the lengths is **not** available at
/// any `p`: `person` and `personaddress` differ by 7 characters and still score
/// 0.892.
fn can_reach_near_miss_threshold(unknown: &str, candidate: &str) -> bool {
    let (a, b) = (unknown.len() as u64, candidate.len() as u64);
    if a == 0 || b == 0 {
        return false;
    }

    // Byte lengths, and byte-wise prefix, rather than characters. For non-ASCII
    // input the byte length is >= the character count and the byte prefix is
    // <= the character prefix, and both errors loosen the bound, so the filter
    // stays sound. Identifier names are ASCII in practice.
    let prefix = unknown
        .as_bytes()
        .iter()
        .zip(candidate.as_bytes())
        .take(4)
        .take_while(|(left, right)| left == right)
        .count();
    let (numerator, denominator) = JARO_REQUIREMENT[prefix];

    // Stage 1, `min / max > 3T(p) - 2`, i.e.
    // `min * denominator > (numerator - denominator) * max`.
    let (shorter, longer) = if a <= b { (a, b) } else { (b, a) };
    if shorter * denominator <= (numerator - denominator) * longer {
        return false;
    }

    // Stage 2, `m * (a + b) > (3T(p) - 1) * a * b` with `m` bounded by the
    // character-multiset intersection.
    let matchable = multiset_intersection(unknown, candidate);
    matchable * (a + b) * denominator > numerator * a * b
}

/// The size of the character-multiset intersection: an upper bound on how many
/// characters Jaro could possibly match.
///
/// Case-sensitive, because `jaro_winkler` is. Folding both sides would still be
/// sound (it can only raise the bound) but would prune less.
fn multiset_intersection(left: &str, right: &str) -> u64 {
    // ASCII identifiers are the overwhelming case, so count bytes into a fixed
    // table and avoid a map allocation. Anything non-ASCII lands in one shared
    // bucket, which over-counts and therefore only loosens the bound.
    let mut counts = [0i32; 129];
    const OTHER: usize = 128;
    for byte in left.bytes() {
        counts[if byte.is_ascii() {
            byte as usize
        } else {
            OTHER
        }] += 1;
    }
    let mut shared = 0u64;
    for byte in right.bytes() {
        let slot = if byte.is_ascii() {
            byte as usize
        } else {
            OTHER
        };
        if counts[slot] > 0 {
            counts[slot] -= 1;
            shared += 1;
        }
    }
    shared
}

fn should_replace_field(current: &FieldDef, candidate: &FieldDef) -> bool {
    replacement_score(
        candidate.explicit,
        candidate.origin,
        candidate
            .inference
            .as_ref()
            .map(|fact| fact.confidence)
            .unwrap_or(1.0),
    ) >= replacement_score(
        current.explicit,
        current.origin,
        current
            .inference
            .as_ref()
            .map(|fact| fact.confidence)
            .unwrap_or(1.0),
    )
}

fn should_replace_function(current: &FunctionDef, candidate: &FunctionDef) -> bool {
    replacement_score(
        candidate.explicit,
        candidate.origin,
        candidate
            .inference
            .as_ref()
            .map(|fact| fact.confidence)
            .unwrap_or(1.0),
    ) >= replacement_score(
        current.explicit,
        current.origin,
        current
            .inference
            .as_ref()
            .map(|fact| fact.confidence)
            .unwrap_or(1.0),
    )
}

fn replacement_score(explicit: bool, origin: SymbolOrigin, confidence: f32) -> i32 {
    let explicit_score = if explicit { 1000 } else { 0 };
    explicit_score + (symbol_priority(origin) as i32 * 100) + (confidence * 10.0) as i32
}

/// Append `value` under `key`, unless it is already there.
///
/// The graph index is read far more often than it is built, and a duplicate
/// would show twice in the completion list, so the linear scan is paid here.
/// Each list holds the edges of one table, so it stays short.
fn push_unique(map: &mut HashMap<String, Vec<String>>, key: &str, value: &str) {
    let entry = match map.get_mut(key) {
        Some(entry) => entry,
        // Only the first edge of a table pays for the key.
        None => map.entry(key.to_string()).or_default(),
    };
    if !entry.iter().any(|existing| existing == value) {
        entry.push(value.to_string());
    }
}

fn symbol_priority(origin: SymbolOrigin) -> usize {
    match origin {
        SymbolOrigin::Local => 4,
        SymbolOrigin::Remote => 3,
        SymbolOrigin::Inferred => 2,
        SymbolOrigin::Builtin => 1,
    }
}

/// True when the table declares `SCHEMAFULL`. The schema is closed, so a field
/// with no `DEFINE FIELD` is a fault.
fn is_schemafull(table: &TableDef) -> bool {
    table
        .schema_mode
        .as_deref()
        .is_some_and(|mode| mode.eq_ignore_ascii_case("schemafull"))
}

/// True when the table declares `SCHEMALESS`. An absent clause is *not*
/// schemaless here — see [`MergedSemanticModel::schemaless_hides`] for why the
/// keyword and the engine's effective mode are kept apart.
fn is_schemaless(table: &TableDef) -> bool {
    table
        .schema_mode
        .as_deref()
        .is_some_and(|mode| mode.eq_ignore_ascii_case("schemaless"))
}

fn format_table_hover(
    table: &TableDef,
    model: &MergedSemanticModel,
    active_context: Option<&AuthContext>,
) -> String {
    let mut metadata = vec![format!("Source: {}", origin_label(table.origin))];
    if let Some(mode) = &table.schema_mode {
        metadata.push(format!("Schema: `{mode}`"));
    }
    metadata.push(format!(
        "Permissions: {}",
        table_permission_posture(&table.permissions)
    ));
    let mut sections = Vec::new();
    let field_count = model.fields_for_table(&table.name).len();
    if field_count > 0 {
        sections.push(list_section("Known fields", vec![field_count.to_string()]));
    }
    let indexes = model.indexes_for_table(&table.name);
    if !indexes.is_empty() {
        sections.push(list_section(
            "Known indexes",
            indexes
                .iter()
                .map(|index| {
                    let mut details = Vec::new();
                    if !index.fields.is_empty() {
                        details.push(index.fields.join(", "));
                    }
                    if index.unique {
                        details.push("unique".to_string());
                    }
                    details.extend(index.options.iter().cloned());

                    if details.is_empty() {
                        index.name.clone()
                    } else {
                        format!("{} ({})", index.name, details.join(" | "))
                    }
                })
                .collect::<Vec<_>>(),
        ));
    }
    let events = model.events_for_table(&table.name);
    if !events.is_empty() {
        sections.push(list_section(
            "Known events",
            events
                .iter()
                .map(|event| event.name.clone())
                .collect::<Vec<_>>(),
        ));
    }
    if let Some(context) = active_context {
        let actions = table
            .permissions
            .iter()
            .map(|rule| {
                let action_list = rule
                    .actions
                    .iter()
                    .map(|action| action_label(*action))
                    .collect::<Vec<_>>()
                    .join(", ");
                format!("{action_list}: {}", permission_summary(rule, Some(context)))
            })
            .collect::<Vec<_>>();
        if !actions.is_empty() {
            sections.push(list_section(
                &format!("Permissions for `{}`", context.name),
                actions,
            ));
        }
    }
    if let Some(inference) = &table.inference {
        metadata.push(format!("Confidence: {:.2}", inference.confidence));
    }
    hover_block(
        format!("TABLE {}", table.name),
        table.comment.clone(),
        metadata,
        sections,
    )
}

fn format_function_hover(function: &FunctionDef, inferred_return: Option<&TypeExpr>) -> String {
    let mut metadata = vec![format!("Source: {}", origin_label(function.origin))];
    match function.language {
        FunctionLanguage::JavaScript => metadata.push("Language: JavaScript".to_string()),
        FunctionLanguage::SurrealQL => {}
    }
    // Say it plainly, so the `->` in the signature above cannot be read as an
    // annotation the author wrote. Same convention as `format_binding_hover`.
    if function.return_type.is_none() && inferred_return.is_some() {
        metadata.push("Return type inferred from the body.".to_string());
    }
    let mut sections = Vec::new();
    if !function.called_functions.is_empty() {
        sections.push(list_section("Calls", function.called_functions.clone()));
    }
    hover_block(
        function_signature_with_return(function, inferred_return),
        function.comment.clone(),
        metadata,
        sections,
    )
}

fn format_builtin_function_hover(function: &BuiltinFunction, token: &str) -> String {
    let mut metadata = vec!["Source: builtin".to_string()];
    if !token.eq_ignore_ascii_case(function.name) {
        metadata.push(format!("Canonical name: `{}`", function.name));
    }
    hover_block(
        function.signature.to_string(),
        Some(function.summary.to_string()),
        metadata,
        vec![list_section(
            "Docs",
            vec![format!(
                "[SurrealDB reference]({})",
                function.documentation_url
            )],
        )],
    )
}

/// Hover for a builtin the curated table has no prose for.
///
/// Everything shown is derived from the engine's own source, so there is no
/// summary to give — the signature and the namespace's documentation page are
/// what we honestly have. Better than the nothing this used to return for 18 of
/// the 20 advertised namespaces.
/// The source text an LSP range covers.
fn text_in_range<'a>(
    source: &'a str,
    lines: &LineIndex,
    range: ls_types::Range,
) -> Option<&'a str> {
    let start = lines.offset(source, range.start);
    let end = lines.offset(source, range.end);
    source.get(start..end)
}

fn format_generated_function_hover(
    signature: &crate::grammar::BuiltinSignature,
    token: &str,
) -> String {
    let name = signature.generated.name;
    let mut metadata = vec!["Source: builtin".to_string()];
    if !token.eq_ignore_ascii_case(name) {
        metadata.push(format!("Canonical name: `{name}`"));
    }
    if signature.generated.not_callable {
        metadata.push(
            "The parser accepts this name, but no implementation is reachable in call form."
                .to_string(),
        );
    }

    // `display_signature` carries the return type in its arrow, so this states
    // it only when there is no signature to carry it. `rand::int` is the case
    // that needs it: its arity cannot be read from the engine's argument
    // wrappers, but the registry still declares that it returns an `int`.
    let title = signature.display_signature();
    if title.is_none()
        && let Some(returns) = crate::grammar::builtin_return_type(name)
    {
        metadata.push(format!("Returns: `{returns}`"));
    }

    let mut sections = Vec::new();
    if let Some(namespace) = name.split_once("::").map(|(namespace, _)| namespace) {
        sections.push(list_section(
            "Docs",
            vec![format!(
                "[SurrealDB reference](https://surrealdb.com/docs/surrealql/functions/database/{namespace})"
            )],
        ));
    }

    hover_block(
        title.unwrap_or_else(|| format!("{name}(…)")),
        None,
        metadata,
        sections,
    )
}

fn format_binding_hover(binding: &crate::semantic::infer::Binding) -> String {
    let mut facts = vec![format!("Type: `{}`", binding.ty)];
    // Only worth saying when the author didn't write the type themselves.
    if binding.declared.is_none() && binding.ty != TypeExpr::Unknown {
        facts.push("Inferred from the assigned value.".to_string());
    }
    hover_block(
        format!("{} {}", binding.kind.label(), binding.name),
        None,
        facts,
        Vec::new(),
    )
}

fn format_param_hover(param: &ParamDef) -> String {
    let mut sections = Vec::new();
    if let Some(value_preview) = &param.value_preview {
        sections.push(list_section("Default", vec![format!("`{value_preview}`")]));
    }
    hover_block(
        format!("PARAM {}", param.name),
        param.comment.clone(),
        vec![format!("Source: {}", origin_label(param.origin))],
        sections,
    )
}

fn format_access_hover(access: &AccessDef) -> String {
    hover_block(
        format!("ACCESS {}", access.name),
        access.comment.clone(),
        vec![format!("Source: {}", origin_label(access.origin))],
        Vec::new(),
    )
}

/// The tables a value *points at*, when the value is itself a record.
///
/// Deliberately not [`TypeExpr::record_tables`], which reaches inside an object
/// and collects whatever its columns point at. That is the right answer for
/// "which tables does this type mention" and the wrong one for "which table are
/// this value's columns declared on".
fn record_target_tables(ty: &TypeExpr) -> Option<&[String]> {
    match ty {
        TypeExpr::Record(tables) if !tables.is_empty() => Some(tables),
        TypeExpr::Array(inner) | TypeExpr::Set(inner) | TypeExpr::Option(inner) => {
            record_target_tables(inner)
        }
        _ => None,
    }
}

/// Hover text for a column that exists without a `DEFINE FIELD`.
fn implicit_field_hover(name: &str, table: &str) -> String {
    let description = match name {
        "id" => "The record's own identifier. Present on every record.",
        "in" => "The record this edge points *from*. Written by `RELATE`.",
        "out" => "The record this edge points *to*. Written by `RELATE`.",
        // Unreachable: `implicit_fields` yields only the three above.
        _ => "A built-in column.",
    };
    hover_block(
        format!("FIELD {table}.{name}"),
        Some(description.to_string()),
        vec!["Source: built-in".to_string()],
        Vec::new(),
    )
}

fn format_field_hover(field: &FieldDef, model: &MergedSemanticModel) -> String {
    let mut metadata = vec![
        format!("Source: {}", origin_label(field.origin)),
        format!(
            "Permissions: {}",
            table_permission_posture(&field.permissions)
        ),
    ];
    if let Some(type_expr) = &field.type_expr {
        metadata.push(format!("Type: `{type_expr}`"));
    }
    if let Some(inference) = &field.inference {
        metadata.push(format!("Confidence: {:.2}", inference.confidence));
    }

    // The column-level counterpart of the table hover's index section: whether
    // this column is indexed is the thing most worth knowing about it that the
    // `DEFINE FIELD` itself does not say.
    let covering: Vec<String> = model
        .indexes_for_table(&field.table)
        .iter()
        .filter(|index| index.fields.iter().any(|name| *name == field.name))
        .map(|index| {
            let mut details = Vec::new();
            if index.fields.len() > 1 {
                details.push(format!("over {}", index.fields.join(", ")));
            }
            if index.unique {
                details.push("unique".to_string());
            }
            details.extend(index.options.iter().cloned());
            if details.is_empty() {
                index.name.clone()
            } else {
                format!("{} ({})", index.name, details.join(" | "))
            }
        })
        .collect();
    let sections = if covering.is_empty() {
        Vec::new()
    } else {
        vec![list_section("Indexed by", covering)]
    };

    hover_block(
        format!("FIELD {}.{}", field.table, field.name),
        field.comment.clone(),
        metadata,
        sections,
    )
}

/// How one parameter is spelled wherever a signature is shown to the user.
///
/// Shared by function hover and by signature help
/// ([`crate::core::LanguageServerCore::signature_help`]) so the two cannot
/// drift — they previously formatted this identically but separately.
pub fn param_label(param: &FunctionParam) -> String {
    match &param.type_expr {
        Some(type_expr) => format!("{}: {}", param.name, type_expr),
        None => param.name.clone(),
    }
}

/// `fn::name($a: type, …) -> type`, as rendered in hover and signature help.
///
/// Renders only what the source declares. Use
/// [`function_signature_with_return`] where a body-inferred return type should
/// show too.
pub fn function_signature(function: &FunctionDef) -> String {
    function_signature_with_return(function, None)
}

/// [`function_signature`], but falling back to a body-inferred return type.
///
/// `inferred` comes from [`MergedSemanticModel::inferred_function_returns`], so
/// only a caller holding the model can supply it. A declared type always wins.
///
/// The arrow alone cannot distinguish the two, so every caller that passes
/// `Some` is responsible for saying so nearby — [`format_function_hover`] adds a
/// line for exactly that reason.
pub fn function_signature_with_return(
    function: &FunctionDef,
    inferred: Option<&TypeExpr>,
) -> String {
    let params = function
        .params
        .iter()
        .map(param_label)
        .collect::<Vec<_>>()
        .join(", ");
    let base = format!("{}({params})", function.name);
    match function.return_type.as_ref().or(inferred) {
        Some(ret) => format!("{base} -> {ret}"),
        None => base,
    }
}

fn table_permission_posture(permissions: &[PermissionRule]) -> &'static str {
    if permissions.is_empty() {
        "no explicit rules"
    } else if permissions
        .iter()
        .all(|rule| matches!(rule.mode, PermissionMode::Full))
    {
        "public"
    } else {
        "gated"
    }
}

fn hover_block(
    title: String,
    summary: Option<String>,
    metadata: Vec<String>,
    sections: Vec<String>,
) -> String {
    let mut blocks = vec![format!("### {title}")];
    if let Some(summary) = summary.filter(|value| !value.trim().is_empty()) {
        blocks.push(summary);
    }
    if !metadata.is_empty() {
        blocks.push(list_section("Details", metadata));
    }
    blocks.extend(
        sections
            .into_iter()
            .filter(|value| !value.trim().is_empty()),
    );
    join_hover_blocks(blocks)
}

fn join_hover_blocks<I>(blocks: I) -> String
where
    I: IntoIterator<Item = String>,
{
    blocks
        .into_iter()
        .filter(|block| !block.trim().is_empty())
        .collect::<Vec<_>>()
        .join("\n\n")
}

fn list_section(title: &str, items: Vec<String>) -> String {
    let mut lines = vec![format!("**{title}**")];
    lines.extend(
        items
            .into_iter()
            .filter(|item| !item.trim().is_empty())
            .map(|item| format!("- {item}")),
    );
    lines.join("\n")
}

fn permission_summary(rule: &PermissionRule, active_context: Option<&AuthContext>) -> String {
    match evaluate_permission_rule(rule, active_context) {
        AccessResult::Allowed => "allowed".to_string(),
        AccessResult::Denied => "denied".to_string(),
        AccessResult::Unknown => compact_preview(&rule.raw),
    }
}

fn evaluate_permission_rule(
    rule: &PermissionRule,
    active_context: Option<&AuthContext>,
) -> AccessResult {
    match &rule.mode {
        PermissionMode::Full => AccessResult::Allowed,
        PermissionMode::None => AccessResult::Denied,
        PermissionMode::Expression(expression) => {
            evaluate_permission_expression(expression, active_context)
        }
    }
}

fn evaluate_permission_expression(
    expression: &str,
    active_context: Option<&AuthContext>,
) -> AccessResult {
    let Some(context) = active_context else {
        return AccessResult::Unknown;
    };
    let lower = expression.to_ascii_lowercase();

    if lower.contains("$auth.roles") {
        let candidates = quoted_literals(expression);
        if candidates.is_empty() {
            return AccessResult::Unknown;
        }
        if candidates
            .iter()
            .any(|role| context.roles.iter().any(|owned| owned == role))
        {
            return AccessResult::Allowed;
        }
        return AccessResult::Denied;
    }

    if lower.contains("$auth.id") || lower.contains("$session") || lower.contains("$auth") {
        return AccessResult::Unknown;
    }

    AccessResult::Unknown
}

fn quoted_literals(input: &str) -> Vec<String> {
    let mut values = Vec::new();
    let mut current = String::new();
    let mut in_quote = false;

    for ch in input.chars() {
        match ch {
            '\'' if in_quote => {
                values.push(current.clone());
                current.clear();
                in_quote = false;
            }
            '\'' => in_quote = true,
            _ if in_quote => current.push(ch),
            _ => {}
        }
    }

    values
}

fn symbol_information(
    name: &str,
    kind: ls_types::SymbolKind,
    location: &Location,
) -> ls_types::SymbolInformation {
    #[allow(deprecated)]
    ls_types::SymbolInformation {
        name: name.to_string(),
        kind,
        tags: None,
        deprecated: None,
        location: location.clone(),
        container_name: None,
    }
}

fn origin_label(origin: SymbolOrigin) -> &'static str {
    match origin {
        SymbolOrigin::Builtin => "builtin",
        SymbolOrigin::Inferred => "inferred",
        SymbolOrigin::Remote => "remote",
        SymbolOrigin::Local => "local",
    }
}

fn action_label(action: QueryAction) -> &'static str {
    match action {
        QueryAction::Select => "SELECT",
        QueryAction::Create => "CREATE",
        QueryAction::Update => "UPDATE",
        QueryAction::Delete => "DELETE",
        QueryAction::Relate => "RELATE",
        QueryAction::Execute => "EXECUTE",
    }
}

pub(crate) fn field_completion_tables(
    statement_fact: Option<&QueryFact>,
    qualifier: Option<&str>,
) -> Vec<String> {
    if let Some(qualified) = qualifier.and_then(normalize_completion_table_name) {
        return vec![qualified];
    }

    let Some(statement_fact) = statement_fact else {
        return Vec::new();
    };
    if !matches!(
        statement_fact.action,
        QueryAction::Select | QueryAction::Create | QueryAction::Update
    ) {
        return Vec::new();
    }

    let mut tables = Vec::new();
    for table in &statement_fact.target_tables {
        if let Some(normalized) = normalize_completion_table_name(table) {
            if !tables.contains(&normalized) {
                tables.push(normalized);
            }
        }
    }
    tables
}

fn normalize_completion_table_name(value: &str) -> Option<String> {
    let trimmed = value.trim().trim_matches('`');
    if trimmed.is_empty() {
        return None;
    }
    let candidate = trimmed
        .split(':')
        .next()
        .unwrap_or(trimmed)
        .trim_matches(|ch| matches!(ch, '<' | '>' | '(' | ')' | '[' | ']'))
        .to_string();
    if candidate.is_empty() {
        None
    } else {
        Some(candidate)
    }
}

pub fn is_record_type_context(source: &str, lines: &LineIndex, position: Position) -> bool {
    let prefix = &source[..lines.offset(source, position)];
    prefix
        .rsplit_once("record<")
        .map(|(_, suffix)| !suffix.contains('>'))
        .unwrap_or(false)
}

/// The byte offset of the `.` that opens the method position at `offset`, if
/// there is one.
///
/// Accepts a partially typed name after the dot (`"abc".sl|`), because `.` is not
/// a token character and the completion prefix therefore arrives empty.
fn method_dot_offset(source: &str, offset: usize) -> Option<usize> {
    let before = source.get(..offset)?;
    let trailing = before
        .chars()
        .rev()
        .take_while(|ch| ch.is_alphanumeric() || *ch == '_')
        .count();
    let (at, ch) = before.char_indices().rev().nth(trailing)?;
    if ch == '.' { Some(at) } else { None }
}

/// The method a cursor sits on: the `IdiomFunction` node and the method name.
///
/// `token_at` treats `.` as a boundary, so hover on `'abc'.len()` only ever sees
/// the bare word `len`. That is why this works from the tree instead: the bare
/// word route answers with the SurrealQL *keyword* `AT` for `.at(0)` and `SPLIT`
/// for `.split(',')` — a wrong answer rather than a missing one.
pub(crate) fn method_at<'tree>(
    analysis: &'tree DocumentAnalysis,
    offset: usize,
) -> Option<(tree_sitter::Node<'tree>, String)> {
    let node = analysis
        .tree
        .root_node()
        .named_descendant_for_byte_range(offset, offset)?;
    if node.kind() != crate::semantic::node_kind::FUNCTION_NAME {
        return None;
    }
    let idiom = node.parent()?;
    if idiom.kind() != crate::semantic::node_kind::IDIOM_FUNCTION {
        return None;
    }
    let name = crate::semantic::node_kind::text_of(&analysis.text, node)?;
    Some((idiom, name.to_string()))
}

#[cfg(test)]
mod tests {
    use std::str::FromStr;
    use std::sync::Arc;

    use ls_types::{
        CompletionItem, DiagnosticSeverity, Documentation, Location, MarkupKind, Position, Range,
        Uri,
    };

    use crate::config::{AuthContext, ServerSettings};
    use crate::semantic::text::LineIndex;
    use crate::semantic::types::{
        DocumentAnalysis, EventDef, FunctionDef, IndexDef, PermissionMode, PermissionRule,
        QueryAction, SymbolOrigin, TableDef, TargetResolution, WorkspaceIndex,
    };

    use super::{MergedSemanticModel, is_record_type_context};

    /// A placeholder parse tree for the `DocumentAnalysis` literals in
    /// these model tests, which exercise the derived fields, not the tree.
    fn empty_tree() -> tree_sitter::Tree {
        let mut parser = tree_sitter::Parser::new();
        parser
            .set_language(&crate::grammar::language())
            .expect("load grammar");
        parser.parse("", None).expect("parse empty")
    }

    #[test]
    fn local_definitions_override_inferred() {
        let uri = Uri::from_str("file:///workspace/schema.surql").expect("valid uri");
        let explicit = TableDef {
            relation: None,
            name: "person".to_string(),
            schema_mode: Some("schemafull".to_string()),
            comment: None,
            permissions: Vec::new(),
            origin: SymbolOrigin::Local,
            explicit: true,
            inference: None,
            location: Location::new(uri.clone(), Range::default()),
        };
        let inferred = TableDef {
            relation: None,
            name: "person".to_string(),
            schema_mode: None,
            comment: None,
            permissions: Vec::new(),
            origin: SymbolOrigin::Inferred,
            explicit: false,
            inference: None,
            location: Location::new(uri.clone(), Range::default()),
        };
        let analysis = DocumentAnalysis {
            edge_observations: Vec::new(),
            uri,
            text: String::new(),
            tree: empty_tree(),
            line_index: LineIndex::default(),
            tables: vec![inferred, explicit.clone()],
            events: Vec::new(),
            indexes: Vec::new(),
            fields: Vec::new(),
            functions: Vec::new(),
            params: Vec::new(),
            accesses: Vec::new(),
            analyzers: Vec::new(),
            query_facts: Vec::new(),
            references: Vec::new(),
            syntax_diagnostics: Vec::new(),
            document_symbols: Vec::new(),
        };
        let mut workspace = WorkspaceIndex::default();
        workspace
            .documents
            .insert(analysis.uri.clone(), Arc::new(analysis));
        let model = MergedSemanticModel::build(&workspace, &Default::default());
        assert_eq!(model.tables["person"].schema_mode, explicit.schema_mode);
    }

    #[test]
    fn evaluates_role_based_permissions() {
        let rule = PermissionRule {
            actions: vec![QueryAction::Select],
            mode: PermissionMode::Expression("WHERE $auth.roles CONTAINS 'viewer'".to_string()),
            raw: "WHERE $auth.roles CONTAINS 'viewer'".to_string(),
            origin: SymbolOrigin::Local,
            location: None,
        };
        let context = AuthContext {
            name: "viewer".to_string(),
            roles: vec!["viewer".to_string()],
            auth_record: None,
            claims: serde_json::Value::Object(Default::default()),
            session: serde_json::Value::Object(Default::default()),
            variables: serde_json::Value::Object(Default::default()),
        };
        let settings = ServerSettings {
            auth_contexts: vec![context.clone()],
            active_auth_context: Some("viewer".to_string()),
            ..ServerSettings::default()
        };
        let table = TableDef {
            relation: None,
            name: "person".to_string(),
            schema_mode: None,
            comment: None,
            permissions: vec![rule],
            origin: SymbolOrigin::Local,
            explicit: true,
            inference: None,
            location: Location::new(
                Uri::from_str("file:///workspace/schema.surql").expect("valid uri"),
                Range::default(),
            ),
        };
        let mut model = MergedSemanticModel::default();
        model.insert_table(table);
        let fact = crate::semantic::types::QueryFact {
            action: QueryAction::Select,
            target_tables: vec!["person".to_string()],
            touched_fields: Vec::new(),
            dynamic: false,
            location: Location::new(
                Uri::from_str("file:///workspace/query.surql").expect("valid uri"),
                Range::default(),
            ),
            target_refs: Vec::new(),
            field_refs: Vec::new(),
            target_resolution: TargetResolution::Static,
        };
        let result = model.semantic_diagnostics(
            &DocumentAnalysis {
                edge_observations: Vec::new(),
                uri: Uri::from_str("file:///workspace/query.surql").expect("valid uri"),
                text: String::new(),
                tree: empty_tree(),
                line_index: LineIndex::default(),
                tables: Vec::new(),
                events: Vec::new(),
                indexes: Vec::new(),
                fields: Vec::new(),
                functions: Vec::new(),
                params: Vec::new(),
                accesses: Vec::new(),
                analyzers: Vec::new(),
                query_facts: vec![fact],
                references: Vec::new(),
                syntax_diagnostics: Vec::new(),
                document_symbols: Vec::new(),
            },
            &settings,
        );
        assert!(result.is_empty());
    }

    #[test]
    fn denied_permissions_produce_error_diagnostic() {
        // SELECT and RELATE are deliberately exempt from static
        // permission checks (their rules are usually row-level and
        // can't be evaluated without an actual record), so this test
        // uses CREATE to exercise the denied-permission code path.
        let settings = ServerSettings::default();
        let table = TableDef {
            relation: None,
            name: "person".to_string(),
            schema_mode: None,
            comment: None,
            permissions: vec![PermissionRule {
                actions: vec![QueryAction::Create],
                mode: PermissionMode::None,
                raw: "PERMISSIONS FOR create NONE".to_string(),
                origin: SymbolOrigin::Local,
                location: None,
            }],
            origin: SymbolOrigin::Local,
            explicit: true,
            inference: None,
            location: Location::new(
                Uri::from_str("file:///workspace/schema.surql").expect("valid uri"),
                Range::default(),
            ),
        };
        let mut model = MergedSemanticModel::default();
        model.insert_table(table);

        let diagnostics = model.semantic_diagnostics(
            &DocumentAnalysis {
                edge_observations: Vec::new(),
                uri: Uri::from_str("file:///workspace/query.surql").expect("valid uri"),
                text: String::new(),
                tree: empty_tree(),
                line_index: LineIndex::default(),
                tables: Vec::new(),
                events: Vec::new(),
                indexes: Vec::new(),
                fields: Vec::new(),
                functions: Vec::new(),
                params: Vec::new(),
                accesses: Vec::new(),
                analyzers: Vec::new(),
                query_facts: vec![crate::semantic::types::QueryFact {
                    action: QueryAction::Create,
                    target_tables: vec!["person".to_string()],
                    touched_fields: Vec::new(),
                    dynamic: false,
                    location: Location::new(
                        Uri::from_str("file:///workspace/query.surql").expect("valid uri"),
                        Range::default(),
                    ),
                    target_refs: Vec::new(),
                    field_refs: Vec::new(),
                    target_resolution: TargetResolution::Static,
                }],
                references: Vec::new(),
                syntax_diagnostics: Vec::new(),
                document_symbols: Vec::new(),
            },
            &settings,
        );

        assert_eq!(diagnostics.len(), 1);
        assert_eq!(diagnostics[0].severity, Some(DiagnosticSeverity::ERROR));
        assert_eq!(
            diagnostics[0].source.as_deref(),
            Some("surreal-language-server")
        );
        assert!(crate::semantic::codes::has_code(
            &diagnostics[0],
            crate::semantic::codes::PERMISSION_DENIED
        ));
    }

    #[test]
    fn select_and_relate_skip_permission_checks() {
        // Even with `PERMISSIONS FOR select NONE` (which would block
        // every reader at runtime), the LSP should not flag SELECTs
        // because runtime row-level rules make static evaluation
        // unreliable. The same applies to RELATE.
        let settings = ServerSettings::default();
        let person = TableDef {
            relation: None,
            name: "person".to_string(),
            schema_mode: None,
            comment: None,
            permissions: vec![
                PermissionRule {
                    actions: vec![QueryAction::Select],
                    mode: PermissionMode::None,
                    raw: "PERMISSIONS FOR select NONE".to_string(),
                    origin: SymbolOrigin::Local,
                    location: None,
                },
                PermissionRule {
                    actions: vec![QueryAction::Relate],
                    mode: PermissionMode::None,
                    raw: "PERMISSIONS FOR relate NONE".to_string(),
                    origin: SymbolOrigin::Local,
                    location: None,
                },
            ],
            origin: SymbolOrigin::Local,
            explicit: true,
            inference: None,
            location: Location::new(
                Uri::from_str("file:///workspace/schema.surql").expect("valid uri"),
                Range::default(),
            ),
        };
        let mut model = MergedSemanticModel::default();
        model.insert_table(person);

        let analysis_uri = Uri::from_str("file:///workspace/query.surql").expect("valid uri");
        let make_fact = |action: QueryAction| crate::semantic::types::QueryFact {
            action,
            target_tables: vec!["person".to_string()],
            touched_fields: Vec::new(),
            dynamic: false,
            location: Location::new(analysis_uri.clone(), Range::default()),
            target_refs: Vec::new(),
            field_refs: Vec::new(),
            target_resolution: TargetResolution::Static,
        };

        let diagnostics = model.semantic_diagnostics(
            &DocumentAnalysis {
                edge_observations: Vec::new(),
                uri: analysis_uri.clone(),
                text: String::new(),
                tree: empty_tree(),
                line_index: LineIndex::default(),
                tables: Vec::new(),
                events: Vec::new(),
                indexes: Vec::new(),
                fields: Vec::new(),
                functions: Vec::new(),
                params: Vec::new(),
                accesses: Vec::new(),
                analyzers: Vec::new(),
                query_facts: vec![
                    make_fact(QueryAction::Select),
                    make_fact(QueryAction::Relate),
                ],
                references: Vec::new(),
                syntax_diagnostics: Vec::new(),
                document_symbols: Vec::new(),
            },
            &settings,
        );

        assert!(
            diagnostics.is_empty(),
            "expected no diagnostics, got {diagnostics:?}"
        );
    }

    #[test]
    fn record_type_hover_resolves_underlying_table() {
        let uri = Uri::from_str("file:///workspace/schema.surql").expect("valid uri");
        let mut workspace = WorkspaceIndex::default();
        workspace.documents.insert(
            uri.clone(),
            Arc::new(DocumentAnalysis {
                edge_observations: Vec::new(),
                uri: uri.clone(),
                text: String::new(),
                tree: empty_tree(),
                line_index: LineIndex::default(),
                tables: vec![TableDef {
                    relation: None,
                    name: "person".to_string(),
                    schema_mode: Some("schemafull".to_string()),
                    comment: Some("People".to_string()),
                    permissions: Vec::new(),
                    origin: SymbolOrigin::Local,
                    explicit: true,
                    inference: None,
                    location: Location::new(uri, Range::default()),
                }],
                events: Vec::new(),
                indexes: Vec::new(),
                fields: Vec::new(),
                functions: Vec::new(),
                params: Vec::new(),
                accesses: Vec::new(),
                analyzers: Vec::new(),
                query_facts: Vec::new(),
                references: Vec::new(),
                syntax_diagnostics: Vec::new(),
                document_symbols: Vec::new(),
            }),
        );
        let model = MergedSemanticModel::build(&workspace, &Default::default());
        let hover = model
            .hover_markdown_for_token("record<person>", None)
            .expect("hover");
        assert!(hover.contains("record<person>"));
        assert!(hover.contains("People"));
    }

    #[test]
    fn record_type_definition_resolves_underlying_table() {
        let uri = Uri::from_str("file:///workspace/schema.surql").expect("valid uri");
        let location = Location::new(
            uri.clone(),
            Range {
                start: Position::new(0, 0),
                end: Position::new(0, 18),
            },
        );
        let mut workspace = WorkspaceIndex::default();
        workspace.documents.insert(
            uri,
            Arc::new(DocumentAnalysis {
                edge_observations: Vec::new(),
                uri: Uri::from_str("file:///workspace/schema.surql").expect("valid uri"),
                text: String::new(),
                tree: empty_tree(),
                line_index: LineIndex::default(),
                tables: vec![TableDef {
                    relation: None,
                    name: "person".to_string(),
                    schema_mode: Some("schemafull".to_string()),
                    comment: Some("People".to_string()),
                    permissions: Vec::new(),
                    origin: SymbolOrigin::Local,
                    explicit: true,
                    inference: None,
                    location: location.clone(),
                }],
                events: Vec::new(),
                indexes: Vec::new(),
                fields: Vec::new(),
                functions: Vec::new(),
                params: Vec::new(),
                accesses: Vec::new(),
                analyzers: Vec::new(),
                query_facts: Vec::new(),
                references: Vec::new(),
                syntax_diagnostics: Vec::new(),
                document_symbols: Vec::new(),
            }),
        );
        let model = MergedSemanticModel::build(&workspace, &Default::default());

        assert_eq!(model.definition_for_token("record<person>"), Some(location));
    }

    #[test]
    fn table_hover_lists_indexes_events_and_permission_posture() {
        let uri = Uri::from_str("file:///workspace/schema.surql").expect("valid uri");
        let analysis = DocumentAnalysis {
            edge_observations: Vec::new(),
            uri: uri.clone(),
            text: String::new(),
            tree: empty_tree(),
            line_index: LineIndex::default(),
            tables: vec![TableDef {
                relation: None,
                name: "person".to_string(),
                schema_mode: Some("schemafull".to_string()),
                comment: Some("People".to_string()),
                permissions: vec![PermissionRule {
                    actions: vec![QueryAction::Select],
                    mode: PermissionMode::Expression(
                        "WHERE $auth.roles CONTAINS 'viewer'".to_string(),
                    ),
                    raw: "PERMISSIONS FOR select WHERE $auth.roles CONTAINS 'viewer'".to_string(),
                    origin: SymbolOrigin::Local,
                    location: None,
                }],
                origin: SymbolOrigin::Local,
                explicit: true,
                inference: None,
                location: Location::new(uri.clone(), Range::default()),
            }],
            events: vec![EventDef {
                table: "person".to_string(),
                name: "audit_person".to_string(),
                comment: None,
                when_clause: None,
                then_clause: None,
                origin: SymbolOrigin::Local,
                location: Location::new(uri.clone(), Range::default()),
            }],
            indexes: vec![IndexDef {
                table: "person".to_string(),
                name: "person_email".to_string(),
                fields: vec!["email".to_string()],
                unique: true,
                options: Vec::new(),
                origin: SymbolOrigin::Local,
                location: Location::new(uri, Range::default()),
            }],
            fields: Vec::new(),
            functions: Vec::new(),
            params: Vec::new(),
            accesses: Vec::new(),
            analyzers: Vec::new(),
            query_facts: Vec::new(),
            references: Vec::new(),
            syntax_diagnostics: Vec::new(),
            document_symbols: Vec::new(),
        };
        let mut workspace = WorkspaceIndex::default();
        workspace
            .documents
            .insert(analysis.uri.clone(), Arc::new(analysis));
        let model = MergedSemanticModel::build(&workspace, &Default::default());
        let hover = model
            .hover_markdown_for_token("person", None)
            .expect("hover");

        assert!(hover.contains("Permissions: gated"));
        assert!(hover.contains("**Known indexes**"));
        assert!(hover.contains("person_email (email | unique)"));
        assert!(hover.contains("**Known events**"));
        assert!(hover.contains("audit_person"));
    }

    #[test]
    fn builtin_function_hover_uses_canonical_signature() {
        let model = MergedSemanticModel::default();
        let hover = model
            .hover_markdown_for_token("type::is::record", None)
            .expect("hover");
        assert!(hover.contains("type::is_record(any, table?: string) -> bool"));
        assert!(hover.contains("Canonical name: `type::is_record`"));
    }

    #[test]
    fn hover_answers_for_the_namespaces_the_curated_table_never_covered() {
        // 18 of the 20 advertised namespaces answered nothing at all before the
        // generated catalogue existed.
        let model = MergedSemanticModel::default();
        for (token, expected) in [
            (
                "math::clamp",
                "math::clamp(arg: number, min: number, max: number)",
            ),
            ("array::at", "array::at(array: array, i: int)"),
            ("crypto::sha256", "crypto::sha256(arg: string)"),
            (
                "time::floor",
                "time::floor(val: datetime, duration: duration)",
            ),
        ] {
            let hover = model
                .hover_markdown_for_token(token, None)
                .unwrap_or_else(|| panic!("no hover for {token}"));
            assert!(
                hover.contains(expected),
                "hover for {token} lacked `{expected}`:\n{hover}"
            );
        }
    }

    #[test]
    fn hover_for_a_generated_builtin_links_its_namespace_docs() {
        let model = MergedSemanticModel::default();
        let hover = model
            .hover_markdown_for_token("math::clamp", None)
            .expect("hover");
        assert!(hover.contains("functions/database/math"), "{hover}");
    }

    #[test]
    fn hover_still_prefers_the_curated_prose_where_it_exists() {
        // The curated table carries a summary and a return type that no
        // generator can produce; it must keep winning.
        let model = MergedSemanticModel::default();
        let hover = model
            .hover_markdown_for_token("string::len", None)
            .expect("hover");
        assert!(hover.contains("Returns the length of a string"), "{hover}");
        assert!(hover.contains("-> number"), "{hover}");
    }

    #[test]
    fn hover_marks_a_name_that_parses_but_cannot_be_called() {
        let model = MergedSemanticModel::default();
        let hover = model
            .hover_markdown_for_token("duration::set_day", None)
            .expect("hover");
        assert!(
            hover.contains("no implementation is reachable"),
            "the nine parse-but-not-callable names should say so:\n{hover}"
        );
    }

    #[test]
    fn builtin_function_completion_includes_string_and_type_families() {
        let model = MergedSemanticModel::default();
        let items = model.completion_items("type::is_", false, None, None, None);
        assert!(items.iter().any(|item| item.label == "type::is_record"));

        let items = model.completion_items("string::low", false, None, None, None);
        assert!(items.iter().any(|item| item.label == "string::lowercase"));
    }

    #[test]
    fn completion_items_include_statement_fields_for_select_update_create() {
        let uri = Uri::from_str("file:///workspace/schema.surql").expect("valid uri");
        let mut model = MergedSemanticModel::default();
        model.insert_field(crate::semantic::types::FieldDef {
            table: "person".to_string(),
            name: "email".to_string(),
            type_expr: Some(crate::semantic::type_expr::TypeExpr::Scalar(
                "string".to_string(),
            )),
            comment: None,
            permissions: Vec::new(),
            origin: SymbolOrigin::Local,
            explicit: true,
            inference: None,
            location: Location::new(uri.clone(), Range::default()),
        });
        model.insert_field(crate::semantic::types::FieldDef {
            table: "company".to_string(),
            name: "email".to_string(),
            type_expr: Some(crate::semantic::type_expr::TypeExpr::Scalar(
                "string".to_string(),
            )),
            comment: None,
            permissions: Vec::new(),
            origin: SymbolOrigin::Local,
            explicit: true,
            inference: None,
            location: Location::new(uri.clone(), Range::default()),
        });

        let single_table = crate::semantic::types::QueryFact {
            action: QueryAction::Select,
            target_tables: vec!["person".to_string()],
            touched_fields: Vec::new(),
            dynamic: false,
            location: Location::new(uri.clone(), Range::default()),
            target_refs: Vec::new(),
            field_refs: Vec::new(),
            target_resolution: TargetResolution::Static,
        };

        let items = model.completion_items("em", false, None, Some(&single_table), None);
        assert!(items.iter().any(|item| {
            item.label == "email"
                && item
                    .detail
                    .as_deref()
                    .unwrap_or_default()
                    .contains("table: person")
        }));

        let multi_table = crate::semantic::types::QueryFact {
            action: QueryAction::Select,
            target_tables: vec!["person".to_string(), "company".to_string()],
            touched_fields: Vec::new(),
            dynamic: false,
            location: Location::new(uri.clone(), Range::default()),
            target_refs: Vec::new(),
            field_refs: Vec::new(),
            target_resolution: TargetResolution::Static,
        };
        let items = model.completion_items("em", false, None, Some(&multi_table), None);
        assert!(items.iter().any(|item| item.label == "person.email"));
        assert!(items.iter().any(|item| item.label == "company.email"));

        let items = model.completion_items("em", false, None, None, Some("person"));
        assert!(items.iter().any(|item| {
            item.label == "email"
                && item
                    .detail
                    .as_deref()
                    .unwrap_or_default()
                    .contains("table: person")
        }));
    }

    #[test]
    fn column_completion_items_returns_only_fields() {
        use ls_types::CompletionItemKind;

        let uri = Uri::from_str("file:///workspace/schema.surql").expect("valid uri");
        let mut model = MergedSemanticModel::default();
        // Tables and functions should NOT leak into the column-only output.
        model.insert_table(TableDef {
            relation: None,
            name: "person".to_string(),
            schema_mode: Some("schemafull".to_string()),
            comment: None,
            permissions: Vec::new(),
            origin: SymbolOrigin::Local,
            explicit: true,
            inference: None,
            location: Location::new(uri.clone(), Range::default()),
        });
        model.functions.insert(
            "fn::greet".to_string(),
            FunctionDef {
                name: "fn::greet".to_string(),
                params: Vec::new(),
                return_type: None,
                language: crate::semantic::types::FunctionLanguage::SurrealQL,
                comment: None,
                permissions: Vec::new(),
                origin: SymbolOrigin::Local,
                explicit: true,
                inference: None,
                location: Location::new(uri.clone(), Range::default()),
                selection_range: Range::default(),
                body_range: None,
                called_functions: Vec::new(),
            },
        );
        for field_name in ["email", "name"] {
            model.insert_field(crate::semantic::types::FieldDef {
                table: "person".to_string(),
                name: field_name.to_string(),
                type_expr: Some(crate::semantic::type_expr::TypeExpr::Scalar(
                    "string".to_string(),
                )),
                comment: None,
                permissions: Vec::new(),
                origin: SymbolOrigin::Local,
                explicit: true,
                inference: None,
                location: Location::new(uri.clone(), Range::default()),
            });
        }

        let items = model.column_completion_items("", &["person".to_string()], false, None);
        assert_eq!(
            items.len(),
            3,
            "the two declared fields plus the implicit `id`, and nothing else"
        );
        assert!(
            items
                .iter()
                .all(|item| item.kind == Some(CompletionItemKind::FIELD)),
            "all items must be FIELD; got {:?}",
            items
                .iter()
                .map(|i| (i.label.clone(), i.kind))
                .collect::<Vec<_>>()
        );
        let labels: Vec<_> = items.iter().map(|item| item.label.clone()).collect();
        assert!(labels.contains(&"email".to_string()));
        assert!(labels.contains(&"name".to_string()));
        // Every record has one, and no `DEFINE FIELD` ever says so.
        assert!(labels.contains(&"id".to_string()));
        // A plain table has no `in` / `out`; only an edge does.
        assert!(!labels.iter().any(|l| l == "in" || l == "out"));
        // No table / function leakage.
        assert!(!labels.iter().any(|l| l == "person" || l == "fn::greet"));
    }

    #[test]
    fn field_sort_text_puts_fields_above_functions_in_loose_mode() {
        let uri = Uri::from_str("file:///workspace/schema.surql").expect("valid uri");
        let mut model = MergedSemanticModel::default();
        model.insert_field(crate::semantic::types::FieldDef {
            table: "person".to_string(),
            name: "email".to_string(),
            type_expr: None,
            comment: None,
            permissions: Vec::new(),
            origin: SymbolOrigin::Local,
            explicit: true,
            inference: None,
            location: Location::new(uri.clone(), Range::default()),
        });
        model.functions.insert(
            "fn::greet".to_string(),
            FunctionDef {
                name: "fn::greet".to_string(),
                params: Vec::new(),
                return_type: None,
                language: crate::semantic::types::FunctionLanguage::SurrealQL,
                comment: None,
                permissions: Vec::new(),
                origin: SymbolOrigin::Local,
                explicit: true,
                inference: None,
                location: Location::new(uri, Range::default()),
                selection_range: Range::default(),
                body_range: None,
                called_functions: Vec::new(),
            },
        );

        let statement_fact = crate::semantic::types::QueryFact {
            action: QueryAction::Select,
            target_tables: vec!["person".to_string()],
            touched_fields: Vec::new(),
            dynamic: false,
            location: Location::new(
                Uri::from_str("file:///workspace/schema.surql").expect("valid uri"),
                Range::default(),
            ),
            target_refs: Vec::new(),
            field_refs: Vec::new(),
            target_resolution: TargetResolution::Static,
        };
        let items = model.completion_items("", false, None, Some(&statement_fact), None);

        let field_sort = items
            .iter()
            .find(|item| item.label == "email")
            .and_then(|item| item.sort_text.clone())
            .expect("field item must have sort_text");
        let function_sort = items
            .iter()
            .find(|item| item.label == "fn::greet")
            .and_then(|item| item.sort_text.clone())
            .expect("function item must have sort_text");
        assert!(
            field_sort < function_sort,
            "field sort_text `{field_sort}` must sort before function sort_text `{function_sort}`"
        );
        assert!(field_sort.starts_with("0-fld-"));
        assert!(function_sort.starts_with("1-"));
    }

    #[test]
    fn remote_functions_cannot_be_renamed() {
        let uri = Uri::from_str("file:///workspace/schema.surql").expect("valid uri");
        let mut model = MergedSemanticModel::default();
        model.functions.insert(
            "fn::remote".to_string(),
            FunctionDef {
                name: "fn::remote".to_string(),
                params: Vec::new(),
                return_type: None,
                language: crate::semantic::types::FunctionLanguage::SurrealQL,
                comment: None,
                permissions: Vec::new(),
                origin: SymbolOrigin::Remote,
                explicit: true,
                inference: None,
                location: Location::new(uri, Range::default()),
                selection_range: Range::default(),
                body_range: None,
                called_functions: Vec::new(),
            },
        );

        assert!(model.rename_edits("fn::remote", "fn::renamed").is_none());
    }

    /// A table item ships without documentation, and resolve puts back exactly
    /// what the eager version used to inline. Without this, moving the hover
    /// text behind `completionItem/resolve` would read as a speed-up while
    /// quietly dropping the documentation.
    #[test]
    fn resolve_restores_the_documentation_the_item_ships_without() {
        let (model, _) = model_with_person_table();

        let items = model.table_completion_items("", None);
        let item = items
            .iter()
            .find(|item| item.label == "person")
            .expect("person is offered")
            .clone();
        assert!(
            item.documentation.is_none(),
            "the item must not carry documentation before resolve"
        );

        let resolved = model.resolve_completion_item(item, None);
        let Some(Documentation::MarkupContent(markup)) = resolved.documentation else {
            panic!("resolve did not attach markdown documentation");
        };
        assert_eq!(markup.kind, MarkupKind::Markdown);
        assert_eq!(
            markup.value,
            super::format_table_hover(model.tables.get("person").expect("present"), &model, None),
            "resolve must produce the same text the eager version inlined"
        );
    }

    /// An item that is not a table, or already carries documentation, comes back
    /// untouched. A resolve that dropped fields would break the client.
    #[test]
    fn resolve_leaves_other_items_alone() {
        let (model, _) = model_with_person_table();

        let keyword = CompletionItem {
            label: "SELECT".to_string(),
            ..CompletionItem::default()
        };
        assert_eq!(
            model.resolve_completion_item(keyword.clone(), None),
            keyword
        );

        let already = CompletionItem {
            label: "person".to_string(),
            documentation: Some(Documentation::String("kept".to_string())),
            data: Some(serde_json::json!({ "table": "person" })),
            ..CompletionItem::default()
        };
        assert_eq!(
            model.resolve_completion_item(already.clone(), None),
            already,
            "an item that already has documentation must not be rewritten"
        );
    }

    /// The prefilter must never reject a pair `jaro_winkler` would have scored
    /// above the gate, over a corpus wide enough to catch a wrong inequality.
    ///
    /// This is the same oracle pattern as the `LineIndex` tests: `strsim` is the
    /// specification, and the fast path has to agree with it. A rejection above
    /// the threshold is a silently lost "did you mean" suggestion, which is why
    /// this sweeps thousands of pairs rather than a handful of named ones.
    #[test]
    fn the_prefilter_never_rejects_a_pair_above_the_threshold() {
        // Deliberately dense in near-misses: a tiny alphabet produces many pairs
        // that genuinely score above 0.86, so the test has something to catch.
        let alphabet = ["a", "b", "c", "_", "0"];
        let mut names: Vec<String> = Vec::new();
        for len in 2..=6 {
            for seed in 0..90u32 {
                let mut name = String::new();
                let mut value = seed;
                for _ in 0..len {
                    name.push_str(alphabet[(value % alphabet.len() as u32) as usize]);
                    value /= alphabet.len() as u32;
                }
                names.push(name);
            }
        }
        // Plus realistic identifiers, including the abbreviation shapes.
        for extra in [
            "person",
            "persn",
            "prson",
            "persons",
            "personaddress",
            "user",
            "userdata",
            "username",
            "acct",
            "accounts",
            "order",
            "orders",
            "oders",
            "address",
            "addres",
            "item",
            "itemvariant",
            "product",
            "prodcut",
            "id",
            "customer_billing_address_line",
            "str",
            "string",
            "rec",
            "record",
        ] {
            names.push(extra.to_string());
        }

        let mut above_threshold = 0usize;
        let mut rejected = 0usize;
        for unknown in &names {
            for candidate in &names {
                if unknown == candidate {
                    continue;
                }
                let score = strsim::jaro_winkler(unknown, candidate);
                let kept = super::can_reach_near_miss_threshold(unknown, candidate);
                if score > super::NEAR_MISS_THRESHOLD {
                    above_threshold += 1;
                    assert!(
                        kept,
                        "prefilter rejected {unknown:?} vs {candidate:?}, which scores {score:.4}"
                    );
                }
                if !kept {
                    rejected += 1;
                }
            }
        }

        // The corpus has to actually contain near-misses, or the assertion above
        // is vacuous, and the filter has to actually reject things, or it is not
        // doing any work.
        assert!(
            above_threshold > 500,
            "corpus produced only {above_threshold} pairs above the threshold — too few to prove anything"
        );
        assert!(
            rejected > 1000,
            "prefilter rejected only {rejected} pairs — it is not pruning"
        );
    }

    /// The prefilter has to prune the shape that made the sweep slow: names that
    /// share most of their characters but no prefix.
    #[test]
    fn the_prefilter_prunes_names_that_share_no_prefix() {
        let unknowns: Vec<String> = (0..20).map(|t| format!("undeclared_d0_t{t}")).collect();
        let candidates: Vec<String> = (0..200)
            .flat_map(|d| (0..5).map(move |t| format!("real_d{d}_t{t}")))
            .collect();

        let total = unknowns.len() * candidates.len();
        let surviving = unknowns
            .iter()
            .flat_map(|unknown| candidates.iter().map(move |candidate| (unknown, candidate)))
            .filter(|(unknown, candidate)| super::can_reach_near_miss_threshold(unknown, candidate))
            .count();

        // None of these pairs is a genuine near-miss, so every survivor is
        // wasted work. The prefix is what does the pruning: `u` against `r`
        // means p = 0, which demands a much higher Jaro score.
        assert!(
            surviving * 100 < total,
            "{surviving} of {total} pairs survived; the prefilter must drop over 99%"
        );
    }

    /// The length prefilter must never reject a pair that jaro-winkler would
    /// have scored above the gate. The named pairs are the trap: they differ in
    /// length by 4 to 7 characters and still score above 0.86, so a prefilter
    /// keyed on the *difference* of the lengths would drop real near-misses.
    #[test]
    fn the_length_prefilter_never_rejects_a_real_near_miss() {
        let pairs = [
            ("user", "userdata"),
            ("user", "username"),
            ("acct", "accounts"),
            ("item", "itemvariant"),
            ("person", "personaddress"),
            ("persn", "person"),
            ("oders", "orders"),
        ];
        for (unknown, candidate) in pairs {
            let score = strsim::jaro_winkler(unknown, candidate);
            if score > super::NEAR_MISS_THRESHOLD {
                assert!(
                    super::can_reach_near_miss_threshold(unknown, candidate),
                    "prefilter rejected {unknown:?} vs {candidate:?}, which scores {score:.3}"
                );
            }
        }
    }

    /// It does still reject the hopeless case, or it would not be worth having.
    #[test]
    fn the_length_prefilter_rejects_a_hopeless_pair() {
        assert!(!super::can_reach_near_miss_threshold(
            "id",
            "customer_billing_address_line"
        ));
        assert!(super::can_reach_near_miss_threshold("person", "persons"));
    }

    #[test]
    fn detects_nested_record_type_context() {
        let source = "DEFINE FIELD friends ON TABLE person TYPE array<record<per";
        let position = Position::new(0, source.len() as u32);
        assert!(is_record_type_context(
            source,
            &LineIndex::new(source),
            position
        ));
    }

    fn model_with_person_table() -> (MergedSemanticModel, DocumentAnalysis) {
        let uri = Uri::from_str("file:///workspace/query.surql").expect("valid uri");
        let mut model = MergedSemanticModel::default();
        model.insert_table(TableDef {
            relation: None,
            name: "person".to_string(),
            schema_mode: None,
            comment: None,
            permissions: vec![PermissionRule {
                actions: vec![QueryAction::Select],
                mode: PermissionMode::Full,
                raw: "PERMISSIONS FULL".to_string(),
                origin: SymbolOrigin::Local,
                location: None,
            }],
            origin: SymbolOrigin::Local,
            explicit: true,
            inference: None,
            location: Location::new(
                Uri::from_str("file:///workspace/schema.surql").expect("valid uri"),
                Range::default(),
            ),
        });
        let analysis = DocumentAnalysis {
            edge_observations: Vec::new(),
            uri,
            text: String::new(),
            tree: empty_tree(),
            line_index: LineIndex::default(),
            tables: Vec::new(),
            events: Vec::new(),
            indexes: Vec::new(),
            fields: Vec::new(),
            functions: Vec::new(),
            params: Vec::new(),
            accesses: Vec::new(),
            analyzers: Vec::new(),
            query_facts: Vec::new(),
            references: Vec::new(),
            syntax_diagnostics: Vec::new(),
            document_symbols: Vec::new(),
        };
        (model, analysis)
    }

    #[test]
    fn code_action_matches_on_stable_code_and_data_not_message_text() {
        let (model, analysis) = model_with_person_table();
        let diagnostic = ls_types::Diagnostic {
            range: Range::default(),
            code: crate::semantic::codes::as_code(crate::semantic::codes::UNKNOWN_TABLE),
            // Sentinel wording proves the matcher never consults the
            // message when the code + data are present.
            message: "totally reworded message".to_string(),
            data: Some(serde_json::json!({ "table": "prson" })),
            ..Default::default()
        };

        let actions = model.code_actions(&analysis.uri.clone(), &analysis, &[diagnostic]);
        let quick_fix = actions
            .iter()
            .find_map(|action| match action {
                ls_types::CodeActionOrCommand::CodeAction(action)
                    if action.title.starts_with("Replace") =>
                {
                    Some(action)
                }
                _ => None,
            })
            .expect("code+data diagnostic must yield the quick fix");
        assert_eq!(quick_fix.title, "Replace `prson` with `person`");
    }

    #[test]
    fn code_action_legacy_message_fallback_still_works() {
        // Pre-0.3 diagnostics carried no code; the string fallback
        // keeps their quick fixes alive for one release. Remove in 0.4.
        let (model, analysis) = model_with_person_table();
        let diagnostic = ls_types::Diagnostic {
            range: Range::default(),
            message: "Unknown table `prson`.".to_string(),
            ..Default::default()
        };

        let actions = model.code_actions(&analysis.uri.clone(), &analysis, &[diagnostic]);
        assert!(
            actions.iter().any(|action| matches!(
                action,
                ls_types::CodeActionOrCommand::CodeAction(action)
                    if action.title == "Replace `prson` with `person`"
            )),
            "legacy message-only diagnostic must still yield the quick fix"
        );
    }

    #[test]
    fn code_action_survives_clients_that_strip_diagnostic_data() {
        // Several clients round-trip `code` but drop the non-standard
        // `data` field — the message fallback must still work.
        let (model, analysis) = model_with_person_table();
        let diagnostic = ls_types::Diagnostic {
            range: Range::default(),
            code: crate::semantic::codes::as_code(crate::semantic::codes::UNKNOWN_TABLE),
            message: "Unknown table `prson`.".to_string(),
            data: None,
            ..Default::default()
        };

        let actions = model.code_actions(&analysis.uri.clone(), &analysis, &[diagnostic]);
        assert!(actions.iter().any(|action| matches!(
            action,
            ls_types::CodeActionOrCommand::CodeAction(action)
                if action.title == "Replace `prson` with `person`"
        )));
    }

    #[test]
    fn code_action_message_fallback_parses_did_you_mean_shape() {
        // The 0.3 message carries a suggestion suffix; the fallback
        // parser must extract both table and suggestion from it.
        let (model, analysis) = model_with_person_table();
        let diagnostic = ls_types::Diagnostic {
            range: Range::default(),
            message: "Unknown table `zzz`. Did you mean `person`?".to_string(),
            ..Default::default()
        };

        // `zzz` has no near-miss, so only the parsed suggestion can
        // produce this action.
        let actions = model.code_actions(&analysis.uri.clone(), &analysis, &[diagnostic]);
        assert!(actions.iter().any(|action| matches!(
            action,
            ls_types::CodeActionOrCommand::CodeAction(action)
                if action.title == "Replace `zzz` with `person`"
        )));
    }

    #[test]
    fn code_action_honours_precomputed_suggestion_in_data() {
        let (model, analysis) = model_with_person_table();
        let diagnostic = ls_types::Diagnostic {
            range: Range::default(),
            code: crate::semantic::codes::as_code(crate::semantic::codes::UNKNOWN_TABLE),
            message: "Unknown table `zzz`. Did you mean `person`?".to_string(),
            data: Some(serde_json::json!({ "table": "zzz", "suggestion": "person" })),
            ..Default::default()
        };

        // `zzz` is nowhere near `person` by string distance, so only
        // the precomputed suggestion can produce this action.
        let actions = model.code_actions(&analysis.uri.clone(), &analysis, &[diagnostic]);
        assert!(actions.iter().any(|action| matches!(
            action,
            ls_types::CodeActionOrCommand::CodeAction(action)
                if action.title == "Replace `zzz` with `person`"
        )));
    }
}