bynk-lsp 0.142.0

bynkc-lsp — the Language Server for the Bynk DSL.
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
//! Symbol lookups for hover and go-to-definition.
//!
//! Single-file lookups walk the parsed AST. Cross-file lookups (v1.1; LSP
//! spec §3.4 cross-file requirement) iterate the project's `.bynk` sources
//! to find a declaration in any unit the user might be referencing — used
//! when the open file lacks the symbol the user clicked on (typically
//! because the name was imported via `uses` or made available via
//! `consumes`).

use std::path::{Path, PathBuf};

use bynk_syntax::ast::*;
use bynk_syntax::lexer::tokenize;
use bynk_syntax::parser::parse_unit_with_recovery;
use bynk_syntax::span::Span;
use tower_lsp::lsp_types::Url;

/// Return the source span of the declaration named `name` in the given
/// source text. Returns `None` if no declaration matches.
pub fn find_declaration_span(source: &str, name: &str) -> Option<Span> {
    let tokens = tokenize(source).ok()?;
    let (unit, _errs) = parse_unit_with_recovery(&tokens, source);
    let unit = unit?;
    let items: &[CommonsItem] = match &unit {
        SourceUnit::Commons(c) => &c.items,
        SourceUnit::Context(c) => &c.items,
        SourceUnit::Adapter(a) => &a.items,
        SourceUnit::Suite(_) => &[],
    };
    for item in items {
        match item {
            CommonsItem::Type(t) if t.name.name == name => return Some(t.name.span),
            CommonsItem::Fn(f) if f.name.ident().name == name => return Some(f.name.ident().span),
            CommonsItem::Capability(c) if c.name.name == name => return Some(c.name.span),
            CommonsItem::Service(s) if s.name.name == name => return Some(s.name.span),
            CommonsItem::Agent(a) if a.name.name == name => return Some(a.name.span),
            CommonsItem::Provider(p) if p.provider_name.name == name => {
                return Some(p.provider_name.span);
            }
            _ => {}
        }
    }
    None
}

/// Build a Markdown summary of a named declaration suitable for an LSP
/// hover response. Returns `None` if no declaration matches.
pub fn describe_symbol(source: &str, name: &str) -> Option<String> {
    let tokens = tokenize(source).ok()?;
    let (unit, _errs) = parse_unit_with_recovery(&tokens, source);
    let unit = unit?;
    let items: &[CommonsItem] = match &unit {
        SourceUnit::Commons(c) => &c.items,
        SourceUnit::Context(c) => &c.items,
        SourceUnit::Adapter(a) => &a.items,
        SourceUnit::Suite(_) => &[],
    };
    for item in items {
        if let Some(summary) = describe_item(item, name) {
            return Some(summary);
        }
    }
    None
}

/// v0.121 (ADR 0156): the reserved-keyword doc for the token at `offset` in
/// `source`, if the cursor sits on one — matched by source text against
/// `bynk_syntax::keywords::KEYWORDS`, independent of the token's `TokenKind`
/// (unlike the identifier-only lexical hover fallback above). This is hover's
/// floor for the mechanical coverage test: every lowercase-initial keyword
/// gets at least this, even where `describe_symbol` has no richer path for it
/// (e.g. the testing-track clause keywords — `requires`/`ensures`/`suite`/…).
pub fn describe_keyword_at(source: &str, offset: usize) -> Option<&'static str> {
    let tokens = tokenize(source).ok()?;
    let word = tokens
        .iter()
        .find(|t| t.span.start <= offset && offset < t.span.end)
        .map(|t| &source[t.span.start..t.span.end])?;
    bynk_syntax::keywords::KEYWORDS
        .iter()
        .find(|k| k.word == word)
        .map(|k| k.meaning)
}

/// v0.137.0 (ADR 0161): hover for the `key`/`store` *contextual* keywords and
/// the agent state fields they introduce. Both are lexed as `Ident`s (not
/// reserved `KEYWORDS`), and the fields they declare are neither `let`/param
/// locals nor top-level declarations — so neither the keyword fallback nor the
/// `describe_symbol`/locals paths in the hover handler reach them. This closes
/// that gap: for the cursor on the `key`/`store` keyword *or* on the field name
/// it declares, render the field's signature (type, and a `store` field's
/// `@indexed`/`@bounded`/… annotations) followed by the contextual-keyword doc.
/// `None` when the cursor is not on an agent's `key`/`store` keyword or its
/// state-field name.
pub fn describe_agent_state_at(source: &str, offset: usize) -> Option<String> {
    let tokens = tokenize(source).ok()?;
    let (unit, _errs) = parse_unit_with_recovery(&tokens, source);
    let unit = unit?;
    let items: &[CommonsItem] = match &unit {
        SourceUnit::Commons(c) => &c.items,
        SourceUnit::Context(c) => &c.items,
        SourceUnit::Adapter(a) => &a.items,
        SourceUnit::Suite(_) => &[],
    };
    for item in items {
        let CommonsItem::Agent(a) = item else {
            continue;
        };
        // `key <name>: <type>` — the cursor on the field name, or on the `key`
        // keyword token immediately preceding it.
        let on_key_kw = preceding_ident_span(&tokens, source, a.key_name.span, "key")
            .is_some_and(|s| span_covers(s, offset));
        if on_key_kw || span_covers(a.key_name.span, offset) {
            let sig = format!("key {}: {}", a.key_name.name, type_ref_str(&a.key_type));
            return Some(render_state_hover(&sig, "key"));
        }
        // `store <name>: <kind> <annotations>` — the parser sets each field's
        // span to start at its `store` keyword, so the keyword span is derivable
        // without re-scanning.
        for f in &a.store_fields {
            let store_kw = Span {
                start: f.span.start,
                end: f.span.start + "store".len(),
            };
            let on_store_kw = source.get(store_kw.start..store_kw.end) == Some("store")
                && span_covers(store_kw, offset);
            if on_store_kw || span_covers(f.name.span, offset) {
                let mut sig = format!("store {}: {}", f.name.name, store_kind_str(&f.kind));
                for ann in &f.annotations {
                    sig.push(' ');
                    sig.push_str(&bynk_fmt::annotation_to_string(ann));
                }
                return Some(render_state_hover(&sig, "store"));
            }
        }
    }
    None
}

/// v0.140 (ADR 0163): hover for a handler-position annotation (`@cache`). Handler
/// annotations are not symbols and declare no local, so they miss both the
/// `describe_symbol` and locals paths — this closes the gap. For the cursor
/// anywhere within a handler's `@cache( … )` annotation, render the formatted
/// annotation followed by a prose description of `@cache` and its fields. `None`
/// when the cursor is not inside a handler annotation.
pub fn describe_handler_annotation_at(source: &str, offset: usize) -> Option<String> {
    let tokens = tokenize(source).ok()?;
    let (unit, _errs) = parse_unit_with_recovery(&tokens, source);
    let unit = unit?;
    let items: &[CommonsItem] = match &unit {
        SourceUnit::Commons(c) => &c.items,
        SourceUnit::Context(c) => &c.items,
        SourceUnit::Adapter(a) => &a.items,
        SourceUnit::Suite(_) => &[],
    };
    for item in items {
        let handlers: &[Handler] = match item {
            CommonsItem::Service(s) => &s.handlers,
            CommonsItem::Agent(a) => &a.handlers,
            _ => continue,
        };
        for h in handlers {
            for ann in &h.annotations {
                if span_covers(ann.span, offset) {
                    return Some(render_handler_annotation_hover(ann));
                }
            }
        }
    }
    None
}

/// v0.140 (ADR 0163): the spans to classify as `decorator` semantic tokens — each
/// handler annotation's `@name` (the `@` through the name) and its argument labels
/// (`maxAge:`, `scope:`). Parsed from `source`; empty when it carries no handler
/// annotations. Feeds the semantic-tokens producer, which is otherwise a
/// parse-free index read, so the parse lives here beside the hover parse.
pub fn handler_annotation_token_spans(source: &str) -> Vec<Span> {
    let Ok(tokens) = tokenize(source) else {
        return Vec::new();
    };
    let (unit, _errs) = parse_unit_with_recovery(&tokens, source);
    let Some(unit) = unit else {
        return Vec::new();
    };
    let items: &[CommonsItem] = match &unit {
        SourceUnit::Commons(c) => &c.items,
        SourceUnit::Context(c) => &c.items,
        SourceUnit::Adapter(a) => &a.items,
        SourceUnit::Suite(_) => &[],
    };
    let mut spans = Vec::new();
    for item in items {
        let handlers: &[Handler] = match item {
            CommonsItem::Service(s) => &s.handlers,
            CommonsItem::Agent(a) => &a.handlers,
            _ => continue,
        };
        for h in handlers {
            for ann in &h.annotations {
                // The `@name` — from the annotation's leading `@` through its name.
                spans.push(Span {
                    start: ann.span.start,
                    end: ann.name.span.end,
                });
                // Each argument label (`maxAge:`, `scope:`).
                for arg in &ann.args {
                    if let Some(label) = &arg.label {
                        spans.push(label.span);
                    }
                }
            }
        }
    }
    spans
}

/// The formatted annotation in a code block, plus a prose description for the
/// closed handler-annotation set. `@cache` and `@limit` (v0.142) carry prose; any
/// other name (a typo the checker will flag) still hovers as its formatted form so
/// the surface is never silent.
fn render_handler_annotation_hover(ann: &Annotation) -> String {
    let sig = bynk_fmt::annotation_to_string(ann);
    if ann.name.name == "cache" {
        return format!(
            "```bynk\n{sig}\n```\n\n\
             **`@cache`** — cache this `GET` read. Every eligible `GET` already carries a \
             synthesised weak `ETag` and is answered `304 Not Modified` on a matching \
             `If-None-Match`; `@cache` adds a `Cache-Control` freshness window on top.\n\n\
             - **`maxAge`** — the freshness window, a `Duration` (e.g. `5.minutes`), lowered to \
             `Cache-Control: max-age`.\n\
             - **`scope`** — `public` or `private` (default `private`; a shared cache stores the \
             response only when `public`)."
        );
    }
    // v0.142 (ADR 0165): `@limit` caps the request body size on a write route.
    if ann.name.name == "limit" {
        return format!(
            "```bynk\n{sig}\n```\n\n\
             **`@limit`** — cap the request body size on this `POST`/`PUT`/`PATCH` route. A \
             request whose body exceeds the `maxBody` byte ceiling is answered `413 Payload Too \
             Large`, synthesised before the body is read.\n\n\
             - **`maxBody`** — the maximum request body size in bytes, a positive `Int`."
        );
    }
    format!("```bynk\n{sig}\n```")
}

/// True when `offset` falls within `span` (half-open, as hover offsets are).
fn span_covers(span: Span, offset: usize) -> bool {
    span.start <= offset && offset < span.end
}

/// The span of the token immediately preceding the token that begins at
/// `name_span`, if that preceding token's source text is exactly `kw` — used to
/// locate a contextual keyword (`key`) that the AST records only by its effect,
/// not with a span of its own.
fn preceding_ident_span(
    tokens: &[bynk_syntax::lexer::Token],
    source: &str,
    name_span: Span,
    kw: &str,
) -> Option<Span> {
    let idx = tokens
        .iter()
        .position(|t| t.span.start == name_span.start)?;
    let prev = tokens.get(idx.checked_sub(1)?)?;
    (source.get(prev.span.start..prev.span.end) == Some(kw)).then_some(prev.span)
}

/// A code-block field signature followed by the contextual keyword's one-line
/// doc from [`bynk_syntax::keywords::CONTEXTUAL_KEYWORDS`].
fn render_state_hover(sig: &str, contextual_kw: &str) -> String {
    let doc = bynk_syntax::keywords::CONTEXTUAL_KEYWORDS
        .iter()
        .find(|k| k.word == contextual_kw)
        .map(|k| k.meaning)
        .unwrap_or_default();
    format!("```bynk\n{sig}\n```\n\n{doc}")
}

/// v0.122 (editor-currency slice 1): a hover summary for `self` under the
/// cursor — `self: <Type>`. `self` is a reserved keyword (never an `Ident`, so
/// it does not flow through `locals_nav`), but a `self` *use* is a typed
/// expression, so its type is in `expr_types` at the token's span. For a method
/// the type is the receiver's name; for an agent handler the checker gives
/// `self` a synthetic record type `__<Agent>Self` (to resolve `self.<key>`),
/// which is un-synthesised here to `<Agent>`. `None` when the cursor is not on
/// the `self` keyword or its type is unknown (a broken buffer — `expr_types` is
/// clean-file-only, so this degrades to the keyword doc, never a wrong type).
pub fn describe_self_at(
    text: &str,
    offset: usize,
    expr_types: &[(Span, bynk_check::checker::Ty)],
) -> Option<String> {
    let tokens = tokenize(text).ok()?;
    let on_self = tokens.iter().any(|t| {
        t.span.start <= offset && offset < t.span.end && &text[t.span.start..t.span.end] == "self"
    });
    if !on_self {
        return None;
    }
    let ty = bynk_check::expr_types::type_at_offset(expr_types, offset)?;
    let display = ty.display();
    let name = display
        .strip_prefix("__")
        .and_then(|s| s.strip_suffix("Self"))
        .unwrap_or(&display);
    Some(format!("```bynk\nself: {name}\n```"))
}

/// v0.123 (editor-currency slice 2, DECISION B): if the identifier at
/// `ident_span` is the member of an `Upper.member` name-receiver access
/// (`Clock.now`, `Email.of`), return the full `Recv.member` callee for
/// [`crate::signature_help::resolve_label`] to resolve to its signature — the
/// same resolution completion and signature help perform, no new index.
/// `None` for a bare identifier or a lowercase (value-receiver) method, which
/// `resolve_label` does not handle.
pub(crate) fn qualified_callee_at(text: &str, ident_span: Span) -> Option<String> {
    let before = text.get(..ident_span.start)?.strip_suffix('.')?;
    let recv_start = before
        .rfind(|c: char| !(c.is_alphanumeric() || c == '_'))
        .map_or(0, |i| i + 1);
    let recv = &before[recv_start..];
    if !recv.chars().next()?.is_uppercase() {
        return None;
    }
    let member = text.get(ident_span.start..ident_span.end)?;
    Some(format!("{recv}.{member}"))
}

/// Describe a symbol declared in the embedded first-party sources — the `bynk`
/// and `bynk.cloudflare` adapters and the `bynk.list`/`bynk.map`/`bynk.string`
/// stdlib. Hover and completion-doc resolution otherwise walk only the project's
/// files (`walk_bynk_files`), so stdlib/surface symbols had no surfaced signature
/// or doc; this is the fallback after the project scan. Any `---` doc block on a
/// first-party declaration rides along (via `describe_fn`/`describe_type`/…),
/// once the sources carry one.
pub(crate) fn describe_firstparty_symbol(name: &str) -> Option<String> {
    const SOURCES: &[&str] = &[
        bynk_check::firstparty::BYNK_ADAPTER_SRC,
        bynk_check::firstparty::CLOUDFLARE_ADAPTER_SRC,
        bynk_check::firstparty::BYNK_LIST_SRC,
        bynk_check::firstparty::BYNK_MAP_SRC,
        bynk_check::firstparty::BYNK_STRING_SRC,
    ];
    SOURCES.iter().find_map(|src| describe_symbol(src, name))
}

/// Slice 6b: the `(unit name, name span)` of every `uses`/`consumes` target in
/// the source — the clickable ranges for document links. The link's target file
/// is resolved by the handler through the unit→source map (ADR 0095); this only
/// finds the spans, so it works on the live buffer regardless of the map.
pub(crate) fn unit_reference_spans(source: &str) -> Vec<(String, Span)> {
    let Ok(tokens) = tokenize(source) else {
        return Vec::new();
    };
    let (Some(unit), _) = parse_unit_with_recovery(&tokens, source) else {
        return Vec::new();
    };
    let (uses, consumes): (&[UsesDecl], &[ConsumesDecl]) = match &unit {
        SourceUnit::Commons(c) => (&c.uses, &[]),
        SourceUnit::Context(c) => (&c.uses, &c.consumes),
        SourceUnit::Adapter(a) => (&a.uses, &a.consumes),
        SourceUnit::Suite(_) => (&[], &[]),
    };
    let mut out: Vec<(String, Span)> = Vec::new();
    for u in uses {
        out.push((u.target.joined(), u.target.span));
    }
    for c in consumes {
        out.push((c.target.joined(), c.target.span));
    }
    out
}

fn describe_item(item: &CommonsItem, name: &str) -> Option<String> {
    match item {
        CommonsItem::Type(t) if t.name.name == name => Some(describe_type(t)),
        CommonsItem::Fn(f) if f.name.ident().name == name => Some(describe_fn(f)),
        CommonsItem::Capability(c) if c.name.name == name => Some(describe_capability(c)),
        CommonsItem::Service(s) if s.name.name == name => Some(describe_service(s)),
        CommonsItem::Agent(a) if a.name.name == name => Some(describe_agent(a)),
        CommonsItem::Provider(p) if p.provider_name.name == name => Some(describe_provider(p)),
        _ => None,
    }
}

fn describe_type(t: &TypeDecl) -> String {
    let mut out = String::new();
    out.push_str("```bynk\n");
    out.push_str(&format!("type {} = ", t.name.name));
    match &t.body {
        // v0.123 (slice 2): render the refined/opaque `where` predicate (was
        // collapsed to the bare base) via the formatter's own renderer.
        TypeBody::Refined {
            base, refinement, ..
        } => {
            out.push_str(base.name());
            if let Some(r) = refinement {
                out.push_str(&format!(" where {}", bynk_fmt::refinement_to_string(r)));
            }
        }
        TypeBody::Opaque {
            base, refinement, ..
        } => {
            out.push_str(&format!("opaque {}", base.name()));
            if let Some(r) = refinement {
                out.push_str(&format!(" where {}", bynk_fmt::refinement_to_string(r)));
            }
        }
        // Record fields, one per line (was collapsed to `record`).
        TypeBody::Record(r) => {
            if r.fields.is_empty() {
                out.push_str("{}");
            } else {
                out.push_str("{\n");
                for f in &r.fields {
                    out.push_str(&format!("\t{}: {}", f.name.name, type_ref_str(&f.type_ref)));
                    if let Some(r) = &f.refinement {
                        out.push_str(&format!(" where {}", bynk_fmt::refinement_to_string(r)));
                    }
                    out.push_str(",\n");
                }
                out.push('}');
            }
        }
        // Sum variants, with payloads (was collapsed to `sum`).
        TypeBody::Sum(s) => {
            out.push_str("enum {\n");
            for v in &s.variants {
                out.push_str(&format!("\t{}", v.name.name));
                if !v.payload.is_empty() {
                    let parts: Vec<String> = v
                        .payload
                        .iter()
                        .map(|p| format!("{}: {}", p.name.name, type_ref_str(&p.type_ref)))
                        .collect();
                    out.push_str(&format!("({})", parts.join(", ")));
                }
                out.push_str(",\n");
            }
            out.push('}');
        }
    }
    out.push_str("\n```\n");
    if let Some(doc) = &t.documentation {
        out.push('\n');
        out.push_str(doc);
        out.push('\n');
    }
    out
}

fn describe_fn(f: &FnDecl) -> String {
    let mut out = String::new();
    out.push_str("```bynk\n");
    out.push_str("fn ");
    out.push_str(&f.name.display());
    out.push('(');
    let mut parts: Vec<String> = Vec::new();
    if f.has_self {
        parts.push("self".into());
    }
    for p in &f.params {
        parts.push(format!("{}: {}", p.name.name, type_ref_str(&p.type_ref)));
    }
    out.push_str(&parts.join(", "));
    out.push_str(") -> ");
    out.push_str(&type_ref_str(&f.return_type));
    // v0.123 (slice 2): the contract clauses (v0.115), beneath the signature —
    // rendered through the formatter's own predicate renderer.
    for c in &f.requires {
        out.push_str(&format!(
            "\n\trequires {}: {}",
            c.name.name,
            bynk_fmt::expr_to_string(&c.predicate)
        ));
    }
    for c in &f.ensures {
        out.push_str(&format!(
            "\n\tensures {}: {}",
            c.name.name,
            bynk_fmt::expr_to_string(&c.predicate)
        ));
    }
    out.push_str("\n```\n");
    if let Some(doc) = &f.documentation {
        out.push('\n');
        out.push_str(doc);
        out.push('\n');
    }
    out
}

fn describe_capability(c: &CapabilityDecl) -> String {
    let mut out = String::new();
    out.push_str("```bynk\ncapability ");
    out.push_str(&c.name.name);
    out.push_str(" {\n");
    for op in &c.ops {
        out.push_str("\tfn ");
        out.push_str(&op.name.name);
        out.push('(');
        let parts: Vec<String> = op
            .params
            .iter()
            .map(|p| format!("{}: {}", p.name.name, type_ref_str(&p.type_ref)))
            .collect();
        out.push_str(&parts.join(", "));
        out.push_str(") -> ");
        out.push_str(&type_ref_str(&op.return_type));
        out.push('\n');
    }
    out.push_str("}\n```\n");
    if let Some(doc) = &c.documentation {
        out.push('\n');
        out.push_str(doc);
        out.push('\n');
    }
    out
}

/// v0.123 (slice 2): the `from <protocol>` header suffix for a service, or the
/// empty string for a plain `on call` service.
fn service_protocol_suffix(p: &ServiceProtocol) -> String {
    match p {
        ServiceProtocol::Call => String::new(),
        ServiceProtocol::Http => " from http".to_string(),
        ServiceProtocol::Cron => " from cron".to_string(),
        ServiceProtocol::Queue { name } => format!(" from queue(\"{name}\")"),
        ServiceProtocol::WebSocket { .. } => " from WebSocket".to_string(),
    }
}

/// v0.131: a one-line summary of a `cors { }` policy for hover — the origins
/// (always present), then `credentials`/`maxAge` when set.
fn cors_summary(cors: &CorsPolicy) -> String {
    let mut parts = vec![format!("origins: {:?}", cors.origins())];
    if cors.credentials() {
        parts.push("credentials: true".to_string());
    }
    if let Some(secs) = cors.max_age_secs() {
        parts.push(format!("maxAge: {secs}s"));
    }
    parts.join(", ")
}

/// v0.141: a one-line summary of a `security { }` policy for hover — `nosniff`
/// (default on, shown when off) and `hsts` (when opted in).
fn security_summary(security: &SecurityPolicy) -> String {
    let mut parts = Vec::new();
    if !security.nosniff() {
        parts.push("nosniff: false".to_string());
    }
    if let Some(secs) = security.hsts_max_age_secs() {
        parts.push(format!("hsts: {secs}s"));
    }
    if parts.is_empty() {
        // The default posture (nosniff on, no HSTS) with an empty block.
        "nosniff".to_string()
    } else {
        parts.join(", ")
    }
}

/// v0.142 (ADR 0165): a one-line summary of a `limits { }` policy for hover — the
/// `maxBody` byte ceiling when set.
fn limits_summary(limits: &LimitsPolicy) -> String {
    match limits.max_body() {
        Some(bytes) => format!("maxBody: {bytes} bytes"),
        None => "maxBody".to_string(),
    }
}

/// v0.123 (slice 2): the `on …` line for a handler — its route/protocol shape.
fn handler_line(h: &Handler) -> String {
    match &h.kind {
        HandlerKind::Call => "on call".to_string(),
        HandlerKind::Http { method, path } => format!("on {}(\"{}\")", method.as_str(), path),
        HandlerKind::Cron { expr } => format!("on schedule(\"{expr}\")"),
        HandlerKind::Message => "on message".to_string(),
        HandlerKind::Open => "on open".to_string(),
        HandlerKind::Close => "on close".to_string(),
    }
}

fn describe_service(s: &ServiceDecl) -> String {
    // v0.123 (slice 2): the protocol header and a line per route (was a bare
    // handler count).
    let mut out = format!(
        "```bynk\nservice {}{} {{\n",
        s.name.name,
        service_protocol_suffix(&s.protocol)
    );
    // v0.131: the CORS policy, if any, renders as a `cors { … }` header line
    // summarising the origins (the load-bearing field).
    if let Some(cors) = &s.cors {
        out.push_str(&format!("\tcors {{ {} }}\n", cors_summary(cors)));
    }
    // v0.141: the security-headers policy, if declared, renders similarly.
    if let Some(security) = &s.security {
        out.push_str(&format!(
            "\tsecurity {{ {} }}\n",
            security_summary(security)
        ));
    }
    // v0.142 (ADR 0165): the request-limits policy, if declared, renders similarly.
    if let Some(limits) = &s.limits {
        out.push_str(&format!("\tlimits {{ {} }}\n", limits_summary(limits)));
    }
    for h in &s.handlers {
        out.push_str(&format!("\t{}\n", handler_line(h)));
    }
    out.push_str("}\n```\n");
    if let Some(doc) = &s.documentation {
        out.push('\n');
        out.push_str(doc);
        out.push('\n');
    }
    out
}

/// v0.123 (slice 2): a store field's kind — `Cell[Int]`, `Map[K, V]`, or a bare
/// head with no type args.
fn store_kind_str(k: &StoreKind) -> String {
    if k.args.is_empty() {
        k.head.name.clone()
    } else {
        let args: Vec<String> = k.args.iter().map(type_ref_str).collect();
        format!("{}[{}]", k.head.name, args.join(", "))
    }
}

fn describe_agent(a: &AgentDecl) -> String {
    // v0.123 (slice 2): the store fields plus the `invariant`/`transition` step
    // invariants (v0.116), was a bare store-field count.
    let mut out = format!(
        "```bynk\nagent {} {{\n\tkey {}: {}\n",
        a.name.name,
        a.key_name.name,
        type_ref_str(&a.key_type),
    );
    for f in &a.store_fields {
        out.push_str(&format!(
            "\tstore {}: {}\n",
            f.name.name,
            store_kind_str(&f.kind)
        ));
    }
    for inv in &a.invariants {
        out.push_str(&format!(
            "\tinvariant {}: {}\n",
            inv.name.name,
            bynk_fmt::expr_to_string(&inv.predicate)
        ));
    }
    for tr in &a.transitions {
        out.push_str(&format!(
            "\ttransition {}: {}\n",
            tr.name.name,
            bynk_fmt::expr_to_string(&tr.predicate)
        ));
    }
    out.push_str("}\n```\n");
    if let Some(doc) = &a.documentation {
        out.push('\n');
        out.push_str(doc);
        out.push('\n');
    }
    out
}

fn describe_provider(p: &ProviderDecl) -> String {
    let mut out = format!(
        "```bynk\nprovides {} = {}\n```\n",
        p.capability.name, p.provider_name.name
    );
    if let Some(doc) = &p.documentation {
        out.push('\n');
        out.push_str(doc);
        out.push('\n');
    }
    out
}

/// A cross-file declaration lookup result: the URI of the file containing
/// the declaration, the declaration's source span, and the full source
/// text of that file (returned because callers need it to convert the
/// span to an LSP range and to build hover content).
pub struct CrossFileSymbol {
    pub uri: Url,
    pub span: Span,
    pub source: String,
}

/// Find `name`'s declaration in any project file other than `current_uri`.
/// Walks `src_root` recursively, parses each `.bynk` file with recovery,
/// and returns the first hit. Returns `None` if the name is not found
/// anywhere in the project.
///
/// Caller is responsible for trying the open file's local symbol table
/// first; this function intentionally skips `current_uri` so the local
/// path remains the fast path.
pub fn find_declaration_cross_file(
    src_root: &Path,
    current_uri: &Url,
    name: &str,
) -> Option<CrossFileSymbol> {
    for path in walk_bynk_files(src_root) {
        let Ok(uri) = Url::from_file_path(&path) else {
            continue;
        };
        if &uri == current_uri {
            continue;
        }
        let Ok(source) = std::fs::read_to_string(&path) else {
            continue;
        };
        if let Some(span) = find_declaration_span(&source, name) {
            return Some(CrossFileSymbol { uri, span, source });
        }
    }
    None
}

/// Markdown hover content for `name` from any project file other than
/// `current_uri`, plus the URI of the file that contributed it. Returns
/// `None` if the name is not declared anywhere in the project.
pub fn describe_symbol_cross_file(
    src_root: &Path,
    current_uri: &Url,
    name: &str,
) -> Option<(Url, String)> {
    for path in walk_bynk_files(src_root) {
        let Ok(uri) = Url::from_file_path(&path) else {
            continue;
        };
        if &uri == current_uri {
            continue;
        }
        let Ok(source) = std::fs::read_to_string(&path) else {
            continue;
        };
        if let Some(desc) = describe_symbol(&source, name) {
            return Some((uri, desc));
        }
    }
    None
}

/// Recursively collect every `.bynk` file under `root`. Returns an empty
/// vector if the root is missing or unreadable.
pub(crate) fn walk_bynk_files(root: &Path) -> Vec<PathBuf> {
    let mut out = Vec::new();
    let mut stack = vec![root.to_path_buf()];
    while let Some(dir) = stack.pop() {
        let Ok(rd) = std::fs::read_dir(&dir) else {
            continue;
        };
        for entry in rd.flatten() {
            let p = entry.path();
            if p.is_dir() {
                stack.push(p);
            } else if p.extension().and_then(|e| e.to_str()) == Some("bynk") {
                out.push(p);
            }
        }
    }
    out.sort();
    out
}

pub(crate) fn type_ref_str(t: &TypeRef) -> String {
    match t {
        // v0.20a: function types render in Bynk surface syntax.
        TypeRef::Fn(params, ret, _) => {
            let lhs = match params.len() {
                0 => "()".to_string(),
                1 if !matches!(params[0], TypeRef::Fn(..)) => type_ref_str(&params[0]),
                _ => format!(
                    "({})",
                    params
                        .iter()
                        .map(type_ref_str)
                        .collect::<Vec<_>>()
                        .join(", ")
                ),
            };
            format!("{lhs} -> {}", type_ref_str(ret))
        }
        TypeRef::Base(b, _) => b.name().to_string(),
        TypeRef::Named(id) => id.name.clone(),
        TypeRef::Result(a, b, _) => format!("Result[{}, {}]", type_ref_str(a), type_ref_str(b)),
        TypeRef::Option(t, _) => format!("Option[{}]", type_ref_str(t)),
        TypeRef::Effect(t, _) => format!("Effect[{}]", type_ref_str(t)),
        TypeRef::HttpResult(t, _) => format!("HttpResult[{}]", type_ref_str(t)),
        TypeRef::QueueResult(_) => "QueueResult".to_string(),
        // v0.20b: the built-in collection types.
        TypeRef::List(t, _) => format!("List[{}]", type_ref_str(t)),
        TypeRef::Query(t, _) => format!("Query[{}]", type_ref_str(t)),
        TypeRef::Stream(t, _) => format!("Stream[{}]", type_ref_str(t)),
        TypeRef::Connection(t, _) => format!("Connection[{}]", type_ref_str(t)),
        TypeRef::History(t, _) => format!("History[{}]", type_ref_str(t)),
        TypeRef::Map(k, v, _) => format!("Map[{}, {}]", type_ref_str(k), type_ref_str(v)),
        TypeRef::ValidationError(_) => "ValidationError".to_string(),
        TypeRef::JsonError(_) => "JsonError".to_string(),
        TypeRef::Unit(_) => "()".to_string(),
    }
}

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

    /// Build a temp directory unique to the test name, populate it with
    /// `(relative_path, contents)` files, and return the root path. The
    /// directory is left behind on the filesystem; callers can clean up
    /// if they care.
    fn setup_project(test_name: &str, files: &[(&str, &str)]) -> PathBuf {
        let root = std::env::temp_dir().join(format!(
            "bynk-lsp-test-{}-{}",
            test_name,
            std::process::id()
        ));
        let _ = fs::remove_dir_all(&root);
        fs::create_dir_all(&root).expect("create test root");
        for (rel, contents) in files {
            let p = root.join(rel);
            if let Some(parent) = p.parent() {
                fs::create_dir_all(parent).expect("create parent");
            }
            fs::write(&p, contents).expect("write file");
        }
        root
    }

    #[test]
    fn cross_file_definition_resolves_into_sibling_file() {
        let root = setup_project(
            "cross_file_definition",
            &[
                (
                    "a.bynk",
                    "commons demo.a\n\ntype Foo = Int where Positive\n",
                ),
                (
                    "b.bynk",
                    "commons demo.b\n\nuses demo.a\n\ntype Bar = Int where NonNegative\n",
                ),
            ],
        );
        let current = Url::from_file_path(root.join("b.bynk")).unwrap();
        let found = find_declaration_cross_file(&root, &current, "Foo")
            .expect("Foo should resolve into a.bynk");
        let expected = Url::from_file_path(root.join("a.bynk")).unwrap();
        assert_eq!(found.uri, expected);
        assert!(
            found.source.contains("type Foo = Int where Positive"),
            "source returned does not contain Foo declaration"
        );
    }

    #[test]
    fn cross_file_definition_skips_current_file() {
        let root = setup_project(
            "cross_file_skip_current",
            &[(
                "only.bynk",
                "commons demo.only\n\ntype Foo = Int where Positive\n",
            )],
        );
        let current = Url::from_file_path(root.join("only.bynk")).unwrap();
        // The only file containing Foo is current; cross-file must skip it.
        assert!(find_declaration_cross_file(&root, &current, "Foo").is_none());
    }

    #[test]
    fn cross_file_hover_returns_markdown_summary() {
        let root = setup_project(
            "cross_file_hover",
            &[
                (
                    "money.bynk",
                    "commons demo.money\n\n\
                     ---\n\
                     Amount in minor units of currency.\n\
                     ---\n\
                     type Money = Int where NonNegative\n",
                ),
                (
                    "orders.bynk",
                    "commons demo.orders\n\nuses demo.money\n\ntype OrderId = Int where Positive\n",
                ),
            ],
        );
        let current = Url::from_file_path(root.join("orders.bynk")).unwrap();
        let (other_uri, desc) = describe_symbol_cross_file(&root, &current, "Money")
            .expect("Money should produce hover content");
        assert_eq!(
            other_uri,
            Url::from_file_path(root.join("money.bynk")).unwrap()
        );
        assert!(desc.contains("type Money"));
        assert!(
            desc.contains("Amount in minor units"),
            "hover should include the doc block"
        );
    }

    #[test]
    fn cross_file_returns_none_for_unknown_name() {
        let root = setup_project(
            "cross_file_none",
            &[(
                "a.bynk",
                "commons demo.a\n\ntype Foo = Int where Positive\n",
            )],
        );
        let current = Url::from_file_path(root.join("a.bynk")).unwrap();
        assert!(find_declaration_cross_file(&root, &current, "DoesNotExist").is_none());
        assert!(describe_symbol_cross_file(&root, &current, "DoesNotExist").is_none());
    }

    #[test]
    fn first_party_symbols_describe_their_signature_and_doc() {
        // Slice 9: stdlib/surface symbols live in the embedded sources, not the
        // project — the hover/completion-doc fallback finds them there, signature
        // and `---` doc block alike.
        let reverse = describe_firstparty_symbol("reverse").expect("`bynk.list.reverse` described");
        assert!(
            reverse.contains("reverse") && reverse.contains("List"),
            "{reverse}"
        );
        assert!(
            reverse.contains("reverse order"),
            "doc block surfaced: {reverse}"
        );
        // The `bynk` adapter surface too (a capability, exercising the adapter path).
        let clock = describe_firstparty_symbol("Clock").expect("`bynk`-surface `Clock`");
        assert!(
            clock.contains("wall-clock"),
            "capability doc surfaced: {clock}"
        );
        // A name in no first-party source yields nothing (the fallback no-ops).
        assert!(describe_firstparty_symbol("DoesNotExist").is_none());
    }

    #[test]
    fn unit_reference_spans_finds_uses_and_consumes_targets() {
        // Slice 6b: the clickable ranges for document links — `uses`/`consumes`
        // unit names, with spans covering the name (resolution is the handler's).
        let src = "context app.main\n  uses billing.charge\n  consumes platform.time\n";
        let spans = unit_reference_spans(src);
        let names: Vec<&str> = spans.iter().map(|(n, _)| n.as_str()).collect();
        assert!(names.contains(&"billing.charge"), "{names:?}");
        assert!(names.contains(&"platform.time"), "{names:?}");
        // The span covers exactly the unit name (so the link underlines it).
        let (_, span) = spans.iter().find(|(n, _)| n == "billing.charge").unwrap();
        assert_eq!(&src[span.start..span.end], "billing.charge");
    }

    // v0.123 (slice 2): hover renders the real shape of each declaration —
    // record fields, sum variants, the refined `where`, the opaque base.
    #[test]
    fn describe_type_renders_fields_variants_and_refinements() {
        let record = describe_symbol(
            "commons demo.m\n\ntype Order = {\n  id: OrderId,\n  total: Money,\n}\n",
            "Order",
        )
        .unwrap();
        assert!(record.contains("type Order = {"), "{record}");
        assert!(record.contains("id: OrderId"), "{record}");
        assert!(record.contains("total: Money"), "{record}");

        let sum = describe_symbol(
            "commons demo.m\n\ntype Status = enum { Pending, Shipped }\n",
            "Status",
        )
        .unwrap();
        assert!(sum.contains("enum {"), "{sum}");
        assert!(sum.contains("Pending") && sum.contains("Shipped"), "{sum}");

        let refined = describe_symbol(
            "commons demo.m\n\ntype Email = String where NonEmpty\n",
            "Email",
        )
        .unwrap();
        assert!(
            refined.contains("type Email = String where NonEmpty"),
            "{refined}"
        );

        let opaque =
            describe_symbol("commons demo.m\n\ntype Token = opaque String\n", "Token").unwrap();
        assert!(opaque.contains("type Token = opaque String"), "{opaque}");
    }

    // v0.123 (slice 2): a function's `requires`/`ensures` contracts render
    // beneath its signature.
    #[test]
    fn describe_fn_renders_contracts() {
        let src = "commons demo.m\n\nfn discount(p: Int, pct: Int) -> Int\n  requires p_nonneg: p >= 0\n  ensures never_negative: result >= 0\n{\n  p\n}\n";
        let out = describe_symbol(src, "discount").unwrap();
        assert!(
            out.contains("fn discount(p: Int, pct: Int) -> Int"),
            "{out}"
        );
        assert!(out.contains("requires p_nonneg: p >= 0"), "{out}");
        assert!(out.contains("ensures never_negative: result >= 0"), "{out}");
    }

    // v0.123 (slice 2): a service renders its protocol header and route lines.
    #[test]
    fn describe_service_renders_routes() {
        let src = "context demo.app\n\nservice greeter {\n  on call(name: String) -> Effect[String] {\n    Effect.pure(name)\n  }\n}\n";
        let out = describe_symbol(src, "greeter").unwrap();
        assert!(out.contains("service greeter {"), "{out}");
        assert!(out.contains("on call"), "{out}");
    }

    // v0.123 (slice 2): an agent renders its store fields and the
    // `invariant`/`transition` step invariants.
    #[test]
    fn describe_agent_renders_store_and_invariants() {
        let src = "context demo.app\n\nagent Counter {\n  key id: String\n  store count: Cell[Int] = 0\n  invariant non_negative: count >= 0\n  transition monotonic: new.count >= old.count\n  on call bump() -> Effect[Result[(), String]] {\n    Ok(())\n  }\n}\n";
        let out = describe_symbol(src, "Counter").unwrap();
        assert!(out.contains("agent Counter {"), "{out}");
        assert!(out.contains("key id: String"), "{out}");
        assert!(out.contains("store count: Cell[Int]"), "{out}");
        assert!(out.contains("invariant non_negative: count >= 0"), "{out}");
        assert!(
            out.contains("transition monotonic: new.count >= old.count"),
            "{out}"
        );
    }

    // v0.123 (slice 2, DECISION B): the `Recv.member` detection that feeds
    // capability-op call-site hover through `resolve_label`.
    #[test]
    fn qualified_callee_detects_upper_receiver_only() {
        let text = "  let t = Clock.now()";
        let now = text.find("now").unwrap();
        assert_eq!(
            qualified_callee_at(
                text,
                Span {
                    start: now,
                    end: now + 3
                }
            )
            .as_deref(),
            Some("Clock.now")
        );
        // A lowercase (value) receiver is not our case — resolve_label can't
        // resolve it anyway.
        let text2 = "  xs.fold(0)";
        let fold = text2.find("fold").unwrap();
        assert!(
            qualified_callee_at(
                text2,
                Span {
                    start: fold,
                    end: fold + 4
                }
            )
            .is_none()
        );
        // A bare identifier (no receiver) → None.
        let text3 = "  total";
        assert!(qualified_callee_at(text3, Span { start: 2, end: 7 }).is_none());
    }

    // v0.137.0 (ADR 0161): hover for the `key`/`store` contextual keywords and
    // the agent state fields they introduce — on the keyword or on the field
    // name alike, with a `store` field's annotations rendered.
    #[test]
    fn describe_agent_state_covers_key_store_keywords_and_fields() {
        let src = "context demo.app\n\nagent Sessions {\n  key id: String\n  store items: Map[String, Int] @indexed( by: id ) @bounded( 10000 )\n  on call read() -> Effect[Int] {\n    Effect.pure(0)\n  }\n}\n";

        // The `key` keyword and the key field name both render `key id: String`
        // plus the contextual-keyword doc.
        let at_key_kw = src.find("key id").unwrap();
        let key_kw = describe_agent_state_at(src, at_key_kw).expect("hover on `key`");
        assert!(key_kw.contains("key id: String"), "{key_kw}");
        assert!(key_kw.contains("identity field"), "doc line: {key_kw}");
        let at_key_name = src.find("id: String").unwrap();
        let key_name = describe_agent_state_at(src, at_key_name).expect("hover on the key field");
        assert_eq!(key_kw, key_name, "keyword and name hover match");

        // The `store` keyword and the store field name both render the field
        // signature — kind and annotations — plus the doc.
        let at_store_kw = src.find("store items").unwrap();
        let store_kw = describe_agent_state_at(src, at_store_kw).expect("hover on `store`");
        assert!(
            store_kw.contains("store items: Map[String, Int]"),
            "{store_kw}"
        );
        assert!(
            store_kw.contains("@indexed(by: id)"),
            "annotation: {store_kw}"
        );
        assert!(
            store_kw.contains("@bounded(10000)"),
            "annotation: {store_kw}"
        );
        assert!(
            store_kw.contains("persisted agent-state"),
            "doc line: {store_kw}"
        );
        let at_store_name = src.find("items:").unwrap();
        let store_name =
            describe_agent_state_at(src, at_store_name).expect("hover on the store field");
        assert_eq!(store_kw, store_name, "keyword and name hover match");

        // Not on a `key`/`store` keyword or state-field name → no hover (the
        // agent name, and the store kind, both fall through to other paths).
        assert!(describe_agent_state_at(src, src.find("Sessions").unwrap()).is_none());
        assert!(describe_agent_state_at(src, src.find("Map").unwrap()).is_none());
        // The word `id` inside `by: id` is an annotation argument, not the key
        // field's declaration — it must not masquerade as the key field.
        assert!(describe_agent_state_at(src, src.find("by: id").unwrap() + 4).is_none());
    }

    // v0.122 (slice 1): `self` hover renders its receiver/agent type, reading
    // the type from `expr_types` and un-synthesising the agent-self record.
    #[test]
    fn describe_self_renders_receiver_and_unwraps_agent() {
        use bynk_check::checker::{NamedKind, Ty};
        let text = "self";
        let span = Span { start: 0, end: 4 };
        // A method receiver — a plain named type renders verbatim.
        let account = vec![(
            span,
            Ty::Named {
                name: "Account".into(),
                kind: NamedKind::Record,
            },
        )];
        assert_eq!(
            describe_self_at(text, 0, &account).as_deref(),
            Some("```bynk\nself: Account\n```")
        );
        // An agent handler — the synthetic `__CounterSelf` record un-synthesises
        // to the agent name.
        let agent = vec![(
            span,
            Ty::Named {
                name: "__CounterSelf".into(),
                kind: NamedKind::Record,
            },
        )];
        assert_eq!(
            describe_self_at(text, 0, &agent).as_deref(),
            Some("```bynk\nself: Counter\n```")
        );
        // Not on the `self` keyword — a different token yields nothing, even
        // when a type sits at the offset.
        let other = "total";
        assert!(
            describe_self_at(
                other,
                0,
                &[(
                    Span { start: 0, end: 5 },
                    Ty::Named {
                        name: "Int".into(),
                        kind: NamedKind::Record,
                    },
                )]
            )
            .is_none()
        );
    }

    const CACHE_SVC: &str = "context api\nservice api from http {\n  @cache(maxAge: 5.minutes, scope: public)\n  on GET(\"/x\") by v: Visitor () -> Effect[HttpResult[String]] {\n    Ok(\"y\")\n  }\n}\n";

    #[test]
    fn hover_on_cache_annotation_describes_it() {
        // Offset on the `cache` name token.
        let offset = CACHE_SVC.find("cache").unwrap() + 1;
        let hover = describe_handler_annotation_at(CACHE_SVC, offset).expect("hovers @cache");
        assert!(hover.contains("`@cache`"), "names the annotation: {hover}");
        assert!(hover.contains("maxAge"), "documents maxAge: {hover}");
        assert!(hover.contains("scope"), "documents scope: {hover}");
        // Off the annotation (on the `Ok` body) — no annotation hover.
        let ok_offset = CACHE_SVC.find("Ok(").unwrap() + 1;
        assert!(describe_handler_annotation_at(CACHE_SVC, ok_offset).is_none());
    }

    #[test]
    fn annotation_token_spans_cover_name_and_labels() {
        let spans = handler_annotation_token_spans(CACHE_SVC);
        // `@cache` + the two argument labels `maxAge`/`scope`.
        assert_eq!(spans.len(), 3, "{spans:?}");
        let texts: Vec<&str> = spans.iter().map(|s| &CACHE_SVC[s.start..s.end]).collect();
        assert_eq!(texts, ["@cache", "maxAge", "scope"]);
        // A service with no annotations yields nothing.
        let plain = "context api\nservice api from http {\n  on GET(\"/x\") by v: Visitor () -> Effect[HttpResult[String]] { Ok(\"y\") }\n}\n";
        assert!(handler_annotation_token_spans(plain).is_empty());
    }
}