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
//! The transport-agnostic language server.
//!
//! [`LanguageServerCore`] owns every piece of mutable state plus the
//! complete LSP request/notification handling logic. The native
//! `Backend` and the WASM `WasmLanguageServer` are thin adapters: they
//! receive transport-specific input (tower-lsp invocations or
//! JSON-RPC strings handed in from JavaScript), call the equivalent
//! method here, and return whatever the core produces.
//!
//! The three trait-bound generics [`LspNotifier`], [`WorkspaceLoader`]
//! and [`MetadataProvider`] keep this module ignorant of how
//! diagnostics are actually shipped, where `.surql` files come from,
//! and how live SurrealDB metadata is fetched. See
//! [`crate::core::client`] for the trait definitions and
//! [`crate::native`] / [`crate::wasm`] for the per-target impls.

use std::path::PathBuf;
use std::sync::Arc;

use ls_types::*;

use crate::config::{AuthContext, ServerSettings};
use crate::core::client::{LspNotifier, MetadataProvider, WorkspaceLoader};
use crate::core::completion_context::{
    ColumnSlot, active_query_fact, column_completion_context, completion_prefix,
    completion_table_qualifier, graph_anchors, graph_edge_context, head_slot_at,
    is_table_name_context, statement_target_in_text,
};
use crate::core::state::{ServerState, merged_workspace, workspace_signature};
use crate::core::statement_shape::SlotYield;
use crate::grammar::{BuiltinFunction, BuiltinSignature, builtin_function, builtin_signature};
use crate::runtime;
use crate::semantic::analyzer::{analyze_document, analyze_document_with_limit};
use crate::semantic::model::{
    field_completion_tables, function_signature_with_return, is_record_type_context, param_label,
};
use crate::semantic::text::{token_at, word_range};
use crate::semantic::types::{
    DocumentAnalysis, FunctionDef, LiveMetadataSnapshot, MergedSemanticModel, SymbolOrigin,
    WorkspaceIndex,
};

/// The crate version plus the source and grammar revisions this binary was
/// compiled from.
///
/// The bare crate version is the *same string* on an unreleased branch and
/// on the published release, so on its own it cannot tell you which binary
/// an editor is actually talking to. Clients surface
/// `serverInfo.version`, which makes that answerable at a glance instead of
/// by deduction.
pub fn build_version() -> String {
    format!(
        "{} ({})",
        env!("CARGO_PKG_VERSION"),
        env!("SURREALQL_LS_BUILD")
    )
}

/// Hosting-agnostic language server. Generic over the three boundary
/// traits so that a native (tower-lsp + walkdir + surrealdb) and a
/// browser (wasm-bindgen) front-end can share every line of business
/// logic.
pub struct LanguageServerCore<N: LspNotifier, W: WorkspaceLoader, M: MetadataProvider> {
    notifier: Arc<N>,
    workspace_loader: Arc<W>,
    metadata_provider: Arc<M>,
    state: Arc<runtime::sync::RwLock<ServerState>>,
    /// Serializes every settings/metadata application (the native
    /// adapter spawns `didChangeConfiguration` / `didSave` handlers,
    /// so two read-merge-apply sequences would otherwise interleave
    /// and lose updates or invert the metadata-error status).
    config_lock: Arc<runtime::sync::Mutex<()>>,
}

impl<N, W, M> LanguageServerCore<N, W, M>
where
    N: LspNotifier,
    W: WorkspaceLoader,
    M: MetadataProvider,
{
    pub fn new(notifier: N, workspace_loader: W, metadata_provider: M) -> Self {
        Self {
            notifier: Arc::new(notifier),
            workspace_loader: Arc::new(workspace_loader),
            metadata_provider: Arc::new(metadata_provider),
            state: Arc::new(runtime::sync::RwLock::new(ServerState::default())),
            config_lock: Arc::new(runtime::sync::Mutex::new(())),
        }
    }

    /// Borrow the outbound notifier (used by the native adapter to
    /// drive `did_save`/`did_change_configuration` background tasks).
    pub fn notifier(&self) -> &Arc<N> {
        &self.notifier
    }

    /// LSP capability advertisement, identical for both targets.
    pub fn server_capabilities() -> ServerCapabilities {
        ServerCapabilities {
            text_document_sync: Some(TextDocumentSyncCapability::Kind(TextDocumentSyncKind::FULL)),
            completion_provider: Some(CompletionOptions {
                // Table items ship without documentation and get it from
                // `completion_resolve`, so the dropdown does not pay to render
                // hover markdown for every table in the schema.
                resolve_provider: Some(true),
                // `>` closes a `->`, the way `<` opens a `<-`. Without it the
                // two arrow directions behaved differently: `<-` popped the
                // list and `->` did not, so the commoner spelling was the one
                // that looked broken.
                trigger_characters: Some(vec![
                    ".".into(),
                    ":".into(),
                    "<".into(),
                    ">".into(),
                    "$".into(),
                    "(".into(),
                ]),
                ..CompletionOptions::default()
            }),
            hover_provider: Some(HoverProviderCapability::Simple(true)),
            definition_provider: Some(OneOf::Left(true)),
            references_provider: Some(OneOf::Left(true)),
            rename_provider: Some(OneOf::Right(RenameOptions {
                prepare_provider: Some(true),
                work_done_progress_options: Default::default(),
            })),
            signature_help_provider: Some(SignatureHelpOptions {
                trigger_characters: Some(vec!["(".into(), ",".into()]),
                retrigger_characters: Some(vec![",".into()]),
                work_done_progress_options: Default::default(),
            }),
            code_action_provider: Some(CodeActionProviderCapability::Simple(true)),
            document_highlight_provider: Some(OneOf::Left(true)),
            inlay_hint_provider: Some(OneOf::Right(InlayHintServerCapabilities::Options(
                InlayHintOptions {
                    resolve_provider: Some(false),
                    ..InlayHintOptions::default()
                },
            ))),
            call_hierarchy_provider: Some(CallHierarchyServerCapability::Simple(true)),
            semantic_tokens_provider: Some(
                SemanticTokensServerCapabilities::SemanticTokensOptions(SemanticTokensOptions {
                    legend: crate::semantic::highlight::legend(),
                    full: Some(SemanticTokensFullOptions::Bool(true)),
                    range: Some(true),
                    work_done_progress_options: Default::default(),
                }),
            ),
            document_symbol_provider: Some(OneOf::Left(true)),
            workspace_symbol_provider: Some(OneOf::Left(true)),
            workspace: Some(WorkspaceServerCapabilities {
                workspace_folders: Some(WorkspaceFoldersServerCapabilities {
                    supported: Some(true),
                    change_notifications: Some(OneOf::Left(true)),
                }),
                file_operations: None,
            }),
            ..ServerCapabilities::default()
        }
    }

    // ──────────────────────────────────────────────────────────────────
    // Lifecycle
    // ──────────────────────────────────────────────────────────────────

    /// Stash the client-supplied initialization options + workspace
    /// folders. The heavy work (workspace walk, live metadata fetch) is
    /// deferred to [`Self::apply_settings`], usually triggered by
    /// `initialized → reload_from_client_configuration`.
    pub async fn initialize(&self, params: InitializeParams) -> InitializeResult {
        let (settings, warnings) = ServerSettings::from_sources_with_warnings(
            params.initialization_options.as_ref(),
            None,
        );
        let workspace_folders = resolve_workspace_folders(&params);

        {
            let mut state = self.state.write().await;
            state.settings = Arc::new(settings);
            state.workspace_folders = workspace_folders;
            // The client can't receive `window/logMessage` until the
            // initialize handshake completes; `initialized` drains these.
            state.pending_settings_warnings = warnings;
        }

        InitializeResult {
            server_info: Some(ServerInfo {
                name: "surreal-language-server".to_string(),
                version: Some(build_version()),
            }),
            capabilities: Self::server_capabilities(),
            ..Default::default()
        }
    }

    /// Pull the latest configuration from the client and re-run
    /// [`Self::apply_settings`]. Logs an info message on completion.
    pub async fn initialized(&self) {
        let pending_warnings = {
            let mut state = self.state.write().await;
            std::mem::take(&mut state.pending_settings_warnings)
        };
        self.report_settings_warnings(&pending_warnings).await;
        self.reload_from_client_configuration().await;
        self.notifier
            .log_message(
                MessageType::INFO,
                "SurrealQL semantic language server ready".to_string(),
            )
            .await;
    }

    /// Asks the client for the `surrealql` configuration section
    /// (`workspace/configuration`), merges the response with whatever
    /// settings are already in flight, and applies the result.
    pub async fn reload_from_client_configuration(&self) {
        // Ask the client before taking the config lock — a slow
        // configuration pull must not stall other settings work.
        let configuration = self.notifier.request_configuration().await;
        let (settings, warnings) =
            ServerSettings::from_sources_with_warnings(None, configuration.as_ref());
        // A client without configuration support answers `None`, and
        // VS Code / Neovim answer the pull with JSON `null` when no
        // `surrealql` section is configured — both always yield zero
        // warnings. Reporting those would reset the dedup signature
        // and fire a spurious "resolved" line right after the
        // initialize-stashed warnings. (A *real* clean section does
        // report: it replaces the previous settings, so its empty
        // warning set genuinely resolves them.)
        if configuration.as_ref().is_some_and(|value| !value.is_null()) {
            self.report_settings_warnings(&warnings).await;
        }

        let _guard = self.config_lock.lock().await;
        let current_settings = {
            let state = self.state.read().await;
            (*state.settings).clone()
        };
        let settings = settings.merge_with_env_if_missing(current_settings);
        self.apply_settings_inner(settings).await;
    }

    /// Log settings warnings, once per *distinct* warning set — a
    /// persistently misconfigured editor would otherwise re-log the
    /// same lines on every configuration pull and `didChange`. Same
    /// pattern as [`Self::report_metadata_errors`]: the state lock is
    /// released before any notifier await.
    async fn report_settings_warnings(&self, warnings: &[String]) {
        let mut signature = warnings.to_vec();
        signature.sort();

        let previous = {
            let mut state = self.state.write().await;
            state.last_settings_warnings.replace(signature.clone())
        };

        if previous.as_ref() == Some(&signature) {
            return;
        }

        if signature.is_empty() {
            if previous.is_some_and(|previous| !previous.is_empty()) {
                self.notifier
                    .log_message(
                        MessageType::INFO,
                        "SurrealQL settings: previous warnings resolved".to_string(),
                    )
                    .await;
            }
            return;
        }

        for warning in warnings {
            self.notifier
                .log_message(
                    MessageType::WARNING,
                    format!("SurrealQL settings: {warning}"),
                )
                .await;
        }
    }

    /// Persist new settings, re-load the saved workspace, refresh live
    /// metadata, rebuild the merged model, and republish diagnostics
    /// for every open document.
    ///
    /// Native callers wrap this in `tokio::spawn` so notification
    /// handlers return immediately. WASM callers `await` it directly
    /// — there is no advantage to background scheduling on a
    /// single-threaded event loop.
    pub async fn apply_settings(&self, settings: ServerSettings) {
        let _guard = self.config_lock.lock().await;
        self.apply_settings_inner(settings).await;
    }

    /// [`Self::apply_settings`] body; callers must hold `config_lock`.
    async fn apply_settings_inner(&self, settings: ServerSettings) {
        let (workspace_folders, last_walked, previous_syntax_limit) = {
            let mut state = self.state.write().await;
            let previous_syntax_limit = state.settings.analysis.max_syntax_diagnostics;
            state.settings = Arc::new(settings.clone());
            (
                state.workspace_folders.clone(),
                state.last_walked.clone(),
                previous_syntax_limit,
            )
        };

        // The syntax cap is applied while the tree is walked, so an already
        // analyzed document keeps the count it was parsed under. Re-analyze
        // the open ones when the cap moves, otherwise raising it appears to
        // do nothing until each buffer is edited.
        if previous_syntax_limit != settings.analysis.max_syntax_diagnostics {
            self.reanalyze_open_documents(settings.analysis.max_syntax_diagnostics)
                .await;
        }

        let folder_signature = workspace_signature(&workspace_folders);
        let need_walk = last_walked
            .as_ref()
            .map(|previous| previous != &folder_signature)
            .unwrap_or(true);

        let saved_workspace = if settings.metadata.filesystem_enabled() {
            if need_walk {
                Arc::new(self.workspace_loader.load(&workspace_folders).await)
            } else {
                let s = self.state.read().await;
                Arc::clone(&s.saved_workspace)
            }
        } else {
            self.state.write().await.last_walked = None;
            Arc::new(Default::default())
        };

        let live_metadata = Arc::new(self.metadata_provider.fetch(&settings).await);
        self.report_metadata_errors(&live_metadata).await;
        if need_walk {
            self.report_scan_stats(&saved_workspace).await;
        }
        let (open_documents, uris_for_diag) = {
            let s = self.state.read().await;
            (
                s.open_documents.clone(),
                s.open_documents.keys().cloned().collect::<Vec<_>>(),
            )
        };
        let workspace = merged_workspace(&saved_workspace, &open_documents);
        let model = Arc::new(MergedSemanticModel::build(&workspace, &live_metadata));

        {
            let mut state = self.state.write().await;
            state.saved_workspace = Arc::clone(&saved_workspace);
            state.live_metadata = Arc::clone(&live_metadata);
            state.model = Arc::clone(&model);
            if need_walk {
                state.last_walked = Some(folder_signature);
            }
        }

        let saved_for_diag = saved_workspace;
        let model_for_diag = model;
        let settings_for_diag = Arc::new(settings);
        for uri in uris_for_diag {
            let analysis = open_documents
                .get(&uri)
                .cloned()
                .or_else(|| saved_for_diag.documents.get(&uri).cloned());
            if let Some(analysis) = analysis {
                let diagnostics =
                    diagnostics_for_document(&analysis, &model_for_diag, &settings_for_diag);
                self.notifier.publish_diagnostics(uri, diagnostics).await;
            }
        }
    }

    // ──────────────────────────────────────────────────────────────────
    // Document lifecycle
    // ──────────────────────────────────────────────────────────────────

    pub async fn did_open(&self, params: DidOpenTextDocumentParams) {
        let document = params.text_document;
        self.upsert_open_document(document.uri, document.text, Edit::Opened)
            .await;
    }

    pub async fn did_change(&self, params: DidChangeTextDocumentParams) {
        let Some(change) = params.content_changes.into_iter().last() else {
            return;
        };
        self.upsert_open_document(
            params.text_document.uri,
            change.text,
            Edit::Changed(params.text_document.version),
        )
        .await;
    }

    pub async fn did_save(&self, params: DidSaveTextDocumentParams) {
        let (refresh_remote, uri) = {
            let state = self.state.read().await;
            (
                state.settings.metadata.refresh_on_save,
                params.text_document.uri.clone(),
            )
        };
        self.sync_saved_document_from_disk(&uri).await;
        self.recompute_model().await;
        if refresh_remote {
            self.refresh_remote_metadata_if_needed().await;
        }
        self.publish_diagnostics_for_uri(&uri).await;
    }

    pub async fn did_close(&self, params: DidCloseTextDocumentParams) {
        let uri = params.text_document.uri;
        {
            let mut state = self.state.write().await;
            state.open_documents.remove(&uri);
        }
        self.sync_saved_document_from_disk(&uri).await;
        self.recompute_model().await;
        self.notifier.publish_diagnostics(uri, Vec::new()).await;
    }

    pub async fn did_change_configuration(&self, params: DidChangeConfigurationParams) {
        // Clients that support configuration pulls send `null` here as
        // a "something changed, ask me" signal.
        if params.settings.is_null() {
            self.reload_from_client_configuration().await;
            return;
        }

        // Merge over the in-flight settings — a partial payload (e.g.
        // one that only carries `metadata.*`) must not wipe the
        // connection details that arrived via initializationOptions.
        // The read-merge-apply sequence runs under the config lock so
        // two spawned configuration changes can't lose each other's
        // updates.
        let (settings, warnings) =
            ServerSettings::from_sources_with_warnings(None, Some(&params.settings));
        self.report_settings_warnings(&warnings).await;

        let _guard = self.config_lock.lock().await;
        let current_settings = {
            let state = self.state.read().await;
            (*state.settings).clone()
        };
        let settings = settings.merge_with_env_if_missing(current_settings);
        self.apply_settings_inner(settings).await;
    }

    pub async fn did_change_workspace_folders(&self, params: DidChangeWorkspaceFoldersParams) {
        {
            let mut state = self.state.write().await;
            for removed in params.event.removed {
                if let Some(path) = removed.uri.to_file_path() {
                    let path = path.into_owned();
                    state.workspace_folders.retain(|folder| folder != &path);
                }
            }
            for added in params.event.added {
                if let Some(path) = added.uri.to_file_path() {
                    let path = path.into_owned();
                    if !state.workspace_folders.contains(&path) {
                        state.workspace_folders.push(path);
                    }
                }
            }
        }

        let settings = {
            let state = self.state.read().await;
            (*state.settings).clone()
        };
        self.apply_settings(settings).await;
    }

    /// Re-run the workspace loader and rebuild the merged model
    /// without touching settings or live metadata. The WASM adapter
    /// uses this after the host pushes / drops a saved document so
    /// the change is reflected immediately.
    pub async fn reload_workspace(&self) {
        let folders = {
            let state = self.state.read().await;
            state.workspace_folders.clone()
        };
        let workspace = Arc::new(self.workspace_loader.load(&folders).await);
        self.report_scan_stats(&workspace).await;
        {
            let mut state = self.state.write().await;
            state.saved_workspace = workspace;
        }
        self.recompute_model().await;
        self.republish_open_diagnostics().await;
    }

    /// Replace the current live metadata snapshot. Used by the WASM
    /// target so Surrealist can push DEFINE strings over from its
    /// already-open SurrealDB connection.
    pub async fn replace_live_metadata(
        &self,
        snapshot: crate::semantic::types::LiveMetadataSnapshot,
    ) {
        {
            let mut state = self.state.write().await;
            state.live_metadata = Arc::new(snapshot);
        }
        self.recompute_model().await;
        self.republish_open_diagnostics().await;
    }

    // ──────────────────────────────────────────────────────────────────
    // Per-request handlers
    // ──────────────────────────────────────────────────────────────────

    pub async fn completion(&self, params: CompletionParams) -> Option<CompletionResponse> {
        let uri = params.text_document_position.text_document.uri;
        let position = params.text_document_position.position;
        let (analysis, model, settings) = self.snapshot_for_uri(&uri).await?;

        let record_type_context =
            is_record_type_context(&analysis.text, &analysis.line_index, position);
        let prefix = completion_prefix(
            &analysis.text,
            &analysis.line_index,
            position,
            record_type_context,
        );

        // A cursor just after `->` / `<-` names the next hop of a graph
        // traversal, so only a table is legal there — and the ones actually
        // reachable from this statement's table belong at the top. Checked
        // before the plain table slot below because the two scans disagree
        // about the arrow: `is_table_name_context` walks back over identifier
        // characters, which `>` is not, so it would answer `false` and let the
        // whole catalogue through.
        if !record_type_context
            && let Some(slot) = graph_edge_context(&analysis.text, &analysis.line_index, position)
        {
            let anchors = graph_anchors(&slot, &analysis, position);
            let items = model.graph_completion_items(
                prefix.trim_matches(|ch: char| ch == ':'),
                &anchors,
                slot.direction,
                slot.from_edge,
                settings.active_auth_context(),
            );
            // Say exactly which characters an item replaces, instead of
            // leaving the client to work it out. Everywhere else in this
            // handler the cursor follows a space or a `.`, so any client's
            // word scan agrees with ours; after `->` it does not. A client
            // whose word pattern admits `-` or `>` reads the prefix as
            // `person->`, filters every item against it, matches none, and
            // shows an empty popup — the same defect this server had, arrived
            // at independently. An explicit range removes the guesswork.
            let replace = replaced_range(&analysis, position, prefix.len());
            return Some(CompletionResponse::Array(with_replace_range(
                items, replace,
            )));
        }

        // When the cursor sits in a slot that only accepts a table name
        // (e.g. `SELECT * FROM |`, `INSERT INTO |`, `UPDATE |`), restrict
        // suggestions to known tables — otherwise the dropdown is flooded
        // with keywords/functions/fields/params the user can't legally use
        // there.
        if !record_type_context
            && is_table_name_context(&analysis.text, &analysis.line_index, position)
        {
            let items = model.table_completion_items(
                prefix.trim_matches(|ch: char| ch == ':'),
                settings.active_auth_context(),
            );
            return Some(CompletionResponse::Array(items));
        }

        let trimmed_prefix = prefix.trim_matches(|ch: char| ch == ':');

        // A statement head whose legal continuations are a closed set —
        // `INFO FOR `, `USE `, `DEFINE `, `REMOVE `, `ALTER `, `SHOW `. Offering
        // the whole catalogue in those positions is the reported defect: an
        // empty prefix disables every filter below, so `INFO FOR ` returned ~375
        // items of which nine were legal.
        //
        // The table answers `Expression` for anything it does not model, which
        // falls through to the behaviour this handler had before, so no working
        // position can regress.
        if !record_type_context {
            let slot = head_slot_at(&analysis.text, &analysis.line_index, position);
            if slot != SlotYield::Expression {
                return Some(CompletionResponse::Array(head_slot_items(
                    slot,
                    trimmed_prefix,
                    &model,
                    settings.active_auth_context(),
                )));
            }
        }

        let statement_fact = active_query_fact(&analysis, position);
        let qualifier = completion_table_qualifier(&analysis.text, &analysis.line_index, position);

        // A `.` admits a field *and* a method, so these are added to whatever the
        // position already offers rather than replacing it.
        let method_items = model.method_completion_items(&analysis, position, trimmed_prefix);

        // A `.` on a value that has named members — a row a query built, or a
        // record pointing at a declared table. Only those members and the
        // methods are legal there, so this answers outright. `completion_table_
        // qualifier` cannot serve this case: it deliberately refuses a `$`
        // receiver, having no way to tell a variable from a table name.
        let property_items = model.property_completion_items(&analysis, position, trimmed_prefix);
        if !property_items.is_empty() {
            let mut items = property_items;
            items.extend(method_items);
            return Some(CompletionResponse::Array(items));
        }

        // Decide whether the cursor is in a column-name slot. A `tbl.`
        // qualifier is always treated as a strict slot (the only legal
        // continuations are field names of `tbl`).
        let column_slot = if qualifier.is_some() {
            Some(ColumnSlot::Strict { allow_star: false })
        } else if record_type_context {
            None
        } else {
            column_completion_context(&analysis.text, &analysis.line_index, position)
        };

        if let Some(ColumnSlot::Strict { allow_star }) = column_slot {
            let field_tables = field_tables_at(&analysis, position, qualifier.as_deref());
            if !field_tables.is_empty() {
                let multi_table_context = qualifier.is_none() && field_tables.len() > 1;
                let mut items = model.column_completion_items(
                    trimmed_prefix,
                    &field_tables,
                    multi_table_context,
                    settings.active_auth_context(),
                );
                if allow_star && (trimmed_prefix.is_empty() || "*".starts_with(trimmed_prefix)) {
                    items.insert(
                        0,
                        CompletionItem {
                            label: "*".to_string(),
                            kind: Some(CompletionItemKind::OPERATOR),
                            detail: Some("All columns".to_string()),
                            insert_text: Some("*".to_string()),
                            sort_text: Some("0-aaa-star".to_string()),
                            ..CompletionItem::default()
                        },
                    );
                }
                items.extend(method_items);
                return Some(CompletionResponse::Array(items));
            }
        }

        let mut items = model.completion_items(
            trimmed_prefix,
            record_type_context,
            settings.active_auth_context(),
            statement_fact,
            qualifier.as_deref(),
        );
        // In-scope `$variables` sort above everything else: when the user
        // has typed a `$`, a local binding is almost always what they mean.
        if !record_type_context {
            let mut variables =
                model.variable_completion_items(&analysis, position, trimmed_prefix);
            variables.append(&mut items);
            items = variables;
        }
        // Methods first: at a `.` position they are what the user is reaching
        // for, and their `sort_text` already ranks a type-matched method above
        // the untyped fallback.
        if !method_items.is_empty() {
            let mut merged = method_items;
            merged.append(&mut items);
            items = merged;
        }
        Some(CompletionResponse::Array(items))
    }

    /// Fill in the documentation for the completion item the client is
    /// showing. See [`MergedSemanticModel::resolve_completion_item`].
    ///
    /// The item is echoed back unchanged when nothing can be added, which is
    /// what the protocol expects — a resolve must never drop fields the client
    /// already has.
    pub async fn completion_resolve(&self, item: CompletionItem) -> CompletionItem {
        let (model, settings) = {
            let state = self.state.read().await;
            (Arc::clone(&state.model), Arc::clone(&state.settings))
        };
        model.resolve_completion_item(item, settings.active_auth_context())
    }

    pub async fn hover(&self, params: HoverParams) -> Option<Hover> {
        let uri = params.text_document_position_params.text_document.uri;
        let position = params.text_document_position_params.position;
        let (analysis, model, settings) = self.snapshot_for_uri(&uri).await?;

        let token = token_at(&analysis.text, &analysis.line_index, position)?;
        let range = word_range(&analysis.text, &analysis.line_index, position)?;
        // A column name resolves only against the table the statement reads, so
        // hover needs the same context completion does — but *not* the `tbl.`
        // qualifier. Completion needs it because the cursor sits after the dot
        // with nothing else to go on; hover can see the whole idiom, and
        // `address.street` would otherwise read `address` as a table and look
        // the column up on a table that does not exist. `field_hover` splits a
        // genuine `table.column` itself.
        let field_tables = field_tables_at(&analysis, position, None);

        let contents = model.hover_markdown_at(
            &analysis,
            position,
            token.trim_matches(|ch: char| {
                matches!(ch, '(' | ')' | '[' | ']' | '{' | '}' | ',' | ';')
            }),
            settings.active_auth_context(),
            &field_tables,
        )?;

        Some(Hover {
            contents: HoverContents::Markup(MarkupContent {
                kind: MarkupKind::Markdown,
                value: contents,
            }),
            range: Some(range),
        })
    }

    pub async fn document_symbol(
        &self,
        params: DocumentSymbolParams,
    ) -> Option<DocumentSymbolResponse> {
        let uri = params.text_document.uri;
        let (analysis, _, _) = self.snapshot_for_uri(&uri).await?;
        Some(DocumentSymbolResponse::Nested(
            analysis.document_symbols.clone(),
        ))
    }

    /// Full-document semantic tokens. Re-parses the document and maps
    /// tree-sitter node kinds onto the standard LSP token legend (see
    /// [`crate::semantic::highlight`]).
    pub async fn semantic_tokens_full(
        &self,
        params: SemanticTokensParams,
    ) -> Option<SemanticTokensResult> {
        let uri = params.text_document.uri;
        let (analysis, _, _) = self.snapshot_for_uri(&uri).await?;
        let data = crate::semantic::highlight::collect_semantic_tokens(
            &analysis.tree,
            &analysis.text,
            &analysis.line_index,
        );
        Some(SemanticTokensResult::Tokens(SemanticTokens {
            result_id: None,
            data,
        }))
    }

    /// Semantic tokens for a viewport range — same mapping as
    /// [`Self::semantic_tokens_full`], restricted to nodes overlapping
    /// `params.range`.
    pub async fn semantic_tokens_range(
        &self,
        params: SemanticTokensRangeParams,
    ) -> Option<SemanticTokensRangeResult> {
        let uri = params.text_document.uri;
        let (analysis, _, _) = self.snapshot_for_uri(&uri).await?;
        let data = crate::semantic::highlight::collect_semantic_tokens_range(
            &analysis.tree,
            &analysis.text,
            &analysis.line_index,
            params.range,
        );
        Some(SemanticTokensRangeResult::Tokens(SemanticTokens {
            result_id: None,
            data,
        }))
    }

    pub async fn goto_definition(
        &self,
        params: GotoDefinitionParams,
    ) -> Option<GotoDefinitionResponse> {
        let uri = params.text_document_position_params.text_document.uri;
        let position = params.text_document_position_params.position;
        let (analysis, model, _) = self.snapshot_for_uri(&uri).await?;
        let token = token_at(&analysis.text, &analysis.line_index, position)?;

        let token = token.trim().to_string();
        model
            .definition_for_token(&token)
            .map(GotoDefinitionResponse::Scalar)
    }

    pub async fn references(&self, params: ReferenceParams) -> Vec<Location> {
        let uri = params.text_document_position.text_document.uri;
        let position = params.text_document_position.position;
        let Some((analysis, model, _)) = self.snapshot_for_uri(&uri).await else {
            return Vec::new();
        };
        let Some(token) = token_at(&analysis.text, &analysis.line_index, position) else {
            return Vec::new();
        };
        model.references_for_function(token.trim())
    }

    pub async fn prepare_rename(
        &self,
        params: TextDocumentPositionParams,
    ) -> Option<PrepareRenameResponse> {
        let uri = params.text_document.uri;
        let position = params.position;
        let (analysis, model, _) = self.snapshot_for_uri(&uri).await?;
        let token = token_at(&analysis.text, &analysis.line_index, position)?;
        let name = token.trim();
        let location = model.definition_for_function(name)?;
        Some(PrepareRenameResponse::RangeWithPlaceholder {
            range: location.range,
            placeholder: name.to_string(),
        })
    }

    pub async fn rename(&self, params: RenameParams) -> Option<WorkspaceEdit> {
        let uri = params.text_document_position.text_document.uri;
        let position = params.text_document_position.position;
        let (analysis, model, _) = self.snapshot_for_uri(&uri).await?;
        let token = token_at(&analysis.text, &analysis.line_index, position)?;
        let changes = model.rename_edits(token.trim(), &params.new_name)?;
        Some(WorkspaceEdit {
            changes: Some(changes),
            ..WorkspaceEdit::default()
        })
    }

    pub async fn signature_help(&self, params: SignatureHelpParams) -> Option<SignatureHelp> {
        let uri = params.text_document_position_params.text_document.uri;
        let position = params.text_document_position_params.position;
        let (analysis, model, _) = self.snapshot_for_uri(&uri).await?;
        let offset = analysis.line_index.offset(&analysis.text, position);
        let prefix = &analysis.text[..offset];
        let open_paren = prefix.rfind('(')?;
        let function_name = prefix[..open_paren]
            .trim_end()
            .split_whitespace()
            .last()
            .map(str::trim)
            .unwrap_or_default();
        let active_parameter = prefix[open_paren + 1..]
            .chars()
            .filter(|ch| *ch == ',')
            .count() as u32;

        // A method: `'abc'.slice(` reads as one whitespace-delimited token, so the
        // tail after the last `.` is the method name. It resolves through the
        // receiver's table, and parameter zero is dropped because the receiver
        // already fills it.
        //
        // The receiver is found from the text rather than from an `IdiomFunction`
        // node, because on the `(` keystroke there is no such node yet: with an
        // empty argument list the grammar reads `.slice` as a *field access* and
        // leaves the `(` as an ERROR sibling. Signature help is most useful at
        // exactly that moment, so it cannot wait for the tree to agree.
        if let Some((_, method)) = function_name.rsplit_once('.')
            && !method.is_empty()
            && let Some(dot) = open_paren.checked_sub(method.len() + 1)
            && analysis.text.as_bytes().get(dot) == Some(&b'.')
        {
            let receiver = analysis
                .tree
                .root_node()
                .named_descendant_for_byte_range(dot.saturating_sub(1), dot);
            if let Some(receiver) = receiver {
                let bindings = crate::semantic::infer::resolve_bindings(&analysis, &model);
                let ctx = crate::semantic::infer::TypeCtx {
                    model: &model,
                    source: &analysis.text,
                    lines: &analysis.line_index,
                    bindings: &bindings,
                };
                let receiver_type = crate::semantic::infer::infer_expr_type(receiver, &ctx);
                if let Some(resolved) = crate::semantic::method::resolve(&receiver_type, method)
                    && let Some(signature) = crate::grammar::builtin_signature(resolved.function)
                {
                    let labels = signature.param_labels();
                    let written: Vec<String> = labels.iter().skip(1).cloned().collect();
                    return Some(SignatureHelp {
                        signatures: vec![SignatureInformation {
                            label: format!(".{method}({})", written.join(", ")),
                            documentation: crate::grammar::builtin_function(resolved.function).map(
                                |curated| {
                                    Documentation::MarkupContent(MarkupContent {
                                        kind: MarkupKind::Markdown,
                                        value: curated.summary.to_string(),
                                    })
                                },
                            ),
                            parameters: Some(
                                written
                                    .into_iter()
                                    .map(|label| ParameterInformation {
                                        label: ParameterLabel::Simple(label),
                                        documentation: None,
                                    })
                                    .collect(),
                            ),
                            active_parameter: Some(active_parameter),
                        }],
                        active_signature: Some(0),
                        active_parameter: Some(active_parameter),
                    });
                }
            }
        }

        if let Some(function) = model.functions.get(function_name) {
            return Some(SignatureHelp {
                signatures: vec![SignatureInformation {
                    label: function_signature_with_return(
                        function,
                        model.inferred_function_returns.get(function_name),
                    ),
                    documentation: function.comment.clone().map(|value| {
                        Documentation::MarkupContent(MarkupContent {
                            kind: MarkupKind::Markdown,
                            value,
                        })
                    }),
                    parameters: Some(
                        function
                            .params
                            .iter()
                            .map(|param| ParameterInformation {
                                label: ParameterLabel::Simple(param_label(param)),
                                documentation: None,
                            })
                            .collect(),
                    ),
                    active_parameter: Some(active_parameter),
                }],
                active_signature: Some(0),
                active_parameter: Some(active_parameter),
            });
        }

        // The generated catalogue supplies parameters for every builtin; the
        // curated table adds prose for the 79 that have it. Before this, help
        // came only from the curated table, so `math::clamp(` offered nothing.
        let signature = builtin_signature(function_name)?;
        Some(SignatureHelp {
            signatures: vec![builtin_signature_information(
                signature,
                builtin_function(function_name),
            )],
            active_signature: Some(0),
            active_parameter: Some(active_parameter),
        })
    }

    pub async fn code_action(&self, params: CodeActionParams) -> Option<CodeActionResponse> {
        let uri = params.text_document.uri;
        let (analysis, model, _) = self.snapshot_for_uri(&uri).await?;
        Some(model.code_actions(&uri, &analysis, &params.context.diagnostics))
    }

    pub async fn document_highlight(
        &self,
        params: DocumentHighlightParams,
    ) -> Vec<DocumentHighlight> {
        let uri = params.text_document_position_params.text_document.uri;
        let position = params.text_document_position_params.position;
        let Some((analysis, model, _)) = self.snapshot_for_uri(&uri).await else {
            return Vec::new();
        };
        let Some(token) = token_at(&analysis.text, &analysis.line_index, position) else {
            return Vec::new();
        };
        model
            .references_for_function(token.trim())
            .into_iter()
            .filter(|location| location.uri == uri)
            .map(|location| DocumentHighlight {
                range: location.range,
                kind: Some(DocumentHighlightKind::READ),
            })
            .collect()
    }

    /// Emit `parameter_name:` hints next to each argument of every
    /// custom function call in the requested viewport range. Builtin
    /// functions don't expose structured parameter names (their
    /// signatures are free-form strings), so they're skipped.
    pub async fn inlay_hint(&self, params: InlayHintParams) -> Vec<InlayHint> {
        let uri = params.text_document.uri;
        let Some((analysis, model, _)) = self.snapshot_for_uri(&uri).await else {
            return Vec::new();
        };

        let range_start = analysis
            .line_index
            .offset(&analysis.text, params.range.start);
        let range_end = analysis.line_index.offset(&analysis.text, params.range.end);

        crate::semantic::analyzer::collect_inlay_hints(
            analysis.tree.root_node(),
            &analysis.text,
            range_start,
            range_end,
            &model,
        )
    }

    pub async fn prepare_call_hierarchy(
        &self,
        params: CallHierarchyPrepareParams,
    ) -> Option<Vec<CallHierarchyItem>> {
        let uri = params.text_document_position_params.text_document.uri;
        let position = params.text_document_position_params.position;
        let (analysis, model, _) = self.snapshot_for_uri(&uri).await?;
        let token = token_at(&analysis.text, &analysis.line_index, position)?;
        let function = model.functions.get(token.trim())?;
        Some(vec![call_hierarchy_item(function)])
    }

    pub async fn incoming_calls(
        &self,
        params: CallHierarchyIncomingCallsParams,
    ) -> Vec<CallHierarchyIncomingCall> {
        let item = params.item;
        let state = self.state.read().await;
        let callers = state
            .model
            .function_callers
            .get(&item.name)
            .cloned()
            .unwrap_or_default();
        let mut calls = Vec::new();
        for caller_name in callers {
            if let Some(function) = state.model.functions.get(&caller_name) {
                calls.push(CallHierarchyIncomingCall {
                    from: call_hierarchy_item(function),
                    from_ranges: vec![function.selection_range],
                });
            }
        }
        calls
    }

    pub async fn outgoing_calls(
        &self,
        params: CallHierarchyOutgoingCallsParams,
    ) -> Vec<CallHierarchyOutgoingCall> {
        let item = params.item;
        let state = self.state.read().await;
        let Some(function) = state.model.functions.get(&item.name) else {
            return Vec::new();
        };
        let mut calls = Vec::new();
        for callee_name in &function.called_functions {
            if let Some(callee) = state.model.functions.get(callee_name) {
                calls.push(CallHierarchyOutgoingCall {
                    to: call_hierarchy_item(callee),
                    from_ranges: vec![function.selection_range],
                });
            }
        }
        calls
    }

    pub async fn workspace_symbol(
        &self,
        params: WorkspaceSymbolParams,
    ) -> Option<WorkspaceSymbolResponse> {
        let state = self.state.read().await;
        Some(state.model.workspace_symbol_items(&params.query).into())
    }

    // ──────────────────────────────────────────────────────────────────
    // Internal helpers
    // ──────────────────────────────────────────────────────────────────

    async fn upsert_open_document(&self, uri: Uri, text: String, edit: Edit) {
        let (limit, debounce_ms) = {
            let state = self.state.read().await;
            (
                state.settings.analysis.max_syntax_diagnostics,
                state.settings.analysis.diagnostic_debounce_ms,
            )
        };

        // Record the version first, so a later edit can tell that this one is
        // superseded even while this call is still waiting or analysing.
        if let Edit::Changed(version) = edit {
            let mut state = self.state.write().await;
            if state
                .document_versions
                .get(&uri)
                .is_some_and(|newest| *newest > version)
            {
                // A newer edit already arrived. Its own call does the work.
                return;
            }
            state.document_versions.insert(uri.clone(), version);
        }

        // Let a burst of keystrokes settle. `didOpen` skips this entirely.
        if let Edit::Changed(version) = edit
            && debounce_ms > 0
        {
            runtime::time::sleep(std::time::Duration::from_millis(debounce_ms)).await;
            if self.superseded(&uri, version).await {
                return;
            }
        }

        // Parsing and extraction are CPU-bound and now the most frequent work
        // the server does, so they must not run on a thread that is also
        // serving requests.
        let Some(analysis) = analyze_off_reactor(uri.clone(), text, limit).await else {
            return;
        };

        // The text may have moved on while the analysis ran.
        if let Edit::Changed(version) = edit
            && self.superseded(&uri, version).await
        {
            return;
        }

        {
            let mut state = self.state.write().await;
            state.open_documents.insert(uri.clone(), Arc::new(analysis));
        }
        self.recompute_model().await;
        self.publish_diagnostics_for_uri(&uri).await;
    }

    /// True when a newer `didChange` for `uri` has arrived since `version`.
    async fn superseded(&self, uri: &Uri, version: i32) -> bool {
        self.state
            .read()
            .await
            .document_versions
            .get(uri)
            .is_some_and(|newest| *newest > version)
    }

    /// Re-run the analysis of every open document under a new syntax cap.
    ///
    /// The text is taken from the stored analysis rather than re-read from
    /// disk: an open buffer may be dirty, and its `DocumentAnalysis.text` is
    /// the exact content the client last sent.
    async fn reanalyze_open_documents(&self, limit: usize) {
        let open_documents = self.state.read().await.open_documents.clone();
        let reanalyzed: Vec<(Uri, Arc<DocumentAnalysis>)> = open_documents
            .iter()
            .filter_map(|(uri, analysis)| {
                analyze_document_with_limit(uri.clone(), &analysis.text, SymbolOrigin::Local, limit)
                    .map(|fresh| (uri.clone(), Arc::new(fresh)))
            })
            .collect();

        let mut state = self.state.write().await;
        for (uri, analysis) in reanalyzed {
            state.open_documents.insert(uri, analysis);
        }
    }

    async fn sync_saved_document_from_disk(&self, uri: &Uri) {
        let Some(text) = self.workspace_loader.read_document(uri).await else {
            return;
        };
        let Some(analysis) = analyze_document(uri.clone(), &text, SymbolOrigin::Local) else {
            return;
        };
        let mut state = self.state.write().await;
        let mut workspace = (*state.saved_workspace).clone();
        workspace.documents.insert(uri.clone(), Arc::new(analysis));
        state.saved_workspace = Arc::new(workspace);
    }

    async fn recompute_model(&self) {
        let (workspace, live_metadata) = {
            let state = self.state.read().await;
            (
                merged_workspace(&state.saved_workspace, &state.open_documents),
                Arc::clone(&state.live_metadata),
            )
        };

        let model = Arc::new(MergedSemanticModel::build(&workspace, &live_metadata));
        let mut state = self.state.write().await;
        state.model = model;
    }

    async fn refresh_remote_metadata_if_needed(&self) {
        // Under the config lock so a concurrent apply_settings can't
        // interleave its fetch/report/store with this one (which
        // would let a stale "clean" fetch overwrite a fresh failure
        // report, or vice versa).
        let _guard = self.config_lock.lock().await;
        let settings = {
            let state = self.state.read().await;
            Arc::clone(&state.settings)
        };
        let live_metadata = Arc::new(self.metadata_provider.fetch(&settings).await);
        self.report_metadata_errors(&live_metadata).await;
        {
            let mut state = self.state.write().await;
            state.live_metadata = live_metadata;
        }
        self.recompute_model().await;
    }

    /// Forward live-metadata fetch failures (bad endpoint, auth
    /// failure, timeout, per-table query errors) to the IDE. Before
    /// this existed, `LiveMetadataSnapshot.errors` was collected and
    /// then dropped — a misconfigured connection looked identical to
    /// an empty schema.
    ///
    /// Each *distinct* failure set toasts once (`window/showMessage`)
    /// with full details in the log, and recovery back to a clean
    /// fetch logs an INFO line. The state lock is released before any
    /// notifier call — the wasm executor is single-threaded and a
    /// held lock across an await can deadlock it.
    async fn report_metadata_errors(&self, snapshot: &LiveMetadataSnapshot) {
        let mut signature = snapshot.errors.clone();
        signature.sort();

        let previous = {
            let mut state = self.state.write().await;
            state.last_metadata_errors.replace(signature.clone())
        };

        if previous.as_ref() == Some(&signature) {
            return;
        }

        if signature.is_empty() {
            if previous.is_some_and(|previous| !previous.is_empty()) {
                self.notifier
                    .log_message(
                        MessageType::INFO,
                        "SurrealQL: live schema metadata is available again".to_string(),
                    )
                    .await;
            }
            return;
        }

        for error in &snapshot.errors {
            self.notifier
                .log_message(MessageType::WARNING, format!("SurrealQL metadata: {error}"))
                .await;
        }

        let first = &snapshot.errors[0];
        let message = match snapshot.errors.len() {
            1 => format!("SurrealQL: live schema metadata unavailable: {first}"),
            more => format!(
                "SurrealQL: live schema metadata unavailable: {first} (+{} more — see the log)",
                more - 1
            ),
        };
        self.notifier
            .show_message(MessageType::WARNING, message)
            .await;
    }

    /// Summarize what a fresh workspace walk had to skip (unreadable
    /// entries, oversized files, the file-count cap) so silent
    /// truncation doesn't masquerade as full coverage.
    async fn report_scan_stats(&self, workspace: &WorkspaceIndex) {
        let stats = workspace.scan_stats;
        if stats == Default::default() {
            return;
        }

        let mut parts = Vec::new();
        if stats.walk_errors > 0 {
            parts.push(format!(
                "{} unreadable directory entries",
                stats.walk_errors
            ));
        }
        if stats.skipped_oversize > 0 {
            parts.push(format!("{} oversized files", stats.skipped_oversize));
        }
        if stats.skipped_unreadable > 0 {
            parts.push(format!("{} unreadable files", stats.skipped_unreadable));
        }
        if stats.file_cap_hit {
            parts.push("the workspace file limit was reached".to_string());
        }
        self.notifier
            .log_message(
                MessageType::WARNING,
                format!("SurrealQL: workspace scan skipped {}.", parts.join(", ")),
            )
            .await;

        if stats.file_cap_hit {
            self.notifier
                .show_message(
                    MessageType::WARNING,
                    "SurrealQL: the workspace contains more .surql files than the indexing \
                     limit; some files were not indexed."
                        .to_string(),
                )
                .await;
        }
    }

    /// Republish diagnostics for every open editor buffer after the
    /// merged model changes without a document edit (e.g. live
    /// metadata arriving from the host).
    async fn republish_open_diagnostics(&self) {
        let uris = {
            let state = self.state.read().await;
            state.open_documents.keys().cloned().collect::<Vec<_>>()
        };
        for uri in uris {
            self.publish_diagnostics_for_uri(&uri).await;
        }
    }

    async fn publish_diagnostics_for_uri(&self, uri: &Uri) {
        let (analysis, model, settings) = {
            let state = self.state.read().await;
            let analysis = state
                .open_documents
                .get(uri)
                .cloned()
                .or_else(|| state.saved_workspace.documents.get(uri).cloned());
            (
                analysis,
                Arc::clone(&state.model),
                Arc::clone(&state.settings),
            )
        };

        if let Some(analysis) = analysis {
            let diagnostics = diagnostics_for_document(&analysis, &model, &settings);
            self.notifier
                .publish_diagnostics(uri.clone(), diagnostics)
                .await;
        }
    }

    async fn snapshot_for_uri(
        &self,
        uri: &Uri,
    ) -> Option<(
        Arc<DocumentAnalysis>,
        Arc<MergedSemanticModel>,
        Arc<ServerSettings>,
    )> {
        let state = self.state.read().await;
        let analysis = state
            .open_documents
            .get(uri)
            .cloned()
            .or_else(|| state.saved_workspace.documents.get(uri).cloned())?;
        Some((
            analysis,
            Arc::clone(&state.model),
            Arc::clone(&state.settings),
        ))
    }
}

// ──────────────────────────────────────────────────────────────────────
// Free helpers
// ──────────────────────────────────────────────────────────────────────

/// The completion items for one closed-vocabulary statement-head slot.
///
/// Keyword order follows the engine's own parser arms rather than the
/// alphabet, because `INFO FOR ` reads better as `ROOT NAMESPACE NS …` than as
/// `DATABASE DB INDEX …`. The `sort_text` preserves that order and keeps every
/// The tables whose columns are in scope at `position`.
///
/// A `tbl.` qualifier names its own table. Otherwise it is the statement's
/// target: from the query fact when the document parses, and from the raw text
/// when it does not. That second half matters more than it looks — the query
/// facts describe the document *as it stands*, and a projection the author has
/// not filled in yet does not parse. `SELECT  FROM person` yields an `ERROR`
/// node and no fact at all, so the one position where the column list is most
/// wanted was the one position with no table to draw it from.
///
/// Shared by completion and hover so the two cannot disagree about which table
/// a bare column name belongs to.
fn field_tables_at(
    analysis: &DocumentAnalysis,
    position: Position,
    qualifier: Option<&str>,
) -> Vec<String> {
    let tables = field_completion_tables(active_query_fact(analysis, position), qualifier);
    if !tables.is_empty() || qualifier.is_some() {
        return tables;
    }
    statement_target_in_text(&analysis.text, &analysis.line_index, position)
        .into_iter()
        .collect()
}

/// The span of the `prefix_len` bytes immediately before the cursor.
///
/// That run is the partial name the author has typed, so it is what a chosen
/// completion replaces.
fn replaced_range(analysis: &DocumentAnalysis, position: Position, prefix_len: usize) -> Range {
    let cursor = analysis.line_index.offset(&analysis.text, position);
    let start = cursor.saturating_sub(prefix_len);
    analysis.line_index.range(&analysis.text, start, cursor)
}

/// Pin every item to replace exactly `range`.
///
/// Without a `textEdit` the client picks the range itself, from its own idea of
/// where the current word starts — which is only safe while the character
/// before the cursor is one every client agrees ends a word.
fn with_replace_range(items: Vec<CompletionItem>, range: Range) -> Vec<CompletionItem> {
    items
        .into_iter()
        .map(|mut item| {
            let new_text = item
                .insert_text
                .clone()
                .unwrap_or_else(|| item.label.clone());
            item.text_edit = Some(CompletionTextEdit::Edit(TextEdit { range, new_text }));
            // With an explicit range the client filters the range's text
            // against this rather than against a word it scanned for itself.
            item.filter_text = Some(item.label.clone());
            item
        })
        .collect()
}

/// Rank the head-slot keywords in the order the engine documents them, each
/// keyword above the table names, which sort under `0-{priority}-{name}` with
/// a priority of at least 1 (`crate::semantic::model`).
fn head_slot_items(
    slot: SlotYield,
    prefix: &str,
    model: &MergedSemanticModel,
    active_context: Option<&AuthContext>,
) -> Vec<CompletionItem> {
    // Analyzer names come from the model rather than from a keyword list.
    if slot == SlotYield::Analyzers {
        return model.analyzer_completion_items(prefix);
    }

    let (keywords, with_tables) = match slot {
        SlotYield::Keywords(list) => (list, false),
        SlotYield::KeywordsAndTables(list) => (list, true),
        SlotYield::Tables => (&[] as &[&str], true),
        SlotYield::Analyzers => unreachable!("handled above"),
        // The caller must not reach this arm: `Expression` means "keep the
        // list you already build".
        SlotYield::Expression => return Vec::new(),
    };

    let upper = prefix.to_ascii_uppercase();
    let mut items: Vec<CompletionItem> = keywords
        .iter()
        .enumerate()
        .filter(|(_, keyword)| upper.is_empty() || keyword.starts_with(&upper))
        .map(|(index, keyword)| CompletionItem {
            label: (*keyword).to_string(),
            kind: Some(CompletionItemKind::KEYWORD),
            detail: Some("SurrealQL keyword".to_string()),
            insert_text: Some((*keyword).to_string()),
            sort_text: Some(format!("0-0-{index:02}-{keyword}")),
            ..CompletionItem::default()
        })
        .collect();

    if with_tables {
        items.extend(model.table_completion_items(prefix, active_context));
    }
    items
}

fn resolve_workspace_folders(params: &InitializeParams) -> Vec<PathBuf> {
    params
        .workspace_folders
        .as_ref()
        .map(|folders| {
            folders
                .iter()
                .filter_map(|folder| folder.uri.to_file_path().map(|p| p.into_owned()))
                .collect()
        })
        .unwrap_or_default()
}

fn call_hierarchy_item(function: &FunctionDef) -> CallHierarchyItem {
    CallHierarchyItem {
        name: function.name.clone(),
        kind: SymbolKind::FUNCTION,
        tags: None,
        detail: function.comment.clone(),
        uri: function.location.uri.clone(),
        range: function.location.range,
        selection_range: function.selection_range,
        data: None,
    }
}

/// Signature help for a builtin.
///
/// Parameters come from the generated catalogue, so every function has them.
/// They used to be recovered by splitting the curated signature string on `(`
/// and `,`, which broke on a parameter type containing a comma
/// (`array<string, 5>`) and covered only the 79 curated entries.
///
/// `curated` supplies the summary and documentation link when the function is
/// one of those 79.
fn builtin_signature_information(
    signature: &BuiltinSignature,
    curated: Option<&'static BuiltinFunction>,
) -> SignatureInformation {
    let parameters = signature
        .param_labels()
        .into_iter()
        .map(|label| ParameterInformation {
            label: ParameterLabel::Simple(label),
            documentation: None,
        })
        .collect();

    SignatureInformation {
        // Prefer the curated signature string: it is written for a reader, with
        // parameter names chosen for the documentation rather than taken from
        // the implementation's bindings. The generated fallback now carries a
        // return type too, read from the engine's registry.
        label: curated
            .map(|function| function.signature.to_string())
            .or_else(|| signature.display_signature())
            .unwrap_or_else(|| signature.generated.name.to_string()),
        documentation: curated.map(|function| {
            Documentation::MarkupContent(MarkupContent {
                kind: MarkupKind::Markdown,
                value: format!(
                    "{}\n\n[Docs]({})",
                    function.summary, function.documentation_url
                ),
            })
        }),
        parameters: Some(parameters),
        active_parameter: None,
    }
}

/// Why a buffer is being (re)analysed.
///
/// `didOpen` and `didChange` differ in two ways that both matter here: an open
/// is never delayed, and it cannot be superseded because there is no earlier
/// version of the same document in flight.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Edit {
    Opened,
    Changed(i32),
}

/// Run [`analyze_document_with_limit`] without occupying a thread that serves
/// requests.
///
/// On native this hands the work to tokio's blocking pool, so a hover or
/// completion arriving mid-keystroke is not queued behind a reparse. The
/// workspace walk already did this (see
/// [`crate::native::workspace_fs::FilesystemWorkspaceLoader::load`]); the
/// per-edit path did not, and it is the far more frequent one.
///
/// On `wasm32` it runs inline. `tokio_with_wasm` would move it to a web worker,
/// which means shipping the module to that worker and a serialisation hop for
/// every edit — a change to how the browser build works that nothing here can
/// test, since CI does not exercise the wasm JS surface. Inline keeps the
/// browser behaviour exactly as it was.
#[cfg(not(target_arch = "wasm32"))]
async fn analyze_off_reactor(uri: Uri, text: String, limit: usize) -> Option<DocumentAnalysis> {
    runtime::task::spawn_blocking(move || {
        analyze_document_with_limit(uri, text, SymbolOrigin::Local, limit)
    })
    .await
    .ok()
    .flatten()
}

#[cfg(target_arch = "wasm32")]
async fn analyze_off_reactor(uri: Uri, text: String, limit: usize) -> Option<DocumentAnalysis> {
    analyze_document_with_limit(uri, text, SymbolOrigin::Local, limit)
}

/// The complete diagnostic set for one document: the syntax pass, then the
/// semantic and type passes, then the schema-mode filter over both.
///
/// The filter has to run last because `unknown-type` comes from the syntax
/// pass, which reads a single document and cannot see the merged model — see
/// [`MergedSemanticModel::apply_schemaless_policy`].
///
/// `model` and `settings` are parameters rather than state reads so callers
/// already holding a snapshot do not re-acquire the lock per document, and
/// cannot race a concurrent `recompute_model`.
fn diagnostics_for_document(
    analysis: &DocumentAnalysis,
    model: &MergedSemanticModel,
    settings: &ServerSettings,
) -> Vec<Diagnostic> {
    let mut diagnostics = analysis.syntax_diagnostics.clone();
    diagnostics.extend(model.semantic_diagnostics(analysis, settings));
    model.apply_schemaless_policy(&mut diagnostics, settings);
    diagnostics
}

/// Extension methods used by [`LanguageServerCore::reload_from_client_configuration`]
/// to merge incoming `workspace/configuration` snapshots with the
/// initial settings (which usually carry the connection details from
/// `initializationOptions`).
trait SettingsMergeExt {
    fn merge_with_env_if_missing(self, fallback: ServerSettings) -> ServerSettings;
}

impl SettingsMergeExt for ServerSettings {
    fn merge_with_env_if_missing(mut self, fallback: ServerSettings) -> ServerSettings {
        if self.connection.endpoint.is_none() {
            self.connection.endpoint = fallback.connection.endpoint;
        }
        if self.connection.namespace.is_none() {
            self.connection.namespace = fallback.connection.namespace;
        }
        if self.connection.database.is_none() {
            self.connection.database = fallback.connection.database;
        }
        if self.connection.username.is_none() {
            self.connection.username = fallback.connection.username;
        }
        if self.connection.password.is_none() {
            self.connection.password = fallback.connection.password;
        }
        if self.connection.token.is_none() {
            self.connection.token = fallback.connection.token;
        }
        if self.active_auth_context.is_none() {
            self.active_auth_context = fallback.active_auth_context;
        }
        if self.auth_contexts.is_empty() {
            self.auth_contexts = fallback.auth_contexts;
        }
        let default_mode = crate::config::MetadataSettings::default().mode;
        if self.metadata.mode == default_mode && fallback.metadata.mode != default_mode {
            self.metadata.mode = fallback.metadata.mode;
        }
        self
    }
}