surrealql-language-server 0.3.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
//! End-to-end tests driving [`LanguageServerCore`] through its public
//! API with recording mocks — the same pipeline real clients exercise
//! (didOpen → analysis → merged model → published diagnostics).

mod common;

use common::{core_with, uri};
use serde_json::json;
use tower_lsp_server::ls_types::{
    DiagnosticSeverity, DidChangeConfigurationParams, DidCloseTextDocumentParams,
    DidOpenTextDocumentParams, InitializeParams, MessageType, NumberOrString,
    TextDocumentIdentifier, TextDocumentItem,
};

fn text_document(path: &str, text: &str) -> TextDocumentItem {
    TextDocumentItem {
        uri: uri(path),
        language_id: "surrealql".to_string(),
        version: 1,
        text: text.to_string(),
    }
}

async fn open(core: &common::TestCore, path: &str, text: &str) {
    core.did_open(DidOpenTextDocumentParams {
        text_document: text_document(path, text),
    })
    .await;
}

#[tokio::test]
async fn did_open_publishes_syntax_diagnostics_for_broken_document() {
    let (core, notifier, _) = core_with(Default::default(), Default::default());

    open(&core, "bad.surql", "DEFINE TABLE @@@invalid@@@;").await;

    let diagnostics = notifier
        .last_published_for(&uri("bad.surql"))
        .expect("diagnostics published for the opened document");
    assert!(
        !diagnostics.is_empty(),
        "broken surql must produce diagnostics"
    );
    for diagnostic in &diagnostics {
        assert_eq!(diagnostic.severity, Some(DiagnosticSeverity::ERROR));
        assert_eq!(
            diagnostic.code,
            Some(NumberOrString::String("parse".to_string()))
        );
        assert_eq!(
            diagnostic.source.as_deref(),
            Some("surreal-language-server")
        );
    }
}

#[tokio::test]
async fn did_open_clean_document_publishes_empty_diagnostics() {
    let (core, notifier, _) = core_with(Default::default(), Default::default());

    open(
        &core,
        "clean.surql",
        "DEFINE TABLE person SCHEMAFULL PERMISSIONS FOR select FULL;\n\
         DEFINE FIELD name ON TABLE person TYPE string;",
    )
    .await;

    let diagnostics = notifier
        .last_published_for(&uri("clean.surql"))
        .expect("diagnostics published for the opened document");
    assert_eq!(
        diagnostics,
        Vec::new(),
        "clean document must publish an empty set"
    );
}

#[tokio::test]
async fn did_close_clears_diagnostics() {
    let (core, notifier, _) = core_with(Default::default(), Default::default());

    open(&core, "bad.surql", "DEFINE TABLE @@@invalid@@@;").await;
    core.did_close(DidCloseTextDocumentParams {
        text_document: TextDocumentIdentifier {
            uri: uri("bad.surql"),
        },
    })
    .await;

    let diagnostics = notifier
        .last_published_for(&uri("bad.surql"))
        .expect("close must publish");
    assert_eq!(diagnostics, Vec::new(), "close must clear diagnostics");
}

#[tokio::test]
async fn initialized_pulls_configuration_and_logs_ready() {
    let (core, notifier, metadata) = core_with(Default::default(), Default::default());
    *notifier.configuration.lock().unwrap() = Some(json!({
        "surrealql": { "connection": { "endpoint": "ws://from-pull:8000/rpc" } }
    }));

    core.initialize(InitializeParams::default()).await;
    core.initialized().await;

    let logs = notifier.logs();
    assert!(
        logs.iter().any(|(level, message)| {
            *level == MessageType::INFO && message == "SurrealQL semantic language server ready"
        }),
        "ready log missing: {logs:?}"
    );
    let settings = metadata
        .last_settings
        .lock()
        .unwrap()
        .clone()
        .expect("initialized must trigger a metadata fetch");
    assert_eq!(
        settings.connection.endpoint.as_deref(),
        Some("ws://from-pull:8000/rpc"),
        "pulled configuration must reach the metadata provider"
    );
}

#[tokio::test]
async fn did_change_configuration_preserves_connection_from_initialize() {
    let (core, _notifier, metadata) = core_with(Default::default(), Default::default());

    core.initialize(InitializeParams {
        initialization_options: Some(json!({
            "surrealql": { "connection": { "endpoint": "ws://from-init:8000/rpc" } }
        })),
        ..InitializeParams::default()
    })
    .await;

    // A partial payload that says nothing about the connection.
    core.did_change_configuration(DidChangeConfigurationParams {
        settings: json!({ "surrealql": { "metadata": { "refreshOnSave": false } } }),
    })
    .await;

    let settings = metadata
        .last_settings
        .lock()
        .unwrap()
        .clone()
        .expect("configuration change must trigger a metadata fetch");
    // A partial payload must merge over the in-flight settings, not
    // replace them: the endpoint from initializationOptions survives
    // while the pushed metadata flag takes effect.
    assert_eq!(
        settings.connection.endpoint.as_deref(),
        Some("ws://from-init:8000/rpc")
    );
    assert!(!settings.metadata.refresh_on_save);
}

#[tokio::test]
async fn metadata_errors_surface_once_and_log_recovery() {
    use surrealql_language_server::semantic::types::LiveMetadataSnapshot;

    let failing = LiveMetadataSnapshot {
        documents: Default::default(),
        errors: vec![
            "failed to connect to SurrealDB: connection refused".to_string(),
            "INFO FOR DB returned an error: not permitted".to_string(),
        ],
    };
    let (core, notifier, metadata) = core_with(Default::default(), failing.clone());

    core.initialize(InitializeParams::default()).await;
    core.initialized().await;

    let shows = notifier.shows();
    assert_eq!(
        shows.len(),
        1,
        "one toast per distinct failure set: {shows:?}"
    );
    assert_eq!(shows[0].0, MessageType::WARNING);
    assert!(shows[0].1.contains("live schema metadata unavailable"));
    assert!(shows[0].1.contains("connection refused"));
    assert!(shows[0].1.contains("+1 more"));
    let warning_logs: Vec<_> = notifier
        .logs()
        .into_iter()
        .filter(|(_, message)| message.starts_with("SurrealQL metadata:"))
        .collect();
    assert_eq!(warning_logs.len(), 2, "each error gets its own log line");

    // Same failure set again (e.g. a save with refreshOnSave): no new toast.
    core.did_change_configuration(DidChangeConfigurationParams {
        settings: json!({ "surrealql": {} }),
    })
    .await;
    assert_eq!(
        notifier.shows().len(),
        1,
        "unchanged failures must not re-toast"
    );

    // Recovery: fetch comes back clean → INFO log, still no new toast.
    *metadata.snapshot.lock().unwrap() = LiveMetadataSnapshot::default();
    core.did_change_configuration(DidChangeConfigurationParams {
        settings: json!({ "surrealql": {} }),
    })
    .await;
    assert_eq!(notifier.shows().len(), 1);
    assert!(
        notifier.logs().iter().any(|(level, message)| {
            *level == MessageType::INFO && message.contains("available again")
        }),
        "recovery must be logged"
    );
}

#[tokio::test]
async fn malformed_settings_payload_logs_a_warning_and_keeps_going() {
    let (core, notifier, _) = core_with(Default::default(), Default::default());

    core.initialize(InitializeParams::default()).await;
    core.did_change_configuration(DidChangeConfigurationParams {
        // endpoint must be a string — this typo'd payload used to be
        // silently replaced with all-default settings.
        settings: json!({ "surrealql": { "connection": { "endpoint": 42 } } }),
    })
    .await;

    assert!(
        notifier.logs().iter().any(|(level, message)| {
            *level == MessageType::WARNING
                && message.starts_with("SurrealQL settings:")
                && message.contains("invalid `surrealql` settings")
        }),
        "malformed settings must be reported: {:?}",
        notifier.logs()
    );
}

/// The audit's headline finding: a typo'd table name used to be
/// auto-inferred by the very statement that misused it, so the
/// unknown-table diagnostic and its quick fix were dead code in the
/// real pipeline. This drives the REAL flow (didOpen → analysis →
/// merged model → semantic diagnostics → code action) end to end.
#[tokio::test]
async fn typo_in_table_name_yields_did_you_mean_diagnostic_and_quick_fix() {
    use tower_lsp_server::ls_types::{CodeActionOrCommand, DiagnosticSeverity};

    let (core, notifier, _) = core_with(Default::default(), Default::default());
    let text = "DEFINE TABLE person SCHEMAFULL;\n\
                DEFINE FIELD email ON person TYPE string;\n\
                CREATE prson SET email = 'x';";
    open(&core, "typo.surql", text).await;

    let diagnostics = notifier
        .last_published_for(&uri("typo.surql"))
        .expect("diagnostics published");
    let unknown: Vec<_> = diagnostics
        .iter()
        .filter(|diagnostic| {
            diagnostic.code == Some(NumberOrString::String("unknown-table".to_string()))
        })
        .collect();
    assert_eq!(
        unknown.len(),
        1,
        "exactly one unknown-table diagnostic: {diagnostics:?}"
    );
    let diagnostic = unknown[0];
    assert_eq!(diagnostic.severity, Some(DiagnosticSeverity::WARNING));
    assert_eq!(
        diagnostic.message,
        "Unknown table `prson`. Did you mean `person`?"
    );
    // The squiggle covers only the `prson` token on line 2.
    assert_eq!(diagnostic.range.start.line, 2);
    assert_eq!(diagnostic.range.start.character, 7);
    assert_eq!(diagnostic.range.end.line, 2);
    assert_eq!(diagnostic.range.end.character, 12);
    // relatedInformation points at the DEFINE TABLE.
    let related = diagnostic
        .related_information
        .as_ref()
        .expect("related information present");
    assert_eq!(related[0].message, "`person` is defined here.");
    assert_eq!(related[0].location.range.start.line, 0);

    // And the quick fix replaces just the typo'd token.
    let code_actions = core
        .code_action(tower_lsp_server::ls_types::CodeActionParams {
            text_document: TextDocumentIdentifier {
                uri: uri("typo.surql"),
            },
            range: diagnostic.range,
            context: tower_lsp_server::ls_types::CodeActionContext {
                diagnostics: vec![diagnostic.clone()],
                ..Default::default()
            },
            work_done_progress_params: Default::default(),
            partial_result_params: Default::default(),
        })
        .await
        .expect("code actions");
    let quick_fix = code_actions
        .iter()
        .find_map(|action| match action {
            CodeActionOrCommand::CodeAction(action) if action.title.starts_with("Replace") => {
                Some(action)
            }
            _ => None,
        })
        .expect("quick fix offered");
    assert_eq!(quick_fix.title, "Replace `prson` with `person`");
}

#[tokio::test]
async fn usage_only_inferred_tables_stay_silent() {
    let (core, notifier, _) = core_with(Default::default(), Default::default());
    // No explicit schema anywhere: inference from usage is a feature,
    // not a typo — no unknown-table diagnostics.
    open(
        &core,
        "inferred.surql",
        "CREATE metrics_daily SET count = 1;\nSELECT * FROM metrics_daily;",
    )
    .await;

    let diagnostics = notifier
        .last_published_for(&uri("inferred.surql"))
        .expect("published");
    assert!(
        diagnostics.iter().all(|diagnostic| {
            diagnostic.code != Some(NumberOrString::String("unknown-table".to_string()))
        }),
        "usage-only inference must not be flagged: {diagnostics:?}"
    );
}

#[tokio::test]
async fn schemaless_tables_allow_ad_hoc_fields() {
    let (core, notifier, _) = core_with(Default::default(), Default::default());
    open(
        &core,
        "schemaless.surql",
        "DEFINE TABLE log SCHEMALESS;\nCREATE log SET anything_goes = true;",
    )
    .await;

    let diagnostics = notifier
        .last_published_for(&uri("schemaless.surql"))
        .expect("published");
    assert!(
        diagnostics.iter().all(|diagnostic| {
            diagnostic.code != Some(NumberOrString::String("unknown-field".to_string()))
        }),
        "SCHEMALESS tables must accept ad-hoc fields: {diagnostics:?}"
    );
}

#[tokio::test]
async fn typo_in_schemafull_field_yields_did_you_mean() {
    let (core, notifier, _) = core_with(Default::default(), Default::default());
    open(
        &core,
        "field-typo.surql",
        "DEFINE TABLE person SCHEMAFULL;\n\
         DEFINE FIELD email ON person TYPE string;\n\
         UPDATE person SET emial = 'x';",
    )
    .await;

    let diagnostics = notifier
        .last_published_for(&uri("field-typo.surql"))
        .expect("published");
    let unknown_field = diagnostics
        .iter()
        .find(|diagnostic| {
            diagnostic.code == Some(NumberOrString::String("unknown-field".to_string()))
        })
        .expect("unknown-field diagnostic must fire on a SCHEMAFULL table");
    assert_eq!(
        unknown_field.message,
        "Unknown field `person.emial`. Did you mean `email`?"
    );
    // Tight range over `emial` on line 2.
    assert_eq!(unknown_field.range.start.line, 2);
    assert_eq!(unknown_field.range.end.line, 2);
    assert!(unknown_field.range.end.character - unknown_field.range.start.character == 5);
}

#[tokio::test]
async fn parameter_targets_do_not_warn() {
    let (core, notifier, _) = core_with(Default::default(), Default::default());
    open(
        &core,
        "param-target.surql",
        "DELETE $record;\nSELECT * FROM $source;",
    )
    .await;

    let diagnostics = notifier
        .last_published_for(&uri("param-target.surql"))
        .expect("published");
    assert!(
        diagnostics.iter().all(|diagnostic| {
            diagnostic.code != Some(NumberOrString::String("dynamic-target".to_string()))
        }),
        "$param targets must not produce dynamic-target warnings: {diagnostics:?}"
    );
}

#[tokio::test]
async fn genuinely_opaque_targets_still_warn() {
    let (core, notifier, _) = core_with(Default::default(), Default::default());
    // A literal-number target is neither a table name, a $param, nor
    // an expression — the dynamic-target warning must still fire.
    open(&core, "opaque.surql", "UPDATE 42 SET x = 1;").await;

    let diagnostics = notifier
        .last_published_for(&uri("opaque.surql"))
        .expect("published");
    let warning = diagnostics
        .iter()
        .find(|diagnostic| {
            diagnostic.code == Some(NumberOrString::String("dynamic-target".to_string()))
        })
        .expect("dynamic-target warning must fire for opaque targets");
    assert_eq!(
        warning.severity,
        Some(tower_lsp_server::ls_types::DiagnosticSeverity::WARNING)
    );
    assert!(
        warning
            .message
            .contains("target could not be resolved statically")
    );
}

#[tokio::test]
async fn builtin_id_field_is_not_flagged_on_schemafull_tables() {
    let (core, notifier, _) = core_with(Default::default(), Default::default());
    open(
        &core,
        "builtin-id.surql",
        "DEFINE TABLE person SCHEMAFULL;\n\
         DEFINE FIELD name ON person TYPE string;\n\
         CREATE person SET id = 'john', name = 'John';",
    )
    .await;

    let diagnostics = notifier
        .last_published_for(&uri("builtin-id.surql"))
        .expect("published");
    assert!(
        diagnostics.iter().all(|diagnostic| {
            diagnostic.code != Some(NumberOrString::String("unknown-field".to_string()))
        }),
        "builtin `id` must not be flagged: {diagnostics:?}"
    );
}

#[tokio::test]
async fn relate_set_fields_are_not_checked_against_subject_tables() {
    let (core, notifier, _) = core_with(Default::default(), Default::default());
    open(
        &core,
        "relate.surql",
        "DEFINE TABLE person SCHEMAFULL;\n\
         DEFINE FIELD name ON person TYPE string;\n\
         DEFINE TABLE likes SCHEMAFULL;\n\
         DEFINE FIELD since ON likes TYPE datetime;\n\
         RELATE person:one->likes->person:two SET since = time::now();",
    )
    .await;

    let diagnostics = notifier
        .last_published_for(&uri("relate.surql"))
        .expect("published");
    assert!(
        diagnostics.iter().all(|diagnostic| {
            diagnostic.code != Some(NumberOrString::String("unknown-field".to_string()))
        }),
        "RELATE SET fields belong to the edge table and must not be checked \
         against the subject tables: {diagnostics:?}"
    );
}

/// PR #18 review: singular/plural sibling tables are a naming
/// convention, not typos — `orders` next to explicit `order` must not
/// warn (and must not offer a quick fix that rewrites the query
/// against a different real table).
#[tokio::test]
async fn sibling_singular_plural_tables_are_not_typos() {
    let (core, notifier, _) = core_with(Default::default(), Default::default());
    open(
        &core,
        "plural.surql",
        "DEFINE TABLE order SCHEMAFULL;\nCREATE orders SET total = 1;",
    )
    .await;

    let diagnostics = notifier
        .last_published_for(&uri("plural.surql"))
        .expect("published");
    assert!(
        diagnostics.iter().all(|diagnostic| {
            diagnostic.code != Some(NumberOrString::String("unknown-table".to_string()))
        }),
        "plural sibling of an explicit table must not be flagged: {diagnostics:?}"
    );
}

/// The plural guard must not swallow real typos of s-ending names:
/// `address` pluralises with `es`, so `addres` is a dropped letter,
/// not a singular sibling.
#[tokio::test]
async fn trailing_s_typo_of_s_ending_table_still_warns() {
    let (core, notifier, _) = core_with(Default::default(), Default::default());
    open(
        &core,
        "address.surql",
        "DEFINE TABLE address SCHEMAFULL;\nCREATE addres SET street = 'x';",
    )
    .await;

    let diagnostics = notifier
        .last_published_for(&uri("address.surql"))
        .expect("published");
    let unknown = diagnostics
        .iter()
        .find(|diagnostic| {
            diagnostic.code == Some(NumberOrString::String("unknown-table".to_string()))
        })
        .expect("dropped-letter typo of an s-ending table must still warn");
    assert!(unknown.message.contains("Did you mean `address`?"));
}

/// PR #18 review: a name used in several statements is a deliberate
/// (if undeclared) table. Trade-off documented here: the same typo
/// pasted twice also goes silent.
#[tokio::test]
async fn repeated_usage_of_inferred_table_is_not_a_typo() {
    let (core, notifier, _) = core_with(Default::default(), Default::default());
    open(
        &core,
        "repeated.surql",
        "DEFINE TABLE person SCHEMAFULL;\n\
         CREATE prson SET x = 1;\n\
         SELECT * FROM prson;",
    )
    .await;

    let diagnostics = notifier
        .last_published_for(&uri("repeated.surql"))
        .expect("published");
    assert!(
        diagnostics.iter().all(|diagnostic| {
            diagnostic.code != Some(NumberOrString::String("unknown-table".to_string()))
        }),
        "multi-use inferred names are deliberate tables: {diagnostics:?}"
    );
}

/// PR #18 review: when the DB connection is down, remote tables drop
/// out of the merged model and local near-misses would warn in bulk —
/// right when the metadata-unavailable toast already fires. Typo
/// detection must stand down while metadata is degraded.
#[tokio::test]
async fn typo_detection_suppressed_while_metadata_unavailable() {
    use surrealql_language_server::semantic::types::LiveMetadataSnapshot;

    let failing = LiveMetadataSnapshot {
        documents: Default::default(),
        errors: vec!["failed to connect to SurrealDB: connection refused".to_string()],
    };
    let (core, notifier, _) = core_with(Default::default(), failing);

    // The failing snapshot only reaches the model through a fetch —
    // drive the real initialize flow, not just did_open.
    core.initialize(InitializeParams::default()).await;
    core.initialized().await;
    open(
        &core,
        "degraded.surql",
        "DEFINE TABLE person SCHEMAFULL;\nCREATE prson SET x = 1;",
    )
    .await;

    let diagnostics = notifier
        .last_published_for(&uri("degraded.surql"))
        .expect("published");
    assert!(
        diagnostics.iter().all(|diagnostic| {
            diagnostic.code != Some(NumberOrString::String("unknown-table".to_string()))
        }),
        "typo detection must stand down while metadata is degraded: {diagnostics:?}"
    );
    assert!(
        notifier
            .shows()
            .iter()
            .any(|(_, message)| message.contains("live schema metadata unavailable")),
        "the outage itself is still reported"
    );
}

/// PR #18 review: a persistently bad configuration must not re-log
/// the same warnings on every configuration push.
#[tokio::test]
async fn settings_warnings_do_not_repeat() {
    let (core, notifier, _) = core_with(Default::default(), Default::default());
    core.initialize(InitializeParams::default()).await;

    let bad_payload = json!({ "surrealql": { "metadata": { "mode": "workspaceanddb" } } });
    core.did_change_configuration(DidChangeConfigurationParams {
        settings: bad_payload.clone(),
    })
    .await;
    core.did_change_configuration(DidChangeConfigurationParams {
        settings: bad_payload,
    })
    .await;

    let warning_count = notifier
        .logs()
        .iter()
        .filter(|(level, message)| {
            *level == MessageType::WARNING && message.starts_with("SurrealQL settings:")
        })
        .count();
    assert_eq!(
        warning_count,
        1,
        "identical warning sets must log once: {:?}",
        notifier.logs()
    );

    // A clean payload resolves the warnings — once.
    core.did_change_configuration(DidChangeConfigurationParams {
        settings: json!({ "surrealql": {} }),
    })
    .await;
    assert!(
        notifier.logs().iter().any(|(level, message)| {
            *level == MessageType::INFO && message.contains("previous warnings resolved")
        }),
        "recovery must be logged: {:?}",
        notifier.logs()
    );
}

/// A client with no `surrealql` workspace section answers the
/// configuration pull with `None` (unsupported) or JSON `null`
/// (VS Code / Neovim) — neither must reset the warning-dedup state
/// nor fire a spurious "resolved" line right after the
/// initializationOptions warnings were logged.
#[tokio::test]
async fn configless_pull_does_not_resolve_init_options_warnings() {
    for pulled in [None, Some(serde_json::Value::Null)] {
        let (core, notifier, _) = core_with(Default::default(), Default::default());
        *notifier.configuration.lock().unwrap() = pulled;

        core.initialize(InitializeParams {
            initialization_options: Some(json!({
                "surrealql": { "connection": { "endpint": "ws://x:8000/rpc" } }
            })),
            ..InitializeParams::default()
        })
        .await;
        core.initialized().await;

        let logs = notifier.logs();
        let warning_count = logs
            .iter()
            .filter(|(level, message)| {
                *level == MessageType::WARNING && message.contains("endpint")
            })
            .count();
        assert_eq!(warning_count, 1, "warning logged exactly once: {logs:?}");
        assert!(
            logs.iter()
                .all(|(_, message)| !message.contains("previous warnings resolved")),
            "a config-less pull must not fake a resolution: {logs:?}"
        );
    }
}

#[tokio::test]
async fn workspace_scan_stats_are_reported() {
    use surrealql_language_server::semantic::types::{WorkspaceIndex, WorkspaceScanStats};

    let workspace = WorkspaceIndex {
        documents: Default::default(),
        scan_stats: WorkspaceScanStats {
            walk_errors: 2,
            skipped_oversize: 1,
            skipped_unreadable: 0,
            file_cap_hit: true,
        },
    };
    let (core, notifier, _) = core_with(workspace, Default::default());

    core.initialize(InitializeParams::default()).await;
    core.initialized().await;

    let logs = notifier.logs();
    let summary = logs
        .iter()
        .find(|(level, message)| {
            *level == MessageType::WARNING && message.contains("workspace scan skipped")
        })
        .expect("scan summary log");
    assert!(summary.1.contains("2 unreadable directory entries"));
    assert!(summary.1.contains("1 oversized files"));
    assert!(summary.1.contains("file limit"));
    assert!(
        notifier
            .shows()
            .iter()
            .any(|(_, message)| message.contains("files were not indexed")),
        "hitting the file cap must toast"
    );
}

#[tokio::test]
async fn unknown_metadata_mode_warns_and_repairs_to_default() {
    let (core, notifier, metadata) = core_with(Default::default(), Default::default());

    core.initialize(InitializeParams::default()).await;
    core.did_change_configuration(DidChangeConfigurationParams {
        settings: json!({ "surrealql": { "metadata": { "mode": "workspaceanddb" } } }),
    })
    .await;

    assert!(
        notifier.logs().iter().any(|(level, message)| {
            *level == MessageType::WARNING && message.contains("unknown metadata.mode")
        }),
        "unknown mode must be reported: {:?}",
        notifier.logs()
    );
    let settings = metadata
        .last_settings
        .lock()
        .unwrap()
        .clone()
        .expect("fetch must run");
    assert_eq!(
        settings.metadata.mode, "workspace+db",
        "unknown mode must repair to the default instead of disabling all metadata"
    );
}