Skip to main content

bynk_lsp/
lib.rs

1//! `bynk-lsp` — Bynk Language Server.
2//!
3//! Implements the LSP capabilities listed in `design/bynk-lsp-spec.md` §4.3:
4//! synchronisation (Full), diagnostics, hover, go-to-definition and -type/-impl,
5//! formatting, document symbols, completion, signature help, references, rename,
6//! code actions, code lens, call hierarchy, document links, inlay hints,
7//! semantic tokens, workspace symbols, real multi-root workspace folders, and
8//! server-registered file watching. Built on `tower-lsp`.
9//!
10//! Architecture:
11//! - [`Backend`] holds the server state (behind a `tokio::sync::RwLock`): a
12//!   **map of projects** keyed by discovered root — each with its own config,
13//!   analysis round, and published set — plus the workspace-folder discovery
14//!   seeds and the client-global map of open documents. A request routes by URI
15//!   to its project (its nearest enclosing `bynk.toml`); a file under none is
16//!   single-file.
17//! - Document changes trigger `schedule_diagnostics`, one generation-based
18//!   debounce (a project-wide round via [`bynk_ide::diagnose_project_with`], or
19//!   single-file [`bynk_ide::diagnose`]) that publishes the resulting
20//!   diagnostics.
21//! - Hover and definition consult the parsed AST for the file under the
22//!   cursor; both are best-effort (return None for unrecognised positions).
23//! - Formatting delegates to [`bynk_fmt::format_source`].
24//!
25//! Slice C (the `[lib]` seam): this crate exposes a library target so its
26//! integration tests can `use bynk_lsp::…` instead of `#[path]`-including source
27//! modules. The `pub mod`s below are exposed for that testing, **not** as a
28//! stable API — `bynk-lsp` is a language-server binary and makes no library
29//! compatibility promise.
30
31pub mod agent_state_request;
32pub mod architecture_request;
33pub mod capability_fixes;
34pub mod capability_path;
35pub mod code_actions;
36pub mod completion;
37mod content;
38pub mod contract_diff_request;
39pub mod doc_link_hints;
40mod document_symbols;
41pub mod documentation_request;
42pub mod explain_request;
43pub mod extract;
44pub mod fill_arms;
45pub use bynk_ide::first_party_docs;
46pub mod fix_all;
47pub use bynk_ide::hover;
48pub mod index_queries;
49mod inlay_hints;
50pub mod inline;
51mod inline_values;
52mod locals_nav;
53pub mod organise;
54pub mod position;
55mod project;
56pub mod provider_stub;
57mod publish;
58pub mod refined_request;
59mod schema_lock;
60mod semantic_tokens;
61pub mod sequence_request;
62mod signature_help;
63mod structure;
64pub mod symbols;
65pub mod transport;
66pub mod wire_contract_request;
67
68use std::path::PathBuf;
69use std::sync::Arc;
70
71use tokio::sync::RwLock;
72use tower_lsp::jsonrpc::Result as JsonRpcResult;
73use tower_lsp::lsp_types::request::{
74    GotoImplementationParams, GotoImplementationResponse, GotoTypeDefinitionParams,
75    GotoTypeDefinitionResponse,
76};
77use tower_lsp::lsp_types::*;
78use tower_lsp::{Client, LanguageServer, LspService, Server};
79
80use crate::project::ProjectConfig;
81
82const SERVER_NAME: &str = "bynk-lsp";
83const SERVER_VERSION: &str = env!("CARGO_PKG_VERSION");
84
85/// In-memory document state.
86#[derive(Debug, Clone)]
87struct DocumentState {
88    text: String,
89    version: i32,
90}
91
92/// v0.25 (ADR 0053): one analysis round's retained outputs — the binding
93/// index plus the snapshots its spans are offsets into, and the open-doc
94/// versions captured when the overlay was built (rename emits versioned
95/// edits against exactly these versions).
96#[derive(Debug)]
97struct Analysis {
98    /// Slice A: the canonicalised **project root** every path in this round
99    /// resolves against. Was the single `src` directory; the round now covers
100    /// every `include` tree, and ADR 0198 makes each file's path
101    /// project-relative — so this is the one base that resolves all of them.
102    project_root: PathBuf,
103    index: bynk_check::index::ProjectIndex,
104    /// Project-relative path → the analysed text.
105    snapshots: std::collections::HashMap<PathBuf, String>,
106    /// Project-relative path → the open document's version at analysis
107    /// time (absent for files read from disk).
108    versions: std::collections::HashMap<PathBuf, i32>,
109    /// v0.26 (ADR 0054): project-relative path → the round's diagnostics,
110    /// full `CompileError`s included — the suggestions `codeAction` serves
111    /// ride on them. Every analysed file has an entry (clean files an empty
112    /// one). Replaces the v0.25 categories-only field; the rename baseline
113    /// derives from these via [`Self::diag_categories`].
114    diagnostics: std::collections::HashMap<PathBuf, Vec<bynk_ide::Diagnostic>>,
115    /// v0.27 (ADR 0056): project-relative path → the round's harvested
116    /// inferred-type hints, spans against the analysed snapshots.
117    hints: bynk_check::hints::FileHints,
118    /// v0.99: project-relative path → the round's capability-requirement ledger,
119    /// driving the materializable ghost `given` inlay hint, spans against the
120    /// analysed snapshots.
121    requirements: bynk_check::requirements::FileRequirements,
122    /// #2469: project-relative path → the round's capability paths, behind the
123    /// `given` hover and the "Show capability path" action.
124    capability_paths: bynk_check::capability_paths::FileCapabilityPaths,
125    /// v0.31 (ADR 0064): project-relative path → the round's local bindings
126    /// with scope ranges, for locals navigation (references/definition/
127    /// highlight), spans against the analysed snapshots.
128    locals: bynk_check::locals::FileLocals,
129    /// Slice 6: project-relative path → the round's expression types, spans
130    /// against the analysed snapshots — backs go-to-type-definition.
131    expr_types: bynk_check::expr_types::FileExprTypes,
132    /// T3.6b (R4.1): the round's intern table — what every `TyId` in
133    /// `expr_types` resolves against. One per analysis round, shared across
134    /// every unit it checked.
135    ty_intern: std::sync::Arc<bynk_check::checker::Types>,
136    /// Slice 6b (ADR 0095): qualified unit name → its project source file(s),
137    /// project-relative — backs document links (`uses`/`consumes` → source).
138    unit_sources: std::collections::HashMap<String, Vec<PathBuf>>,
139    /// #846: qualified context/adapter unit name → the cross-context/agent
140    /// tables the `bynk/sequenceModel` request classifies handler calls
141    /// against.
142    sequence_info: std::collections::HashMap<String, bynk_ide::ContextSequenceInfo>,
143    /// #3583: see `bynk_ide::ProjectDiagnostics::architecture_facts`.
144    architecture_facts: bynk_ide::ArchitectureFacts,
145    /// #855: qualified context/adapter unit name → the combined type table
146    /// and service/agent tables the `bynk/wireContract` request resolves a
147    /// handler's boundary shape and cross-context hash against.
148    boundary_info: std::collections::HashMap<String, bynk_ide::ContextBoundaryInfo>,
149    /// #848: qualified unit name → its doc-comment intra-doc-link search
150    /// order — itself first, then its `uses` targets, then its `consumes`
151    /// targets — backs intra-doc-link resolution in `document_link` and
152    /// `hover`. See `bynk_ide::ProjectDiagnostics::doc_scope`.
153    doc_scope: std::collections::HashMap<String, Vec<String>>,
154    /// #2467: the round's boundary changes since `bynk.schema.lock` and the
155    /// contract hashes provided now, behind `bynk/contractDiff`.
156    contract_diff: bynk_check::analysis::ContractDiff,
157}
158
159impl Analysis {
160    /// Per-file diagnostic categories — the rename validator's baseline,
161    /// derived from the retained diagnostics.
162    fn diag_categories(&self) -> Vec<(PathBuf, String)> {
163        self.diagnostics
164            .iter()
165            .flat_map(|(path, diags)| {
166                diags
167                    .iter()
168                    .map(|d| (path.clone(), d.error.category.to_string()))
169            })
170            .collect()
171    }
172}
173
174/// The owning unit name of `file`, read from `cache` when the text is the one it
175/// was last read from, else re-parsed and stored (#3243 S0).
176fn cached_owner_unit<'c>(
177    cache: &'c mut std::collections::HashMap<PathBuf, (u64, Option<String>)>,
178    file: &bynk_ide::FileDiagnostics,
179) -> Option<&'c str> {
180    use std::hash::{Hash, Hasher};
181    let mut hasher = std::collections::hash_map::DefaultHasher::new();
182    file.text.hash(&mut hasher);
183    let hash = hasher.finish();
184    let fresh = cache
185        .get(&file.source_path)
186        .is_some_and(|(cached, _)| *cached == hash);
187    if !fresh {
188        let owner = crate::symbols::own_declaration_name(&file.text).map(|(unit, _)| unit);
189        cache.insert(file.source_path.clone(), (hash, owner));
190    }
191    cache.get(&file.source_path)?.1.as_deref()
192}
193
194/// One project's mutable state — the fields that were flat on `State` before
195/// slice D, now one set per discovered project root. Every request routes by
196/// URI (via `resolve_root`) to its owning entry, so two projects analyse,
197/// version, and publish independently.
198/// One project's analysis round, through its memo when it has one (#3243 S2.3b).
199/// A memo poisoned by a panic in an earlier round is dropped, not trusted.
200fn analyse_with_memo(
201    roots: &bynk_ide::AnalysisRoots,
202    content: &std::collections::HashMap<PathBuf, String>,
203    schema_lock: &bynk_ide::SchemaLock,
204    memo: Option<&std::sync::Mutex<bynk_check::memo::AnalysisMemo>>,
205) -> bynk_ide::ProjectDiagnostics {
206    let Some(memo) = memo else {
207        return bynk_ide::diagnose_project_with(roots, content, schema_lock);
208    };
209    if memo.is_poisoned() {
210        // A panic mid-round may have left the memo half-updated: empty it, and
211        // clear the flag so later rounds keep what they learn instead of
212        // starting over every time.
213        *memo.lock().unwrap_or_else(|e| e.into_inner()) = bynk_check::memo::AnalysisMemo::new();
214        memo.clear_poison();
215    }
216    let mut guard = memo.lock().unwrap_or_else(|e| e.into_inner());
217    bynk_ide::diagnose_project_memoised(roots, content, schema_lock, &mut guard)
218}
219
220#[derive(Debug, Default)]
221struct ProjectState {
222    /// Parsed `bynk.toml` configuration for this root. Defaults for missing
223    /// fields. Read live for the diagnostics mode/debounce and formatting;
224    /// reloaded on a `bynk.toml` change (`did_change_watched_files`).
225    config: ProjectConfig,
226    /// v0.25: the latest analysis round's index + snapshots. References,
227    /// rename, and the re-pointed definition/hover read this; positions
228    /// convert against the analysed snapshots (v0.24 rule).
229    analysis: Option<Arc<Analysis>>,
230    /// #3243 S0: each file's owning unit name, as `own_declaration_name` reads
231    /// it, keyed by project-relative path with a hash of the text it was read
232    /// from. The doc-link hint scan needs it for every file on every round;
233    /// re-tokenising and re-parsing every file just to learn a name that only
234    /// changes when the file does was about 8% of a round.
235    doc_owner_cache: std::collections::HashMap<PathBuf, (u64, Option<String>)>,
236    /// #3243 S2.3b: what the last analysis round kept for the next (each
237    /// file's checked output, keyed by a digest of everything the check read).
238    /// Behind a mutex because the round runs on a blocking thread; rounds of one
239    /// project never overlap in practice, and a second would simply wait.
240    analysis_memo: Arc<std::sync::Mutex<bynk_check::memo::AnalysisMemo>>,
241    /// v0.24: URIs that currently carry published project diagnostics — the
242    /// previous round's dirty set, so newly-clean files get a clearing
243    /// (empty) publish. Per-project (slice D): a round for this root must only
244    /// clear its own files, never another project's.
245    published: std::collections::HashSet<Url>,
246    /// v0.24: debounce generation. Each change bumps it; a scheduled
247    /// analysis runs only if it is still the latest when the delay elapses.
248    /// Per-project: two projects debounce independently.
249    analysis_generation: u64,
250    /// Monotonic id handed to each analysis round as it *starts*. Together
251    /// with `analysis_round_committed` this orders round completions: an old
252    /// slow round must never overwrite a newer round's results (#513).
253    /// Per-project (slice D): a global counter would let one project's round
254    /// discard another's.
255    analysis_round_started: u64,
256    /// The id of the newest round whose results have been committed.
257    analysis_round_committed: u64,
258    /// #1667: the newest round panicked and no round has committed since.
259    /// The client is told once per such streak, not on every keystroke.
260    analysis_failed: bool,
261    /// #1667: makes this project's next round panic, so a test can watch the
262    /// failure reach the client. Per project, not a global, so parallel tests'
263    /// rounds can't take it.
264    #[cfg(test)]
265    panic_next_round: bool,
266    /// #2081: this project's `bynk.schema.lock`, read-only and cached by its
267    /// `(mtime, len)` stamp, handed to every diagnostics round so the editor
268    /// reports a non-additive event change as `bynk check` does. Cleared by
269    /// the `**/bynk.schema.lock` watcher.
270    schema_lock: schema_lock::SchemaLockCache,
271}
272
273/// #733: the client's `workspace/*/refresh` support, per pull-based decoration,
274/// captured at `initialize`. Each flag gates the corresponding round-commit
275/// nudge in [`Backend::run_project_diagnostics`].
276#[derive(Debug, Clone, Copy, Default)]
277struct RefreshSupport {
278    semantic_tokens: bool,
279    inlay_hints: bool,
280    code_lens: bool,
281}
282
283/// Mutable server state. Slice D: a map of projects (was one flat project),
284/// plus the open buffers (client-global) and the workspace-folder seeds.
285#[derive(Debug, Default)]
286struct State {
287    /// Discovered projects, keyed by **canonical project root** (Q4: the
288    /// directory a file's `resolve_root` walk lands on — a `bynk.toml`, else an
289    /// implicit `src/` parent). Empty in single-file mode. A request routes to
290    /// its entry by URI; the entry is created lazily on first touch (open or
291    /// request) and pruned when no folder covers it and it holds no open buffer.
292    projects: std::collections::HashMap<PathBuf, ProjectState>,
293    /// The workspace-folder roots the client has open (slice D). **Discovery
294    /// seeds, not routing owners** (Q4): they bound where
295    /// `did_change_workspace_folders` prunes, but a URI routes by its nearest
296    /// enclosing `bynk.toml`, which may sit above every folder.
297    folders: Vec<PathBuf>,
298    /// Open documents keyed by URI — a client-global set; each doc routes to
299    /// its project via `resolve_root`.
300    docs: std::collections::HashMap<Url, DocumentState>,
301    /// Slice E: whether the client advertised `didChangeWatchedFiles`
302    /// **dynamic registration** at `initialize`. When set, `initialized`
303    /// registers the file watchers server-side (so any client is notified);
304    /// when not, the client is expected to supply them itself (as VS Code did
305    /// before the extension's client-side watchers were removed).
306    supports_dynamic_watchers: bool,
307    /// Whether the client advertised `typeHierarchy` **dynamic registration**.
308    /// The `lsp-types` this server is built on has no `typeHierarchyProvider`
309    /// server capability, so `initialized` registers the feature instead.
310    supports_dynamic_type_hierarchy: bool,
311    /// #733: whether the client advertised `refresh_support` for each pull-based
312    /// decoration at `initialize`. When set, a committed round asks the client to
313    /// re-pull that decoration (`workspace/*/refresh`) — the "revalidate" half of
314    /// serving `committed_analysis` stale while typing. Only sent when advertised,
315    /// so a client that never supported it is never spammed with unknown requests.
316    supports_refresh: RefreshSupport,
317    /// #2098: whether the client advertised
318    /// `experimental.explainDiagnosticCommand` at `initialize` — it implements
319    /// the client-side `bynk.explainDiagnostic` command, so `code_action`
320    /// offers the "Explain …" action. Off for any other client.
321    supports_explain_command: bool,
322    /// #2469: whether the client advertised `experimental.capabilityPathCommand`,
323    /// so it runs `bynk.showCapabilityPath` (the "Show capability path" action).
324    supports_capability_path_command: bool,
325    /// #2470: the client runs `bynk.exploreRefinedType`, so a refined type's
326    /// hover may carry the "Try values…" link.
327    supports_refined_explorer_command: bool,
328    /// #2100 slice 2: whether the client shows a disabled code action's
329    /// reason (`codeAction.disabledSupport`) — extract-function tells the user
330    /// why a capability-using selection can't be extracted that way.
331    supports_code_action_disabled: bool,
332    /// #2459: the `bynk.docLinks.reportUnresolved` setting — how an unresolved
333    /// doc link is reported. Client-global; `initializationOptions` and
334    /// `workspace/didChangeConfiguration` set it.
335    doc_link_report: doc_link_hints::Level,
336    /// Slice F: debounce generation for **single-file** buffers (no project),
337    /// keyed by URI. The project path holds its generation in `ProjectState`;
338    /// this is the same coalescing for a buffer that has no entry — a burst runs
339    /// one `diagnose`, not one per keystroke. Cleared on `did_close`.
340    single_file_generations: std::collections::HashMap<Url, u64>,
341    /// #682: memoised URI → canonical project root routing (`None` for
342    /// single-file mode is itself a cached answer), so the hot request path
343    /// stops re-walking the filesystem and `canonicalize()`ing on every call.
344    /// For a URI whose own path is fixed, routing depends only on `bynk.toml`
345    /// presence among its ancestors — `find_source_root`'s `src`-ancestor
346    /// fallback is a pure string match against that fixed path, with no
347    /// filesystem I/O of its own, so it can't drift independently. That makes
348    /// a `bynk.toml` create/delete/change the only event that can move an
349    /// already-cached URI's route, and this is invalidated wholesale on it
350    /// (`did_change_watched_files`). A workspace-folder change also clears it
351    /// (`did_change_workspace_folders`) even though `resolve_canonical` never
352    /// consults `folders` today — a defensive, effectively-free no-op kept in
353    /// case that ever changes, not a correctness requirement. Bounded entries
354    /// are never individually evicted (e.g. on `did_close`); only ever
355    /// wholesale-cleared, which is judged an acceptable tradeoff — bounded by
356    /// the distinct files touched in a session. See [`Backend::root_for_uri`].
357    root_cache: std::collections::HashMap<Url, Option<PathBuf>>,
358    /// #682: bumped every time `root_cache` is wholesale-cleared. `root_for_uri`
359    /// resolves a cache miss off the `state` lock (a filesystem walk must not
360    /// run while holding it); this closes the race where an invalidating clear
361    /// lands *during* that walk — the write-back re-checks the generation and
362    /// drops a stale answer instead of resurrecting it into the freshly-cleared
363    /// cache.
364    root_cache_generation: u64,
365}
366
367#[derive(Clone)]
368pub struct Backend {
369    client: Client,
370    state: Arc<RwLock<State>>,
371    /// Slice B (the freshness contract): serialises request-driven refreshes so
372    /// concurrent index-backed requests after one edit coalesce onto a single
373    /// round instead of each spawning its own. Held only across `analysis_for`'s
374    /// refresh; never across a `state` lock.
375    refresh_lock: Arc<tokio::sync::Mutex<()>>,
376    /// #1667: set when the client sends `shutdown`. [`run`] reads it once the
377    /// session ends, to exit 0 after an orderly shutdown and 1 otherwise, as
378    /// the LSP spec's `exit` notification prescribes.
379    shutdown_requested: Arc<std::sync::atomic::AtomicBool>,
380}
381
382/// #1667: a failed `spawn_blocking` task, described for the log: the panic's
383/// message when it panicked, else that it was cancelled.
384fn describe_join_error(e: tokio::task::JoinError) -> String {
385    if !e.is_panic() {
386        return format!("cancelled ({e})");
387    }
388    let payload = e.into_panic();
389    if let Some(s) = payload.downcast_ref::<&str>() {
390        format!("panicked: {s}")
391    } else if let Some(s) = payload.downcast_ref::<String>() {
392        format!("panicked: {s}")
393    } else {
394        "panicked with a non-string payload".to_string()
395    }
396}
397
398impl Backend {
399    #[cfg(test)]
400    fn new(client: Client) -> Self {
401        Self::with_shutdown_flag(client, Arc::default())
402    }
403
404    fn with_shutdown_flag(
405        client: Client,
406        shutdown_requested: Arc<std::sync::atomic::AtomicBool>,
407    ) -> Self {
408        Self {
409            client,
410            state: Arc::new(RwLock::new(State::default())),
411            refresh_lock: Arc::new(tokio::sync::Mutex::new(())),
412            shutdown_requested,
413        }
414    }
415
416    /// Locate `bynk.toml` walking upward from the given path. Returns the
417    /// project root (the directory containing `bynk.toml`) on success.
418    fn find_project_root(start: &std::path::Path) -> Option<PathBuf> {
419        let mut current = if start.is_file() {
420            start.parent()?.to_path_buf()
421        } else {
422            start.to_path_buf()
423        };
424        loop {
425            let candidate = current.join("bynk.toml");
426            if candidate.is_file() {
427                return Some(current);
428            }
429            current = current.parent()?.to_path_buf();
430        }
431    }
432
433    /// Locate the nearest ancestor directory named `src`, walking upward from
434    /// `start`. This is the implicit source root of a *rootless* tree — the
435    /// same `src/`-without-`bynk.toml` layout `bynk` compiles in its legacy
436    /// single-tree mode (`bynk-tests/tests/e2e.rs` `compile_fixture`), which the
437    /// compiler fixtures use. Returns that `src` directory.
438    fn find_source_root(start: &std::path::Path) -> Option<PathBuf> {
439        let mut current = if start.is_file() {
440            start.parent()?.to_path_buf()
441        } else {
442            start.to_path_buf()
443        };
444        loop {
445            if current.file_name().and_then(|n| n.to_str()) == Some("src") {
446                return Some(current);
447            }
448            current = current.parent()?.to_path_buf();
449        }
450    }
451
452    /// Resolve the analysis root for a path, with its config. A real
453    /// `bynk.toml` project (config loaded from disk) takes precedence;
454    /// otherwise (#485) fall back to the nearest enclosing `src/` as an
455    /// implicit project so a multi-file commons in a rootless tree still
456    /// analyses cross-file instead of dropping to sibling-blind single-file
457    /// mode. `None` when neither is found — the caller stays single-file.
458    fn resolve_root(start: &std::path::Path) -> Option<(PathBuf, project::ProjectConfig)> {
459        if let Some(root) = Self::find_project_root(start) {
460            let config = project::load_config(&root).unwrap_or_default();
461            return Some((root, config));
462        }
463        // The implicit project root is the parent of `src`: with the default
464        // `src_dir` ("src"), `run_project_diagnostics` re-derives exactly this
465        // `src` tree as the analysis root, so every project-mode feature works
466        // with no further plumbing.
467        let src = Self::find_source_root(start)?;
468        let root = src.parent()?.to_path_buf();
469        Some((root, project::ProjectConfig::default()))
470    }
471
472    /// Slice D (Q4): the **canonical** project root that owns `uri`, with its
473    /// config, or `None` for a file under no project (single-file mode). Routing
474    /// is `resolve_root`'s walk-up — the same project `bynk` attributes the file
475    /// to — canonicalised so it matches the `projects` map key and every
476    /// `Analysis.project_root`. Workspace folders do not enter here: a URI routes
477    /// by its nearest enclosing `bynk.toml`, whatever folder it sits in.
478    fn resolve_canonical(uri: &Url) -> Option<(PathBuf, project::ProjectConfig)> {
479        let path = uri.to_file_path().ok()?;
480        let (root, config) = Self::resolve_root(&path)?;
481        Some((root.canonicalize().unwrap_or(root), config))
482    }
483
484    /// The canonical project root owning `uri`, or `None` in single-file mode.
485    /// Uncached — walks the filesystem and `canonicalize()`s on every call.
486    /// Kept for the one caller that must route off the `state` lock
487    /// (`prune_orphaned_projects`, #682 DECISION B) and for tests exercising
488    /// routing directly; every other caller wants the memoised
489    /// [`Self::root_for_uri`].
490    fn root_for_uri_uncached(uri: &Url) -> Option<PathBuf> {
491        Self::resolve_canonical(uri).map(|(root, _)| root)
492    }
493
494    /// #682: the cached counterpart of `root_for_uri_uncached` — the canonical
495    /// project root owning `uri`, memoised in `State.root_cache` so a repeated
496    /// request for the same URI does not re-walk the filesystem. A miss runs
497    /// the uncached walk and stores the result (`None` included — a file that
498    /// routes to no project is itself a stable answer worth caching).
499    ///
500    /// The walk runs off the `state` lock (it is synchronous filesystem I/O),
501    /// so a wholesale `root_cache.clear()` can land between the read that
502    /// found the miss and the write that stores its answer — a `bynk.toml`
503    /// created mid-walk would otherwise have this write resurrect the
504    /// pre-creation (stale) route into the just-cleared cache, and unlike
505    /// `prune_orphaned_projects`'s TOCTOU window this one would never
506    /// self-heal. `root_cache_generation` closes it: the write-back only
507    /// applies if no clear happened while the walk was in flight; otherwise
508    /// the fresh answer is simply not cached (correct either way — just an
509    /// uncached hit for that one request).
510    async fn root_for_uri(&self, uri: &Url) -> Option<PathBuf> {
511        let generation = {
512            let state = self.state.read().await;
513            if let Some(cached) = state.root_cache.get(uri) {
514                return cached.clone();
515            }
516            state.root_cache_generation
517        };
518        let root = Self::root_for_uri_uncached(uri);
519        let mut state = self.state.write().await;
520        if Self::root_cache_write_is_current(generation, state.root_cache_generation) {
521            state.root_cache.insert(uri.clone(), root.clone());
522        }
523        root
524    }
525
526    /// #682: whether a `root_for_uri` write-back computed while the cache was
527    /// at `read_generation` should still be applied, given the cache is now at
528    /// `current_generation` — `false` once an invalidating clear has bumped it
529    /// past the read, meaning the walk's answer may already be stale. Pulled
530    /// out of `root_for_uri` so the guard itself — the one thing standing
531    /// between the fix and the TOCTOU it closes — is unit-testable without
532    /// needing to actually win the race in real time.
533    fn root_cache_write_is_current(read_generation: u64, current_generation: u64) -> bool {
534        read_generation == current_generation
535    }
536
537    /// Slice E: every project root under `folder` — the folder's own
538    /// `resolve_root` (a manifest at or above it, the folder-inside-a-project
539    /// case) plus a bounded recursive walk collecting each directory that holds
540    /// a `bynk.toml`. Roots are **canonical** (the `projects` map key). The walk
541    /// skips the caches and heavy dirs it should never descend (`out`,
542    /// `node_modules`, `target`, `.git`, and dot-dirs), and a **visited-set of
543    /// canonicalised dirs** stops a symlink cycle (`ln -s . loop`) from recursing
544    /// forever. Synchronous FS I/O — callers run it via `spawn_blocking`, off the
545    /// executor. This is the "one tree-walk"
546    /// [ADR 0204](../decisions/0204-per-workspace-project-state.md) §C named —
547    /// shared by startup warming and added-folder warming.
548    fn discover_projects_under(folder: &std::path::Path) -> Vec<PathBuf> {
549        fn should_skip(name: &std::ffi::OsStr) -> bool {
550            let name = name.to_string_lossy();
551            matches!(name.as_ref(), "out" | "node_modules" | "target" | ".git")
552                || name.starts_with('.')
553        }
554        fn walk(
555            dir: &std::path::Path,
556            out: &mut Vec<PathBuf>,
557            visited: &mut std::collections::HashSet<PathBuf>,
558        ) {
559            // Guard against symlink cycles: a directory reached twice (by its
560            // canonical path) is not descended again.
561            let canon_dir = dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf());
562            if !visited.insert(canon_dir.clone()) {
563                return;
564            }
565            if dir.join("bynk.toml").is_file() && !out.contains(&canon_dir) {
566                out.push(canon_dir);
567            }
568            let Ok(entries) = std::fs::read_dir(dir) else {
569                return;
570            };
571            for entry in entries.flatten() {
572                let path = entry.path();
573                if path.is_dir() && !should_skip(&entry.file_name()) {
574                    walk(&path, out, visited);
575                }
576            }
577        }
578        let mut roots = Vec::new();
579        // A manifest at or above the folder (the folder sits inside a project).
580        if let Some((root, _)) = Self::resolve_root(folder) {
581            let canon = root.canonicalize().unwrap_or(root);
582            roots.push(canon);
583        }
584        // The implicit-`src/` shape (#485): a `src/` tree with no `bynk.toml`.
585        // `resolve_root` only finds a `src/` *ancestor*, so the folder-is-the-root
586        // case (folder holds `src/`, no manifest) needs an explicit check — else
587        // a rootless project would warm only lazily on first open, not at startup.
588        if folder.join("src").is_dir() && !folder.join("bynk.toml").is_file() {
589            let canon = folder
590                .canonicalize()
591                .unwrap_or_else(|_| folder.to_path_buf());
592            if !roots.contains(&canon) {
593                roots.push(canon);
594            }
595        }
596        let mut visited = std::collections::HashSet::new();
597        walk(folder, &mut roots, &mut visited);
598        // #2207: a workspace root isn't a project. Analysing it as one would
599        // read every member's sources as a single tree; each member is found
600        // by the walk on its own.
601        roots.retain(|root| !bynk_ide::is_workspace_root(root));
602        roots
603    }
604
605    /// Slice F: the single diagnostics-scheduler entry point. Route `uri` to its
606    /// owning project (a debounced project round) or, if none, single-file mode
607    /// (a debounced buffer `diagnose`). **One** generation-based debounce at the
608    /// configured delay covers both — a burst coalesces to one analysis. Replaces
609    /// `recompile_and_publish`, whose route + second hardcoded debounce stacked
610    /// on `did_change`'s own sleep.
611    async fn schedule_diagnostics(&self, uri: &Url) {
612        // Slice D: route by URI to the owning project, creating its entry on
613        // first touch (a file opened before any folder scan). Q4: the root is
614        // the file's nearest enclosing `bynk.toml`, not its workspace folder.
615        // #682: routing goes through the cache; the config is only loaded from
616        // disk when the entry doesn't exist yet, not on every call.
617        if let Some(root) = self.root_for_uri(uri).await {
618            {
619                let mut state = self.state.write().await;
620                if !state.projects.contains_key(&root) {
621                    let config = project::load_config(&root).unwrap_or_default();
622                    state.projects.insert(
623                        root.clone(),
624                        ProjectState {
625                            config,
626                            ..Default::default()
627                        },
628                    );
629                }
630            }
631            self.schedule_project_diagnostics(root).await;
632        } else {
633            self.schedule_single_file(uri.clone()).await;
634        }
635    }
636
637    /// v0.24: debounce a project-wide analysis — each call bumps the project's
638    /// generation; the spawned task runs only if still the latest after the
639    /// delay, so a typing burst produces one analysis. Slice D: keyed on one
640    /// project root, so two projects debounce independently. A no-op if the
641    /// root's entry is gone (its folder was removed mid-debounce).
642    ///
643    /// Slice F: the delay is the project's **configured** `diagnostics_debounce_ms`
644    /// (was a hardcoded 200 ms stacked on `did_change`'s own sleep — the two are
645    /// now one debounce).
646    async fn schedule_project_diagnostics(&self, root: PathBuf) {
647        let (generation, debounce) = {
648            let mut state = self.state.write().await;
649            let Some(ps) = state.projects.get_mut(&root) else {
650                return;
651            };
652            ps.analysis_generation += 1;
653            (ps.analysis_generation, ps.config.diagnostics_debounce_ms)
654        };
655        let this = self.clone();
656        tokio::spawn(async move {
657            tokio::time::sleep(std::time::Duration::from_millis(debounce)).await;
658            let superseded = match this.state.read().await.projects.get(&root) {
659                Some(ps) => ps.analysis_generation != generation,
660                None => true, // entry pruned — nothing to analyse
661            };
662            if superseded {
663                return;
664            }
665            this.run_project_diagnostics(root).await;
666        });
667    }
668
669    /// Slice F: the single-file counterpart to `schedule_project_diagnostics` —
670    /// a buffer with no project. Bump the URI's generation, sleep the (default)
671    /// configured delay, and run one `diagnose` only if still latest, so a burst
672    /// coalesces to one run (before slice F single-file had no generation and ran
673    /// once per keystroke).
674    async fn schedule_single_file(&self, uri: Url) {
675        let debounce = ProjectConfig::default().diagnostics_debounce_ms;
676        let generation = {
677            let mut state = self.state.write().await;
678            let g = state
679                .single_file_generations
680                .entry(uri.clone())
681                .or_insert(0);
682            *g += 1;
683            *g
684        };
685        let this = self.clone();
686        tokio::spawn(async move {
687            tokio::time::sleep(std::time::Duration::from_millis(debounce)).await;
688            let current = this
689                .state
690                .read()
691                .await
692                .single_file_generations
693                .get(&uri)
694                .copied();
695            if current != Some(generation) {
696                return;
697            }
698            this.diagnose_single_file(&uri).await;
699        });
700    }
701
702    /// Slice F: run `bynk_ide::diagnose` on one buffer and publish — the
703    /// single-file leaf of the scheduler (extracted from `recompile_and_publish`).
704    /// Best-effort: a malformed file produces diagnostics, not a hard failure.
705    async fn diagnose_single_file(&self, uri: &Url) {
706        let (text, version) = {
707            let state = self.state.read().await;
708            match state.docs.get(uri) {
709                Some(d) => (d.text.clone(), d.version),
710                None => return,
711            }
712        };
713        let positions = crate::position::PositionMap::new(&text);
714        let lsp_diags: Vec<Diagnostic> = bynk_ide::diagnose(&text)
715            .into_iter()
716            .map(|d| make_diagnostic(&d, &positions, uri, &ProjectFiles::new()))
717            .collect();
718        self.client
719            .publish_diagnostics(uri.clone(), lsp_diags, Some(version))
720            .await;
721    }
722
723    /// #1667: an analysis round for `root` failed (`reason` says how). Log
724    /// it, and tell the client once per failure streak: the published
725    /// diagnostics are the last good round's and may be stale. The streak ends
726    /// at the next committed round, which clears the flag.
727    async fn report_failed_round(&self, root: &std::path::Path, reason: String) {
728        tracing::error!("analysis of {} {reason}", root.display());
729        let first_failure = {
730            let mut state = self.state.write().await;
731            match state.projects.get_mut(root) {
732                Some(ps) => !std::mem::replace(&mut ps.analysis_failed, true),
733                None => false,
734            }
735        };
736        if first_failure {
737            self.client
738                .show_message(
739                    MessageType::ERROR,
740                    format!(
741                        "Bynk: analysing {} failed with an internal error, so its diagnostics may \
742                         be out of date until a later edit analyses cleanly. Details are in \
743                         ~/.bynk-lsp.log; please report it.",
744                        root.display()
745                    ),
746                )
747                .await;
748        }
749    }
750
751    /// #2081: `root`'s `bynk.schema.lock`, through its project's cache. The
752    /// cache is copied out, refreshed with no `state` lock held (a `stat`,
753    /// and a read only when the file changed), then stored back. A root with
754    /// no project entry gets a one-off read. Never writes the lock.
755    async fn schema_lock_for(&self, root: &std::path::Path) -> bynk_ide::SchemaLock {
756        let mut cache = self
757            .state
758            .read()
759            .await
760            .projects
761            .get(root)
762            .map(|ps| ps.schema_lock.clone())
763            .unwrap_or_default();
764        let lock = cache.current(root);
765        if let Some(ps) = self.state.write().await.projects.get_mut(root) {
766            ps.schema_lock = cache;
767        }
768        lock
769    }
770
771    /// v0.24 (ADR 0052): one project-wide diagnostics round — overlay the
772    /// open buffers over disk, analyse off the async runtime, convert spans
773    /// against the **analysed snapshots**, and publish via the pure
774    /// publish-plan (clears included).
775    async fn run_project_diagnostics(&self, root: PathBuf) {
776        let (round, root, canonical_root, overlay, versions, previously_dirty) = {
777            let mut state = self.state.write().await;
778            // Slice D: the round is for one project's entry. If it was pruned
779            // (its folder removed) between scheduling and now, there is nothing
780            // to analyse — bail.
781            let Some(ps) = state.projects.get_mut(&root) else {
782                return;
783            };
784            ps.analysis_round_started += 1;
785            let round = ps.analysis_round_started;
786            // Slice A: the analysis is rooted at the *project*, not at one
787            // `include` tree, and every path it returns is project-relative
788            // (ADR 0198) — so this is the base the overlay keys against too.
789            let canonical_root = root.canonicalize().unwrap_or_else(|_| root.clone());
790            let previously_dirty = ps.published.clone();
791            let mut overlay = std::collections::HashMap::new();
792            let mut versions = std::collections::HashMap::new();
793            // Every open buffer overlays disk. A buffer belonging to another
794            // project keys to an absolute path outside this root, so it is inert
795            // here — discovery never matches it — and its `versions` entry is
796            // skipped by the `strip_prefix` guard. So the round stays scoped to
797            // this project without filtering the doc set.
798            for (uri, doc) in &state.docs {
799                if let Ok(p) = uri.to_file_path() {
800                    let canonical = p.canonicalize().unwrap_or(p);
801                    // v0.25: capture the version the overlay snapshot came
802                    // from, keyed project-relative like the analysis output.
803                    if let Ok(rel) = canonical.strip_prefix(&canonical_root) {
804                        versions.insert(rel.to_path_buf(), doc.version);
805                    }
806                    overlay.insert(canonical, doc.text.clone());
807                }
808            }
809            (
810                round,
811                root,
812                canonical_root,
813                overlay,
814                versions,
815                previously_dirty,
816            )
817        };
818
819        // Slice A: manifest-aware, multi-root — the same trees `bynk` compiles.
820        let roots = bynk_ide::AnalysisRoots::Project(root.clone());
821        // Content-ownership track (#1086) slice 5: `overlay` above is only the
822        // open buffers — with `discovery.rs`'s disk fallback gone, a project's
823        // closed files need `sweep_project_content`'s full disk sweep too, or
824        // every one of them fails `bynk.project.read_failed` on every round.
825        #[cfg(test)]
826        let inject_panic = self
827            .state
828            .write()
829            .await
830            .projects
831            .get_mut(&root)
832            .is_some_and(|ps| std::mem::take(&mut ps.panic_next_round));
833        // #2081: the committed schema lock, so a non-additive event change is
834        // diagnosed here as `bynk check` diagnoses it.
835        let schema_lock = self.schema_lock_for(&root).await;
836        let memo = self
837            .state
838            .read()
839            .await
840            .projects
841            .get(&root)
842            .map(|ps| Arc::clone(&ps.analysis_memo));
843        let joined = tokio::task::spawn_blocking(move || {
844            #[cfg(test)]
845            if inject_panic {
846                panic!("injected analysis panic");
847            }
848            let content = crate::content::sweep_project_content(&roots, &overlay);
849            analyse_with_memo(&roots, &content, &schema_lock, memo.as_deref())
850        })
851        .await;
852        let result = match joined {
853            Ok(result) => result,
854            Err(e) => {
855                self.report_failed_round(&root, describe_join_error(e))
856                    .await;
857                return;
858            }
859        };
860
861        let mut new_by_uri: std::collections::HashMap<Url, Vec<Diagnostic>> =
862            std::collections::HashMap::new();
863        // Slice B (DECISION C): the document version each file was analysed at,
864        // keyed by URI — so the publish can carry it and the client can drop a
865        // range computed against a buffer it has already edited past. `None` for
866        // a file read from disk (no open buffer, no version).
867        let mut version_by_uri: std::collections::HashMap<Url, Option<i32>> =
868            std::collections::HashMap::new();
869        let mut snapshots = std::collections::HashMap::new();
870        let mut diagnostics: std::collections::HashMap<PathBuf, Vec<bynk_ide::Diagnostic>> =
871            std::collections::HashMap::new();
872        // Spans convert against the snapshot the analysis saw — never a newer
873        // buffer (Settled, v0.24 proposal). Built for every file up front: a
874        // diagnostic's secondary label may lie in a sibling file.
875        let (doc_link_report, mut doc_owner_cache) = {
876            let state = self.state.read().await;
877            (
878                state.doc_link_report,
879                state
880                    .projects
881                    .get(&root)
882                    .map(|ps| ps.doc_owner_cache.clone())
883                    .unwrap_or_default(),
884            )
885        };
886        let files: ProjectFiles<'_> = result
887            .files
888            .iter()
889            .filter_map(|file| {
890                let abs = canonical_root.join(&file.source_path);
891                let abs = abs.canonicalize().unwrap_or(abs);
892                let uri = Url::from_file_path(&abs).ok()?;
893                let positions = crate::position::PositionMap::new(&file.text);
894                Some((file.source_path.clone(), (uri, positions)))
895            })
896            .collect();
897        for file in &result.files {
898            let Some((uri, positions)) = files.get(&file.source_path) else {
899                continue;
900            };
901            let mut diags: Vec<Diagnostic> = file
902                .diagnostics
903                .iter()
904                .map(|d| make_diagnostic(d, positions, uri, &files))
905                .collect();
906            // #2459: the opt-in unresolved-doc-link hint (LSP-only).
907            if doc_link_report != doc_link_hints::Level::Off
908                && let Some(owner_unit) = cached_owner_unit(&mut doc_owner_cache, file)
909            {
910                diags.extend(doc_link_hints::unresolved_link_diagnostics(
911                    &file.text,
912                    &file.source_path,
913                    owner_unit,
914                    &result.index,
915                    &result.doc_scope,
916                    result
917                        .locals
918                        .get(&file.source_path)
919                        .map_or(&[][..], Vec::as_slice),
920                    doc_link_report,
921                ));
922            }
923            version_by_uri.insert(uri.clone(), versions.get(&file.source_path).copied());
924            new_by_uri.insert(uri.clone(), diags);
925            diagnostics.insert(file.source_path.clone(), file.diagnostics.clone());
926            snapshots.insert(file.source_path.clone(), file.text.clone());
927        }
928        let result_paths: std::collections::HashSet<PathBuf> =
929            result.files.iter().map(|f| f.source_path.clone()).collect();
930        // v0.25: retain the round's index + snapshots for references/rename
931        // and the binding-correct definition/hover. v0.26: plus the raw
932        // diagnostics, for `codeAction` (the suggestions ride on them).
933        {
934            let analysis = Arc::new(Analysis {
935                project_root: canonical_root.clone(),
936                index: result.index.clone(),
937                snapshots,
938                versions,
939                diagnostics,
940                hints: result.hints,
941                requirements: result.requirements,
942                capability_paths: result.capability_paths,
943                locals: result.locals,
944                expr_types: result.expr_types,
945                ty_intern: result.ty_intern,
946                unit_sources: result.unit_sources,
947                sequence_info: result.sequence_info,
948                architecture_facts: result.architecture_facts,
949                boundary_info: result.boundary_info,
950                doc_scope: result.doc_scope,
951                contract_diff: result.contract_diff,
952            });
953            let mut state = self.state.write().await;
954            let Some(ps) = state.projects.get_mut(&root) else {
955                return; // pruned mid-round
956            };
957            // Completion order is not start order: a slow old round finishing
958            // after a newer one must be dropped, not committed (#513).
959            if ps.analysis_round_committed >= round {
960                return;
961            }
962            ps.analysis_round_committed = round;
963            ps.analysis_failed = false;
964            // Keep only the files this round saw, so the cache cannot grow with
965            // deleted files.
966            doc_owner_cache.retain(|path, _| result_paths.contains(path));
967            ps.doc_owner_cache = doc_owner_cache;
968            ps.analysis = Some(analysis);
969        }
970        // Project-level diagnostics with no single owning file surface at
971        // position 0:0 rather than vanishing — on `bynk.toml` when it exists,
972        // else (#485, implicit `src/` mode has no manifest) on the first
973        // analysed file, so they anchor to a real, openable document.
974        let unattributed_anchor = {
975            let toml = root.join("bynk.toml");
976            if toml.is_file() {
977                Url::from_file_path(toml).ok()
978            } else {
979                result.files.first().and_then(|f| {
980                    let abs = canonical_root.join(&f.source_path);
981                    let abs = abs.canonicalize().unwrap_or(abs);
982                    Url::from_file_path(abs).ok()
983                })
984            }
985        };
986        if !result.unattributed.is_empty()
987            && let Some(anchor_uri) = unattributed_anchor
988        {
989            let entry = new_by_uri.entry(anchor_uri).or_default();
990            for d in &result.unattributed {
991                entry.push(Diagnostic {
992                    range: Default::default(),
993                    severity: Some(match d.severity {
994                        bynk_syntax::Severity::Error => DiagnosticSeverity::ERROR,
995                        bynk_syntax::Severity::Warning => DiagnosticSeverity::WARNING,
996                        bynk_syntax::Severity::Hint => DiagnosticSeverity::HINT,
997                    }),
998                    code: Some(tower_lsp::lsp_types::NumberOrString::String(
999                        d.error.category.to_string(),
1000                    )),
1001                    message: d.error.message.clone(),
1002                    ..Default::default()
1003                });
1004            }
1005        }
1006
1007        let (publishes, dirty) = publish::publish_plan(&previously_dirty, new_by_uri);
1008        for (uri, diags) in publishes {
1009            // Slice B (DECISION C): stamp the publish with the version the round
1010            // analysed this file at (was `None`), so a client can reject a range
1011            // its buffer has moved past. A clearing publish for a now-absent file
1012            // carries no version — it has no entry in `version_by_uri`.
1013            let version = version_by_uri.get(&uri).copied().flatten();
1014            self.client.publish_diagnostics(uri, diags, version).await;
1015        }
1016        let still_current = {
1017            let mut state = self.state.write().await;
1018            if let Some(ps) = state.projects.get_mut(&root)
1019                && ps.analysis_round_committed == round
1020            {
1021                ps.published = dirty;
1022                true
1023            } else {
1024                false
1025            }
1026        };
1027        // #733: revalidate. Pull-based decorations are served from the committed
1028        // round (`committed_analysis`) without a forced re-analysis, so a fresh
1029        // round is invisible to the client until it re-pulls. Nudge it to — but
1030        // only for this round if a newer one has not already superseded it (that
1031        // one sends its own nudge), and only for decorations the client can
1032        // refresh. Fired on a detached task: `run_project_diagnostics` also runs
1033        // on the *request* path (a cursor request's forced refresh), and a
1034        // `workspace/*/refresh` awaits a client round-trip — spawning keeps that
1035        // off the request's critical path. Best-effort: a failed nudge just
1036        // leaves the client on the previous pull until its next request.
1037        if still_current {
1038            let refresh = self.state.read().await.supports_refresh;
1039            if refresh.semantic_tokens || refresh.inlay_hints || refresh.code_lens {
1040                let client = self.client.clone();
1041                tokio::spawn(async move {
1042                    if refresh.semantic_tokens {
1043                        let _ = client.semantic_tokens_refresh().await;
1044                    }
1045                    if refresh.inlay_hints {
1046                        let _ = client.inlay_hint_refresh().await;
1047                    }
1048                    if refresh.code_lens {
1049                        let _ = client.code_lens_refresh().await;
1050                    }
1051                });
1052            }
1053        }
1054    }
1055
1056    /// Slice A: the analysis roots for the project that owns `uri` — the
1057    /// manifest's, resolved by the compiler's own discovery. `None` in
1058    /// single-file mode (no project root), where cross-file lookups are skipped.
1059    /// Slice D: routes by URI (Q4), so a completion in project B enumerates B's
1060    /// units, not the first project's.
1061    ///
1062    /// Replaces `project_src_root`, which returned `root.join(config.src_dir)`:
1063    /// one tree, chosen by reducing `[paths] include` to its first entry and
1064    /// ignoring `exclude`. That reduction is the defect slice A removed.
1065    async fn analysis_roots_for(&self, uri: &Url) -> Option<bynk_ide::AnalysisRoots> {
1066        Some(bynk_ide::AnalysisRoots::Project(
1067            self.root_for_uri(uri).await?,
1068        ))
1069    }
1070
1071    /// Content-ownership track (#1086): the owning project's `.bynk` files
1072    /// as a pre-read `(path, content)` map — every open buffer's **live**
1073    /// text, a real disk read for everything else `bynk_ide::discover_files`
1074    /// names. `None` in single-file mode. Backs completion, signature help
1075    /// (slice 0), and the cross-file symbol lookups (slice 1) — this is now
1076    /// the sole enumeration entry point; the bare-paths `project_files` it
1077    /// replaced (slice 0's `Backend::project_files`) was deleted once slice 1
1078    /// migrated its last two callers.
1079    ///
1080    /// Finding #62's exclusion carries over unchanged from `project_files`:
1081    /// the cursor's own file is filtered out here, once, for every caller —
1082    /// `bynk-ide`'s completion helpers already parse it fresh from the live
1083    /// buffer (`for_each_unit`'s `doc_text`), so leaving it in the map would
1084    /// offer a second, stale version of the same file alongside the live one.
1085    async fn project_content(
1086        &self,
1087        uri: &Url,
1088    ) -> Option<Arc<std::collections::HashMap<PathBuf, String>>> {
1089        let roots = self.analysis_roots_for(uri).await?;
1090        let current = uri
1091            .to_file_path()
1092            .ok()
1093            .and_then(|p| std::fs::canonicalize(&p).ok());
1094        let overlay = {
1095            let state = self.state.read().await;
1096            let mut ov = std::collections::HashMap::new();
1097            for (u, doc) in &state.docs {
1098                if let Ok(p) = u.to_file_path() {
1099                    let canonical = p.canonicalize().unwrap_or(p);
1100                    ov.insert(canonical, doc.text.clone());
1101                }
1102            }
1103            ov
1104        };
1105        tokio::task::spawn_blocking(move || {
1106            let mut content = crate::content::sweep_project_content(&roots, &overlay);
1107            if let Some(current) = current {
1108                content.remove(&current);
1109            }
1110            // `Arc`, not an owned map: a caller that needs to move this into
1111            // its own `spawn_blocking` closure (signature help fires on every
1112            // `(`/`,`) clones a refcount, not every project file's content.
1113            Arc::new(content)
1114        })
1115        .await
1116        .map_err(|e| tracing::error!("project content sweep {}", describe_join_error(e)))
1117        .ok()
1118    }
1119
1120    /// v0.31: the def + use spans of the local under the cursor (def first), or
1121    /// `None` if the cursor is not on a local.
1122    fn local_sites(
1123        &self,
1124        analysis: &Analysis,
1125        rel: &std::path::Path,
1126        offset: usize,
1127    ) -> Option<Vec<bynk_syntax::span::Span>> {
1128        let text = analysis.snapshots.get(rel)?;
1129        let locals = analysis.locals.get(rel)?;
1130        crate::locals_nav::local_sites_at(locals, text, offset)
1131    }
1132
1133    /// v0.31 (ADR 0064): the in-scope local bindings at the cursor, as
1134    /// `variable` completions, read from the **cached** analysis — so they
1135    /// survive the mid-edit buffer the current keystroke produced (the last
1136    /// good round's bindings around the cursor are what's wanted). Positions
1137    /// convert against the cached snapshot, like the other cached-round reads.
1138    async fn locals_completions(&self, uri: &Url, pos: Position) -> Vec<CompletionItem> {
1139        // Slice B: completion's locals sub-path resolves `pos` against the
1140        // round's snapshot (like `index_position`), so it refreshes too — the
1141        // one exposed reader the §4.2 table missed.
1142        let analysis = self.analysis_for(uri).await;
1143        let Some(analysis) = analysis else {
1144            return Vec::new();
1145        };
1146        let Some(rel) = Self::uri_to_rel(&analysis, uri) else {
1147            return Vec::new();
1148        };
1149        let (Some(text), Some(locals)) = (analysis.snapshots.get(&rel), analysis.locals.get(&rel))
1150        else {
1151            return Vec::new();
1152        };
1153        let Some(offset) = crate::position::position_to_offset(text, pos) else {
1154            return Vec::new();
1155        };
1156        bynk_check::locals::locals_at(locals, offset)
1157            .into_iter()
1158            .map(|b| CompletionItem {
1159                label: b.name.clone(),
1160                kind: Some(CompletionItemKind::VARIABLE),
1161                detail: Some(b.ty.clone()),
1162                ..Default::default()
1163            })
1164            .collect()
1165    }
1166
1167    /// Convert same-file local spans to LSP `Location`s.
1168    fn local_locations(
1169        &self,
1170        analysis: &Analysis,
1171        rel: &std::path::Path,
1172        spans: &[bynk_syntax::span::Span],
1173    ) -> Vec<Location> {
1174        let Some(text) = analysis.snapshots.get(rel) else {
1175            return Vec::new();
1176        };
1177        let Ok(uri) = Url::from_file_path(analysis.project_root.join(rel)) else {
1178            return Vec::new();
1179        };
1180        spans
1181            .iter()
1182            .map(|s| Location {
1183                uri: uri.clone(),
1184                range: crate::position::span_to_range(text, *s),
1185            })
1186            .collect()
1187    }
1188
1189    /// Slice 3 (ADR 0063): complete the members of a typed **value** receiver.
1190    /// Re-analyses the buffer rewritten so the receiver parses (the trailing
1191    /// `.partial` dropped), types the receiver via the retained `expr_types`,
1192    /// and maps its type to kernel methods + record fields. Silent (not
1193    /// necessarily empty — see below) when the receiver itself has no
1194    /// recorded type; an error elsewhere in the file no longer silences it
1195    /// (ADR 0094's partial types lifted the clean-file ceiling).
1196    ///
1197    /// #596: additionally merges a bare `store` field receiver's own
1198    /// vocabulary (entry ops, and for `Map` the `.entries`/`.keys`/`.values`
1199    /// accessors) — dispatched by receiver *provenance* in the checker, which
1200    /// the typed `ty` alone can't distinguish from an ordinary `Query`-typed
1201    /// local (a bare store `Map` widens to `Ty::Query` too, ADR 0120). This
1202    /// half runs **independently of whether `type_receiver` succeeded**: it
1203    /// re-parses the buffer itself and needs no typed `ty` at all, so a `store`
1204    /// field still offers its entry ops/accessors even when the receiver goes
1205    /// untyped. (Its original motivation — an unresolved name *elsewhere* in
1206    /// the file bailing the checker before it ran, the one clean-file-ceiling
1207    /// gap ADR 0094 didn't close — has gone since #1663 let the checker run
1208    /// past a resolve error.) A review on #812 flagged the earlier draft's
1209    /// single early return as undercutting that motivation.
1210    async fn value_member_completions(
1211        &self,
1212        uri: &Url,
1213        text: &str,
1214        offset: usize,
1215    ) -> Vec<CompletionItem> {
1216        let Some((rewritten, recv_offset)) = completion::value_receiver_rewrite(text, offset)
1217        else {
1218            return Vec::new();
1219        };
1220        let mut items: Vec<CompletionItem> = Vec::new();
1221        if let Some((ty, tys)) = self
1222            .type_receiver(uri, rewritten.clone(), recv_offset)
1223            .await
1224        {
1225            let files = self.project_content(uri).await;
1226            items.extend(
1227                completion::value_member_candidates(ty, &tys, text, files.as_deref())
1228                    .into_iter()
1229                    .map(to_completion_item),
1230            );
1231        }
1232        // #2138: `run.id`, when `run` is the test run (it has no type then).
1233        if items.is_empty() {
1234            items.extend(
1235                completion::run_id_member_candidates(&rewritten, recv_offset)
1236                    .into_iter()
1237                    .map(to_completion_item),
1238            );
1239        }
1240        let locals = self.fast_path_locals(uri, &rewritten).await;
1241        items.extend(
1242            completion::store_field_member_candidates(&rewritten, recv_offset, &locals)
1243                .into_iter()
1244                .map(to_completion_item),
1245        );
1246        items
1247    }
1248
1249    /// #596: the current analysed round's locals for `uri`, only when its
1250    /// snapshot exactly matches `rewritten` — the same fast-path match
1251    /// [`Self::type_receiver`] uses. Empty (rather than forcing a synchronous
1252    /// re-analysis) when the round is stale or absent, so the store-field
1253    /// shadowing check degrades to "no local shadows the name".
1254    async fn fast_path_locals(
1255        &self,
1256        uri: &Url,
1257        rewritten: &str,
1258    ) -> Vec<bynk_check::locals::LocalBinding> {
1259        let Some(analysis) = self.project_analysis_for(uri).await else {
1260            return Vec::new();
1261        };
1262        let Some(rel) = Self::uri_to_rel(&analysis, uri) else {
1263            return Vec::new();
1264        };
1265        if analysis.snapshots.get(&rel).map(String::as_str) != Some(rewritten) {
1266            return Vec::new();
1267        }
1268        analysis.locals.get(&rel).cloned().unwrap_or_default()
1269    }
1270
1271    /// v0.124 (slice 3): at `<expr> is <cursor>`, the scrutinee sum type's
1272    /// variants. The scrutinee is typed via `expr_types` (re-analysing through
1273    /// `type_receiver`, the value-member path), so it is subject to the clean-
1274    /// file ceiling and goes silent — never wrong — on a broken buffer.
1275    async fn is_pattern_completions(
1276        &self,
1277        uri: &Url,
1278        text: &str,
1279        offset: usize,
1280    ) -> Vec<CompletionItem> {
1281        let Some(scrut_off) = is_scrutinee_offset(text, offset) else {
1282            return Vec::new();
1283        };
1284        self.scrutinee_variant_completions(uri, text, scrut_off)
1285            .await
1286    }
1287
1288    /// v0.128: at an arm-pattern-start inside a `match <expr> { … }`, the
1289    /// scrutinee sum type's variants — the deferred half of slice 3's
1290    /// `is`-pattern completion, sharing its scrutinee typing and candidate set.
1291    async fn match_arm_completions(
1292        &self,
1293        uri: &Url,
1294        text: &str,
1295        offset: usize,
1296    ) -> Vec<CompletionItem> {
1297        let Some(scrut_off) = match_scrutinee_offset(text, offset) else {
1298            return self.let_else_match_completions(uri, text, offset).await;
1299        };
1300        self.scrutinee_variant_completions(uri, text, scrut_off)
1301            .await
1302    }
1303
1304    /// #2010: at an arm-pattern-start inside `let <pattern> (= | <-) <value>
1305    /// else match { … }`, the variants of the value's type (its `Effect`
1306    /// payload for `<-`) that the `let` pattern leaves for the arms to cover.
1307    async fn let_else_match_completions(
1308        &self,
1309        uri: &Url,
1310        text: &str,
1311        offset: usize,
1312    ) -> Vec<CompletionItem> {
1313        let Some(head) = let_else_match_head(text, offset) else {
1314            return Vec::new();
1315        };
1316        // Just past the value's last character: an offset *on* it would also
1317        // sit at the end of its innermost sub-expression (the `o` in
1318        // `Effect.pure(o)`), which `type_at_offset` prefers as the smaller span.
1319        let Some((ty, tys)) = self
1320            .type_receiver(uri, text.to_string(), head.value_end + 1)
1321            .await
1322        else {
1323            return Vec::new();
1324        };
1325        let ty = if head.effectful {
1326            match &*tys.get(ty) {
1327                bynk_check::checker::Ty::Effect(inner) => *inner,
1328                _ => return Vec::new(),
1329            }
1330        } else {
1331            ty
1332        };
1333        let files = self.project_content(uri).await;
1334        completion::variants_for_ty(ty, &tys, text, files.as_deref())
1335            .into_iter()
1336            .filter(|c| head.covered.as_deref() != Some(c.label.as_str()))
1337            .map(to_completion_item)
1338            .collect()
1339    }
1340
1341    /// The variants of the scrutinee whose last character is at `scrut_off` — the
1342    /// shared tail of `is`/`match` pattern completion. Types the scrutinee via
1343    /// `expr_types` (ADR 0094's partial types on a broken buffer; silent when
1344    /// the scrutinee itself has no recorded type) and offers its variants;
1345    /// empty for a non-sum, non-`Result`/`Option`
1346    /// scrutinee. v0.145 (ADR 0169): `Result`/`Option` scrutinees now fire too
1347    /// (`variants_for_ty`), not only user-declared sums.
1348    async fn scrutinee_variant_completions(
1349        &self,
1350        uri: &Url,
1351        text: &str,
1352        scrut_off: usize,
1353    ) -> Vec<CompletionItem> {
1354        let Some((ty, tys)) = self.type_receiver(uri, text.to_string(), scrut_off).await else {
1355            return Vec::new();
1356        };
1357        let files = self.project_content(uri).await;
1358        completion::variants_for_ty(ty, &tys, text, files.as_deref())
1359            .into_iter()
1360            .map(to_completion_item)
1361            .collect()
1362    }
1363
1364    /// v0.145 (ADR 0169): at `OuterVariant(‸` inside a match arm-pattern, the
1365    /// payload field type's variants — e.g. `Ok`/`Err` inside `Some(‸)` on an
1366    /// `Option[Result[…]]` scrutinee. `match_scrutinee_offset` deliberately bails
1367    /// on a nested constructor; `nested_pattern_offset` targets exactly it,
1368    /// yielding the scrutinee offset and the outer variant. Types the scrutinee
1369    /// via the same `type_receiver` path and resolves the payload type.
1370    async fn nested_pattern_completions(
1371        &self,
1372        uri: &Url,
1373        text: &str,
1374        offset: usize,
1375    ) -> Vec<CompletionItem> {
1376        let Some((scrut_off, variant)) = nested_pattern_offset(text, offset) else {
1377            return Vec::new();
1378        };
1379        let Some((ty, tys)) = self.type_receiver(uri, text.to_string(), scrut_off).await else {
1380            return Vec::new();
1381        };
1382        let files = self.project_content(uri).await;
1383        completion::nested_variant_completions(ty, &tys, &variant, text, files.as_deref())
1384            .into_iter()
1385            .map(to_completion_item)
1386            .collect()
1387    }
1388
1389    /// v0.32 (ADR 0065): the type of a receiver expression at `recv_offset` in a
1390    /// buffer `rewritten` so it parses — re-analyse the overlay and query the
1391    /// retained `expr_types`. Shared by value-member completion and signature
1392    /// help; `None` when the receiver has no recorded type. A file with errors
1393    /// elsewhere still types it (ADR 0094's best-effort partial types).
1394    async fn type_receiver(
1395        &self,
1396        uri: &Url,
1397        rewritten: String,
1398        recv_offset: usize,
1399    ) -> Option<(
1400        bynk_check::checker::TyId,
1401        std::sync::Arc<bynk_check::checker::Types>,
1402    )> {
1403        // T3.6b (R4.1): the id is meaningless without the table it was minted
1404        // from, so both travel together — the round's own table on the fast
1405        // path, the fresh re-analysis's on the slow one.
1406        let roots = self.analysis_roots_for(uri).await?;
1407        let project_root = roots.project_root().to_path_buf();
1408        let canonical_root = project_root
1409            .canonicalize()
1410            .unwrap_or_else(|_| project_root.clone());
1411        let cur = uri.to_file_path().ok()?;
1412        let cur = cur.canonicalize().unwrap_or(cur);
1413        // Slice A: project-relative, matching the round's identity (ADR 0198).
1414        let rel = cur.strip_prefix(&canonical_root).ok()?.to_path_buf();
1415        // Overlay every open doc, with this one rewritten so it parses.
1416        let overlay = {
1417            let state = self.state.read().await;
1418            let mut ov = std::collections::HashMap::new();
1419            for (u, doc) in &state.docs {
1420                if let Ok(p) = u.to_file_path() {
1421                    let canonical = p.canonicalize().unwrap_or(p);
1422                    let t = if u == uri {
1423                        rewritten.clone()
1424                    } else {
1425                        doc.text.clone()
1426                    };
1427                    ov.insert(canonical, t);
1428                }
1429            }
1430            ov
1431        };
1432        // Fast path (#513): completion fires on every `.` keystroke, and the
1433        // rewritten buffer (the trailing `.`-segment removed so it parses) is
1434        // usually byte-identical to the snapshot the last debounced round
1435        // analysed. Reuse that round's expression types instead of running a
1436        // synchronous whole-project re-analysis on the request path.
1437        if let Some(analysis) = self.project_analysis_for(uri).await
1438            && analysis.snapshots.get(&rel).map(String::as_str) == Some(rewritten.as_str())
1439            && let Some((_, entries)) = analysis.expr_types.iter().find(|(p, _)| **p == rel)
1440        {
1441            return bynk_check::expr_types::type_at_offset(
1442                entries,
1443                recv_offset,
1444                &analysis.ty_intern,
1445            )
1446            .map(|t| (t, std::sync::Arc::clone(&analysis.ty_intern)));
1447        }
1448        // Content-ownership track (#1086) slice 5: same complete-content
1449        // requirement as `run_project_diagnostics` — `overlay` here is only
1450        // the open buffers, and `discovery.rs`'s disk fallback is gone.
1451        // #2081: `Off` — this re-analysis only reads expression types, which
1452        // the schema lock cannot change, so it skips the event sweep.
1453        let result = tokio::task::spawn_blocking(move || {
1454            let content = crate::content::sweep_project_content(&roots, &overlay);
1455            bynk_ide::diagnose_project_with(&roots, &content, &bynk_ide::SchemaLock::Off)
1456        })
1457        .await
1458        .map_err(|e| tracing::error!("receiver-typing analysis {}", describe_join_error(e)))
1459        .ok()?;
1460        let (_, entries) = result.expr_types.iter().find(|(p, _)| **p == rel)?;
1461        bynk_check::expr_types::type_at_offset(entries, recv_offset, &result.ty_intern)
1462            .map(|t| (t, std::sync::Arc::clone(&result.ty_intern)))
1463    }
1464
1465    /// Slice D: the committed analysis for one project root, ungated — the raw
1466    /// last round, or `None` if the root has no entry or has not analysed yet.
1467    async fn project_analysis(&self, root: &std::path::Path) -> Option<Arc<Analysis>> {
1468        self.state.read().await.projects.get(root)?.analysis.clone()
1469    }
1470
1471    /// The owning project's committed analysis for `uri`, ungated. For callers
1472    /// that reuse a round opportunistically (completion's receiver-typing fast
1473    /// path); the freshness gate is [`Self::analysis_for`].
1474    async fn project_analysis_for(&self, uri: &Url) -> Option<Arc<Analysis>> {
1475        let root = self.root_for_uri(uri).await?;
1476        self.project_analysis(&root).await
1477    }
1478
1479    /// Ensure `root` has an entry (created with `config` if absent) and a
1480    /// committed analysis (one round run if none yet), and return it. For the
1481    /// cross-project workspace-symbol scan, which must answer over every project
1482    /// including ones no request has warmed. `None` if the round produced none.
1483    async fn ensure_project_analysed(
1484        &self,
1485        root: PathBuf,
1486        config: ProjectConfig,
1487    ) -> Option<Arc<Analysis>> {
1488        {
1489            let mut state = self.state.write().await;
1490            state
1491                .projects
1492                .entry(root.clone())
1493                .or_insert_with(|| ProjectState {
1494                    config,
1495                    ..Default::default()
1496                });
1497        }
1498        if let Some(a) = self.project_analysis(&root).await {
1499            return Some(a);
1500        }
1501        self.refresh_now(root.clone()).await;
1502        self.project_analysis(&root).await
1503    }
1504
1505    /// Slice D (Q4 lifecycle): drop every project no longer reachable from a
1506    /// workspace folder **and** holding no open buffer, clearing its published
1507    /// diagnostics. A project is retained while some remaining folder relates to
1508    /// it (one is a path-prefix of the other — a file under that folder can still
1509    /// route to the root) or while any open buffer routes to it. Shared by the
1510    /// two events that can orphan a project: a folder leaving
1511    /// (`did_change_workspace_folders`) and its last buffer closing (`did_close`)
1512    /// — a project falls only when *both* its seed and its buffers are gone.
1513    /// Returns the URIs whose diagnostics were cleared so the caller can publish
1514    /// the clears (done outside the lock).
1515    async fn prune_orphaned_projects(&self) -> Vec<Url> {
1516        // #733: `root_for_uri_uncached` canonicalises and walks the filesystem
1517        // up to a `bynk.toml` for every open buffer — syscalls that must not run
1518        // while holding `state.write()`. Snapshot the inputs under a short read
1519        // lock, resolve the open roots off the lock, then take the write lock
1520        // only to mutate `projects`.
1521        //
1522        // #682 (DECISION B): this stays on the *uncached* router rather than
1523        // `root_for_uri` — pruning is not hot (it fires only on folder-removal
1524        // or close), and it runs inside a synchronous `filter_map` off the
1525        // lock, where an async, cache-consulting router can't be called inline
1526        // without either re-locking `state` here (defeating the point of
1527        // computing `open_roots` off-lock) or restructuring this into an async
1528        // stream. This opens a small TOCTOU window: `orphaned` is
1529        // computed against live `state.projects` under the write lock but against
1530        // the *snapshot's* `folders`/`open_roots`, so a `did_open` that lands in
1531        // between — newly covering a root — is not yet in `open_roots` and that
1532        // root could be pruned here. It is self-healing: the pruning callers
1533        // (`did_close`, `did_change_workspace_folders`) only ever *remove*
1534        // coverage, so a racing `did_open` re-creates the entry the moment that
1535        // buffer routes/analyses (`schedule_diagnostics` → a lazily-created
1536        // `ProjectState`) — its diagnostics clear-then-repopulate, never a
1537        // permanently-dropped project.
1538        let (folders, open_uris) = {
1539            let state = self.state.read().await;
1540            (
1541                state.folders.clone(),
1542                state.docs.keys().cloned().collect::<Vec<_>>(),
1543            )
1544        };
1545        let open_roots: std::collections::HashSet<PathBuf> = open_uris
1546            .iter()
1547            .filter_map(Self::root_for_uri_uncached)
1548            .collect();
1549        let covered = |root: &std::path::Path| {
1550            folders
1551                .iter()
1552                .any(|f| f.starts_with(root) || root.starts_with(f))
1553                || open_roots.contains(root)
1554        };
1555        let mut state = self.state.write().await;
1556        let orphaned: Vec<PathBuf> = state
1557            .projects
1558            .keys()
1559            .filter(|r| !covered(r))
1560            .cloned()
1561            .collect();
1562        let mut to_clear = Vec::new();
1563        for root in orphaned {
1564            if let Some(ps) = state.projects.remove(&root) {
1565                to_clear.extend(ps.published);
1566            }
1567        }
1568        to_clear
1569    }
1570
1571    /// Slice E: discover and warm every project under `folders` — create each
1572    /// entry (idempotent, keyed by canonical root) and schedule its round — so a
1573    /// workspace shows diagnostics without a file being opened. Non-blocking:
1574    /// entries are created synchronously (routing is immediately correct) and the
1575    /// rounds run on the debounce path. Shared by `initialized` (all folders) and
1576    /// the `did_change_workspace_folders` added branch (the new folders).
1577    async fn warm_projects(&self, folders: &[PathBuf]) {
1578        if folders.is_empty() {
1579            return;
1580        }
1581        // Discover off the lock **and** off the executor: the walk is synchronous
1582        // FS I/O, so run it on a blocking thread rather than stalling an async
1583        // worker while a workspace tree is scanned.
1584        let folders = folders.to_vec();
1585        let roots = tokio::task::spawn_blocking(move || {
1586            let mut roots: Vec<PathBuf> = Vec::new();
1587            for folder in &folders {
1588                for root in Self::discover_projects_under(folder) {
1589                    if !roots.contains(&root) {
1590                        roots.push(root);
1591                    }
1592                }
1593            }
1594            roots
1595        })
1596        .await
1597        .unwrap_or_else(|e| {
1598            tracing::error!("project discovery {}", describe_join_error(e));
1599            Vec::new()
1600        });
1601        for root in roots {
1602            let config = project::load_config(&root).unwrap_or_default();
1603            {
1604                let mut state = self.state.write().await;
1605                state
1606                    .projects
1607                    .entry(root.clone())
1608                    .or_insert_with(|| ProjectState {
1609                        config,
1610                        ..Default::default()
1611                    });
1612            }
1613            self.schedule_project_diagnostics(root).await;
1614        }
1615    }
1616
1617    /// Slice E: register the `workspace/didChangeWatchedFiles` capability with
1618    /// the client — once, with folder-independent globs (`**/*.bynk`,
1619    /// `**/bynk.toml`, and since #2081 `**/bynk.schema.lock`), per Q4 (ADR
1620    /// 0204 §D). So a client that supports dynamic
1621    /// registration is notified of source and manifest changes without watching
1622    /// files itself. Best-effort: a registration failure is logged, not fatal.
1623    async fn register_file_watchers(&self) {
1624        use tower_lsp::lsp_types::{
1625            DidChangeWatchedFilesRegistrationOptions, FileSystemWatcher, GlobPattern,
1626        };
1627        let watchers = [
1628            "**/*.bynk",
1629            "**/bynk.toml",
1630            "**/bynk.schema.lock",
1631            // #2841: a suite `fixture` reads from `fixtures/`.
1632            "**/fixtures/**",
1633        ]
1634        .into_iter()
1635        .map(|g| FileSystemWatcher {
1636            glob_pattern: GlobPattern::String(g.to_string()),
1637            kind: None, // create | change | delete
1638        })
1639        .collect();
1640        let registration = Registration {
1641            id: "bynk-watched-files".to_string(),
1642            method: "workspace/didChangeWatchedFiles".to_string(),
1643            register_options: serde_json::to_value(DidChangeWatchedFilesRegistrationOptions {
1644                watchers,
1645            })
1646            .ok(),
1647        };
1648        if let Err(e) = self.client.register_capability(vec![registration]).await {
1649            self.client
1650                .log_message(
1651                    MessageType::WARNING,
1652                    format!("bynk-lsp: file-watcher registration failed: {e}"),
1653                )
1654                .await;
1655        }
1656    }
1657
1658    /// Register `textDocument/prepareTypeHierarchy` for Bynk documents. A
1659    /// client that does not accept dynamic registration gets no type hierarchy.
1660    async fn register_type_hierarchy(&self) {
1661        let registration = Registration {
1662            id: "bynk-type-hierarchy".to_string(),
1663            method: "textDocument/prepareTypeHierarchy".to_string(),
1664            register_options: Some(serde_json::json!({
1665                "documentSelector": [{ "language": "bynk" }],
1666            })),
1667        };
1668        if let Err(e) = self.client.register_capability(vec![registration]).await {
1669            self.client
1670                .log_message(
1671                    MessageType::WARNING,
1672                    format!("bynk-lsp: type-hierarchy registration failed: {e}"),
1673                )
1674                .await;
1675        }
1676    }
1677
1678    /// The `bynk.toml` config governing `uri` — its project's, or the default
1679    /// (single-file mode). Backs the per-file diagnostics mode/debounce and the
1680    /// formatting options, which now differ by project.
1681    async fn config_for(&self, uri: &Url) -> ProjectConfig {
1682        let Some(root) = self.root_for_uri(uri).await else {
1683            return ProjectConfig::default();
1684        };
1685        self.state
1686            .read()
1687            .await
1688            .projects
1689            .get(&root)
1690            .map(|p| p.config.clone())
1691            .unwrap_or_default()
1692    }
1693
1694    /// Slice B — the freshness contract (Q3, settled #663). The analysis a
1695    /// request must answer from, **current for `uri`**: cold start triggers a
1696    /// round; a round that predates `uri`'s buffer triggers a refresh.
1697    ///
1698    /// The client's request position refers to `uri`'s current document
1699    /// version — messages are ordered, so `docs[uri].version` reflects every
1700    /// `didChange` sent before the request. The returned analysis is guaranteed
1701    /// to have analysed *that* version of `uri`, so `position_to_offset` against
1702    /// its snapshot is never resolved against text the user edited past.
1703    ///
1704    /// Slice D: routes to the project that owns `uri` (Q4) before gating, so the
1705    /// freshness check is against *that* project's round. A file under no
1706    /// project (single-file mode) is never index-answerable — decline.
1707    ///
1708    /// Returns `None` — decline, per Q3 — only when the request cannot be
1709    /// answered at the version the client holds: single-file mode (no project),
1710    /// a file outside every `include` root (never a snapshot key), or a
1711    /// concurrent edit that moved past the refresh (rare; the next request is
1712    /// current). Never returns an analysis whose snapshot for `uri` is stale.
1713    async fn analysis_for(&self, uri: &Url) -> Option<Arc<Analysis>> {
1714        let root = self.root_for_uri(uri).await?;
1715        // The version the request's position is stated against. `None` when the
1716        // file is not an open buffer — then any round is as authoritative as it
1717        // gets (nothing newer to be stale against), so the freshness gate is a
1718        // no-op and only cold start matters.
1719        let want = self.state.read().await.docs.get(uri).map(|d| d.version);
1720        let current = |a: &Arc<Analysis>| {
1721            let Some(rel) = Self::uri_to_rel(a, uri) else {
1722                return false; // unmappable URI — cannot be answered
1723            };
1724            // The file must actually be *analysed* (a snapshot key), not merely
1725            // have a version entry: `versions` is built from open docs, so a
1726            // file open but outside every `include` root has a version and no
1727            // snapshot. Such a file is never answerable — decline.
1728            if !a.snapshots.contains_key(&rel) {
1729                return false;
1730            }
1731            match want {
1732                // Open buffer: the analysed snapshot must be at the client's
1733                // version, or the position resolves against text edited past.
1734                Some(v) => a.versions.get(&rel) == Some(&v),
1735                // Not an open buffer (a closed/disk file, e.g. a goto target):
1736                // the analysed round is authoritative — nothing newer to lag.
1737                None => true,
1738            }
1739        };
1740
1741        if let Some(a) = self.project_analysis(&root).await
1742            && current(&a)
1743        {
1744            return Some(a);
1745        }
1746
1747        // Refresh. The lock serialises concurrent requests: the first runs the
1748        // round, the rest wait and then find it already current below — so N
1749        // requests after one edit share one round, not N. (One lock across all
1750        // projects is fine — a refresh holds it only across its own round.)
1751        let _guard = self.refresh_lock.lock().await;
1752        if let Some(a) = self.project_analysis(&root).await
1753            && current(&a)
1754        {
1755            return Some(a);
1756        }
1757        self.refresh_now(root.clone()).await;
1758        let a = self.project_analysis(&root).await?;
1759        // Strict: only answer if the fresh round is actually current for `uri`.
1760        // An edit that landed during the round leaves us behind — decline, and
1761        // the next request refreshes again. Never a position against stale text.
1762        current(&a).then_some(a)
1763    }
1764
1765    /// #733 — the non-refreshing gate for **pull-based decoration requests**
1766    /// (`semanticTokens`, `inlayHint`, `codeLens`, `documentLink`, `codeAction`).
1767    /// Returns the last committed round for `uri`'s project **as-is**, without
1768    /// forcing a synchronous re-analysis on the request path.
1769    ///
1770    /// Why this is safe where [`Self::analysis_for`] is not: these handlers
1771    /// resolve nothing against the client's *live* cursor — every range and span
1772    /// they emit converts against the round's own `snapshots` (or, for
1773    /// `document_link`, against live text plus the project-level `unit_sources`
1774    /// map). So a committed round lagging the buffer by at most one debounce
1775    /// cycle is internally consistent; the strict version match `analysis_for`
1776    /// demands is stronger than a decoration needs. The editor auto-fires these
1777    /// on every `didChange`, so forcing a whole-project round here is exactly
1778    /// what defeated the debounce (#733).
1779    ///
1780    /// This is stale-while-revalidate: serve the committed round now; the
1781    /// already-scheduled debounce round is the revalidation, and on its commit
1782    /// [`Self::run_project_diagnostics`] nudges the client to re-pull via
1783    /// `workspace/*/refresh`. Cursor requests keep the strict gate.
1784    ///
1785    /// `None` — the handler returns empty — when the file is under no project, is
1786    /// outside every `include` root (never a snapshot key), or no round has
1787    /// committed yet (cold start; the scheduled round will produce one and the
1788    /// client re-pulls on the refresh nudge).
1789    async fn committed_analysis(&self, uri: &Url) -> Option<Arc<Analysis>> {
1790        let root = self.root_for_uri(uri).await?;
1791        let a = self.project_analysis(&root).await?;
1792        // Must actually be analysed (a snapshot key), not merely version-tracked
1793        // — the handler converts its spans against this snapshot.
1794        let rel = Self::uri_to_rel(&a, uri)?;
1795        a.snapshots.contains_key(&rel).then_some(a)
1796    }
1797
1798    /// #2100 (DECISION B): the organise-imports action for `rel`, offered
1799    /// only if its edit re-checks clean. The full organise (drops included)
1800    /// is tried first; if a drop would introduce a diagnostic, the sort-and-
1801    /// dedupe-only edit is tried instead, so one wrongly-judged drop doesn't
1802    /// withhold the whole action.
1803    async fn organise_action(
1804        &self,
1805        analysis: &Arc<Analysis>,
1806        rel: &std::path::Path,
1807        uri: &Url,
1808        version: Option<i32>,
1809    ) -> Option<CodeActionOrCommand> {
1810        use crate::organise::{Mode, Project};
1811        let text = analysis.snapshots.get(rel)?;
1812        let project = Project {
1813            index: &analysis.index,
1814            snapshots: &analysis.snapshots,
1815            unit_sources: &analysis.unit_sources,
1816        };
1817        let mut tried: Option<String> = None;
1818        for mode in [Mode::Full, Mode::SortOnly] {
1819            let Some(edit) = crate::organise::organise(text, rel, mode, &project) else {
1820                continue;
1821            };
1822            let edited = crate::organise::apply(text, &edit);
1823            if tried.as_deref() == Some(edited.as_str()) {
1824                continue;
1825            }
1826            if self.rechecks_clean(analysis, rel, edited.clone()).await {
1827                return Some(crate::organise::action(text, edit, uri, version));
1828            }
1829            tried = Some(edited);
1830        }
1831        None
1832    }
1833
1834    /// #2100 slice 1: resolve a listed inline action — re-plan it against the
1835    /// committed round (which must still be the version it was listed from)
1836    /// and offer the edit only if the inlined project re-checks clean.
1837    async fn resolve_inline(
1838        &self,
1839        action: CodeAction,
1840        target: crate::inline::Target,
1841    ) -> JsonRpcResult<CodeAction> {
1842        let refused = |msg: &str| tower_lsp::jsonrpc::Error {
1843            code: tower_lsp::jsonrpc::ErrorCode::InvalidParams,
1844            message: msg.to_string().into(),
1845            data: None,
1846        };
1847        let stale = "the document changed since the inline was offered";
1848        let analysis = self
1849            .committed_analysis(&target.uri)
1850            .await
1851            .ok_or_else(|| refused(stale))?;
1852        let rel = Self::uri_to_rel(&analysis, &target.uri).ok_or_else(|| refused(stale))?;
1853        let (Some(text), Some(locals)) = (analysis.snapshots.get(&rel), analysis.locals.get(&rel))
1854        else {
1855            return Err(refused(stale));
1856        };
1857        let version = analysis.versions.get(&rel).copied();
1858        if version != target.version {
1859            return Err(refused(stale));
1860        }
1861        let plan = crate::inline::plan(text, target.def, locals)
1862            .ok_or_else(|| refused("this binding can't be inlined"))?;
1863        let inlined = crate::fix_all::apply(text, &plan.edits);
1864        if !self.rechecks_clean(&analysis, &rel, inlined).await {
1865            return Err(refused(&format!(
1866                "inlining `{}` would introduce a new problem",
1867                plan.name
1868            )));
1869        }
1870        Ok(crate::fill_arms::resolve(
1871            action,
1872            text,
1873            &plan.edits,
1874            &target.uri,
1875            version,
1876        ))
1877    }
1878
1879    /// #2100 slice 4: resolve a listed provider-stub action — re-plan it
1880    /// against the committed round (which must still be the version it was
1881    /// listed from) and offer the edit only if the project re-checks clean.
1882    async fn resolve_provider_stub(
1883        &self,
1884        action: CodeAction,
1885        target: crate::provider_stub::Target,
1886    ) -> JsonRpcResult<CodeAction> {
1887        let refused = |msg: &str| tower_lsp::jsonrpc::Error {
1888            code: tower_lsp::jsonrpc::ErrorCode::InvalidParams,
1889            message: msg.to_string().into(),
1890            data: None,
1891        };
1892        let stale = "the document changed since the provider stub was offered";
1893        let analysis = self
1894            .committed_analysis(&target.uri)
1895            .await
1896            .ok_or_else(|| refused(stale))?;
1897        let rel = Self::uri_to_rel(&analysis, &target.uri).ok_or_else(|| refused(stale))?;
1898        let Some(text) = analysis.snapshots.get(&rel) else {
1899            return Err(refused(stale));
1900        };
1901        let version = analysis.versions.get(&rel).copied();
1902        if version != target.version {
1903            return Err(refused(stale));
1904        }
1905        let plan = crate::provider_stub::plan(text, &target.capability, &analysis.index)
1906            .ok_or_else(|| refused("a provider stub can't be generated here"))?;
1907        let stubbed = crate::fix_all::apply(text, &plan.edits);
1908        if !self.rechecks_clean(&analysis, &rel, stubbed).await {
1909            return Err(refused(&format!(
1910                "a provider stub for `{}` would introduce a new problem",
1911                plan.capability
1912            )));
1913        }
1914        Ok(crate::fill_arms::resolve(
1915            action,
1916            text,
1917            &plan.edits,
1918            &target.uri,
1919            version,
1920        ))
1921    }
1922
1923    /// #2100 slice 2: resolve a listed extract-function action — re-plan it
1924    /// against the committed round (which must still be the version it was
1925    /// listed from) and offer the edit only if the project re-checks clean.
1926    async fn resolve_extract_function(
1927        &self,
1928        action: CodeAction,
1929        target: crate::extract::FunctionTarget,
1930    ) -> JsonRpcResult<CodeAction> {
1931        let refused = |msg: &str| tower_lsp::jsonrpc::Error {
1932            code: tower_lsp::jsonrpc::ErrorCode::InvalidParams,
1933            message: msg.to_string().into(),
1934            data: None,
1935        };
1936        let stale = "the document changed since the extraction was offered";
1937        let analysis = self
1938            .committed_analysis(&target.uri)
1939            .await
1940            .ok_or_else(|| refused(stale))?;
1941        let rel = Self::uri_to_rel(&analysis, &target.uri).ok_or_else(|| refused(stale))?;
1942        let Some(text) = analysis.snapshots.get(&rel) else {
1943            return Err(refused(stale));
1944        };
1945        let version = analysis.versions.get(&rel).copied();
1946        if version != target.version {
1947            return Err(refused(stale));
1948        }
1949        let empty_reqs = Vec::new();
1950        let empty_locals = Vec::new();
1951        let empty_types = Vec::new();
1952        let plan = crate::extract::plan_function(
1953            text,
1954            target.requested,
1955            analysis.requirements.get(&rel).unwrap_or(&empty_reqs),
1956            analysis.locals.get(&rel).unwrap_or(&empty_locals),
1957            analysis.expr_types.get(&rel).unwrap_or(&empty_types),
1958            &analysis.ty_intern,
1959        )
1960        .map_err(|r| {
1961            refused(
1962                r.reason
1963                    .as_deref()
1964                    .unwrap_or("the selection can't be extracted into a function"),
1965            )
1966        })?;
1967        let extracted = crate::fix_all::apply(text, &plan.edits);
1968        if !self.rechecks_clean(&analysis, &rel, extracted).await {
1969            return Err(refused(&format!(
1970                "extracting `{}` would introduce a new problem",
1971                plan.name
1972            )));
1973        }
1974        Ok(crate::fill_arms::resolve(
1975            action,
1976            text,
1977            &plan.edits,
1978            &target.uri,
1979            version,
1980        ))
1981    }
1982
1983    /// #2100 (DECISION B): re-analyse the round's project with `rel`'s text
1984    /// replaced by `edited`, and report whether that introduces no diagnostic
1985    /// the round didn't already have (rename's validator 1, for one file).
1986    /// Every other file is pinned to its round snapshot, so the re-analysis
1987    /// differs from the round only by the edit.
1988    async fn rechecks_clean(
1989        &self,
1990        analysis: &Arc<Analysis>,
1991        rel: &std::path::Path,
1992        edited: String,
1993    ) -> bool {
1994        let mut overlay = std::collections::HashMap::new();
1995        for (rel_path, text) in &analysis.snapshots {
1996            let abs = analysis.project_root.join(rel_path);
1997            let abs = abs.canonicalize().unwrap_or(abs);
1998            let text = if rel_path == rel {
1999                edited.clone()
2000            } else {
2001                text.clone()
2002            };
2003            overlay.insert(abs, text);
2004        }
2005        let roots = bynk_ide::AnalysisRoots::Project(analysis.project_root.clone());
2006        // #2081: `Off`, as rename's re-check: schema-lock diagnostics are
2007        // project-level and never compared here.
2008        let Ok(post) = tokio::task::spawn_blocking(move || {
2009            bynk_ide::diagnose_project_with(&roots, &overlay, &bynk_ide::SchemaLock::Off)
2010        })
2011        .await
2012        else {
2013            return false;
2014        };
2015        let post_diags: Vec<(PathBuf, String)> = post
2016            .files
2017            .iter()
2018            .flat_map(|f| {
2019                f.diagnostics
2020                    .iter()
2021                    .map(|d| (f.source_path.clone(), d.error.category.to_string()))
2022            })
2023            .collect();
2024        crate::index_queries::no_new_diagnostics(&analysis.diag_categories(), &post_diags).is_ok()
2025    }
2026
2027    /// Slice B: the analysis for a handler that emits **multi-file versioned
2028    /// edits** — today, `rename`. Per-URI freshness ([`Self::analysis_for`]) is
2029    /// not enough here: a rename touches every file that references the symbol,
2030    /// and each edit is stamped with *that* file's analysed version, so the
2031    /// round must be current for **every open buffer**, not just the cursor's.
2032    ///
2033    /// Without this, a buffer edited since the last round but not under the
2034    /// cursor keeps its stale version in the round; `rename`'s edit for it is
2035    /// then stamped with that old version and the client rejects the whole
2036    /// operation (VS Code: "document changed since the refactoring was
2037    /// requested"). This restores the whole-project guarantee the pre-v0.179
2038    /// `fresh_analysis` gave — as a version-aware refresh, not an unconditional
2039    /// one. Returns `None` on the same terms as `analysis_for` (no project, or a
2040    /// concurrent edit that raced the refresh).
2041    ///
2042    /// Slice D: takes the rename's project `root` — a rename spans one project
2043    /// (the symbol and its references live under one root), so the round must
2044    /// cover *that* project's open buffers. A buffer in another project strips
2045    /// against a different `project_root`, so `uri_to_rel` returns `None` for it
2046    /// and it does not gate this rename.
2047    async fn analysis_covering_open_buffers(
2048        &self,
2049        root: &std::path::Path,
2050    ) -> Option<Arc<Analysis>> {
2051        // Every open buffer that maps into the project must be analysed at its
2052        // current version. A buffer outside the project (no snapshot key) is not
2053        // part of a project rename and does not gate it.
2054        let all_current =
2055            |a: &Arc<Analysis>, docs: &std::collections::HashMap<Url, DocumentState>| {
2056                docs.iter()
2057                    .all(|(uri, doc)| match Self::uri_to_rel(a, uri) {
2058                        Some(rel) if a.snapshots.contains_key(&rel) => {
2059                            a.versions.get(&rel) == Some(&doc.version)
2060                        }
2061                        _ => true,
2062                    })
2063            };
2064
2065        {
2066            let state = self.state.read().await;
2067            if let Some(a) = state.projects.get(root).and_then(|p| p.analysis.clone())
2068                && all_current(&a, &state.docs)
2069            {
2070                return Some(a);
2071            }
2072        }
2073        let _guard = self.refresh_lock.lock().await;
2074        {
2075            let state = self.state.read().await;
2076            if let Some(a) = state.projects.get(root).and_then(|p| p.analysis.clone())
2077                && all_current(&a, &state.docs)
2078            {
2079                return Some(a);
2080            }
2081        }
2082        self.refresh_now(root.to_path_buf()).await;
2083        let state = self.state.read().await;
2084        let a = state.projects.get(root).and_then(|p| p.analysis.clone())?;
2085        all_current(&a, &state.docs).then_some(a)
2086    }
2087
2088    /// Run a round now for one project, superseding any pending debounced one.
2089    /// Bumping the project's generation makes a scheduled round (which checks it
2090    /// before running) bail, so a request-driven refresh does not race a
2091    /// redundant debounce round that would produce the same result 200 ms later.
2092    async fn refresh_now(&self, root: PathBuf) {
2093        if let Some(ps) = self.state.write().await.projects.get_mut(&root) {
2094            ps.analysis_generation += 1;
2095        }
2096        self.run_project_diagnostics(root).await;
2097    }
2098
2099    /// Map a request URI to the analysis' project-relative path.
2100    fn uri_to_rel(analysis: &Analysis, uri: &Url) -> Option<PathBuf> {
2101        let p = uri.to_file_path().ok()?;
2102        let canonical = p.canonicalize().unwrap_or(p);
2103        // Slice A: one `strip_prefix` still, but against the *project* root —
2104        // which is total across `include` trees, where the old `src` base could
2105        // only ever name files in one of them. A file under no root strips fine
2106        // and simply misses every lookup, which is correct: it was not analysed.
2107        canonical
2108            .strip_prefix(&analysis.project_root)
2109            .ok()
2110            .map(|r| r.to_path_buf())
2111    }
2112
2113    /// #302: like [`Self::uri_to_rel`], but for a URI whose file does not
2114    /// exist yet — `willRenameFiles`' `new_uri`, named before the physical
2115    /// move happens. `Path::canonicalize` requires the path to exist, so
2116    /// `uri_to_rel`'s fallback (`unwrap_or(p)`, dead code for every other
2117    /// caller, which only ever resolves existing files) would silently keep
2118    /// the client's raw, non-canonical path — mismatching `project_root`
2119    /// (always canonical) whenever the workspace sits behind a symlink (macOS
2120    /// `/tmp` → `/private/tmp` being the common case), and the rename would
2121    /// quietly produce no edit. Canonicalizing the *parent* directory
2122    /// instead — it does exist — and rejoining the file name sidesteps that.
2123    fn uri_to_rel_for_new_path(analysis: &Analysis, uri: &Url) -> Option<PathBuf> {
2124        let p = uri.to_file_path().ok()?;
2125        let file_name = p.file_name()?;
2126        let parent = p.parent()?;
2127        let canonical_parent = parent
2128            .canonicalize()
2129            .unwrap_or_else(|_| parent.to_path_buf());
2130        canonical_parent
2131            .join(file_name)
2132            .strip_prefix(&analysis.project_root)
2133            .ok()
2134            .map(|r| r.to_path_buf())
2135    }
2136
2137    /// #2105: the per-file renames one `FileRename` stands for, as
2138    /// project-relative `(old, new)` paths. A path the round has a snapshot
2139    /// for is a file rename. Anything else is treated as a folder: every
2140    /// snapshot under it (a component-wise prefix match, so `src/bill` never
2141    /// matches `src/billing/…`), each mapped to the same relative position
2142    /// under the new folder. A folder with no project file under it, or an
2143    /// old/new path outside the project, yields nothing. Sorted, so the edit
2144    /// set is deterministic.
2145    fn expand_rename(analysis: &Analysis, old_uri: &Url, new_uri: &Url) -> Vec<(PathBuf, PathBuf)> {
2146        let (Some(old_rel), Some(new_rel)) = (
2147            Self::uri_to_rel(analysis, old_uri),
2148            Self::uri_to_rel_for_new_path(analysis, new_uri),
2149        ) else {
2150            return Vec::new();
2151        };
2152        if analysis.snapshots.contains_key(&old_rel) {
2153            return vec![(old_rel, new_rel)];
2154        }
2155        let mut pairs: Vec<(PathBuf, PathBuf)> = analysis
2156            .snapshots
2157            .keys()
2158            .filter_map(|rel| {
2159                let suffix = rel.strip_prefix(&old_rel).ok()?;
2160                (!suffix.as_os_str().is_empty()).then(|| (rel.clone(), new_rel.join(suffix)))
2161            })
2162            .collect();
2163        pairs.sort();
2164        pairs
2165    }
2166
2167    /// #2105 (DECISION B): the canonical project root a rename's destination
2168    /// would belong to. The destination does not exist yet (`willRenameFiles`
2169    /// fires before the move), so its existing parent is canonicalized and the
2170    /// last segment rejoined, as [`Self::uri_to_rel_for_new_path`] does, before
2171    /// the usual walk up to a `bynk.toml` (or implicit `src/` parent).
2172    fn new_path_root(new_uri: &Url) -> Option<PathBuf> {
2173        let p = new_uri.to_file_path().ok()?;
2174        let parent = p.parent()?;
2175        let canonical = parent
2176            .canonicalize()
2177            .unwrap_or_else(|_| parent.to_path_buf())
2178            .join(p.file_name()?);
2179        let (root, _) = Self::resolve_root(&canonical)?;
2180        Some(root.canonicalize().unwrap_or(root))
2181    }
2182
2183    /// Slice 6a follow-up (ADR 0095): if `pos` sits on a `uses`/`consumes` unit
2184    /// name, the location of that unit's source (its first file, at the top —
2185    /// units aren't index symbols, so there is no finer def span to land on).
2186    /// Spans come from the live buffer; the target from the round's unit→source
2187    /// map. `None` for a first-party/unresolved unit or a non-unit position.
2188    async fn unit_reference_definition(&self, uri: &Url, pos: Position) -> Option<Location> {
2189        // Slice B: the position is resolved against *live* text (no stale-offset
2190        // risk), but the `uses`/`consumes` → source lookup reads the round's
2191        // `unit_sources`, so route that through the gate — fresh or decline,
2192        // never a stale unit map. Cheap here: `goto_definition` already
2193        // refreshed via `index_position`, so this hits the current-round path.
2194        let analysis = self.analysis_for(uri).await;
2195        let text = self
2196            .state
2197            .read()
2198            .await
2199            .docs
2200            .get(uri)
2201            .map(|d| d.text.clone());
2202        let (text, analysis) = (text?, analysis?);
2203        let offset = cursor_offset(&text, pos);
2204        for (unit, span) in crate::symbols::unit_reference_spans(&text) {
2205            if span.start <= offset && offset <= span.end {
2206                // #2223: a dependency unit is keyed by its canonical name,
2207                // resolved against the live content map (an unsaved alias
2208                // edit counts, as it does for the analysed round).
2209                let view = if analysis.unit_sources.contains_key(&unit) {
2210                    None
2211                } else {
2212                    let files = self.project_content(uri).await;
2213                    let empty = std::collections::HashMap::new();
2214                    bynk_ide::packages::DependencyView::for_root(
2215                        &analysis.project_root,
2216                        files.as_deref().unwrap_or(&empty),
2217                    )
2218                };
2219                let rel = bynk_ide::packages::unit_sources_for(
2220                    &analysis.unit_sources,
2221                    view.as_ref(),
2222                    &unit,
2223                )?
2224                .first()?;
2225                let target = Url::from_file_path(analysis.project_root.join(rel)).ok()?;
2226                return Some(Location {
2227                    uri: target,
2228                    range: Range::default(),
2229                });
2230            }
2231        }
2232        None
2233    }
2234
2235    /// #2457: every doc-link mention that resolves to the symbol at the
2236    /// cursor (see `index_queries::doc_link_mentions`); empty when the cursor
2237    /// is not on an indexed symbol or the symbol has no definition site. With
2238    /// `only_in`, just that file is scanned (the document highlight, which keeps
2239    /// nothing else); resolution still uses the full index and doc scope.
2240    fn doc_mention_sites(
2241        analysis: &Analysis,
2242        rel: &std::path::Path,
2243        offset: usize,
2244        only_in: Option<&std::path::Path>,
2245    ) -> Vec<bynk_check::index::SiteRef> {
2246        let index = &analysis.index;
2247        let Some((key, _)) = index.symbol_at(rel, offset) else {
2248            return Vec::new();
2249        };
2250        let Some(def) = index.symbols.get(key).and_then(|e| e.def.as_ref()) else {
2251            return Vec::new();
2252        };
2253        let one_file;
2254        let snapshots = match only_in {
2255            Some(path) => {
2256                one_file = analysis
2257                    .snapshots
2258                    .get(path)
2259                    .map(|text| {
2260                        std::collections::HashMap::from([(path.to_path_buf(), text.clone())])
2261                    })
2262                    .unwrap_or_default();
2263                &one_file
2264            }
2265            None => &analysis.snapshots,
2266        };
2267        crate::index_queries::doc_link_mentions(
2268            index,
2269            &analysis.doc_scope,
2270            snapshots,
2271            &analysis.locals,
2272            def,
2273        )
2274        .into_iter()
2275        .map(|m| bynk_check::index::SiteRef {
2276            path: m.path,
2277            span: m.name_span,
2278        })
2279        .collect()
2280    }
2281
2282    /// Convert an index site to an LSP location, spans against the analysed
2283    /// snapshot (v0.24 rule).
2284    fn site_to_location(
2285        analysis: &Analysis,
2286        site: &bynk_check::index::SiteRef,
2287    ) -> Option<Location> {
2288        let text = analysis.snapshots.get(&site.path)?;
2289        let abs = analysis.project_root.join(&site.path);
2290        let uri = Url::from_file_path(abs).ok()?;
2291        Some(Location {
2292            uri,
2293            range: crate::position::span_to_range(text, site.span),
2294        })
2295    }
2296
2297    /// v0.34 (ADR 0067): build a `CallHierarchyItem` for an index symbol from
2298    /// its key + definition site. The key is round-tripped through `data` so
2299    /// the incoming/outgoing follow-ups resolve straight off it, never
2300    /// re-inferring from a position.
2301    fn call_hierarchy_item(
2302        analysis: &Analysis,
2303        key: &bynk_check::index::SymbolKey,
2304        def: &bynk_check::index::SiteRef,
2305    ) -> Option<CallHierarchyItem> {
2306        let location = Self::site_to_location(analysis, def)?;
2307        Some(CallHierarchyItem {
2308            name: key.handler_display_name().to_string(),
2309            kind: lsp_symbol_kind(key.kind),
2310            tags: None,
2311            detail: Some(key.unit.clone()),
2312            uri: location.uri,
2313            range: location.range,
2314            selection_range: location.range,
2315            data: serde_json::to_value(SerKey::from(key)).ok(),
2316        })
2317    }
2318
2319    /// A `TypeHierarchyItem` for a refined/opaque/alias type. `from` is the
2320    /// unit the hierarchy was opened from, round-tripped so follow-ups apply the
2321    /// same opaque-visibility rule.
2322    fn type_hierarchy_item(
2323        analysis: &Analysis,
2324        key: &bynk_check::index::SymbolKey,
2325        def: &bynk_check::index::SiteRef,
2326        from: Option<&str>,
2327    ) -> Option<TypeHierarchyItem> {
2328        let location = Self::site_to_location(analysis, def)?;
2329        Some(TypeHierarchyItem {
2330            name: key.name.clone(),
2331            kind: SymbolKind::STRUCT,
2332            tags: None,
2333            detail: Some(key.unit.clone()),
2334            uri: location.uri,
2335            range: location.range,
2336            selection_range: location.range,
2337            data: serde_json::to_value(TypeHierData::Type {
2338                key: SerKey::from(key),
2339                from: from.map(str::to_string),
2340            })
2341            .ok(),
2342        })
2343    }
2344
2345    /// The `TypeHierarchyItem` for a primitive. It has no declaration, so it is
2346    /// anchored on `anchor` — an occurrence of its name as a declaration's base —
2347    /// and identified by `data`.
2348    fn primitive_hierarchy_item(
2349        analysis: &Analysis,
2350        base: bynk_syntax::ast::BaseType,
2351        anchor: &bynk_check::index::SiteRef,
2352        from: Option<&str>,
2353    ) -> Option<TypeHierarchyItem> {
2354        let location = Self::site_to_location(analysis, anchor)?;
2355        Some(TypeHierarchyItem {
2356            name: base.name().to_string(),
2357            kind: SymbolKind::CLASS,
2358            tags: None,
2359            detail: Some("primitive".to_string()),
2360            uri: location.uri,
2361            range: location.range,
2362            selection_range: location.range,
2363            data: serde_json::to_value(TypeHierData::Primitive {
2364                base: base.name().to_string(),
2365                from: from.map(str::to_string),
2366            })
2367            .ok(),
2368        })
2369    }
2370
2371    /// The call-site ranges (`fromRanges`) for a call relation, each converted
2372    /// against its file's analysed snapshot.
2373    fn call_ranges(analysis: &Analysis, sites: &[&bynk_check::index::SiteRef]) -> Vec<Range> {
2374        sites
2375            .iter()
2376            .filter_map(|s| {
2377                let text = analysis.snapshots.get(&s.path)?;
2378                Some(crate::position::span_to_range(text, s.span))
2379            })
2380            .collect()
2381    }
2382
2383    /// v0.28 (ADR 0057): the shared body of both semantic-tokens requests —
2384    /// resolve the cached round, convert the optional range against the
2385    /// analysed snapshot, and run the pure producer. Empty when no round is
2386    /// cached or the file is outside the project.
2387    async fn semantic_tokens_for(&self, uri: &Url, range: Option<Range>) -> Vec<SemanticToken> {
2388        // #733: serve the last committed round without forcing a re-analysis —
2389        // tokens convert against the round's own snapshot, so a one-cycle lag is
2390        // consistent, and the client re-pulls on the round-commit refresh nudge.
2391        let analysis = self.committed_analysis(uri).await;
2392        let Some(analysis) = analysis else {
2393            return Vec::new();
2394        };
2395        let Some(rel) = Self::uri_to_rel(&analysis, uri) else {
2396            return Vec::new();
2397        };
2398        let Some(text) = analysis.snapshots.get(&rel) else {
2399            return Vec::new();
2400        };
2401        let span = match range {
2402            None => None,
2403            // The requested range converts against the analysed snapshot,
2404            // like the spans it is intersected with.
2405            Some(r) => {
2406                let (Some(start), Some(end)) = (
2407                    crate::position::position_to_offset(text, r.start),
2408                    crate::position::position_to_offset(text, r.end),
2409                ) else {
2410                    return Vec::new();
2411                };
2412                Some(bynk_syntax::span::Span::new(start, end))
2413            }
2414        };
2415        let lt = analysis
2416            .locals
2417            .get(&rel)
2418            .map(|l| crate::locals_nav::local_token_sites(l, text))
2419            .unwrap_or_default();
2420        // v0.140 (ADR 0163): handler-annotation spans (`@cache` name + argument
2421        // labels), classified as `decorator`. Parsed from the snapshot here, off
2422        // the index-read path (mirroring how locals are precomputed).
2423        let mut dt: Vec<(bynk_syntax::span::Span, u32)> =
2424            crate::symbols::handler_annotation_token_spans(text)
2425                .into_iter()
2426                .map(|s| (s, crate::semantic_tokens::TOK_DECORATOR))
2427                .collect();
2428        // Constraint names in a bound (`T: Eq`, `where A: Eq`), as `interface`.
2429        dt.extend(
2430            crate::symbols::constraint_token_spans(text)
2431                .into_iter()
2432                .map(|s| (s, crate::semantic_tokens::TOK_INTERFACE)),
2433        );
2434        // #2837: a reserved word written as a field or method name.
2435        dt.extend(
2436            crate::symbols::keyword_name_token_spans(text)
2437                .into_iter()
2438                .map(|(s, is_method)| {
2439                    (
2440                        s,
2441                        if is_method {
2442                            crate::semantic_tokens::TOK_METHOD
2443                        } else {
2444                            crate::semantic_tokens::TOK_PROPERTY
2445                        },
2446                    )
2447                }),
2448        );
2449        // #2618: each `private` modifier, as `keyword`.
2450        dt.extend(
2451            crate::symbols::private_modifier_token_spans(text)
2452                .into_iter()
2453                .map(|s| (s, crate::semantic_tokens::TOK_KEYWORD)),
2454        );
2455        // #2842: the contextual `matches` and `snapshot` of a snapshot claim.
2456        dt.extend(
2457            crate::symbols::snapshot_keyword_spans(text)
2458                .into_iter()
2459                .map(|s| (s, crate::semantic_tokens::TOK_KEYWORD)),
2460        );
2461        // #2619: escape sequences in every form of string literal, and a raw
2462        // literal's delimiters as `string`. #2958: a multi-line literal's
2463        // language tag as `decorator`; the body gets no token, so an editor's
2464        // embedded-language highlighting shows through.
2465        dt.extend(
2466            bynk_syntax::lexer::string_parts(text)
2467                .into_iter()
2468                .map(|(s, part)| match part {
2469                    bynk_syntax::lexer::StringPart::Escape => {
2470                        (s, crate::semantic_tokens::TOK_ESCAPE)
2471                    }
2472                    bynk_syntax::lexer::StringPart::RawDelimiter => {
2473                        (s, crate::semantic_tokens::TOK_STRING)
2474                    }
2475                    // #2958: a multi-line literal's language tag reads as
2476                    // metadata, not string text.
2477                    bynk_syntax::lexer::StringPart::Tag => {
2478                        (s, crate::semantic_tokens::TOK_DECORATOR)
2479                    }
2480                }),
2481        );
2482        crate::index_queries::semantic_tokens(&analysis.index, &lt, &dt, &rel, text, span)
2483    }
2484
2485    /// The (analysis, rel-path, snapshot byte offset) for a request
2486    /// position — the shared front half of every index-backed handler.
2487    async fn index_position(
2488        &self,
2489        uri: &Url,
2490        position: Position,
2491    ) -> Option<(Arc<Analysis>, PathBuf, usize)> {
2492        // Slice B: `analysis_for` guarantees the round analysed `uri`'s current
2493        // version, so `position_to_offset` resolves against the same text the
2494        // client's position refers to — the `fresh` flag every caller used to
2495        // pass is gone (freshness is the contract now, not a per-call choice).
2496        let analysis = self.analysis_for(uri).await?;
2497        let rel = Self::uri_to_rel(&analysis, uri)?;
2498        let text = analysis.snapshots.get(&rel)?;
2499        let offset = crate::position::position_to_offset(text, position)?;
2500        Some((analysis, rel, offset))
2501    }
2502
2503    /// Locate the AST node at the given cursor position by re-parsing the
2504    /// document. Returns the textual identifier (if any) and its span.
2505    /// Used by hover and definition handlers.
2506    async fn identifier_at(
2507        &self,
2508        uri: &Url,
2509        position: Position,
2510    ) -> Option<(String, bynk_syntax::span::Span, String)> {
2511        let text = {
2512            let state = self.state.read().await;
2513            state.docs.get(uri)?.text.clone()
2514        };
2515        let offset = crate::position::position_to_offset(&text, position)?;
2516        // Hole-aware (issue #473): interpolation holes are expanded so a cursor
2517        // inside `"… \(name) …"` lands on the hole's identifier token, not the
2518        // opaque `InterpStr` token.
2519        let tokens = bynk_syntax::lexer::tokenize_expanding_holes(&text).ok()?;
2520        // Find the token whose span covers `offset`.
2521        for t in &tokens {
2522            if t.span.start <= offset
2523                && offset < t.span.end
2524                && matches!(
2525                    t.kind,
2526                    bynk_syntax::lexer::TokenKind::Ident
2527                        | bynk_syntax::lexer::TokenKind::Int
2528                        | bynk_syntax::lexer::TokenKind::String
2529                        | bynk_syntax::lexer::TokenKind::Bool
2530                        | bynk_syntax::lexer::TokenKind::Float
2531                        | bynk_syntax::lexer::TokenKind::Decimal
2532                        | bynk_syntax::lexer::TokenKind::Result
2533                        | bynk_syntax::lexer::TokenKind::Option
2534                        | bynk_syntax::lexer::TokenKind::Effect
2535                )
2536            {
2537                let name = text[t.span.start..t.span.end].to_string();
2538                return Some((name, t.span, text));
2539            }
2540        }
2541        None
2542    }
2543
2544    /// #846: `bynk/sequenceModel` — the sequence-diagram query for the
2545    /// handler under the cursor. This server's first custom (non-standard)
2546    /// request, registered via `custom_method` in [`run`] rather than a
2547    /// `LanguageServer` trait slot. Served from the committed round (#733),
2548    /// like `code_lens`; no refresh nudge (see the `sequence_request` module
2549    /// doc for why one isn't needed).
2550    async fn sequence_model(
2551        &self,
2552        params: sequence_request::SequenceModelParams,
2553    ) -> JsonRpcResult<Option<sequence_request::WireSequenceModel>> {
2554        let uri = params.text_document.uri;
2555        let Some(analysis) = self.committed_analysis(&uri).await else {
2556            return Ok(None);
2557        };
2558        let Some(rel) = Self::uri_to_rel(&analysis, &uri) else {
2559            return Ok(None);
2560        };
2561        let Some(text) = analysis.snapshots.get(&rel) else {
2562            return Ok(None);
2563        };
2564        let Some(offset) = crate::position::position_to_offset(text, params.position) else {
2565            return Ok(None);
2566        };
2567        let own = bynk_ide::symbols::own_declaration_name(text).map(|(name, _)| name);
2568        let info = own
2569            .as_ref()
2570            .and_then(|name| analysis.sequence_info.get(name));
2571        let model = sequence_request::sequence_model_at(text, offset, info);
2572        // Model-diagrams slice 3: locate each callee among its unit's files in
2573        // this round — the caller's own unit for an agent, else the consumed
2574        // context's.
2575        // A handler calling one agent several times names the same callee
2576        // each time: parse its unit's files once per request (review, #3651).
2577        let located: std::cell::RefCell<
2578            std::collections::HashMap<
2579                bynk_ide::sequence::Callee,
2580                Option<tower_lsp::lsp_types::Location>,
2581            >,
2582        > = Default::default();
2583        let locate = |callee: &bynk_ide::sequence::Callee| {
2584            if let Some(hit) = located.borrow().get(callee) {
2585                return hit.clone();
2586            }
2587            let found = Self::locate_callee_in(&analysis, own.as_ref(), callee);
2588            located.borrow_mut().insert(callee.clone(), found.clone());
2589            found
2590        };
2591        Ok(model.map(|m| sequence_request::to_wire(&m, text, locate)))
2592    }
2593
2594    /// Model-diagrams slice 3: where `callee`'s handler is declared, among its
2595    /// unit's files in `analysis` — the caller's own unit (`own`) for an agent.
2596    fn locate_callee_in(
2597        analysis: &Analysis,
2598        own: Option<&String>,
2599        callee: &bynk_ide::sequence::Callee,
2600    ) -> Option<tower_lsp::lsp_types::Location> {
2601        let unit = callee.unit.as_ref().or(own)?;
2602        let files = analysis.unit_sources.get(unit)?.iter().filter_map(|rel| {
2603            let text = analysis.snapshots.get(rel)?;
2604            let uri = Url::from_file_path(analysis.project_root.join(rel)).ok()?;
2605            Some((uri, text.as_str()))
2606        });
2607        sequence_request::locate_callee(callee, files)
2608    }
2609
2610    /// #2196: `bynk/agentStateModel` — the agent state view's query for the
2611    /// agent enclosing the cursor: its state machines, derived from its
2612    /// handlers. Agent-scoped (the cursor anywhere in the `agent`), served from
2613    /// the committed round, no refresh nudge — like `sequence_model`. A
2614    /// non-project file, no committed round, an offset outside every agent, or
2615    /// a unit `boundary_info` has no entry for all answer `None`.
2616    async fn agent_state_model(
2617        &self,
2618        params: agent_state_request::AgentStateModelParams,
2619    ) -> JsonRpcResult<Option<agent_state_request::WireAgentStateModel>> {
2620        let uri = params.text_document.uri;
2621        let Some(analysis) = self.committed_analysis(&uri).await else {
2622            return Ok(None);
2623        };
2624        let Some(rel) = Self::uri_to_rel(&analysis, &uri) else {
2625            return Ok(None);
2626        };
2627        let Some(text) = analysis.snapshots.get(&rel) else {
2628            return Ok(None);
2629        };
2630        let Some(offset) = crate::position::position_to_offset(text, params.position) else {
2631            return Ok(None);
2632        };
2633        let Some((unit, _)) = bynk_ide::symbols::own_declaration_name(text) else {
2634            return Ok(None);
2635        };
2636        let Some(info) = analysis.boundary_info.get(&unit) else {
2637            return Ok(None);
2638        };
2639        // The agents a handler can call: the context's own, across its files.
2640        let agents: std::collections::HashSet<String> = analysis
2641            .sequence_info
2642            .get(&unit)
2643            .map(|s| s.agents.keys().cloned().collect())
2644            .unwrap_or_default();
2645        Ok(
2646            agent_state_request::agent_state_at(text, offset, &info.types).map(|(agent, model)| {
2647                let effects = agent_state_request::effects_of(&agent, &agents);
2648                agent_state_request::to_wire(&agent, &model, &effects, text)
2649            }),
2650        )
2651    }
2652
2653    /// #847: `bynk/documentationModel` — the documentation-view query for the
2654    /// unit under the request. This server's second custom request,
2655    /// registered via `custom_method` in [`run`] (like `sequence_model`).
2656    /// Served from the committed round (#733), on-demand: no cursor position
2657    /// (the page is the whole unit — every file of a multi-file unit since
2658    /// #1885) and no refresh nudge (Decision D — see the
2659    /// `documentation_request` module doc, and #846's for why a custom method
2660    /// needs none). A non-project file / no committed round → `None` (empty
2661    /// page).
2662    async fn documentation_model(
2663        &self,
2664        params: documentation_request::DocumentationModelParams,
2665    ) -> JsonRpcResult<Option<documentation_request::WireDocModel>> {
2666        let uri = params.text_document.uri;
2667        let Some(analysis) = self.committed_analysis(&uri).await else {
2668            return Ok(None);
2669        };
2670        let Some(rel) = Self::uri_to_rel(&analysis, &uri) else {
2671            return Ok(None);
2672        };
2673        Ok(documentation_request::documentation_model_for(
2674            &rel,
2675            &analysis.snapshots,
2676            &analysis.unit_sources,
2677            &analysis.project_root,
2678            Some(documentation_request::DocLinkContext {
2679                index: &analysis.index,
2680                doc_scope: &analysis.doc_scope,
2681                locals: &analysis.locals,
2682            }),
2683        ))
2684    }
2685
2686    /// #2098: `bynk/explain` — the curated, offline explanation of a diagnostic
2687    /// code, from the toolchain's own compiled-in table (so it always matches
2688    /// the installed compiler). Not document-scoped and reads no analysis
2689    /// round: the code alone is the key. `None` for an uncurated or unknown
2690    /// code. Registered via `custom_method` in [`run`].
2691    async fn explain(
2692        &self,
2693        params: explain_request::ExplainParams,
2694    ) -> JsonRpcResult<Option<explain_request::WireExplanation>> {
2695        Ok(explain_request::explanation_for(&params.code))
2696    }
2697
2698    /// #851: `bynk/architectureModel` — the whole-project architecture-map
2699    /// query. This server's third custom request, registered via
2700    /// `custom_method` in [`run`] (like `sequence_model`/`documentation_model`).
2701    /// Served from the committed round (#733); no refresh nudge, for the same
2702    /// reason neither sibling needs one. Unlike both siblings this is
2703    /// **project-scoped** — `params.text_document` only resolves which
2704    /// project's round to read (via `committed_analysis`); the result covers
2705    /// every context/adapter unit in that round, not just the request's own
2706    /// file. A non-project file / no committed round → `None` (empty map).
2707    async fn architecture_model(
2708        &self,
2709        params: architecture_request::ArchitectureModelParams,
2710    ) -> JsonRpcResult<Option<architecture_request::WireArchModel>> {
2711        let uri = params.text_document.uri;
2712        let Some(analysis) = self.committed_analysis(&uri).await else {
2713            return Ok(None);
2714        };
2715        let model = architecture_request::architecture_model_for(
2716            &analysis.unit_sources,
2717            &analysis.snapshots,
2718            &analysis.sequence_info,
2719            &analysis.architecture_facts,
2720        );
2721        Ok(Some(architecture_request::to_wire(
2722            &model,
2723            &analysis.project_root,
2724            &analysis.snapshots,
2725        )))
2726    }
2727
2728    /// #2467: `bynk/contractDiff` — every boundary change since
2729    /// `bynk.schema.lock` (events and agents, classified by the lock
2730    /// reconciliation's own classifier) and every `on call` contract hash that
2731    /// differs from `bynk.deploy.lock` (services, hash-compared, never
2732    /// "breaking"). Project-scoped, served from the committed round; the
2733    /// ledger is read per request. A non-project file / no committed round →
2734    /// `None`.
2735    async fn contract_diff(
2736        &self,
2737        params: contract_diff_request::ContractDiffParams,
2738    ) -> JsonRpcResult<Option<contract_diff_request::CdModel>> {
2739        let uri = params.text_document.uri;
2740        let Some(analysis) = self.committed_analysis(&uri).await else {
2741            return Ok(None);
2742        };
2743        let (state, text) = contract_diff_request::read_ledger(&analysis.project_root);
2744        Ok(Some(contract_diff_request::to_wire(
2745            &analysis.contract_diff,
2746            (state, text.as_deref()),
2747            &analysis.project_root,
2748            &analysis.index,
2749            &analysis.snapshots,
2750        )))
2751    }
2752
2753    /// #2470: the refined type named at `pos`, resolved through the index
2754    /// (binding-correct, any file) and else lexically over the live buffer and
2755    /// the project's files, as hover's declaration rungs are.
2756    async fn refined_model_at(
2757        &self,
2758        uri: &Url,
2759        pos: Position,
2760        with_examples: bool,
2761    ) -> Option<refined_request::RefinedModel> {
2762        if let Some((analysis, rel, offset)) = self.index_position(uri, pos).await
2763            && let Some((key, def)) = index_queries::definition_at(&analysis.index, &rel, offset)
2764            && key.kind == bynk_check::index::SymbolKind::Type
2765            && let Some(text) = analysis.snapshots.get(&def.path)
2766            && let Some(decl) = refined_request::find_type_decl(text, &key.name)
2767        {
2768            return refined_request::model_for(&decl, with_examples);
2769        }
2770        let text = {
2771            let state = self.state.read().await;
2772            state.docs.get(uri)?.text.clone()
2773        };
2774        let offset = crate::position::position_to_offset(&text, pos)?;
2775        let (name, _) = hover::identifier_at(&text, offset)?;
2776        if let Some(decl) = refined_request::find_type_decl(&text, &name) {
2777            return refined_request::model_for(&decl, with_examples);
2778        }
2779        let files = self.project_content(uri).await?;
2780        let mut paths: Vec<_> = files.keys().collect();
2781        paths.sort();
2782        paths
2783            .into_iter()
2784            .find_map(|p| refined_request::find_type_decl(&files[p], &name))
2785            .and_then(|decl| refined_request::model_for(&decl, with_examples))
2786    }
2787
2788    /// #2470: `bynk/refinedTypeModel` — the explorer's model for the refined
2789    /// type at the cursor, or `null` when it names none.
2790    async fn refined_type_model(
2791        &self,
2792        params: refined_request::RefinedParams,
2793    ) -> JsonRpcResult<Option<refined_request::RefinedModel>> {
2794        Ok(self
2795            .refined_model_at(&params.text_document.uri, params.position, true)
2796            .await)
2797    }
2798
2799    /// #855: `bynk/wireContract` — the wire-contract peek for the handler
2800    /// under the cursor. This server's fourth custom request, modelled on
2801    /// `sequence_model` (file-scoped + position, not project-scoped like
2802    /// `architecture_model` — the panel is per-handler). Served from the
2803    /// committed round; no refresh nudge, for the same reason no custom
2804    /// request needs one. A non-project file, no committed round, an offset
2805    /// outside any handler, or a unit `boundary_info` has no entry for (the
2806    /// pipeline bailed before the checker) all answer `None` (`null` on the
2807    /// wire).
2808    async fn wire_contract(
2809        &self,
2810        params: wire_contract_request::WireContractParams,
2811    ) -> JsonRpcResult<Option<wire_contract_request::WcModel>> {
2812        let uri = params.text_document.uri;
2813        let Some(analysis) = self.committed_analysis(&uri).await else {
2814            return Ok(None);
2815        };
2816        let tys = &analysis.ty_intern;
2817        let Some(rel) = Self::uri_to_rel(&analysis, &uri) else {
2818            return Ok(None);
2819        };
2820        let Some(text) = analysis.snapshots.get(&rel) else {
2821            return Ok(None);
2822        };
2823        let Some(offset) = crate::position::position_to_offset(text, params.position) else {
2824            return Ok(None);
2825        };
2826        // The owning unit — same `own_declaration_name` convention
2827        // `sequence_model` uses to key `sequence_info`.
2828        let Some((unit, _)) = bynk_ide::symbols::own_declaration_name(text) else {
2829            return Ok(None);
2830        };
2831        let Some(info) = analysis.boundary_info.get(&unit) else {
2832            return Ok(None);
2833        };
2834        let expr_types = analysis
2835            .expr_types
2836            .get(&rel)
2837            .map(|v| v.as_slice())
2838            .unwrap_or(&[]);
2839        let context_count = bynk_ide::wire_contract::real_context_count(
2840            &analysis.boundary_info,
2841            &analysis.unit_sources,
2842        );
2843        let Some(model) = bynk_ide::wire_contract::wire_contract_at(
2844            &unit,
2845            text,
2846            offset,
2847            info,
2848            expr_types,
2849            tys,
2850            context_count,
2851        ) else {
2852            return Ok(None);
2853        };
2854        // #848's own search order (self, then `uses`, then `consumes`) —
2855        // reused rather than re-derived, since it is exactly the priority a
2856        // boundary type name resolves through in `ContextBoundaryInfo::types`.
2857        let search_order = analysis
2858            .doc_scope
2859            .get(&unit)
2860            .cloned()
2861            .unwrap_or_else(|| vec![unit.clone()]);
2862        Ok(Some(wire_contract_request::to_wire(
2863            &model,
2864            &analysis.project_root,
2865            text,
2866            &info.types,
2867            &analysis.index,
2868            &analysis.snapshots,
2869            &search_order,
2870        )))
2871    }
2872
2873    /// #2458: the doc-link completion items for `ctx`, in resolution order
2874    /// (`index_queries::doc_link_suggestions`). Each inserts `Name]`, omitting the
2875    /// `]` when one already follows the cursor. Empty for a suite or a file with
2876    /// no committed analysis (its doc comments are out of scope, as for links).
2877    async fn doc_link_completions(
2878        &self,
2879        uri: &Url,
2880        text: &str,
2881        ctx: &bynk_ide::symbols::DocLinkCompletionContext,
2882    ) -> Option<CompletionResponse> {
2883        let analysis = self.committed_analysis(uri).await?;
2884        let (owner_unit, _) = crate::symbols::own_declaration_name(text)?;
2885        let range = Range::new(
2886            crate::position::offset_to_position(text, ctx.replace_start),
2887            crate::position::offset_to_position(text, ctx.replace_end),
2888        );
2889        let rel = Self::uri_to_rel(&analysis, uri);
2890        let no_locals = Vec::new();
2891        let locals = rel
2892            .as_ref()
2893            .and_then(|r| analysis.locals.get(r))
2894            .unwrap_or(&no_locals);
2895        // `ctx.attached` is an offset in the live buffer, but the index and
2896        // locals are the last committed round's: map it into that snapshot,
2897        // or offer no own parts when the two cannot be reconciled.
2898        let link_ctx = rel.as_ref().zip(ctx.attached).and_then(|(path, attached)| {
2899            let snapshot = analysis.snapshots.get(path).map_or(text, |t| t.as_str());
2900            Some(crate::index_queries::DocLinkContext {
2901                path,
2902                text: snapshot,
2903                attached: live_to_snapshot_offset(text, snapshot, attached)?,
2904                locals,
2905            })
2906        });
2907        let suggestions = crate::index_queries::doc_link_suggestions(
2908            &analysis.index,
2909            &analysis.doc_scope,
2910            &owner_unit,
2911            ctx.owner.as_deref(),
2912            link_ctx.as_ref(),
2913        );
2914        let close = if ctx.closed { "" } else { "]" };
2915        let items = suggestions
2916            .into_iter()
2917            .enumerate()
2918            .map(|(i, s)| CompletionItem {
2919                kind: Some(doc_link_item_kind(s.kind)),
2920                detail: Some(if s.kind.is_none() {
2921                    "parameter".to_string()
2922                } else {
2923                    s.unit
2924                }),
2925                sort_text: Some(format!("{i:05}")),
2926                filter_text: Some(s.label.clone()),
2927                text_edit: Some(CompletionTextEdit::Edit(TextEdit::new(
2928                    range,
2929                    format!("{}{close}", s.label),
2930                ))),
2931                label: s.label,
2932                ..Default::default()
2933            })
2934            .collect();
2935        Some(CompletionResponse::Array(items))
2936    }
2937}
2938
2939#[tower_lsp::async_trait]
2940impl LanguageServer for Backend {
2941    async fn initialize(&self, params: InitializeParams) -> JsonRpcResult<InitializeResult> {
2942        // Slice D (Q4): record **every** workspace folder as a discovery seed
2943        // (was `folders.first()` only). Folders do not own URIs — a request
2944        // routes by its nearest enclosing `bynk.toml` (`resolve_root`) — so this
2945        // seeds where `did_change_workspace_folders` prunes and where slice E's
2946        // startup scan looks. Slice E: also capture whether the client accepts a
2947        // server-side `didChangeWatchedFiles` registration, used in `initialized`.
2948        let dynamic_watchers = params
2949            .capabilities
2950            .workspace
2951            .as_ref()
2952            .and_then(|w| w.did_change_watched_files.as_ref())
2953            .and_then(|d| d.dynamic_registration)
2954            .unwrap_or(false);
2955        // #733: whether the client can be nudged to re-pull each pull-based
2956        // decoration after a round commits (the "revalidate" of stale-while-
2957        // revalidate). Absent → the flag stays false and no nudge is sent.
2958        let dynamic_type_hierarchy = params
2959            .capabilities
2960            .text_document
2961            .as_ref()
2962            .and_then(|t| t.type_hierarchy.as_ref())
2963            .and_then(|h| h.dynamic_registration)
2964            .unwrap_or(false);
2965        let ws = params.capabilities.workspace.as_ref();
2966        let supports_refresh = RefreshSupport {
2967            semantic_tokens: ws
2968                .and_then(|w| w.semantic_tokens.as_ref())
2969                .and_then(|s| s.refresh_support)
2970                .unwrap_or(false),
2971            inlay_hints: ws
2972                .and_then(|w| w.inlay_hint.as_ref())
2973                .and_then(|i| i.refresh_support)
2974                .unwrap_or(false),
2975            code_lens: ws
2976                .and_then(|w| w.code_lens.as_ref())
2977                .and_then(|c| c.refresh_support)
2978                .unwrap_or(false),
2979        };
2980        {
2981            let mut state = self.state.write().await;
2982            state.supports_dynamic_watchers = dynamic_watchers;
2983            state.supports_dynamic_type_hierarchy = dynamic_type_hierarchy;
2984            state.supports_refresh = supports_refresh;
2985            state.supports_explain_command = explain_request::client_supports_explain_command(
2986                params.capabilities.experimental.as_ref(),
2987            );
2988            state.supports_capability_path_command =
2989                capability_path::client_supports_command(params.capabilities.experimental.as_ref());
2990            state.supports_refined_explorer_command =
2991                refined_request::client_supports_explorer_command(
2992                    params.capabilities.experimental.as_ref(),
2993                );
2994            if let Some(level) = params
2995                .initialization_options
2996                .as_ref()
2997                .and_then(doc_link_hints::Level::from_settings)
2998            {
2999                state.doc_link_report = level;
3000            }
3001            state.supports_code_action_disabled = params
3002                .capabilities
3003                .text_document
3004                .as_ref()
3005                .and_then(|t| t.code_action.as_ref())
3006                .and_then(|c| c.disabled_support)
3007                .unwrap_or(false);
3008            if let Some(folders) = &params.workspace_folders {
3009                state.folders = folders
3010                    .iter()
3011                    .filter_map(|f| f.uri.to_file_path().ok())
3012                    .map(|p| p.canonicalize().unwrap_or(p))
3013                    .collect();
3014            }
3015        }
3016        Ok(InitializeResult {
3017            capabilities: server_capabilities(),
3018            server_info: Some(ServerInfo {
3019                name: SERVER_NAME.into(),
3020                version: Some(SERVER_VERSION.into()),
3021            }),
3022        })
3023    }
3024
3025    /// #2459: `bynk.docLinks.reportUnresolved` changed — adopt it and
3026    /// re-publish every open project's diagnostics under the new level.
3027    async fn did_change_configuration(&self, params: DidChangeConfigurationParams) {
3028        let Some(level) = doc_link_hints::Level::from_settings(&params.settings) else {
3029            return;
3030        };
3031        let roots: Vec<PathBuf> = {
3032            let mut state = self.state.write().await;
3033            if state.doc_link_report == level {
3034                return;
3035            }
3036            state.doc_link_report = level;
3037            state.projects.keys().cloned().collect()
3038        };
3039        for root in roots {
3040            self.schedule_project_diagnostics(root).await;
3041        }
3042    }
3043
3044    async fn initialized(&self, _: InitializedParams) {
3045        let (folders, dynamic, dynamic_type_hierarchy) = {
3046            let s = self.state.read().await;
3047            (
3048                s.folders.clone(),
3049                s.supports_dynamic_watchers,
3050                s.supports_dynamic_type_hierarchy,
3051            )
3052        };
3053        if dynamic_type_hierarchy {
3054            self.register_type_hierarchy().await;
3055        }
3056        // Slice E (Q4/ADR 0204 §D): register the file watchers server-side, once,
3057        // with folder-independent globs — so any client is notified, and the VS
3058        // Code extension no longer supplies them (avoiding a double
3059        // notification). Only when the client accepts dynamic registration;
3060        // otherwise it is expected to watch files itself.
3061        if dynamic {
3062            self.register_file_watchers().await;
3063        }
3064        // Slice E: warm every project under the workspace folders, so diagnostics
3065        // appear at activation without a file being opened (spec §2.3).
3066        self.warm_projects(&folders).await;
3067        let msg = if folders.is_empty() {
3068            "bynk-lsp: no workspace folders; single-file mode".to_string()
3069        } else {
3070            format!(
3071                "bynk-lsp: {} workspace folder(s); projects resolved per file",
3072                folders.len()
3073            )
3074        };
3075        self.client.log_message(MessageType::INFO, msg).await;
3076    }
3077
3078    async fn shutdown(&self) -> JsonRpcResult<()> {
3079        self.shutdown_requested
3080            .store(true, std::sync::atomic::Ordering::SeqCst);
3081        Ok(())
3082    }
3083
3084    async fn did_open(&self, params: DidOpenTextDocumentParams) {
3085        let uri = params.text_document.uri.clone();
3086        {
3087            let mut state = self.state.write().await;
3088            state.docs.insert(
3089                uri.clone(),
3090                DocumentState {
3091                    text: params.text_document.text,
3092                    version: params.text_document.version,
3093                },
3094            );
3095        }
3096        // Slice D/F: `schedule_diagnostics` routes the URI to its project and
3097        // creates the entry on first touch — no separate root-setting step.
3098        self.schedule_diagnostics(&uri).await;
3099    }
3100
3101    async fn did_change(&self, params: DidChangeTextDocumentParams) {
3102        let uri = params.text_document.uri.clone();
3103        {
3104            let mut state = self.state.write().await;
3105            if let Some(doc) = state.docs.get_mut(&uri)
3106                && let Some(change) = params.content_changes.into_iter().next_back()
3107            {
3108                doc.text = change.text;
3109                doc.version = params.text_document.version;
3110            }
3111        }
3112        // `[lsp] diagnostics_mode = "on_save"`: no per-keystroke rounds — the
3113        // buffer state is updated above and diagnosis waits for `didSave`.
3114        // Slice D: the mode is the *owning project's* (config differs per
3115        // project); a single-file buffer uses the defaults.
3116        if self.config_for(&uri).await.diagnostics_mode == crate::project::DiagnosticsMode::OnSave {
3117            return;
3118        }
3119        // Slice F: hand off to the one scheduler — it debounces once, at the
3120        // configured delay (no manual pre-sleep stacked on the round's own
3121        // debounce), and coalesces a burst to a single analysis.
3122        self.schedule_diagnostics(&uri).await;
3123    }
3124
3125    async fn did_save(&self, params: DidSaveTextDocumentParams) {
3126        // The live path already diagnosed on change; this matters for
3127        // `diagnostics_mode = "on_save"`, where saves are the only trigger.
3128        self.schedule_diagnostics(&params.text_document.uri).await;
3129    }
3130
3131    async fn did_close(&self, params: DidCloseTextDocumentParams) {
3132        let uri = params.text_document.uri;
3133        {
3134            let mut state = self.state.write().await;
3135            state.docs.remove(&uri);
3136            // Slice F: drop the buffer's single-file debounce generation (a no-op
3137            // for a project file, which never had one).
3138            state.single_file_generations.remove(&uri);
3139        }
3140        // Slice D (Q4 §C): closing the last buffer can orphan a project whose
3141        // folder was already removed — it was retained *because* a buffer held
3142        // it. Prune it now and clear its diagnostics, the mirror of the folder
3143        // path, so a fully-orphaned project never lingers with stale squiggles.
3144        for cleared in self.prune_orphaned_projects().await {
3145            self.client
3146                .publish_diagnostics(cleared, Vec::new(), None)
3147                .await;
3148        }
3149    }
3150
3151    /// Transport only: resolve the position, gather the round's tables and the
3152    /// live buffer, and package the result. The resolution *order* — which is the
3153    /// behaviour — lives in [`crate::hover::hover_content`], so it has one
3154    /// definition a test can pin (ADR 0190; #611's gap B was a fall-through bug).
3155    async fn hover(&self, params: HoverParams) -> JsonRpcResult<Option<Hover>> {
3156        let uri = params.text_document_position_params.text_document.uri;
3157        let pos = params.text_document_position_params.position;
3158        // The analysed round, positioned — absent for a file outside it.
3159        let positioned = self.index_position(&uri, pos).await;
3160        // The live buffer — absent when the document is not open. Distinct from
3161        // the snapshot above, which lags while the user types.
3162        let doc_text = {
3163            let state = self.state.read().await;
3164            state.docs.get(&uri).map(|d| d.text.clone())
3165        };
3166        let doc = doc_text
3167            .as_deref()
3168            .and_then(|t| Some((t, crate::position::position_to_offset(t, pos)?)));
3169        let files = self.project_content(&uri).await;
3170        let analysis = positioned
3171            .as_ref()
3172            .map(|(a, rel, offset)| crate::hover::HoverAnalysis {
3173                index: &a.index,
3174                snapshots: &a.snapshots,
3175                locals: &a.locals,
3176                expr_types: &a.expr_types,
3177                tys: &a.ty_intern,
3178                rel,
3179                offset: *offset,
3180                capability_paths: &a.capability_paths,
3181                project_root: &a.project_root,
3182                doc_scope: &a.doc_scope,
3183                boundary_info: &a.boundary_info,
3184                // #855: computed once per round, not re-derived as a bare
3185                // `boundary_info.len()` — see `real_context_count`'s doc.
3186                context_count: bynk_ide::wire_contract::real_context_count(
3187                    &a.boundary_info,
3188                    &a.unit_sources,
3189                ),
3190            });
3191        // #2842: a `matches snapshot` claim hovers with the stored snapshot, read
3192        // from the project's `snapshots/` folder (or "not yet recorded").
3193        let snapshot_hover = match (&positioned, doc) {
3194            (Some((a, rel, _)), Some((text, offset))) => {
3195                let file = crate::symbols::snapshot_file_for(rel);
3196                let stored = std::fs::read_to_string(a.project_root.join(&file)).ok();
3197                crate::symbols::describe_snapshot_at(text, offset, stored.as_deref())
3198            }
3199            _ => None,
3200        };
3201        let content = snapshot_hover.or_else(|| {
3202            crate::hover::hover_content(&crate::hover::HoverInput {
3203                analysis,
3204                doc,
3205                path: uri.to_file_path().ok().as_deref(),
3206                files: files.as_deref(),
3207            })
3208        });
3209        // #2470: a refined type's hover gains its predicates in words and,
3210        // for a client that runs the command, a "Try values…" link.
3211        let content = match content {
3212            Some(value) if value.starts_with("```bynk\ntype ") => {
3213                match self.refined_model_at(&uri, pos, false).await {
3214                    Some(model) => {
3215                        let mut value = format!(
3216                            "{value}\n\n---\n\n{}",
3217                            refined_request::hover_section(&model)
3218                        );
3219                        if self.state.read().await.supports_refined_explorer_command {
3220                            value.push_str(&format!(
3221                                "\n\n{}",
3222                                refined_request::hover_link(uri.as_str(), pos)
3223                            ));
3224                        }
3225                        Some(value)
3226                    }
3227                    None => Some(value),
3228                }
3229            }
3230            other => other,
3231        };
3232        Ok(content.map(|value| Hover {
3233            contents: HoverContents::Markup(MarkupContent {
3234                kind: MarkupKind::Markdown,
3235                value,
3236            }),
3237            range: None,
3238        }))
3239    }
3240
3241    /// v0.32 (ADR 0065): signature help for the call under the cursor.
3242    async fn signature_help(
3243        &self,
3244        params: SignatureHelpParams,
3245    ) -> JsonRpcResult<Option<SignatureHelp>> {
3246        let uri = params.text_document_position_params.text_document.uri;
3247        let pos = params.text_document_position_params.position;
3248        let text = {
3249            let s = self.state.read().await;
3250            s.docs.get(&uri).map(|d| d.text.clone())
3251        };
3252        let Some(text) = text else { return Ok(None) };
3253        let offset = cursor_offset(&text, pos);
3254        let Some(ctx) = crate::signature_help::call_context(&text, offset) else {
3255            return Ok(None);
3256        };
3257        let files = self.project_content(&uri).await;
3258        // Name callees (free fns, statics, capability ops, of/unsafe) — lexical.
3259        // #733: `resolve_label` enumerates the project's units (file stats +
3260        // recovery parse of the cache-missed ones), so run it on the blocking
3261        // pool — signature help fires on every `(`/`,` while typing a call.
3262        let resolved_label = {
3263            let callee = ctx.callee.clone();
3264            let text = text.clone();
3265            let files = files.clone();
3266            match tokio::task::spawn_blocking(move || {
3267                crate::signature_help::resolve_label(&callee, &text, files.as_deref())
3268            })
3269            .await
3270            {
3271                Ok(l) => l,
3272                Err(e) => {
3273                    tracing::error!("signature-help label task failed: {e}");
3274                    None
3275                }
3276            }
3277        };
3278        let label = match resolved_label {
3279            Some(l) => Some(l),
3280            // v0.32 slice 2: a value-receiver method (`xs.fold(`) — type the
3281            // receiver via the rewrite + re-analyse, then the kernel signature.
3282            None => match crate::signature_help::value_receiver_method(&ctx.callee) {
3283                Some((_, method)) => {
3284                    if let Some((rewritten, recv_offset)) =
3285                        crate::signature_help::value_receiver_rewrite(
3286                            &text,
3287                            &ctx.callee,
3288                            ctx.open_paren,
3289                            offset,
3290                        )
3291                        && let Some((ty, tys)) =
3292                            self.type_receiver(&uri, rewritten, recv_offset).await
3293                    {
3294                        crate::signature_help::kernel_method_signature(ty, &tys, method)
3295                    } else {
3296                        None
3297                    }
3298                }
3299                None => None,
3300            },
3301        };
3302        let Some(label) = label else { return Ok(None) };
3303        let active = ctx.active_param as u32;
3304        let parameters: Vec<ParameterInformation> = crate::signature_help::param_ranges(&label)
3305            .into_iter()
3306            .map(|(s, e)| ParameterInformation {
3307                label: ParameterLabel::LabelOffsets([s as u32, e as u32]),
3308                documentation: None,
3309            })
3310            .collect();
3311        Ok(Some(SignatureHelp {
3312            signatures: vec![SignatureInformation {
3313                label,
3314                documentation: None,
3315                parameters: Some(parameters),
3316                active_parameter: Some(active),
3317            }],
3318            active_signature: Some(0),
3319            active_parameter: Some(active),
3320        }))
3321    }
3322
3323    /// v0.33 (ADR 0066): a reference-count lens above each top-level definition,
3324    /// clickable to peek the references. Served from the cached round.
3325    async fn code_lens(&self, params: CodeLensParams) -> JsonRpcResult<Option<Vec<CodeLens>>> {
3326        let uri = params.text_document.uri;
3327        // #733: committed round, no forced re-analysis (see `committed_analysis`).
3328        let analysis = self.committed_analysis(&uri).await;
3329        let Some(analysis) = analysis else {
3330            return Ok(Some(Vec::new()));
3331        };
3332        let Some(rel) = Self::uri_to_rel(&analysis, &uri) else {
3333            return Ok(Some(Vec::new()));
3334        };
3335        let Some(text) = analysis.snapshots.get(&rel) else {
3336            return Ok(Some(Vec::new()));
3337        };
3338        // Peek the references/providers on click — a standard client command,
3339        // so no extension support is required (the client middleware hydrates the
3340        // three-argument shape). Shared by both the reference and provider lenses.
3341        let show_references = |range: Range, locations: Vec<Location>, title: String| CodeLens {
3342            range,
3343            command: Some(Command {
3344                title,
3345                command: "editor.action.showReferences".to_string(),
3346                arguments: Some(vec![
3347                    serde_json::to_value(&uri).unwrap_or_default(),
3348                    serde_json::to_value(range.start).unwrap_or_default(),
3349                    serde_json::to_value(&locations).unwrap_or_default(),
3350                ]),
3351            }),
3352            data: None,
3353        };
3354        let mut lenses: Vec<CodeLens> = crate::index_queries::code_lenses(&analysis.index, &rel)
3355            .into_iter()
3356            .map(|(def, refs)| {
3357                let range = crate::position::span_to_range(text, def.span);
3358                let locations: Vec<Location> = refs
3359                    .iter()
3360                    .filter_map(|r| Self::site_to_location(&analysis, r))
3361                    .collect();
3362                let n = refs.len();
3363                show_references(
3364                    range,
3365                    locations,
3366                    format!("{n} reference{}", if n == 1 { "" } else { "s" }),
3367                )
3368            })
3369            .collect();
3370        // v0.127 (editor-currency slice 6): a `N provider(s)` lens on each
3371        // capability, listing the services that `provides` it. Stacks below the
3372        // reference lens, as a referenced test stacks a reference + test lens.
3373        lenses.extend(
3374            crate::index_queries::capability_provider_lenses(&analysis.index, &rel)
3375                .into_iter()
3376                .map(|(def, providers)| {
3377                    let range = crate::position::span_to_range(text, def.span);
3378                    let locations: Vec<Location> = providers
3379                        .iter()
3380                        .filter_map(|r| Self::site_to_location(&analysis, r))
3381                        .collect();
3382                    let n = providers.len();
3383                    show_references(
3384                        range,
3385                        locations,
3386                        format!("{n} provider{}", if n == 1 { "" } else { "s" }),
3387                    )
3388                }),
3389        );
3390        // v0.129 (#259): a `N refinements of <Base>` lens on each refined/opaque
3391        // type, listing its family — every type over the same builtin base. Stacks
3392        // below the reference lens, like the provider lens on a capability.
3393        lenses.extend(
3394            crate::index_queries::refinement_family_lenses(&analysis.index, &rel)
3395                .into_iter()
3396                .map(|(def, base, family)| {
3397                    let range = crate::position::span_to_range(text, def.span);
3398                    let locations: Vec<Location> = family
3399                        .iter()
3400                        .filter_map(|r| Self::site_to_location(&analysis, r))
3401                        .collect();
3402                    let n = family.len();
3403                    show_references(
3404                        range,
3405                        locations,
3406                        format!("{n} refinements of {}", base.name()),
3407                    )
3408                }),
3409        );
3410        // #846: a "Show Sequence" lens above every handler declaration —
3411        // `bynk.showSequenceDiagram` is a plain extension command (not a
3412        // built-in VS Code command), so its arguments travel as plain JSON
3413        // with no `codelens.ts` hydration needed, unlike `show_references`
3414        // above. A direct AST walk (`handler_lens_sites`), not
3415        // `index_queries::code_lenses` — that only indexes agent handlers
3416        // (`SymbolKind::Handler`; service handlers have no per-handler name)
3417        // and would silently drop the lens for every service handler.
3418        lenses.extend(
3419            crate::sequence_request::handler_lens_sites(text)
3420                .into_iter()
3421                .map(|span| {
3422                    let range = crate::position::span_to_range(text, span);
3423                    CodeLens {
3424                        range,
3425                        command: Some(Command {
3426                            title: "Show Sequence".to_string(),
3427                            command: "bynk.showSequenceDiagram".to_string(),
3428                            arguments: Some(vec![
3429                                serde_json::to_value(&uri).unwrap_or_default(),
3430                                serde_json::to_value(range.start).unwrap_or_default(),
3431                            ]),
3432                        }),
3433                        data: None,
3434                    }
3435                }),
3436        );
3437        // #2196: a "Show State" lens on every agent's name — the state view is
3438        // agent-scoped, so one lens per agent, not per handler.
3439        lenses.extend(
3440            crate::agent_state_request::agent_lens_sites(text)
3441                .into_iter()
3442                .map(|span| {
3443                    let range = crate::position::span_to_range(text, span);
3444                    CodeLens {
3445                        range,
3446                        command: Some(Command {
3447                            title: "Show State".to_string(),
3448                            command: "bynk.showAgentState".to_string(),
3449                            arguments: Some(vec![
3450                                serde_json::to_value(&uri).unwrap_or_default(),
3451                                serde_json::to_value(range.start).unwrap_or_default(),
3452                            ]),
3453                        }),
3454                        data: None,
3455                    }
3456                }),
3457        );
3458        Ok(Some(lenses))
3459    }
3460
3461    async fn prepare_call_hierarchy(
3462        &self,
3463        params: CallHierarchyPrepareParams,
3464    ) -> JsonRpcResult<Option<Vec<CallHierarchyItem>>> {
3465        let uri = params.text_document_position_params.text_document.uri;
3466        let pos = params.text_document_position_params.position;
3467        let Some((analysis, rel, offset)) = self.index_position(&uri, pos).await else {
3468            return Ok(None);
3469        };
3470        let Some((key, def)) =
3471            crate::index_queries::prepare_call_hierarchy(&analysis.index, &rel, offset)
3472        else {
3473            return Ok(None);
3474        };
3475        Ok(Self::call_hierarchy_item(&analysis, key, def).map(|item| vec![item]))
3476    }
3477
3478    async fn incoming_calls(
3479        &self,
3480        params: CallHierarchyIncomingCallsParams,
3481    ) -> JsonRpcResult<Option<Vec<CallHierarchyIncomingCall>>> {
3482        let analysis = self.analysis_for(&params.item.uri).await;
3483        let Some(analysis) = analysis else {
3484            return Ok(Some(Vec::new()));
3485        };
3486        let Some(key) = SerKey::read(&params.item.data) else {
3487            return Ok(Some(Vec::new()));
3488        };
3489        let calls = crate::index_queries::incoming_calls(&analysis.index, &key)
3490            .into_iter()
3491            .filter_map(|rel| {
3492                let from = Self::call_hierarchy_item(&analysis, rel.key, rel.def)?;
3493                let from_ranges = Self::call_ranges(&analysis, &rel.sites);
3494                Some(CallHierarchyIncomingCall { from, from_ranges })
3495            })
3496            .collect();
3497        Ok(Some(calls))
3498    }
3499
3500    async fn outgoing_calls(
3501        &self,
3502        params: CallHierarchyOutgoingCallsParams,
3503    ) -> JsonRpcResult<Option<Vec<CallHierarchyOutgoingCall>>> {
3504        let analysis = self.analysis_for(&params.item.uri).await;
3505        let Some(analysis) = analysis else {
3506            return Ok(Some(Vec::new()));
3507        };
3508        let Some(key) = SerKey::read(&params.item.data) else {
3509            return Ok(Some(Vec::new()));
3510        };
3511        let calls = crate::index_queries::outgoing_calls(&analysis.index, &key)
3512            .into_iter()
3513            .filter_map(|rel| {
3514                let to = Self::call_hierarchy_item(&analysis, rel.key, rel.def)?;
3515                let from_ranges = Self::call_ranges(&analysis, &rel.sites);
3516                Some(CallHierarchyOutgoingCall { to, from_ranges })
3517            })
3518            .collect();
3519        Ok(Some(calls))
3520    }
3521
3522    async fn prepare_type_hierarchy(
3523        &self,
3524        params: TypeHierarchyPrepareParams,
3525    ) -> JsonRpcResult<Option<Vec<TypeHierarchyItem>>> {
3526        let uri = params.text_document_position_params.text_document.uri;
3527        let pos = params.text_document_position_params.position;
3528        let Some((analysis, rel, offset)) = self.index_position(&uri, pos).await else {
3529            return Ok(None);
3530        };
3531        let Some(text) = analysis.snapshots.get(&rel) else {
3532            return Ok(None);
3533        };
3534        let Some(target) =
3535            crate::index_queries::prepare_type_hierarchy(&analysis.index, &rel, text, offset)
3536        else {
3537            return Ok(None);
3538        };
3539        let from = crate::index_queries::unit_of_file(&analysis.index, &rel);
3540        let item = match target {
3541            crate::index_queries::HierarchyTarget::Type(key, def) => {
3542                Self::type_hierarchy_item(&analysis, key, def, from)
3543            }
3544            crate::index_queries::HierarchyTarget::Primitive(base, at) => {
3545                Self::primitive_hierarchy_item(&analysis, base, &at, from)
3546            }
3547        };
3548        Ok(item.map(|item| vec![item]))
3549    }
3550
3551    async fn supertypes(
3552        &self,
3553        params: TypeHierarchySupertypesParams,
3554    ) -> JsonRpcResult<Option<Vec<TypeHierarchyItem>>> {
3555        let Some(analysis) = self.analysis_for(&params.item.uri).await else {
3556            return Ok(Some(Vec::new()));
3557        };
3558        // Only a declared type has a supertype; a primitive is the root.
3559        let Some(TypeHierData::Type { key, from }) = TypeHierData::read(&params.item.data) else {
3560            return Ok(Some(Vec::new()));
3561        };
3562        let Some(key) = key.into_key() else {
3563            return Ok(Some(Vec::new()));
3564        };
3565        let items = crate::index_queries::type_supertype(&analysis.index, &key, from.as_deref())
3566            .and_then(|(base, at)| {
3567                Self::primitive_hierarchy_item(&analysis, base, at, from.as_deref())
3568            })
3569            .into_iter()
3570            .collect();
3571        Ok(Some(items))
3572    }
3573
3574    async fn subtypes(
3575        &self,
3576        params: TypeHierarchySubtypesParams,
3577    ) -> JsonRpcResult<Option<Vec<TypeHierarchyItem>>> {
3578        let Some(analysis) = self.analysis_for(&params.item.uri).await else {
3579            return Ok(Some(Vec::new()));
3580        };
3581        // Bynk has no type derived from a declared type: only a primitive has
3582        // subtypes.
3583        let Some(TypeHierData::Primitive { base, from }) = TypeHierData::read(&params.item.data)
3584        else {
3585            return Ok(Some(Vec::new()));
3586        };
3587        let Some(base) = bynk_syntax::ast::BaseType::from_name(&base) else {
3588            return Ok(Some(Vec::new()));
3589        };
3590        let items = crate::index_queries::type_subtypes(&analysis.index, base, from.as_deref())
3591            .into_iter()
3592            .filter_map(|(key, def)| {
3593                Self::type_hierarchy_item(&analysis, key, def, from.as_deref())
3594            })
3595            .collect();
3596        Ok(Some(items))
3597    }
3598
3599    /// v0.35 (ADR 0068): `textDocument/implementation` — on a capability
3600    /// symbol (its declaration, a `given Cap` use, or a `provides Cap` use),
3601    /// the providers that implement it. `None` for any other symbol (the
3602    /// reverse, provider → capability, is served by goto-definition).
3603    async fn goto_implementation(
3604        &self,
3605        params: GotoImplementationParams,
3606    ) -> JsonRpcResult<Option<GotoImplementationResponse>> {
3607        let uri = params.text_document_position_params.text_document.uri;
3608        let pos = params.text_document_position_params.position;
3609        let Some((analysis, rel, offset)) = self.index_position(&uri, pos).await else {
3610            return Ok(None);
3611        };
3612        let Some((key, _)) = analysis.index.symbol_at(&rel, offset) else {
3613            return Ok(None);
3614        };
3615        if key.kind != bynk_check::index::SymbolKind::Capability {
3616            return Ok(None);
3617        }
3618        let locations: Vec<Location> = crate::index_queries::implementations(&analysis.index, key)
3619            .into_iter()
3620            .filter_map(|d| Self::site_to_location(&analysis, d))
3621            .collect();
3622        if locations.is_empty() {
3623            return Ok(None);
3624        }
3625        Ok(Some(GotoDefinitionResponse::Array(locations)))
3626    }
3627
3628    /// Slice 6: `textDocument/typeDefinition` — from a value at the cursor to the
3629    /// definition of its (user-declared) type. Reads the value's type from the
3630    /// round's `expr_types`, unwraps it to a `Named` target, and returns that
3631    /// type's definition site(s). `None` for a built-in/function/actor type, or
3632    /// a cursor not on a typed expression in a clean round.
3633    async fn goto_type_definition(
3634        &self,
3635        params: GotoTypeDefinitionParams,
3636    ) -> JsonRpcResult<Option<GotoTypeDefinitionResponse>> {
3637        let uri = params.text_document_position_params.text_document.uri;
3638        let pos = params.text_document_position_params.position;
3639        let Some((analysis, rel, offset)) = self.index_position(&uri, pos).await else {
3640            return Ok(None);
3641        };
3642        let tys = &analysis.ty_intern;
3643        let Some(entries) = analysis.expr_types.get(&rel) else {
3644            return Ok(None);
3645        };
3646        let Some(ty) = bynk_check::expr_types::type_at_offset(entries, offset, tys) else {
3647            return Ok(None);
3648        };
3649        let Some(name) = crate::index_queries::named_type_target(ty, tys) else {
3650            return Ok(None);
3651        };
3652        let locations: Vec<Location> =
3653            crate::index_queries::type_definitions_named(&analysis.index, &name)
3654                .into_iter()
3655                .filter_map(|d| Self::site_to_location(&analysis, d))
3656                .collect();
3657        if locations.is_empty() {
3658            return Ok(None);
3659        }
3660        Ok(Some(GotoDefinitionResponse::Array(locations)))
3661    }
3662
3663    /// Slice 6b (ADR 0095): `textDocument/documentLink` — `uses`/`consumes` unit
3664    /// names are clickable to the unit's source. Spans come from parsing the live
3665    /// buffer; the target is the unit's first source file from the round's
3666    /// unit→source map. A first-party `uses` (embedded, no on-disk file) or an
3667    /// unresolved unit yields no link.
3668    ///
3669    /// #848: plus intra-doc links inside the file's own `--- … ---` doc
3670    /// comments — `[Name]`/`[Owner.member]` resolved against the declaring
3671    /// unit's `doc_scope`. Resolves against the full `analysis.index` under
3672    /// the same `committed_analysis` gate as the unit-reference links above;
3673    /// consistent with `code_lens`/`capability_provider_lenses`, which
3674    /// already resolve full-index cross-references under this gate.
3675    async fn document_link(
3676        &self,
3677        params: DocumentLinkParams,
3678    ) -> JsonRpcResult<Option<Vec<DocumentLink>>> {
3679        let uri = params.text_document.uri;
3680        // #733: committed round. Link ranges convert against live `text` here and
3681        // the round only supplies the project-level `unit_sources` map (it changes
3682        // only on a `uses`/`consumes` edit), so a committed round is safe.
3683        let analysis = self.committed_analysis(&uri).await;
3684        let text = self
3685            .state
3686            .read()
3687            .await
3688            .docs
3689            .get(&uri)
3690            .map(|d| d.text.clone());
3691        let (Some(text), Some(analysis)) = (text, analysis) else {
3692            return Ok(None);
3693        };
3694        let mut links: Vec<DocumentLink> = crate::symbols::unit_reference_spans(&text)
3695            .into_iter()
3696            .filter_map(|(unit, span)| {
3697                let rel = analysis.unit_sources.get(&unit)?.first()?;
3698                let target = Url::from_file_path(analysis.project_root.join(rel)).ok()?;
3699                Some(DocumentLink {
3700                    range: crate::position::span_to_range(&text, span),
3701                    target: Some(target),
3702                    tooltip: Some(format!("Open unit `{unit}`")),
3703                    data: None,
3704                })
3705            })
3706            .collect();
3707        // #848 / #2454: a doc link resolves from the declaration its comment
3708        // is attached to, then the unit scope (a suite's is its target
3709        // unit's), then unit-qualified names.
3710        if let Some(owner_unit) = crate::symbols::doc_link_unit(&text) {
3711            let rel = Self::uri_to_rel(&analysis, &uri);
3712            let no_locals = Vec::new();
3713            for link in crate::symbols::doc_link_spans_attached(&text) {
3714                let name = link.name;
3715                let locals = rel
3716                    .as_ref()
3717                    .and_then(|r| analysis.locals.get(r))
3718                    .unwrap_or(&no_locals);
3719                let ctx = rel.as_ref().zip(link.attached).map(|(path, attached)| {
3720                    crate::index_queries::DocLinkContext {
3721                        path,
3722                        text: analysis
3723                            .snapshots
3724                            .get(path)
3725                            .map_or(text.as_str(), |t| t.as_str()),
3726                        attached,
3727                        locals,
3728                    }
3729                });
3730                let Some(target) = crate::symbols::doc_link_url(
3731                    &analysis.index,
3732                    &analysis.doc_scope,
3733                    &analysis.project_root,
3734                    &analysis.snapshots,
3735                    &owner_unit,
3736                    &name,
3737                    ctx.as_ref(),
3738                ) else {
3739                    continue;
3740                };
3741                links.push(DocumentLink {
3742                    range: crate::position::span_to_range(&text, link.span),
3743                    target: Some(target),
3744                    tooltip: Some(format!("Go to `{name}`")),
3745                    data: None,
3746                });
3747            }
3748        }
3749        Ok((!links.is_empty()).then_some(links))
3750    }
3751
3752    async fn completion(
3753        &self,
3754        params: CompletionParams,
3755    ) -> JsonRpcResult<Option<CompletionResponse>> {
3756        let uri = params.text_document_position.text_document.uri;
3757        let pos = params.text_document_position.position;
3758        let text = {
3759            let s = self.state.read().await;
3760            s.docs.get(&uri).map(|d| d.text.clone())
3761        };
3762        let Some(text) = text else { return Ok(None) };
3763        let offset = cursor_offset(&text, pos);
3764        // The line up to the cursor — the context the completion keys off.
3765        // Derived from the converted offset (always a char boundary), not by
3766        // slicing the line at `pos.character` bytes.
3767        let line_prefix = text[..offset].rsplit('\n').next().unwrap_or("").to_string();
3768        // #2458: inside a doc comment, `[` (and typing after it) offers the names
3769        // a doc link would resolve. The `[` trigger character is server-wide, so a
3770        // `[` anywhere else (a list literal) must offer nothing: the cheap
3771        // line-prefix test keeps the tokenising check off the ordinary path.
3772        let doc_ctx = if line_prefix.contains('[') {
3773            bynk_ide::symbols::doc_link_context(&text, offset)
3774        } else {
3775            None
3776        };
3777        if let Some(ctx) = doc_ctx {
3778            return Ok(self.doc_link_completions(&uri, &text, &ctx).await);
3779        }
3780        if params
3781            .context
3782            .as_ref()
3783            .and_then(|c| c.trigger_character.as_deref())
3784            == Some("[")
3785        {
3786            return Ok(None);
3787        }
3788        // #2640: directly inside a `par { … }` block, only its two statement forms.
3789        if completion::in_par_block_position(&text, offset)
3790            && completion::is_keyword_position(&line_prefix)
3791        {
3792            let items = completion::par_block_candidates()
3793                .into_iter()
3794                .map(to_completion_item)
3795                .collect();
3796            return Ok(Some(CompletionResponse::Array(items)));
3797        }
3798        let files = self.project_content(&uri).await;
3799        // #2134: inside a suite's or case's `env { }` block, at a name position,
3800        // offer the secret names actors declare and the `Secrets.get` literals.
3801        if completion::in_env_name_position(&text, offset) {
3802            let items = completion::env_name_candidates(&text, files.as_deref())
3803                .into_iter()
3804                .map(to_completion_item)
3805                .collect();
3806            return Ok(Some(CompletionResponse::Array(items)));
3807        }
3808        // `complete()` enumerates the project's units — file stats and CPU-bound
3809        // recovery parsing (of the buffer, and any project file whose parse cache
3810        // missed). Run it on the blocking pool so a keystroke on a large project
3811        // never stalls the async runtime (#733).
3812        let candidates = {
3813            let line_prefix = line_prefix.clone();
3814            let text = text.clone();
3815            let root = self.root_for_uri(&uri).await;
3816            match tokio::task::spawn_blocking(move || {
3817                completion::complete_in(root.as_deref(), &line_prefix, &text, files.as_deref())
3818            })
3819            .await
3820            {
3821                Ok(c) => c,
3822                // A panic (or cancellation) inside `complete()` degrades to empty
3823                // completions rather than a failed request — but log the
3824                // `JoinError` so the underlying bug is not silently swallowed
3825                // (#776 review).
3826                Err(e) => {
3827                    tracing::error!("completion enumeration task failed: {e}");
3828                    Vec::new()
3829                }
3830            }
3831        };
3832        let mut items: Vec<CompletionItem> =
3833            candidates.into_iter().map(to_completion_item).collect();
3834        // ADR 0064/0093 D3: offer in-scope locals/params at keyword position
3835        // (alongside keywords) and at expression position (alongside the
3836        // constructors + type names `complete()` now yields there). Both are
3837        // places a value or name can begin; the two positions are disjoint.
3838        if completion::is_keyword_position(&line_prefix)
3839            || completion::is_expression_position(&line_prefix)
3840        {
3841            items.extend(self.locals_completions(&uri, pos).await);
3842        }
3843        // v0.124 (slice 3): inside a `requires`/`ensures` predicate, offer the
3844        // enclosing function's parameters (and `result` in an `ensures`),
3845        // merged with whatever the lexical cell yields there — the same
3846        // append-in-scope-names posture as locals above.
3847        items.extend(contract_param_completions(&text, offset, &line_prefix));
3848        // v0.131: inside a `cors { }` block, offer the policy field names; at a
3849        // service-body item start, offer the `cors` section keyword alongside the
3850        // handler-kind keywords the keyword-position cell already yields.
3851        items.extend(cors_completions(&text, offset, &line_prefix));
3852        // v0.141 (ADR 0164): inside a `security { }` block, offer the policy field
3853        // names; at a service-body item start, offer the `security` section keyword.
3854        items.extend(security_completions(&text, offset, &line_prefix));
3855        // v0.140 (ADR 0163): inside `@cache( … )`, offer the annotation argument
3856        // names; at a service-body item start, offer the `@cache` snippet alongside
3857        // the `cors` keyword and handler kinds.
3858        items.extend(cache_completions(&text, offset, &line_prefix));
3859        // v0.142 (ADR 0165): inside a `limits { }` block, offer the policy field
3860        // names; at a service-body item start, offer the `limits` section keyword.
3861        items.extend(limits_completions(&text, offset, &line_prefix));
3862        items.extend(json_completions(&text, offset, &line_prefix));
3863        // v0.142 (ADR 0165): inside `@limit( … )`, offer the annotation argument
3864        // names; at a service-body item start, offer the `@limit` snippet.
3865        items.extend(limit_completions(&text, offset, &line_prefix));
3866        // Inside `@raw( … )`, offer the `contentType` argument; at a service-body
3867        // item start, offer the `@raw` snippet.
3868        items.extend(raw_completions(&text, offset, &line_prefix));
3869        // #3276: at a service-body item start, offer the `@form` snippet.
3870        items.extend(form_completions(&text, offset, &line_prefix));
3871        // #2854: in an `on http` handler's parameter list, offer the special
3872        // parameter names (`query`, `headers`, `body`).
3873        items.extend(http_param_completions(&text, offset));
3874        // #2640: at statement position in an effectful body, the `par` block.
3875        if completion::is_keyword_position(&line_prefix)
3876            && completion::in_effectful_body_position(&text, offset)
3877        {
3878            items.push(to_completion_item(completion::par_snippet()));
3879        }
3880        // P3 (#2342): on a `capability X = …` line, the instantiable bases and
3881        // then a base's required options.
3882        items.extend(
3883            completion::instance_declaration_completions(&line_prefix)
3884                .into_iter()
3885                .map(|(label, detail, insert)| CompletionItem {
3886                    label,
3887                    kind: Some(CompletionItemKind::SNIPPET),
3888                    detail: Some(detail),
3889                    insert_text: Some(insert),
3890                    insert_text_format: Some(InsertTextFormat::SNIPPET),
3891                    ..Default::default()
3892                }),
3893        );
3894        // P3 (#2342): inside `capability X = RateLimit @period(`, offer the
3895        // platform's two windows.
3896        items.extend(
3897            completion::instance_option_values(&text, offset)
3898                .iter()
3899                .map(|(value, doc)| CompletionItem {
3900                    label: value.to_string(),
3901                    kind: Some(CompletionItemKind::VALUE),
3902                    detail: Some((*doc).to_string()),
3903                    ..Default::default()
3904                }),
3905        );
3906        // v0.128: at a `match` arm-pattern-start, prepend the scrutinee's
3907        // variants — the most relevant candidate there. Unlike an `is` position, a
3908        // fresh-line or after-comma arm already looks like a keyword/expression
3909        // position (so `items` is non-empty and the `is_empty` path below never
3910        // fires), hence the merge. The expensive scrutinee typing is gated behind
3911        // the cheap lexical `match_scrutinee_offset` check inside, so ordinary
3912        // keyword-position completion pays only a string scan.
3913        // v0.145 (ADR 0169): a nested constructor position (`Some(‸`) offers the
3914        // payload type's variants; it and the arm-start position are mutually
3915        // exclusive (one is inside a `(`, the other before any), so the two lists
3916        // never overlap. Nested is the more specific position, so it leads.
3917        let mut pattern_items = self.nested_pattern_completions(&uri, &text, offset).await;
3918        pattern_items.extend(self.match_arm_completions(&uri, &text, offset).await);
3919        if !pattern_items.is_empty() {
3920            let mut merged = pattern_items;
3921            merged.extend(items);
3922            stamp_resolve_data(&mut merged, &uri);
3923            return Ok(Some(CompletionResponse::Array(merged)));
3924        }
3925        if items.is_empty() {
3926            // Slice 3: `<expr> is <cursor>` — offer the scrutinee sum type's
3927            // variants, resolved from `expr_types` (the ADR 0063 ceiling).
3928            let is_items = self.is_pattern_completions(&uri, &text, offset).await;
3929            if !is_items.is_empty() {
3930                return Ok(Some(CompletionResponse::Array(is_items)));
3931            }
3932            // A lowercase `receiver.` is a value receiver — type it by
3933            // re-analysing the rewritten buffer and offer its members. (Value
3934            // members name no declared symbol, so they carry no resolve data.)
3935            let value_items = self.value_member_completions(&uri, &text, offset).await;
3936            return Ok((!value_items.is_empty()).then_some(CompletionResponse::Array(value_items)));
3937        }
3938        // Slice 5: stash the doc URI so `completion_resolve` can attach lazy docs.
3939        stamp_resolve_data(&mut items, &uri);
3940        Ok(Some(CompletionResponse::Array(items)))
3941    }
3942
3943    /// Slice 5: fill in hover-quality `documentation` for the focused completion
3944    /// item, reusing the hover renderer (`symbols::describe_symbol`, local then
3945    /// cross-file — §3.4). The originating doc URI is read from the item's
3946    /// `data` (a resolve request carries only the item, not a position). A no-op
3947    /// for an item that names no declared symbol (a keyword, kernel method, or
3948    /// local) — its one-line `detail` already suffices.
3949    async fn completion_resolve(&self, mut item: CompletionItem) -> JsonRpcResult<CompletionItem> {
3950        if item.documentation.is_some() {
3951            return Ok(item);
3952        }
3953        let Some(uri) = item
3954            .data
3955            .as_ref()
3956            .and_then(|d| d.get("uri"))
3957            .and_then(serde_json::Value::as_str)
3958            .and_then(|s| Url::parse(s).ok())
3959        else {
3960            return Ok(item);
3961        };
3962        let local = {
3963            let s = self.state.read().await;
3964            s.docs.get(&uri).map(|d| d.text.clone())
3965        };
3966        let doc = match local
3967            .as_deref()
3968            .and_then(|t| crate::symbols::describe_symbol(t, &item.label))
3969        {
3970            Some(md) => Some(md),
3971            // #733: the cross-file fallback enumerates the project's units (file
3972            // stats + recovery parse of the cache-missed ones); the firstparty
3973            // fallback parses the embedded surface. Both read/parse off the
3974            // blocking pool — completion-item resolve fires as the user arrows
3975            // through the completion list.
3976            None => {
3977                let files = self.project_content(&uri).await;
3978                let uri = uri.clone();
3979                let label = item.label.clone();
3980                match tokio::task::spawn_blocking(move || {
3981                    files
3982                        .and_then(|files| {
3983                            crate::symbols::describe_symbol_cross_file(&files, &uri, &label)
3984                        })
3985                        .map(|(_uri, md)| md)
3986                        // Slice 9: stdlib/surface symbols (e.g. a `uses bynk.list`
3987                        // combinator) live in the embedded first-party sources,
3988                        // not the project's files.
3989                        .or_else(|| crate::symbols::describe_firstparty_symbol(&label))
3990                })
3991                .await
3992                {
3993                    Ok(md) => md,
3994                    Err(e) => {
3995                        tracing::error!("completion-resolve describe task failed: {e}");
3996                        None
3997                    }
3998                }
3999            }
4000        };
4001        if let Some(md) = doc {
4002            item.documentation = Some(Documentation::MarkupContent(MarkupContent {
4003                kind: MarkupKind::Markdown,
4004                value: md,
4005            }));
4006        }
4007        Ok(item)
4008    }
4009
4010    async fn goto_definition(
4011        &self,
4012        params: GotoDefinitionParams,
4013    ) -> JsonRpcResult<Option<GotoDefinitionResponse>> {
4014        let uri = params
4015            .text_document_position_params
4016            .text_document
4017            .uri
4018            .clone();
4019        let pos = params.text_document_position_params.position;
4020        // v0.25 rider: binding-correct definition via the index (fixes the
4021        // name-collision mis-navigation of the string-matching path). The
4022        // legacy path remains as fallback for not-yet-indexed symbol kinds
4023        // (locals, methods, fields, ops).
4024        if let Some((analysis, rel, offset)) = self.index_position(&uri, pos).await {
4025            if let Some((_, def)) =
4026                crate::index_queries::definition_at(&analysis.index, &rel, offset)
4027                && let Some(location) = Self::site_to_location(&analysis, def)
4028            {
4029                return Ok(Some(GotoDefinitionResponse::Scalar(location)));
4030            }
4031            // v0.31: a local binding — scope-correct definition (before the
4032            // string-matching fallback, which can't tell scopes apart).
4033            if let Some(text) = analysis.snapshots.get(&rel)
4034                && let Some(locals) = analysis.locals.get(&rel)
4035                && let Some(def) = crate::locals_nav::local_definition_at(locals, text, offset)
4036                && let Some(location) = self
4037                    .local_locations(&analysis, &rel, &[def])
4038                    .into_iter()
4039                    .next()
4040            {
4041                return Ok(Some(GotoDefinitionResponse::Scalar(location)));
4042            }
4043        }
4044        // Slice 6a follow-up (ADR 0095): the cursor on a `uses`/`consumes` unit
4045        // name jumps to that unit's source. Units aren't index symbols, so the
4046        // unit→source map resolves them; runs before the name-matching path so a
4047        // unit segment can't be mistaken for a like-named type.
4048        if let Some(location) = self.unit_reference_definition(&uri, pos).await {
4049            return Ok(Some(GotoDefinitionResponse::Scalar(location)));
4050        }
4051        let Some((name, _span, text)) = self.identifier_at(&uri, pos).await else {
4052            return Ok(None);
4053        };
4054        if let Some(decl_span) = crate::symbols::find_declaration_span(&text, &name) {
4055            let range = crate::position::span_to_range(&text, decl_span);
4056            return Ok(Some(GotoDefinitionResponse::Scalar(Location {
4057                uri,
4058                range,
4059            })));
4060        }
4061        // Cross-file fallback (v1.1; LSP spec §3.4).
4062        if let Some(files) = self.project_content(&uri).await
4063            && let Some(found) = crate::symbols::find_declaration_cross_file(&files, &uri, &name)
4064        {
4065            let range = crate::position::span_to_range(&found.source, found.span);
4066            return Ok(Some(GotoDefinitionResponse::Scalar(Location {
4067                uri: found.uri,
4068                range,
4069            })));
4070        }
4071        Ok(None)
4072    }
4073
4074    async fn formatting(
4075        &self,
4076        params: DocumentFormattingParams,
4077    ) -> JsonRpcResult<Option<Vec<TextEdit>>> {
4078        let uri = params.text_document.uri;
4079        let text = {
4080            let s = self.state.read().await;
4081            s.docs.get(&uri).map(|d| d.text.clone())
4082        };
4083        let Some(text) = text else { return Ok(None) };
4084        // Slice D: the format options are the owning project's (or the defaults
4085        // in single-file mode).
4086        let opts = self.config_for(&uri).await.format_options();
4087        match bynk_fmt::format_source(&text, &opts) {
4088            Ok(formatted) => {
4089                // #1763: a CRLF buffer whose LF form is canonical needs no edit,
4090                // as on the command line; otherwise every format-on-save would
4091                // rewrite an already-canonical Windows file.
4092                if formatted == bynk_fmt::normalize_line_endings(&text) {
4093                    Ok(Some(Vec::new()))
4094                } else {
4095                    // Replace the entire document.
4096                    let end_pos = crate::position::end_position(&text);
4097                    Ok(Some(vec![TextEdit {
4098                        range: Range {
4099                            start: Position::new(0, 0),
4100                            end: end_pos,
4101                        },
4102                        new_text: formatted,
4103                    }]))
4104                }
4105            }
4106            Err(_) => {
4107                // Formatting failed (parse error). Return no edits; the
4108                // diagnostics flow will surface the parse error.
4109                Ok(Some(Vec::new()))
4110            }
4111        }
4112    }
4113
4114    async fn range_formatting(
4115        &self,
4116        params: DocumentRangeFormattingParams,
4117    ) -> JsonRpcResult<Option<Vec<TextEdit>>> {
4118        // Best-effort: format the whole document. Per spec, range
4119        // formatting may return edits wider than the requested range.
4120        self.formatting(DocumentFormattingParams {
4121            text_document: params.text_document,
4122            options: params.options,
4123            work_done_progress_params: params.work_done_progress_params,
4124        })
4125        .await
4126    }
4127
4128    async fn document_symbol(
4129        &self,
4130        params: DocumentSymbolParams,
4131    ) -> JsonRpcResult<Option<DocumentSymbolResponse>> {
4132        // v1.1 — outline view + Cmd-Shift-O. See `design/bynk-lsp-spec.md` §3.7.
4133        let uri = params.text_document.uri;
4134        let text = {
4135            let s = self.state.read().await;
4136            s.docs.get(&uri).map(|d| d.text.clone())
4137        };
4138        let Some(text) = text else { return Ok(None) };
4139        let syms = crate::document_symbols::outline(&text);
4140        if syms.is_empty() {
4141            return Ok(None);
4142        }
4143        Ok(Some(DocumentSymbolResponse::Nested(syms)))
4144    }
4145
4146    /// v0.37 (ADR 0070): `textDocument/foldingRange` — structural folds + comment
4147    /// runs from the recovered AST (no analysis round).
4148    async fn folding_range(
4149        &self,
4150        params: FoldingRangeParams,
4151    ) -> JsonRpcResult<Option<Vec<FoldingRange>>> {
4152        let uri = params.text_document.uri;
4153        let text = {
4154            let s = self.state.read().await;
4155            s.docs.get(&uri).map(|d| d.text.clone())
4156        };
4157        let Some(text) = text else { return Ok(None) };
4158        Ok(Some(crate::structure::folding_ranges(&text)))
4159    }
4160
4161    /// v0.37 (ADR 0070): `textDocument/selectionRange` — the enclosing-node
4162    /// chain (innermost first) for each requested position.
4163    async fn selection_range(
4164        &self,
4165        params: SelectionRangeParams,
4166    ) -> JsonRpcResult<Option<Vec<SelectionRange>>> {
4167        let uri = params.text_document.uri;
4168        let text = {
4169            let s = self.state.read().await;
4170            s.docs.get(&uri).map(|d| d.text.clone())
4171        };
4172        let Some(text) = text else { return Ok(None) };
4173        Ok(Some(crate::structure::selection_ranges(
4174            &text,
4175            &params.positions,
4176        )))
4177    }
4178
4179    async fn references(&self, params: ReferenceParams) -> JsonRpcResult<Option<Vec<Location>>> {
4180        let uri = params.text_document_position.text_document.uri;
4181        let pos = params.text_document_position.position;
4182        let Some((analysis, rel, offset)) = self.index_position(&uri, pos).await else {
4183            return Ok(None);
4184        };
4185        let include_decl = params.context.include_declaration;
4186        if let Some(sites) =
4187            crate::index_queries::sites_for(&analysis.index, &rel, offset, include_decl)
4188        {
4189            let mut locations: Vec<Location> = sites
4190                .into_iter()
4191                .filter_map(|site| Self::site_to_location(&analysis, site))
4192                .collect();
4193            // #2457: `[Name]` doc-comment mentions that resolve to the symbol.
4194            locations.extend(
4195                Self::doc_mention_sites(&analysis, &rel, offset, None)
4196                    .iter()
4197                    .filter_map(|site| Self::site_to_location(&analysis, site)),
4198            );
4199            return Ok(Some(locations));
4200        }
4201        // v0.31: a local binding — its def + uses, resolved from the snapshot.
4202        if let Some(spans) = self.local_sites(&analysis, &rel, offset) {
4203            let spans = if include_decl {
4204                &spans[..]
4205            } else {
4206                &spans[1..]
4207            }; // def first
4208            let locations = self.local_locations(&analysis, &rel, spans);
4209            return Ok(Some(locations));
4210        }
4211        Ok(None)
4212    }
4213
4214    /// v0.26 (ADR 0054): quick-fixes from structured suggestions. v0.213
4215    /// (ADR 0239) adds the extract-variable refactor
4216    /// (`CodeActionKind::REFACTOR_EXTRACT`), computed from the same snapshot.
4217    /// Track #800 adds the sibling extract-function refactor, additionally
4218    /// fed the round's `requirements`/`locals`/`expr_types` (the
4219    /// capability-free-only gate and the parameter/return type synthesis).
4220    /// Served from the **cached** analysis round only (never a fresh run —
4221    /// slow, and it could disagree with the squiggles the client is
4222    /// showing): a request before the first round, or for a file outside
4223    /// the project, returns the empty list. #804: the combined list is then
4224    /// filtered against `params.context.only`, if the client set it.
4225    async fn code_action(
4226        &self,
4227        params: CodeActionParams,
4228    ) -> JsonRpcResult<Option<CodeActionResponse>> {
4229        let uri = params.text_document.uri;
4230        // #733: committed round. The request range and the diagnostics the fixes
4231        // ride on both convert against the round's snapshot, and the emitted edits
4232        // carry the round's version, so a committed round is self-consistent.
4233        let analysis = self.committed_analysis(&uri).await;
4234        let Some(analysis) = analysis else {
4235            return Ok(Some(Vec::new()));
4236        };
4237        let Some(rel) = Self::uri_to_rel(&analysis, &uri) else {
4238            return Ok(Some(Vec::new()));
4239        };
4240        let (Some(text), Some(diags)) =
4241            (analysis.snapshots.get(&rel), analysis.diagnostics.get(&rel))
4242        else {
4243            return Ok(Some(Vec::new()));
4244        };
4245        // The request range converts against the analysed snapshot (the
4246        // v0.24 rule), like the spans it is intersected with.
4247        let (Some(start), Some(end)) = (
4248            crate::position::position_to_offset(text, params.range.start),
4249            crate::position::position_to_offset(text, params.range.end),
4250        ) else {
4251            return Ok(Some(Vec::new()));
4252        };
4253        let version = analysis.versions.get(&rel).copied();
4254        let span = bynk_syntax::span::Span::new(start, end);
4255        let mut actions = crate::code_actions::quick_fixes(text, diags, span, &uri, version);
4256        // #852: capability-aware header fixes (`add consumes`, auto-`uses`/
4257        // `consumes`), computed from the committed index + a fresh reparse.
4258        actions.extend(crate::capability_fixes::header_quick_fixes(
4259            text,
4260            diags,
4261            span,
4262            &uri,
4263            version,
4264            &analysis.index,
4265        ));
4266        // #2100 slice 3: fill-match-arms, listed without its edit; the edit
4267        // and its re-check run in `code_action_resolve`.
4268        for match_span in crate::fill_arms::fillable(diags, span) {
4269            actions.push(crate::fill_arms::listed(diags, match_span, &uri, version));
4270        }
4271        // #2100 slice 1: inline the local binding under the cursor, listed
4272        // without its edit (resolved and re-checked lazily, like fill-arms).
4273        if let Some(plan) = analysis
4274            .locals
4275            .get(&rel)
4276            .and_then(|locals| crate::inline::offerable(text, span.start, locals))
4277        {
4278            actions.push(crate::inline::listed(&plan, &uri, version));
4279        }
4280        // #2100 slice 4: a provider stub for a capability with none, listed
4281        // without its edit (resolved and re-checked lazily).
4282        for request in crate::provider_stub::requested(text, diags, span) {
4283            if let Some(plan) =
4284                crate::provider_stub::plan(text, &request.capability, &analysis.index)
4285            {
4286                actions.push(crate::provider_stub::listed(
4287                    &plan,
4288                    request.quick_fix,
4289                    &uri,
4290                    version,
4291                ));
4292            }
4293        }
4294        // #2459: did-you-mean fixes for unresolved doc links, carried on the
4295        // published diagnostics the client echoes back.
4296        actions.extend(doc_link_hints::quick_fix_actions(
4297            text,
4298            &params.context.diagnostics,
4299            params.range,
4300            &uri,
4301            version,
4302        ));
4303        actions.extend(crate::extract::extract_variable(text, span, &uri, version));
4304        let empty_reqs = Vec::new();
4305        let empty_locals = Vec::new();
4306        let empty_types = Vec::new();
4307        // #2100 slice 2: extract-function is listed without its edit and
4308        // re-checked in `code_action_resolve`; a capability-using (or `?`-
4309        // containing) selection gets a disabled action saying why, for a
4310        // client that shows those.
4311        let planned = crate::extract::plan_function(
4312            text,
4313            span,
4314            analysis.requirements.get(&rel).unwrap_or(&empty_reqs),
4315            analysis.locals.get(&rel).unwrap_or(&empty_locals),
4316            analysis.expr_types.get(&rel).unwrap_or(&empty_types),
4317            &analysis.ty_intern,
4318        );
4319        let disabled_support = self.state.read().await.supports_code_action_disabled;
4320        actions.extend(crate::extract::function_listed(
4321            &planned,
4322            span,
4323            &uri,
4324            version,
4325            disabled_support,
4326        ));
4327        // #2100: source actions are computed only when the client asks for
4328        // their kind (the Source Action menu, the organise-imports command,
4329        // `editor.codeActionsOnSave`), never for the unfiltered lightbulb
4330        // request every cursor move sends: each one re-analyses the project
4331        // before it is offered (DECISION B).
4332        let only = params.context.only.as_deref();
4333        let wants = |kind: &CodeActionKind| {
4334            only.is_some_and(|only| {
4335                only.iter()
4336                    .any(|requested| crate::code_actions::kind_matches(kind, requested))
4337            })
4338        };
4339        if wants(&CodeActionKind::SOURCE_ORGANIZE_IMPORTS)
4340            && let Some(action) = self.organise_action(&analysis, &rel, &uri, version).await
4341        {
4342            actions.push(action);
4343        }
4344        if wants(&crate::fix_all::kind()) {
4345            let edits = crate::fix_all::edits(text, diags);
4346            if !edits.is_empty()
4347                && self
4348                    .rechecks_clean(&analysis, &rel, crate::fix_all::apply(text, &edits))
4349                    .await
4350            {
4351                actions.push(crate::fix_all::action(text, &edits, &uri, version));
4352            }
4353        }
4354        // #2098: "Explain `code`" for curated codes in range — last, so it never
4355        // preempts a real fix, and only for a client that runs the command.
4356        if self.state.read().await.supports_explain_command {
4357            actions.extend(crate::explain_request::explain_actions(diags, span));
4358        }
4359        // #2469: "Show capability path" on a `given` entry, for a client that runs
4360        // the command.
4361        if self.state.read().await.supports_capability_path_command
4362            && let Some(action) = crate::capability_path::show_action(
4363                &crate::capability_path::PathView {
4364                    graphs: &analysis.capability_paths,
4365                    snapshots: &analysis.snapshots,
4366                    project_root: &analysis.project_root,
4367                    rel: &rel,
4368                },
4369                &uri,
4370                span.start,
4371            )
4372        {
4373            actions.push(action);
4374        }
4375        // #804: honour the client's requested action kinds, if any.
4376        let actions = crate::code_actions::filter_by_only(actions, only);
4377        Ok(Some(actions))
4378    }
4379
4380    /// #2100 slice 3: resolve a listed fill-match-arms action — compute its
4381    /// edit from the committed round and offer it only if the edited project
4382    /// re-checks clean (DECISION B). The round must still be the one the
4383    /// action was listed from (same document version); otherwise, or when
4384    /// the fill doesn't re-check, the resolve is refused with a message the
4385    /// client shows. Any other action resolves to itself.
4386    async fn code_action_resolve(&self, action: CodeAction) -> JsonRpcResult<CodeAction> {
4387        if let Some(target) = crate::inline::Target::of(&action) {
4388            return self.resolve_inline(action, target).await;
4389        }
4390        if let Some(target) = crate::provider_stub::Target::of(&action) {
4391            return self.resolve_provider_stub(action, target).await;
4392        }
4393        if let Some(target) = crate::extract::FunctionTarget::of(&action) {
4394            return self.resolve_extract_function(action, target).await;
4395        }
4396        let Some(target) = crate::fill_arms::Target::of(&action) else {
4397            return Ok(action);
4398        };
4399        let refused = |msg: &str| tower_lsp::jsonrpc::Error {
4400            code: tower_lsp::jsonrpc::ErrorCode::InvalidParams,
4401            message: msg.to_string().into(),
4402            data: None,
4403        };
4404        let stale = "the document changed since the match arms were offered";
4405        let analysis = self
4406            .committed_analysis(&target.uri)
4407            .await
4408            .ok_or_else(|| refused(stale))?;
4409        let rel = Self::uri_to_rel(&analysis, &target.uri).ok_or_else(|| refused(stale))?;
4410        let (Some(text), Some(diags)) =
4411            (analysis.snapshots.get(&rel), analysis.diagnostics.get(&rel))
4412        else {
4413            return Err(refused(stale));
4414        };
4415        let version = analysis.versions.get(&rel).copied();
4416        if version != target.version {
4417            return Err(refused(stale));
4418        }
4419        let edits = crate::fill_arms::edits(text, diags, target.match_span)
4420            .ok_or_else(|| refused("the missing match arms can't be filled here"))?;
4421        let filled = crate::fix_all::apply(text, &edits);
4422        if !self.rechecks_clean(&analysis, &rel, filled).await {
4423            return Err(refused(
4424                "filling the missing match arms would introduce a new problem",
4425            ));
4426        }
4427        Ok(crate::fill_arms::resolve(
4428            action,
4429            text,
4430            &edits,
4431            &target.uri,
4432            version,
4433        ))
4434    }
4435
4436    /// v0.27 (ADR 0056): inferred-type inlay hints for the visible range,
4437    /// served from the cached round only — no cached round (pre-first-
4438    /// analysis, non-project file) returns the empty list. Positions
4439    /// convert against the analysed snapshot (the v0.24 rule).
4440    async fn inlay_hint(&self, params: InlayHintParams) -> JsonRpcResult<Option<Vec<InlayHint>>> {
4441        let uri = params.text_document.uri;
4442        // #733: committed round, no forced re-analysis (see `committed_analysis`).
4443        let analysis = self.committed_analysis(&uri).await;
4444        let Some(analysis) = analysis else {
4445            return Ok(Some(Vec::new()));
4446        };
4447        let Some(rel) = Self::uri_to_rel(&analysis, &uri) else {
4448            return Ok(Some(Vec::new()));
4449        };
4450        let Some(text) = analysis.snapshots.get(&rel) else {
4451            return Ok(Some(Vec::new()));
4452        };
4453        // The visible range converts against the analysed snapshot, like
4454        // the hint spans it is intersected with.
4455        let (Some(start), Some(end)) = (
4456            crate::position::position_to_offset(text, params.range.start),
4457            crate::position::position_to_offset(text, params.range.end),
4458        ) else {
4459            return Ok(Some(Vec::new()));
4460        };
4461        let visible = bynk_syntax::span::Span::new(start, end);
4462        // v0.27: inferred-type hints. v0.99: plus the materializable ghost
4463        // `given` hints for uncovered capability requirements. A file may carry
4464        // one set without the other, so each defaults to empty independently.
4465        let mut hints = analysis
4466            .hints
4467            .get(&rel)
4468            .map(|h| crate::inlay_hints::inlay_hints(text, h, visible))
4469            .unwrap_or_default();
4470        if let Some(reqs) = analysis.requirements.get(&rel) {
4471            hints.extend(crate::inlay_hints::given_hints(text, reqs, visible));
4472        }
4473        Ok(Some(hints))
4474    }
4475
4476    /// #2476: inline values while a debugger is paused — a variable lookup for
4477    /// each local declared in the visible range and still in scope at the
4478    /// stopped location, under the name the emitter gives it, so the debug
4479    /// adapter resolves the value. Served from the committed round, like
4480    /// inlay hints; positions convert against the analysed snapshot.
4481    async fn inline_value(
4482        &self,
4483        params: InlineValueParams,
4484    ) -> JsonRpcResult<Option<Vec<InlineValue>>> {
4485        let uri = params.text_document.uri;
4486        let Some(analysis) = self.committed_analysis(&uri).await else {
4487            return Ok(Some(Vec::new()));
4488        };
4489        let Some(rel) = Self::uri_to_rel(&analysis, &uri) else {
4490            return Ok(Some(Vec::new()));
4491        };
4492        let (Some(text), Some(locals)) = (analysis.snapshots.get(&rel), analysis.locals.get(&rel))
4493        else {
4494            return Ok(Some(Vec::new()));
4495        };
4496        // Names the project declares: what a suite's scaffold may destructure
4497        // into a case's scope (see `inline_value_sites`).
4498        let project_names: std::collections::HashSet<String> = analysis
4499            .index
4500            .symbols
4501            .keys()
4502            .map(|k| k.name.clone())
4503            .collect();
4504        Ok(Some(crate::inline_values::inline_values(
4505            text,
4506            locals,
4507            &project_names,
4508            params.range,
4509            params.context.stopped_location.start,
4510        )))
4511    }
4512
4513    /// v0.28 (ADR 0057): semantic tokens for the whole document, served
4514    /// from the cached round only (no cached round / non-project file →
4515    /// empty), positions against the analysed snapshot (the v0.24 rule).
4516    async fn semantic_tokens_full(
4517        &self,
4518        params: SemanticTokensParams,
4519    ) -> JsonRpcResult<Option<SemanticTokensResult>> {
4520        let data = self
4521            .semantic_tokens_for(&params.text_document.uri, None)
4522            .await;
4523        Ok(Some(SemanticTokensResult::Tokens(SemanticTokens {
4524            result_id: None,
4525            data,
4526        })))
4527    }
4528
4529    /// v0.28 (ADR 0057): the `…/range` variant — the same pure read,
4530    /// filtered to tokens overlapping the requested range.
4531    async fn semantic_tokens_range(
4532        &self,
4533        params: SemanticTokensRangeParams,
4534    ) -> JsonRpcResult<Option<SemanticTokensRangeResult>> {
4535        let data = self
4536            .semantic_tokens_for(&params.text_document.uri, Some(params.range))
4537            .await;
4538        Ok(Some(SemanticTokensRangeResult::Tokens(SemanticTokens {
4539            result_id: None,
4540            data,
4541        })))
4542    }
4543
4544    /// v0.26 rider (ADR 0055): workspace-wide symbol search — the index's
4545    /// definitions, filtered by the query. Slice D (Q4): one server, many
4546    /// projects — aggregate across **every** project. Candidates are the
4547    /// **already-warmed** projects (slice E warms every project under the folders
4548    /// at `initialized`, and the watcher warms one created later), plus each
4549    /// folder's own `resolve_root` — a cheap bounded walk-*up*, the pre-slice-E
4550    /// seeding. No full tree-walk on this request path: a `workspace/symbol`
4551    /// query can fire per keystroke, and the warmed set already holds the nested
4552    /// monorepo projects a walk would rediscover.
4553    async fn symbol(
4554        &self,
4555        params: WorkspaceSymbolParams,
4556    ) -> JsonRpcResult<Option<Vec<SymbolInformation>>> {
4557        let candidates: Vec<(PathBuf, ProjectConfig)> = {
4558            // Snapshot warmed projects + folders under the lock; resolve the
4559            // folders' own roots off it (a bounded walk-up, but still FS I/O).
4560            let (mut set, folders) = {
4561                let state = self.state.read().await;
4562                let known: std::collections::HashMap<PathBuf, ProjectConfig> = state
4563                    .projects
4564                    .iter()
4565                    .map(|(r, p)| (r.clone(), p.config.clone()))
4566                    .collect();
4567                (known, state.folders.clone())
4568            };
4569            for folder in &folders {
4570                if let Some((root, config)) = Self::resolve_root(folder) {
4571                    let root = root.canonicalize().unwrap_or(root);
4572                    set.entry(root).or_insert(config);
4573                }
4574            }
4575            set.into_iter().collect()
4576        };
4577        let mut symbols: Vec<SymbolInformation> = Vec::new();
4578        for (root, config) in candidates {
4579            let Some(analysis) = self.ensure_project_analysed(root, config).await else {
4580                continue;
4581            };
4582            for (key, def) in
4583                crate::index_queries::workspace_symbols(&analysis.index, &params.query)
4584            {
4585                let Some(location) = Self::site_to_location(&analysis, def) else {
4586                    continue;
4587                };
4588                #[allow(deprecated)]
4589                symbols.push(SymbolInformation {
4590                    name: key.name.clone(),
4591                    kind: lsp_symbol_kind(key.kind),
4592                    tags: None,
4593                    deprecated: None,
4594                    location,
4595                    container_name: Some(key.unit.clone()),
4596                });
4597            }
4598        }
4599        // Aggregating across projects (a `HashMap`-derived candidate list) groups
4600        // matches by project in arbitrary order; the spec (§3.11) promises a
4601        // stable `(name, unit)` ordering, so sort the merged result. `unit` is
4602        // the container name.
4603        symbols.sort_by(|a, b| {
4604            a.name
4605                .cmp(&b.name)
4606                .then_with(|| a.container_name.cmp(&b.container_name))
4607        });
4608        Ok(Some(symbols))
4609    }
4610
4611    /// v0.26 rider (ADR 0055): the symbol-at-cursor's occurrences in the
4612    /// active file. `kind` is omitted — the index does not distinguish read
4613    /// from write references.
4614    async fn document_highlight(
4615        &self,
4616        params: DocumentHighlightParams,
4617    ) -> JsonRpcResult<Option<Vec<DocumentHighlight>>> {
4618        let uri = params.text_document_position_params.text_document.uri;
4619        let pos = params.text_document_position_params.position;
4620        let Some((analysis, rel, offset)) = self.index_position(&uri, pos).await else {
4621            return Ok(None);
4622        };
4623        let Some(text) = analysis.snapshots.get(&rel) else {
4624            return Ok(None);
4625        };
4626        if let Some(sites) =
4627            crate::index_queries::document_highlights(&analysis.index, &rel, offset)
4628        {
4629            // #2457: plus this file's own doc-comment mentions of the symbol.
4630            let mentions = Self::doc_mention_sites(&analysis, &rel, offset, Some(&rel));
4631            let highlights: Vec<DocumentHighlight> = sites
4632                .into_iter()
4633                .chain(mentions.iter().filter(|s| s.path == rel))
4634                .map(|s| DocumentHighlight {
4635                    range: crate::position::span_to_range(text, s.span),
4636                    kind: None,
4637                })
4638                .collect();
4639            return Ok(Some(highlights));
4640        }
4641        // v0.31: a local binding's occurrences (def + uses) in the file.
4642        if let Some(spans) = self.local_sites(&analysis, &rel, offset) {
4643            let highlights = spans
4644                .iter()
4645                .map(|s| DocumentHighlight {
4646                    range: crate::position::span_to_range(text, *s),
4647                    kind: None,
4648                })
4649                .collect();
4650            return Ok(Some(highlights));
4651        }
4652        Ok(None)
4653    }
4654
4655    async fn prepare_rename(
4656        &self,
4657        params: TextDocumentPositionParams,
4658    ) -> JsonRpcResult<Option<PrepareRenameResponse>> {
4659        let uri = params.text_document.uri;
4660        let pos = params.position;
4661        // Refuse (None) for anything the index does not cover — locals,
4662        // methods, record fields, capability ops, unit names — rather than
4663        // falling through to a partial or name-matched rename.
4664        let Some((analysis, rel, offset)) = self.index_position(&uri, pos).await else {
4665            return Ok(None);
4666        };
4667        let Some((key, site)) = crate::index_queries::prepare_rename(&analysis.index, &rel, offset)
4668        else {
4669            return Ok(None);
4670        };
4671        let Some(text) = analysis.snapshots.get(&rel) else {
4672            return Ok(None);
4673        };
4674        Ok(Some(PrepareRenameResponse::RangeWithPlaceholder {
4675            range: crate::position::span_to_range(text, site.span),
4676            placeholder: key.name.clone(),
4677        }))
4678    }
4679
4680    async fn rename(&self, params: RenameParams) -> JsonRpcResult<Option<WorkspaceEdit>> {
4681        let uri = params.text_document_position.text_document.uri;
4682        let pos = params.text_document_position.position;
4683        let new_name = params.new_name;
4684        let refused = |msg: String| tower_lsp::jsonrpc::Error {
4685            code: tower_lsp::jsonrpc::ErrorCode::InvalidParams,
4686            message: msg.into(),
4687            data: None,
4688        };
4689        // Slice B: rename emits versioned edits across *every* file that
4690        // references the symbol, so it needs the round current for **all** open
4691        // buffers, not just the cursor's (`analysis_for` would leave a dirty
4692        // non-cursor file stale and its edit would be stamped with an old
4693        // version, which the client rejects). `analysis_covering_open_buffers`
4694        // restores the whole-project freshness the pre-v0.179 `fresh_analysis`
4695        // gave. The cursor's file is one of those buffers, so it is current too;
4696        // resolve `rel`/`offset` against it here (what `index_position` did).
4697        // Slice D (Q4): route by the cursor's project — a rename spans one
4698        // project, so the round need only cover *that* project's buffers.
4699        let Some(root) = self.root_for_uri(&uri).await else {
4700            return Err(refused("rename requires a project (bynk.toml)".into()));
4701        };
4702        let Some(analysis) = self.analysis_covering_open_buffers(&root).await else {
4703            return Err(refused("rename requires a project (bynk.toml)".into()));
4704        };
4705        let Some(rel) = Self::uri_to_rel(&analysis, &uri) else {
4706            return Ok(None);
4707        };
4708        let Some(text) = analysis.snapshots.get(&rel) else {
4709            return Ok(None);
4710        };
4711        let Some(offset) = crate::position::position_to_offset(text, pos) else {
4712            return Ok(None);
4713        };
4714        let mut plan = crate::index_queries::plan_rename(&analysis.index, &rel, offset, &new_name)
4715            .map_err(refused)?;
4716        // #2456: doc links that resolved to the symbol are rewritten with it.
4717        crate::index_queries::add_doc_link_edits(
4718            &mut plan,
4719            &analysis.index,
4720            &analysis.doc_scope,
4721            &analysis.snapshots,
4722            &analysis.locals,
4723        );
4724
4725        // Validator 1 + 2 input: re-analyse with the edits applied. Every
4726        // snapshot is pinned via the overlay so the re-analysis differs from
4727        // the plan's baseline only by the edits themselves.
4728        //
4729        // Slice A: this must re-analyse over the **same roots** the baseline
4730        // round used (`AnalysisRoots::Project`, manifest-aware), not the
4731        // single-tree `diagnose_project`. `diagnose_project(project_root)`
4732        // resolves to `Roots::Single`, which walks the whole tree with **no
4733        // `exclude`** and no `out`/`node_modules` skip — so `post` would cover a
4734        // superset of the baseline's files, and validators 1 and 2 (which
4735        // compare `post` against baselines from the manifest-aware round) would
4736        // read a diagnostic or index site in an excluded tree as *new* and
4737        // refuse a valid rename.
4738        let mut overlay = std::collections::HashMap::new();
4739        for (rel_path, text) in &analysis.snapshots {
4740            let edited = match plan.edits.get(rel_path) {
4741                Some(spans) => crate::index_queries::apply_edits(text, spans, &plan.new_name),
4742                None => text.clone(),
4743            };
4744            let abs = analysis.project_root.join(rel_path);
4745            let abs = abs.canonicalize().unwrap_or(abs);
4746            overlay.insert(abs, edited);
4747        }
4748        let roots = bynk_ide::AnalysisRoots::Project(analysis.project_root.clone());
4749        // #2081: `Off`. Schema-lock diagnostics are project-level: they land
4750        // in `unattributed`, which neither validator compares (both read
4751        // `post.files`), so reading the lock here would cost a `stat` and an
4752        // event sweep for nothing. A rename that changes an event
4753        // non-additively is not refused; the next diagnostics round reports
4754        // it on `bynk.toml`.
4755        let Ok(post) = tokio::task::spawn_blocking(move || {
4756            bynk_ide::diagnose_project_with(&roots, &overlay, &bynk_ide::SchemaLock::Off)
4757        })
4758        .await
4759        else {
4760            return Err(refused("rename validation failed to run".into()));
4761        };
4762
4763        // Validator 1 — collisions: refuse on any new diagnostic.
4764        let post_diags: Vec<(PathBuf, String)> = post
4765            .files
4766            .iter()
4767            .flat_map(|f| {
4768                f.diagnostics
4769                    .iter()
4770                    .map(|d| (f.source_path.clone(), d.error.category.to_string()))
4771            })
4772            .collect();
4773        crate::index_queries::no_new_diagnostics(&analysis.diag_categories(), &post_diags)
4774            .map_err(refused)?;
4775
4776        // Validator 2 — capture/escape: the re-built index must be the old
4777        // index modulo the rename; a silent re-binding has no diagnostic.
4778        if !crate::index_queries::index_unchanged_modulo_rename(&analysis.index, &post.index, &plan)
4779        {
4780            return Err(refused(format!(
4781                "renaming `{}` to `{new_name}` would silently re-bind another name — refused",
4782                plan.key.name
4783            )));
4784        }
4785
4786        // Validator 3 (#2456) — doc links: none may resolve differently.
4787        let edited_texts: std::collections::HashMap<PathBuf, String> = analysis
4788            .snapshots
4789            .iter()
4790            .map(|(p, t)| {
4791                let edited = match plan.edits.get(p) {
4792                    Some(spans) => crate::index_queries::apply_edits(t, spans, &plan.new_name),
4793                    None => t.clone(),
4794                };
4795                (p.clone(), edited)
4796            })
4797            .collect();
4798        crate::index_queries::doc_links_rebound(
4799            (&analysis.index, &analysis.doc_scope, &analysis.locals),
4800            (&post.index, &post.doc_scope, &post.locals),
4801            &analysis.snapshots,
4802            &edited_texts,
4803            &plan,
4804        )
4805        .map_err(refused)?;
4806
4807        // Versioned edits: the client rejects the rename if a buffer drifted
4808        // past the analysed version rather than mis-applying it.
4809        let mut document_edits: Vec<TextDocumentEdit> = Vec::new();
4810        for (rel_path, spans) in &plan.edits {
4811            let Some(text) = analysis.snapshots.get(rel_path) else {
4812                continue;
4813            };
4814            let abs = analysis.project_root.join(rel_path);
4815            let Ok(file_uri) = Url::from_file_path(&abs) else {
4816                continue;
4817            };
4818            let edits: Vec<OneOf<TextEdit, AnnotatedTextEdit>> = spans
4819                .iter()
4820                .map(|span| {
4821                    OneOf::Left(TextEdit {
4822                        range: crate::position::span_to_range(text, *span),
4823                        new_text: plan.new_name.clone(),
4824                    })
4825                })
4826                .collect();
4827            document_edits.push(TextDocumentEdit {
4828                text_document: OptionalVersionedTextDocumentIdentifier {
4829                    uri: file_uri,
4830                    version: analysis.versions.get(rel_path).copied(),
4831                },
4832                edits,
4833            });
4834        }
4835        Ok(Some(WorkspaceEdit {
4836            changes: None,
4837            document_changes: Some(DocumentChanges::Edits(document_edits)),
4838            change_annotations: None,
4839        }))
4840    }
4841
4842    /// #302: `workspace/willRenameFiles` — when a `.bynk` file is renamed or
4843    /// moved, keep `uses`/`consumes` references pointing at its unit in sync.
4844    /// Uses `analysis_covering_open_buffers`, the same gate `rename`
4845    /// uses: this handler emits multi-file **versioned** edits too, so a
4846    /// stale open buffer must be refreshed first or the client rejects the
4847    /// whole edit — unlike `documentLink`'s read-only decoration, which
4848    /// tolerates a round lagging by one debounce cycle.
4849    ///
4850    /// Never refuses: a filesystem rename isn't something this soft,
4851    /// edit-only hook can block (the response is just an optional edit), so
4852    /// anything this can't confidently resolve — an unparseable file, a
4853    /// `suite` (addressed by no one), a rename that preserves the unit's
4854    /// arrangement, a cross-project move, a name collision with an existing
4855    /// unit — is simply skipped rather than erroring the whole batch. The
4856    /// collision check is a lightweight `unit_sources` lookup, not `rename`'s
4857    /// full re-analysis: good enough to avoid handing back an edit that is
4858    /// *known in advance* to break the build, without paying for a second
4859    /// analysis round on every file move.
4860    ///
4861    /// Edits for the moved file's own declaration target `old_uri`, not
4862    /// `new_uri`: the client applies the returned edit against files at
4863    /// their current (pre-move) locations, then performs the actual rename,
4864    /// so the file lands at its new path already carrying the new name.
4865    ///
4866    /// #2105: a `FileRename` may name a **folder** (the capability registers a
4867    /// folder filter too). A folder rename is the same operation as one file
4868    /// rename per `.bynk` file under it, so it is expanded server-side from
4869    /// the round's snapshots (`Self::expand_rename`) and each file goes
4870    /// through the single-file computation. A folder holding no project file
4871    /// expands to nothing. Across the whole request, a file is handled once
4872    /// (a request naming a file *and* its enclosing folder is deduplicated by
4873    /// resolved path), and each renamed unit's references are rewritten once
4874    /// (the files of a multi-file unit all map to the same new name). A move
4875    /// whose destination belongs to a different project root is skipped with
4876    /// a log line (DECISION B): the units' identity changes beyond a rename.
4877    async fn will_rename_files(
4878        &self,
4879        params: RenameFilesParams,
4880    ) -> JsonRpcResult<Option<WorkspaceEdit>> {
4881        let mut combined: std::collections::HashMap<Url, (Option<i32>, Vec<TextEdit>)> =
4882            std::collections::HashMap::new();
4883        // #2105: (project root, project-relative path) of every file handled,
4884        // and (project root, old unit name) of every unit whose references
4885        // were rewritten, across the whole request.
4886        let mut handled_files: std::collections::HashSet<(PathBuf, PathBuf)> =
4887            std::collections::HashSet::new();
4888        let mut renamed_units: std::collections::HashSet<(PathBuf, String)> =
4889            std::collections::HashSet::new();
4890        for fr in &params.files {
4891            let (Ok(old_uri), Ok(new_uri)) = (Url::parse(&fr.old_uri), Url::parse(&fr.new_uri))
4892            else {
4893                continue;
4894            };
4895            let Some(root) = self.root_for_uri(&old_uri).await else {
4896                continue;
4897            };
4898            // DECISION B: a move into another project changes the units'
4899            // identity beyond a rename; leave its references to the user.
4900            if Self::new_path_root(&new_uri).as_ref() != Some(&root) {
4901                tracing::info!(
4902                    "willRenameFiles: {} -> {} leaves project {}; no reference edits",
4903                    fr.old_uri,
4904                    fr.new_uri,
4905                    root.display()
4906                );
4907                continue;
4908            }
4909            let Some(analysis) = self.analysis_covering_open_buffers(&root).await else {
4910                continue;
4911            };
4912            for (old_rel, new_rel) in Self::expand_rename(&analysis, &old_uri, &new_uri) {
4913                if !handled_files.insert((root.clone(), old_rel.clone())) {
4914                    continue;
4915                }
4916                let Some(text) = analysis.snapshots.get(&old_rel) else {
4917                    continue;
4918                };
4919                let Some((old_name, name_span)) = crate::symbols::own_declaration_name(text) else {
4920                    continue;
4921                };
4922                let Some(new_name) = bynk_ide::renamed_unit_name(&old_rel, &old_name, &new_rel)
4923                else {
4924                    // #2105: logged, since inside a folder rename the other
4925                    // units are still edited and this one is moved unchanged.
4926                    tracing::info!(
4927                        "willRenameFiles: {} -> {}: no unit name follows from the new path \
4928                         for `{old_name}`; left unchanged",
4929                        old_rel.display(),
4930                        new_rel.display()
4931                    );
4932                    continue;
4933                };
4934                if new_name == old_name {
4935                    continue;
4936                }
4937                // Refuse to hand back an edit that would create a duplicate unit
4938                // name — some other file already declares `new_name`.
4939                if analysis.unit_sources.contains_key(&new_name) {
4940                    tracing::info!(
4941                        "willRenameFiles: {} -> {}: `{new_name}` is already declared; \
4942                         `{old_name}` left unchanged",
4943                        old_rel.display(),
4944                        new_rel.display()
4945                    );
4946                    continue;
4947                }
4948                // Every file's Url is reconstructed the same way (never the
4949                // client's raw `old_uri`/`new_uri` strings) so the moved file's
4950                // own edit and a referencer's edit merge into the same
4951                // `TextDocumentEdit` when they're the same file — a raw client
4952                // string and a `from_file_path` reconstruction aren't guaranteed
4953                // byte-identical (percent-encoding, trailing slashes).
4954                let Ok(old_file_uri) = Url::from_file_path(analysis.project_root.join(&old_rel))
4955                else {
4956                    continue;
4957                };
4958                // The moved file's own declaration header — edited at its old
4959                // (still current) location.
4960                combined
4961                    .entry(old_file_uri)
4962                    .or_insert_with(|| (analysis.versions.get(&old_rel).copied(), Vec::new()))
4963                    .1
4964                    .push(TextEdit {
4965                        range: crate::position::span_to_range(text, name_span),
4966                        new_text: new_name.clone(),
4967                    });
4968                // #2105: the files of a multi-file unit share its name, so its
4969                // references are rewritten for the first of them only — a
4970                // second pass would emit the same, overlapping, edits again.
4971                if !renamed_units.insert((root.clone(), old_name.clone())) {
4972                    continue;
4973                }
4974                // Every other file's `uses`/`consumes` references to the old name.
4975                for (rel, snap_text) in &analysis.snapshots {
4976                    if *rel == old_rel {
4977                        continue;
4978                    }
4979                    let edits: Vec<TextEdit> = crate::symbols::unit_reference_spans(snap_text)
4980                        .into_iter()
4981                        .filter(|(unit, _)| *unit == old_name)
4982                        .map(|(_, span)| TextEdit {
4983                            range: crate::position::span_to_range(snap_text, span),
4984                            new_text: new_name.clone(),
4985                        })
4986                        .collect();
4987                    if edits.is_empty() {
4988                        continue;
4989                    }
4990                    let Ok(file_uri) = Url::from_file_path(analysis.project_root.join(rel)) else {
4991                        continue;
4992                    };
4993                    combined
4994                        .entry(file_uri)
4995                        .or_insert_with(|| (analysis.versions.get(rel).copied(), Vec::new()))
4996                        .1
4997                        .extend(edits);
4998                }
4999            }
5000        }
5001        if combined.is_empty() {
5002            return Ok(None);
5003        }
5004        let document_edits: Vec<TextDocumentEdit> = combined
5005            .into_iter()
5006            .map(|(uri, (version, edits))| TextDocumentEdit {
5007                text_document: OptionalVersionedTextDocumentIdentifier { uri, version },
5008                edits: edits.into_iter().map(OneOf::Left).collect(),
5009            })
5010            .collect();
5011        Ok(Some(WorkspaceEdit {
5012            changes: None,
5013            document_changes: Some(DocumentChanges::Edits(document_edits)),
5014            change_annotations: None,
5015        }))
5016    }
5017
5018    async fn did_change_watched_files(&self, params: DidChangeWatchedFilesParams) {
5019        // #682: a `bynk.toml` create/delete/change is the one event that can
5020        // move an already-cached URI's route (see `State.root_cache`'s doc) —
5021        // invalidate the whole cache before this batch's lookups consult it,
5022        // so a manifest that just appeared/vanished is reflected within the
5023        // same round rather than one event late. The generation bump closes
5024        // `root_for_uri`'s TOCTOU window against a walk already in flight.
5025        if params.changes.iter().any(|ev| is_bynk_toml(&ev.uri)) {
5026            let mut state = self.state.write().await;
5027            state.root_cache.clear();
5028            state.root_cache_generation += 1;
5029        }
5030        // For every changed `.bynk` file we have open, refresh diagnostics.
5031        // Changes to files we do *not* have open (a git checkout, an external
5032        // edit) still invalidate the project index — schedule a project round
5033        // so cross-file state doesn't go stale (#513).
5034        let mut uris_to_refresh = Vec::new();
5035        // Slice D: route each change to its owning project root, so a change in
5036        // project A never re-analyses project B.
5037        let mut roots_to_reanalyse: std::collections::HashSet<PathBuf> =
5038            std::collections::HashSet::new();
5039        // A `bynk.toml` edit changes the formatting style, the diagnostics
5040        // mode/debounce, and the source root — none of which were re-read after
5041        // the initial load, so the settings only took effect on an LSP restart.
5042        // Detect the change here and reload that project's config before
5043        // re-analysing it.
5044        let mut config_changed_roots: std::collections::HashSet<PathBuf> =
5045            std::collections::HashSet::new();
5046        // #682: snapshotted off the lock — the loop below calls the
5047        // cache-consulting `root_for_uri`, which itself locks `state`, so it
5048        // must not run while a read lock from this function is still held.
5049        let open_docs: std::collections::HashSet<Url> =
5050            self.state.read().await.docs.keys().cloned().collect();
5051        for ev in &params.changes {
5052            if is_bynk_toml(&ev.uri) {
5053                // The manifest's own directory is the project root.
5054                if let Ok(p) = ev.uri.to_file_path()
5055                    && let Some(dir) = p.parent()
5056                {
5057                    let root = dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf());
5058                    config_changed_roots.insert(root.clone());
5059                    roots_to_reanalyse.insert(root);
5060                }
5061            } else if schema_lock::is_schema_lock(&ev.uri) {
5062                // #2081: the lock's own directory is the project root. Drop
5063                // its cached content and re-analyse, so the editor shows the
5064                // new lock's verdict without waiting for an edit.
5065                if let Ok(p) = ev.uri.to_file_path()
5066                    && let Some(dir) = p.parent()
5067                {
5068                    let root = dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf());
5069                    if let Some(ps) = self.state.write().await.projects.get_mut(&root) {
5070                        ps.schema_lock.invalidate();
5071                    }
5072                    roots_to_reanalyse.insert(root);
5073                }
5074            } else if open_docs.contains(&ev.uri) {
5075                uris_to_refresh.push(ev.uri.clone());
5076            } else if (ev.uri.path().ends_with(".bynk") || is_fixture_file(&ev.uri))
5077                && let Some(root) = self.root_for_uri(&ev.uri).await
5078            {
5079                // #2841: an edit to a fixture file re-analyses its project, so
5080                // a `fixture` that now names a missing file (or a restored one)
5081                // shows at once.
5082                roots_to_reanalyse.insert(root);
5083            }
5084        }
5085        // A `bynk.toml` change reloads its project's config — and, if the
5086        // manifest was just *created*, warms the new project (create the entry).
5087        // Slice E: this is how a project added after startup is picked up now
5088        // that `workspace/symbol` no longer walks the tree per query.
5089        for root in &config_changed_roots {
5090            let config = project::load_config(root).unwrap_or_default();
5091            let mut state = self.state.write().await;
5092            state
5093                .projects
5094                .entry(root.clone())
5095                .and_modify(|ps| ps.config = config.clone())
5096                .or_insert_with(|| ProjectState {
5097                    config,
5098                    ..Default::default()
5099                });
5100        }
5101        for uri in uris_to_refresh {
5102            self.schedule_diagnostics(&uri).await;
5103        }
5104        // A reloaded config re-derives the diagnostics behaviour, so re-analyse
5105        // each affected project against it — the same debounced round a non-open
5106        // `.bynk` change schedules. A no-op for a root with no entry (a project
5107        // no file has opened): nothing is published there to go stale.
5108        for root in roots_to_reanalyse {
5109            self.schedule_project_diagnostics(root).await;
5110        }
5111    }
5112
5113    async fn did_change_workspace_folders(&self, params: DidChangeWorkspaceFoldersParams) {
5114        // Slice D (Q4): folders are discovery seeds, not routing owners.
5115        // Added folders extend the seed set; removed folders shrink it, then any
5116        // project a removed folder orphaned — no remaining folder, no open
5117        // buffer — is pruned.
5118        let added_dirs: Vec<PathBuf> = {
5119            let mut state = self.state.write().await;
5120            let mut added = Vec::new();
5121            for a in &params.event.added {
5122                if let Ok(p) = a.uri.to_file_path() {
5123                    let dir = p.canonicalize().unwrap_or(p);
5124                    if !state.folders.contains(&dir) {
5125                        state.folders.push(dir.clone());
5126                        added.push(dir);
5127                    }
5128                }
5129            }
5130            for removed in &params.event.removed {
5131                if let Ok(p) = removed.uri.to_file_path() {
5132                    let dir = p.canonicalize().unwrap_or(p);
5133                    state.folders.retain(|f| f != &dir);
5134                }
5135            }
5136            // #682: `resolve_canonical` never consults `folders` — a folder
5137            // change cannot actually move any URI's route today — but clear
5138            // (and bump the generation, same as the `bynk.toml` case) as a
5139            // defensive, effectively-free no-op against that ever changing,
5140            // rather than relying on routing's independence from folders
5141            // staying true forever.
5142            state.root_cache.clear();
5143            state.root_cache_generation += 1;
5144            added
5145        };
5146        // Slice E: warm the added folders proactively — the analysis D deferred
5147        // to here, using the same discovery walk as startup.
5148        self.warm_projects(&added_dirs).await;
5149        // Clear the dropped projects' diagnostics so the client does not keep
5150        // showing stale squiggles for a folder that is gone.
5151        for uri in self.prune_orphaned_projects().await {
5152            self.client.publish_diagnostics(uri, Vec::new(), None).await;
5153        }
5154    }
5155}
5156
5157/// The advertised capability set — `design/bynk-lsp-spec.md` §4.3. Split out
5158/// of `initialize` so the advertisement is unit-testable without transport.
5159fn server_capabilities() -> ServerCapabilities {
5160    ServerCapabilities {
5161        // Full-text sync, with save notifications explicitly opted in — the
5162        // `on_save` diagnostics mode is driven by `didSave` (#513).
5163        text_document_sync: Some(TextDocumentSyncCapability::Options(
5164            TextDocumentSyncOptions {
5165                open_close: Some(true),
5166                change: Some(TextDocumentSyncKind::FULL),
5167                save: Some(TextDocumentSyncSaveOptions::Supported(true)),
5168                ..Default::default()
5169            },
5170        )),
5171        hover_provider: Some(HoverProviderCapability::Simple(true)),
5172        definition_provider: Some(OneOf::Left(true)),
5173        // v0.17: completion for `consumes` units and `given` /
5174        // `consumes U { … }` capabilities. Trigger on the space after a
5175        // keyword, the `{` of a selected-capability list, and `,`. The `.`
5176        // auto-fires the name- and value-receiver member contexts (ADR 0093 D1).
5177        completion_provider: Some(CompletionOptions {
5178            trigger_characters: Some(vec![
5179                " ".to_string(),
5180                "{".to_string(),
5181                ",".to_string(),
5182                ".".to_string(),
5183                // #2458: doc-link completion; gated to doc ranges in the handler.
5184                "[".to_string(),
5185                // #2686: `@example` after a refinement.
5186                "@".to_string(),
5187            ]),
5188            // Slice 5: resolve fills in hover-quality `documentation` lazily, on
5189            // the focused item only, so the initial list stays cheap.
5190            resolve_provider: Some(true),
5191            ..Default::default()
5192        }),
5193        // v0.32 (ADR 0065): signature help while typing a call's arguments.
5194        signature_help_provider: Some(SignatureHelpOptions {
5195            trigger_characters: Some(vec!["(".to_string(), ",".to_string()]),
5196            retrigger_characters: Some(vec![",".to_string()]),
5197            ..Default::default()
5198        }),
5199        // v0.33 (ADR 0066): reference-count lenses above top-level definitions.
5200        code_lens_provider: Some(CodeLensOptions {
5201            resolve_provider: Some(false),
5202        }),
5203        // v0.34 (ADR 0067): call hierarchy over the binding index's call graph.
5204        call_hierarchy_provider: Some(CallHierarchyServerCapability::Simple(true)),
5205        // v0.35 (ADR 0068): implementation nav — capability → its providers.
5206        implementation_provider: Some(ImplementationProviderCapability::Simple(true)),
5207        // Slice 6: go-to-type-definition (value → its type's declaration).
5208        type_definition_provider: Some(TypeDefinitionProviderCapability::Simple(true)),
5209        // Slice 6b: `uses`/`consumes` unit names link to their source.
5210        document_link_provider: Some(DocumentLinkOptions {
5211            resolve_provider: Some(false),
5212            work_done_progress_options: Default::default(),
5213        }),
5214        document_formatting_provider: Some(OneOf::Left(true)),
5215        document_range_formatting_provider: Some(OneOf::Left(true)),
5216        document_symbol_provider: Some(OneOf::Left(true)),
5217        // v0.37 (ADR 0070): structural folding + selection ranges (AST-driven).
5218        folding_range_provider: Some(FoldingRangeProviderCapability::Simple(true)),
5219        selection_range_provider: Some(SelectionRangeProviderCapability::Simple(true)),
5220        // v0.25 (ADR 0053): references + rename over the binding
5221        // index; prepareRename refuses out-of-scope symbols.
5222        references_provider: Some(OneOf::Left(true)),
5223        rename_provider: Some(OneOf::Right(RenameOptions {
5224            prepare_provider: Some(true),
5225            work_done_progress_options: Default::default(),
5226        })),
5227        // v0.26 (ADR 0054): quick-fixes from the diagnostics' structured
5228        // suggestions. v0.213 (ADR 0239) adds the extract-variable refactor.
5229        code_action_provider: Some(CodeActionProviderCapability::Options(CodeActionOptions {
5230            code_action_kinds: Some(vec![
5231                CodeActionKind::QUICKFIX,
5232                CodeActionKind::REFACTOR,
5233                CodeActionKind::REFACTOR_EXTRACT,
5234                CodeActionKind::REFACTOR_INLINE,
5235                CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
5236                crate::fix_all::kind(),
5237            ]),
5238            // #2100 slice 3: fill-match-arms computes its edit lazily.
5239            resolve_provider: Some(true),
5240            ..Default::default()
5241        })),
5242        // v0.27 (ADR 0056): inferred-type inlay hints from the retained
5243        // analysis round's harvested hint set.
5244        inlay_hint_provider: Some(OneOf::Left(true)),
5245        // #2476: inline values while debugging, from the locals table.
5246        inline_value_provider: Some(OneOf::Right(InlineValueServerCapabilities::Options(
5247            InlineValueOptions {
5248                work_done_progress_options: Default::default(),
5249            },
5250        ))),
5251        // v0.28 (ADR 0057): semantic tokens over the frozen legend — a
5252        // pure read of the cached index (`symbols` + `foreign_refs`),
5253        // additive over the client's syntactic layer. `delta` deferred.
5254        semantic_tokens_provider: Some(SemanticTokensServerCapabilities::SemanticTokensOptions(
5255            SemanticTokensOptions {
5256                legend: crate::index_queries::semantic_tokens_legend(),
5257                full: Some(SemanticTokensFullOptions::Bool(true)),
5258                range: Some(true),
5259                ..Default::default()
5260            },
5261        )),
5262        // v0.26 riders (ADR 0055): both are `ProjectIndex` queries.
5263        workspace_symbol_provider: Some(OneOf::Left(true)),
5264        document_highlight_provider: Some(OneOf::Left(true)),
5265        workspace: Some(WorkspaceServerCapabilities {
5266            workspace_folders: Some(WorkspaceFoldersServerCapabilities {
5267                supported: Some(true),
5268                change_notifications: Some(OneOf::Left(true)),
5269            }),
5270            // #302: `willRenameFiles` over `.bynk` files keeps `uses`/`consumes`
5271            // references in sync on a file rename/move. #2105: a second filter
5272            // matches every folder (a folder's name can't say whether it holds
5273            // `.bynk` files); the handler expands it from the round's snapshots,
5274            // and one holding no project file produces no edit.
5275            file_operations: Some(WorkspaceFileOperationsServerCapabilities {
5276                will_rename: Some(FileOperationRegistrationOptions {
5277                    filters: vec![
5278                        FileOperationFilter {
5279                            scheme: Some("file".to_string()),
5280                            pattern: FileOperationPattern {
5281                                glob: "**/*.bynk".to_string(),
5282                                matches: Some(FileOperationPatternKind::File),
5283                                options: None,
5284                            },
5285                        },
5286                        FileOperationFilter {
5287                            scheme: Some("file".to_string()),
5288                            pattern: FileOperationPattern {
5289                                glob: "**".to_string(),
5290                                matches: Some(FileOperationPatternKind::Folder),
5291                                options: None,
5292                            },
5293                        },
5294                    ],
5295                }),
5296                ..Default::default()
5297            }),
5298        }),
5299        // #846/#847: no standard `ServerCapabilities` field exists for a custom
5300        // request — `experimental` is the only feature-detection surface a
5301        // client has for `bynk/sequenceModel`, `bynk/documentationModel`, and
5302        // `bynk/architectureModel`.
5303        experimental: Some(custom_request_capabilities()),
5304        ..Default::default()
5305    }
5306}
5307
5308/// #2545: the single table of `bynk/…` custom requests. Each row is the
5309/// `experimental` capability flag, the wire method, and the handler; both the
5310/// `ServerCapabilities.experimental` block ([`custom_request_capabilities`])
5311/// and the builder registration ([`register_custom_requests`]) are generated
5312/// from it, so a new request is one added row.
5313macro_rules! custom_requests {
5314    ($($flag:literal => $method:literal, $handler:path;)*) => {
5315        /// The `experimental` capability block: one `true` flag per custom
5316        /// request — the only feature-detection surface a client has, since
5317        /// `ServerCapabilities` has no field for a custom request.
5318        fn custom_request_capabilities() -> serde_json::Value {
5319            serde_json::json!({ $($flag: true,)* })
5320        }
5321
5322        /// Register every custom request on the service builder (they have no
5323        /// `LanguageServer` trait slot, so `LspService::new` cannot see them).
5324        fn register_custom_requests(
5325            builder: tower_lsp::LspServiceBuilder<Backend>,
5326        ) -> tower_lsp::LspServiceBuilder<Backend> {
5327            builder$(.custom_method($method, $handler))*
5328        }
5329    };
5330}
5331
5332custom_requests! {
5333    "sequenceModel" => "bynk/sequenceModel", Backend::sequence_model;
5334    "agentStateModel" => "bynk/agentStateModel", Backend::agent_state_model;
5335    "documentationModel" => "bynk/documentationModel", Backend::documentation_model;
5336    "architectureModel" => "bynk/architectureModel", Backend::architecture_model;
5337    "wireContract" => "bynk/wireContract", Backend::wire_contract;
5338    "contractDiff" => "bynk/contractDiff", Backend::contract_diff;
5339    "explain" => "bynk/explain", Backend::explain;
5340    "refinedTypeModel" => "bynk/refinedTypeModel", Backend::refined_type_model;
5341}
5342
5343/// Index symbol kind → LSP symbol kind, aligned with the document-symbol
5344/// outline's choices (capability=INTERFACE, service/agent=CLASS,
5345/// provider=OBJECT). The index does not distinguish type shapes, so every
5346/// type maps to STRUCT.
5347/// Map a `completion::Completion` to an LSP `CompletionItem`.
5348/// Stash the document URI in each item's `data` so `completion_resolve` can look
5349/// the symbol up — a resolve request carries only the item, not a position.
5350fn stamp_resolve_data(items: &mut [CompletionItem], uri: &Url) {
5351    let data = serde_json::json!({ "uri": uri.to_string() });
5352    for item in items.iter_mut() {
5353        item.data = Some(data.clone());
5354    }
5355}
5356
5357/// v0.124 (slice 3): the enclosing function's parameters (and `result` for an
5358/// `ensures`) as completions, when `offset` sits in a `requires`/`ensures`
5359/// predicate. Empty when not in a contract clause or no enclosing `fn` is
5360/// found. A pure parse — the params are read straight off the recovered AST.
5361/// v0.131: the CORS completion cells. Inside a `cors { }` block at a field-name
5362/// position, offer the closed field set; at a service-body item start, offer the
5363/// `cors` section keyword. Both are lexical (offset-based), matching the
5364/// `contract_param_completions` posture.
5365fn cors_completions(text: &str, offset: usize, line: &str) -> Vec<CompletionItem> {
5366    if completion::in_cors_field_position(text, offset) {
5367        return completion::CORS_FIELDS
5368            .iter()
5369            .map(|(name, doc)| CompletionItem {
5370                label: name.to_string(),
5371                kind: Some(CompletionItemKind::FIELD),
5372                detail: Some((*doc).to_string()),
5373                insert_text: Some(format!("{name}: ")),
5374                ..Default::default()
5375            })
5376            .collect();
5377    }
5378    if completion::in_service_body_item_position(text, offset, line) {
5379        return vec![CompletionItem {
5380            label: "cors".to_string(),
5381            kind: Some(CompletionItemKind::KEYWORD),
5382            detail: Some("a cross-origin (CORS) policy for this HTTP service".to_string()),
5383            insert_text: Some("cors {\n\torigins: [$0],\n}".to_string()),
5384            insert_text_format: Some(InsertTextFormat::SNIPPET),
5385            ..Default::default()
5386        }];
5387    }
5388    Vec::new()
5389}
5390
5391/// v0.141 (ADR 0164): the security-headers completion cells. Inside a
5392/// `security { }` block at a field-name position, offer the closed field set
5393/// (`nosniff`/`hsts`); at a service-body item start, offer the `security` section
5394/// keyword. Both are lexical (offset-based), mirroring `cors_completions`.
5395fn security_completions(text: &str, offset: usize, line: &str) -> Vec<CompletionItem> {
5396    if completion::in_security_field_position(text, offset) {
5397        return completion::SECURITY_FIELDS
5398            .iter()
5399            .map(|(name, doc)| CompletionItem {
5400                label: name.to_string(),
5401                kind: Some(CompletionItemKind::FIELD),
5402                detail: Some((*doc).to_string()),
5403                insert_text: Some(format!("{name}: ")),
5404                ..Default::default()
5405            })
5406            .collect();
5407    }
5408    if completion::in_service_body_item_position(text, offset, line) {
5409        return vec![CompletionItem {
5410            label: "security".to_string(),
5411            kind: Some(CompletionItemKind::KEYWORD),
5412            detail: Some("security response headers for this HTTP service".to_string()),
5413            insert_text: Some("security {\n\tnosniff: $0,\n}".to_string()),
5414            insert_text_format: Some(InsertTextFormat::SNIPPET),
5415            ..Default::default()
5416        }];
5417    }
5418    Vec::new()
5419}
5420
5421/// v0.140 (ADR 0163): the `@cache` completion cells. Inside `@cache( … )` at an
5422/// argument-name position, offer the closed argument set (`maxAge`/`scope`/`immutable`); at a
5423/// service-body item start, offer the `@cache` annotation snippet. Both are lexical
5424/// (offset-based), mirroring `cors_completions`.
5425fn cache_completions(text: &str, offset: usize, line: &str) -> Vec<CompletionItem> {
5426    if completion::in_cache_arg_position(text, offset) {
5427        return completion::CACHE_ARGS
5428            .iter()
5429            .map(|(name, doc)| CompletionItem {
5430                label: name.to_string(),
5431                kind: Some(CompletionItemKind::FIELD),
5432                detail: Some((*doc).to_string()),
5433                insert_text: Some(format!("{name}: ")),
5434                ..Default::default()
5435            })
5436            .collect();
5437    }
5438    if completion::in_service_body_item_position(text, offset, line) {
5439        return vec![CompletionItem {
5440            label: "@cache".to_string(),
5441            kind: Some(CompletionItemKind::SNIPPET),
5442            detail: Some(
5443                "cache a GET read — a synthesised ETag/304 revalidation with a freshness window"
5444                    .to_string(),
5445            ),
5446            insert_text: Some("@cache(maxAge: ${1:5.minutes})".to_string()),
5447            insert_text_format: Some(InsertTextFormat::SNIPPET),
5448            ..Default::default()
5449        }];
5450    }
5451    Vec::new()
5452}
5453
5454/// v0.142 (ADR 0165): the request-limits completion cells. Inside a `limits { }`
5455/// block at a field-name position, offer the closed field set (`maxBody`); at a
5456/// service-body item start, offer the `limits` section keyword. Both are lexical
5457/// (offset-based), mirroring `security_completions`.
5458fn limits_completions(text: &str, offset: usize, line: &str) -> Vec<CompletionItem> {
5459    if completion::in_limits_field_position(text, offset) {
5460        return completion::LIMITS_FIELDS
5461            .iter()
5462            .map(|(name, doc)| CompletionItem {
5463                label: name.to_string(),
5464                kind: Some(CompletionItemKind::FIELD),
5465                detail: Some((*doc).to_string()),
5466                insert_text: Some(format!("{name}: ")),
5467                ..Default::default()
5468            })
5469            .collect();
5470    }
5471    if completion::in_service_body_item_position(text, offset, line) {
5472        return vec![CompletionItem {
5473            label: "limits".to_string(),
5474            kind: Some(CompletionItemKind::KEYWORD),
5475            detail: Some("request limits for this HTTP service".to_string()),
5476            insert_text: Some("limits {\n\tmaxBody: $0,\n}".to_string()),
5477            insert_text_format: Some(InsertTextFormat::SNIPPET),
5478            ..Default::default()
5479        }];
5480    }
5481    Vec::new()
5482}
5483
5484/// #2858: the response-JSON completion cells. Inside `json { }` or `@json( )` at a
5485/// name position, the closed field set (`options`); at the value of `options:`,
5486/// `tagged` / `plain`; at a service-body item start, the `json` section keyword
5487/// and the `@json` annotation snippet. Lexical (offset-based), as
5488/// `limits_completions`.
5489fn json_completions(text: &str, offset: usize, line: &str) -> Vec<CompletionItem> {
5490    if completion::in_json_options_value_position(text, offset) {
5491        return completion::JSON_OPTIONS_VALUES
5492            .iter()
5493            .map(|(name, doc)| CompletionItem {
5494                label: name.to_string(),
5495                kind: Some(CompletionItemKind::ENUM_MEMBER),
5496                detail: Some((*doc).to_string()),
5497                ..Default::default()
5498            })
5499            .collect();
5500    }
5501    if completion::in_json_field_position(text, offset)
5502        || completion::in_json_arg_position(text, offset)
5503    {
5504        return completion::JSON_FIELDS
5505            .iter()
5506            .map(|(name, doc)| CompletionItem {
5507                label: name.to_string(),
5508                kind: Some(CompletionItemKind::FIELD),
5509                detail: Some((*doc).to_string()),
5510                insert_text: Some(format!("{name}: ")),
5511                ..Default::default()
5512            })
5513            .collect();
5514    }
5515    if completion::in_service_body_item_position(text, offset, line) {
5516        return vec![
5517            CompletionItem {
5518                label: "json".to_string(),
5519                kind: Some(CompletionItemKind::KEYWORD),
5520                detail: Some("response JSON encoding for this HTTP service".to_string()),
5521                insert_text: Some("json {\n\toptions: ${1:plain},\n}".to_string()),
5522                insert_text_format: Some(InsertTextFormat::SNIPPET),
5523                ..Default::default()
5524            },
5525            CompletionItem {
5526                label: "@json".to_string(),
5527                kind: Some(CompletionItemKind::SNIPPET),
5528                detail: Some(
5529                    "write this route's response `Option`s as `tagged` or `plain` JSON".to_string(),
5530                ),
5531                insert_text: Some("@json(options: ${1:plain})".to_string()),
5532                insert_text_format: Some(InsertTextFormat::SNIPPET),
5533                ..Default::default()
5534            },
5535        ];
5536    }
5537    Vec::new()
5538}
5539
5540/// v0.142 (ADR 0165): the `@limit` completion cells. Inside `@limit( … )` at an
5541/// argument-name position, offer the closed argument set (`maxBody`); at a
5542/// service-body item start, offer the `@limit` annotation snippet. Both are lexical
5543/// (offset-based), mirroring `cache_completions`.
5544fn limit_completions(text: &str, offset: usize, line: &str) -> Vec<CompletionItem> {
5545    if completion::in_limit_arg_position(text, offset) {
5546        return completion::LIMIT_ARGS
5547            .iter()
5548            .map(|(name, doc)| CompletionItem {
5549                label: name.to_string(),
5550                kind: Some(CompletionItemKind::FIELD),
5551                detail: Some((*doc).to_string()),
5552                insert_text: Some(format!("{name}: ")),
5553                ..Default::default()
5554            })
5555            .collect();
5556    }
5557    if completion::in_service_body_item_position(text, offset, line) {
5558        return vec![CompletionItem {
5559            label: "@limit".to_string(),
5560            kind: Some(CompletionItemKind::SNIPPET),
5561            detail: Some(
5562                "cap the request body size — a `413` synthesised before the body is read"
5563                    .to_string(),
5564            ),
5565            insert_text: Some("@limit(maxBody: ${1:1048576})".to_string()),
5566            insert_text_format: Some(InsertTextFormat::SNIPPET),
5567            ..Default::default()
5568        }];
5569    }
5570    Vec::new()
5571}
5572
5573/// #2854: the special parameter names of an `on http` handler, at a
5574/// parameter-name position in its header. Lexical, like the annotation cells.
5575fn http_param_completions(text: &str, offset: usize) -> Vec<CompletionItem> {
5576    if !completion::in_http_param_name_position(text, offset) {
5577        return Vec::new();
5578    }
5579    completion::HTTP_PARAMS
5580        .iter()
5581        .map(|(name, ty, doc)| CompletionItem {
5582            label: name.to_string(),
5583            kind: Some(CompletionItemKind::VARIABLE),
5584            detail: Some((*doc).to_string()),
5585            insert_text: Some(format!("{name}: ${{1:{ty}}}")),
5586            insert_text_format: Some(InsertTextFormat::SNIPPET),
5587            ..Default::default()
5588        })
5589        .collect()
5590}
5591
5592/// The `@raw` completion cells, mirroring `limit_completions`: inside `@raw( … )` at
5593/// an argument-name position, the closed argument set (`contentType`); at a
5594/// service-body item start, the `@raw` annotation snippet.
5595fn raw_completions(text: &str, offset: usize, line: &str) -> Vec<CompletionItem> {
5596    if completion::in_raw_arg_position(text, offset) {
5597        return completion::RAW_ARGS
5598            .iter()
5599            .map(|(name, doc)| CompletionItem {
5600                label: name.to_string(),
5601                kind: Some(CompletionItemKind::FIELD),
5602                detail: Some((*doc).to_string()),
5603                insert_text: Some(format!("{name}: ")),
5604                ..Default::default()
5605            })
5606            .collect();
5607    }
5608    if completion::in_service_body_item_position(text, offset, line) {
5609        return vec![CompletionItem {
5610            label: "@raw".to_string(),
5611            kind: Some(CompletionItemKind::SNIPPET),
5612            detail: Some(
5613                "take `body: Bytes` as the raw request body — a `415` for any other content type"
5614                    .to_string(),
5615            ),
5616            insert_text: Some("@raw(contentType: \"${1:application/octet-stream}\")".to_string()),
5617            insert_text_format: Some(InsertTextFormat::SNIPPET),
5618            ..Default::default()
5619        }];
5620    }
5621    Vec::new()
5622}
5623
5624/// #3276: the `@form` and `@multipart` annotation snippets, at a service-body item
5625/// start. Neither takes arguments, so there is no argument position to complete.
5626fn form_completions(text: &str, offset: usize, line: &str) -> Vec<CompletionItem> {
5627    if !completion::in_service_body_item_position(text, offset, line) {
5628        return Vec::new();
5629    }
5630    [
5631        (
5632            "@form",
5633            "decode `body: T` from an `application/x-www-form-urlencoded` form — a `415` for any other content type",
5634        ),
5635        (
5636            "@multipart",
5637            "decode `body: T` from a `multipart/form-data` body, with `File` parts — a `415` for any other content type; needs a body cap",
5638        ),
5639    ]
5640    .into_iter()
5641    .map(|(label, detail)| CompletionItem {
5642        label: label.to_string(),
5643        kind: Some(CompletionItemKind::SNIPPET),
5644        detail: Some(detail.to_string()),
5645        insert_text: Some(label.to_string()),
5646        insert_text_format: Some(InsertTextFormat::PLAIN_TEXT),
5647        ..Default::default()
5648    })
5649    .collect()
5650}
5651
5652fn contract_param_completions(text: &str, offset: usize, line: &str) -> Vec<CompletionItem> {
5653    use bynk_syntax::ast::{CommonsItem, SourceUnit};
5654    let Some(is_ensures) = completion::contract_clause_kind(line) else {
5655        return Vec::new();
5656    };
5657    let Ok(tokens) = bynk_syntax::lexer::tokenize(text) else {
5658        return Vec::new();
5659    };
5660    let (Some(unit), _) = bynk_syntax::parser::parse_unit_with_recovery(&tokens, text) else {
5661        return Vec::new();
5662    };
5663    let items = match &unit {
5664        SourceUnit::Commons(c) => &c.items,
5665        SourceUnit::Context(c) => &c.items,
5666        SourceUnit::Adapter(a) => &a.items,
5667        _ => return Vec::new(),
5668    };
5669    for item in items {
5670        // The cursor sits in a fn's signature/contract region: between the fn's
5671        // start and the `{` that opens its body.
5672        if let CommonsItem::Fn(f) = item
5673            && f.span.start <= offset
5674            && offset <= f.body.span.start
5675        {
5676            // Built directly as VARIABLE items, matching `locals_completions`
5677            // (in-scope names carry no resolve data).
5678            let mut out: Vec<CompletionItem> = f
5679                .params
5680                .iter()
5681                .filter(|p| p.name.name != "_")
5682                .map(|p| CompletionItem {
5683                    label: p.name.name.clone(),
5684                    kind: Some(CompletionItemKind::VARIABLE),
5685                    detail: Some(format!(
5686                        "parameter: {}",
5687                        crate::symbols::type_ref_str(&p.type_ref)
5688                    )),
5689                    ..Default::default()
5690                })
5691                .collect();
5692            if is_ensures {
5693                out.push(CompletionItem {
5694                    label: "result".to_string(),
5695                    kind: Some(CompletionItemKind::VARIABLE),
5696                    detail: Some("the function's return value".to_string()),
5697                    ..Default::default()
5698                });
5699            }
5700            return out;
5701        }
5702    }
5703    Vec::new()
5704}
5705
5706/// v0.124 (slice 3): the byte offset of the scrutinee's last character in
5707/// `<scrutinee> is <partial>` ending at `cursor`, or `None` if the cursor is
5708/// not at an `is`-pattern position. `is` must be a standalone word (so `basis`
5709/// does not trigger it).
5710fn is_scrutinee_offset(text: &str, cursor: usize) -> Option<usize> {
5711    let before = text.get(..cursor)?;
5712    // Drop the partial variant being typed, then the whitespace before it.
5713    let before = before
5714        .trim_end_matches(|c: char| c.is_alphanumeric() || c == '_')
5715        .trim_end();
5716    let before = before.strip_suffix("is")?;
5717    if !before.ends_with(char::is_whitespace) {
5718        return None;
5719    }
5720    let before = before.trim_end();
5721    (!before.is_empty()).then(|| before.len() - 1)
5722}
5723
5724/// v0.128: the byte offset of the scrutinee's last character in a
5725/// `match <scrutinee> { … <partial>` whose cursor sits at an **arm-pattern-start**
5726/// position, or `None` otherwise — the deferred half of slice 3's `is`-pattern
5727/// completion. Conservative: it fires only at the *start* of an arm's pattern
5728/// (after the `{` or a top-level `,`, before any `=>`), never inside an arm body
5729/// or a nested constructor pattern, so it stays honest mid-edit.
5730fn match_scrutinee_offset(text: &str, cursor: usize) -> Option<usize> {
5731    let before = text.get(..cursor)?;
5732    // The innermost `{` still open at the cursor — the block the cursor is in.
5733    let brace = innermost_open_brace(before)?;
5734    // The current arm: from the last top-level `,` after the brace (or the brace
5735    // itself) to the cursor. A `=>` in it means the cursor is in the arm body.
5736    let arm_start = arm_start_offset(before, brace);
5737    let arm = before.get(arm_start..)?;
5738    if arm.contains("=>") {
5739        return None;
5740    }
5741    // Only at the pattern's *start*: nothing but the partial pattern being typed
5742    // sits between the arm boundary and the cursor.
5743    if !arm
5744        .trim_end_matches(|c: char| c.is_alphanumeric() || c == '_')
5745        .trim()
5746        .is_empty()
5747    {
5748        return None;
5749    }
5750    match_head_scrutinee_offset(before, brace)
5751}
5752
5753/// v0.145 (ADR 0169): the scrutinee offset and outer variant name at a
5754/// `match <scrutinee> { … OuterVariant(<partial>` position — the cursor inside a
5755/// variant's payload parens within an arm-pattern (before `=>`), the one place
5756/// `match_scrutinee_offset` bails. Conservative: the payload `(` must be still
5757/// open, the token before it an uppercase-led variant constructor, and only the
5758/// partial nested pattern may sit between the `(` and the cursor.
5759fn nested_pattern_offset(text: &str, cursor: usize) -> Option<(usize, String)> {
5760    let before = text.get(..cursor)?;
5761    let brace = innermost_open_brace(before)?;
5762    let arm_start = arm_start_offset(before, brace);
5763    let arm = before.get(arm_start..)?;
5764    if arm.contains("=>") {
5765        return None; // in the arm body, not its pattern
5766    }
5767    // The innermost `(` still open in the arm — the outer variant's payload.
5768    let paren = innermost_open_paren(arm)?;
5769    // The identifier immediately before that `(` is the outer variant; only an
5770    // uppercase-led constructor opens a nested pattern (a binding never does).
5771    let head = arm.get(..paren)?.trim_end();
5772    let variant: String = head
5773        .chars()
5774        .rev()
5775        .take_while(|c| c.is_alphanumeric() || *c == '_')
5776        .collect::<Vec<_>>()
5777        .into_iter()
5778        .rev()
5779        .collect();
5780    if !variant.chars().next().is_some_and(char::is_uppercase) {
5781        return None;
5782    }
5783    // Between the payload `(` and the cursor, only the partial nested pattern
5784    // being typed (an identifier, optionally a `Type.` qualifier) may sit.
5785    let after = arm.get(paren + 1..)?;
5786    if !after
5787        .trim_start_matches(|c: char| c.is_alphanumeric() || c == '_' || c == '.')
5788        .trim()
5789        .is_empty()
5790    {
5791        return None;
5792    }
5793    let scrut_off = match_head_scrutinee_offset(before, brace)?;
5794    Some((scrut_off, variant))
5795}
5796
5797/// The byte offset of the scrutinee's last character for the `match <scrutinee>`
5798/// whose body brace is at `brace`, or `None` if `brace` does not head a
5799/// `match`: a standalone `match` keyword, then a scrutinee expression with no
5800/// nested block or arrow between it and the brace. Shared by
5801/// `match_scrutinee_offset` and `nested_pattern_offset`.
5802fn match_head_scrutinee_offset(before: &str, brace: usize) -> Option<usize> {
5803    let head = before.get(..brace)?.trim_end();
5804    let m = head.rfind("match")?;
5805    if head[..m]
5806        .chars()
5807        .next_back()
5808        .is_some_and(|c| c.is_alphanumeric() || c == '_')
5809    {
5810        return None; // part of a longer identifier (`rematch`), not the keyword
5811    }
5812    let after = head.get(m + "match".len()..)?;
5813    if !after.starts_with(char::is_whitespace) {
5814        return None;
5815    }
5816    let scrut = after.trim();
5817    if scrut.is_empty() || scrut.contains(['{', '}']) || scrut.contains("=>") {
5818        return None;
5819    }
5820    // `head` was trimmed to end at the scrutinee's last char (the brace followed).
5821    Some(head.len() - 1)
5822}
5823
5824/// #2010: what `let_else_match_completions` needs from the head of a
5825/// `let <pattern> (= | <-) <value> else match {` — read from text, like the
5826/// other pattern-position scanners here, so it works on a half-typed buffer.
5827#[derive(Debug, PartialEq, Eq)]
5828struct LetElseMatchHead {
5829    /// The offset of the value expression's last character.
5830    value_end: usize,
5831    /// `<-`: the value is an `Effect`, whose payload the arms match.
5832    effectful: bool,
5833    /// The variant the `let` pattern matches outright (`Ok(x)`, `Some(_)`,
5834    /// `P.Late`), which the arms never need; `None` when the pattern only
5835    /// covers part of a variant (`Err(Missing)`) or is not a variant.
5836    covered: Option<String>,
5837}
5838
5839/// #2010: the [`LetElseMatchHead`] when the cursor is at an arm-pattern-start
5840/// inside a `let … else match { … }`.
5841fn let_else_match_head(text: &str, cursor: usize) -> Option<LetElseMatchHead> {
5842    let before = text.get(..cursor)?;
5843    let brace = innermost_open_brace(before)?;
5844    let arm = before.get(arm_start_offset(before, brace)..)?;
5845    if arm.contains("=>")
5846        || !arm
5847            .trim_end_matches(|c: char| c.is_alphanumeric() || c == '_')
5848            .trim()
5849            .is_empty()
5850    {
5851        return None;
5852    }
5853    let is_ident = |c: char| c.is_alphanumeric() || c == '_';
5854    let strip_word = |s: &'_ str, word: &str| -> Option<usize> {
5855        let rest = s.strip_suffix(word)?;
5856        (!rest.ends_with(is_ident)).then_some(rest.trim_end().len())
5857    };
5858    let head = before.get(..brace)?.trim_end();
5859    let head = &head[..strip_word(head, "match")?];
5860    let head = &head[..strip_word(head, "else")?];
5861    let value_end = head.len().checked_sub(1)?;
5862    // The statement's own `let`: the last one at the start of a word.
5863    let let_at = head
5864        .match_indices("let")
5865        .map(|(i, _)| i)
5866        .filter(|&i| {
5867            !head[..i].ends_with(is_ident) && head[i + 3..].starts_with(char::is_whitespace)
5868        })
5869        .last()?;
5870    let rest = &head[let_at + 3..];
5871    // The first `=` (not `==`/`=>`) or `<-` outside brackets ends the pattern.
5872    let mut depth = 0i32;
5873    let mut split = None;
5874    let bytes = rest.as_bytes();
5875    for (i, &b) in bytes.iter().enumerate() {
5876        match b {
5877            b'(' | b'[' | b'{' => depth += 1,
5878            b')' | b']' | b'}' => depth -= 1,
5879            b'<' if depth == 0 && bytes.get(i + 1) == Some(&b'-') => {
5880                split = Some((i, true));
5881                break;
5882            }
5883            b'=' if depth == 0
5884                && !matches!(bytes.get(i + 1), Some(b'=' | b'>'))
5885                && !matches!(
5886                    i.checked_sub(1).map(|j| bytes[j]),
5887                    Some(b'=' | b'!' | b'<' | b'>')
5888                ) =>
5889            {
5890                split = Some((i, false));
5891                break;
5892            }
5893            _ => {}
5894        }
5895    }
5896    let (at, effectful) = split?;
5897    let pattern = rest[..at].trim();
5898    let (name, payload) = match pattern.split_once('(') {
5899        Some((name, payload)) => (name, Some(payload.trim_end_matches(')'))),
5900        None => (pattern, None),
5901    };
5902    let name = name.rsplit('.').next()?.trim();
5903    let whole_variant = name.starts_with(char::is_uppercase)
5904        && payload.is_none_or(|p| {
5905            p.split(',').all(|part| {
5906                let binder = part.rsplit(':').next().unwrap_or(part).trim();
5907                binder == "_"
5908                    || binder.starts_with(char::is_lowercase) && binder.chars().all(is_ident)
5909            })
5910        });
5911    Some(LetElseMatchHead {
5912        value_end,
5913        effectful,
5914        covered: whole_variant.then(|| name.to_string()),
5915    })
5916}
5917
5918/// The offset (relative to `arm`) of the innermost `(` left unclosed in `arm` — a
5919/// `(`-only balance scan, the payload paren the cursor sits in — or `None` if
5920/// every `(` is closed.
5921fn innermost_open_paren(arm: &str) -> Option<usize> {
5922    let mut stack: Vec<usize> = Vec::new();
5923    for (i, c) in arm.char_indices() {
5924        match c {
5925            '(' => stack.push(i),
5926            ')' => {
5927                stack.pop();
5928            }
5929            _ => {}
5930        }
5931    }
5932    stack.pop()
5933}
5934
5935/// The byte offset of the innermost `{` left unclosed in `before` (a `{`-only
5936/// balance scan — the block the cursor sits in), or `None` if every `{` is closed.
5937fn innermost_open_brace(before: &str) -> Option<usize> {
5938    let mut stack: Vec<usize> = Vec::new();
5939    for (i, c) in before.char_indices() {
5940        match c {
5941            '{' => stack.push(i),
5942            '}' => {
5943                stack.pop();
5944            }
5945            _ => {}
5946        }
5947    }
5948    stack.pop()
5949}
5950
5951/// The offset just past the last top-level `,` inside the block opened at `brace`
5952/// (depth 0 relative to that brace), or just past the brace itself if the block
5953/// holds no top-level comma yet — the start of the arm the cursor is editing.
5954fn arm_start_offset(before: &str, brace: usize) -> usize {
5955    let mut depth = 0i32;
5956    let mut start = brace + 1; // just after the `{`
5957    for (rel, c) in before[brace + 1..].char_indices() {
5958        match c {
5959            '{' | '(' | '[' => depth += 1,
5960            '}' | ')' | ']' => depth -= 1,
5961            ',' if depth == 0 => start = brace + 1 + rel + c.len_utf8(),
5962            _ => {}
5963        }
5964    }
5965    start
5966}
5967
5968/// #2458: the completion icon for a doc-link target, matching the symbol kind.
5969/// Maps `offset` in the live buffer `live` to the same position in the older
5970/// `snapshot` of it, when the edit that separates them lies wholly before
5971/// `offset` (the bytes from `offset` on are unchanged). `None` otherwise.
5972fn live_to_snapshot_offset(live: &str, snapshot: &str, offset: usize) -> Option<usize> {
5973    let suffix = live
5974        .bytes()
5975        .rev()
5976        .zip(snapshot.bytes().rev())
5977        .take_while(|(a, b)| a == b)
5978        .count();
5979    let unchanged_from = live.len() - suffix;
5980    (offset >= unchanged_from).then(|| offset + snapshot.len() - live.len())
5981}
5982
5983fn doc_link_item_kind(kind: Option<bynk_check::index::SymbolKind>) -> CompletionItemKind {
5984    use bynk_check::index::SymbolKind as K;
5985    let Some(kind) = kind else {
5986        return CompletionItemKind::VARIABLE;
5987    };
5988    match kind {
5989        K::Type => CompletionItemKind::STRUCT,
5990        K::Fn => CompletionItemKind::FUNCTION,
5991        K::Capability => CompletionItemKind::INTERFACE,
5992        K::Method | K::CapabilityOp | K::Handler => CompletionItemKind::METHOD,
5993        K::Field => CompletionItemKind::FIELD,
5994        K::Asset | K::Embed | K::Const => CompletionItemKind::CONSTANT,
5995        _ => CompletionItemKind::CLASS,
5996    }
5997}
5998
5999fn to_completion_item(c: completion::Completion) -> CompletionItem {
6000    CompletionItem {
6001        kind: Some(match c.kind {
6002            completion::CompletionKind::Unit => CompletionItemKind::MODULE,
6003            completion::CompletionKind::Capability => CompletionItemKind::INTERFACE,
6004            completion::CompletionKind::Type => CompletionItemKind::STRUCT,
6005            completion::CompletionKind::Keyword => CompletionItemKind::KEYWORD,
6006            completion::CompletionKind::Snippet => CompletionItemKind::SNIPPET,
6007            completion::CompletionKind::Variant => CompletionItemKind::ENUM_MEMBER,
6008            completion::CompletionKind::Member => CompletionItemKind::METHOD,
6009            completion::CompletionKind::Field => CompletionItemKind::FIELD,
6010            completion::CompletionKind::Constructor => CompletionItemKind::CONSTRUCTOR,
6011            completion::CompletionKind::Function => CompletionItemKind::FUNCTION,
6012            completion::CompletionKind::Constant => CompletionItemKind::CONSTANT,
6013            completion::CompletionKind::Constraint => CompletionItemKind::INTERFACE,
6014        }),
6015        // Snippet items carry `${n:…}` tab stops; everything else inserts its
6016        // label verbatim (the default).
6017        insert_text_format: c.insert_text.as_ref().map(|_| InsertTextFormat::SNIPPET),
6018        insert_text: c.insert_text,
6019        label: c.label,
6020        detail: c.detail,
6021        // #1888: a field's or variant's doc, rendered as Markdown.
6022        documentation: c.documentation.map(|value| {
6023            Documentation::MarkupContent(MarkupContent {
6024                kind: MarkupKind::Markdown,
6025                value,
6026            })
6027        }),
6028        ..Default::default()
6029    }
6030}
6031
6032/// The byte offset of an LSP `(line, character)` position in `text`,
6033/// clamped to the end of the document when the position lies past it.
6034/// LSP positions count UTF-16 code units, so this goes through the shared
6035/// converter — a byte-faithful reading misplaces the cursor on any line
6036/// with non-ASCII text before it.
6037fn cursor_offset(text: &str, pos: Position) -> usize {
6038    crate::position::position_to_offset(text, pos).unwrap_or(text.len())
6039}
6040
6041/// v0.34 (ADR 0067): a serializable mirror of [`bynk_check::index::SymbolKey`] for
6042/// round-tripping through `CallHierarchyItem.data` — the index kind isn't
6043/// `Serialize`, so the kind travels as its `display()` string.
6044#[derive(serde::Serialize, serde::Deserialize)]
6045struct SerKey {
6046    unit: String,
6047    kind: String,
6048    name: String,
6049}
6050
6051impl From<&bynk_check::index::SymbolKey> for SerKey {
6052    fn from(k: &bynk_check::index::SymbolKey) -> Self {
6053        SerKey {
6054            unit: k.unit.clone(),
6055            kind: k.kind.display().to_string(),
6056            name: k.name.clone(),
6057        }
6058    }
6059}
6060
6061impl SerKey {
6062    /// Recover a `SymbolKey` from a `CallHierarchyItem`'s `data`. `None` for a
6063    /// missing/garbled payload or an unknown kind — the follow-up then returns
6064    /// no calls rather than guessing.
6065    fn read(data: &Option<serde_json::Value>) -> Option<bynk_check::index::SymbolKey> {
6066        let sk: SerKey = serde_json::from_value(data.as_ref()?.clone()).ok()?;
6067        sk.into_key()
6068    }
6069
6070    /// The `SymbolKey` this payload names; `None` for an unknown kind.
6071    fn into_key(self) -> Option<bynk_check::index::SymbolKey> {
6072        let sk = self;
6073        let kind = match sk.kind.as_str() {
6074            "type" => bynk_check::index::SymbolKind::Type,
6075            "fn" => bynk_check::index::SymbolKind::Fn,
6076            "capability" => bynk_check::index::SymbolKind::Capability,
6077            "service" => bynk_check::index::SymbolKind::Service,
6078            "agent" => bynk_check::index::SymbolKind::Agent,
6079            "provider" => bynk_check::index::SymbolKind::Provider,
6080            _ => return None,
6081        };
6082        Some(bynk_check::index::SymbolKey {
6083            unit: sk.unit,
6084            kind,
6085            name: sk.name,
6086        })
6087    }
6088}
6089
6090/// The `TypeHierarchyItem.data` payload: which hierarchy node the item is, and
6091/// the unit the hierarchy was opened from (for the opaque-visibility rule).
6092#[derive(serde::Serialize, serde::Deserialize)]
6093#[serde(tag = "node", rename_all = "lowercase")]
6094enum TypeHierData {
6095    Type { key: SerKey, from: Option<String> },
6096    Primitive { base: String, from: Option<String> },
6097}
6098
6099impl TypeHierData {
6100    fn read(data: &Option<serde_json::Value>) -> Option<TypeHierData> {
6101        serde_json::from_value(data.as_ref()?.clone()).ok()
6102    }
6103}
6104
6105fn lsp_symbol_kind(kind: bynk_check::index::SymbolKind) -> SymbolKind {
6106    match kind {
6107        bynk_check::index::SymbolKind::Type => SymbolKind::STRUCT,
6108        bynk_check::index::SymbolKind::Fn => SymbolKind::FUNCTION,
6109        bynk_check::index::SymbolKind::Capability => SymbolKind::INTERFACE,
6110        bynk_check::index::SymbolKind::Service | bynk_check::index::SymbolKind::Agent => {
6111            SymbolKind::CLASS
6112        }
6113        bynk_check::index::SymbolKind::Provider => SymbolKind::OBJECT,
6114        bynk_check::index::SymbolKind::Method => SymbolKind::METHOD,
6115        bynk_check::index::SymbolKind::CapabilityOp => SymbolKind::METHOD,
6116        bynk_check::index::SymbolKind::Field => SymbolKind::FIELD,
6117        bynk_check::index::SymbolKind::Actor => SymbolKind::INTERFACE,
6118        bynk_check::index::SymbolKind::Handler => SymbolKind::METHOD,
6119        bynk_check::index::SymbolKind::Messages => SymbolKind::STRUCT,
6120        // #1883: an asset is a named value that never changes — as the
6121        // document outline already shows it (`document_symbols::asset_symbol`).
6122        bynk_check::index::SymbolKind::Asset => SymbolKind::CONSTANT,
6123        // #2387: likewise a named string constant.
6124        bynk_check::index::SymbolKind::Embed => SymbolKind::CONSTANT,
6125        // #2617: a named constant.
6126        bynk_check::index::SymbolKind::Const => SymbolKind::CONSTANT,
6127    }
6128}
6129
6130/// Whether a watched-file URI names a `bynk.toml` manifest — the trigger for a
6131/// live config reload. Matches on the file-name component (not a path suffix),
6132/// so a file like `notbynk.toml` doesn't spuriously fire.
6133/// #2841: whether `uri` is a file under a `fixtures/` directory — the folder a
6134/// suite's `fixture` declarations read from.
6135fn is_fixture_file(uri: &Url) -> bool {
6136    uri.path().split('/').any(|seg| seg == "fixtures")
6137}
6138
6139fn is_bynk_toml(uri: &Url) -> bool {
6140    let Ok(path) = uri.to_file_path() else {
6141        return false;
6142    };
6143    path.file_name().and_then(|n| n.to_str()) == Some("bynk.toml")
6144}
6145
6146/// The `codeDescription` link for a diagnostic `code` (#853, #3876): a link to
6147/// the code's own page, `https://bynk-lang.org/d/<code>`, for every code in the
6148/// registry, curated or not; `None` for a string that is not a registered code.
6149/// Split out from [`make_diagnostic`] so the contract is directly testable.
6150fn code_description(code: &str) -> Option<CodeDescription> {
6151    bynk_syntax::diagnostics::lookup(code)?;
6152    let href = Url::parse(&bynk_syntax::diagnostics::href(code)).ok()?;
6153    Some(CodeDescription { href })
6154}
6155
6156#[cfg(test)]
6157mod code_description_tests {
6158    use super::code_description;
6159
6160    #[test]
6161    fn a_code_links_to_its_own_page() {
6162        let cd = code_description("bynk.resolve.unknown_type")
6163            .expect("a registered code produces a codeDescription");
6164        assert_eq!(
6165            cd.href.as_str(),
6166            "https://bynk-lang.org/d/bynk.resolve.unknown_type"
6167        );
6168    }
6169
6170    #[test]
6171    fn an_uncurated_code_links_too_and_an_unknown_one_does_not() {
6172        // #3876: every registered code has a page, curated or not.
6173        assert!(code_description("bynk.wasm.panic").is_some());
6174        assert!(code_description("bynk.not.a_real_code").is_none());
6175    }
6176
6177    #[test]
6178    fn every_registered_code_yields_a_parseable_url() {
6179        // Guards that no code ever silently drops its link because `Url::parse`
6180        // rejected it.
6181        for d in bynk_syntax::diagnostics::REGISTRY {
6182            assert!(
6183                code_description(d.code).is_some(),
6184                "`{}` produced no codeDescription — its href `{}` did not parse",
6185                d.code,
6186                bynk_syntax::diagnostics::href(d.code)
6187            );
6188        }
6189    }
6190}
6191
6192/// Every analysed project file's URI and the positions of the snapshot it
6193/// was analysed at, by identity path — where [`make_diagnostic`] places a
6194/// secondary label that lies in a sibling file.
6195type ProjectFiles<'a> = std::collections::HashMap<PathBuf, (Url, crate::position::PositionMap<'a>)>;
6196
6197fn make_diagnostic(
6198    d: &bynk_ide::Diagnostic,
6199    positions: &crate::position::PositionMap,
6200    uri: &Url,
6201    files: &ProjectFiles<'_>,
6202) -> Diagnostic {
6203    let range = positions.range(d.error.span);
6204    let severity = match d.severity {
6205        bynk_syntax::Severity::Error => DiagnosticSeverity::ERROR,
6206        bynk_syntax::Severity::Warning => DiagnosticSeverity::WARNING,
6207        bynk_syntax::Severity::Hint => DiagnosticSeverity::HINT,
6208    };
6209    let mut related_information: Vec<DiagnosticRelatedInformation> = Vec::new();
6210    let mut label_notes: Vec<&str> = Vec::new();
6211    for (i, (span, msg)) in d.error.labels.iter().enumerate() {
6212        // A label's span is an offset into the text of the file it lies in:
6213        // this document's, or a sibling's in the same project, which has its
6214        // own URI and positions. A label in a file with no snapshot (a
6215        // toolchain-injected unit) has nowhere to point, so it is a note.
6216        let (label_uri, label_positions) = match d.label_file(i) {
6217            bynk_ide::LabelFile::Primary => (uri, positions),
6218            bynk_ide::LabelFile::Other(path) => match files.get(path) {
6219                Some((u, p)) => (u, p),
6220                None => {
6221                    label_notes.push(msg);
6222                    continue;
6223                }
6224            },
6225            // A first-party unit (`bynk.bynk`) has no document to point at.
6226            bynk_ide::LabelFile::FirstParty { .. } | bynk_ide::LabelFile::Unavailable => {
6227                label_notes.push(msg);
6228                continue;
6229            }
6230        };
6231        related_information.push(DiagnosticRelatedInformation {
6232            location: Location {
6233                uri: label_uri.clone(),
6234                range: label_positions.range(*span),
6235            },
6236            message: msg.clone(),
6237        });
6238    }
6239    let mut message = d.error.message.clone();
6240    for note in d.error.notes.iter().map(String::as_str).chain(label_notes) {
6241        message.push_str("\n\n");
6242        message.push_str("note: ");
6243        message.push_str(note);
6244    }
6245    Diagnostic {
6246        range,
6247        severity: Some(severity),
6248        code: Some(NumberOrString::String(d.error.category.to_string())),
6249        // #853: a curated code carries a `codeDescription` link to its Book
6250        // explanation (rendered as a link on the code in Problems/hover); an
6251        // uncurated code has no entry and stays `None` — the designed
6252        // graceful-fallback state, not an error.
6253        code_description: code_description(d.error.category),
6254        source: Some(SERVER_NAME.to_string()),
6255        message,
6256        related_information: if related_information.is_empty() {
6257            None
6258        } else {
6259            Some(related_information)
6260        },
6261        tags: None,
6262        data: None,
6263    }
6264}
6265
6266/// Slice C: the server's entry point, moved out of `main.rs` so the crate
6267/// has a `[lib]` target. `main.rs` is now a thin shim over this.
6268///
6269/// #1667: returns the process's exit code: success after an orderly
6270/// `shutdown`, failure (with a line on stderr) when the session ended any
6271/// other way.
6272pub async fn run() -> std::process::ExitCode {
6273    // Answer `--version`/`-V` and exit before entering the stdio LSP loop, so
6274    // tooling (e.g. the VS Code status bar) can query the version without the
6275    // server blocking on stdin.
6276    if std::env::args()
6277        .skip(1)
6278        .any(|a| a == "--version" || a == "-V")
6279    {
6280        println!("{SERVER_NAME} {SERVER_VERSION}");
6281        return std::process::ExitCode::SUCCESS;
6282    }
6283    // Logging to ~/.bynk-lsp.log. Default level: warn; tunable via
6284    // RUST_LOG or the LSP client's trace setting.
6285    if let Some(home) = std::env::var_os("HOME") {
6286        let path: PathBuf = PathBuf::from(home).join(".bynk-lsp.log");
6287        if let Ok(file) = std::fs::OpenOptions::new()
6288            .create(true)
6289            .append(true)
6290            .open(&path)
6291        {
6292            use tracing_subscriber::prelude::*;
6293            let env_filter = tracing_subscriber::EnvFilter::try_from_env("BYNK_LSP_LOG")
6294                .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("warn"));
6295            let file_layer = tracing_subscriber::fmt::layer()
6296                .with_writer(std::sync::Mutex::new(file))
6297                .with_ansi(false);
6298            tracing_subscriber::registry()
6299                .with(env_filter)
6300                .with(file_layer)
6301                .try_init()
6302                .ok();
6303        }
6304    }
6305    tracing::info!("bynk-lsp v{} starting", SERVER_VERSION);
6306    let stdout = tokio::io::stdout();
6307    // #1667: the server reads a re-framed copy of stdin, so one malformed
6308    // message is skipped rather than ending the session (see `transport`).
6309    let (server_input, pump_output) = tokio::io::duplex(1 << 16);
6310    tokio::spawn(transport::pump(tokio::io::stdin(), pump_output));
6311    let shutdown_requested = Arc::new(std::sync::atomic::AtomicBool::new(false));
6312    let flag = Arc::clone(&shutdown_requested);
6313    // #846: custom (non-standard) requests have no `LanguageServer` trait
6314    // slot, so they are registered on the builder from the `custom_requests!`
6315    // table (#2545) rather than picked up by `LspService::new`.
6316    let (service, socket) = register_custom_requests(LspService::build(move |client| {
6317        Backend::with_shutdown_flag(client, Arc::clone(&flag))
6318    }))
6319    .finish();
6320    Server::new(server_input, stdout, socket)
6321        .serve(service)
6322        .await;
6323    if shutdown_requested.load(std::sync::atomic::Ordering::SeqCst) {
6324        std::process::ExitCode::SUCCESS
6325    } else {
6326        eprintln!(
6327            "bynk-lsp: the session ended without a `shutdown` request \
6328             (the client closed the connection, or sent `exit` early); see ~/.bynk-lsp.log"
6329        );
6330        std::process::ExitCode::FAILURE
6331    }
6332}
6333
6334#[cfg(test)]
6335mod tests {
6336    use super::*;
6337
6338    // -- Slice A: the project model, driven through `Backend` ---------------
6339    //
6340    // These are the crate's first *behaviour-over-time* tests: they drive the
6341    // real `Backend` — the layer the track doc (§4.1) notes has always been
6342    // testable in-crate via `LspService::new(Backend::new)`, and never was.
6343    // Everything else in this module asserts *static* shape.
6344    //
6345    // Hermetic on purpose. `bynk-lsp` is published and `Cargo.toml`'s `exclude`
6346    // list can only drop `tests/*.rs`, never this file — so an in-crate test
6347    // reading a sibling directory would fail `cargo test` on the released
6348    // tarball. (`find_source_root_walks_up_to_the_nearest_src` below already
6349    // does exactly that; not this slice's to fix.) The sibling-reading fixtures
6350    // live in `tests/project_model.rs`, which *is* excluded.
6351
6352    /// A throwaway project, removed on drop — including on panic.
6353    struct Scratch(PathBuf);
6354    impl Drop for Scratch {
6355        fn drop(&mut self) {
6356            let _ = std::fs::remove_dir_all(&self.0);
6357        }
6358    }
6359
6360    fn scratch_project(tag: &str, files: &[(&str, &str)]) -> Scratch {
6361        let dir = std::env::temp_dir().join(format!(
6362            "bynk_lsp_sliceA_{tag}_{}_{:?}",
6363            std::process::id(),
6364            std::thread::current().id()
6365        ));
6366        let _ = std::fs::remove_dir_all(&dir);
6367        for (rel, body) in files {
6368            let p = dir.join(rel);
6369            std::fs::create_dir_all(p.parent().unwrap()).unwrap();
6370            std::fs::write(&p, body).unwrap();
6371        }
6372        Scratch(dir)
6373    }
6374
6375    /// Build a `Backend` over a real `LspService`, rooted at `root`.
6376    ///
6377    /// `LspService::new(Backend::new)` is what `main` itself calls — the
6378    /// `Client` it hands back is the only thing `Backend` needed, and it has
6379    /// been available for this since the server was written.
6380    async fn backend_at(root: &std::path::Path) -> Backend {
6381        let (service, _socket) = tower_lsp::LspService::new(Backend::new);
6382        let backend = service.inner().clone();
6383        // Slice D: seed one project entry, keyed by the **canonical** root so a
6384        // request's `resolve_root`-based routing lands on the same key.
6385        let canonical = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
6386        {
6387            let mut state = backend.state.write().await;
6388            state.folders.push(canonical.clone());
6389            state.projects.insert(
6390                canonical.clone(),
6391                ProjectState {
6392                    config: project::load_config(&canonical).unwrap_or_default(),
6393                    ..Default::default()
6394                },
6395            );
6396        }
6397        backend
6398    }
6399
6400    /// #1667: a panic in an analysis round reaches the client once per
6401    /// failure streak, as a `window/showMessage`, and the streak ends at the
6402    /// next clean round. Before, the `JoinError` was dropped without a trace.
6403    #[tokio::test]
6404    async fn a_panicking_round_tells_the_client_once_and_clears_on_success() {
6405        use futures::StreamExt;
6406        use tower::{Service, ServiceExt};
6407
6408        let s = scratch_project(
6409            "panic",
6410            &[
6411                ("bynk.toml", "[project]\nname = \"panic\"\n"),
6412                ("src/thing.bynk", "context thing\n"),
6413            ],
6414        );
6415        let (mut service, socket) = tower_lsp::LspService::new(Backend::new);
6416        // The client sends nothing until the server is initialised.
6417        let initialize = tower_lsp::jsonrpc::Request::build("initialize")
6418            .params(serde_json::json!({ "capabilities": {} }))
6419            .id(1)
6420            .finish();
6421        service
6422            .ready()
6423            .await
6424            .unwrap()
6425            .call(initialize)
6426            .await
6427            .unwrap();
6428        let initialized = tower_lsp::jsonrpc::Request::build("initialized")
6429            .params(serde_json::json!({}))
6430            .finish();
6431        service
6432            .ready()
6433            .await
6434            .unwrap()
6435            .call(initialized)
6436            .await
6437            .unwrap();
6438        // Drain the client side as the server writes to it: its channel is
6439        // small, so an unread socket would block the server's next
6440        // notification (a `publishDiagnostics`, or the `showMessage` itself).
6441        let shown = Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
6442        let drain = {
6443            let shown = Arc::clone(&shown);
6444            tokio::spawn(socket.for_each(move |message| {
6445                if message.method() == "window/showMessage" {
6446                    shown
6447                        .lock()
6448                        .unwrap()
6449                        .push(format!("{:?}", message.params()));
6450                }
6451                async {}
6452            }))
6453        };
6454        let backend = service.inner().clone();
6455        let canonical = s.0.canonicalize().unwrap();
6456        backend
6457            .state
6458            .write()
6459            .await
6460            .projects
6461            .insert(canonical.clone(), ProjectState::default());
6462        let failed = |b: &Backend| {
6463            let b = b.clone();
6464            let root = canonical.clone();
6465            async move { b.state.read().await.projects[&root].analysis_failed }
6466        };
6467
6468        let inject = |b: &Backend| {
6469            let b = b.clone();
6470            let root = canonical.clone();
6471            async move {
6472                b.state
6473                    .write()
6474                    .await
6475                    .projects
6476                    .get_mut(&root)
6477                    .unwrap()
6478                    .panic_next_round = true;
6479            }
6480        };
6481        inject(&backend).await;
6482        backend.run_project_diagnostics(canonical.clone()).await;
6483        assert!(failed(&backend).await, "the failed round is recorded");
6484        // A second failure in the same streak says nothing new.
6485        inject(&backend).await;
6486        backend.run_project_diagnostics(canonical.clone()).await;
6487
6488        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
6489        {
6490            let shown = shown.lock().unwrap();
6491            assert_eq!(shown.len(), 1, "told once per streak: {shown:?}");
6492            assert!(shown[0].contains("internal error"), "{shown:?}");
6493        }
6494
6495        backend.run_project_diagnostics(canonical.clone()).await;
6496        assert!(!failed(&backend).await, "a clean round ends the streak");
6497        // A failure after the streak ended is a new streak, and is told.
6498        inject(&backend).await;
6499        backend.run_project_diagnostics(canonical.clone()).await;
6500        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
6501        assert_eq!(shown.lock().unwrap().len(), 2, "a new streak is told again");
6502        drain.abort();
6503    }
6504
6505    /// A diagnostic's secondary label in a sibling file of a multi-file unit
6506    /// points at that file's URI, at its position there. Before, every label
6507    /// took the diagnostic's own URI, so "previously declared here" for a
6508    /// service declared in `a_web.bynk` pointed into `z_more.bynk`, at the same
6509    /// byte offsets.
6510    #[tokio::test]
6511    async fn a_label_in_a_sibling_file_points_at_that_file() {
6512        use futures::StreamExt;
6513        use tower::{Service, ServiceExt};
6514
6515        let service_src =
6516            "service api {\n  on call() -> Effect[Int] by Caller {\n    Effect.pure(1)\n  }\n}\n";
6517        let s = scratch_project(
6518            "sibling_label",
6519            &[
6520                ("bynk.toml", "[project]\nname = \"demo\"\n"),
6521                (
6522                    "src/app/a_web.bynk",
6523                    &format!("context app\n\n{service_src}"),
6524                ),
6525                (
6526                    "src/app/z_more.bynk",
6527                    &format!("context app\n\n\n\n\n{service_src}"),
6528                ),
6529            ],
6530        );
6531        let (mut service, socket) = tower_lsp::LspService::new(Backend::new);
6532        for request in [
6533            tower_lsp::jsonrpc::Request::build("initialize")
6534                .params(serde_json::json!({ "capabilities": {} }))
6535                .id(1)
6536                .finish(),
6537            tower_lsp::jsonrpc::Request::build("initialized")
6538                .params(serde_json::json!({}))
6539                .finish(),
6540        ] {
6541            service.ready().await.unwrap().call(request).await.unwrap();
6542        }
6543        let published = Arc::new(std::sync::Mutex::new(Vec::<PublishDiagnosticsParams>::new()));
6544        let drain = {
6545            let published = Arc::clone(&published);
6546            tokio::spawn(socket.for_each(move |message| {
6547                if message.method() == "textDocument/publishDiagnostics"
6548                    && let Some(params) = message.params()
6549                {
6550                    published
6551                        .lock()
6552                        .unwrap()
6553                        .push(serde_json::from_value(params.clone()).unwrap());
6554                }
6555                async {}
6556            }))
6557        };
6558        let backend = service.inner().clone();
6559        let canonical = s.0.canonicalize().unwrap();
6560        backend
6561            .state
6562            .write()
6563            .await
6564            .projects
6565            .insert(canonical.clone(), ProjectState::default());
6566        backend.run_project_diagnostics(canonical.clone()).await;
6567        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
6568        drain.abort();
6569
6570        let a_web = Url::from_file_path(canonical.join("src/app/a_web.bynk")).unwrap();
6571        let z_more = Url::from_file_path(canonical.join("src/app/z_more.bynk")).unwrap();
6572        let published = published.lock().unwrap();
6573        let duplicate = published
6574            .iter()
6575            .filter(|p| p.uri == z_more)
6576            .flat_map(|p| &p.diagnostics)
6577            .find(|d| {
6578                d.code
6579                    == Some(NumberOrString::String(
6580                        "bynk.resolve.duplicate_service".into(),
6581                    ))
6582            })
6583            .unwrap_or_else(|| panic!("z_more.bynk must report the duplicate: {published:?}"));
6584        let related = duplicate
6585            .related_information
6586            .as_deref()
6587            .expect("the duplicate carries its \"previously declared here\" label");
6588        assert_eq!(related.len(), 1, "{related:?}");
6589        assert_eq!(related[0].message, "previously declared here");
6590        assert_eq!(
6591            related[0].location.uri, a_web,
6592            "the label lies in a_web.bynk, not the diagnostic's own file"
6593        );
6594        // `service api {` is line 2 (0-based) of a_web.bynk; `api` at column 8.
6595        assert_eq!(
6596            related[0].location.range,
6597            Range::new(Position::new(2, 8), Position::new(2, 11)),
6598        );
6599    }
6600
6601    /// #2081: a round reconciles events against the committed
6602    /// `bynk.schema.lock`, read-only, so a non-additive change reaches the
6603    /// editor as `bynk.event.non_additive_schema_change`, as it reaches
6604    /// `bynk check`. The lock is never written, and a changed lock is re-read
6605    /// on the next round (its stamp moved), clearing the diagnostic.
6606    #[tokio::test]
6607    async fn a_round_reports_a_non_additive_event_change_against_the_lock() {
6608        use futures::StreamExt;
6609        use tower::{Service, ServiceExt};
6610
6611        const CODE: &str = "bynk.event.non_additive_schema_change";
6612        const LOCK_V1: &str = "version = 1\n\n\
6613            [events.\"commerce.order.PaymentConfirmed\"]\nschema = 1\n\n\
6614            [[events.\"commerce.order.PaymentConfirmed\".fields]]\n\
6615            name = \"orderId\"\ntype = \"String\"\ndefault = false\n";
6616        // The same event recorded with the source's current shape.
6617        const LOCK_V2: &str = "version = 1\n\n\
6618            [events.\"commerce.order.PaymentConfirmed\"]\nschema = 1\n\n\
6619            [[events.\"commerce.order.PaymentConfirmed\".fields]]\n\
6620            name = \"orderId\"\ntype = \"String\"\ndefault = false\n\n\
6621            [[events.\"commerce.order.PaymentConfirmed\".fields]]\n\
6622            name = \"region\"\ntype = \"String\"\ndefault = false\n";
6623        // `region` added with no default: not additive against `LOCK_V1`.
6624        const SOURCE: &str = "context commerce.order\n\n\
6625            consumes bynk { Events }\n\n\
6626            event PaymentConfirmed = {\n  orderId: String,\n  region: String,\n}\n\n\
6627            service markPaid {\n  on call(orderId: String) -> Effect[()] by Caller given Events {\n    \
6628            Events.emit[PaymentConfirmed](PaymentConfirmed { orderId: orderId, region: \"US\" })\n  \
6629            }\n}\n";
6630
6631        let s = scratch_project(
6632            "schema_lock",
6633            &[
6634                ("bynk.toml", "[project]\nname = \"shop\"\n"),
6635                ("src/commerce/order.bynk", SOURCE),
6636                ("bynk.schema.lock", LOCK_V1),
6637            ],
6638        );
6639        let (mut service, socket) = tower_lsp::LspService::new(Backend::new);
6640        for request in [
6641            tower_lsp::jsonrpc::Request::build("initialize")
6642                .params(serde_json::json!({ "capabilities": {} }))
6643                .id(1)
6644                .finish(),
6645            tower_lsp::jsonrpc::Request::build("initialized")
6646                .params(serde_json::json!({}))
6647                .finish(),
6648        ] {
6649            service.ready().await.unwrap().call(request).await.unwrap();
6650        }
6651        let published = Arc::new(std::sync::Mutex::new(Vec::<PublishDiagnosticsParams>::new()));
6652        let drain = {
6653            let published = Arc::clone(&published);
6654            tokio::spawn(socket.for_each(move |message| {
6655                if message.method() == "textDocument/publishDiagnostics"
6656                    && let Some(params) = message.params()
6657                {
6658                    published
6659                        .lock()
6660                        .unwrap()
6661                        .push(serde_json::from_value(params.clone()).unwrap());
6662                }
6663                async {}
6664            }))
6665        };
6666        let backend = service.inner().clone();
6667        let canonical = s.0.canonicalize().unwrap();
6668        backend
6669            .state
6670            .write()
6671            .await
6672            .projects
6673            .insert(canonical.clone(), ProjectState::default());
6674        // The project-level diagnostic anchors on `bynk.toml`.
6675        let manifest = Url::from_file_path(canonical.join("bynk.toml")).unwrap();
6676        let reported = |published: &[PublishDiagnosticsParams]| {
6677            published
6678                .iter()
6679                .rfind(|p| p.uri == manifest)
6680                .is_some_and(|p| {
6681                    p.diagnostics
6682                        .iter()
6683                        .any(|d| d.code == Some(NumberOrString::String(CODE.into())))
6684                })
6685        };
6686
6687        backend.run_project_diagnostics(canonical.clone()).await;
6688        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
6689        assert!(
6690            reported(&published.lock().unwrap()),
6691            "the round must report {CODE} against the committed lock: {:?}",
6692            published.lock().unwrap()
6693        );
6694        assert_eq!(
6695            std::fs::read_to_string(canonical.join("bynk.schema.lock")).unwrap(),
6696            LOCK_V1,
6697            "the editor must never write the lock"
6698        );
6699
6700        // Record the new shape, as `bynk compile` would after a fix: the next
6701        // round re-reads the lock and the diagnostic clears.
6702        std::fs::write(canonical.join("bynk.schema.lock"), LOCK_V2).unwrap();
6703        backend.run_project_diagnostics(canonical.clone()).await;
6704        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
6705        assert!(
6706            !reported(&published.lock().unwrap()),
6707            "a lock matching the source must clear {CODE}: {:?}",
6708            published.lock().unwrap()
6709        );
6710
6711        // Restore the stale lock: it is read again and the diagnostic returns.
6712        std::fs::write(canonical.join("bynk.schema.lock"), LOCK_V1).unwrap();
6713        backend.run_project_diagnostics(canonical.clone()).await;
6714        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
6715        assert!(
6716            reported(&published.lock().unwrap()),
6717            "the old lock is read again"
6718        );
6719        // No lock at all: a fresh project, nothing to report.
6720        std::fs::remove_file(canonical.join("bynk.schema.lock")).unwrap();
6721        backend.run_project_diagnostics(canonical.clone()).await;
6722        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
6723        drain.abort();
6724        assert!(
6725            !reported(&published.lock().unwrap()),
6726            "with no lock there is nothing to report: {:?}",
6727            published.lock().unwrap()
6728        );
6729        assert!(
6730            !canonical.join("bynk.schema.lock").exists(),
6731            "the editor must not create a lock"
6732        );
6733    }
6734
6735    /// State-migrations S0 (#2204): a round reconciles agent state shapes
6736    /// against the committed lock too, so renaming a `store` field reaches the
6737    /// editor as `bynk.agent.non_additive_state_change` on the agent's own
6738    /// file, as it reaches `bynk check`. The lock is never written.
6739    #[tokio::test]
6740    async fn a_round_reports_a_non_additive_agent_state_change_against_the_lock() {
6741        use futures::StreamExt;
6742        use tower::{Service, ServiceExt};
6743
6744        const CODE: &str = "bynk.agent.non_additive_state_change";
6745        const LOCK: &str = "version = 2\n\n[events]\n\n\
6746            [agents.\"shop.Cart\"]\nversion = 1\nfloor = 1\n\n\
6747            [[agents.\"shop.Cart\".shapes]]\nversion = 1\nadditive = false\n\n\
6748            [[agents.\"shop.Cart\".shapes.fields]]\n\
6749            name = \"owner\"\nkind = \"Cell\"\ntype = \"String\"\nrefinement = \"String\"\n";
6750        const SOURCE: &str = "context shop\n\nagent Cart {\n  key id: String\n\n  \
6751            store ownerName: Cell[String]\n\n  on call ping() -> Effect[Int] {\n    1\n  }\n}\n";
6752
6753        let s = scratch_project(
6754            "agent_schema_lock",
6755            &[
6756                ("bynk.toml", "[project]\nname = \"shop\"\n"),
6757                ("src/shop/cart.bynk", SOURCE),
6758                ("bynk.schema.lock", LOCK),
6759            ],
6760        );
6761        let (mut service, socket) = tower_lsp::LspService::new(Backend::new);
6762        for request in [
6763            tower_lsp::jsonrpc::Request::build("initialize")
6764                .params(serde_json::json!({ "capabilities": {} }))
6765                .id(1)
6766                .finish(),
6767            tower_lsp::jsonrpc::Request::build("initialized")
6768                .params(serde_json::json!({}))
6769                .finish(),
6770        ] {
6771            service.ready().await.unwrap().call(request).await.unwrap();
6772        }
6773        let published = Arc::new(std::sync::Mutex::new(Vec::<PublishDiagnosticsParams>::new()));
6774        let drain = {
6775            let published = Arc::clone(&published);
6776            tokio::spawn(socket.for_each(move |message| {
6777                if message.method() == "textDocument/publishDiagnostics"
6778                    && let Some(params) = message.params()
6779                {
6780                    published
6781                        .lock()
6782                        .unwrap()
6783                        .push(serde_json::from_value(params.clone()).unwrap());
6784                }
6785                async {}
6786            }))
6787        };
6788        let backend = service.inner().clone();
6789        let canonical = s.0.canonicalize().unwrap();
6790        backend
6791            .state
6792            .write()
6793            .await
6794            .projects
6795            .insert(canonical.clone(), ProjectState::default());
6796        let source = Url::from_file_path(canonical.join("src/shop/cart.bynk")).unwrap();
6797
6798        backend.run_project_diagnostics(canonical.clone()).await;
6799        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
6800        drain.abort();
6801        let published = published.lock().unwrap();
6802        assert!(
6803            published
6804                .iter()
6805                .rfind(|p| p.uri == source)
6806                .is_some_and(|p| p
6807                    .diagnostics
6808                    .iter()
6809                    .any(|d| d.code == Some(NumberOrString::String(CODE.into())))),
6810            "the round must report {CODE} on the agent's file: {published:?}"
6811        );
6812        assert_eq!(
6813            std::fs::read_to_string(canonical.join("bynk.schema.lock")).unwrap(),
6814            LOCK,
6815            "the editor must never write the lock"
6816        );
6817    }
6818
6819    /// #2467: `bynk/contractDiff` lists every boundary change since the lock,
6820    /// classified by the reconciliation's own classifier: an added defaulted
6821    /// field is compatible, a removed field and a renamed agent `store` field
6822    /// are breaking. A service whose contract hash differs from the deploy
6823    /// ledger's live record is `changed` (never `breaking`), and an unchanged
6824    /// one yields nothing. Read-only: neither lock is written.
6825    #[tokio::test]
6826    async fn contract_diff_classifies_boundary_changes_against_the_lock() {
6827        const LOCK: &str = "version = 2\n\n\
6828            [events.\"commerce.order.PaymentConfirmed\"]\nschema = 1\n\n\
6829            [[events.\"commerce.order.PaymentConfirmed\".fields]]\n\
6830            name = \"orderId\"\ntype = \"String\"\ndefault = false\n\n\
6831            [events.\"commerce.order.ShipmentSent\"]\nschema = 1\n\n\
6832            [[events.\"commerce.order.ShipmentSent\".fields]]\n\
6833            name = \"orderId\"\ntype = \"String\"\ndefault = false\n\n\
6834            [[events.\"commerce.order.ShipmentSent\".fields]]\n\
6835            name = \"email\"\ntype = \"String\"\ndefault = false\n\n\
6836            [agents.\"shop.Cart\"]\nversion = 1\nfloor = 1\n\n\
6837            [[agents.\"shop.Cart\".shapes]]\nversion = 1\nadditive = false\n\n\
6838            [[agents.\"shop.Cart\".shapes.fields]]\n\
6839            name = \"owner\"\nkind = \"Cell\"\ntype = \"String\"\nrefinement = \"String\"\n\n\
6840            [agents.\"shop.Gone\"]\nversion = 1\nfloor = 1\n\n\
6841            [[agents.\"shop.Gone\".shapes]]\nversion = 1\nadditive = false\n\n\
6842            [[agents.\"shop.Gone\".shapes.fields]]\n\
6843            name = \"n\"\nkind = \"Cell\"\ntype = \"Int\"\nrefinement = \"Int\"\n";
6844        const ORDER: &str = "context commerce.order\n\n\
6845            consumes bynk { Events }\n\n\
6846            event PaymentConfirmed = {\n  orderId: String,\n  region: String = \"US\",\n}\n\n\
6847            event ShipmentSent = {\n  orderId: String,\n}\n\n\
6848            service markPaid {\n  on call(orderId: String) -> Effect[()] by Caller given Events {\n    \
6849            Events.emit[PaymentConfirmed](PaymentConfirmed { orderId: orderId, region: \"US\" })\n  \
6850            }\n}\n";
6851        const CART: &str = "context shop\n\nagent Cart {\n  key id: String\n\n  \
6852            store ownerName: Cell[String]\n\n  on call ping() -> Effect[Int] {\n    1\n  }\n}\n";
6853        // `markPaid`'s recorded hash cannot match what the source provides.
6854        const LEDGER: &str = "version = 1\n\n\
6855            [environments.default.workers.commerce-order]\ndeployed = true\n\n\
6856            [environments.default.workers.commerce-order.contracts]\nmarkPaid = \"0000000000000000\"\n";
6857
6858        let s = scratch_project(
6859            "contract_diff",
6860            &[
6861                ("bynk.toml", "[project]\nname = \"shop\"\n"),
6862                ("src/commerce/order.bynk", ORDER),
6863                ("src/shop/cart.bynk", CART),
6864                ("bynk.schema.lock", LOCK),
6865                ("bynk.deploy.lock", LEDGER),
6866            ],
6867        );
6868        let backend = backend_at(&s.0).await;
6869        let canonical = s.0.canonicalize().unwrap();
6870        backend.run_project_diagnostics(canonical.clone()).await;
6871        let uri = Url::from_file_path(canonical.join("src/commerce/order.bynk")).unwrap();
6872        let model = backend
6873            .contract_diff(contract_diff_request::ContractDiffParams {
6874                text_document: TextDocumentIdentifier { uri },
6875            })
6876            .await
6877            .unwrap()
6878            .expect("a committed round answers");
6879
6880        let rows: Vec<(&str, &str, &str)> = model
6881            .changes
6882            .iter()
6883            .map(|c| (c.kind, c.name.as_str(), c.class))
6884            .collect();
6885        assert_eq!(
6886            rows,
6887            vec![
6888                ("event", "PaymentConfirmed", "compatible"),
6889                ("event", "ShipmentSent", "breaking"),
6890                ("agent", "Cart", "breaking"),
6891                // Recorded in the lock, declared nowhere: `class_removed`.
6892                ("agent", "Gone", "breaking"),
6893            ],
6894            "{model:?}"
6895        );
6896        let shipment = &model.changes[1];
6897        assert!(shipment.detail.contains("email"), "{}", shipment.detail);
6898        assert_eq!(shipment.locked_version, 1);
6899        assert!(
6900            model
6901                .changes
6902                .iter()
6903                .filter(|c| c.name != "Gone")
6904                .all(|c| c.loc.is_some()),
6905            "each declared change points at its declaration: {model:?}"
6906        );
6907        assert_eq!(model.lock, contract_diff_request::LockWire::Read);
6908        let services: Vec<(&str, &str)> = model
6909            .services
6910            .iter()
6911            .map(|r| (r.service.as_str(), r.status))
6912            .collect();
6913        assert_eq!(services, vec![("markPaid", "changed")], "{model:?}");
6914        assert_eq!(
6915            std::fs::read_to_string(canonical.join("bynk.schema.lock")).unwrap(),
6916            LOCK,
6917            "the editor must never write the lock"
6918        );
6919        assert_eq!(
6920            std::fs::read_to_string(canonical.join("bynk.deploy.lock")).unwrap(),
6921            LEDGER,
6922            "the editor must never write the ledger"
6923        );
6924    }
6925
6926    /// #2467: a `bynk.schema.lock` that does not parse is reported as
6927    /// unreadable, not as absent.
6928    #[tokio::test]
6929    async fn contract_diff_says_a_corrupt_lock_is_unreadable() {
6930        let s = scratch_project(
6931            "contract_diff_corrupt",
6932            &[
6933                ("bynk.toml", "[project]\nname = \"shop\"\n"),
6934                ("src/shop/cart.bynk", "context shop\n"),
6935                ("bynk.schema.lock", "not a lock ["),
6936            ],
6937        );
6938        let backend = backend_at(&s.0).await;
6939        let canonical = s.0.canonicalize().unwrap();
6940        backend.run_project_diagnostics(canonical.clone()).await;
6941        let uri = Url::from_file_path(canonical.join("src/shop/cart.bynk")).unwrap();
6942        let model = backend
6943            .contract_diff(contract_diff_request::ContractDiffParams {
6944                text_document: TextDocumentIdentifier { uri },
6945            })
6946            .await
6947            .unwrap()
6948            .expect("a committed round answers");
6949        assert_eq!(model.lock, contract_diff_request::LockWire::Unreadable);
6950    }
6951
6952    /// #2838: a hint-severity diagnostic reaches the editor as an LSP hint.
6953    #[test]
6954    fn a_hint_diagnostic_maps_to_the_lsp_hint_severity() {
6955        let text = "context app\n";
6956        let positions = crate::position::PositionMap::new(text);
6957        let uri = Url::parse("file:///z.bynk").unwrap();
6958        let d = bynk_ide::Diagnostic {
6959            severity: bynk_syntax::Severity::Hint,
6960            error: bynk_syntax::CompileError::new(
6961                "bynk.parse.let_else_staircase",
6962                bynk_syntax::span::Span::new(0, 7),
6963                "msg",
6964            ),
6965            label_files: Vec::new(),
6966        };
6967        let diagnostic = make_diagnostic(&d, &positions, &uri, &ProjectFiles::new());
6968        assert_eq!(diagnostic.severity, Some(DiagnosticSeverity::HINT));
6969    }
6970
6971    /// A label with nowhere to point — in a toolchain-injected unit, or in a
6972    /// file the round has no snapshot of — is a `note:` on the message, never
6973    /// a `relatedInformation` entry at this document's own positions.
6974    #[test]
6975    fn a_label_with_no_file_to_point_at_becomes_a_note() {
6976        let text = "context app\n";
6977        let positions = crate::position::PositionMap::new(text);
6978        let uri = Url::parse("file:///z.bynk").unwrap();
6979        let d = bynk_ide::Diagnostic {
6980            severity: bynk_syntax::Severity::Error,
6981            error: bynk_syntax::CompileError::new(
6982                "bynk.test",
6983                bynk_syntax::span::Span::new(0, 7),
6984                "msg",
6985            )
6986            .with_label(bynk_syntax::span::Span::new(0, 1), "in an injected unit")
6987            .with_label(bynk_syntax::span::Span::new(0, 1), "in an unanalysed file")
6988            .with_label(bynk_syntax::span::Span::new(0, 1), "in no known file"),
6989            label_files: vec![
6990                bynk_ide::LabelFile::FirstParty {
6991                    identity_path: "bynk.bynk",
6992                    source: "commons bynk\n",
6993                },
6994                bynk_ide::LabelFile::Other(PathBuf::from("src/missing.bynk")),
6995                bynk_ide::LabelFile::Unavailable,
6996            ],
6997        };
6998        let diagnostic = make_diagnostic(&d, &positions, &uri, &ProjectFiles::new());
6999        assert!(
7000            diagnostic.related_information.is_none(),
7001            "{:?}",
7002            diagnostic.related_information
7003        );
7004        assert_eq!(
7005            diagnostic.message,
7006            "msg\n\nnote: in an injected unit\n\nnote: in an unanalysed file\n\nnote: in no known file"
7007        );
7008    }
7009
7010    /// Test helpers for the single-project behaviour tests (each builds exactly
7011    /// one project via `backend_at` or an equivalent insert). They read whatever
7012    /// the one entry's key is, so a test need not thread the canonical root.
7013    impl Backend {
7014        async fn test_root(&self) -> PathBuf {
7015            self.state
7016                .read()
7017                .await
7018                .projects
7019                .keys()
7020                .next()
7021                .cloned()
7022                .expect("a test project entry")
7023        }
7024        async fn run_round(&self) {
7025            let root = self.test_root().await;
7026            self.run_project_diagnostics(root).await;
7027        }
7028        async fn test_analysis(&self) -> Option<Arc<Analysis>> {
7029            let root = self.test_root().await;
7030            self.project_analysis(&root).await
7031        }
7032        async fn test_round_started(&self) -> u64 {
7033            let root = self.test_root().await;
7034            self.state
7035                .read()
7036                .await
7037                .projects
7038                .get(&root)
7039                .map(|p| p.analysis_round_started)
7040                .unwrap_or(0)
7041        }
7042    }
7043
7044    /// The slice, end to end through the server: a round covers **every**
7045    /// `include` tree, and each file keeps a distinct project-relative identity
7046    /// (ADR 0198). Before slice A the round was handed `<root>/src` and the
7047    /// `tests/` tree did not exist as far as the LSP was concerned.
7048    #[tokio::test]
7049    async fn a_round_covers_every_include_tree() {
7050        let s = scratch_project(
7051            "round",
7052            &[
7053                ("bynk.toml", "[project]\nname = \"round\"\n"),
7054                ("src/thing.bynk", "context thing\n"),
7055                // Same basename, second root — the ADR 0198 collision.
7056                ("tests/thing.bynk", "suite thing\n"),
7057            ],
7058        );
7059        let backend = backend_at(&s.0).await;
7060        backend.run_round().await;
7061
7062        let analysis = backend.test_analysis().await.expect("a round committed");
7063        let mut keys: Vec<String> = analysis
7064            .snapshots
7065            .keys()
7066            .map(|p| p.to_string_lossy().replace('\\', "/"))
7067            .collect();
7068        keys.sort();
7069        assert_eq!(
7070            keys,
7071            vec!["src/thing.bynk", "tests/thing.bynk"],
7072            "the round must cover both include trees, with distinct identities",
7073        );
7074    }
7075
7076    /// The identity a request resolves through. `uri_to_rel` is one
7077    /// `strip_prefix` against the project root — total across `include` trees,
7078    /// where the old `src` base could only ever name files in one of them.
7079    #[tokio::test]
7080    async fn a_uri_in_any_include_tree_resolves_to_its_analysed_file() {
7081        let s = scratch_project(
7082            "uri",
7083            &[
7084                ("bynk.toml", "[project]\nname = \"uri\"\n"),
7085                ("src/thing.bynk", "context thing\n"),
7086                ("tests/thing.bynk", "suite thing\n"),
7087            ],
7088        );
7089        let backend = backend_at(&s.0).await;
7090        backend.run_round().await;
7091        let analysis = backend.test_analysis().await.expect("round");
7092
7093        for (rel, label) in [
7094            ("src/thing.bynk", "primary"),
7095            ("tests/thing.bynk", "secondary"),
7096        ] {
7097            let abs = s.0.join(rel);
7098            let uri = Url::from_file_path(abs.canonicalize().unwrap_or(abs)).unwrap();
7099            let resolved = Backend::uri_to_rel(&analysis, &uri)
7100                .unwrap_or_else(|| panic!("{label} root URI must resolve"));
7101            assert_eq!(
7102                resolved.to_string_lossy().replace('\\', "/"),
7103                rel,
7104                "a {label}-tree URI must name its own analysed file",
7105            );
7106            assert!(
7107                analysis.snapshots.contains_key(&resolved),
7108                "…and that file must be in the round",
7109            );
7110        }
7111    }
7112
7113    /// Finding #62: `project_content` must exclude the calling file's own
7114    /// path — `bynk-ide`'s completion helpers already parse it fresh from the
7115    /// live buffer, so leaving it in the map would additionally serve its
7116    /// on-disk copy (stale relative to any unsaved edit) alongside the buffer
7117    /// parse.
7118    #[tokio::test]
7119    async fn project_content_excludes_the_calling_file() {
7120        let s = scratch_project(
7121            "self_excl",
7122            &[
7123                ("bynk.toml", "[project]\nname = \"self_excl\"\n"),
7124                ("a.bynk", "context a\n"),
7125                ("b.bynk", "context b\n"),
7126            ],
7127        );
7128        let backend = backend_at(&s.0).await;
7129        let abs = s.0.join("a.bynk");
7130        let uri = Url::from_file_path(abs.canonicalize().unwrap_or(abs)).unwrap();
7131        let content = backend
7132            .project_content(&uri)
7133            .await
7134            .expect("a project root resolves to a content map");
7135        assert!(
7136            !content.keys().any(|p| p.file_name().unwrap() == "a.bynk"),
7137            "the calling file's own path must not be in its own project content map: {content:?}"
7138        );
7139        assert!(
7140            content.keys().any(|p| p.file_name().unwrap() == "b.bynk"),
7141            "a sibling project file must still be present: {content:?}"
7142        );
7143        assert_eq!(
7144            content
7145                .iter()
7146                .find(|(p, _)| p.file_name().unwrap() == "b.bynk")
7147                .map(|(_, text)| text.as_str()),
7148            Some("context b\n"),
7149            "the sibling's content must be the real file content, not just its path"
7150        );
7151    }
7152
7153    /// `exclude` reaches the server, not just the compiler. `project.rs` used to
7154    /// parse it and throw it away — its own comment said the analyse walk "does
7155    /// not yet prune by `exclude`".
7156    #[tokio::test]
7157    async fn an_excluded_tree_is_not_analysed() {
7158        let s = scratch_project(
7159            "excl",
7160            &[
7161                (
7162                    "bynk.toml",
7163                    "[project]\nname = \"excl\"\n\n[paths]\ninclude = [\".\"]\nexclude = [\"generated\"]\n",
7164                ),
7165                ("a.bynk", "context a\n"),
7166                ("generated/gen.bynk", "context gen\n"),
7167            ],
7168        );
7169        let backend = backend_at(&s.0).await;
7170        backend.run_round().await;
7171        let analysis = backend.test_analysis().await.expect("round");
7172        let keys: Vec<String> = analysis
7173            .snapshots
7174            .keys()
7175            .map(|p| p.to_string_lossy().replace('\\', "/"))
7176            .collect();
7177        assert_eq!(keys, vec!["a.bynk"], "excluded trees stay out of the round");
7178    }
7179
7180    /// CI repro (#653): the VS Code extension's fixture workspace — a legacy
7181    /// `[paths] src`/`tests` manifest (keys ADR 0147 retired, so
7182    /// `read_project_paths` ignores them → `conventional()` → `["src"]`) with a
7183    /// dotted commons in `src/`. Drives the real `references` handler.
7184    #[tokio::test]
7185    async fn references_resolve_in_the_vscode_fixture_layout() {
7186        let s = scratch_project(
7187            "vsc",
7188            &[
7189                (
7190                    "bynk.toml",
7191                    "[project]\nname = \"fixture\"\nversion = \"0.1.0\"\n\n[paths]\nsrc = \"src\"\ntests = \"tests\"\n",
7192                ),
7193                (
7194                    "src/text.bynk",
7195                    "commons fixture.text\n\nfn shout(s: String) -> String {\n  s\n}\n\nfn greet(name: String) -> String {\n  \"Hi, \\(shout(name))!\"\n}\n",
7196                ),
7197            ],
7198        );
7199        // Root exactly as `initialize` does: resolve from the workspace folder.
7200        let (root, config) = Backend::resolve_root(&s.0).expect("bynk.toml is present");
7201        assert_eq!(root, s.0, "the manifest's directory is the project root");
7202
7203        let (service, _socket) = tower_lsp::LspService::new(Backend::new);
7204        let backend = service.inner().clone();
7205        {
7206            let mut st = backend.state.write().await;
7207            // Key by the canonical root, so the entry matches `references`'
7208            // URI-based routing (`resolve_root` canonicalises).
7209            let canonical = root.canonicalize().unwrap_or_else(|_| root.clone());
7210            st.projects.insert(
7211                canonical,
7212                ProjectState {
7213                    config,
7214                    ..Default::default()
7215                },
7216            );
7217        }
7218        backend.run_round().await;
7219
7220        let analysis = backend.test_analysis().await.expect("a round committed");
7221        let keys: Vec<String> = analysis
7222            .snapshots
7223            .keys()
7224            .map(|p| p.to_string_lossy().replace('\\', "/"))
7225            .collect();
7226        assert_eq!(keys, vec!["src/text.bynk"], "the fixture file is analysed");
7227
7228        // The URI the editor sends, mapped through the round's identity.
7229        let abs = s.0.join("src/text.bynk");
7230        let uri = Url::from_file_path(abs.canonicalize().unwrap_or(abs)).unwrap();
7231        let rel = Backend::uri_to_rel(&analysis, &uri).expect("URI resolves into the round");
7232        assert_eq!(rel, PathBuf::from("src/text.bynk"));
7233
7234        // `shout`'s declaration site: line 2 (0-based), at `fn shout`.
7235        let text = analysis.snapshots.get(&rel).expect("snapshot present");
7236        let decl = text.find("shout").expect("`shout` in source");
7237        let pos = crate::position::offset_to_position(text, decl);
7238
7239        let refs = backend
7240            .references(ReferenceParams {
7241                text_document_position: TextDocumentPositionParams {
7242                    text_document: TextDocumentIdentifier { uri: uri.clone() },
7243                    position: pos,
7244                },
7245                work_done_progress_params: Default::default(),
7246                partial_result_params: Default::default(),
7247                context: ReferenceContext {
7248                    include_declaration: true,
7249                },
7250            })
7251            .await
7252            .expect("references must not error");
7253        let found = refs.unwrap_or_default();
7254        assert!(
7255            !found.is_empty(),
7256            "`shout` is referenced by `greet` — references must resolve; got none",
7257        );
7258    }
7259
7260    // -- Type hierarchy: refined/opaque types over their primitive -----------
7261
7262    const HIER_MANIFEST: &str = "[project]\nname = \"hier\"\nversion = \"0.1.0\"\n";
7263    const HIER_A: &str = "commons hier.a\n\ntype Age = Int where InRange(0, 150)\ntype Quantity = Int where InRange(1, 100)\ntype OrderId = opaque String\ntype Name = String where NonEmpty\ntype Point = { x: Int, y: Int }\n";
7264    const HIER_B: &str =
7265        "commons hier.b\n\ntype Score = Int where InRange(0, 10)\ntype Secret = opaque Int\n";
7266
7267    /// A scratch project of `files`, rounded, with the analysis it committed.
7268    async fn hier_backend(tag: &str, files: &[(&str, &str)]) -> (Scratch, Backend) {
7269        let s = scratch_project(tag, files);
7270        let (root, config) = Backend::resolve_root(&s.0).expect("bynk.toml is present");
7271        let backend = bare_backend().await;
7272        {
7273            let canonical = root.canonicalize().unwrap_or_else(|_| root.clone());
7274            backend.state.write().await.projects.insert(
7275                canonical,
7276                ProjectState {
7277                    config,
7278                    ..Default::default()
7279                },
7280            );
7281        }
7282        backend.run_round().await;
7283        (s, backend)
7284    }
7285
7286    /// `prepareTypeHierarchy` at the first occurrence of `needle` in `rel`.
7287    async fn hier_prepare(
7288        s: &Scratch,
7289        backend: &Backend,
7290        rel: &str,
7291        needle: &str,
7292    ) -> Option<TypeHierarchyItem> {
7293        let analysis = backend.test_analysis().await.expect("a round committed");
7294        let uri = file_uri(&s.0, rel);
7295        let path = Backend::uri_to_rel(&analysis, &uri).expect("file in round");
7296        let text = analysis.snapshots.get(&path).expect("snapshot");
7297        let pos = crate::position::offset_to_position(text, text.find(needle).expect("needle"));
7298        backend
7299            .prepare_type_hierarchy(TypeHierarchyPrepareParams {
7300                text_document_position_params: TextDocumentPositionParams {
7301                    text_document: TextDocumentIdentifier { uri },
7302                    position: pos,
7303                },
7304                work_done_progress_params: Default::default(),
7305            })
7306            .await
7307            .expect("no error")
7308            .and_then(|v| v.into_iter().next())
7309    }
7310
7311    async fn hier_supers(backend: &Backend, item: &TypeHierarchyItem) -> Vec<TypeHierarchyItem> {
7312        backend
7313            .supertypes(TypeHierarchySupertypesParams {
7314                item: item.clone(),
7315                work_done_progress_params: Default::default(),
7316                partial_result_params: Default::default(),
7317            })
7318            .await
7319            .expect("no error")
7320            .expect("some")
7321    }
7322
7323    async fn hier_subs(backend: &Backend, item: &TypeHierarchyItem) -> Vec<TypeHierarchyItem> {
7324        backend
7325            .subtypes(TypeHierarchySubtypesParams {
7326                item: item.clone(),
7327                work_done_progress_params: Default::default(),
7328                partial_result_params: Default::default(),
7329            })
7330            .await
7331            .expect("no error")
7332            .expect("some")
7333    }
7334
7335    fn names(items: &[TypeHierarchyItem]) -> Vec<&str> {
7336        items.iter().map(|i| i.name.as_str()).collect()
7337    }
7338
7339    /// A refined type's supertype is its primitive, and the primitive's
7340    /// subtypes span every file in the project.
7341    #[tokio::test]
7342    async fn type_hierarchy_walks_from_a_refinement_to_its_primitive_and_back() {
7343        let (s, backend) = hier_backend(
7344            "hier_chain",
7345            &[
7346                ("bynk.toml", HIER_MANIFEST),
7347                ("src/a.bynk", HIER_A),
7348                ("src/b.bynk", HIER_B),
7349            ],
7350        )
7351        .await;
7352        let age = hier_prepare(&s, &backend, "src/a.bynk", "Age")
7353            .await
7354            .expect("Age is a refined type");
7355        assert_eq!(age.name, "Age");
7356
7357        let supers = hier_supers(&backend, &age).await;
7358        assert_eq!(names(&supers), ["Int"]);
7359        // A declared type has no subtypes; a primitive has no supertypes.
7360        assert!(hier_subs(&backend, &age).await.is_empty());
7361        assert!(hier_supers(&backend, &supers[0]).await.is_empty());
7362
7363        // Every `Int` refinement, across both files; `Secret` (opaque, in
7364        // `hier.b`) is hidden from a hierarchy opened in `hier.a`.
7365        let subs = hier_subs(&backend, &supers[0]).await;
7366        assert_eq!(names(&subs), ["Age", "Quantity", "Score"]);
7367        assert!(subs.iter().any(|i| i.uri.path().ends_with("src/b.bynk")));
7368        // The round-trip: a subtype leads back to the same primitive.
7369        let back = hier_supers(&backend, &subs[2]).await;
7370        assert_eq!(names(&back), ["Int"]);
7371    }
7372
7373    /// A primitive written as a declaration's base is a hierarchy root in its
7374    /// own right, anchored at that occurrence — from the cursor or from
7375    /// `supertypes`.
7376    #[tokio::test]
7377    async fn type_hierarchy_anchors_a_primitive_at_its_written_occurrence() {
7378        let (s, backend) = hier_backend(
7379            "hier_anchor",
7380            &[("bynk.toml", HIER_MANIFEST), ("src/a.bynk", HIER_A)],
7381        )
7382        .await;
7383        let int = hier_prepare(&s, &backend, "src/a.bynk", "Int where")
7384            .await
7385            .expect("`Int` under the cursor is offered");
7386        assert_eq!(int.name, "Int");
7387        let line = HIER_A
7388            .lines()
7389            .position(|l| l.starts_with("type Age"))
7390            .unwrap() as u32;
7391        let col = HIER_A
7392            .lines()
7393            .nth(line as usize)
7394            .unwrap()
7395            .find("Int")
7396            .unwrap() as u32;
7397        assert_eq!(int.range.start, Position::new(line, col));
7398        assert_eq!(names(&hier_subs(&backend, &int).await), ["Age", "Quantity"]);
7399
7400        // Reached through `supertypes`, the primitive anchors at the same
7401        // occurrence in the type's own declaration.
7402        let age = hier_prepare(&s, &backend, "src/a.bynk", "Age")
7403            .await
7404            .unwrap();
7405        let up = hier_supers(&backend, &age).await;
7406        assert_eq!(up[0].range, int.range);
7407        // #2530: a primitive written anywhere a type is — here a record field —
7408        // is a root too, anchored at that occurrence.
7409        let field = hier_prepare(&s, &backend, "src/a.bynk", "Int, y")
7410            .await
7411            .expect("`Int` in a field type is offered");
7412        assert_eq!(field.name, "Int");
7413        assert_ne!(field.range, int.range);
7414        assert_eq!(
7415            names(&hier_subs(&backend, &field).await),
7416            ["Age", "Quantity"]
7417        );
7418        // A cursor on a name that is not a declaration's base offers nothing.
7419        assert!(
7420            hier_prepare(&s, &backend, "src/a.bynk", "commons")
7421                .await
7422                .is_none()
7423        );
7424    }
7425
7426    /// An opaque type's representation shows only inside its declaring unit.
7427    #[tokio::test]
7428    async fn type_hierarchy_hides_an_opaque_representation_outside_its_unit() {
7429        let (s, backend) = hier_backend(
7430            "hier_opaque",
7431            &[
7432                ("bynk.toml", HIER_MANIFEST),
7433                ("src/a.bynk", HIER_A),
7434                ("src/b.bynk", HIER_B),
7435            ],
7436        )
7437        .await;
7438
7439        // Opened inside `hier.a`: `OrderId` shows `String`, and `String`'s
7440        // subtypes include it.
7441        let order_id = hier_prepare(&s, &backend, "src/a.bynk", "OrderId")
7442            .await
7443            .expect("OrderId is an opaque type");
7444        let supers = hier_supers(&backend, &order_id).await;
7445        assert_eq!(names(&supers), ["String"]);
7446        let subs = hier_subs(&backend, &supers[0]).await;
7447        assert_eq!(names(&subs), ["OrderId", "Name"]);
7448
7449        // Opened inside `hier.b`: `hier.a`'s `OrderId` is not offered at all,
7450        // and `hier.b`'s own opaque `Secret` is.
7451        let secret = hier_prepare(&s, &backend, "src/b.bynk", "Secret")
7452            .await
7453            .expect("Secret is an opaque type");
7454        let int = &hier_supers(&backend, &secret).await[0];
7455        assert_eq!(
7456            names(&hier_subs(&backend, int).await),
7457            ["Age", "Quantity", "Score", "Secret"]
7458        );
7459        let mut foreign = order_id.clone();
7460        // Re-point the item at `OrderId` but keep `hier.b` as the origin.
7461        let mut data = order_id.data.clone().unwrap();
7462        data["from"] = serde_json::json!("hier.b");
7463        foreign.data = Some(data);
7464        assert!(hier_supers(&backend, &foreign).await.is_empty());
7465        let mut string = supers[0].clone();
7466        let mut data = string.data.clone().unwrap();
7467        data["from"] = serde_json::json!("hier.b");
7468        string.data = Some(data);
7469        assert_eq!(names(&hier_subs(&backend, &string).await), ["Name"]);
7470    }
7471
7472    /// Only refined, opaque and alias types are prepared; a record has no base.
7473    #[tokio::test]
7474    async fn type_hierarchy_is_not_offered_on_a_record() {
7475        let (s, backend) = hier_backend(
7476            "hier_record",
7477            &[("bynk.toml", HIER_MANIFEST), ("src/a.bynk", HIER_A)],
7478        )
7479        .await;
7480        assert!(
7481            hier_prepare(&s, &backend, "src/a.bynk", "Point")
7482                .await
7483                .is_none()
7484        );
7485    }
7486
7487    /// A client that accepts dynamic registration is captured, because the
7488    /// server capability for type hierarchy is registered at `initialized`.
7489    #[tokio::test]
7490    async fn initialize_captures_the_dynamic_type_hierarchy_capability() {
7491        let backend = bare_backend().await;
7492        let params = InitializeParams {
7493            capabilities: ClientCapabilities {
7494                text_document: Some(TextDocumentClientCapabilities {
7495                    type_hierarchy: Some(TypeHierarchyClientCapabilities {
7496                        dynamic_registration: Some(true),
7497                    }),
7498                    ..Default::default()
7499                }),
7500                ..Default::default()
7501            },
7502            ..Default::default()
7503        };
7504        backend.initialize(params).await.expect("initialize");
7505        assert!(backend.state.read().await.supports_dynamic_type_hierarchy);
7506    }
7507
7508    /// #2457: a backend rounded over a one-file project with a `[shout]` doc
7509    /// mention, plus the file's URI and text.
7510    async fn doc_mention_backend() -> (Backend, Url, String) {
7511        let s = scratch_project(
7512            "docmention",
7513            &[
7514                (
7515                    "bynk.toml",
7516                    "[project]\nname = \"fixture\"\nversion = \"0.1.0\"\n",
7517                ),
7518                (
7519                    "src/fixture/other.bynk",
7520                    "commons fixture.other\n\nuses fixture.text\n\n---\nAlso [shout].\n---\nfn quiet() -> Int {\n  0\n}\n",
7521                ),
7522                (
7523                    "src/fixture/text.bynk",
7524                    "commons fixture.text\n\nfn shout(s: String) -> String {\n  s\n}\n\n---\nGreets via [shout], not [Nope].\n---\nfn greet(name: String) -> String {\n  shout(name)\n}\n\n---\nA view. The [cents] field is never negative.\n---\ntype View = {\n  cents: Int,\n}\n",
7525                ),
7526            ],
7527        );
7528        let (root, config) = Backend::resolve_root(&s.0).expect("bynk.toml is present");
7529        let (service, _socket) = tower_lsp::LspService::new(Backend::new);
7530        let backend = service.inner().clone();
7531        {
7532            let mut st = backend.state.write().await;
7533            let canonical = root.canonicalize().unwrap_or_else(|_| root.clone());
7534            st.projects.insert(
7535                canonical,
7536                ProjectState {
7537                    config,
7538                    ..Default::default()
7539                },
7540            );
7541        }
7542        backend.run_round().await;
7543        let analysis = backend.test_analysis().await.expect("a round committed");
7544        let abs = s.0.join("src/fixture/text.bynk");
7545        let uri = Url::from_file_path(abs.canonicalize().unwrap_or(abs)).unwrap();
7546        let rel = Backend::uri_to_rel(&analysis, &uri).expect("URI resolves");
7547        let text = analysis.snapshots.get(&rel).expect("snapshot").clone();
7548        // Keep the scratch directory alive for the test's duration.
7549        std::mem::forget(s);
7550        (backend, uri, text)
7551    }
7552
7553    /// The `(file, offset)` of the first `needle` in `text`, as a position.
7554    fn pos_of(text: &str, needle: &str, plus: usize) -> Position {
7555        crate::position::offset_to_position(text, text.find(needle).unwrap() + plus)
7556    }
7557
7558    async fn shout_references(
7559        backend: &Backend,
7560        uri: &Url,
7561        text: &str,
7562        include_declaration: bool,
7563    ) -> Vec<Location> {
7564        backend
7565            .references(ReferenceParams {
7566                text_document_position: TextDocumentPositionParams {
7567                    text_document: TextDocumentIdentifier { uri: uri.clone() },
7568                    position: pos_of(text, "shout", 0),
7569                },
7570                work_done_progress_params: Default::default(),
7571                partial_result_params: Default::default(),
7572                context: ReferenceContext {
7573                    include_declaration,
7574                },
7575            })
7576            .await
7577            .unwrap()
7578            .unwrap_or_default()
7579    }
7580
7581    #[tokio::test]
7582    async fn references_include_doc_comment_mentions_whatever_include_declaration_says() {
7583        let (backend, uri, text) = doc_mention_backend().await;
7584        let mention = pos_of(&text, "[shout]", 1);
7585        let nope = pos_of(&text, "[Nope]", 1);
7586        for include_declaration in [true, false] {
7587            let refs = shout_references(&backend, &uri, &text, include_declaration).await;
7588            assert!(
7589                refs.iter()
7590                    .any(|l| l.uri == uri && l.range.start == mention),
7591                "the `[shout]` doc mention is a reference (includeDeclaration={include_declaration}); got {refs:?}",
7592            );
7593            assert!(
7594                refs.iter().all(|l| l.range.start != nope),
7595                "an unresolved `[Nope]` is never a reference; got {refs:?}",
7596            );
7597            // The other file's `[shout]` (it `uses` the commons) is included too.
7598            assert!(
7599                refs.iter().any(|l| l.uri != uri),
7600                "the cross-file doc mention is a reference; got {refs:?}",
7601            );
7602        }
7603    }
7604
7605    /// A bare `[field]` in its own record's doc is a reference to the field.
7606    #[tokio::test]
7607    async fn references_include_a_bare_field_link_in_its_own_records_doc() {
7608        let (backend, uri, text) = doc_mention_backend().await;
7609        let mention = pos_of(&text, "[cents]", 1);
7610        for include_declaration in [true, false] {
7611            let refs = backend
7612                .references(ReferenceParams {
7613                    text_document_position: TextDocumentPositionParams {
7614                        text_document: TextDocumentIdentifier { uri: uri.clone() },
7615                        position: pos_of(&text, "cents: Int", 0),
7616                    },
7617                    work_done_progress_params: Default::default(),
7618                    partial_result_params: Default::default(),
7619                    context: ReferenceContext {
7620                        include_declaration,
7621                    },
7622                })
7623                .await
7624                .unwrap()
7625                .unwrap_or_default();
7626            assert!(
7627                refs.iter()
7628                    .any(|l| l.uri == uri && l.range.start == mention),
7629                "`[cents]` in the record's own doc is a reference to the field (includeDeclaration={include_declaration}); got {refs:?}",
7630            );
7631        }
7632    }
7633
7634    #[tokio::test]
7635    async fn document_highlight_includes_same_file_doc_mentions_only() {
7636        let (backend, uri, text) = doc_mention_backend().await;
7637        let hl = backend
7638            .document_highlight(DocumentHighlightParams {
7639                text_document_position_params: TextDocumentPositionParams {
7640                    text_document: TextDocumentIdentifier { uri },
7641                    position: pos_of(&text, "shout", 0),
7642                },
7643                work_done_progress_params: Default::default(),
7644                partial_result_params: Default::default(),
7645            })
7646            .await
7647            .unwrap()
7648            .unwrap_or_default();
7649        let mention = pos_of(&text, "[shout]", 1);
7650        let nope = pos_of(&text, "[Nope]", 1);
7651        assert!(
7652            hl.iter().any(|h| h.range.start == mention),
7653            "the `[shout]` doc mention is highlighted; got {hl:?}",
7654        );
7655        assert!(
7656            hl.iter().all(|h| h.range.start != nope),
7657            "an unresolved `[Nope]` is not highlighted; got {hl:?}",
7658        );
7659        // 3 in this file: the declaration, the call in `greet`, and the doc mention;
7660        // the other file's mention is not highlighted here.
7661        assert_eq!(hl.len(), 3, "same-file occurrences only; got {hl:?}");
7662    }
7663
7664    /// #2457: on the real `examples/rate-limiter` project, references on the
7665    /// `Limiter` agent include its `[Limiter]` doc mention, and references on
7666    /// `decide` (declared in `window`) include the cross-unit `[decide]` one.
7667    #[tokio::test]
7668    async fn references_include_doc_mentions_in_the_rate_limiter_example() {
7669        let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
7670            .parent()
7671            .unwrap()
7672            .join("examples/rate-limiter");
7673        let (root, config) = Backend::resolve_root(&root).expect("bynk.toml is present");
7674        let (service, _socket) = tower_lsp::LspService::new(Backend::new);
7675        let backend = service.inner().clone();
7676        {
7677            let mut st = backend.state.write().await;
7678            let canonical = root.canonicalize().unwrap_or_else(|_| root.clone());
7679            st.projects.insert(
7680                canonical,
7681                ProjectState {
7682                    config,
7683                    ..Default::default()
7684                },
7685            );
7686        }
7687        backend.run_round().await;
7688        let analysis = backend.test_analysis().await.expect("a round committed");
7689        let limiter_uri = |file: &str| {
7690            let abs = root.join(file);
7691            Url::from_file_path(abs.canonicalize().unwrap_or(abs)).unwrap()
7692        };
7693        let refs_at = |file: &'static str, decl: &'static str, mention: &'static str| {
7694            let backend = backend.clone();
7695            let analysis = analysis.clone();
7696            let uri = limiter_uri(file);
7697            async move {
7698                let rel = Backend::uri_to_rel(&analysis, &uri).expect("URI resolves");
7699                let text = analysis.snapshots.get(&rel).unwrap().clone();
7700                // Cursor on the declared name, the last word of `decl`.
7701                let at = text.find(decl).unwrap() + decl.rfind(' ').unwrap() + 1;
7702                let pos = crate::position::offset_to_position(&text, at);
7703                let refs = backend
7704                    .references(ReferenceParams {
7705                        text_document_position: TextDocumentPositionParams {
7706                            text_document: TextDocumentIdentifier { uri },
7707                            position: pos,
7708                        },
7709                        work_done_progress_params: Default::default(),
7710                        partial_result_params: Default::default(),
7711                        context: ReferenceContext {
7712                            include_declaration: true,
7713                        },
7714                    })
7715                    .await
7716                    .unwrap()
7717                    .unwrap_or_default();
7718                // The mention lives in ratelimit.bynk, at the name inside `[..]`.
7719                let rl = Backend::uri_to_rel(&analysis, &limiter_uri("src/ratelimit.bynk"))
7720                    .expect("URI resolves");
7721                let rl_text = analysis.snapshots.get(&rl).unwrap();
7722                let at = rl_text.find(mention).unwrap() + 1;
7723                let want = crate::position::offset_to_position(rl_text, at);
7724                refs.iter().any(|l| l.range.start == want)
7725            }
7726        };
7727        assert!(
7728            refs_at("src/ratelimit.bynk", "agent Limiter", "[Limiter]").await,
7729            "`[Limiter]` is a reference to the `Limiter` agent",
7730        );
7731        assert!(
7732            refs_at("src/window.bynk", "fn decide", "[decide]").await,
7733            "the cross-unit `[decide]` doc mention is a reference to `decide`",
7734        );
7735    }
7736
7737    // -- Slice B: the freshness contract, driven through a real Backend -------
7738    //
7739    // These are behaviour-over-time tests (§4.1): they edit a buffer and then
7740    // make a request, asserting the request answers against the *new* text.
7741    // The static tests above can't see this — the defect lives between the
7742    // edit and the request, which only a driven sequence exercises.
7743
7744    /// Open `src/a.bynk`, round it, then edit and drive `did_change`. `uri`,
7745    /// the round-1 relative path, and the edited version are returned.
7746    async fn open_round_edit(
7747        backend: &Backend,
7748        root: &std::path::Path,
7749        v1_text: &str,
7750        v2_text: &str,
7751    ) -> (Url, PathBuf) {
7752        let abs = root.join("src/a.bynk");
7753        let uri = Url::from_file_path(abs.canonicalize().unwrap_or(abs)).unwrap();
7754
7755        backend
7756            .did_open(DidOpenTextDocumentParams {
7757                text_document: TextDocumentItem {
7758                    uri: uri.clone(),
7759                    language_id: "bynk".into(),
7760                    version: 1,
7761                    text: v1_text.to_string(),
7762                },
7763            })
7764            .await;
7765        backend.run_round().await;
7766
7767        // The round exists and is version 1.
7768        let a1 = backend.test_analysis().await.expect("round 1");
7769        let rel = Backend::uri_to_rel(&a1, &uri).expect("uri resolves");
7770        assert_eq!(a1.versions.get(&rel), Some(&1), "round 1 is version 1");
7771
7772        // Edit: the buffer becomes `v2_text` at version 2. The debounce this
7773        // schedules is superseded by the request-driven refresh below.
7774        backend
7775            .did_change(DidChangeTextDocumentParams {
7776                text_document: VersionedTextDocumentIdentifier {
7777                    uri: uri.clone(),
7778                    version: 2,
7779                },
7780                content_changes: vec![TextDocumentContentChangeEvent {
7781                    range: None,
7782                    range_length: None,
7783                    text: v2_text.to_string(),
7784                }],
7785            })
7786            .await;
7787        (uri, rel)
7788    }
7789
7790    /// The headline. After an edit that inserts a line above a symbol, a
7791    /// position request at the symbol's *new* location resolves to the symbol —
7792    /// because the gate refreshes to the edited buffer first. Under the old
7793    /// behaviour the new position was resolved against the round-1 snapshot,
7794    /// landing on the wrong text.
7795    #[tokio::test]
7796    async fn a_position_after_an_edit_resolves_against_the_new_text() {
7797        let v1 = "commons q.a\n\nfn target(x: Int) -> Int {\n  x\n}\n";
7798        // Prepend a blank line: `target` moves from line 2 to line 3.
7799        let v2 = format!("\n{v1}");
7800        let s = scratch_project(
7801            "fresh_hd",
7802            &[("bynk.toml", "[project]\nname=\"q\"\n"), ("src/a.bynk", v1)],
7803        );
7804        let backend = backend_at(&s.0).await;
7805        let (uri, rel) = open_round_edit(&backend, &s.0, v1, &v2).await;
7806
7807        // The gate refreshes to the edited version and text.
7808        let a = backend.analysis_for(&uri).await.expect("current analysis");
7809        assert_eq!(a.versions.get(&rel), Some(&2), "gate refreshed to the edit");
7810        assert_eq!(a.snapshots.get(&rel).map(String::as_str), Some(v2.as_str()));
7811
7812        // `target`'s new position resolves to `target` in the refreshed snapshot.
7813        let off_v2 = v2.find("target").unwrap();
7814        let new_pos = crate::position::offset_to_position(&v2, off_v2);
7815        let (a2, rel2, off) = backend
7816            .index_position(&uri, new_pos)
7817            .await
7818            .expect("position resolves");
7819        assert!(
7820            a2.snapshots.get(&rel2).unwrap()[off..].starts_with("target"),
7821            "the new position must land on `target` in the current snapshot — \
7822             the whole point of refreshing",
7823        );
7824    }
7825
7826    /// The gate never returns a round whose snapshot for the file predates the
7827    /// buffer. A cached round at version 1 with the buffer at version 2 must be
7828    /// refreshed, not served.
7829    #[tokio::test]
7830    async fn a_stale_round_is_never_served() {
7831        let v1 = "commons q.a\n\nfn f(x: Int) -> Int {\n  x\n}\n";
7832        let v2 = format!("{v1}\nfn g(y: Int) -> Int {{\n  y\n}}\n");
7833        let s = scratch_project(
7834            "fresh_stale",
7835            &[("bynk.toml", "[project]\nname=\"q\"\n"), ("src/a.bynk", v1)],
7836        );
7837        let backend = backend_at(&s.0).await;
7838        let (uri, rel) = open_round_edit(&backend, &s.0, v1, &v2).await;
7839
7840        // Precondition: the *cached* round is still version 1 (no refresh yet).
7841        let cached = backend.test_analysis().await.unwrap();
7842        assert_eq!(cached.versions.get(&rel), Some(&1), "cached round is stale");
7843
7844        // The gate must not hand back that stale round.
7845        let a = backend.analysis_for(&uri).await.unwrap();
7846        assert_eq!(
7847            a.versions.get(&rel),
7848            Some(&2),
7849            "analysis_for must refresh past a stale cached round, never serve it",
7850        );
7851    }
7852
7853    /// #733: `committed_analysis` is the non-refreshing counterpart of
7854    /// `analysis_for`. Where the strict gate refreshes past a stale round (the
7855    /// test above), this one **serves the committed round as-is** — even with the
7856    /// buffer a version ahead — and never triggers a refresh. That is what lets a
7857    /// decoration request answer from the committed round while the user types,
7858    /// instead of forcing a whole-project round on every keystroke.
7859    #[tokio::test]
7860    async fn committed_analysis_serves_the_stale_round_without_refreshing() {
7861        let v1 = "commons q.a\n\nfn f(x: Int) -> Int {\n  x\n}\n";
7862        let v2 = format!("{v1}\nfn g(y: Int) -> Int {{\n  y\n}}\n");
7863        let s = scratch_project(
7864            "fresh_committed",
7865            &[("bynk.toml", "[project]\nname=\"q\"\n"), ("src/a.bynk", v1)],
7866        );
7867        let backend = backend_at(&s.0).await;
7868        let (uri, rel) = open_round_edit(&backend, &s.0, v1, &v2).await;
7869
7870        // Precondition: the cached round is still version 1 (buffer is at 2).
7871        assert_eq!(
7872            backend.test_analysis().await.unwrap().versions.get(&rel),
7873            Some(&1),
7874            "cached round is stale",
7875        );
7876
7877        // The non-refreshing gate hands back that stale round unchanged...
7878        let a = backend
7879            .committed_analysis(&uri)
7880            .await
7881            .expect("committed round");
7882        assert_eq!(
7883            a.versions.get(&rel),
7884            Some(&1),
7885            "committed_analysis serves the committed round, stale and all",
7886        );
7887        // ...and left the cached round untouched (no refresh was triggered).
7888        assert_eq!(
7889            backend.test_analysis().await.unwrap().versions.get(&rel),
7890            Some(&1),
7891            "committed_analysis must not trigger a refresh",
7892        );
7893    }
7894
7895    /// DECISION B: concurrent requests after one edit coalesce onto a single
7896    /// round, not one each. The refresh lock serialises them; the second finds
7897    /// the first's round already current.
7898    #[tokio::test]
7899    async fn concurrent_requests_after_one_edit_share_one_round() {
7900        let v1 = "commons q.a\n\nfn f(x: Int) -> Int {\n  x\n}\n";
7901        let v2 = format!("\n{v1}");
7902        let s = scratch_project(
7903            "fresh_coal",
7904            &[("bynk.toml", "[project]\nname=\"q\"\n"), ("src/a.bynk", v1)],
7905        );
7906        let backend = backend_at(&s.0).await;
7907        let (uri, _rel) = open_round_edit(&backend, &s.0, v1, &v2).await;
7908
7909        let started_before = backend.test_round_started().await;
7910
7911        // Fire several gate calls concurrently.
7912        let calls = (0..5).map(|_| {
7913            let b = backend.clone();
7914            let u = uri.clone();
7915            tokio::spawn(async move { b.analysis_for(&u).await.is_some() })
7916        });
7917        for c in calls {
7918            assert!(
7919                c.await.unwrap(),
7920                "each concurrent request must get an analysis"
7921            );
7922        }
7923
7924        let started_after = backend.test_round_started().await;
7925        assert_eq!(
7926            started_after - started_before,
7927            1,
7928            "five concurrent requests after one edit must share ONE round, not run five",
7929        );
7930    }
7931
7932    /// DECISION D: a file outside every `include` root cannot be answered at the
7933    /// client's version — the gate declines rather than serving something.
7934    #[tokio::test]
7935    async fn a_file_outside_the_project_is_declined() {
7936        let v1 = "commons q.a\n\nfn f(x: Int) -> Int {\n  x\n}\n";
7937        let s = scratch_project(
7938            "fresh_out",
7939            &[("bynk.toml", "[project]\nname=\"q\"\n"), ("src/a.bynk", v1)],
7940        );
7941        let backend = backend_at(&s.0).await;
7942        // Round the project so a cached analysis exists.
7943        backend.run_round().await;
7944
7945        // A URI for a file the project does not contain, opened as a buffer.
7946        let outside = s.0.join("elsewhere.bynk");
7947        std::fs::write(&outside, v1).unwrap();
7948        let uri = Url::from_file_path(outside.canonicalize().unwrap()).unwrap();
7949        backend
7950            .did_open(DidOpenTextDocumentParams {
7951                text_document: TextDocumentItem {
7952                    uri: uri.clone(),
7953                    language_id: "bynk".into(),
7954                    version: 1,
7955                    text: v1.to_string(),
7956                },
7957            })
7958            .await;
7959
7960        assert!(
7961            backend.analysis_for(&uri).await.is_none(),
7962            "a file outside the include roots is never a snapshot key — decline, \
7963             don't serve a round that doesn't cover it",
7964        );
7965    }
7966
7967    /// Review of #666: rename emits versioned edits across every file that
7968    /// references the symbol, so it must refresh **all** open buffers, not just
7969    /// the cursor's. Edit a non-cursor file that references the symbol, then
7970    /// rename from the (unedited) definition file: the edit for the dirty file
7971    /// must carry its *current* version, or the client rejects the whole rename.
7972    /// Under the per-URI gate the cursor's file was current, so no refresh ran
7973    /// and the dirty file kept its stale version.
7974    #[tokio::test]
7975    async fn a_multi_file_rename_stamps_a_dirty_non_cursor_file_at_its_current_version() {
7976        let util = "commons demo.util\n\ntype Money = Int where Positive\n";
7977        let thing = "commons demo.thing\n\nuses demo.util\n\nfn f(m: Money) -> Money {\n  m\n}\n";
7978        let s = scratch_project(
7979            "rename_multi",
7980            &[
7981                ("bynk.toml", "[project]\nname=\"demo\"\n"),
7982                ("src/demo/util.bynk", util),
7983                ("src/demo/thing.bynk", thing),
7984            ],
7985        );
7986        let backend = backend_at(&s.0).await;
7987        let uri = |rel: &str| {
7988            let abs = s.0.join(rel);
7989            Url::from_file_path(abs.canonicalize().unwrap_or(abs)).unwrap()
7990        };
7991        let util_uri = uri("src/demo/util.bynk");
7992        let thing_uri = uri("src/demo/thing.bynk");
7993
7994        for (u, text) in [(&util_uri, util), (&thing_uri, thing)] {
7995            backend
7996                .did_open(DidOpenTextDocumentParams {
7997                    text_document: TextDocumentItem {
7998                        uri: u.clone(),
7999                        language_id: "bynk".into(),
8000                        version: 1,
8001                        text: text.to_string(),
8002                    },
8003                })
8004                .await;
8005        }
8006        backend.run_round().await;
8007
8008        // Edit the NON-cursor file (`thing`) to version 2 — a blank line above,
8009        // so `Money`'s references shift but still resolve.
8010        let thing_v2 = format!("\n{thing}");
8011        backend
8012            .did_change(DidChangeTextDocumentParams {
8013                text_document: VersionedTextDocumentIdentifier {
8014                    uri: thing_uri.clone(),
8015                    version: 2,
8016                },
8017                content_changes: vec![TextDocumentContentChangeEvent {
8018                    range: None,
8019                    range_length: None,
8020                    text: thing_v2.clone(),
8021                }],
8022            })
8023            .await;
8024
8025        // Rename `Money` from its definition in `util` (untouched, still v1).
8026        let money_off = util.find("Money").unwrap();
8027        let pos = crate::position::offset_to_position(util, money_off);
8028        let edit = backend
8029            .rename(RenameParams {
8030                text_document_position: TextDocumentPositionParams {
8031                    text_document: TextDocumentIdentifier {
8032                        uri: util_uri.clone(),
8033                    },
8034                    position: pos,
8035                },
8036                new_name: "Amount".into(),
8037                work_done_progress_params: Default::default(),
8038            })
8039            .await
8040            .expect("rename must not error")
8041            .expect("rename must produce edits");
8042
8043        let DocumentChanges::Edits(edits) = edit.document_changes.unwrap() else {
8044            panic!("expected document-change edits");
8045        };
8046        let thing_edit = edits
8047            .iter()
8048            .find(|e| e.text_document.uri == thing_uri)
8049            .expect("the rename must edit `thing`, which references the symbol");
8050        assert_eq!(
8051            thing_edit.text_document.version,
8052            Some(2),
8053            "the dirty non-cursor file's edit must carry its current version (2), \
8054             not the stale round's (1) — else the client rejects the whole rename",
8055        );
8056    }
8057
8058    /// #302: renaming a unit's file rewrites its own declaration header
8059    /// **and** every other file's `uses`/`consumes` reference — over a split
8060    /// `src`/`tests` project, exercising the project-relative (`src/`-prefixed)
8061    /// path the `src`/`tests` split leaves on every identity path.
8062    #[tokio::test]
8063    async fn will_rename_files_updates_the_declaration_and_every_reference() {
8064        let charge = "commons billing.charge\n\ntype ChargeId = Int where Positive\n";
8065        let main = "context app.main\n\nuses billing.charge\n";
8066        let s = scratch_project(
8067            "will_rename_basic",
8068            &[
8069                ("bynk.toml", "[project]\nname=\"demo\"\n"),
8070                ("src/billing/charge.bynk", charge),
8071                ("src/app/main.bynk", main),
8072            ],
8073        );
8074        let backend = backend_at(&s.0).await;
8075        let root_canon = s.0.canonicalize().unwrap_or_else(|_| s.0.clone());
8076        let uri = |rel: &str| Url::from_file_path(root_canon.join(rel)).unwrap();
8077        let old_uri = uri("src/billing/charge.bynk");
8078        let new_uri = uri("src/billing/pay.bynk");
8079        let main_uri = uri("src/app/main.bynk");
8080
8081        backend.run_round().await;
8082
8083        let edit = backend
8084            .will_rename_files(RenameFilesParams {
8085                files: vec![FileRename {
8086                    old_uri: old_uri.to_string(),
8087                    new_uri: new_uri.to_string(),
8088                }],
8089            })
8090            .await
8091            .expect("will_rename_files must not error")
8092            .expect("must produce edits");
8093
8094        let DocumentChanges::Edits(edits) = edit.document_changes.unwrap() else {
8095            panic!("expected document-change edits");
8096        };
8097
8098        let own = edits
8099            .iter()
8100            .find(|e| e.text_document.uri == old_uri)
8101            .expect("the moved file's own declaration must be rewritten");
8102        assert_eq!(own.edits.len(), 1);
8103        let OneOf::Left(own_edit) = &own.edits[0] else {
8104            panic!("expected a plain TextEdit");
8105        };
8106        assert_eq!(own_edit.new_text, "billing.pay");
8107
8108        let referencer = edits
8109            .iter()
8110            .find(|e| e.text_document.uri == main_uri)
8111            .expect("the referencing file must be rewritten");
8112        assert_eq!(referencer.edits.len(), 1);
8113        let OneOf::Left(ref_edit) = &referencer.edits[0] else {
8114            panic!("expected a plain TextEdit");
8115        };
8116        assert_eq!(ref_edit.new_text, "billing.pay");
8117    }
8118
8119    /// #302: renaming one member file within a multi-file unit's directory
8120    /// doesn't change the unit's qualified name (it's the directory, not the
8121    /// filename) — no edits are needed.
8122    #[tokio::test]
8123    async fn will_rename_files_is_a_noop_for_a_multi_file_unit_member() {
8124        let s = scratch_project(
8125            "will_rename_multi_file_noop",
8126            &[
8127                ("bynk.toml", "[project]\nname=\"demo\"\n"),
8128                (
8129                    "src/billing/charge/one.bynk",
8130                    "context billing.charge\n\ntype ChargeId = Int where Positive\n",
8131                ),
8132                (
8133                    "src/billing/charge/two.bynk",
8134                    "context billing.charge\n\ntype PaymentId = Int where Positive\n",
8135                ),
8136            ],
8137        );
8138        let backend = backend_at(&s.0).await;
8139        let root_canon = s.0.canonicalize().unwrap_or_else(|_| s.0.clone());
8140        let uri = |rel: &str| Url::from_file_path(root_canon.join(rel)).unwrap();
8141
8142        backend.run_round().await;
8143
8144        let edit = backend
8145            .will_rename_files(RenameFilesParams {
8146                files: vec![FileRename {
8147                    old_uri: uri("src/billing/charge/one.bynk").to_string(),
8148                    new_uri: uri("src/billing/charge/renamed.bynk").to_string(),
8149                }],
8150            })
8151            .await
8152            .expect("will_rename_files must not error");
8153        assert!(
8154            edit.is_none(),
8155            "renaming a member file within the same directory must not edit anything"
8156        );
8157    }
8158
8159    /// #302: a `suite` file has no addressable name of its own
8160    /// (`SourceUnit::name()` is its *target*'s name) — renaming it produces
8161    /// no edits.
8162    #[tokio::test]
8163    async fn will_rename_files_is_a_noop_for_a_suite() {
8164        let s = scratch_project(
8165            "will_rename_suite_noop",
8166            &[
8167                ("bynk.toml", "[project]\nname=\"demo\"\n"),
8168                (
8169                    "src/billing/charge.bynk",
8170                    "commons billing.charge\n\ntype ChargeId = Int where Positive\n",
8171                ),
8172                ("tests/billing_charge.bynk", "suite billing.charge\n"),
8173            ],
8174        );
8175        let backend = backend_at(&s.0).await;
8176        let root_canon = s.0.canonicalize().unwrap_or_else(|_| s.0.clone());
8177        let uri = |rel: &str| Url::from_file_path(root_canon.join(rel)).unwrap();
8178
8179        backend.run_round().await;
8180
8181        let edit = backend
8182            .will_rename_files(RenameFilesParams {
8183                files: vec![FileRename {
8184                    old_uri: uri("tests/billing_charge.bynk").to_string(),
8185                    new_uri: uri("tests/billing_charge_renamed.bynk").to_string(),
8186                }],
8187            })
8188            .await
8189            .expect("will_rename_files must not error");
8190        assert!(edit.is_none(), "a suite rename must produce no edits");
8191    }
8192
8193    /// #302 review: a `suite`'s own `target` is a *reference* too
8194    /// (`unit_reference_spans`' suite branch) — renaming the unit a suite
8195    /// tests must rewrite the suite's `suite <target>` header, not just
8196    /// `uses`/`consumes` clauses in ordinary units.
8197    #[tokio::test]
8198    async fn will_rename_files_updates_a_suite_s_target_reference() {
8199        let s = scratch_project(
8200            "will_rename_suite_target",
8201            &[
8202                ("bynk.toml", "[project]\nname=\"demo\"\n"),
8203                (
8204                    "src/billing/charge.bynk",
8205                    "commons billing.charge\n\ntype ChargeId = Int where Positive\n",
8206                ),
8207                ("tests/billing_charge.bynk", "suite billing.charge\n"),
8208            ],
8209        );
8210        let backend = backend_at(&s.0).await;
8211        let root_canon = s.0.canonicalize().unwrap_or_else(|_| s.0.clone());
8212        let uri = |rel: &str| Url::from_file_path(root_canon.join(rel)).unwrap();
8213        let suite_uri = uri("tests/billing_charge.bynk");
8214
8215        backend.run_round().await;
8216
8217        let edit = backend
8218            .will_rename_files(RenameFilesParams {
8219                files: vec![FileRename {
8220                    old_uri: uri("src/billing/charge.bynk").to_string(),
8221                    new_uri: uri("src/billing/pay.bynk").to_string(),
8222                }],
8223            })
8224            .await
8225            .expect("will_rename_files must not error")
8226            .expect("must produce edits");
8227
8228        let DocumentChanges::Edits(edits) = edit.document_changes.unwrap() else {
8229            panic!("expected document-change edits");
8230        };
8231        let suite_edit = edits
8232            .iter()
8233            .find(|e| e.text_document.uri == suite_uri)
8234            .expect("the suite's own `suite <target>` header must be rewritten");
8235        assert_eq!(suite_edit.edits.len(), 1);
8236        let OneOf::Left(e) = &suite_edit.edits[0] else {
8237            panic!("expected a plain TextEdit");
8238        };
8239        assert_eq!(e.new_text, "billing.pay");
8240    }
8241
8242    /// #302 review: renaming into a path that implies a name some other file
8243    /// already declares must not hand back an edit that would create a
8244    /// duplicate-name project — a lightweight `unit_sources` check, not
8245    /// `rename`'s full re-analysis.
8246    #[tokio::test]
8247    async fn will_rename_files_refuses_a_rename_that_collides_with_an_existing_unit() {
8248        let s = scratch_project(
8249            "will_rename_collision",
8250            &[
8251                ("bynk.toml", "[project]\nname=\"demo\"\n"),
8252                (
8253                    "src/billing/charge.bynk",
8254                    "commons billing.charge\n\ntype ChargeId = Int where Positive\n",
8255                ),
8256                (
8257                    "src/billing/pay.bynk",
8258                    "commons billing.pay\n\ntype PaymentId = Int where Positive\n",
8259                ),
8260            ],
8261        );
8262        let backend = backend_at(&s.0).await;
8263        let root_canon = s.0.canonicalize().unwrap_or_else(|_| s.0.clone());
8264        let uri = |rel: &str| Url::from_file_path(root_canon.join(rel)).unwrap();
8265
8266        backend.run_round().await;
8267
8268        // Renaming `charge.bynk` to `pay.bynk` would imply `billing.pay` —
8269        // already declared by the sibling file.
8270        let edit = backend
8271            .will_rename_files(RenameFilesParams {
8272                files: vec![FileRename {
8273                    old_uri: uri("src/billing/charge.bynk").to_string(),
8274                    new_uri: uri("src/billing/pay.bynk").to_string(),
8275                }],
8276            })
8277            .await
8278            .expect("will_rename_files must not error");
8279        assert!(
8280            edit.is_none(),
8281            "a rename that collides with an existing unit name must produce no edits"
8282        );
8283    }
8284
8285    /// #302 review: `willRenameFiles`' `new_uri` names a file that doesn't
8286    /// exist yet, so `uri_to_rel`'s `canonicalize` fails and previously fell
8287    /// back to the client's raw, non-canonical path — which mismatches
8288    /// `project_root` (always canonical) whenever the workspace root sits
8289    /// behind a symlink, and the handler silently produced no edit.
8290    /// `uri_to_rel_for_new_path` canonicalizes the parent directory (which
8291    /// does exist) instead, so this must still produce edits.
8292    #[cfg(unix)]
8293    #[tokio::test]
8294    async fn will_rename_files_tolerates_a_symlinked_project_root() {
8295        let real = scratch_project(
8296            "will_rename_symlink_real",
8297            &[
8298                ("bynk.toml", "[project]\nname=\"demo\"\n"),
8299                (
8300                    "src/billing/charge.bynk",
8301                    "commons billing.charge\n\ntype ChargeId = Int where Positive\n",
8302                ),
8303            ],
8304        );
8305        let alias = std::env::temp_dir().join(format!(
8306            "bynk_lsp_sliceA_will_rename_symlink_alias_{}_{:?}",
8307            std::process::id(),
8308            std::thread::current().id()
8309        ));
8310        let _ = std::fs::remove_file(&alias);
8311        std::os::unix::fs::symlink(&real.0, &alias).expect("symlink the scratch root");
8312
8313        let backend = backend_at(&alias).await;
8314        // Built through the symlink, deliberately uncanonicalized — the path
8315        // shape a client actually sends (it opened the workspace at `alias`,
8316        // not at whatever `alias` resolves to).
8317        let uri = |rel: &str| Url::from_file_path(alias.join(rel)).unwrap();
8318        let old_uri = uri("src/billing/charge.bynk");
8319        let new_uri = uri("src/billing/pay.bynk"); // does not exist on disk
8320
8321        backend.run_round().await;
8322
8323        let edit = backend
8324            .will_rename_files(RenameFilesParams {
8325                files: vec![FileRename {
8326                    old_uri: old_uri.to_string(),
8327                    new_uri: new_uri.to_string(),
8328                }],
8329            })
8330            .await
8331            .expect("will_rename_files must not error")
8332            .expect("must produce edits despite the symlinked root");
8333
8334        let DocumentChanges::Edits(edits) = edit.document_changes.unwrap() else {
8335            panic!("expected document-change edits");
8336        };
8337        assert_eq!(
8338            edits.len(),
8339            1,
8340            "only the moved file's own header changes here"
8341        );
8342        let OneOf::Left(e) = &edits[0].edits[0] else {
8343            panic!("expected a plain TextEdit");
8344        };
8345        assert_eq!(e.new_text, "billing.pay");
8346
8347        let _ = std::fs::remove_file(&alias);
8348    }
8349
8350    /// #2105: run `willRenameFiles` over `renames` (project-relative old →
8351    /// new paths) against a fresh round of `files`, and flatten the result to
8352    /// `project-relative file → sorted new texts`. `None` when no edit comes
8353    /// back. Also asserts that no file's edits overlap, the failure mode of a
8354    /// multi-file unit or a file-plus-folder request emitting an edit twice.
8355    async fn folder_rename(
8356        tag: &str,
8357        files: &[(&str, &str)],
8358        renames: &[(&str, &str)],
8359    ) -> Option<std::collections::BTreeMap<String, Vec<String>>> {
8360        let s = scratch_project(tag, files);
8361        let backend = backend_at(&s.0).await;
8362        let root_canon = s.0.canonicalize().unwrap_or_else(|_| s.0.clone());
8363        // Joined component by component, so a `/`-separated fixture path is a
8364        // real path on Windows too (a `\\?\` canonical root does not split on
8365        // `/`).
8366        let uri = |rel: &str| {
8367            Url::from_file_path(root_canon.join(rel.split('/').collect::<PathBuf>())).unwrap()
8368        };
8369        // An edited document's URI maps back to its fixture path by comparing
8370        // file paths after a `Url` round trip on both sides, which normalises
8371        // the platform's spelling (drive letter, verbatim prefix, separators).
8372        let fixture_of = |edited: &Url| -> String {
8373            let edited = edited.to_file_path().unwrap();
8374            files
8375                .iter()
8376                .map(|(rel, _)| *rel)
8377                .find(|rel| uri(rel).to_file_path().ok().as_ref() == Some(&edited))
8378                .unwrap_or_else(|| panic!("edit to a non-fixture file {}", edited.display()))
8379                .to_string()
8380        };
8381        backend.run_round().await;
8382        let edit = backend
8383            .will_rename_files(RenameFilesParams {
8384                files: renames
8385                    .iter()
8386                    .map(|(old, new)| FileRename {
8387                        old_uri: uri(old).to_string(),
8388                        new_uri: uri(new).to_string(),
8389                    })
8390                    .collect(),
8391            })
8392            .await
8393            .expect("will_rename_files must not error")?;
8394        let DocumentChanges::Edits(edits) = edit.document_changes.unwrap() else {
8395            panic!("expected document-change edits");
8396        };
8397        let mut out = std::collections::BTreeMap::new();
8398        for doc in edits {
8399            let rel = fixture_of(&doc.text_document.uri);
8400            let mut ranges: Vec<Range> = Vec::new();
8401            let mut texts = Vec::new();
8402            for e in doc.edits {
8403                let OneOf::Left(e) = e else {
8404                    panic!("expected a plain TextEdit");
8405                };
8406                assert!(
8407                    !ranges
8408                        .iter()
8409                        .any(|r| r.start <= e.range.end && e.range.start <= r.end),
8410                    "overlapping edits in {rel}: {:?} and {ranges:?}",
8411                    e.range
8412                );
8413                ranges.push(e.range);
8414                texts.push(e.new_text);
8415            }
8416            texts.sort();
8417            assert!(
8418                out.insert(rel.clone(), texts).is_none(),
8419                "{rel} edited twice"
8420            );
8421        }
8422        Some(out)
8423    }
8424
8425    fn expect_edits(pairs: &[(&str, &[&str])]) -> std::collections::BTreeMap<String, Vec<String>> {
8426        pairs
8427            .iter()
8428            .map(|(f, texts)| (f.to_string(), texts.iter().map(|t| t.to_string()).collect()))
8429            .collect()
8430    }
8431
8432    /// The project the folder-rename tests share: two units in `billing/`, one
8433    /// referencing the other, and a context outside referencing both.
8434    const BILLING: &[(&str, &str)] = &[
8435        ("bynk.toml", "[project]\nname=\"demo\"\n"),
8436        (
8437            "src/billing/charge.bynk",
8438            "commons billing.charge\n\ntype ChargeId = Int where Positive\n",
8439        ),
8440        (
8441            "src/billing/refund.bynk",
8442            "commons billing.refund\n\nuses billing.charge\n\ntype RefundId = Int where Positive\n",
8443        ),
8444        (
8445            "src/app/main.bynk",
8446            "context app.main\n\nuses billing.charge\nuses billing.refund\n",
8447        ),
8448    ];
8449
8450    /// #2105: renaming a folder renames every unit in it and rewrites every
8451    /// reference to them, including one between two units inside the folder.
8452    #[tokio::test]
8453    async fn will_rename_files_renames_a_folder_of_units() {
8454        let edits = folder_rename(
8455            "will_rename_folder",
8456            BILLING,
8457            &[("src/billing", "src/payments")],
8458        )
8459        .await
8460        .expect("a folder rename must produce edits");
8461        assert_eq!(
8462            edits,
8463            expect_edits(&[
8464                ("src/app/main.bynk", &["payments.charge", "payments.refund"]),
8465                ("src/billing/charge.bynk", &["payments.charge"]),
8466                (
8467                    "src/billing/refund.bynk",
8468                    &["payments.charge", "payments.refund"]
8469                ),
8470            ])
8471        );
8472    }
8473
8474    /// #2105: moving a folder under a different parent prefixes every unit
8475    /// in it, nested folders included.
8476    #[tokio::test]
8477    async fn will_rename_files_moves_a_folder_with_nested_units() {
8478        let mut files = BILLING.to_vec();
8479        files.push((
8480            "src/billing/core/ledger.bynk",
8481            "commons billing.core.ledger\n\ntype Entry = Int where Positive\n",
8482        ));
8483        files.push((
8484            "src/app/books.bynk",
8485            "context app.books\n\nuses billing.core.ledger\n",
8486        ));
8487        files.push((
8488            "src/finance/tax.bynk",
8489            "commons finance.tax\n\ntype Rate = Int where Positive\n",
8490        ));
8491        let edits = folder_rename(
8492            "will_rename_folder_move",
8493            &files,
8494            &[("src/billing", "src/finance/billing")],
8495        )
8496        .await
8497        .expect("a folder move must produce edits");
8498        assert_eq!(
8499            edits,
8500            expect_edits(&[
8501                ("src/app/books.bynk", &["finance.billing.core.ledger"]),
8502                (
8503                    "src/app/main.bynk",
8504                    &["finance.billing.charge", "finance.billing.refund"]
8505                ),
8506                ("src/billing/charge.bynk", &["finance.billing.charge"]),
8507                (
8508                    "src/billing/core/ledger.bynk",
8509                    &["finance.billing.core.ledger"]
8510                ),
8511                (
8512                    "src/billing/refund.bynk",
8513                    &["finance.billing.charge", "finance.billing.refund"]
8514                ),
8515            ])
8516        );
8517    }
8518
8519    /// #2105: renaming a nested folder renames only the units under it; a
8520    /// sibling folder sharing its name as a prefix (`core` vs `corex`) is not
8521    /// "under" it.
8522    #[tokio::test]
8523    async fn will_rename_files_renames_only_the_nested_folder() {
8524        let edits = folder_rename(
8525            "will_rename_folder_nested",
8526            &[
8527                ("bynk.toml", "[project]\nname=\"demo\"\n"),
8528                (
8529                    "src/billing/core/ledger.bynk",
8530                    "commons billing.core.ledger\n",
8531                ),
8532                (
8533                    "src/billing/corex/extra.bynk",
8534                    "commons billing.corex.extra\n",
8535                ),
8536                (
8537                    "src/app/main.bynk",
8538                    "context app.main\n\nuses billing.core.ledger\nuses billing.corex.extra\n",
8539                ),
8540            ],
8541            &[("src/billing/core", "src/billing/base")],
8542        )
8543        .await
8544        .expect("a nested folder rename must produce edits");
8545        assert_eq!(
8546            edits,
8547            expect_edits(&[
8548                ("src/app/main.bynk", &["billing.base.ledger"]),
8549                ("src/billing/core/ledger.bynk", &["billing.base.ledger"]),
8550            ])
8551        );
8552    }
8553
8554    /// #2105: a folder that *is* a multi-file unit renames the unit: every
8555    /// member's header changes, and each reference is rewritten exactly once
8556    /// (`folder_rename` fails on an overlapping or duplicated edit).
8557    #[tokio::test]
8558    async fn will_rename_files_renames_a_multi_file_unit_folder_once() {
8559        let edits = folder_rename(
8560            "will_rename_folder_multi_file",
8561            &[
8562                ("bynk.toml", "[project]\nname=\"demo\"\n"),
8563                (
8564                    "src/billing/charge/one.bynk",
8565                    "context billing.charge\n\ntype ChargeId = Int where Positive\n",
8566                ),
8567                (
8568                    "src/billing/charge/two.bynk",
8569                    "context billing.charge\n\ntype PaymentId = Int where Positive\n",
8570                ),
8571                (
8572                    "src/app/main.bynk",
8573                    "context app.main\n\nconsumes billing.charge\n",
8574                ),
8575            ],
8576            &[("src/billing/charge", "src/billing/payment")],
8577        )
8578        .await
8579        .expect("a multi-file unit folder rename must produce edits");
8580        assert_eq!(
8581            edits,
8582            expect_edits(&[
8583                ("src/app/main.bynk", &["billing.payment"]),
8584                ("src/billing/charge/one.bynk", &["billing.payment"]),
8585                ("src/billing/charge/two.bynk", &["billing.payment"]),
8586            ])
8587        );
8588    }
8589
8590    /// #2105: a folder holding no `.bynk` file produces no edit.
8591    #[tokio::test]
8592    async fn will_rename_files_is_a_noop_for_a_folder_without_units() {
8593        let mut files = BILLING.to_vec();
8594        files.push(("src/assets/logo.txt", "not bynk\n"));
8595        let edits = folder_rename(
8596            "will_rename_folder_empty",
8597            &files,
8598            &[("src/assets", "src/static")],
8599        )
8600        .await;
8601        assert!(edits.is_none(), "{edits:?}");
8602    }
8603
8604    /// #2105: a request naming a file and also its enclosing folder (both
8605    /// moving the same way) edits each file once, like the folder alone.
8606    #[tokio::test]
8607    async fn will_rename_files_deduplicates_a_file_inside_a_renamed_folder() {
8608        let edits = folder_rename(
8609            "will_rename_folder_mixed",
8610            BILLING,
8611            &[
8612                ("src/billing/charge.bynk", "src/payments/charge.bynk"),
8613                ("src/billing", "src/payments"),
8614            ],
8615        )
8616        .await
8617        .expect("a mixed rename must produce edits");
8618        assert_eq!(
8619            edits,
8620            expect_edits(&[
8621                ("src/app/main.bynk", &["payments.charge", "payments.refund"]),
8622                ("src/billing/charge.bynk", &["payments.charge"]),
8623                (
8624                    "src/billing/refund.bynk",
8625                    &["payments.charge", "payments.refund"]
8626                ),
8627            ])
8628        );
8629    }
8630
8631    /// #2105 (DECISION B): moving a folder into another project (here a
8632    /// nested `bynk.toml`, which the old `strip_prefix` check let through)
8633    /// produces no edit.
8634    #[tokio::test]
8635    async fn will_rename_files_refuses_a_move_into_another_project() {
8636        let mut files = BILLING.to_vec();
8637        files.push(("vendor/bynk.toml", "[project]\nname=\"vendor\"\n"));
8638        files.push(("vendor/src/keep.bynk", "commons keep\n"));
8639        let folder = folder_rename(
8640            "will_rename_folder_cross_project",
8641            &files,
8642            &[("src/billing", "vendor/src/billing")],
8643        )
8644        .await;
8645        assert!(folder.is_none(), "{folder:?}");
8646        let file = folder_rename(
8647            "will_rename_file_cross_project",
8648            &files,
8649            &[("src/billing/charge.bynk", "vendor/src/charge.bynk")],
8650        )
8651        .await;
8652        assert!(file.is_none(), "{file:?}");
8653    }
8654
8655    /// #485: a rootless multi-file-commons file (a `src/` tree with no
8656    /// `bynk.toml`, the layout the compiler fixtures use) resolves its
8657    /// implicit source root — the nearest ancestor `src/` — so project-mode
8658    /// analysis kicks in instead of sibling-blind single-file `diagnose`.
8659    #[test]
8660    fn find_source_root_walks_up_to_the_nearest_src() {
8661        let ws = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
8662            .parent()
8663            .expect("workspace root");
8664        let make = ws.join(
8665            "bynk-tests/tests/fixtures/positive/\
8666             252_multi_file_commons_dotted_test/src/shipping/rates/make.bynk",
8667        );
8668        assert!(make.is_file(), "fixture present: {}", make.display());
8669
8670        let src = Backend::find_source_root(&make).expect("an ancestor src/");
8671        assert!(
8672            src.ends_with("252_multi_file_commons_dotted_test/src"),
8673            "nearest ancestor src, got {}",
8674            src.display()
8675        );
8676
8677        // No `bynk.toml` on the path, so resolution falls back to the implicit
8678        // src tree, and the project root is `src`'s parent.
8679        //
8680        // Slice A: the old invariant here was `root.join(config.src_dir) == src`
8681        // — the analysis root re-derived by reducing the manifest to one
8682        // directory. That reduction is gone: the round is rooted at the project
8683        // and `bynk_ide::AnalysisRoots::Project` resolves the trees from the
8684        // manifest (here, absent → `ProjectPaths::conventional`, which picks up
8685        // exactly this `src/`). So what must hold is that the root is `src`'s
8686        // parent, and that conventional discovery finds this file from it.
8687        let (root, _config) = Backend::resolve_root(&make).expect("implicit project");
8688        assert_eq!(root, src.parent().expect("src has a parent"));
8689
8690        // No `bynk.toml` in this fixture (the test is exactly about the
8691        // absent-manifest → conventional-layout path), so an empty overlay
8692        // is correct here, not a stand-in for a real manifest read.
8693        let found = bynk_ide::discover_files(
8694            &bynk_ide::AnalysisRoots::Project(root.clone()),
8695            &std::collections::HashMap::new(),
8696        );
8697        let make_canon = make.canonicalize().unwrap_or(make.clone());
8698        assert!(
8699            found
8700                .iter()
8701                .any(|p| p.canonicalize().unwrap_or_else(|_| p.clone()) == make_canon),
8702            "the compiler's own discovery must reach {} from the project root {}; got {found:?}",
8703            make.display(),
8704            root.display(),
8705        );
8706    }
8707
8708    /// A file with no `bynk.toml` and no ancestor `src/` stays in single-file
8709    /// mode — resolution returns `None`, so the caller keeps the per-buffer
8710    /// `diagnose` path.
8711    #[test]
8712    fn resolve_root_is_none_without_toml_or_src() {
8713        // The crate manifest sits under `bynk-lsp/`, not inside any `src/`.
8714        let p = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("Cargo.toml");
8715        assert!(p.is_file());
8716        assert!(Backend::find_source_root(&p).is_none());
8717        assert!(Backend::resolve_root(&p).is_none());
8718    }
8719
8720    // v0.124 (slice 3): the `<expr> is <cursor>` scrutinee-offset detection that
8721    // feeds `is`-pattern completion.
8722    #[test]
8723    fn is_scrutinee_offset_locates_the_scrutinee() {
8724        let text = "  order.status is Pen";
8725        let off = is_scrutinee_offset(text, text.len()).expect("at an is-position");
8726        // Lands on the last char of `order.status` (the `s` of `status`).
8727        assert_eq!(&text[off..off + 1], "s");
8728        assert!(off < text.find(" is ").unwrap());
8729        // No trailing partial, cursor right after `is `.
8730        let text2 = "  x is ";
8731        let off2 = is_scrutinee_offset(text2, text2.len()).expect("at an is-position");
8732        assert_eq!(&text2[off2..off2 + 1], "x");
8733        // `basis` is not a standalone `is`.
8734        assert!(is_scrutinee_offset("  basis ", "  basis ".len()).is_none());
8735        // Not an is-position at all.
8736        assert!(is_scrutinee_offset("  let x = ", "  let x = ".len()).is_none());
8737    }
8738
8739    // v0.128: the `match <expr> { <arm-start>` scrutinee-offset detection that
8740    // feeds match-arm variant completion.
8741    #[test]
8742    fn let_else_match_head_reads_the_value_and_the_covered_variant() {
8743        // #2010: the first arm, right after the brace.
8744        let t = "  let Ok(n) = load(r) else match {\n    ";
8745        let h = let_else_match_head(t, t.len()).expect("at an arm-start");
8746        assert_eq!(&t[h.value_end..h.value_end + 1], ")"); // last char of `load(r)`
8747        assert!(!h.effectful);
8748        assert_eq!(h.covered.as_deref(), Some("Ok"));
8749
8750        // `<-`, a later arm, a partial pattern typed.
8751        let t = "let Some(x) <- find(k) else match {\n  None => 0,\n  Er";
8752        let h = let_else_match_head(t, t.len()).expect("at a later arm-start");
8753        assert!(h.effectful);
8754        assert_eq!(&t[h.value_end..h.value_end + 1], ")");
8755        assert_eq!(h.covered.as_deref(), Some("Some"));
8756
8757        // A pattern that covers only part of a variant leaves it offerable.
8758        let t = "let Err(Missing) = r else match {\n  ";
8759        assert_eq!(let_else_match_head(t, t.len()).unwrap().covered, None);
8760
8761        // A qualified nullary variant is covered whole.
8762        let t = "let Status.Done = s else match {\n  ";
8763        assert_eq!(
8764            let_else_match_head(t, t.len()).unwrap().covered.as_deref(),
8765            Some("Done")
8766        );
8767
8768        // An `==` in the value is not the binding `=`.
8769        let t = "let Ok(b) = check(a == 1) else match {\n  ";
8770        let h = let_else_match_head(t, t.len()).unwrap();
8771        assert_eq!(&t[h.value_end..h.value_end + 1], ")");
8772
8773        // Not a let-else: a plain `match`, or an arm body.
8774        assert!(let_else_match_head("match c {\n  ", 11).is_none());
8775        let t = "let Ok(n) = r else match {\n  Err(e) => ";
8776        assert!(let_else_match_head(t, t.len()).is_none());
8777    }
8778
8779    #[test]
8780    fn match_scrutinee_offset_locates_the_scrutinee() {
8781        // First arm, cursor right after the opening brace.
8782        let t = "match order.status {\n  ";
8783        let off = match_scrutinee_offset(t, t.len()).expect("at an arm-start");
8784        assert_eq!(&t[off..off + 1], "s"); // last char of `order.status`
8785        assert!(off < t.find(" {").unwrap());
8786
8787        // First arm with a partial pattern typed.
8788        let t = "match color { Re";
8789        let off = match_scrutinee_offset(t, t.len()).expect("at an arm-start");
8790        assert_eq!(&t[off..off + 1], "r"); // last char of `color`
8791
8792        // A later arm after a top-level comma, mid-partial.
8793        let t = "match c {\n  Red => 1,\n  Gr";
8794        let off = match_scrutinee_offset(t, t.len()).expect("at a later arm-start");
8795        assert_eq!(&t[off..off + 1], "c");
8796
8797        // A top-level comma inside a preceding arm body does not confuse the
8798        // header (the nested call's comma is at depth > 0).
8799        let t = "match c {\n  Red => f(a, b),\n  ";
8800        assert!(match_scrutinee_offset(t, t.len()).is_some());
8801
8802        // Inside an arm *body* (after `=>`) — not a pattern position.
8803        assert!(
8804            match_scrutinee_offset("match c {\n  Red => ", "match c {\n  Red => ".len()).is_none()
8805        );
8806
8807        // A non-`match` block offers nothing.
8808        assert!(match_scrutinee_offset("fn f() {\n  ", "fn f() {\n  ".len()).is_none());
8809
8810        // A nested constructor position (`Ok(<cursor>`) is not an arm-start.
8811        assert!(match_scrutinee_offset("match c {\n  Ok(", "match c {\n  Ok(".len()).is_none());
8812
8813        // No open brace / no scrutinee → nothing.
8814        assert!(match_scrutinee_offset("match c ", "match c ".len()).is_none());
8815        assert!(match_scrutinee_offset("match {\n  ", "match {\n  ".len()).is_none());
8816    }
8817
8818    // v0.145 (ADR 0169): the `match <expr> { … Variant(<partial>` nested-pattern
8819    // detection that feeds payload-variant completion — the position
8820    // `match_scrutinee_offset` deliberately bails on.
8821    #[test]
8822    fn nested_pattern_offset_locates_the_scrutinee_and_variant() {
8823        // Cursor right inside a variant's payload parens.
8824        let t = "match res {\n  Some(";
8825        let (off, variant) = nested_pattern_offset(t, t.len()).expect("inside a nested pattern");
8826        assert_eq!(&t[off..off + 1], "s"); // last char of `res`
8827        assert_eq!(variant, "Some");
8828
8829        // With a partial nested pattern typed, and a qualifier.
8830        let t = "match res {\n  Ok(Po";
8831        let (off, variant) = nested_pattern_offset(t, t.len()).expect("mid partial");
8832        assert_eq!(&t[off..off + 1], "s");
8833        assert_eq!(variant, "Ok");
8834
8835        // A later arm after a top-level comma.
8836        let t = "match r {\n  Ok(n) => n,\n  Err(";
8837        let (off, variant) = nested_pattern_offset(t, t.len()).expect("later arm");
8838        assert_eq!(&t[off..off + 1], "r");
8839        assert_eq!(variant, "Err");
8840
8841        // A lowercase-led token before `(` is a binding/call, not a variant
8842        // constructor — no nested completion (there is no inner type to open).
8843        assert!(nested_pattern_offset("match r {\n  ok(", "match r {\n  ok(".len()).is_none());
8844
8845        // An arm-start (no open paren) is the flat position, not a nested one.
8846        assert!(nested_pattern_offset("match c {\n  ", "match c {\n  ".len()).is_none());
8847        assert!(nested_pattern_offset("match c {\n  Ok", "match c {\n  Ok".len()).is_none());
8848
8849        // Inside an arm body (after `=>`) is not a pattern position.
8850        let t = "match c {\n  Ok(n) => g(";
8851        assert!(nested_pattern_offset(t, t.len()).is_none());
8852
8853        // A non-`match` block offers nothing.
8854        assert!(nested_pattern_offset("fn f() {\n  h(", "fn f() {\n  h(".len()).is_none());
8855    }
8856
8857    /// A watched-file change on `bynk.toml` is recognised (so the config can be
8858    /// reloaded live), while a sibling `.bynk` file or a merely `…bynk.toml`-
8859    /// suffixed name is not — the name-component match, not a path suffix.
8860    #[test]
8861    fn is_bynk_toml_matches_only_the_manifest() {
8862        // Build URIs from a host-absolute base so `from_file_path` succeeds on
8863        // Windows too (a Unix-style `/proj` path is not absolute there — no
8864        // drive letter — and would fail to convert). Mirrors the sibling
8865        // `find_source_root` test's `CARGO_MANIFEST_DIR` base.
8866        let base = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
8867        let toml = Url::from_file_path(base.join("bynk.toml")).expect("abs path");
8868        assert!(is_bynk_toml(&toml));
8869        let nested = Url::from_file_path(base.join("sub").join("bynk.toml")).expect("abs path");
8870        assert!(is_bynk_toml(&nested));
8871
8872        // A source file is not the manifest.
8873        let src = Url::from_file_path(base.join("src").join("main.bynk")).expect("abs path");
8874        assert!(!is_bynk_toml(&src));
8875        // A file whose name merely *ends with* `bynk.toml` must not fire.
8876        let decoy = Url::from_file_path(base.join("notbynk.toml")).expect("abs path");
8877        assert!(!is_bynk_toml(&decoy));
8878        // A non-file URI never matches.
8879        let remote = Url::parse("https://example.com/bynk.toml").expect("url");
8880        assert!(!is_bynk_toml(&remote));
8881    }
8882
8883    /// #2100 slice 5: the organise-imports source action is computed only
8884    /// when the client asks for its kind (directly, or via its `source`
8885    /// parent), never for an unfiltered lightbulb request or another kind —
8886    /// and when it is, its edit is the re-checked organise.
8887    #[tokio::test]
8888    async fn organise_imports_is_offered_only_when_asked_for() {
8889        let other = "commons shared.other\n\ntype Other = { n: Int }\n";
8890        let widget = "commons shared.widget\n\ntype Widget = { size: Int }\n";
8891        let app = "commons app.a\n\nuses shared.widget\nuses shared.other\n\nfn area(w: Widget) -> Int {\n  w.size\n}\n";
8892        let s = scratch_project(
8893            "organise_only",
8894            &[
8895                ("bynk.toml", "[project]\nname=\"demo\"\n"),
8896                ("src/shared/other.bynk", other),
8897                ("src/shared/widget.bynk", widget),
8898                ("src/app/a.bynk", app),
8899            ],
8900        );
8901        let backend = backend_at(&s.0).await;
8902        let uri = file_uri(&s.0, "src/app/a.bynk");
8903        open(&backend, &uri, app).await;
8904        backend.run_round().await;
8905
8906        let request = |only: Option<Vec<CodeActionKind>>| CodeActionParams {
8907            text_document: TextDocumentIdentifier { uri: uri.clone() },
8908            range: Range::default(),
8909            context: CodeActionContext {
8910                diagnostics: Vec::new(),
8911                only,
8912                trigger_kind: None,
8913            },
8914            work_done_progress_params: Default::default(),
8915            partial_result_params: Default::default(),
8916        };
8917        let organise_titles = |actions: Vec<CodeActionOrCommand>| -> Vec<String> {
8918            actions
8919                .into_iter()
8920                .filter_map(|a| match a {
8921                    CodeActionOrCommand::CodeAction(a)
8922                        if a.kind == Some(CodeActionKind::SOURCE_ORGANIZE_IMPORTS) =>
8923                    {
8924                        Some(a.title)
8925                    }
8926                    _ => None,
8927                })
8928                .collect()
8929        };
8930
8931        for only in [None, Some(vec![CodeActionKind::QUICKFIX])] {
8932            let actions = backend
8933                .code_action(request(only.clone()))
8934                .await
8935                .unwrap()
8936                .unwrap();
8937            assert!(organise_titles(actions).is_empty(), "offered for {only:?}");
8938        }
8939        for only in [
8940            CodeActionKind::SOURCE,
8941            CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
8942        ] {
8943            let actions = backend
8944                .code_action(request(Some(vec![only.clone()])))
8945                .await
8946                .unwrap()
8947                .unwrap();
8948            assert_eq!(actions.len(), 1, "one action for {only:?}");
8949            let CodeActionOrCommand::CodeAction(action) = &actions[0] else {
8950                panic!("expected a CodeAction");
8951            };
8952            assert_eq!(action.kind, Some(CodeActionKind::SOURCE_ORGANIZE_IMPORTS));
8953            let Some(DocumentChanges::Edits(doc_edits)) =
8954                &action.edit.as_ref().unwrap().document_changes
8955            else {
8956                panic!("expected versioned document edits");
8957            };
8958            assert_eq!(doc_edits[0].text_document.version, Some(1));
8959            let OneOf::Left(edit) = &doc_edits[0].edits[0] else {
8960                panic!("expected a plain TextEdit");
8961            };
8962            // `shared.other` is unused: the header keeps only `shared.widget`.
8963            assert_eq!(edit.new_text, "uses shared.widget");
8964        }
8965    }
8966
8967    /// #2100 slice 6: fix-all is computed only when asked for (`source`,
8968    /// the generic `source.fixAll` VS Code sends on save, or its own
8969    /// `source.fixAll.bynk`), and carries every machine-applicable fix.
8970    #[tokio::test]
8971    async fn fix_all_is_offered_only_when_asked_for() {
8972        let src = "context app.c\n\ncapability Clock {\n  fn now() -> Effect[Int]\n}\n\nprovides Clock = Sys {\n  fn now() -> Effect[Int] {\n    1\n  }\n}\n\nservice one {\n  on call(x: Int) -> Effect[Int] by Caller given Clock {\n    x\n  }\n}\n\nservice two {\n  on call(x: Int) -> Effect[Int] by Caller given Clock {\n    x\n  }\n}\n";
8973        let s = scratch_project(
8974            "fix_all_only",
8975            &[
8976                ("bynk.toml", "[project]\nname=\"demo\"\n"),
8977                ("src/app/c.bynk", src),
8978            ],
8979        );
8980        let backend = backend_at(&s.0).await;
8981        let uri = file_uri(&s.0, "src/app/c.bynk");
8982        open(&backend, &uri, src).await;
8983        backend.run_round().await;
8984
8985        let request = |only: Option<Vec<CodeActionKind>>| CodeActionParams {
8986            text_document: TextDocumentIdentifier { uri: uri.clone() },
8987            range: Range::default(),
8988            context: CodeActionContext {
8989                diagnostics: Vec::new(),
8990                only,
8991                trigger_kind: None,
8992            },
8993            work_done_progress_params: Default::default(),
8994            partial_result_params: Default::default(),
8995        };
8996        let fix_all = |actions: Vec<CodeActionOrCommand>| -> Vec<CodeAction> {
8997            actions
8998                .into_iter()
8999                .filter_map(|a| match a {
9000                    CodeActionOrCommand::CodeAction(a)
9001                        if a.kind == Some(crate::fix_all::kind()) =>
9002                    {
9003                        Some(a)
9004                    }
9005                    _ => None,
9006                })
9007                .collect()
9008        };
9009        for only in [None, Some(vec![CodeActionKind::QUICKFIX])] {
9010            let actions = backend
9011                .code_action(request(only.clone()))
9012                .await
9013                .unwrap()
9014                .unwrap();
9015            assert!(fix_all(actions).is_empty(), "offered for {only:?}");
9016        }
9017        for only in [
9018            CodeActionKind::SOURCE,
9019            CodeActionKind::SOURCE_FIX_ALL,
9020            crate::fix_all::kind(),
9021        ] {
9022            let actions = backend
9023                .code_action(request(Some(vec![only.clone()])))
9024                .await
9025                .unwrap()
9026                .unwrap();
9027            let found = fix_all(actions);
9028            assert_eq!(found.len(), 1, "one fix-all for {only:?}");
9029            let Some(DocumentChanges::Edits(doc_edits)) =
9030                &found[0].edit.as_ref().unwrap().document_changes
9031            else {
9032                panic!("expected versioned document edits");
9033            };
9034            // Both handlers' unused `given Clock` go in the one action.
9035            assert_eq!(doc_edits[0].edits.len(), 2);
9036        }
9037    }
9038
9039    /// #2100 slice 3: fill-match-arms is listed on the unfiltered lightbulb
9040    /// request without an edit, and `codeAction/resolve` fills in the
9041    /// re-checked, versioned edit. A resolve for a stale version is refused.
9042    #[tokio::test]
9043    async fn fill_match_arms_lists_then_resolves() {
9044        let src = "commons app.m\n\ntype Shape =\n  | Circle(r: Int)\n  | Dot\n\nfn area(s: Shape) -> Int {\n  match s {\n    Dot => 1,\n  }\n}\n";
9045        let s = scratch_project(
9046            "fill_arms",
9047            &[
9048                ("bynk.toml", "[project]\nname=\"demo\"\n"),
9049                ("src/app/m.bynk", src),
9050            ],
9051        );
9052        let backend = backend_at(&s.0).await;
9053        let uri = file_uri(&s.0, "src/app/m.bynk");
9054        open(&backend, &uri, src).await;
9055        backend.run_round().await;
9056
9057        let at = crate::position::offset_to_position(src, src.find("Dot =>").unwrap());
9058        let actions = backend
9059            .code_action(CodeActionParams {
9060                text_document: TextDocumentIdentifier { uri: uri.clone() },
9061                range: Range { start: at, end: at },
9062                context: CodeActionContext::default(),
9063                work_done_progress_params: Default::default(),
9064                partial_result_params: Default::default(),
9065            })
9066            .await
9067            .unwrap()
9068            .unwrap();
9069        let listed: Vec<CodeAction> = actions
9070            .into_iter()
9071            .filter_map(|a| match a {
9072                CodeActionOrCommand::CodeAction(a) if a.title.starts_with("Fill") => Some(a),
9073                _ => None,
9074            })
9075            .collect();
9076        assert_eq!(listed.len(), 1, "one fill action");
9077        assert!(listed[0].edit.is_none(), "listed without its edit");
9078
9079        let resolved = backend
9080            .code_action_resolve(listed[0].clone())
9081            .await
9082            .unwrap();
9083        let Some(DocumentChanges::Edits(doc_edits)) =
9084            &resolved.edit.as_ref().unwrap().document_changes
9085        else {
9086            panic!("expected versioned document edits");
9087        };
9088        assert_eq!(doc_edits[0].text_document.version, Some(1));
9089        let inserted: String = doc_edits[0]
9090            .edits
9091            .iter()
9092            .map(|e| match e {
9093                OneOf::Left(e) => e.new_text.clone(),
9094                OneOf::Right(e) => e.text_edit.new_text.clone(),
9095            })
9096            .collect();
9097        assert_eq!(inserted, "\n    Circle(_) => 0,");
9098
9099        let mut stale = listed[0].clone();
9100        stale.data.as_mut().unwrap()["version"] = serde_json::json!(0);
9101        assert!(backend.code_action_resolve(stale).await.is_err());
9102
9103        // Any other action resolves to itself.
9104        let other = CodeAction {
9105            title: "x".into(),
9106            ..Default::default()
9107        };
9108        assert_eq!(
9109            backend.code_action_resolve(other.clone()).await.unwrap(),
9110            other
9111        );
9112    }
9113
9114    /// #2100 slice 1: inline-variable is listed on the unfiltered lightbulb
9115    /// request at a `let`'s name without an edit, and `codeAction/resolve`
9116    /// fills in the re-checked, versioned edit.
9117    #[tokio::test]
9118    async fn inline_variable_lists_then_resolves() {
9119        let src = "commons app.m\n\nfn f(a: Int) -> Int {\n  let y = a + 1\n  y * 3\n}\n";
9120        let s = scratch_project(
9121            "inline_var",
9122            &[
9123                ("bynk.toml", "[project]\nname=\"demo\"\n"),
9124                ("src/app/m.bynk", src),
9125            ],
9126        );
9127        let backend = backend_at(&s.0).await;
9128        let uri = file_uri(&s.0, "src/app/m.bynk");
9129        open(&backend, &uri, src).await;
9130        backend.run_round().await;
9131
9132        let at = crate::position::offset_to_position(src, src.find("y =").unwrap());
9133        let actions = backend
9134            .code_action(CodeActionParams {
9135                text_document: TextDocumentIdentifier { uri: uri.clone() },
9136                range: Range { start: at, end: at },
9137                context: CodeActionContext::default(),
9138                work_done_progress_params: Default::default(),
9139                partial_result_params: Default::default(),
9140            })
9141            .await
9142            .unwrap()
9143            .unwrap();
9144        let listed: Vec<CodeAction> = actions
9145            .into_iter()
9146            .filter_map(|a| match a {
9147                CodeActionOrCommand::CodeAction(a)
9148                    if a.kind == Some(CodeActionKind::REFACTOR_INLINE) =>
9149                {
9150                    Some(a)
9151                }
9152                _ => None,
9153            })
9154            .collect();
9155        assert_eq!(listed.len(), 1, "one inline action");
9156        assert_eq!(listed[0].title, "Inline `y`");
9157        assert!(listed[0].edit.is_none());
9158
9159        let resolved = backend
9160            .code_action_resolve(listed[0].clone())
9161            .await
9162            .unwrap();
9163        let Some(DocumentChanges::Edits(doc_edits)) =
9164            &resolved.edit.as_ref().unwrap().document_changes
9165        else {
9166            panic!("expected versioned document edits");
9167        };
9168        assert_eq!(doc_edits[0].text_document.version, Some(1));
9169        let texts: Vec<String> = doc_edits[0]
9170            .edits
9171            .iter()
9172            .map(|e| match e {
9173                OneOf::Left(e) => e.new_text.clone(),
9174                OneOf::Right(e) => e.text_edit.new_text.clone(),
9175            })
9176            .collect();
9177        // Not canonical (two-space indent), so the raw edits apply: the `let`
9178        // line is deleted and the use replaced.
9179        assert_eq!(texts, vec![String::new(), "(a + 1)".to_string()]);
9180
9181        let mut stale = listed[0].clone();
9182        stale.data.as_mut().unwrap()["version"] = serde_json::json!(0);
9183        assert!(backend.code_action_resolve(stale).await.is_err());
9184    }
9185
9186    /// #2100 slice 4: a provider stub is listed on the unfiltered lightbulb
9187    /// request at a capability's name without an edit, and
9188    /// `codeAction/resolve` fills in the re-checked, versioned edit.
9189    #[tokio::test]
9190    async fn provider_stub_lists_then_resolves() {
9191        let src = "context app.c\n\ncapability Clock {\n  fn now() -> Effect[Int]\n}\n";
9192        let s = scratch_project(
9193            "provider_stub",
9194            &[
9195                ("bynk.toml", "[project]\nname=\"demo\"\n"),
9196                ("src/app/c.bynk", src),
9197            ],
9198        );
9199        let backend = backend_at(&s.0).await;
9200        let uri = file_uri(&s.0, "src/app/c.bynk");
9201        open(&backend, &uri, src).await;
9202        backend.run_round().await;
9203
9204        let at = crate::position::offset_to_position(src, src.find("Clock").unwrap());
9205        let actions = backend
9206            .code_action(CodeActionParams {
9207                text_document: TextDocumentIdentifier { uri: uri.clone() },
9208                range: Range { start: at, end: at },
9209                context: CodeActionContext::default(),
9210                work_done_progress_params: Default::default(),
9211                partial_result_params: Default::default(),
9212            })
9213            .await
9214            .unwrap()
9215            .unwrap();
9216        let listed: Vec<CodeAction> = actions
9217            .into_iter()
9218            .filter_map(|a| match a {
9219                CodeActionOrCommand::CodeAction(a) if a.title.starts_with("Generate provider") => {
9220                    Some(a)
9221                }
9222                _ => None,
9223            })
9224            .collect();
9225        assert_eq!(listed.len(), 1, "one stub action");
9226        assert_eq!(listed[0].kind, Some(CodeActionKind::REFACTOR));
9227        assert!(listed[0].edit.is_none());
9228
9229        let resolved = backend
9230            .code_action_resolve(listed[0].clone())
9231            .await
9232            .unwrap();
9233        let Some(DocumentChanges::Edits(doc_edits)) =
9234            &resolved.edit.as_ref().unwrap().document_changes
9235        else {
9236            panic!("expected versioned document edits");
9237        };
9238        assert_eq!(doc_edits[0].text_document.version, Some(1));
9239        let OneOf::Left(edit) = &doc_edits[0].edits[0] else {
9240            panic!("expected a plain TextEdit");
9241        };
9242        assert_eq!(
9243            edit.new_text,
9244            "\n\nprovides Clock = ClockImpl {\n  fn now() -> Effect[Int] {\n    0\n  }\n}"
9245        );
9246
9247        let mut stale = listed[0].clone();
9248        stale.data.as_mut().unwrap()["version"] = serde_json::json!(0);
9249        assert!(backend.code_action_resolve(stale).await.is_err());
9250    }
9251
9252    /// #2100 slice 2: extract-function is listed without an edit and
9253    /// resolved (re-checked) lazily; a capability-using selection gets a
9254    /// disabled action with its reason, only for a client that shows those.
9255    #[tokio::test]
9256    async fn extract_function_lists_then_resolves_or_says_why_not() {
9257        let src = "context app.m\n\ncapability Clock {\n  fn now() -> Effect[Int]\n}\n\nprovides Clock = Sys {\n  fn now() -> Effect[Int] {\n    1\n  }\n}\n\nservice s {\n  on call(x: Int) -> Effect[Int] by Caller given Clock {\n    let n <- Clock.now()\n    let y = x * 2 + 1\n    n + y\n  }\n}\n";
9258        let s = scratch_project(
9259            "extract_fn",
9260            &[
9261                ("bynk.toml", "[project]\nname=\"demo\"\n"),
9262                ("src/app/m.bynk", src),
9263            ],
9264        );
9265        let backend = backend_at(&s.0).await;
9266        let uri = file_uri(&s.0, "src/app/m.bynk");
9267        open(&backend, &uri, src).await;
9268        backend.run_round().await;
9269
9270        let request = |sel: &str| {
9271            let start = src.find(sel).unwrap();
9272            CodeActionParams {
9273                text_document: TextDocumentIdentifier { uri: uri.clone() },
9274                range: Range {
9275                    start: crate::position::offset_to_position(src, start),
9276                    end: crate::position::offset_to_position(src, start + sel.len()),
9277                },
9278                context: CodeActionContext::default(),
9279                work_done_progress_params: Default::default(),
9280                partial_result_params: Default::default(),
9281            }
9282        };
9283        let extract_fn = |actions: Vec<CodeActionOrCommand>| -> Vec<CodeAction> {
9284            actions
9285                .into_iter()
9286                .filter_map(|a| match a {
9287                    CodeActionOrCommand::CodeAction(a)
9288                        if a.title.starts_with("Extract function") =>
9289                    {
9290                        Some(a)
9291                    }
9292                    _ => None,
9293                })
9294                .collect()
9295        };
9296
9297        let listed = extract_fn(
9298            backend
9299                .code_action(request("x * 2 + 1"))
9300                .await
9301                .unwrap()
9302                .unwrap(),
9303        );
9304        assert_eq!(listed.len(), 1);
9305        assert!(listed[0].edit.is_none());
9306        let resolved = backend
9307            .code_action_resolve(listed[0].clone())
9308            .await
9309            .unwrap();
9310        let Some(DocumentChanges::Edits(doc_edits)) =
9311            &resolved.edit.as_ref().unwrap().document_changes
9312        else {
9313            panic!("expected versioned document edits");
9314        };
9315        assert_eq!(doc_edits[0].text_document.version, Some(1));
9316        assert_eq!(doc_edits[0].edits.len(), 2);
9317
9318        // Without `disabledSupport` a capability-using selection lists nothing.
9319        let refused = extract_fn(
9320            backend
9321                .code_action(request("Clock.now()"))
9322                .await
9323                .unwrap()
9324                .unwrap(),
9325        );
9326        assert!(refused.is_empty());
9327        // With it, a disabled action says why.
9328        backend.state.write().await.supports_code_action_disabled = true;
9329        let refused = extract_fn(
9330            backend
9331                .code_action(request("Clock.now()"))
9332                .await
9333                .unwrap()
9334                .unwrap(),
9335        );
9336        assert_eq!(refused.len(), 1);
9337        let reason = &refused[0].disabled.as_ref().expect("disabled").reason;
9338        assert!(reason.contains("capability-free"), "{reason}");
9339    }
9340
9341    /// #2117 review: fix-all is withheld when its combined edit fails the
9342    /// DECISION B re-check. The committed round's diagnostics are replaced
9343    /// with one machine-applicable suggestion: a harmless one is offered, one
9344    /// that introduces a type error is not.
9345    #[tokio::test]
9346    async fn fix_all_is_withheld_when_the_recheck_fails() {
9347        use bynk_syntax::error::{Applicability, CompileError};
9348        let src = "commons app.m\n\nfn f() -> Int {\n  1\n}\n";
9349        let s = scratch_project(
9350            "fix_all_gate",
9351            &[
9352                ("bynk.toml", "[project]\nname=\"demo\"\n"),
9353                ("src/app/m.bynk", src),
9354            ],
9355        );
9356        let backend = backend_at(&s.0).await;
9357        let uri = file_uri(&s.0, "src/app/m.bynk");
9358        open(&backend, &uri, src).await;
9359        backend.run_round().await;
9360
9361        let one = src.find("  1\n").unwrap() + 2;
9362        let one = bynk_syntax::span::Span::new(one, one + 1);
9363        // Swap the round's diagnostics for one carrying `replacement` as a
9364        // machine-applicable fix of the `1` body. It reuses a registered code:
9365        // the diagnostics registry rejects any `bynk.*` literal it doesn't
9366        // list.
9367        let inject = |replacement: &'static str| {
9368            let backend = backend.clone();
9369            async move {
9370                let root = backend.test_root().await;
9371                let mut state = backend.state.write().await;
9372                let project = state.projects.get_mut(&root).unwrap();
9373                let analysis = Arc::get_mut(project.analysis.as_mut().unwrap())
9374                    .expect("the round is not shared");
9375                let rel = analysis.snapshots.keys().next().unwrap().clone();
9376                let error = CompileError::new("bynk.given.unused_capability", one, "injected")
9377                    .with_suggestion(
9378                        "replace",
9379                        vec![(one, replacement.to_string())],
9380                        Applicability::MachineApplicable,
9381                    );
9382                analysis.diagnostics.insert(
9383                    rel,
9384                    vec![bynk_ide::Diagnostic {
9385                        severity: bynk_syntax::Severity::Warning,
9386                        label_files: Vec::new(),
9387                        error,
9388                    }],
9389                );
9390            }
9391        };
9392        let fix_all_count = || {
9393            let backend = backend.clone();
9394            let uri = uri.clone();
9395            async move {
9396                backend
9397                    .code_action(CodeActionParams {
9398                        text_document: TextDocumentIdentifier { uri },
9399                        range: Range::default(),
9400                        context: CodeActionContext {
9401                            diagnostics: Vec::new(),
9402                            only: Some(vec![crate::fix_all::kind()]),
9403                            trigger_kind: None,
9404                        },
9405                        work_done_progress_params: Default::default(),
9406                        partial_result_params: Default::default(),
9407                    })
9408                    .await
9409                    .unwrap()
9410                    .unwrap()
9411                    .len()
9412            }
9413        };
9414
9415        inject("2").await;
9416        assert_eq!(fix_all_count().await, 1, "a clean fix is offered");
9417        inject("\"one\"").await;
9418        assert_eq!(fix_all_count().await, 0, "a breaking fix is withheld");
9419    }
9420
9421    /// The v0.26 capability advertisements — the "trivial unit check" the
9422    /// proposal scopes in place of a transport round-trip.
9423    #[test]
9424    fn advertises_code_actions_and_the_index_riders() {
9425        let caps = server_capabilities();
9426        let Some(CodeActionProviderCapability::Options(opts)) = caps.code_action_provider else {
9427            panic!("codeActionProvider not advertised with options");
9428        };
9429        assert_eq!(
9430            opts.code_action_kinds,
9431            Some(vec![
9432                CodeActionKind::QUICKFIX,
9433                CodeActionKind::REFACTOR,
9434                CodeActionKind::REFACTOR_EXTRACT,
9435                CodeActionKind::REFACTOR_INLINE,
9436                CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
9437                CodeActionKind::new("source.fixAll.bynk"),
9438            ])
9439        );
9440        assert_eq!(
9441            opts.resolve_provider,
9442            Some(true),
9443            "fill-arms resolves lazily"
9444        );
9445        assert!(matches!(
9446            caps.workspace_symbol_provider,
9447            Some(OneOf::Left(true))
9448        ));
9449        assert!(matches!(
9450            caps.document_highlight_provider,
9451            Some(OneOf::Left(true))
9452        ));
9453    }
9454
9455    /// The v0.27 capability advertisement — the "trivial unit check" the
9456    /// proposal scopes in place of a transport round-trip.
9457    #[test]
9458    fn advertises_save_notifications() {
9459        // `diagnostics_mode = "on_save"` is driven by `didSave`; the sync
9460        // options must opt in explicitly or clients may not send it (#513).
9461        let caps = server_capabilities();
9462        let Some(TextDocumentSyncCapability::Options(opts)) = caps.text_document_sync else {
9463            panic!("textDocumentSync not advertised with options");
9464        };
9465        assert_eq!(opts.change, Some(TextDocumentSyncKind::FULL));
9466        assert!(matches!(
9467            opts.save,
9468            Some(TextDocumentSyncSaveOptions::Supported(true))
9469        ));
9470    }
9471
9472    #[test]
9473    fn advertises_inline_values() {
9474        let caps = server_capabilities();
9475        assert!(caps.inline_value_provider.is_some());
9476    }
9477
9478    #[test]
9479    fn advertises_inlay_hints() {
9480        let caps = server_capabilities();
9481        assert!(matches!(caps.inlay_hint_provider, Some(OneOf::Left(true))));
9482    }
9483
9484    /// Slice 6: go-to-type-definition (value → its type's declaration).
9485    #[test]
9486    fn advertises_type_definition() {
9487        let caps = server_capabilities();
9488        assert!(matches!(
9489            caps.type_definition_provider,
9490            Some(TypeDefinitionProviderCapability::Simple(true))
9491        ));
9492    }
9493
9494    /// Slice 6b: `uses`/`consumes` document links.
9495    #[test]
9496    fn advertises_document_links() {
9497        let caps = server_capabilities();
9498        assert!(caps.document_link_provider.is_some());
9499    }
9500
9501    /// #302: `willRenameFiles` over `.bynk` files; #2105: and every folder.
9502    #[test]
9503    fn advertises_will_rename_files() {
9504        let caps = server_capabilities();
9505        let file_ops = caps
9506            .workspace
9507            .as_ref()
9508            .and_then(|w| w.file_operations.as_ref())
9509            .expect("workspace.fileOperations advertised");
9510        let will_rename = file_ops
9511            .will_rename
9512            .as_ref()
9513            .expect("willRename registered");
9514        let filter = &will_rename.filters[0];
9515        assert_eq!(filter.pattern.glob, "**/*.bynk");
9516        assert_eq!(filter.pattern.matches, Some(FileOperationPatternKind::File));
9517        let folders = &will_rename.filters[1];
9518        assert_eq!(folders.scheme.as_deref(), Some("file"));
9519        assert_eq!(folders.pattern.glob, "**");
9520        assert_eq!(
9521            folders.pattern.matches,
9522            Some(FileOperationPatternKind::Folder)
9523        );
9524    }
9525
9526    /// #2098: `bynk/explain` is advertised under `experimental.explain`.
9527    #[test]
9528    fn advertises_the_explain_request() {
9529        let caps = server_capabilities();
9530        let experimental = caps.experimental.expect("experimental advertised");
9531        assert_eq!(experimental.get("explain"), Some(&serde_json::json!(true)));
9532    }
9533
9534    /// #2098: `initialize` records whether the client runs the explain command.
9535    #[tokio::test]
9536    async fn initialize_records_the_explain_command_capability() {
9537        for (experimental, expected) in [
9538            (None, false),
9539            (
9540                Some(serde_json::json!({ "explainDiagnosticCommand": true })),
9541                true,
9542            ),
9543        ] {
9544            let backend = bare_backend().await;
9545            backend
9546                .initialize(InitializeParams {
9547                    capabilities: ClientCapabilities {
9548                        experimental,
9549                        ..Default::default()
9550                    },
9551                    ..Default::default()
9552                })
9553                .await
9554                .expect("initialize");
9555            assert_eq!(
9556                backend.state.read().await.supports_explain_command,
9557                expected
9558            );
9559        }
9560    }
9561
9562    /// #2098: a curated diagnostic in range gets one "Explain …" quick fix,
9563    /// carrying the client command and the code, placed after every real fix
9564    /// and never preferred — but only for a client that runs the command.
9565    #[tokio::test]
9566    async fn code_action_offers_explain_for_a_curated_code_when_the_client_supports_it() {
9567        let src = "commons demo.a\n\nfn f(u: Usr) -> Int {\n  1\n}\n";
9568        let s = scratch_project(
9569            "explain_action",
9570            &[
9571                ("bynk.toml", "[project]\nname=\"demo\"\n"),
9572                ("src/demo/a.bynk", src),
9573            ],
9574        );
9575        let backend = backend_at(&s.0).await;
9576        let uri = file_uri(&s.0, "src/demo/a.bynk");
9577        backend.run_round().await;
9578        let at = crate::position::offset_to_position(src, src.find("Usr").unwrap());
9579        let request = || CodeActionParams {
9580            text_document: TextDocumentIdentifier { uri: uri.clone() },
9581            range: Range::new(at, at),
9582            context: CodeActionContext::default(),
9583            work_done_progress_params: Default::default(),
9584            partial_result_params: Default::default(),
9585        };
9586        let titles = |actions: &CodeActionResponse| -> Vec<String> {
9587            actions
9588                .iter()
9589                .map(|a| match a {
9590                    CodeActionOrCommand::CodeAction(c) => c.title.clone(),
9591                    CodeActionOrCommand::Command(c) => c.title.clone(),
9592                })
9593                .collect()
9594        };
9595        let explain_title = "Explain `bynk.resolve.unknown_type`";
9596
9597        // Without the client capability: no explain action.
9598        let without = backend.code_action(request()).await.unwrap().unwrap();
9599        assert!(
9600            !titles(&without).iter().any(|t| t == explain_title),
9601            "{:?}",
9602            titles(&without)
9603        );
9604
9605        backend.state.write().await.supports_explain_command = true;
9606        let with = backend.code_action(request()).await.unwrap().unwrap();
9607        let names = titles(&with);
9608        let pos = names
9609            .iter()
9610            .position(|t| t == explain_title)
9611            .unwrap_or_else(|| panic!("explain action offered: {names:?}"));
9612        assert_eq!(pos, names.len() - 1, "explain comes last: {names:?}");
9613        let CodeActionOrCommand::CodeAction(action) = &with[pos] else {
9614            panic!("a CodeAction");
9615        };
9616        assert_eq!(action.kind, Some(CodeActionKind::QUICKFIX));
9617        assert_eq!(action.is_preferred, Some(false));
9618        assert!(action.edit.is_none());
9619        let cmd = action.command.as_ref().expect("carries a command");
9620        assert_eq!(cmd.command, "bynk.explainDiagnostic");
9621        assert_eq!(
9622            cmd.arguments,
9623            Some(vec![serde_json::json!("bynk.resolve.unknown_type")])
9624        );
9625    }
9626
9627    /// #2098: the request itself, through the backend handler.
9628    #[tokio::test]
9629    async fn explain_request_serves_curated_and_declines_the_rest() {
9630        let backend = bare_backend().await;
9631        let ask = |code: &str| explain_request::ExplainParams { code: code.into() };
9632        let curated = backend
9633            .explain(ask("bynk.resolve.unknown_type"))
9634            .await
9635            .unwrap()
9636            .expect("curated");
9637        assert_eq!(curated.title, "bynk.resolve.unknown_type");
9638        assert!(
9639            backend
9640                .explain(ask("bynk.wasm.panic"))
9641                .await
9642                .unwrap()
9643                .is_none()
9644        );
9645        assert!(backend.explain(ask("nonsense")).await.unwrap().is_none());
9646    }
9647
9648    /// #2470: `bynk/refinedTypeModel` is advertised under `experimental`.
9649    #[test]
9650    fn advertises_the_refined_type_model_request() {
9651        let caps = server_capabilities();
9652        let experimental = caps.experimental.expect("experimental advertised");
9653        assert_eq!(
9654            experimental.get("refinedTypeModel"),
9655            Some(&serde_json::json!(true))
9656        );
9657    }
9658
9659    /// #2470: `initialize` records whether the client runs the explorer command.
9660    #[tokio::test]
9661    async fn initialize_records_the_refined_explorer_capability() {
9662        for (experimental, expected) in [
9663            (None, false),
9664            (
9665                Some(serde_json::json!({ "refinedTypeExplorerCommand": true })),
9666                true,
9667            ),
9668        ] {
9669            let backend = bare_backend().await;
9670            backend
9671                .initialize(InitializeParams {
9672                    capabilities: ClientCapabilities {
9673                        experimental,
9674                        ..Default::default()
9675                    },
9676                    ..Default::default()
9677                })
9678                .await
9679                .expect("initialize");
9680            assert_eq!(
9681                backend.state.read().await.supports_refined_explorer_command,
9682                expected
9683            );
9684        }
9685    }
9686
9687    /// #2470: a refined type's hover gains its predicates in words, and — for a
9688    /// client that runs the command — the "Try values…" link; an unrefined type
9689    /// gains neither. The request answers the same position.
9690    #[tokio::test]
9691    async fn refined_type_hover_and_model_request() {
9692        let src = "commons demo.a\n\ntype Quantity = Int where InRange(1, 100)\n\ntype Plain = Int\n\nfn f(q: Quantity, p: Plain) -> Int {\n  1\n}\n";
9693        let s = scratch_project(
9694            "refined_explorer",
9695            &[
9696                ("bynk.toml", "[project]\nname=\"demo\"\n"),
9697                ("src/demo/a.bynk", src),
9698            ],
9699        );
9700        let backend = backend_at(&s.0).await;
9701        let uri = file_uri(&s.0, "src/demo/a.bynk");
9702        backend.run_round().await;
9703        let at =
9704            |needle: &str| crate::position::offset_to_position(src, src.rfind(needle).unwrap() + 1);
9705        let hover = |pos: Position| {
9706            let backend = &backend;
9707            let uri = uri.clone();
9708            async move {
9709                let h = backend
9710                    .hover(HoverParams {
9711                        text_document_position_params: TextDocumentPositionParams {
9712                            text_document: TextDocumentIdentifier { uri },
9713                            position: pos,
9714                        },
9715                        work_done_progress_params: Default::default(),
9716                    })
9717                    .await
9718                    .unwrap()
9719                    .expect("hover");
9720                let HoverContents::Markup(m) = h.contents else {
9721                    panic!("markup")
9722                };
9723                m.value
9724            }
9725        };
9726
9727        // A reference to the refined type, from a parameter's annotation.
9728        let without = hover(at("Quantity,")).await;
9729        assert!(without.contains("**Refined type** over `Int`"), "{without}");
9730        assert!(
9731            without.contains("`InRange(1, 100)` — 1 ≤ value ≤ 100"),
9732            "{without}"
9733        );
9734        assert!(!without.contains("Try values"), "{without}");
9735
9736        backend
9737            .state
9738            .write()
9739            .await
9740            .supports_refined_explorer_command = true;
9741        let with = hover(at("Quantity,")).await;
9742        assert!(
9743            with.contains("[Try values…](command:bynk.exploreRefinedType?"),
9744            "{with}"
9745        );
9746
9747        // The declaration's own name hovers the same; an unrefined type does not.
9748        assert!(hover(at("Quantity =")).await.contains("Try values"));
9749        let plain = hover(at("Plain)")).await;
9750        assert!(
9751            !plain.contains("Refined type") && !plain.contains("Try values"),
9752            "{plain}"
9753        );
9754
9755        let model = backend
9756            .refined_type_model(refined_request::RefinedParams {
9757                text_document: TextDocumentIdentifier { uri: uri.clone() },
9758                position: at("Quantity,"),
9759            })
9760            .await
9761            .unwrap()
9762            .expect("a model");
9763        assert_eq!(model.name, "Quantity");
9764        assert_eq!(model.clauses.len(), 1);
9765        assert!(!model.examples.is_empty());
9766        let none = backend
9767            .refined_type_model(refined_request::RefinedParams {
9768                text_document: TextDocumentIdentifier { uri },
9769                position: at("Plain)"),
9770            })
9771            .await
9772            .unwrap();
9773        assert!(none.is_none());
9774    }
9775
9776    /// Slice 5: completion advertises `.` triggers and lazy doc resolution.
9777    #[test]
9778    fn advertises_completion_with_dot_trigger_and_resolve() {
9779        // #2458: `[` also triggers (doc-link completion, gated in the handler).
9780        assert!(
9781            server_capabilities()
9782                .completion_provider
9783                .and_then(|o| o.trigger_characters)
9784                .is_some_and(|t| t.iter().any(|c| c == "[")),
9785            "`[` trigger char"
9786        );
9787        let caps = server_capabilities();
9788        let opts = caps.completion_provider.expect("completion advertised");
9789        assert_eq!(opts.resolve_provider, Some(true), "resolve_provider");
9790        assert!(
9791            opts.trigger_characters
9792                .as_deref()
9793                .is_some_and(|t| t.iter().any(|c| c == ".")),
9794            "`.` trigger char"
9795        );
9796    }
9797
9798    /// The v0.28 capability advertisement: full + range with the frozen
9799    /// legend (the legend's content is pinned in `index_queries`).
9800    #[test]
9801    fn advertises_semantic_tokens() {
9802        let caps = server_capabilities();
9803        let Some(SemanticTokensServerCapabilities::SemanticTokensOptions(opts)) =
9804            caps.semantic_tokens_provider
9805        else {
9806            panic!("semanticTokensProvider not advertised with options");
9807        };
9808        assert_eq!(opts.full, Some(SemanticTokensFullOptions::Bool(true)));
9809        assert_eq!(opts.range, Some(true));
9810        assert_eq!(opts.legend, crate::index_queries::semantic_tokens_legend());
9811    }
9812
9813    // ---- Slice D: per-workspace state (Q4) ----
9814
9815    /// #2459: end to end through a real round — the project publish adds the
9816    /// unresolved-link hint (and only for the unescaped, unresolved link), the
9817    /// `codeAction` request turns the echoed diagnostic into the did-you-mean
9818    /// fix, and a runtime switch to `off` re-publishes without it.
9819    #[tokio::test]
9820    async fn a_round_publishes_the_doc_link_hint_and_off_clears_it() {
9821        use futures::StreamExt;
9822        use tower::{Service, ServiceExt};
9823
9824        let s = scratch_project(
9825            "doc_link_hint",
9826            &[
9827                ("bynk.toml", "[project]\nname = \"demo\"\n"),
9828                (
9829                    "src/app/window.bynk",
9830                    "context app\n\n--| A window. See [Windw], \\[TODO] and [Window].\ntype Window = Int\n",
9831                ),
9832            ],
9833        );
9834        let (mut service, socket) = tower_lsp::LspService::new(Backend::new);
9835        for request in [
9836            tower_lsp::jsonrpc::Request::build("initialize")
9837                .params(serde_json::json!({ "capabilities": {} }))
9838                .id(1)
9839                .finish(),
9840            tower_lsp::jsonrpc::Request::build("initialized")
9841                .params(serde_json::json!({}))
9842                .finish(),
9843        ] {
9844            service.ready().await.unwrap().call(request).await.unwrap();
9845        }
9846        let published = Arc::new(std::sync::Mutex::new(Vec::<PublishDiagnosticsParams>::new()));
9847        let drain = {
9848            let published = Arc::clone(&published);
9849            tokio::spawn(socket.for_each(move |message| {
9850                if message.method() == "textDocument/publishDiagnostics"
9851                    && let Some(params) = message.params()
9852                {
9853                    published
9854                        .lock()
9855                        .unwrap()
9856                        .push(serde_json::from_value(params.clone()).unwrap());
9857                }
9858                async {}
9859            }))
9860        };
9861        let backend = service.inner().clone();
9862        let canonical = s.0.canonicalize().unwrap();
9863        backend
9864            .state
9865            .write()
9866            .await
9867            .projects
9868            .insert(canonical.clone(), ProjectState::default());
9869        backend.run_project_diagnostics(canonical.clone()).await;
9870        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
9871
9872        let uri = Url::from_file_path(canonical.join("src/app/window.bynk")).unwrap();
9873        let hints_in = |published: &[PublishDiagnosticsParams]| -> Vec<Diagnostic> {
9874            published
9875                .iter()
9876                .rev()
9877                .find(|p| p.uri == uri)
9878                .map(|p| {
9879                    p.diagnostics
9880                        .iter()
9881                        .filter(|d| {
9882                            d.code == Some(NumberOrString::String(doc_link_hints::CODE.into()))
9883                        })
9884                        .cloned()
9885                        .collect()
9886                })
9887                .unwrap_or_default()
9888        };
9889        let hint = {
9890            let published = published.lock().unwrap();
9891            let hints = hints_in(&published);
9892            assert_eq!(hints.len(), 1, "only `[Windw]` is unresolved: {hints:?}");
9893            assert_eq!(hints[0].severity, Some(DiagnosticSeverity::HINT));
9894            hints[0].clone()
9895        };
9896
9897        // The `codeAction` request, with the diagnostic the client echoes back.
9898        let actions = backend
9899            .code_action(CodeActionParams {
9900                text_document: TextDocumentIdentifier { uri: uri.clone() },
9901                range: hint.range,
9902                context: CodeActionContext {
9903                    diagnostics: vec![hint.clone()],
9904                    only: None,
9905                    trigger_kind: None,
9906                },
9907                work_done_progress_params: Default::default(),
9908                partial_result_params: Default::default(),
9909            })
9910            .await
9911            .unwrap()
9912            .unwrap();
9913        assert!(
9914            actions.iter().any(|a| matches!(
9915                a,
9916                CodeActionOrCommand::CodeAction(a) if a.title == "Change to `Window`"
9917            )),
9918            "{actions:?}"
9919        );
9920
9921        // A runtime switch to `off` re-publishes the file without the hint.
9922        let before = published.lock().unwrap().len();
9923        backend
9924            .did_change_configuration(DidChangeConfigurationParams {
9925                settings: serde_json::json!({
9926                    "bynk": { "docLinks": { "reportUnresolved": "off" } }
9927                }),
9928            })
9929            .await;
9930        let mut cleared = false;
9931        for _ in 0..50 {
9932            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
9933            let published = published.lock().unwrap();
9934            if published.len() > before && hints_in(&published).is_empty() {
9935                cleared = true;
9936                break;
9937            }
9938        }
9939        drain.abort();
9940        assert!(cleared, "`off` must re-publish the file without the hint");
9941    }
9942
9943    /// #2459: the doc-link setting defaults to `hint`, is taken from
9944    /// `initializationOptions` at start-up, and an unrecognised value is ignored.
9945    #[tokio::test]
9946    async fn doc_link_report_is_read_from_initialization_options() {
9947        let backend = bare_backend().await;
9948        assert_eq!(
9949            backend.state.read().await.doc_link_report,
9950            doc_link_hints::Level::Hint
9951        );
9952        backend
9953            .initialize(InitializeParams {
9954                initialization_options: Some(serde_json::json!({
9955                    "docLinks": { "reportUnresolved": "warning" }
9956                })),
9957                ..Default::default()
9958            })
9959            .await
9960            .expect("initialize");
9961        assert_eq!(
9962            backend.state.read().await.doc_link_report,
9963            doc_link_hints::Level::Warning
9964        );
9965
9966        let ignored = bare_backend().await;
9967        ignored
9968            .initialize(InitializeParams {
9969                initialization_options: Some(serde_json::json!({
9970                    "docLinks": { "reportUnresolved": "loud" }
9971                })),
9972                ..Default::default()
9973            })
9974            .await
9975            .expect("initialize");
9976        assert_eq!(
9977            ignored.state.read().await.doc_link_report,
9978            doc_link_hints::Level::Hint
9979        );
9980    }
9981
9982    /// #2459: a runtime `workspace/didChangeConfiguration` changes the setting
9983    /// (in the client's `{ "bynk": { … } }` shape), and an unrelated payload
9984    /// leaves it alone.
9985    #[tokio::test]
9986    async fn doc_link_report_follows_did_change_configuration() {
9987        let backend = bare_backend().await;
9988        backend
9989            .did_change_configuration(DidChangeConfigurationParams {
9990                settings: serde_json::json!({
9991                    "bynk": { "docLinks": { "reportUnresolved": "off" } }
9992                }),
9993            })
9994            .await;
9995        assert_eq!(
9996            backend.state.read().await.doc_link_report,
9997            doc_link_hints::Level::Off
9998        );
9999        backend
10000            .did_change_configuration(DidChangeConfigurationParams {
10001                settings: serde_json::json!({ "bynk": { "inlayHints": { "enable": false } } }),
10002            })
10003            .await;
10004        assert_eq!(
10005            backend.state.read().await.doc_link_report,
10006            doc_link_hints::Level::Off,
10007            "an unrelated settings change keeps the level"
10008        );
10009    }
10010
10011    /// A backend with **no** seeded project — the real lazy-discovery flow,
10012    /// where `did_open` and requests create entries by routing (`resolve_root`).
10013    async fn bare_backend() -> Backend {
10014        let (service, _socket) = tower_lsp::LspService::new(Backend::new);
10015        service.inner().clone()
10016    }
10017
10018    fn file_uri(root: &std::path::Path, rel: &str) -> Url {
10019        let abs = root.join(rel);
10020        Url::from_file_path(abs.canonicalize().unwrap_or(abs)).unwrap()
10021    }
10022
10023    async fn set_folders(backend: &Backend, roots: &[&std::path::Path]) {
10024        backend.state.write().await.folders = roots
10025            .iter()
10026            .map(|r| r.canonicalize().unwrap_or_else(|_| r.to_path_buf()))
10027            .collect();
10028    }
10029
10030    async fn open(backend: &Backend, uri: &Url, text: &str) {
10031        backend
10032            .did_open(DidOpenTextDocumentParams {
10033                text_document: TextDocumentItem {
10034                    uri: uri.clone(),
10035                    language_id: "bynk".into(),
10036                    version: 1,
10037                    text: text.to_string(),
10038                },
10039            })
10040            .await;
10041    }
10042
10043    fn snapshot_keys(a: &Analysis) -> Vec<String> {
10044        let mut keys: Vec<String> = a
10045            .snapshots
10046            .keys()
10047            .map(|p| p.to_string_lossy().replace('\\', "/"))
10048            .collect();
10049        keys.sort();
10050        keys
10051    }
10052
10053    /// Two `bynk.toml` projects under **one** workspace folder are two projects
10054    /// (Q4: route by discovered root, not folder). Opening a file in each creates
10055    /// its own entry, and each analyses **only its own** tree — the overlay
10056    /// isolation guard, too: project A's round never sees project B's file.
10057    #[tokio::test]
10058    async fn two_projects_under_one_folder_are_two_projects() {
10059        let ax_src = "commons a.x\n\nfn ax(n: Int) -> Int {\n  n\n}\n";
10060        let by_src = "commons b.y\n\nfn by(n: Int) -> Int {\n  n\n}\n";
10061        let s = scratch_project(
10062            "d_two",
10063            &[
10064                ("a/bynk.toml", "[project]\nname=\"a\"\n"),
10065                ("a/src/x.bynk", ax_src),
10066                ("b/bynk.toml", "[project]\nname=\"b\"\n"),
10067                ("b/src/y.bynk", by_src),
10068            ],
10069        );
10070        let backend = bare_backend().await;
10071        set_folders(&backend, &[&s.0]).await;
10072        let ax = file_uri(&s.0, "a/src/x.bynk");
10073        let by = file_uri(&s.0, "b/src/y.bynk");
10074        open(&backend, &ax, ax_src).await;
10075        open(&backend, &by, by_src).await;
10076
10077        assert_ne!(
10078            Backend::root_for_uri_uncached(&ax).unwrap(),
10079            Backend::root_for_uri_uncached(&by).unwrap(),
10080            "the two files resolve to different project roots",
10081        );
10082        assert_eq!(
10083            backend.state.read().await.projects.len(),
10084            2,
10085            "one entry per project, not one for the shared folder",
10086        );
10087
10088        let a = backend.analysis_for(&ax).await.expect("A analysed");
10089        let b = backend.analysis_for(&by).await.expect("B analysed");
10090        assert_eq!(
10091            snapshot_keys(&a),
10092            vec!["src/x.bynk"],
10093            "A sees only A's file"
10094        );
10095        assert_eq!(
10096            snapshot_keys(&b),
10097            vec!["src/y.bynk"],
10098            "B sees only B's file"
10099        );
10100    }
10101
10102    /// Q4 lifecycle: `did_change_workspace_folders` removing a folder with **no
10103    /// open buffer** prunes the idle project entry and clears nothing it must
10104    /// keep. Routing no longer resolves it because the seed is gone.
10105    #[tokio::test]
10106    async fn removing_a_folder_prunes_an_idle_project() {
10107        let a = "commons p.a\n\nfn f(n: Int) -> Int {\n  n\n}\n";
10108        let s = scratch_project(
10109            "d_prune",
10110            &[("bynk.toml", "[project]\nname=\"p\"\n"), ("src/a.bynk", a)],
10111        );
10112        let folder = s.0.canonicalize().unwrap_or_else(|_| s.0.clone());
10113        let backend = bare_backend().await;
10114        set_folders(&backend, &[&s.0]).await;
10115        let uri = file_uri(&s.0, "src/a.bynk");
10116        open(&backend, &uri, a).await;
10117        backend.analysis_for(&uri).await.expect("analysed");
10118        // Close the buffer, so nothing but the folder pins the project.
10119        backend
10120            .did_close(DidCloseTextDocumentParams {
10121                text_document: TextDocumentIdentifier { uri: uri.clone() },
10122            })
10123            .await;
10124        assert_eq!(backend.state.read().await.projects.len(), 1);
10125
10126        backend
10127            .did_change_workspace_folders(DidChangeWorkspaceFoldersParams {
10128                event: WorkspaceFoldersChangeEvent {
10129                    added: vec![],
10130                    removed: vec![WorkspaceFolder {
10131                        uri: Url::from_file_path(&folder).unwrap(),
10132                        name: "p".into(),
10133                    }],
10134                },
10135            })
10136            .await;
10137        assert!(
10138            backend.state.read().await.projects.is_empty(),
10139            "an idle project is pruned when its last covering folder is removed",
10140        );
10141    }
10142
10143    /// Q4 lifecycle: a project that still holds an **open buffer** survives folder
10144    /// removal — routing needs it until the buffer closes.
10145    #[tokio::test]
10146    async fn removing_a_folder_retains_a_project_with_an_open_buffer() {
10147        let a = "commons p.a\n\nfn f(n: Int) -> Int {\n  n\n}\n";
10148        let s = scratch_project(
10149            "d_retain",
10150            &[("bynk.toml", "[project]\nname=\"p\"\n"), ("src/a.bynk", a)],
10151        );
10152        let folder = s.0.canonicalize().unwrap_or_else(|_| s.0.clone());
10153        let backend = bare_backend().await;
10154        set_folders(&backend, &[&s.0]).await;
10155        let uri = file_uri(&s.0, "src/a.bynk");
10156        open(&backend, &uri, a).await; // buffer stays open
10157
10158        backend
10159            .did_change_workspace_folders(DidChangeWorkspaceFoldersParams {
10160                event: WorkspaceFoldersChangeEvent {
10161                    added: vec![],
10162                    removed: vec![WorkspaceFolder {
10163                        uri: Url::from_file_path(&folder).unwrap(),
10164                        name: "p".into(),
10165                    }],
10166                },
10167            })
10168            .await;
10169        assert_eq!(
10170            backend.state.read().await.projects.len(),
10171            1,
10172            "a project with an open buffer must survive folder removal",
10173        );
10174        assert!(
10175            backend.analysis_for(&uri).await.is_some(),
10176            "and it must still answer requests",
10177        );
10178    }
10179
10180    /// Q4 §C: closing the **last** buffer of a project whose folder was already
10181    /// removed prunes it — the mirror of the folder path. Without it the project
10182    /// lingers forever with published diagnostics no folder or buffer justifies.
10183    #[tokio::test]
10184    async fn closing_the_last_buffer_of_a_folder_removed_project_prunes_it() {
10185        let a = "commons p.a\n\nfn f(n: Int) -> Int {\n  n\n}\n";
10186        let s = scratch_project(
10187            "d_close_prune",
10188            &[("bynk.toml", "[project]\nname=\"p\"\n"), ("src/a.bynk", a)],
10189        );
10190        let folder = s.0.canonicalize().unwrap_or_else(|_| s.0.clone());
10191        let backend = bare_backend().await;
10192        set_folders(&backend, &[&s.0]).await;
10193        let uri = file_uri(&s.0, "src/a.bynk");
10194        open(&backend, &uri, a).await;
10195        backend.analysis_for(&uri).await.expect("analysed");
10196
10197        // Remove the folder while the buffer is open — retained (its buffer pins it).
10198        backend
10199            .did_change_workspace_folders(DidChangeWorkspaceFoldersParams {
10200                event: WorkspaceFoldersChangeEvent {
10201                    added: vec![],
10202                    removed: vec![WorkspaceFolder {
10203                        uri: Url::from_file_path(&folder).unwrap(),
10204                        name: "p".into(),
10205                    }],
10206                },
10207            })
10208            .await;
10209        assert_eq!(
10210            backend.state.read().await.projects.len(),
10211            1,
10212            "retained while its buffer is open",
10213        );
10214
10215        // Close the last buffer — now fully orphaned (no folder, no buffer).
10216        backend
10217            .did_close(DidCloseTextDocumentParams {
10218                text_document: TextDocumentIdentifier { uri: uri.clone() },
10219            })
10220            .await;
10221        assert!(
10222            backend.state.read().await.projects.is_empty(),
10223            "closing the last buffer of a folder-removed project must prune it",
10224        );
10225    }
10226
10227    /// Q4: a rename spans **one** project — a stale buffer in another project must
10228    /// not block it (`analysis_covering_open_buffers` is per-project). Under a
10229    /// whole-server gate, B's dirty buffer would refuse A's rename.
10230    #[tokio::test]
10231    async fn a_rename_in_one_project_ignores_a_dirty_buffer_in_another() {
10232        let a_src = "commons a.x\n\ntype Money = Int where Positive\n\nfn charge(m: Money) -> Money {\n  m\n}\n";
10233        let b_src = "commons b.y\n\nfn by(n: Int) -> Int {\n  n\n}\n";
10234        let s = scratch_project(
10235            "d_rename_iso",
10236            &[
10237                ("a/bynk.toml", "[project]\nname=\"a\"\n"),
10238                ("a/src/x.bynk", a_src),
10239                ("b/bynk.toml", "[project]\nname=\"b\"\n"),
10240                ("b/src/y.bynk", b_src),
10241            ],
10242        );
10243        let backend = bare_backend().await;
10244        set_folders(&backend, &[&s.0]).await;
10245        let ax = file_uri(&s.0, "a/src/x.bynk");
10246        let by = file_uri(&s.0, "b/src/y.bynk");
10247        open(&backend, &ax, a_src).await;
10248        open(&backend, &by, b_src).await;
10249        backend.analysis_for(&ax).await.expect("A analysed");
10250        backend.analysis_for(&by).await.expect("B analysed");
10251
10252        // Make B's buffer dirty (version 2, not yet re-analysed).
10253        backend
10254            .did_change(DidChangeTextDocumentParams {
10255                text_document: VersionedTextDocumentIdentifier {
10256                    uri: by.clone(),
10257                    version: 2,
10258                },
10259                content_changes: vec![TextDocumentContentChangeEvent {
10260                    range: None,
10261                    range_length: None,
10262                    text: format!("\n{b_src}"),
10263                }],
10264            })
10265            .await;
10266
10267        // Rename `Money` in A — must succeed despite B being dirty.
10268        let off = a_src.find("Money").unwrap();
10269        let pos = crate::position::offset_to_position(a_src, off);
10270        let edit = backend
10271            .rename(RenameParams {
10272                text_document_position: TextDocumentPositionParams {
10273                    text_document: TextDocumentIdentifier { uri: ax.clone() },
10274                    position: pos,
10275                },
10276                new_name: "Amount".into(),
10277                work_done_progress_params: Default::default(),
10278            })
10279            .await
10280            .expect("rename must not error");
10281        assert!(
10282            edit.is_some(),
10283            "a rename in project A must not be blocked by a dirty buffer in project B",
10284        );
10285    }
10286
10287    // ---- Slice E: startup analysis & dynamic watchers ----
10288
10289    /// `initialize` captures the client's `didChangeWatchedFiles` dynamic-
10290    /// registration support, which gates the server-side watcher registration.
10291    #[tokio::test]
10292    async fn initialize_captures_the_dynamic_watcher_capability() {
10293        let backend = bare_backend().await;
10294        let params = InitializeParams {
10295            capabilities: ClientCapabilities {
10296                workspace: Some(WorkspaceClientCapabilities {
10297                    did_change_watched_files: Some(DidChangeWatchedFilesClientCapabilities {
10298                        dynamic_registration: Some(true),
10299                        relative_pattern_support: None,
10300                    }),
10301                    ..Default::default()
10302                }),
10303                ..Default::default()
10304            },
10305            ..Default::default()
10306        };
10307        backend.initialize(params).await.expect("initialize");
10308        assert!(
10309            backend.state.read().await.supports_dynamic_watchers,
10310            "the client's dynamic-registration support must be captured for `initialized`",
10311        );
10312    }
10313
10314    /// #733: `initialize` captures each pull-based decoration's `refresh_support`
10315    /// independently — the flag gates whether a committed round nudges the client
10316    /// to re-pull that decoration. The three `and_then` chains are easy to
10317    /// mis-wire (a swapped field reads the wrong capability), so pin each: two
10318    /// advertised, one withheld, one whole family absent.
10319    #[tokio::test]
10320    async fn initialize_captures_each_decoration_refresh_capability() {
10321        let backend = bare_backend().await;
10322        let params = InitializeParams {
10323            capabilities: ClientCapabilities {
10324                workspace: Some(WorkspaceClientCapabilities {
10325                    // Semantic tokens: advertised.
10326                    semantic_tokens: Some(SemanticTokensWorkspaceClientCapabilities {
10327                        refresh_support: Some(true),
10328                    }),
10329                    // Inlay hints: explicitly withheld.
10330                    inlay_hint: Some(InlayHintWorkspaceClientCapabilities {
10331                        refresh_support: Some(false),
10332                    }),
10333                    // Code lens: the whole family absent (no capability at all).
10334                    ..Default::default()
10335                }),
10336                ..Default::default()
10337            },
10338            ..Default::default()
10339        };
10340        backend.initialize(params).await.expect("initialize");
10341        let refresh = backend.state.read().await.supports_refresh;
10342        assert!(
10343            refresh.semantic_tokens,
10344            "semantic tokens: advertised → true"
10345        );
10346        assert!(!refresh.inlay_hints, "inlay hints: withheld → false");
10347        assert!(!refresh.code_lens, "code lens: absent → false");
10348    }
10349
10350    /// #2207: a workspace root's `bynk.toml` isn't a project; its members are.
10351    #[tokio::test]
10352    async fn discover_projects_under_skips_a_workspace_root() {
10353        let s = scratch_project(
10354            "e_discover_workspace",
10355            &[
10356                ("bynk.toml", "[workspace]\nmembers = [\"packages/*\"]\n"),
10357                ("packages/a/bynk.toml", "[package]\nname=\"acme/a\"\n"),
10358                ("packages/a/src/x.bynk", "commons a.x\n"),
10359            ],
10360        );
10361        let roots = Backend::discover_projects_under(&s.0);
10362        let names: Vec<String> = roots
10363            .iter()
10364            .map(|r| r.file_name().unwrap().to_string_lossy().into_owned())
10365            .collect();
10366        assert_eq!(names, vec!["a"], "the member, not the root; got {roots:?}");
10367    }
10368
10369    /// The discovery walk finds every nested `bynk.toml` project under a folder
10370    /// (a monorepo), and skips the caches it must never descend.
10371    #[tokio::test]
10372    async fn discover_projects_under_finds_nested_projects_and_skips_caches() {
10373        let s = scratch_project(
10374            "e_discover",
10375            &[
10376                ("packages/a/bynk.toml", "[project]\nname=\"a\"\n"),
10377                ("packages/a/src/x.bynk", "commons a.x\n"),
10378                ("packages/b/bynk.toml", "[project]\nname=\"b\"\n"),
10379                ("packages/b/src/y.bynk", "commons b.y\n"),
10380                // A manifest under a skipped dir must NOT be discovered.
10381                ("node_modules/dep/bynk.toml", "[project]\nname=\"dep\"\n"),
10382            ],
10383        );
10384        let mut roots = Backend::discover_projects_under(&s.0);
10385        roots.sort();
10386        let names: Vec<String> = roots
10387            .iter()
10388            .map(|r| r.file_name().unwrap().to_string_lossy().into_owned())
10389            .collect();
10390        assert_eq!(
10391            names,
10392            vec!["a", "b"],
10393            "both monorepo projects found, node_modules skipped; got {roots:?}",
10394        );
10395    }
10396
10397    /// Startup analysis: `initialized` warms every project under the workspace
10398    /// folders — creating each entry so diagnostics/features are ready — **with
10399    /// no `did_open`**. This is spec §2.3's documented startup analysis.
10400    #[tokio::test]
10401    async fn initialized_warms_every_project_under_the_folders() {
10402        let s = scratch_project(
10403            "e_warm",
10404            &[
10405                ("packages/a/bynk.toml", "[project]\nname=\"a\"\n"),
10406                (
10407                    "packages/a/src/x.bynk",
10408                    "commons a.x\n\nfn ax(n: Int) -> Int {\n  n\n}\n",
10409                ),
10410                ("packages/b/bynk.toml", "[project]\nname=\"b\"\n"),
10411                (
10412                    "packages/b/src/y.bynk",
10413                    "commons b.y\n\nfn by(n: Int) -> Int {\n  n\n}\n",
10414                ),
10415            ],
10416        );
10417        let backend = bare_backend().await;
10418        set_folders(&backend, &[&s.0]).await;
10419
10420        // No file opened — just the handshake completion.
10421        backend.initialized(InitializedParams {}).await;
10422
10423        assert_eq!(
10424            backend.state.read().await.projects.len(),
10425            2,
10426            "both monorepo projects are warmed at `initialized`, before any open",
10427        );
10428        // And each is genuinely analysable without an open buffer.
10429        let ax = file_uri(&s.0, "packages/a/src/x.bynk");
10430        assert!(
10431            backend.analysis_for(&ax).await.is_some(),
10432            "a warmed project answers index requests with no `did_open`",
10433        );
10434    }
10435
10436    /// #3274: a workspace folder that is no project but holds projects (the
10437    /// manifest-less directory `bynk check --each` runs) needs no editor
10438    /// support of its own. Each project directly inside it is its own root,
10439    /// routed by its nearest `bynk.toml`, so two projects that declare the same
10440    /// unit name neither collide nor merge.
10441    #[tokio::test]
10442    async fn a_manifestless_folder_of_projects_is_analysed_per_project() {
10443        let unit = "commons shared\n\nfn twice(n: Int) -> Int {\n  n + n\n}\n";
10444        let s = scratch_project(
10445            "e_each_folder",
10446            &[
10447                ("one/bynk.toml", "[project]\nname=\"one\"\n"),
10448                ("one/src/shared.bynk", unit),
10449                ("two/bynk.toml", "[project]\nname=\"two\"\n"),
10450                ("two/src/shared.bynk", unit),
10451                // Not a project: no `bynk.toml`, so it is no root.
10452                ("docs/notes.bynk", "commons notes\n"),
10453            ],
10454        );
10455        let backend = bare_backend().await;
10456        set_folders(&backend, &[&s.0]).await;
10457        backend.initialized(InitializedParams {}).await;
10458
10459        assert_eq!(
10460            backend.state.read().await.projects.len(),
10461            2,
10462            "each project directly inside the folder is a root; the folder is not",
10463        );
10464        let one = file_uri(&s.0, "one/src/shared.bynk");
10465        let two = file_uri(&s.0, "two/src/shared.bynk");
10466        let root_one = backend.root_for_uri(&one).await.expect("routes");
10467        let root_two = backend.root_for_uri(&two).await.expect("routes");
10468        assert_ne!(root_one, root_two, "the same unit name routes per project");
10469        assert!(root_one.ends_with("one") && root_two.ends_with("two"));
10470        for uri in [&one, &two] {
10471            assert!(
10472                backend.analysis_for(uri).await.is_some(),
10473                "each project answers on its own, with no cross-project collision",
10474            );
10475        }
10476    }
10477
10478    /// The implicit-`src/` project (#485 — a `src/` tree with no `bynk.toml`) is
10479    /// warmed at startup too, not only lazily on first open. `resolve_root` finds
10480    /// only a `src/` *ancestor*, so the folder-is-the-root case needs the explicit
10481    /// check in `discover_projects_under`.
10482    #[tokio::test]
10483    async fn initialized_warms_an_implicit_src_project() {
10484        let s = scratch_project(
10485            "e_implicit",
10486            &[(
10487                "src/a.bynk",
10488                "commons demo.a\n\nfn f(n: Int) -> Int {\n  n\n}\n",
10489            )],
10490        );
10491        let backend = bare_backend().await;
10492        set_folders(&backend, &[&s.0]).await;
10493        backend.initialized(InitializedParams {}).await;
10494        assert_eq!(
10495            backend.state.read().await.projects.len(),
10496            1,
10497            "a rootless `src/` project is warmed at startup, not only on open",
10498        );
10499    }
10500
10501    /// Review of #677: the discovery walk must not follow a symlink cycle into a
10502    /// stack overflow — a `loop -> .` in an ordinary directory. The visited-set
10503    /// (canonicalised dirs) bounds it.
10504    #[cfg(unix)]
10505    #[tokio::test]
10506    async fn discover_projects_under_survives_a_symlink_cycle() {
10507        let s = scratch_project(
10508            "e_cycle",
10509            &[
10510                ("bynk.toml", "[project]\nname=\"p\"\n"),
10511                ("src/a.bynk", "commons p.a\n"),
10512            ],
10513        );
10514        // A directory symlink pointing back at the folder — a cycle.
10515        std::os::unix::fs::symlink(&s.0, s.0.join("loop")).ok();
10516        let roots = Backend::discover_projects_under(&s.0); // must terminate
10517        let canon = s.0.canonicalize().unwrap_or_else(|_| s.0.clone());
10518        assert!(
10519            roots.contains(&canon),
10520            "the project is found and the walk terminates despite the cycle",
10521        );
10522    }
10523
10524    /// Review of #677: with the per-query `workspace/symbol` walk dropped, a
10525    /// `bynk.toml` **created** after startup is picked up via its watcher event
10526    /// — the watcher warms the new project.
10527    #[tokio::test]
10528    async fn a_created_manifest_warms_a_new_project() {
10529        let s = scratch_project("e_created", &[("src/a.bynk", "commons p.a\n")]);
10530        std::fs::write(s.0.join("bynk.toml"), "[project]\nname=\"p\"\n").unwrap();
10531        let root = s.0.canonicalize().unwrap_or_else(|_| s.0.clone());
10532        let backend = bare_backend().await;
10533        set_folders(&backend, &[&s.0]).await;
10534        assert!(
10535            backend.state.read().await.projects.is_empty(),
10536            "no entry before the watcher fires",
10537        );
10538
10539        let toml_uri = Url::from_file_path(root.join("bynk.toml")).unwrap();
10540        backend
10541            .did_change_watched_files(DidChangeWatchedFilesParams {
10542                changes: vec![FileEvent {
10543                    uri: toml_uri,
10544                    typ: FileChangeType::CREATED,
10545                }],
10546            })
10547            .await;
10548        assert_eq!(
10549            backend.state.read().await.projects.len(),
10550            1,
10551            "a created bynk.toml warms its project via the watcher event",
10552        );
10553    }
10554
10555    /// #2081: a `bynk.schema.lock` watcher event clears that project's cached
10556    /// lock, so a rewrite the stamp cannot see (same length, same mtime: an
10557    /// edit within one mtime tick) is still read on the next round.
10558    #[tokio::test]
10559    async fn a_schema_lock_watcher_event_invalidates_the_cached_lock() {
10560        const OLD: &str = "version = 1\n# aaaa\n";
10561        const NEW: &str = "version = 1\n# bbbb\n";
10562        let s = scratch_project(
10563            "lock_watch",
10564            &[
10565                ("bynk.toml", "[project]\nname = \"p\"\n"),
10566                ("bynk.schema.lock", OLD),
10567            ],
10568        );
10569        let backend = backend_at(&s.0).await;
10570        let root = backend.test_root().await;
10571        let lock = root.join("bynk.schema.lock");
10572        let on = |text: &str| bynk_ide::SchemaLock::On {
10573            existing: Some(text.to_string()),
10574        };
10575        assert_eq!(backend.schema_lock_for(&root).await, on(OLD));
10576
10577        // Rewrite with the same length, then put the old mtime back: the
10578        // stamp is unchanged, so only the watcher can tell the cache.
10579        let mtime = std::fs::metadata(&lock).unwrap().modified().unwrap();
10580        std::fs::write(&lock, NEW).unwrap();
10581        std::fs::File::options()
10582            .write(true)
10583            .open(&lock)
10584            .unwrap()
10585            .set_modified(mtime)
10586            .unwrap();
10587        assert_eq!(
10588            backend.schema_lock_for(&root).await,
10589            on(OLD),
10590            "an unchanged stamp serves the cache"
10591        );
10592
10593        backend
10594            .did_change_watched_files(DidChangeWatchedFilesParams {
10595                changes: vec![FileEvent {
10596                    uri: Url::from_file_path(&lock).unwrap(),
10597                    typ: FileChangeType::CHANGED,
10598                }],
10599            })
10600            .await;
10601        assert_eq!(
10602            backend.schema_lock_for(&root).await,
10603            on(NEW),
10604            "the watcher event must clear the cached lock"
10605        );
10606    }
10607
10608    /// #682: a repeated route for the same URI is served from `root_cache`
10609    /// rather than re-walking the filesystem each time — a `None` route
10610    /// (single-file mode) is cached too, since it's just as stable an answer.
10611    #[tokio::test]
10612    async fn root_for_uri_populates_the_cache() {
10613        let s = scratch_project("g_cache_hit", &[("a.bynk", "commons demo.a\n")]);
10614        let uri = file_uri(&s.0, "a.bynk");
10615        let backend = bare_backend().await;
10616
10617        assert!(
10618            backend.root_for_uri(&uri).await.is_none(),
10619            "no bynk.toml and no src/ ancestor — routes to no project",
10620        );
10621        assert_eq!(
10622            backend.state.read().await.root_cache.get(&uri),
10623            Some(&None),
10624            "the miss is cached too",
10625        );
10626    }
10627
10628    /// #682 (DECISION C): a `bynk.toml` created after a URI was already routed
10629    /// (and cached) re-routes that URI once the watcher event invalidates the
10630    /// cache — a stale cached `None` must not survive the manifest's arrival.
10631    #[tokio::test]
10632    async fn a_created_manifest_invalidates_the_cached_route() {
10633        let s = scratch_project("g_cache_invalidate", &[("a.bynk", "commons p.a\n")]);
10634        let uri = file_uri(&s.0, "a.bynk");
10635        let backend = bare_backend().await;
10636
10637        assert!(
10638            backend.root_for_uri(&uri).await.is_none(),
10639            "precondition: cached as routing to no project",
10640        );
10641
10642        std::fs::write(s.0.join("bynk.toml"), "[project]\nname=\"p\"\n").unwrap();
10643        let root = s.0.canonicalize().unwrap_or_else(|_| s.0.clone());
10644        let toml_uri = Url::from_file_path(root.join("bynk.toml")).unwrap();
10645        backend
10646            .did_change_watched_files(DidChangeWatchedFilesParams {
10647                changes: vec![FileEvent {
10648                    uri: toml_uri,
10649                    typ: FileChangeType::CREATED,
10650                }],
10651            })
10652            .await;
10653
10654        assert_eq!(
10655            backend.root_for_uri(&uri).await,
10656            Some(root),
10657            "re-routes to the new project now the stale cache entry is gone",
10658        );
10659    }
10660
10661    /// #822: the guard `root_for_uri` checks before writing back a cache miss
10662    /// — an accidental `!=`-for-`==` inversion here would silently reopen the
10663    /// TOCTOU the generation counter exists to close, and the real race is too
10664    /// timing-dependent to exercise deterministically, so this pins the
10665    /// predicate directly.
10666    #[test]
10667    fn root_cache_write_is_current_rejects_a_generation_that_moved() {
10668        assert!(
10669            Backend::root_cache_write_is_current(3, 3),
10670            "no clear happened since the read — the write-back applies",
10671        );
10672        assert!(
10673            !Backend::root_cache_write_is_current(3, 4),
10674            "a clear bumped the generation since the read — the write-back must be dropped",
10675        );
10676    }
10677
10678    /// #822: both `root_cache.clear()` sites must bump `root_cache_generation`
10679    /// alongside the clear — the guard only closes the TOCTOU if every
10680    /// invalidation does both. `did_change_watched_files`'s bump is covered
10681    /// indirectly by `a_created_manifest_invalidates_the_cached_route`; this
10682    /// covers `did_change_workspace_folders`'s directly, since a regression
10683    /// dropping just that one bump would reopen the race there specifically.
10684    #[tokio::test]
10685    async fn a_workspace_folder_change_bumps_the_root_cache_generation() {
10686        let s = scratch_project("g_race_folder", &[("bynk.toml", "[project]\nname=\"p\"\n")]);
10687        let backend = bare_backend().await;
10688        let before = backend.state.read().await.root_cache_generation;
10689
10690        backend
10691            .did_change_workspace_folders(DidChangeWorkspaceFoldersParams {
10692                event: WorkspaceFoldersChangeEvent {
10693                    added: vec![WorkspaceFolder {
10694                        uri: Url::from_file_path(&s.0).unwrap(),
10695                        name: "p".into(),
10696                    }],
10697                    removed: vec![],
10698                },
10699            })
10700            .await;
10701
10702        assert!(
10703            backend.state.read().await.root_cache_generation > before,
10704            "a workspace-folder change must bump the generation, not just clear the cache",
10705        );
10706    }
10707
10708    /// A folder added at runtime is warmed the same way (the proactive scan
10709    /// slice D deferred to E), so its projects appear without an open.
10710    #[tokio::test]
10711    async fn an_added_folder_is_warmed() {
10712        let s = scratch_project(
10713            "e_added",
10714            &[
10715                ("bynk.toml", "[project]\nname=\"p\"\n"),
10716                (
10717                    "src/a.bynk",
10718                    "commons p.a\n\nfn f(n: Int) -> Int {\n  n\n}\n",
10719                ),
10720            ],
10721        );
10722        let folder = s.0.canonicalize().unwrap_or_else(|_| s.0.clone());
10723        let backend = bare_backend().await; // no folders yet
10724        assert!(backend.state.read().await.projects.is_empty());
10725
10726        backend
10727            .did_change_workspace_folders(DidChangeWorkspaceFoldersParams {
10728                event: WorkspaceFoldersChangeEvent {
10729                    added: vec![WorkspaceFolder {
10730                        uri: Url::from_file_path(&folder).unwrap(),
10731                        name: "p".into(),
10732                    }],
10733                    removed: vec![],
10734                },
10735            })
10736            .await;
10737
10738        assert_eq!(
10739            backend.state.read().await.projects.len(),
10740            1,
10741            "an added workspace folder's project is warmed proactively",
10742        );
10743    }
10744
10745    // ---- Slice F: one diagnostics scheduler ----
10746
10747    fn change_params(uri: &Url, version: i32, text: &str) -> DidChangeTextDocumentParams {
10748        DidChangeTextDocumentParams {
10749            text_document: VersionedTextDocumentIdentifier {
10750                uri: uri.clone(),
10751                version,
10752            },
10753            content_changes: vec![TextDocumentContentChangeEvent {
10754                range: None,
10755                range_length: None,
10756                text: text.to_string(),
10757            }],
10758        }
10759    }
10760
10761    /// Slice F: a **single-file** buffer (no project) now debounces by
10762    /// generation — a burst bumps the URI's generation once per change, so only
10763    /// the last-scheduled task survives its freshness check and runs `diagnose`.
10764    /// Before F single-file had no generation and ran once per keystroke.
10765    #[tokio::test]
10766    async fn a_single_file_burst_coalesces_by_generation() {
10767        // A `.bynk` file with no `bynk.toml` and no `src/` — single-file mode.
10768        let s = scratch_project("f_single", &[("a.bynk", "commons demo.a\n")]);
10769        let uri = file_uri(&s.0, "a.bynk");
10770        assert!(
10771            Backend::root_for_uri_uncached(&uri).is_none(),
10772            "precondition: the file routes to no project",
10773        );
10774        let backend = bare_backend().await;
10775        for _ in 0..3 {
10776            backend.schedule_single_file(uri.clone()).await;
10777        }
10778        assert_eq!(
10779            backend
10780                .state
10781                .read()
10782                .await
10783                .single_file_generations
10784                .get(&uri)
10785                .copied(),
10786            Some(3),
10787            "each change bumps the generation; only the third task passes its check",
10788        );
10789    }
10790
10791    /// Slice F: `did_close` clears a single-file buffer's debounce generation, so
10792    /// the map does not grow unboundedly across a session.
10793    #[tokio::test]
10794    async fn did_close_clears_the_single_file_generation() {
10795        let s = scratch_project("f_close", &[("a.bynk", "commons demo.a\n")]);
10796        let uri = file_uri(&s.0, "a.bynk");
10797        let backend = bare_backend().await;
10798        backend.schedule_single_file(uri.clone()).await;
10799        assert!(
10800            backend
10801                .state
10802                .read()
10803                .await
10804                .single_file_generations
10805                .contains_key(&uri),
10806            "the generation exists after scheduling",
10807        );
10808        backend
10809            .did_close(DidCloseTextDocumentParams {
10810                text_document: TextDocumentIdentifier { uri: uri.clone() },
10811            })
10812            .await;
10813        assert!(
10814            !backend
10815                .state
10816                .read()
10817                .await
10818                .single_file_generations
10819                .contains_key(&uri),
10820            "did_close clears the single-file generation",
10821        );
10822    }
10823
10824    /// Slice F: `did_change` in **project** mode now feeds the one generation-
10825    /// based scheduler directly (no separate pre-sleep, no second hardcoded
10826    /// debounce). A burst bumps the project's generation once per change, so a
10827    /// single round survives — coalescing, through the real handler.
10828    #[tokio::test]
10829    async fn a_project_change_burst_coalesces_through_did_change() {
10830        let src = "commons q.a\n\nfn f(x: Int) -> Int {\n  x\n}\n";
10831        let s = scratch_project(
10832            "f_burst",
10833            &[
10834                ("bynk.toml", "[project]\nname=\"q\"\n"),
10835                ("src/a.bynk", src),
10836            ],
10837        );
10838        let backend = backend_at(&s.0).await;
10839        let root = backend.test_root().await;
10840        let uri = file_uri(&s.0, "src/a.bynk");
10841        open(&backend, &uri, src).await;
10842
10843        let gen_before = {
10844            let state = backend.state.read().await;
10845            state.projects.get(&root).unwrap().analysis_generation
10846        };
10847        for v in 2..=5 {
10848            backend
10849                .did_change(change_params(
10850                    &uri,
10851                    v,
10852                    &format!("{}{src}", "\n".repeat(v as usize)),
10853                ))
10854                .await;
10855        }
10856        let gen_after = {
10857            let state = backend.state.read().await;
10858            state.projects.get(&root).unwrap().analysis_generation
10859        };
10860        assert_eq!(
10861            gen_after - gen_before,
10862            4,
10863            "each of the four changes bumps the generation once — only the last \
10864             scheduled round runs (no per-change round, no stacked debounce)",
10865        );
10866    }
10867
10868    // -- #596: store-map query vocabulary, end to end through `completion` ----
10869    //
10870    // The unit tests in `completion.rs`/`kernel_methods.rs`/`store_ops.rs`
10871    // cover each half in isolation; a #812 review flagged the gap that no test
10872    // drove a real `textDocument/completion` request through `Backend` to
10873    // check the two halves actually merge (and, separately, that the
10874    // provenance-based half survives a project-wide resolve failure that
10875    // blanks `type_receiver`). These close both.
10876
10877    fn completion_labels(response: Option<CompletionResponse>) -> Vec<String> {
10878        match response {
10879            Some(CompletionResponse::Array(items)) => items.into_iter().map(|i| i.label).collect(),
10880            Some(CompletionResponse::List(list)) => {
10881                list.items.into_iter().map(|i| i.label).collect()
10882            }
10883            None => Vec::new(),
10884        }
10885    }
10886
10887    async fn complete_at(backend: &Backend, uri: &Url, text: &str, needle: &str) -> Vec<String> {
10888        let offset = text.find(needle).expect("needle present") + needle.len();
10889        let pos = crate::position::offset_to_position(text, offset);
10890        let response = backend
10891            .completion(CompletionParams {
10892                text_document_position: TextDocumentPositionParams {
10893                    text_document: TextDocumentIdentifier { uri: uri.clone() },
10894                    position: pos,
10895                },
10896                work_done_progress_params: Default::default(),
10897                partial_result_params: Default::default(),
10898                context: None,
10899            })
10900            .await
10901            .expect("completion must not error");
10902        completion_labels(response)
10903    }
10904
10905    async fn complete_items(
10906        backend: &Backend,
10907        uri: &Url,
10908        text: &str,
10909        needle: &str,
10910        trigger: Option<&str>,
10911    ) -> Vec<CompletionItem> {
10912        let offset = text.find(needle).expect("needle present") + needle.len();
10913        let response = backend
10914            .completion(CompletionParams {
10915                text_document_position: TextDocumentPositionParams {
10916                    text_document: TextDocumentIdentifier { uri: uri.clone() },
10917                    position: crate::position::offset_to_position(text, offset),
10918                },
10919                work_done_progress_params: Default::default(),
10920                partial_result_params: Default::default(),
10921                context: trigger.map(|c| CompletionContext {
10922                    trigger_kind: CompletionTriggerKind::TRIGGER_CHARACTER,
10923                    trigger_character: Some(c.to_string()),
10924                }),
10925            })
10926            .await
10927            .expect("completion must not error");
10928        match response {
10929            Some(CompletionResponse::Array(items)) => items,
10930            Some(CompletionResponse::List(list)) => list.items,
10931            None => Vec::new(),
10932        }
10933    }
10934
10935    /// #2458: `[` in a doc comment offers the names a doc link resolves, in
10936    /// resolution order, inserting `Name]`; `[RateView.` offers its fields; a
10937    /// `[` in code (the trigger character) offers nothing.
10938    #[tokio::test]
10939    async fn doc_link_completion_offers_linkable_names_inside_doc_ranges_only() {
10940        let src = "commons shop.rates\n\n---\nFields: [\n---\ntype RateView = { remaining: Int, limit: Int }\n\n---\nDecides. See [\n---\nfn decide(x: Int) -> Int {\n  x\n}\n\n---\nOwner [RateView.\n---\nfn other(x: Int) -> Int {\n  let xs = [1, 2]\n  x\n}\n";
10941        let s = scratch_project(
10942            "doc_link_completion",
10943            &[
10944                ("bynk.toml", "[project]\nname=\"shop\"\n"),
10945                ("src/a.bynk", src),
10946            ],
10947        );
10948        let backend = backend_at(&s.0).await;
10949        let uri = file_uri(&s.0, "src/a.bynk");
10950        open(&backend, &uri, src).await;
10951        backend.run_round().await;
10952
10953        let items = complete_items(&backend, &uri, src, "See [", Some("[")).await;
10954        let labels: Vec<_> = items.iter().map(|i| i.label.as_str()).collect();
10955        // `decide`'s own parameter comes first, then the unit scope.
10956        assert_eq!(labels, ["x", "RateView", "decide", "other"], "{labels:?}");
10957        assert_eq!(items[0].kind, Some(CompletionItemKind::VARIABLE));
10958        let Some(CompletionTextEdit::Edit(edit)) = &items[1].text_edit else {
10959            panic!("a text edit: {:?}", items[1]);
10960        };
10961        assert_eq!(edit.new_text, "RateView]");
10962        assert_eq!(items[1].kind, Some(CompletionItemKind::STRUCT));
10963
10964        let members = complete_items(&backend, &uri, src, "[RateView.", Some(".")).await;
10965        let labels: Vec<_> = members.iter().map(|i| i.label.as_str()).collect();
10966        assert_eq!(labels, ["limit", "remaining"], "{labels:?}");
10967
10968        // Inside `RateView`'s own doc its fields come first.
10969        let own = complete_items(&backend, &uri, src, "Fields: [", Some("[")).await;
10970        let labels: Vec<_> = own.iter().map(|i| i.label.as_str()).collect();
10971        assert_eq!(
10972            labels,
10973            ["remaining", "limit", "RateView", "decide", "other"],
10974            "{labels:?}"
10975        );
10976        assert_eq!(own[0].kind, Some(CompletionItemKind::FIELD));
10977
10978        let in_code = complete_items(&backend, &uri, src, "[1, 2", Some("[")).await;
10979        assert!(
10980            in_code.is_empty(),
10981            "`[` in code offers nothing: {in_code:?}"
10982        );
10983        let typed = complete_items(&backend, &uri, src, "let xs = [", Some("[")).await;
10984        assert!(typed.is_empty(), "`[` in code offers nothing: {typed:?}");
10985    }
10986
10987    /// #2458: the committed round is stale once `[` is typed, so the cursor
10988    /// context's live offsets must be mapped into it — own parts still come first.
10989    #[tokio::test]
10990    async fn doc_link_completion_offers_own_parts_from_a_stale_round() {
10991        let v1 =
10992            "commons shop.rates\n\n---\nDecides. See \n---\nfn decide(x: Int) -> Int {\n  x\n}\n";
10993        let v2 = v1.replace("See ", "See [");
10994        let s = scratch_project(
10995            "doc_link_completion_stale",
10996            &[
10997                ("bynk.toml", "[project]\nname=\"shop\"\n"),
10998                ("src/a.bynk", v1),
10999            ],
11000        );
11001        let backend = backend_at(&s.0).await;
11002        let (uri, rel) = open_round_edit(&backend, &s.0, v1, &v2).await;
11003        assert_eq!(
11004            backend.test_analysis().await.unwrap().versions.get(&rel),
11005            Some(&1),
11006            "cached round is stale",
11007        );
11008        let items = complete_items(&backend, &uri, &v2, "See [", Some("[")).await;
11009        let labels: Vec<_> = items.iter().map(|i| i.label.as_str()).collect();
11010        assert_eq!(labels, ["x", "decide"], "{labels:?}");
11011        assert_eq!(items[0].detail.as_deref(), Some("parameter"));
11012    }
11013
11014    #[test]
11015    fn live_to_snapshot_offset_maps_across_an_earlier_edit_only() {
11016        let snap = "a b\nname";
11017        let live = "a [b\nname";
11018        assert_eq!(
11019            live_to_snapshot_offset(live, snap, live.find("name").unwrap()),
11020            Some(4)
11021        );
11022        // An offset inside the edited region cannot be mapped.
11023        assert_eq!(live_to_snapshot_offset(live, snap, 0), None);
11024        // An edit after the offset also changes the tail.
11025        assert_eq!(live_to_snapshot_offset("a b\nname!", snap, 4), None);
11026        assert_eq!(live_to_snapshot_offset(snap, snap, 4), Some(4));
11027    }
11028
11029    /// A `store Map` field's `.` completion merges both halves in one
11030    /// response: the `Query` kernel methods (`filter`, `collect`, …) from
11031    /// `kernel_methods::methods_for`, and the store-field vocabulary (entry
11032    /// ops + accessors) from the provenance-based path — driven through the
11033    /// real `Backend::completion`, not the pure helpers directly.
11034    #[tokio::test]
11035    async fn store_map_receiver_completion_merges_both_vocabularies() {
11036        let src = "context shop\n\nagent Inventory {\n  key id: String\n  store items: Map[String, Int]\n\n  on call f() -> Effect[()] {\n    items.\n  }\n}\n";
11037        let s = scratch_project(
11038            "store_map_merge",
11039            &[
11040                ("bynk.toml", "[project]\nname=\"shop\"\n"),
11041                ("src/a.bynk", src),
11042            ],
11043        );
11044        let backend = backend_at(&s.0).await;
11045        let uri = file_uri(&s.0, "src/a.bynk");
11046        open(&backend, &uri, src).await;
11047        backend.run_round().await;
11048
11049        let labels = complete_at(&backend, &uri, src, "    items.").await;
11050        assert!(
11051            labels.contains(&"filter".to_string()),
11052            "the Query kernel vocabulary: {labels:?}"
11053        );
11054        assert!(
11055            labels.contains(&"collect".to_string()),
11056            "the Query kernel vocabulary: {labels:?}"
11057        );
11058        assert!(
11059            labels.contains(&"put".to_string()),
11060            "the store entry ops: {labels:?}"
11061        );
11062        assert!(
11063            labels.contains(&"entries".to_string()),
11064            "the Map query accessors: {labels:?}"
11065        );
11066    }
11067
11068    /// #2010: inside `let <pattern> … else match { … }`, arm-start completion
11069    /// offers the value's variants minus the one the pattern already matches —
11070    /// through the real `Backend::completion`, for `=` and for `<-` (whose
11071    /// `Effect` payload is what the arms match).
11072    #[tokio::test]
11073    async fn let_else_match_offers_the_residual_variants() {
11074        let src = "context shop\n\nfn f(r: Result[Int, String]) -> Int {\n  let Ok(n) = r else match {\n    Err(e) => 0,\n  }\n  n\n}\n\nfn g(o: Option[Int]) -> Effect[Int] {\n  let Some(m) <- Effect.pure(o) else match {\n    None => 0,\n  }\n  m\n}\n";
11075        let s = scratch_project(
11076            "let_else_match_residual",
11077            &[
11078                ("bynk.toml", "[project]\nname=\"shop\"\n"),
11079                ("src/shop.bynk", src),
11080            ],
11081        );
11082        let backend = backend_at(&s.0).await;
11083        let uri = file_uri(&s.0, "src/shop.bynk");
11084        open(&backend, &uri, src).await;
11085        backend.run_round().await;
11086
11087        let labels = complete_at(&backend, &uri, src, "r else match {\n    ").await;
11088        assert!(labels.contains(&"Err".to_string()), "{labels:?}");
11089        assert!(
11090            !labels.contains(&"Ok".to_string()),
11091            "`Ok(n)` covers `Ok`: {labels:?}"
11092        );
11093
11094        let labels = complete_at(&backend, &uri, src, "pure(o) else match {\n    ").await;
11095        assert!(labels.contains(&"None".to_string()), "{labels:?}");
11096        assert!(
11097            !labels.contains(&"Some".to_string()),
11098            "`Some(m)` covers `Some`: {labels:?}"
11099        );
11100    }
11101
11102    /// An unresolved type name elsewhere in the same file — in an unrelated
11103    /// `type` declaration, not even the agent using `items` — trips the
11104    /// *resolve* gate. That once blanked `expr_types` for the **whole file**
11105    /// (the one clean-file-ceiling gap ADR 0094 didn't close), and before the
11106    /// #812 review fix `value_member_completions` then returned early and
11107    /// never reached the store-field path. Since #1663 (Decision A) the
11108    /// checker runs past a resolve error, so both halves survive: the typed
11109    /// `Query` kernel methods and the store-field entry ops/accessors.
11110    #[tokio::test]
11111    async fn store_field_vocabulary_survives_an_unrelated_resolve_failure() {
11112        let src = "context shop\n\ntype Bad = { x: NoSuchType }\n\nagent Inventory {\n  key id: String\n  store items: Map[String, Int]\n\n  on call f() -> Effect[()] {\n    items.\n  }\n}\n";
11113        let s = scratch_project(
11114            "store_map_resolve_gap",
11115            &[
11116                ("bynk.toml", "[project]\nname=\"shop\"\n"),
11117                ("src/a.bynk", src),
11118            ],
11119        );
11120        let backend = backend_at(&s.0).await;
11121        let uri = file_uri(&s.0, "src/a.bynk");
11122        open(&backend, &uri, src).await;
11123        backend.run_round().await;
11124
11125        // Precondition: the round really did fail to type this file (the
11126        // fixture actually reaches the ceiling this test is about, rather
11127        // than passing vacuously because the file happened to check fine).
11128        let analysis = backend.test_analysis().await.expect("a round committed");
11129        let rel = Backend::uri_to_rel(&analysis, &uri).expect("uri resolves");
11130        assert!(
11131            analysis
11132                .diagnostics
11133                .get(&rel)
11134                .is_some_and(|ds| !ds.is_empty()),
11135            "the fixture must actually fail to check — an undeclared return \
11136             type is the trigger this test exercises",
11137        );
11138
11139        let labels = complete_at(&backend, &uri, src, "    items.").await;
11140        // #1663: the resolve error in `Bad` no longer blanks the agent's types,
11141        // so the typed half (`Query` kernel methods) survives too.
11142        assert!(
11143            labels.contains(&"filter".to_string()),
11144            "an unrelated resolve error must not blank the typed half: {labels:?}"
11145        );
11146        assert!(
11147            labels.contains(&"put".to_string()),
11148            "store entry ops must survive an unrelated resolve failure: {labels:?}"
11149        );
11150        assert!(
11151            labels.contains(&"entries".to_string()),
11152            "Map query accessors must survive an unrelated resolve failure: {labels:?}"
11153        );
11154    }
11155
11156    /// Content-ownership track (#1086) §8's "done when": an unsaved edit in
11157    /// file A is visible to a completion triggered from file B — driven
11158    /// through a real `Backend` (`did_open`/`did_change` → `completion`),
11159    /// not the pure `bynk_ide` helpers directly. `shared/widget.bynk`
11160    /// declares `Widget` with one field on disk; opening it and editing its
11161    /// buffer (never saved) to add a second field must be visible to
11162    /// `app/use.bynk`'s cross-file record-construction completion
11163    /// (`Widget { <cursor>`, via `record_field_names`/`project_content`) in
11164    /// the very same round. This exercises the sweep both files' rounds
11165    /// share, not `type_receiver` specifically — see
11166    /// `type_receivers_slow_path_sees_a_closed_files_disk_content` below for
11167    /// that path's own dedicated coverage (a review of this PR found this
11168    /// test alone doesn't reach it).
11169    #[tokio::test]
11170    async fn an_unsaved_edit_in_one_file_is_visible_to_completion_in_another() {
11171        let widget_v1 = "commons shared.widget\n\ntype Widget = { size: Int }\n";
11172        let widget_v2 = "commons shared.widget\n\ntype Widget = { size: Int, weight: Int }\n";
11173        let use_src =
11174            "commons app.use\n\nuses shared.widget\n\nfn make() -> Widget {\n  Widget { \n}\n";
11175        let s = scratch_project(
11176            "cross_file_unsaved",
11177            &[
11178                (
11179                    "bynk.toml",
11180                    "[project]\nname = \"cross\"\n\n[paths]\ninclude = [\"shared\", \"app\"]\n",
11181                ),
11182                ("shared/widget.bynk", widget_v1),
11183                ("app/use.bynk", use_src),
11184            ],
11185        );
11186        let backend = backend_at(&s.0).await;
11187        let widget_uri = file_uri(&s.0, "shared/widget.bynk");
11188        let use_uri = file_uri(&s.0, "app/use.bynk");
11189        open(&backend, &widget_uri, widget_v1).await;
11190        open(&backend, &use_uri, use_src).await;
11191        backend.run_round().await;
11192
11193        // Precondition: before the edit, only the on-disk field completes.
11194        let before = complete_at(&backend, &use_uri, use_src, "  Widget { ").await;
11195        assert!(before.contains(&"size".to_string()), "{before:?}");
11196        assert!(
11197            !before.contains(&"weight".to_string()),
11198            "the fixture must not already have `weight` on disk: {before:?}"
11199        );
11200
11201        // Edit `widget.bynk`'s buffer — never saved to disk — to add `weight`.
11202        backend
11203            .did_change(DidChangeTextDocumentParams {
11204                text_document: VersionedTextDocumentIdentifier {
11205                    uri: widget_uri.clone(),
11206                    version: 2,
11207                },
11208                content_changes: vec![TextDocumentContentChangeEvent {
11209                    range: None,
11210                    range_length: None,
11211                    text: widget_v2.to_string(),
11212                }],
11213            })
11214            .await;
11215
11216        let after = complete_at(&backend, &use_uri, use_src, "  Widget { ").await;
11217        assert!(
11218            after.contains(&"weight".to_string()),
11219            "an unsaved edit to `widget.bynk` must be visible to `use.bynk`'s \
11220             cross-file completion in the same round: {after:?}"
11221        );
11222        assert!(after.contains(&"size".to_string()), "{after:?}");
11223
11224        // On-disk content is untouched — the visibility came from the buffer.
11225        assert_eq!(
11226            std::fs::read_to_string(s.0.join("shared/widget.bynk")).unwrap(),
11227            widget_v1,
11228            "the edit must never have been saved to disk"
11229        );
11230    }
11231
11232    /// Content-ownership track (#1086) slice 5: dedicated coverage for
11233    /// `type_receiver`'s slow path specifically (the fix a PR review found
11234    /// the test above doesn't reach — `Widget { ` completion never calls
11235    /// `type_receiver` at all, it's pure syntax via `record_field_names`).
11236    /// `widget.bynk` is **never opened** — closed, on-disk only — so its
11237    /// content can only reach `w.`'s value-member completion in
11238    /// `use.bynk` through `type_receiver`'s own `sweep_project_content`
11239    /// call, not through any open-buffer overlay. No round runs before the
11240    /// request either, so `project_analysis_for`'s fast-path cache is empty
11241    /// and `type_receiver` must take its slow, re-analysing path — the one
11242    /// this slice fixed.
11243    #[tokio::test]
11244    async fn type_receivers_slow_path_sees_a_closed_files_disk_content() {
11245        let widget_src = "commons shared.widget\n\ntype Widget = { size: Int }\n";
11246        let use_src =
11247            "commons app.use\n\nuses shared.widget\n\nfn area(w: Widget) -> Int {\n  w.\n}\n";
11248        let s = scratch_project(
11249            "type_receiver_slow_path",
11250            &[
11251                (
11252                    "bynk.toml",
11253                    "[project]\nname = \"cross\"\n\n[paths]\ninclude = [\"shared\", \"app\"]\n",
11254                ),
11255                ("shared/widget.bynk", widget_src),
11256                ("app/use.bynk", use_src),
11257            ],
11258        );
11259        let backend = backend_at(&s.0).await;
11260        let use_uri = file_uri(&s.0, "app/use.bynk");
11261        // `widget.bynk` is deliberately never opened — no did_open, no round.
11262        open(&backend, &use_uri, use_src).await;
11263
11264        let labels = complete_at(&backend, &use_uri, use_src, "  w.").await;
11265        assert!(
11266            labels.contains(&"size".to_string()),
11267            "type_receiver's slow path must resolve `w: Widget` off the \
11268             closed widget.bynk's real disk content: {labels:?}"
11269        );
11270    }
11271}
11272
11273#[cfg(test)]
11274mod owner_cache_tests {
11275    use super::cached_owner_unit;
11276    use std::collections::HashMap;
11277    use std::path::PathBuf;
11278
11279    fn file(text: &str) -> bynk_ide::FileDiagnostics {
11280        bynk_ide::FileDiagnostics {
11281            source_path: PathBuf::from("src/a.bynk"),
11282            text: text.to_string(),
11283            diagnostics: Vec::new(),
11284        }
11285    }
11286
11287    /// #3243 S0: the owner unit is read once per distinct text, and follows an edit
11288    /// that renames the unit; a file with no parseable unit has no owner.
11289    #[test]
11290    fn the_owner_unit_is_cached_per_text_and_follows_an_edit() {
11291        let mut cache = HashMap::new();
11292        assert_eq!(
11293            cached_owner_unit(&mut cache, &file("commons shop.a\n")),
11294            Some("shop.a")
11295        );
11296        let (hash, _) = cache[&PathBuf::from("src/a.bynk")].clone();
11297        // The same text is a hit: the entry is untouched.
11298        assert_eq!(
11299            cached_owner_unit(&mut cache, &file("commons shop.a\n")),
11300            Some("shop.a")
11301        );
11302        assert_eq!(cache[&PathBuf::from("src/a.bynk")].0, hash);
11303        // A renamed unit is a different text, so a fresh read.
11304        assert_eq!(
11305            cached_owner_unit(&mut cache, &file("commons shop.b\n")),
11306            Some("shop.b")
11307        );
11308        // Unparseable text: no owner, and the miss is remembered.
11309        assert_eq!(cached_owner_unit(&mut cache, &file("\u{1}\u{1}")), None);
11310    }
11311}
11312
11313#[cfg(test)]
11314mod analysis_memo_tests {
11315    use super::analyse_with_memo;
11316    use bynk_check::memo::AnalysisMemo;
11317    use std::sync::{Arc, Mutex};
11318
11319    /// #3243 S2.3b: a memo poisoned by a panic is emptied, and the poison is
11320    /// cleared, so the rounds after it keep what they learn.
11321    #[test]
11322    fn a_poisoned_memo_is_emptied_and_then_works_again() {
11323        let root =
11324            std::env::temp_dir().join(format!("bynk-lsp-memo-poison-{}", std::process::id()));
11325        let _ = std::fs::remove_dir_all(&root);
11326        std::fs::create_dir_all(&root).unwrap();
11327        std::fs::write(root.join("bynk.toml"), "").unwrap();
11328        let src = "context demo\n\nservice probe {\n  on call(n: Int) -> Effect[Int] by Caller {\n    n\n  }\n}\n";
11329        std::fs::write(root.join("demo.bynk"), src).unwrap();
11330        let roots = bynk_ide::AnalysisRoots::SingleTree(root.clone());
11331        let content = std::collections::HashMap::from([(root.join("demo.bynk"), src.to_string())]);
11332
11333        let memo = Arc::new(Mutex::new(AnalysisMemo::new()));
11334        let round = |memo: &Arc<Mutex<AnalysisMemo>>| {
11335            analyse_with_memo(&roots, &content, &bynk_ide::SchemaLock::Off, Some(memo));
11336            memo.lock().unwrap().stats()
11337        };
11338        assert!(round(&memo).misses > 0, "the first round checks the file");
11339        assert_eq!(round(&memo).misses, 0, "the second replays it");
11340
11341        // Poison it the way a panicking round would.
11342        let poisoner = Arc::clone(&memo);
11343        let _ = std::thread::spawn(move || {
11344            let _guard = poisoner.lock().unwrap();
11345            panic!("injected");
11346        })
11347        .join();
11348        assert!(memo.is_poisoned());
11349
11350        let after = round(&memo);
11351        assert!(!memo.is_poisoned(), "the poison is cleared");
11352        assert!(
11353            after.misses > 0,
11354            "the recovered memo started empty: {after:?}"
11355        );
11356        assert_eq!(
11357            round(&memo).misses,
11358            0,
11359            "and keeps what it learns afterwards"
11360        );
11361        let _ = std::fs::remove_dir_all(&root);
11362    }
11363}