Skip to main content

aft/lsp/
manager.rs

1use std::collections::{HashMap, HashSet};
2use std::path::{Path, PathBuf};
3
4use crossbeam_channel::{unbounded, Receiver, RecvTimeoutError, Sender};
5use lsp_types::notification::{
6    DidChangeTextDocument, DidChangeWatchedFiles, DidCloseTextDocument, DidOpenTextDocument,
7};
8use lsp_types::{
9    DidChangeTextDocumentParams, DidChangeWatchedFilesParams, DidCloseTextDocumentParams,
10    DidOpenTextDocumentParams, FileChangeType, FileEvent, TextDocumentContentChangeEvent,
11    TextDocumentIdentifier, TextDocumentItem, VersionedTextDocumentIdentifier,
12};
13
14use crate::config::Config;
15use crate::lsp::child_registry::LspChildRegistry;
16use crate::lsp::client::{LspClient, LspEvent, ServerState};
17use crate::lsp::diagnostics::{
18    from_lsp_diagnostics, DiagnosticEntry, DiagnosticsStore, StoredDiagnostic,
19};
20use crate::lsp::document::DocumentStore;
21use crate::lsp::position::{uri_for_path, uri_to_path};
22use crate::lsp::pull_params::{
23    AftDocumentDiagnosticParams, AftDocumentDiagnosticRequest, AftWorkspaceDiagnosticParams,
24    AftWorkspaceDiagnosticRequest,
25};
26use crate::lsp::registry::{resolve_lsp_binary, servers_for_file, ServerDef, ServerKind};
27use crate::lsp::roots::ServerKey;
28use crate::lsp::LspError;
29use crate::slog_error;
30
31const STDERR_REASON_BYTES: usize = 2 * 1024;
32
33/// Outcome of attempting to ensure a server is running for a single matching
34/// `ServerDef`. Returned per matching server so the caller can report exactly
35/// what happened to the user instead of collapsing all failures into "no
36/// server".
37#[derive(Debug, Clone)]
38pub enum ServerAttemptResult {
39    /// Server is running and ready to serve requests for this file.
40    Ok { server_key: ServerKey },
41    /// No workspace root was found by walking up from the file looking for
42    /// any of the server's configured root markers.
43    NoRootMarker { looked_for: Vec<String> },
44    /// The server's binary could not be found on PATH (or override was
45    /// missing/invalid).
46    BinaryNotInstalled { binary: String },
47    /// Binary was found but spawning or initializing the server failed.
48    SpawnFailed { binary: String, reason: String },
49}
50
51/// One server's attempt to handle a file.
52#[derive(Debug, Clone)]
53pub struct ServerAttempt {
54    /// Stable server identifier (kind ID, e.g. "pyright", "rust-analyzer").
55    pub server_id: String,
56    /// Server display name from the registry.
57    pub server_name: String,
58    pub result: ServerAttemptResult,
59}
60
61/// Aggregate outcome of `ensure_server_for_file_detailed`. Distinguishes:
62/// - "No server registered for this file's extension" (`attempts.is_empty()`)
63/// - "Servers registered but none could start" (`successful.is_empty()` but
64///   `!attempts.is_empty()`)
65/// - "At least one server is ready" (`!successful.is_empty()`)
66#[derive(Debug, Clone, Default)]
67pub struct EnsureServerOutcomes {
68    /// Server keys that are now running and ready to serve requests.
69    pub successful: Vec<ServerKey>,
70    /// Per-server attempt records. Empty if no server is registered for the
71    /// file's extension.
72    pub attempts: Vec<ServerAttempt>,
73}
74
75impl EnsureServerOutcomes {
76    /// True if no server in the registry matched this file's extension.
77    pub fn no_server_registered(&self) -> bool {
78        self.attempts.is_empty()
79    }
80
81    /// True when servers matched the file's extension but none actually apply
82    /// to this project — i.e. nothing started and every attempt failed the root
83    /// marker check (e.g. oxlint registered for `.ts` with no `.oxlintrc.json`).
84    /// Distinct from `no_server_registered` (extension unsupported) and from a
85    /// real outage (binary missing / spawn failed): a missing root marker is a
86    /// filesystem fact that never changes mid-scan, so such a file will never
87    /// produce diagnostics and must not be reported as "pending".
88    pub fn only_inapplicable_root_markers(&self) -> bool {
89        self.successful.is_empty()
90            && !self.attempts.is_empty()
91            && self
92                .attempts
93                .iter()
94                .all(|attempt| matches!(attempt.result, ServerAttemptResult::NoRootMarker { .. }))
95    }
96}
97
98/// Outcome of a post-edit diagnostics wait. Reports the per-server status
99/// alongside the fresh diagnostics, so the response layer can build an
100/// honest tri-state payload (`success: true` + `complete: bool` + named
101/// gap fields per `crates/aft/src/protocol.rs`).
102///
103/// `diagnostics` only contains entries from servers that proved freshness
104/// (version-match preferred, epoch-fallback for unversioned servers).
105/// Pre-edit cached entries are NEVER included — that's the whole point of
106/// this type.
107#[derive(Debug, Clone, Default)]
108pub struct PostEditWaitOutcome {
109    /// Diagnostics from servers whose response we verified is FOR the
110    /// post-edit document version (or whose epoch we saw advance after our
111    /// pre-edit snapshot, for unversioned servers).
112    pub diagnostics: Vec<StoredDiagnostic>,
113    /// Servers we expected to publish but didn't before the deadline.
114    /// Reported to the agent via `pending_lsp_servers` so they understand
115    /// the result is partial.
116    pub pending_servers: Vec<ServerKey>,
117    /// Servers whose process exited between notification and deadline.
118    /// Reported separately so the agent knows the gap is unrecoverable
119    /// without a server restart, not "wait longer."
120    pub exited_servers: Vec<ServerKey>,
121}
122
123/// Pre-edit freshness snapshot for one server/file pair.
124#[derive(Debug, Clone, Copy, Default)]
125pub struct PreEditSnapshot {
126    pub epoch: u64,
127    pub document_version_at_capture: Option<i32>,
128}
129
130#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
131pub struct StaleDiagnosticsMark {
132    pub had_entries: bool,
133    pub changed: bool,
134}
135
136pub fn post_edit_entry_is_fresh(
137    entry: &DiagnosticEntry,
138    target_version: i32,
139    pre: PreEditSnapshot,
140) -> bool {
141    if entry.stale || entry.epoch <= pre.epoch {
142        return false;
143    }
144
145    match entry.version {
146        Some(version) => version >= target_version,
147        // Unversioned publishDiagnostics payloads cannot prove which document
148        // state they describe. Epoch advancement only proves arrival order; an
149        // old analysis result can still arrive after our pre-snapshot. Treat as
150        // pending/partial rather than fresh.
151        None => false,
152    }
153}
154
155impl PostEditWaitOutcome {
156    /// True if every expected server reported a fresh result. False means
157    /// the agent should treat the diagnostics as a partial picture.
158    pub fn complete(&self) -> bool {
159        self.pending_servers.is_empty() && self.exited_servers.is_empty()
160    }
161}
162
163/// Per-server outcome of a `textDocument/diagnostic` (per-file pull) request.
164#[derive(Debug, Clone)]
165pub enum PullFileOutcome {
166    /// Server returned a full report; diagnostics stored.
167    Full { diagnostic_count: usize },
168    /// Server returned `kind: "unchanged"` — cached diagnostics still valid.
169    Unchanged,
170    /// Server returned a partial-result token; we don't subscribe to streamed
171    /// progress so the response is treated as a soft empty until the next pull.
172    PartialNotSupported,
173    /// Server doesn't advertise pull capability — caller should fall back to
174    /// push diagnostics for this server.
175    PullNotSupported,
176    /// The pull request failed (timeout, server error, etc.).
177    RequestFailed { reason: String },
178}
179
180/// Result of ensuring a document is open in every matching server.
181#[derive(Debug, Clone, Default)]
182pub struct EnsureFileOpenResult {
183    pub server_keys: Vec<ServerKey>,
184    /// Servers that received `textDocument/didOpen` during this call.
185    pub newly_opened: Vec<ServerKey>,
186}
187
188impl EnsureFileOpenResult {
189    pub fn is_empty(&self) -> bool {
190        self.server_keys.is_empty()
191    }
192}
193
194/// Result of `pull_file_diagnostics` for one matching server.
195#[derive(Debug, Clone)]
196pub struct PullFileResult {
197    pub server_key: ServerKey,
198    pub outcome: PullFileOutcome,
199}
200
201pub(crate) struct TrackedPullFileResult {
202    pub results: Vec<PullFileResult>,
203    pub newly_opened: Vec<ServerKey>,
204}
205
206/// Result of `pull_workspace_diagnostics` for a single server.
207#[derive(Debug, Clone)]
208pub struct PullWorkspaceResult {
209    pub server_key: ServerKey,
210    /// Files for which a Full report was received and cached. Files that came
211    /// back as `Unchanged` are NOT listed here because their cached entry was
212    /// already authoritative.
213    pub files_reported: Vec<PathBuf>,
214    /// True if the server returned a full response within the timeout.
215    pub complete: bool,
216    /// True if we cancelled (request timed out before the server responded).
217    pub cancelled: bool,
218    /// True if the server advertised workspace pull support. When false, the
219    /// other fields are empty and the caller should fall back to file-mode
220    /// pull or to push semantics.
221    pub supports_workspace: bool,
222}
223
224pub struct DrainedLspEvents {
225    pub events: Vec<LspEvent>,
226    pub diagnostics_changed: bool,
227    pub has_more: bool,
228}
229
230impl IntoIterator for DrainedLspEvents {
231    type Item = LspEvent;
232    type IntoIter = std::vec::IntoIter<LspEvent>;
233
234    fn into_iter(self) -> Self::IntoIter {
235        self.events.into_iter()
236    }
237}
238
239pub struct LspManager {
240    /// Active server instances, keyed by (ServerKind, workspace_root).
241    clients: HashMap<ServerKey, LspClient>,
242    /// Binary names for active server instances. Kept separate from
243    /// `LspClient` so crash handling can report the installable binary name
244    /// after a post-initialize process exit.
245    server_binaries: HashMap<ServerKey, String>,
246    /// Tracks opened documents and versions per active server.
247    documents: HashMap<ServerKey, DocumentStore>,
248    /// Stored publishDiagnostics payloads across all servers.
249    diagnostics: DiagnosticsStore,
250    /// Unified event channel — all server reader threads send here.
251    event_tx: Sender<LspEvent>,
252    event_rx: Receiver<LspEvent>,
253    /// Optional binary path overrides used by integration tests.
254    binary_overrides: HashMap<ServerKind, PathBuf>,
255    /// Extra env vars merged into every spawned LSP child. Used in tests to
256    /// drive the fake server's behavioral variants (`AFT_FAKE_LSP_PULL=1`,
257    /// `AFT_FAKE_LSP_WORKSPACE=1`, etc.). Production code does not set this.
258    extra_env: HashMap<String, String>,
259    /// Per-(kind,root) cache of spawn failures. Once a server fails to spawn
260    /// for a workspace root, we remember why and skip subsequent attempts for
261    /// the lifetime of this AFT process. Without this, every file open or
262    /// didChange retries `spawn_server` and logs a fresh ERROR — visible as
263    /// repeated `failed to spawn TypeScript Language Server: Could not find a
264    /// valid TypeScript installation` lines per edit.
265    ///
266    /// Entries are NEVER evicted automatically. The expected recovery path is
267    /// for the user to fix their environment (install the missing binary or
268    /// add a `tsconfig.json` / `package.json` with the right dependency) and
269    /// restart OpenCode/Pi, which spawns a fresh `aft` process with an empty
270    /// cache. We deliberately don't auto-retry on file events: the failure
271    /// modes we track here (binary not installed, init handshake failure)
272    /// don't fix themselves at runtime.
273    failed_spawns: HashMap<ServerKey, ServerAttemptResult>,
274    /// Server/root pairs for which we already logged that watched-file
275    /// notifications are skipped because the capability is absent.
276    watched_file_skip_logged: HashSet<ServerKey>,
277    /// Tracks PIDs of spawned LSP child processes so the signal handler can
278    /// kill them on SIGTERM/SIGINT before aft exits, preventing orphans.
279    /// Defaults to empty; production wires this from `AppContext`.
280    child_registry: LspChildRegistry,
281}
282
283impl LspManager {
284    pub fn new() -> Self {
285        let (event_tx, event_rx) = unbounded();
286        Self {
287            clients: HashMap::new(),
288            server_binaries: HashMap::new(),
289            documents: HashMap::new(),
290            diagnostics: DiagnosticsStore::new(),
291            event_tx,
292            event_rx,
293            binary_overrides: HashMap::new(),
294            extra_env: HashMap::new(),
295            failed_spawns: HashMap::new(),
296            watched_file_skip_logged: HashSet::new(),
297            child_registry: LspChildRegistry::new(),
298        }
299    }
300
301    /// Set the child-PID registry. Must be called before any servers spawn.
302    pub fn set_child_registry(&mut self, registry: LspChildRegistry) {
303        self.child_registry = registry;
304    }
305
306    /// For testing: set an extra environment variable that gets passed to
307    /// every spawned LSP child process. Useful for driving fake-server
308    /// behavioral variants in integration tests.
309    pub fn set_extra_env(&mut self, key: &str, value: &str) {
310        self.extra_env.insert(key.to_string(), value.to_string());
311    }
312
313    /// Count active LSP server instances.
314    pub fn server_count(&self) -> usize {
315        self.clients.len()
316    }
317
318    /// Estimate the per-server document metadata and diagnostics retained by
319    /// the manager. LSP child-process memory is outside this process RSS and is
320    /// not included.
321    pub fn estimated_memory(&self) -> crate::memory::MemoryEstimate {
322        let mut bytes = 0u64;
323        let mut document_count = 0u64;
324        for documents in self.documents.values() {
325            let estimate = documents.estimated_memory();
326            bytes = bytes.saturating_add(estimate.estimated_bytes.unwrap_or(0));
327            document_count = document_count
328                .saturating_add(estimate.counts.get("documents").copied().unwrap_or(0));
329        }
330        let diagnostics = self.diagnostics.estimated_memory();
331        bytes = bytes.saturating_add(diagnostics.estimated_bytes.unwrap_or(0));
332        crate::memory::MemoryEstimate::estimated(bytes)
333            .count("servers", self.clients.len())
334            .count("document_stores", self.documents.len())
335            .count_u64("documents", document_count)
336            .count_u64(
337                "diagnostic_entries",
338                diagnostics
339                    .counts
340                    .get("diagnostic_entries")
341                    .copied()
342                    .unwrap_or(0),
343            )
344            .count_u64(
345                "diagnostics",
346                diagnostics.counts.get("diagnostics").copied().unwrap_or(0),
347            )
348    }
349
350    /// Apply the configured diagnostic LRU cap (the `lsp.diagnostic_cache_size`
351    /// knob). 0 disables the cap. Called at construction so the documented
352    /// config field actually takes effect instead of always using the default.
353    pub fn set_diagnostic_capacity(&mut self, capacity: usize) {
354        self.diagnostics.set_capacity(capacity);
355    }
356
357    /// For testing: override the binary for a server kind.
358    pub fn override_binary(&mut self, kind: ServerKind, binary_path: PathBuf) {
359        self.binary_overrides.insert(kind, binary_path);
360    }
361
362    /// Ensure a server is running for the given file. Spawns if needed.
363    /// Returns the active server keys for the file, or an empty vec if none match.
364    ///
365    /// This is the lightweight wrapper around [`ensure_server_for_file_detailed`]
366    /// that drops failure context. Prefer the detailed variant in command
367    /// handlers that need to surface honest error messages to the agent.
368    pub fn ensure_server_for_file(&mut self, file_path: &Path, config: &Config) -> Vec<ServerKey> {
369        self.ensure_server_for_file_detailed(file_path, config)
370            .successful
371    }
372
373    /// Detailed version of [`ensure_server_for_file`] that records every
374    /// matching server's outcome (`Ok` / `NoRootMarker` / `BinaryNotInstalled`
375    /// / `SpawnFailed`).
376    ///
377    /// Use this when the caller wants to honestly report _why_ a file has no
378    /// active server (e.g., to surface "bash-language-server not on PATH" to
379    /// the agent instead of silently returning `total: 0`).
380    pub fn ensure_server_for_file_detailed(
381        &mut self,
382        file_path: &Path,
383        config: &Config,
384    ) -> EnsureServerOutcomes {
385        let defs = servers_for_file(file_path, config);
386        let mut outcomes = EnsureServerOutcomes::default();
387
388        for def in defs {
389            let server_id = def.kind.id_str().to_string();
390            let server_name = def.name.to_string();
391
392            let Some(root) = def.workspace_root_for_file(file_path) else {
393                outcomes.attempts.push(ServerAttempt {
394                    server_id,
395                    server_name,
396                    result: ServerAttemptResult::NoRootMarker {
397                        looked_for: def.root_markers.iter().map(|s| s.to_string()).collect(),
398                    },
399                });
400                continue;
401            };
402
403            let key = ServerKey {
404                kind: def.kind.clone(),
405                root,
406            };
407
408            if !self.clients.contains_key(&key) {
409                // If we already tried and failed to spawn this server for this
410                // root, return the cached classification without retrying or
411                // re-logging. This prevents per-edit ERROR spam when the user's
412                // environment is missing a dependency the LSP needs (the
413                // typescript-language-server "Could not find a valid TypeScript
414                // installation" case is the canonical example).
415                if let Some(cached) = self.failed_spawns.get(&key) {
416                    outcomes.attempts.push(ServerAttempt {
417                        server_id,
418                        server_name,
419                        result: cached.clone(),
420                    });
421                    continue;
422                }
423
424                match self.spawn_server(&def, &key.root, config) {
425                    Ok(client) => {
426                        self.clients.insert(key.clone(), client);
427                        self.server_binaries.insert(key.clone(), def.binary.clone());
428                        self.documents.entry(key.clone()).or_default();
429                    }
430                    Err(err) => {
431                        slog_error!("failed to spawn {}: {}", def.name, err);
432                        let result = classify_spawn_error(&def.binary, &err);
433                        // Remember the failure so subsequent file events skip
434                        // this (kind, root) pair instead of producing a fresh
435                        // spawn attempt + ERROR log per request.
436                        self.failed_spawns.insert(key.clone(), result.clone());
437                        outcomes.attempts.push(ServerAttempt {
438                            server_id,
439                            server_name,
440                            result,
441                        });
442                        continue;
443                    }
444                }
445            }
446
447            outcomes.attempts.push(ServerAttempt {
448                server_id,
449                server_name,
450                result: ServerAttemptResult::Ok {
451                    server_key: key.clone(),
452                },
453            });
454            outcomes.successful.push(key);
455        }
456
457        outcomes
458    }
459
460    /// Ensure a server is running using the default LSP registry.
461    /// Kept for integration tests that exercise built-in server helpers directly.
462    pub fn ensure_server_for_file_default(&mut self, file_path: &Path) -> Vec<ServerKey> {
463        self.ensure_server_for_file(file_path, &Config::default())
464    }
465    /// Ensure that servers are running for the file and that the document is open
466    /// in each server's DocumentStore. Reads file content from disk if not already open.
467    /// The result identifies which servers were already tracking the document and which
468    /// received `textDocument/didOpen` during this call.
469    pub fn ensure_file_open(
470        &mut self,
471        file_path: &Path,
472        config: &Config,
473    ) -> Result<EnsureFileOpenResult, LspError> {
474        let canonical_path = canonicalize_for_lsp(file_path)?;
475        let server_keys = self.ensure_server_for_file(&canonical_path, config);
476        if server_keys.is_empty() {
477            return Ok(EnsureFileOpenResult::default());
478        }
479
480        let uri = uri_for_path(&canonical_path)?;
481        let language_id = language_id_for_extension(
482            canonical_path
483                .extension()
484                .and_then(|ext| ext.to_str())
485                .unwrap_or_default(),
486        )
487        .to_string();
488        let needs_content = server_keys.iter().any(|key| {
489            !self
490                .documents
491                .get(key)
492                .is_some_and(|store| store.is_open(&canonical_path))
493        });
494        let initial_content = needs_content
495            .then(|| std::fs::read_to_string(&canonical_path).map_err(LspError::Io))
496            .transpose()?;
497        let mut newly_opened = Vec::new();
498
499        for key in &server_keys {
500            let already_open = self
501                .documents
502                .get(key)
503                .is_some_and(|store| store.is_open(&canonical_path));
504
505            if !already_open {
506                let content = initial_content
507                    .as_ref()
508                    .expect("content is loaded when any server needs didOpen");
509                let send_result = if let Some(client) = self.clients.get_mut(key) {
510                    client.send_notification::<DidOpenTextDocument>(DidOpenTextDocumentParams {
511                        text_document: TextDocumentItem::new(
512                            uri.clone(),
513                            language_id.clone(),
514                            0,
515                            content.clone(),
516                        ),
517                    })
518                } else {
519                    Ok(())
520                };
521                if let Err(err) = send_result {
522                    let _ = self.close_file_for_servers(&canonical_path, &newly_opened);
523                    return Err(err);
524                }
525                self.documents
526                    .entry(key.clone())
527                    .or_default()
528                    .open(canonical_path.clone());
529                newly_opened.push(key.clone());
530                continue;
531            }
532
533            // Document is already open. Check disk drift — if the file has
534            // been modified outside the AFT pipeline (other tool, manual
535            // edit, sibling session) we MUST send a didChange before any
536            // pull-diagnostic / hover query, otherwise the LSP server
537            // returns results computed from stale in-memory content.
538            //
539            // Without this, ensure_file_open would skip an already-open file
540            // without checking whether its disk content changed, leaving the
541            // server's in-memory copy stale.
542            let drifted = self
543                .documents
544                .get(key)
545                .is_some_and(|store| store.is_stale_on_disk(&canonical_path));
546            if drifted {
547                let content = match std::fs::read_to_string(&canonical_path) {
548                    Ok(content) => content,
549                    Err(err) => {
550                        let _ = self.close_file_for_servers(&canonical_path, &newly_opened);
551                        return Err(LspError::Io(err));
552                    }
553                };
554                let next_version = self
555                    .documents
556                    .get(key)
557                    .and_then(|store| store.version(&canonical_path))
558                    .map(|v| v + 1)
559                    .unwrap_or(1);
560                let send_result = if let Some(client) = self.clients.get_mut(key) {
561                    client.send_notification::<DidChangeTextDocument>(DidChangeTextDocumentParams {
562                        text_document: VersionedTextDocumentIdentifier::new(
563                            uri.clone(),
564                            next_version,
565                        ),
566                        content_changes: vec![TextDocumentContentChangeEvent {
567                            range: None,
568                            range_length: None,
569                            text: content,
570                        }],
571                    })
572                } else {
573                    Ok(())
574                };
575                if let Err(err) = send_result {
576                    let _ = self.close_file_for_servers(&canonical_path, &newly_opened);
577                    return Err(err);
578                }
579                if let Some(store) = self.documents.get_mut(key) {
580                    store.bump_version(&canonical_path);
581                }
582            }
583        }
584
585        Ok(EnsureFileOpenResult {
586            server_keys,
587            newly_opened,
588        })
589    }
590
591    pub fn ensure_file_open_default(
592        &mut self,
593        file_path: &Path,
594    ) -> Result<EnsureFileOpenResult, LspError> {
595        self.ensure_file_open(file_path, &Config::default())
596    }
597
598    /// Notify relevant LSP servers that a file has been written/changed.
599    /// This is the main hook called after every file write in AFT.
600    ///
601    /// If the file's server isn't running yet, starts it (lazy spawn).
602    /// If the file isn't open in LSP yet, sends didOpen. Otherwise sends didChange.
603    pub fn notify_file_changed(
604        &mut self,
605        file_path: &Path,
606        content: &str,
607        config: &Config,
608    ) -> Result<(), LspError> {
609        self.notify_file_changed_versioned(file_path, content, config)
610            .map(|_| ())
611    }
612
613    /// Like `notify_file_changed`, but returns the target document version
614    /// per server so the post-edit waiter can match `publishDiagnostics`
615    /// against the exact version that this notification carried.
616    ///
617    /// Returns: `Vec<(ServerKey, target_version)>`. `target_version` is the
618    /// `version` field on the `VersionedTextDocumentIdentifier` we just sent
619    /// (post-bump). For freshly-opened documents (`didOpen`) the version is
620    /// `0`. Servers that don't honor versioned text document sync will not
621    /// echo this back on `publishDiagnostics`; the caller is expected to
622    /// fall back to the epoch-delta path for those.
623    pub fn notify_file_changed_versioned(
624        &mut self,
625        file_path: &Path,
626        content: &str,
627        config: &Config,
628    ) -> Result<Vec<(ServerKey, i32)>, LspError> {
629        let canonical_path = canonicalize_for_lsp(file_path)?;
630        let server_keys = self.ensure_server_for_file(&canonical_path, config);
631        if server_keys.is_empty() {
632            return Ok(Vec::new());
633        }
634
635        let uri = uri_for_path(&canonical_path)?;
636        let language_id = language_id_for_extension(
637            canonical_path
638                .extension()
639                .and_then(|ext| ext.to_str())
640                .unwrap_or_default(),
641        )
642        .to_string();
643
644        let mut versions: Vec<(ServerKey, i32)> = Vec::with_capacity(server_keys.len());
645
646        for key in server_keys {
647            let current_version = self
648                .documents
649                .get(&key)
650                .and_then(|store| store.version(&canonical_path));
651
652            if let Some(version) = current_version {
653                let next_version = version + 1;
654                if let Some(client) = self.clients.get_mut(&key) {
655                    client.send_notification::<DidChangeTextDocument>(
656                        DidChangeTextDocumentParams {
657                            text_document: VersionedTextDocumentIdentifier::new(
658                                uri.clone(),
659                                next_version,
660                            ),
661                            content_changes: vec![TextDocumentContentChangeEvent {
662                                range: None,
663                                range_length: None,
664                                text: content.to_string(),
665                            }],
666                        },
667                    )?;
668                }
669                if let Some(store) = self.documents.get_mut(&key) {
670                    store.bump_version(&canonical_path);
671                }
672                versions.push((key, next_version));
673                continue;
674            }
675
676            if let Some(client) = self.clients.get_mut(&key) {
677                client.send_notification::<DidOpenTextDocument>(DidOpenTextDocumentParams {
678                    text_document: TextDocumentItem::new(
679                        uri.clone(),
680                        language_id.clone(),
681                        0,
682                        content.to_string(),
683                    ),
684                })?;
685            }
686            self.documents
687                .entry(key.clone())
688                .or_default()
689                .open(canonical_path.clone());
690            // didOpen carries version 0 — that's the version the server
691            // will echo on its first publishDiagnostics for this document.
692            versions.push((key, 0));
693        }
694
695        Ok(versions)
696    }
697
698    pub fn notify_file_changed_default(
699        &mut self,
700        file_path: &Path,
701        content: &str,
702    ) -> Result<(), LspError> {
703        self.notify_file_changed(file_path, content, &Config::default())
704    }
705
706    /// Notify every active server whose workspace contains at least one changed
707    /// path that watched files changed. This is intentionally workspace-scoped
708    /// rather than extension-scoped: configuration edits such as `package.json`
709    /// or `tsconfig.json` affect a server's project graph even though those
710    /// files may not be documents handled by the server itself.
711    pub fn notify_files_watched_changed(
712        &mut self,
713        paths: &[(PathBuf, FileChangeType)],
714        _config: &Config,
715    ) -> Result<(), LspError> {
716        if paths.is_empty() {
717            return Ok(());
718        }
719
720        let mut canonical_events = Vec::with_capacity(paths.len());
721        for (path, typ) in paths {
722            let canonical_path = resolve_for_lsp_uri(path);
723            canonical_events.push((canonical_path, *typ));
724        }
725
726        let keys: Vec<ServerKey> = self.clients.keys().cloned().collect();
727        for key in keys {
728            let mut changes = Vec::new();
729            for (path, typ) in &canonical_events {
730                if !path.starts_with(&key.root) {
731                    continue;
732                }
733                changes.push(FileEvent::new(uri_for_path(path)?, *typ));
734            }
735
736            if changes.is_empty() {
737                continue;
738            }
739
740            if let Some(client) = self.clients.get_mut(&key) {
741                // Send when the server either advertised initialize-time
742                // watched-file support or dynamically registered a watcher.
743                // The dynamic client capability we send during initialize only
744                // permits runtime registration; it is tracked separately via
745                // `has_watched_file_registration()`.
746                let supports_static_watched_files = client.supports_watched_files();
747                let has_dynamic_registration = client.has_watched_file_registration();
748                if !(supports_static_watched_files || has_dynamic_registration) {
749                    if self.watched_file_skip_logged.insert(key.clone()) {
750                        log::debug!(
751                            "skipping didChangeWatchedFiles for {:?} (not supported or registered)",
752                            key
753                        );
754                    }
755                    continue;
756                }
757                client.send_notification::<DidChangeWatchedFiles>(DidChangeWatchedFilesParams {
758                    changes,
759                })?;
760            }
761        }
762
763        Ok(())
764    }
765
766    /// Close a document in all servers that have it open.
767    pub fn notify_file_closed(&mut self, file_path: &Path) -> Result<(), LspError> {
768        let canonical_path = canonicalize_for_lsp(file_path)?;
769        let keys = self
770            .documents
771            .iter()
772            .filter(|(_, store)| store.is_open(&canonical_path))
773            .map(|(key, _)| key.clone())
774            .collect::<Vec<_>>();
775        self.close_file_for_servers(&canonical_path, &keys)
776    }
777
778    /// Close a document only in the specified servers.
779    ///
780    /// Scoped inspection uses this to release documents it opened without
781    /// disturbing pre-existing editor documents in other server stores.
782    pub(crate) fn close_file_for_servers(
783        &mut self,
784        file_path: &Path,
785        server_keys: &[ServerKey],
786    ) -> Result<(), LspError> {
787        let canonical_path = canonicalize_for_lsp(file_path)?;
788        let uri = uri_for_path(&canonical_path)?;
789        let mut first_error = None;
790
791        for key in server_keys {
792            let was_open = self
793                .documents
794                .get(key)
795                .is_some_and(|store| store.is_open(&canonical_path));
796            if !was_open {
797                continue;
798            }
799
800            if let Some(client) = self.clients.get_mut(key) {
801                if let Err(err) =
802                    client.send_notification::<DidCloseTextDocument>(DidCloseTextDocumentParams {
803                        text_document: TextDocumentIdentifier::new(uri.clone()),
804                    })
805                {
806                    if first_error.is_none() {
807                        first_error = Some(err);
808                    }
809                }
810            }
811
812            if let Some(store) = self.documents.get_mut(key) {
813                store.close(&canonical_path);
814            }
815            self.diagnostics.clear_for_server_file(key, &canonical_path);
816        }
817
818        match first_error {
819            Some(err) => Err(err),
820            None => Ok(()),
821        }
822    }
823
824    /// Get an active client for a file path, if one exists.
825    pub fn client_for_file(&self, file_path: &Path, config: &Config) -> Option<&LspClient> {
826        let key = self.server_key_for_file(file_path, config)?;
827        self.clients.get(&key)
828    }
829
830    pub fn client_for_file_default(&self, file_path: &Path) -> Option<&LspClient> {
831        self.client_for_file(file_path, &Config::default())
832    }
833
834    /// Get a mutable active client for a file path, if one exists.
835    pub fn client_for_file_mut(
836        &mut self,
837        file_path: &Path,
838        config: &Config,
839    ) -> Option<&mut LspClient> {
840        let key = self.server_key_for_file(file_path, config)?;
841        self.clients.get_mut(&key)
842    }
843
844    pub fn client_for_file_mut_default(&mut self, file_path: &Path) -> Option<&mut LspClient> {
845        self.client_for_file_mut(file_path, &Config::default())
846    }
847
848    /// Number of tracked server clients.
849    pub fn active_client_count(&self) -> usize {
850        self.clients.len()
851    }
852
853    /// Drain all pending LSP events. Call from the main loop.
854    pub fn drain_events(&mut self) -> DrainedLspEvents {
855        self.drain_events_bounded(usize::MAX)
856    }
857
858    /// Whether LSP events are waiting to be drained. Cheap channel peek for
859    /// the maintenance scheduler's skip probe.
860    pub fn has_pending_events(&self) -> bool {
861        !self.event_rx.is_empty()
862    }
863
864    pub fn drain_events_bounded(&mut self, max_events: usize) -> DrainedLspEvents {
865        let mut events = Vec::new();
866        let mut diagnostics_changed = false;
867        while events.len() < max_events {
868            let Ok(event) = self.event_rx.try_recv() else {
869                break;
870            };
871            if self.handle_event(&event).is_some() {
872                diagnostics_changed = true;
873            }
874            events.push(event);
875        }
876        let has_more = events.len() >= max_events && !self.event_rx.is_empty();
877        DrainedLspEvents {
878            events,
879            diagnostics_changed,
880            has_more,
881        }
882    }
883
884    /// Wait for diagnostics to arrive for a specific file until a timeout expires.
885    pub fn wait_for_diagnostics(
886        &mut self,
887        file_path: &Path,
888        config: &Config,
889        timeout: std::time::Duration,
890    ) -> Vec<StoredDiagnostic> {
891        let deadline = std::time::Instant::now() + timeout;
892        self.wait_for_file_diagnostics(file_path, config, deadline)
893    }
894
895    pub fn wait_for_diagnostics_default(
896        &mut self,
897        file_path: &Path,
898        timeout: std::time::Duration,
899    ) -> Vec<StoredDiagnostic> {
900        self.wait_for_diagnostics(file_path, &Config::default(), timeout)
901    }
902
903    /// Test-only accessor for the diagnostics store. Used by integration
904    /// tests that need to inspect per-server entries (e.g., to verify that
905    /// `ServerKey::root` is populated correctly, not the empty path that
906    /// the legacy `publish_with_kind` path produced).
907    #[doc(hidden)]
908    pub fn diagnostics_store_for_test(&self) -> &DiagnosticsStore {
909        &self.diagnostics
910    }
911
912    #[doc(hidden)]
913    pub fn diagnostics_store_mut_for_test(&mut self) -> &mut DiagnosticsStore {
914        &mut self.diagnostics
915    }
916
917    #[doc(hidden)]
918    pub fn enqueue_event_for_test(&self, event: LspEvent) {
919        self.event_tx
920            .send(event)
921            .expect("LSP event receiver should remain connected");
922    }
923
924    #[doc(hidden)]
925    pub fn pending_event_count_for_test(&self) -> usize {
926        self.event_rx.len()
927    }
928
929    #[doc(hidden)]
930    pub fn document_is_open_for_test(&self, file_path: &Path) -> bool {
931        canonicalize_for_lsp(file_path).is_ok_and(|canonical_path| {
932            self.documents
933                .values()
934                .any(|store| store.is_open(&canonical_path))
935        })
936    }
937
938    /// Error/warning counts across the entire warm diagnostics set (all files
939    /// any server has published for this session). Powers the agent status bar;
940    /// reads the continuously-drained store with no extra LSP round-trip.
941    pub fn warm_error_warning_counts(&self) -> (usize, usize) {
942        self.diagnostics.error_warning_counts()
943    }
944
945    pub fn diagnostics_generation(&self) -> u64 {
946        self.diagnostics.generation()
947    }
948
949    /// Status-bar error/warning counts with a per-file `keep` predicate and
950    /// cross-server dedup applied (see
951    /// [`DiagnosticsStore::filtered_error_warning_counts`]). The caller supplies
952    /// the project-root + tsconfig-membership policy via `keep`.
953    pub fn filtered_error_warning_counts(
954        &self,
955        keep: impl FnMut(&std::path::Path) -> bool,
956    ) -> (usize, usize) {
957        self.diagnostics.filtered_error_warning_counts(keep)
958    }
959
960    /// Snapshot the current per-server epoch for every entry that exists
961    /// for `file_path`. Servers without an entry yet (never published)
962    /// are absent from the map; for those, `pre = 0` (any first publish
963    /// will be considered fresh under the epoch-fallback rule).
964    pub fn snapshot_diagnostic_epochs(&self, file_path: &Path) -> HashMap<ServerKey, u64> {
965        let lookup_path = normalize_lookup_path(file_path);
966        self.diagnostics
967            .entries_for_file(&lookup_path)
968            .into_iter()
969            .map(|(key, entry)| (key.clone(), entry.epoch))
970            .collect()
971    }
972
973    /// Snapshot the current diagnostic epoch and document version for every
974    /// active server relevant to `file_path` before a post-edit notification.
975    pub fn snapshot_pre_edit_state(&self, file_path: &Path) -> HashMap<ServerKey, PreEditSnapshot> {
976        let lookup_path = normalize_lookup_path(file_path);
977        let mut snapshots: HashMap<ServerKey, PreEditSnapshot> = self
978            .diagnostics
979            .entries_for_file(&lookup_path)
980            .into_iter()
981            .map(|(key, entry)| {
982                (
983                    key.clone(),
984                    PreEditSnapshot {
985                        epoch: entry.epoch,
986                        document_version_at_capture: None,
987                    },
988                )
989            })
990            .collect();
991
992        for (key, store) in &self.documents {
993            if let Some(version) = store.version(&lookup_path) {
994                snapshots
995                    .entry(key.clone())
996                    .or_default()
997                    .document_version_at_capture = Some(version);
998            }
999        }
1000
1001        snapshots
1002    }
1003
1004    /// True when the current diagnostic entry for `server_key` can be tied to
1005    /// that server's current in-memory document version for `file_path`.
1006    ///
1007    /// File-mode `lsp_diagnostics` uses this for push-only fallback after it
1008    /// has synced/opened the document. Versioned publishes are accepted when
1009    /// they match the current document version; unversioned publishes are not
1010    /// accepted as fresh because epoch/wall-clock ordering alone is racy.
1011    pub fn diagnostic_entry_is_fresh_for_document(
1012        &self,
1013        file_path: &Path,
1014        server_key: &ServerKey,
1015        pre: PreEditSnapshot,
1016    ) -> bool {
1017        let lookup_path = normalize_lookup_path(file_path);
1018        let Some(entry) = self
1019            .diagnostics
1020            .entries_for_file(&lookup_path)
1021            .into_iter()
1022            .find_map(|(key, entry)| if key == server_key { Some(entry) } else { None })
1023        else {
1024            return false;
1025        };
1026
1027        if entry.stale {
1028            return false;
1029        }
1030
1031        let target_version = self
1032            .documents
1033            .get(server_key)
1034            .and_then(|store| store.version(&lookup_path))
1035            .or(pre.document_version_at_capture)
1036            .unwrap_or(0);
1037
1038        matches!(entry.version, Some(version) if version >= target_version)
1039    }
1040
1041    /// Wait for FRESH per-server diagnostics that match the just-sent
1042    /// document version. This is the v0.17.3 post-edit path that fixes the
1043    /// stale-diagnostics bug: instead of returning whatever is in the cache
1044    /// when the deadline hits, we only return entries whose `version`
1045    /// matches the post-edit target version (or, for servers that don't
1046    /// participate in versioned sync, whose `epoch` was bumped after the
1047    /// pre-edit snapshot).
1048    ///
1049    /// `expected_versions` should come from `notify_file_changed_versioned`
1050    /// — one `(ServerKey, target_version)` per server we sent didChange/
1051    /// didOpen to.
1052    ///
1053    /// `pre_snapshot` is the per-server epoch BEFORE the notification was
1054    /// sent; it gates the epoch-fallback path so an old-version publish
1055    /// arriving after `drain_events` and before `didChange` cannot be
1056    /// mistaken for a fresh response.
1057    ///
1058    /// Returns a per-server tri-state: `Fresh` (publish matched target
1059    /// version OR epoch advanced past snapshot for an unversioned server),
1060    /// `Pending` (deadline hit before this server published anything we
1061    /// could verify), or `Exited` (server died between notification and
1062    /// deadline).
1063    pub fn wait_for_post_edit_diagnostics(
1064        &mut self,
1065        file_path: &Path,
1066        // `config` is intentionally accepted (matches sibling wait APIs and
1067        // future-proofs us if freshness rules need it). Currently unused
1068        // because expected_versions/pre_snapshot fully determine behavior.
1069        _config: &Config,
1070        expected_versions: &[(ServerKey, i32)],
1071        pre_snapshot: &HashMap<ServerKey, PreEditSnapshot>,
1072        timeout: std::time::Duration,
1073    ) -> PostEditWaitOutcome {
1074        let lookup_path = normalize_lookup_path(file_path);
1075        let deadline = std::time::Instant::now() + timeout;
1076
1077        // Drain any events that arrived while we were sending didChange.
1078        // The publishDiagnostics handler stores the version, so even
1079        // pre-snapshot publishes that landed late won't be mistaken for
1080        // fresh — the version-match check will reject them.
1081        let _ = self.drain_events_for_file(&lookup_path);
1082
1083        let mut fresh: HashMap<ServerKey, Vec<StoredDiagnostic>> = HashMap::new();
1084        let mut exited: Vec<ServerKey> = Vec::new();
1085
1086        loop {
1087            // Check freshness for every expected server. A server is fresh
1088            // if its current entry for this file satisfies either:
1089            //   1. version-match: entry.version == Some(target_version), OR
1090            //   2. push-only freshness: entry.version is None AND entry.epoch
1091            //      advanced strictly after the pre-edit snapshot. Versioned
1092            //      publishes must be >= the post-edit target version.
1093            // Servers whose process has exited are reported separately.
1094            for (key, target_version) in expected_versions {
1095                if fresh.contains_key(key) || exited.contains(key) {
1096                    continue;
1097                }
1098                if !self.clients.contains_key(key) {
1099                    exited.push(key.clone());
1100                    continue;
1101                }
1102                if let Some(entry) = self
1103                    .diagnostics
1104                    .entries_for_file(&lookup_path)
1105                    .into_iter()
1106                    .find_map(|(k, e)| if k == key { Some(e) } else { None })
1107                {
1108                    let pre = pre_snapshot.get(key).copied().unwrap_or_default();
1109                    let is_fresh = post_edit_entry_is_fresh(entry, *target_version, pre);
1110                    if is_fresh {
1111                        fresh.insert(key.clone(), entry.diagnostics.clone());
1112                    }
1113                }
1114            }
1115
1116            // All accounted for? Done.
1117            if fresh.len() + exited.len() == expected_versions.len() {
1118                break;
1119            }
1120
1121            let now = std::time::Instant::now();
1122            if now >= deadline {
1123                break;
1124            }
1125
1126            let timeout = deadline.saturating_duration_since(now);
1127            match self.event_rx.recv_timeout(timeout) {
1128                Ok(event) => {
1129                    self.handle_event(&event);
1130                }
1131                Err(RecvTimeoutError::Timeout) | Err(RecvTimeoutError::Disconnected) => break,
1132            }
1133        }
1134
1135        // Pending = expected but neither fresh nor exited.
1136        let pending: Vec<ServerKey> = expected_versions
1137            .iter()
1138            .filter(|(k, _)| !fresh.contains_key(k) && !exited.contains(k))
1139            .map(|(k, _)| k.clone())
1140            .collect();
1141
1142        // Build deduplicated, sorted diagnostics from the fresh servers only.
1143        // Stale or pending servers contribute zero diagnostics.
1144        let mut diagnostics: Vec<StoredDiagnostic> = fresh
1145            .into_iter()
1146            .flat_map(|(_, diags)| diags.into_iter())
1147            .collect();
1148        diagnostics.sort_by(|a, b| {
1149            a.file
1150                .cmp(&b.file)
1151                .then(a.line.cmp(&b.line))
1152                .then(a.column.cmp(&b.column))
1153                .then(a.message.cmp(&b.message))
1154        });
1155
1156        PostEditWaitOutcome {
1157            diagnostics,
1158            pending_servers: pending,
1159            exited_servers: exited,
1160        }
1161    }
1162
1163    /// Wait for diagnostics to arrive for a specific file until a deadline.
1164    ///
1165    /// Drains already-queued events first, then blocks on the shared event
1166    /// channel only until either `publishDiagnostics` arrives for this file or
1167    /// the deadline is reached.
1168    pub fn wait_for_file_diagnostics(
1169        &mut self,
1170        file_path: &Path,
1171        config: &Config,
1172        deadline: std::time::Instant,
1173    ) -> Vec<StoredDiagnostic> {
1174        let lookup_path = normalize_lookup_path(file_path);
1175
1176        if self.server_key_for_file(&lookup_path, config).is_none() {
1177            return Vec::new();
1178        }
1179
1180        loop {
1181            if self.drain_events_for_file(&lookup_path) {
1182                break;
1183            }
1184
1185            let now = std::time::Instant::now();
1186            if now >= deadline {
1187                break;
1188            }
1189
1190            let timeout = deadline.saturating_duration_since(now);
1191            match self.event_rx.recv_timeout(timeout) {
1192                Ok(event) => {
1193                    if matches!(
1194                        self.handle_event(&event),
1195                        Some(ref published_file) if published_file.as_path() == lookup_path.as_path()
1196                    ) {
1197                        break;
1198                    }
1199                }
1200                Err(RecvTimeoutError::Timeout) | Err(RecvTimeoutError::Disconnected) => break,
1201            }
1202        }
1203
1204        self.get_diagnostics_for_file(&lookup_path)
1205            .into_iter()
1206            .cloned()
1207            .collect()
1208    }
1209
1210    /// Default timeout for `textDocument/diagnostic` (per-file pull). Servers
1211    /// usually respond in under 1s for files they've already analyzed; we
1212    /// allow up to 10s before falling back to push semantics. Currently
1213    /// surfaced via [`Self::pull_file_timeout`] for callers that want to
1214    /// override the wait via the `wait_ms` knob.
1215    pub const PULL_FILE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
1216
1217    /// Public accessor so command handlers can reuse the documented default.
1218    pub fn pull_file_timeout() -> std::time::Duration {
1219        Self::PULL_FILE_TIMEOUT
1220    }
1221
1222    /// Default timeout for `workspace/diagnostic`. The LSP spec allows the
1223    /// server to hold this open indefinitely; we cap at 10s and report
1224    /// `complete: false` to the agent rather than hanging the bridge.
1225    const PULL_WORKSPACE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
1226
1227    /// Issue a `textDocument/diagnostic` (LSP 3.17 per-file pull) request to
1228    /// every server that supports pull diagnostics for the given file.
1229    ///
1230    /// Returns the per-server outcome. If a server reports `kind: "unchanged"`,
1231    /// the cached entry's diagnostics are surfaced (deterministic re-use of
1232    /// the previous response). If a server doesn't advertise pull capability,
1233    /// it's skipped here — the caller should fall back to push for those.
1234    ///
1235    /// Side effects: results are stored in `DiagnosticsStore` so directory-mode
1236    /// queries can aggregate them later.
1237    pub fn pull_file_diagnostics(
1238        &mut self,
1239        file_path: &Path,
1240        config: &Config,
1241    ) -> Result<Vec<PullFileResult>, LspError> {
1242        self.pull_file_diagnostics_tracked(file_path, config)
1243            .map(|tracked| tracked.results)
1244    }
1245
1246    pub(crate) fn pull_file_diagnostics_tracked(
1247        &mut self,
1248        file_path: &Path,
1249        config: &Config,
1250    ) -> Result<TrackedPullFileResult, LspError> {
1251        let canonical_path = canonicalize_for_lsp(file_path)?;
1252        // Make sure servers are running and the document is open with fresh
1253        // content (handles disk-drift via DocumentStore::is_stale_on_disk).
1254        let opened = self.ensure_file_open(&canonical_path, config)?;
1255        if opened.server_keys.is_empty() {
1256            return Ok(TrackedPullFileResult {
1257                results: Vec::new(),
1258                newly_opened: opened.newly_opened,
1259            });
1260        }
1261
1262        let uri = uri_for_path(&canonical_path)?;
1263        let mut results = Vec::with_capacity(opened.server_keys.len());
1264
1265        for key in opened.server_keys {
1266            let supports_pull = self
1267                .clients
1268                .get(&key)
1269                .and_then(|c| c.diagnostic_capabilities())
1270                .is_some_and(|caps| caps.pull_diagnostics);
1271
1272            if !supports_pull {
1273                results.push(PullFileResult {
1274                    server_key: key.clone(),
1275                    outcome: PullFileOutcome::PullNotSupported,
1276                });
1277                continue;
1278            }
1279
1280            // Look up previous resultId for incremental requests.
1281            let previous_result_id = self
1282                .diagnostics
1283                .entries_for_file(&canonical_path)
1284                .into_iter()
1285                .find(|(k, _)| **k == key)
1286                .and_then(|(_, entry)| entry.result_id.clone());
1287
1288            let identifier = self
1289                .clients
1290                .get(&key)
1291                .and_then(|c| c.diagnostic_capabilities())
1292                .and_then(|caps| caps.identifier.clone());
1293
1294            let params = AftDocumentDiagnosticParams {
1295                text_document: lsp_types::TextDocumentIdentifier { uri: uri.clone() },
1296                identifier,
1297                previous_result_id,
1298                work_done_progress_params: Default::default(),
1299                partial_result_params: Default::default(),
1300            };
1301
1302            let outcome = match self.send_pull_request(&key, params) {
1303                Ok(report) => {
1304                    if matches!(
1305                        &report,
1306                        lsp_types::DocumentDiagnosticReportResult::Report(
1307                            lsp_types::DocumentDiagnosticReport::Full(_)
1308                        )
1309                    ) {
1310                        // The server may publish diagnostics for didOpen before
1311                        // returning a full pull response. Apply those older events
1312                        // first so the full report remains authoritative. An
1313                        // unchanged response must inspect only a previous pull cache.
1314                        self.drain_events();
1315                    }
1316                    self.ingest_document_report(&key, &canonical_path, report)
1317                }
1318                Err(err) => {
1319                    if let Some(result) = self.cache_post_initialize_exit(&key, &err) {
1320                        PullFileOutcome::RequestFailed {
1321                            reason: server_attempt_result_reason(&result),
1322                        }
1323                    } else if recoverable_pull_rejection(&err)
1324                        && self.clients.get(&key).is_some_and(|client| {
1325                            matches!(
1326                                client.state(),
1327                                ServerState::Ready | ServerState::Initializing
1328                            )
1329                        })
1330                    {
1331                        PullFileOutcome::RequestFailed {
1332                            reason: format!("pull_rejected_push_fallback: {err}"),
1333                        }
1334                    } else {
1335                        PullFileOutcome::RequestFailed {
1336                            reason: err.to_string(),
1337                        }
1338                    }
1339                }
1340            };
1341
1342            results.push(PullFileResult {
1343                server_key: key,
1344                outcome,
1345            });
1346        }
1347
1348        Ok(TrackedPullFileResult {
1349            results,
1350            newly_opened: opened.newly_opened,
1351        })
1352    }
1353
1354    /// Issue a `workspace/diagnostic` request to a specific server. Cancels
1355    /// internally if `timeout` elapses before the server responds. Cached
1356    /// entries from the response are stored so directory-mode queries pick
1357    /// them up.
1358    pub fn pull_workspace_diagnostics(
1359        &mut self,
1360        server_key: &ServerKey,
1361        timeout: Option<std::time::Duration>,
1362    ) -> Result<PullWorkspaceResult, LspError> {
1363        let timeout = timeout.unwrap_or(Self::PULL_WORKSPACE_TIMEOUT);
1364
1365        let supports_workspace = self
1366            .clients
1367            .get(server_key)
1368            .and_then(|c| c.diagnostic_capabilities())
1369            .is_some_and(|caps| caps.workspace_diagnostics);
1370
1371        if !supports_workspace {
1372            return Ok(PullWorkspaceResult {
1373                server_key: server_key.clone(),
1374                files_reported: Vec::new(),
1375                complete: false,
1376                cancelled: false,
1377                supports_workspace: false,
1378            });
1379        }
1380
1381        let identifier = self
1382            .clients
1383            .get(server_key)
1384            .and_then(|c| c.diagnostic_capabilities())
1385            .and_then(|caps| caps.identifier.clone());
1386
1387        let params = AftWorkspaceDiagnosticParams {
1388            identifier,
1389            previous_result_ids: Vec::new(),
1390            work_done_progress_params: Default::default(),
1391            partial_result_params: Default::default(),
1392        };
1393
1394        let result = match self
1395            .clients
1396            .get_mut(server_key)
1397            .ok_or_else(|| LspError::ServerNotReady("server not found".into()))?
1398            .send_request_with_timeout::<AftWorkspaceDiagnosticRequest>(params, timeout)
1399        {
1400            Ok(result) => result,
1401            Err(LspError::Timeout(_)) => {
1402                return Ok(PullWorkspaceResult {
1403                    server_key: server_key.clone(),
1404                    files_reported: Vec::new(),
1405                    complete: false,
1406                    cancelled: true,
1407                    supports_workspace: true,
1408                });
1409            }
1410            Err(err) => {
1411                if let Some(result) = self.cache_post_initialize_exit(server_key, &err) {
1412                    return Err(LspError::ServerNotReady(server_attempt_result_reason(
1413                        &result,
1414                    )));
1415                }
1416                return Err(err);
1417            }
1418        };
1419
1420        // Extract the items list. Partial responses are not a complete
1421        // workspace view, but the partial payload can still contain useful
1422        // document reports; ingest those while surfacing complete=false.
1423        let (items, complete) = match result {
1424            lsp_types::WorkspaceDiagnosticReportResult::Report(report) => (report.items, true),
1425            lsp_types::WorkspaceDiagnosticReportResult::Partial(partial) => (partial.items, false),
1426        };
1427
1428        // Ingest each file report into the diagnostics store.
1429        let mut files_reported = Vec::with_capacity(items.len());
1430        for item in items {
1431            match item {
1432                lsp_types::WorkspaceDocumentDiagnosticReport::Full(full) => {
1433                    if let Some(file) = uri_to_path(&full.uri) {
1434                        let stored = from_lsp_diagnostics(
1435                            file.clone(),
1436                            full.full_document_diagnostic_report.items.clone(),
1437                        );
1438                        self.diagnostics.publish_with_result_id(
1439                            server_key.clone(),
1440                            file.clone(),
1441                            stored,
1442                            full.full_document_diagnostic_report.result_id.clone(),
1443                        );
1444                        files_reported.push(file);
1445                    }
1446                }
1447                lsp_types::WorkspaceDocumentDiagnosticReport::Unchanged(_unchanged) => {
1448                    // "Unchanged" means the previously cached report is still
1449                    // valid. We left it in place; nothing to do.
1450                }
1451            }
1452        }
1453
1454        Ok(PullWorkspaceResult {
1455            server_key: server_key.clone(),
1456            files_reported,
1457            complete,
1458            cancelled: false,
1459            supports_workspace: true,
1460        })
1461    }
1462
1463    fn cache_post_initialize_exit(
1464        &mut self,
1465        key: &ServerKey,
1466        err: &LspError,
1467    ) -> Option<ServerAttemptResult> {
1468        let binary = self
1469            .server_binaries
1470            .get(key)
1471            .cloned()
1472            .unwrap_or_else(|| key.kind.id_str().to_string());
1473        let (status, stderr_tail) = {
1474            let client = self.clients.get_mut(key)?;
1475            let mut status = client.child_exit_status();
1476            for _ in 0..10 {
1477                if status.is_some() {
1478                    break;
1479                }
1480                std::thread::sleep(std::time::Duration::from_millis(10));
1481                status = client.child_exit_status();
1482            }
1483            let status = status?;
1484            wait_for_stderr_tail(client);
1485            (status, client.stderr_tail())
1486        };
1487        let reason = format_post_initialize_exit_reason(&binary, status, &stderr_tail, err);
1488        let result = ServerAttemptResult::SpawnFailed { binary, reason };
1489        self.clients.remove(key);
1490        self.server_binaries.remove(key);
1491        self.documents.remove(key);
1492        self.diagnostics.clear_for_server(key);
1493        self.failed_spawns.insert(key.clone(), result.clone());
1494        Some(result)
1495    }
1496
1497    /// Issue the per-file diagnostic request and return the report.
1498    fn send_pull_request(
1499        &mut self,
1500        key: &ServerKey,
1501        params: AftDocumentDiagnosticParams,
1502    ) -> Result<lsp_types::DocumentDiagnosticReportResult, LspError> {
1503        let client = self
1504            .clients
1505            .get_mut(key)
1506            .ok_or_else(|| LspError::ServerNotReady("server not found".into()))?;
1507        // Use the documented 10s pull cap, not the global 30s request timeout —
1508        // a stalled pull server must not blow the scoped aft_inspect 8s budget
1509        // (or the lsp_diagnostics wait caps) all the way out to 30s.
1510        client.send_request_with_timeout::<AftDocumentDiagnosticRequest>(
1511            params,
1512            Self::PULL_FILE_TIMEOUT,
1513        )
1514    }
1515
1516    /// Store the result of a per-file pull request and return a structured
1517    /// outcome the caller can inspect.
1518    fn ingest_document_report(
1519        &mut self,
1520        key: &ServerKey,
1521        canonical_path: &Path,
1522        result: lsp_types::DocumentDiagnosticReportResult,
1523    ) -> PullFileOutcome {
1524        let report = match result {
1525            lsp_types::DocumentDiagnosticReportResult::Report(report) => report,
1526            lsp_types::DocumentDiagnosticReportResult::Partial(_) => {
1527                // Partial results stream in via $/progress notifications which
1528                // we don't currently subscribe to. Treat as a soft-empty
1529                // success — the next pull will get the full version.
1530                return PullFileOutcome::PartialNotSupported;
1531            }
1532        };
1533
1534        match report {
1535            lsp_types::DocumentDiagnosticReport::Full(full) => {
1536                let result_id = full.full_document_diagnostic_report.result_id.clone();
1537                let stored = from_lsp_diagnostics(
1538                    canonical_path.to_path_buf(),
1539                    full.full_document_diagnostic_report.items.clone(),
1540                );
1541                let count = stored.len();
1542                self.diagnostics.publish_with_result_id(
1543                    key.clone(),
1544                    canonical_path.to_path_buf(),
1545                    stored,
1546                    result_id,
1547                );
1548                PullFileOutcome::Full {
1549                    diagnostic_count: count,
1550                }
1551            }
1552            lsp_types::DocumentDiagnosticReport::Unchanged(_unchanged) => {
1553                // The server says the previous resultId is still valid for the
1554                // current document. That is only usable if we already have a
1555                // report for this exact server/file; an initial `unchanged`
1556                // response cannot prove freshness. A stale watcher entry is
1557                // acceptable here because the pull response itself proves the
1558                // cached diagnostics still describe the now-synced file.
1559                if self
1560                    .diagnostics
1561                    .has_report_for_server_file(key, canonical_path)
1562                {
1563                    self.diagnostics
1564                        .mark_fresh_for_server_file(key, canonical_path);
1565                    PullFileOutcome::Unchanged
1566                } else {
1567                    PullFileOutcome::RequestFailed {
1568                        reason: "no_cache_for_unchanged".to_string(),
1569                    }
1570                }
1571            }
1572        }
1573    }
1574
1575    /// Shutdown all servers gracefully.
1576    pub fn shutdown_all(&mut self) {
1577        for (key, mut client) in self.clients.drain() {
1578            if let Err(err) = client.shutdown() {
1579                slog_error!("error shutting down {:?}: {}", key, err);
1580            }
1581        }
1582        self.server_binaries.clear();
1583        self.documents.clear();
1584        self.diagnostics = DiagnosticsStore::new();
1585    }
1586
1587    /// Check if any server is active.
1588    pub fn has_active_servers(&self) -> bool {
1589        self.clients
1590            .values()
1591            .any(|client| client.state() == ServerState::Ready)
1592    }
1593
1594    /// Active server keys (running clients). Used by `lsp_diagnostics`
1595    /// directory mode to know which servers to ask for workspace pull.
1596    pub fn active_server_keys(&self) -> Vec<ServerKey> {
1597        self.clients.keys().cloned().collect()
1598    }
1599
1600    pub fn get_diagnostics_for_file(&self, file: &Path) -> Vec<&StoredDiagnostic> {
1601        let normalized = normalize_lookup_path(file);
1602        self.diagnostics.for_file(&normalized)
1603    }
1604
1605    /// Drop all cached diagnostics for a file across every server. Called when a
1606    /// file is deleted/renamed away so its diagnostics don't linger in the warm
1607    /// set (no server republishes for a vanished path), inflating the
1608    /// error/warning counts in the status bar and `aft_inspect`.
1609    ///
1610    /// The store key is the canonical path from publish time, but a deleted file
1611    /// can no longer be canonicalized directly (`canonicalize` needs the file to
1612    /// exist). We therefore try several equivalent forms: the raw path, the
1613    /// canonicalize-or-fallback form, and — crucially — a reconstruction that
1614    /// canonicalizes the still-present parent directory and rejoins the file
1615    /// name, which reproduces the publish-time key even across `/var`↔
1616    /// `/private/var`-style symlink aliasing. Returns true if anything was
1617    /// removed.
1618    /// Forget all cached spawn FAILURES so the next file event retries them.
1619    /// Called on `configure`: a configure means something changed (the user may
1620    /// have just installed the missing language server, or fixed PATH / a
1621    /// version pin), so a previously-failed (kind, root) pair deserves a fresh
1622    /// attempt instead of being skipped until a full restart. Bounded: configure
1623    /// is not a per-request hot path, so this cannot cause a spawn storm.
1624    /// Returns the number of cleared entries.
1625    pub fn clear_failed_spawns(&mut self) -> usize {
1626        let n = self.failed_spawns.len();
1627        self.failed_spawns.clear();
1628        n
1629    }
1630
1631    #[cfg(test)]
1632    pub(crate) fn insert_failed_spawn_for_test(&mut self) {
1633        let key = ServerKey {
1634            kind: crate::lsp::registry::ServerKind::Rust,
1635            root: std::path::PathBuf::from("/tmp/test-root"),
1636        };
1637        self.failed_spawns.insert(
1638            key,
1639            ServerAttemptResult::SpawnFailed {
1640                binary: "rust-analyzer".to_string(),
1641                reason: "test".to_string(),
1642            },
1643        );
1644    }
1645
1646    pub fn clear_diagnostics_for_file(&mut self, file: &Path) -> bool {
1647        let mut removed = self.diagnostics.clear_for_file(file);
1648
1649        let normalized = normalize_lookup_path(file);
1650        if normalized != file {
1651            removed |= self.diagnostics.clear_for_file(&normalized);
1652        }
1653
1654        // Reconstruct the canonical key via the parent dir (which still exists
1655        // for a just-deleted file) so symlink-aliased roots still match.
1656        if let (Some(parent), Some(name)) = (file.parent(), file.file_name()) {
1657            if let Ok(canonical_parent) = std::fs::canonicalize(parent) {
1658                let reconstructed = canonical_parent.join(name);
1659                if reconstructed != file && reconstructed != normalized {
1660                    removed |= self.diagnostics.clear_for_file(&reconstructed);
1661                }
1662            }
1663        }
1664
1665        removed
1666    }
1667
1668    /// Mark cached diagnostics for this file stale after a watcher-observed
1669    /// external edit. The same path aliases as deletion are checked so canonical
1670    /// publish keys are found even when the watcher reports a symlinked path.
1671    pub fn mark_diagnostics_stale_for_file(&mut self, file: &Path) -> StaleDiagnosticsMark {
1672        let mut candidates = vec![file.to_path_buf()];
1673        let normalized = normalize_lookup_path(file);
1674        if !candidates.iter().any(|candidate| candidate == &normalized) {
1675            candidates.push(normalized.clone());
1676        }
1677
1678        if let (Some(parent), Some(name)) = (file.parent(), file.file_name()) {
1679            if let Ok(canonical_parent) = std::fs::canonicalize(parent) {
1680                let reconstructed = canonical_parent.join(name);
1681                if !candidates
1682                    .iter()
1683                    .any(|candidate| candidate == &reconstructed)
1684                {
1685                    candidates.push(reconstructed);
1686                }
1687            }
1688        }
1689
1690        let mut result = StaleDiagnosticsMark::default();
1691        for candidate in candidates {
1692            let (had_entries, changed) = self.diagnostics.mark_stale_for_file(&candidate);
1693            result.had_entries |= had_entries;
1694            result.changed |= changed;
1695        }
1696        result
1697    }
1698
1699    pub fn get_diagnostics_for_directory(&self, dir: &Path) -> Vec<&StoredDiagnostic> {
1700        let normalized = normalize_lookup_path(dir);
1701        self.diagnostics.for_directory(&normalized)
1702    }
1703
1704    pub fn get_all_diagnostics(&self) -> Vec<&StoredDiagnostic> {
1705        self.diagnostics.all()
1706    }
1707
1708    /// True if any LSP server has a current diagnostic report, including an
1709    /// empty report that proves a checked-clean file. This lets callers avoid
1710    /// treating an empty flattened diagnostic list as trustworthy when no server
1711    /// has actually run or every report was marked stale after an external edit.
1712    pub fn has_any_diagnostic_reports(&self) -> bool {
1713        self.diagnostics.has_any_fresh_report()
1714    }
1715
1716    /// True if any server has a current report for this file, including an
1717    /// empty checked-clean report. Watcher-stale reports are excluded because
1718    /// they predate an external edit.
1719    pub fn has_diagnostic_report_for_file(&self, file: &Path) -> bool {
1720        let normalized = normalize_lookup_path(file);
1721        self.diagnostics.has_any_fresh_report_for_file(&normalized)
1722    }
1723
1724    /// True if this exact server/file pair has a current diagnostic report,
1725    /// including an empty checked-clean report. Watcher-stale reports are
1726    /// excluded because they predate an external edit.
1727    pub fn has_diagnostic_report_for_server_file(&self, server: &ServerKey, file: &Path) -> bool {
1728        let normalized = normalize_lookup_path(file);
1729        self.diagnostics
1730            .has_fresh_report_for_server_file(server, &normalized)
1731    }
1732
1733    fn drain_events_for_file(&mut self, file_path: &Path) -> bool {
1734        let mut saw_file_diagnostics = false;
1735        while let Ok(event) = self.event_rx.try_recv() {
1736            if matches!(
1737                self.handle_event(&event),
1738                Some(ref published_file) if published_file.as_path() == file_path
1739            ) {
1740                saw_file_diagnostics = true;
1741            }
1742        }
1743        saw_file_diagnostics
1744    }
1745
1746    fn handle_event(&mut self, event: &LspEvent) -> Option<PathBuf> {
1747        match event {
1748            LspEvent::Notification {
1749                server_kind,
1750                root,
1751                method,
1752                params: Some(params),
1753            } if method == "textDocument/publishDiagnostics" => {
1754                self.handle_publish_diagnostics(server_kind.clone(), root.clone(), params)
1755            }
1756            LspEvent::ServerExited { server_kind, root } => {
1757                let key = ServerKey {
1758                    kind: server_kind.clone(),
1759                    root: root.clone(),
1760                };
1761                self.clients.remove(&key);
1762                self.server_binaries.remove(&key);
1763                self.documents.remove(&key);
1764                self.diagnostics.clear_for_server(&key);
1765                None
1766            }
1767            _ => None,
1768        }
1769    }
1770
1771    fn handle_publish_diagnostics(
1772        &mut self,
1773        server: ServerKind,
1774        root: PathBuf,
1775        params: &serde_json::Value,
1776    ) -> Option<PathBuf> {
1777        if let Ok(publish_params) =
1778            serde_json::from_value::<lsp_types::PublishDiagnosticsParams>(params.clone())
1779        {
1780            let file = uri_to_path(&publish_params.uri)?;
1781            let stored = from_lsp_diagnostics(file.clone(), publish_params.diagnostics);
1782            // v0.17.3: store with real ServerKey { kind, root } and capture
1783            // the document `version` (when the server provided one) so the
1784            // post-edit waiter can reject stale publishes deterministically
1785            // via version-match (preferred) or epoch-delta (fallback). The
1786            // earlier `publish_with_kind` path silently dropped both.
1787            let key = ServerKey { kind: server, root };
1788            self.diagnostics
1789                .publish_full(key, file.clone(), stored, None, publish_params.version);
1790            return Some(file);
1791        }
1792        None
1793    }
1794
1795    fn spawn_server(
1796        &self,
1797        def: &ServerDef,
1798        root: &Path,
1799        config: &Config,
1800    ) -> Result<LspClient, LspError> {
1801        let binary = self.resolve_binary(def, config)?;
1802
1803        // Merge the server-defined env with our test-injected env.
1804        // `extra_env` is empty in production; tests use it to drive fake
1805        // server variants (AFT_FAKE_LSP_PULL=1, etc.).
1806        let mut merged_env = def.env.clone();
1807        for (key, value) in &self.extra_env {
1808            merged_env.insert(key.clone(), value.clone());
1809        }
1810
1811        let mut client = LspClient::spawn(
1812            def.kind.clone(),
1813            root.to_path_buf(),
1814            &binary,
1815            &def.args,
1816            &merged_env,
1817            self.event_tx.clone(),
1818            self.child_registry.clone(),
1819        )?;
1820        if let Err(err) = client.initialize(root, def.initialization_options.clone()) {
1821            wait_for_stderr_tail(&mut client);
1822            let stderr_tail = client.stderr_tail();
1823            let reason = if client.child_exited() || !stderr_tail.is_empty() {
1824                format_initialize_failure_reason(&def.binary, &stderr_tail, &err)
1825            } else {
1826                format!("server failed during initialize: {err}")
1827            };
1828            return Err(LspError::ServerNotReady(reason));
1829        }
1830        Ok(client)
1831    }
1832
1833    fn resolve_binary(&self, def: &ServerDef, config: &Config) -> Result<PathBuf, LspError> {
1834        if let Some(path) = self.binary_overrides.get(&def.kind) {
1835            if path.exists() {
1836                return Ok(path.clone());
1837            }
1838            return Err(LspError::NotFound(format!(
1839                "override binary for {:?} not found: {}",
1840                def.kind,
1841                path.display()
1842            )));
1843        }
1844
1845        if let Some(path) = env_binary_override(&def.kind) {
1846            if path.exists() {
1847                return Ok(path);
1848            }
1849            return Err(LspError::NotFound(format!(
1850                "environment override binary for {:?} not found: {}",
1851                def.kind,
1852                path.display()
1853            )));
1854        }
1855
1856        // Layered resolution:
1857        //   1. <project_root>/node_modules/.bin/<binary>
1858        //   2. config.lsp_paths_extra (plugin auto-install cache, etc.)
1859        //   3. PATH via `which`
1860        resolve_lsp_binary(
1861            &def.binary,
1862            config.project_root.as_deref(),
1863            &config.lsp_paths_extra,
1864        )
1865        .ok_or_else(|| {
1866            LspError::NotFound(format!(
1867                "language server binary '{}' not found in node_modules/.bin, lsp_paths_extra, or PATH",
1868                def.binary
1869            ))
1870        })
1871    }
1872
1873    fn server_key_for_file(&self, file_path: &Path, config: &Config) -> Option<ServerKey> {
1874        for def in servers_for_file(file_path, config) {
1875            let root = def.workspace_root_for_file(file_path)?;
1876            let key = ServerKey {
1877                kind: def.kind.clone(),
1878                root,
1879            };
1880            if self.clients.contains_key(&key) {
1881                return Some(key);
1882            }
1883        }
1884        None
1885    }
1886}
1887
1888impl Default for LspManager {
1889    fn default() -> Self {
1890        Self::new()
1891    }
1892}
1893
1894fn wait_for_stderr_tail(client: &mut LspClient) {
1895    for _ in 0..10 {
1896        if !client.stderr_tail().is_empty() {
1897            break;
1898        }
1899        std::thread::sleep(std::time::Duration::from_millis(10));
1900    }
1901}
1902
1903fn recoverable_pull_rejection(err: &LspError) -> bool {
1904    matches!(
1905        err,
1906        LspError::ServerError {
1907            code: -32601 | -32602,
1908            ..
1909        }
1910    )
1911}
1912
1913fn server_attempt_result_reason(result: &ServerAttemptResult) -> String {
1914    match result {
1915        ServerAttemptResult::SpawnFailed { binary, reason } => {
1916            format!("spawn_failed: {binary} ({reason})")
1917        }
1918        ServerAttemptResult::BinaryNotInstalled { binary } => {
1919            format!("binary_not_installed: {binary}")
1920        }
1921        ServerAttemptResult::NoRootMarker { looked_for } => {
1922            format!("no_root_marker (looked for: {})", looked_for.join(", "))
1923        }
1924        ServerAttemptResult::Ok { .. } => "ok".to_string(),
1925    }
1926}
1927
1928fn format_stderr_tail_for_reason(stderr_tail: &str) -> String {
1929    truncate_stderr_tail_for_reason(stderr_tail)
1930        .lines()
1931        .map(|line| format!("  {line}"))
1932        .collect::<Vec<_>>()
1933        .join("\n")
1934}
1935
1936fn truncate_stderr_tail_for_reason(stderr_tail: &str) -> String {
1937    if stderr_tail.len() <= STDERR_REASON_BYTES {
1938        return stderr_tail.to_string();
1939    }
1940
1941    let ellipsis = "...";
1942    let target_len = STDERR_REASON_BYTES.saturating_sub(ellipsis.len());
1943    let mut start = stderr_tail.len() - target_len;
1944    while start < stderr_tail.len() && !stderr_tail.is_char_boundary(start) {
1945        start += 1;
1946    }
1947    format!("{ellipsis}{}", &stderr_tail[start..])
1948}
1949
1950fn format_initialize_failure_reason(binary: &str, stderr_tail: &str, err: &LspError) -> String {
1951    let mut reason = format!("server crashed during initialize: {err}");
1952    if !stderr_tail.is_empty() {
1953        reason.push_str("; stderr (last 64 lines):\n");
1954        reason.push_str(&format_stderr_tail_for_reason(stderr_tail));
1955        reason.push_str("\n\n");
1956        reason.push_str(&failure_hint(binary, stderr_tail));
1957    }
1958    reason
1959}
1960
1961fn format_post_initialize_exit_reason(
1962    binary: &str,
1963    status: std::process::ExitStatus,
1964    stderr_tail: &str,
1965    err: &LspError,
1966) -> String {
1967    let code = status
1968        .code()
1969        .map(|c| c.to_string())
1970        .unwrap_or_else(|| "signal/unknown".to_string());
1971    let mut reason = format!("server exited after initialize (code {code}): {err}");
1972    if !stderr_tail.is_empty() {
1973        reason.push_str("; stderr (last 64 lines):\n");
1974        reason.push_str(&format_stderr_tail_for_reason(stderr_tail));
1975        reason.push_str("\n\n");
1976        reason.push_str(&failure_hint(binary, stderr_tail));
1977    }
1978    reason
1979}
1980
1981fn failure_hint(binary: &str, stderr_tail: &str) -> String {
1982    if stderr_tail.contains("MODULE_NOT_FOUND") || stderr_tail.contains("Cannot find module") {
1983        let package_manager = infer_package_manager(stderr_tail);
1984        format!(
1985            "Your package-manager shim resolves to a missing file. Try reinstalling: {package_manager} install -g {binary} --force. Common cause: hard-link breakage from fs migration or store prune."
1986        )
1987    } else if let Some(component) = rustup_missing_component(stderr_tail) {
1988        // The binary on PATH is rustup's proxy shim, but the toolchain
1989        // component isn't installed, so rustup rejects the dispatch with
1990        // "Unknown binary '<name>' in ... toolchain". The actionable fix is to
1991        // add the component, not anything about the binary itself.
1992        format!("'{component}' is a rustup proxy but the component is not installed. Install it: rustup component add {component}")
1993    } else {
1994        format!("Hint: see stderr above for '{binary}' failure details.")
1995    }
1996}
1997
1998/// Detect the rustup "proxy shim without installed component" failure and
1999/// return the component name to add. rustup prints
2000/// `error: Unknown binary '<name>' in official toolchain '<triple>'` when a
2001/// `~/.cargo/bin/<name>` proxy is on PATH but the component was never installed
2002/// (the canonical case is `rust-analyzer`, which ships as an opt-in component).
2003fn rustup_missing_component(stderr_tail: &str) -> Option<String> {
2004    let marker = "Unknown binary '";
2005    let start = stderr_tail.find(marker)? + marker.len();
2006    let rest = &stderr_tail[start..];
2007    let end = rest.find('\'')?;
2008    let name = &rest[..end];
2009    // Only treat it as a rustup-component issue when the toolchain phrasing is
2010    // present, so an unrelated "Unknown binary" message doesn't mislead.
2011    if name.is_empty() || !stderr_tail.contains("toolchain") {
2012        return None;
2013    }
2014    Some(name.to_string())
2015}
2016
2017fn infer_package_manager(stderr_tail: &str) -> &'static str {
2018    let lower = stderr_tail.to_ascii_lowercase();
2019    if lower.contains(".pnpm/") || lower.contains(".pnpm\\") || lower.contains("/pnpm/") {
2020        "pnpm"
2021    } else if lower.contains(".yarn/")
2022        || lower.contains(".yarn\\")
2023        || lower.contains("/yarn/")
2024        || lower.contains("yarn")
2025    {
2026        "yarn"
2027    } else {
2028        "npm"
2029    }
2030}
2031
2032fn canonicalize_for_lsp(file_path: &Path) -> Result<PathBuf, LspError> {
2033    std::fs::canonicalize(file_path).map_err(LspError::from)
2034}
2035
2036fn resolve_for_lsp_uri(file_path: &Path) -> PathBuf {
2037    if let Ok(path) = std::fs::canonicalize(file_path) {
2038        return path;
2039    }
2040
2041    let mut existing = file_path.to_path_buf();
2042    let mut missing = Vec::new();
2043    while !existing.exists() {
2044        let Some(name) = existing.file_name() else {
2045            break;
2046        };
2047        missing.push(name.to_owned());
2048        let Some(parent) = existing.parent() else {
2049            break;
2050        };
2051        existing = parent.to_path_buf();
2052    }
2053
2054    let mut resolved = std::fs::canonicalize(&existing).unwrap_or(existing);
2055    for segment in missing.into_iter().rev() {
2056        resolved.push(segment);
2057    }
2058    resolved
2059}
2060
2061fn language_id_for_extension(ext: &str) -> &'static str {
2062    match ext {
2063        "ts" => "typescript",
2064        "tsx" => "typescriptreact",
2065        "js" | "mjs" | "cjs" => "javascript",
2066        "jsx" => "javascriptreact",
2067        "py" | "pyi" => "python",
2068        "rs" => "rust",
2069        "go" => "go",
2070        "html" | "htm" => "html",
2071        _ => "plaintext",
2072    }
2073}
2074
2075fn normalize_lookup_path(path: &Path) -> PathBuf {
2076    std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
2077}
2078
2079/// Classify an error returned by `spawn_server` into a structured
2080/// `ServerAttemptResult`. The two interesting cases for callers are:
2081/// - `BinaryNotInstalled` — the server's binary couldn't be resolved on PATH
2082///   or via override. The agent can be told "install bash-language-server".
2083/// - `SpawnFailed` — binary was found but spawning/initializing failed
2084///   (permissions, missing runtime, server crashed during initialize, etc.).
2085fn classify_spawn_error(binary: &str, err: &LspError) -> ServerAttemptResult {
2086    match err {
2087        // resolve_binary returns NotFound for both missing override paths and
2088        // missing PATH binaries. The "override missing" case is rare in
2089        // practice (only set in tests / env vars); we report all NotFound as
2090        // BinaryNotInstalled so the user sees an actionable install hint.
2091        LspError::NotFound(_) => ServerAttemptResult::BinaryNotInstalled {
2092            binary: binary.to_string(),
2093        },
2094        other => ServerAttemptResult::SpawnFailed {
2095            binary: binary.to_string(),
2096            reason: other.to_string(),
2097        },
2098    }
2099}
2100
2101fn env_binary_override(kind: &ServerKind) -> Option<PathBuf> {
2102    let id = kind.id_str();
2103    let suffix: String = id
2104        .chars()
2105        .map(|ch| {
2106            if ch.is_ascii_alphanumeric() {
2107                ch.to_ascii_uppercase()
2108            } else {
2109                '_'
2110            }
2111        })
2112        .collect();
2113    let key = format!("AFT_LSP_{suffix}_BINARY");
2114    std::env::var_os(key).map(PathBuf::from)
2115}
2116
2117#[cfg(test)]
2118mod failure_hint_tests {
2119    use super::{failure_hint, rustup_missing_component};
2120
2121    #[test]
2122    fn detects_rustup_proxy_without_component() {
2123        // The exact rustup stderr for a proxy shim whose component is missing.
2124        let stderr = "error: Unknown binary 'rust-analyzer' in official toolchain 'stable-aarch64-apple-darwin'.";
2125        assert_eq!(
2126            rustup_missing_component(stderr).as_deref(),
2127            Some("rust-analyzer")
2128        );
2129        let hint = failure_hint("rust-analyzer", stderr);
2130        assert!(
2131            hint.contains("rustup component add rust-analyzer"),
2132            "expected actionable rustup hint, got: {hint}"
2133        );
2134    }
2135
2136    #[test]
2137    fn ignores_unknown_binary_without_toolchain_phrasing() {
2138        // "Unknown binary" without the rustup toolchain phrasing must not be
2139        // misattributed to a rustup component issue.
2140        let stderr = "fatal: Unknown binary 'foo' was requested by the linker.";
2141        assert_eq!(rustup_missing_component(stderr), None);
2142        assert!(failure_hint("foo", stderr).starts_with("Hint: see stderr"));
2143    }
2144
2145    #[test]
2146    fn npm_module_not_found_still_wins() {
2147        // The existing package-manager-shim case is unaffected.
2148        let stderr = "Error: Cannot find module '/x/typescript-language-server/lib/cli.mjs'";
2149        let hint = failure_hint("typescript-language-server", stderr);
2150        assert!(hint.contains("install -g"), "got: {hint}");
2151    }
2152}
2153
2154#[cfg(test)]
2155mod diagnostic_capacity_tests {
2156    use super::LspManager;
2157
2158    // The lsp.diagnostic_cache_size config knob must actually take effect:
2159    // set_diagnostic_capacity (called at AppContext construction with the config
2160    // value) propagates the cap to the underlying DiagnosticsStore. Before this
2161    // wiring the field was parsed but never applied (always the hardcoded 5000).
2162    #[test]
2163    fn set_diagnostic_capacity_propagates_to_store() {
2164        let mut manager = LspManager::new();
2165        manager.set_diagnostic_capacity(7);
2166        assert_eq!(manager.diagnostics_store_for_test().capacity_for_test(), 7);
2167        manager.set_diagnostic_capacity(0); // 0 = unbounded
2168        assert_eq!(manager.diagnostics_store_for_test().capacity_for_test(), 0);
2169    }
2170
2171    // configure clears cached spawn failures so a just-installed server retries
2172    // without a full restart.
2173    #[test]
2174    fn clear_failed_spawns_empties_the_cache() {
2175        let mut manager = LspManager::new();
2176        assert_eq!(manager.clear_failed_spawns(), 0);
2177        manager.insert_failed_spawn_for_test();
2178        assert_eq!(manager.clear_failed_spawns(), 1);
2179        assert_eq!(manager.clear_failed_spawns(), 0);
2180    }
2181}
2182
2183#[cfg(test)]
2184mod clear_diagnostics_tests {
2185    use std::path::PathBuf;
2186
2187    use super::LspManager;
2188    use crate::lsp::client::LspEvent;
2189    use crate::lsp::diagnostics::{DiagnosticSeverity, StoredDiagnostic};
2190    use crate::lsp::position::uri_for_path;
2191    use crate::lsp::registry::ServerKind;
2192    use crate::lsp::roots::ServerKey;
2193
2194    fn err_diag(file: &PathBuf) -> StoredDiagnostic {
2195        StoredDiagnostic {
2196            file: file.clone(),
2197            line: 1,
2198            column: 1,
2199            end_line: 1,
2200            end_column: 2,
2201            severity: DiagnosticSeverity::Error,
2202            message: "boom".into(),
2203            code: None,
2204            source: None,
2205        }
2206    }
2207
2208    // A just-deleted file can no longer be canonicalized directly, but its
2209    // store key was the canonical path from publish time. The manager must
2210    // reconstruct that key via the still-present parent dir so symlink-aliased
2211    // roots (macOS /var -> /private/var) still match and the diagnostic clears.
2212    #[test]
2213    fn clear_diagnostics_for_deleted_file_matches_canonical_key() {
2214        let dir = tempfile::tempdir().unwrap();
2215        // Canonicalize the parent the way publish time would have.
2216        let canonical_dir = std::fs::canonicalize(dir.path()).unwrap();
2217        let canonical_file = canonical_dir.join("gone.ts");
2218        // Write then remove the file so its parent exists but the file does not,
2219        // mirroring the post-delete state the watcher observes.
2220        std::fs::write(&canonical_file, "x").unwrap();
2221
2222        let mut manager = LspManager::new();
2223        let key = ServerKey {
2224            kind: ServerKind::TypeScript,
2225            root: canonical_dir.clone(),
2226        };
2227        manager.diagnostics_store_mut_for_test().publish(
2228            key,
2229            canonical_file.clone(),
2230            vec![err_diag(&canonical_file)],
2231        );
2232        assert_eq!(manager.warm_error_warning_counts(), (1, 0));
2233
2234        std::fs::remove_file(&canonical_file).unwrap();
2235
2236        // Clear by the NON-canonical path the watcher might hand us (the raw
2237        // tempdir path, which on macOS differs from the canonical /private form).
2238        let watcher_path = dir.path().join("gone.ts");
2239        let removed = manager.clear_diagnostics_for_file(&watcher_path);
2240
2241        assert!(removed, "expected the deleted file's diagnostic to clear");
2242        assert_eq!(manager.warm_error_warning_counts(), (0, 0));
2243    }
2244
2245    #[test]
2246    fn clear_diagnostics_for_unknown_file_is_noop() {
2247        let mut manager = LspManager::new();
2248        assert!(!manager.clear_diagnostics_for_file(&PathBuf::from("/nope/missing.ts")));
2249        assert_eq!(manager.warm_error_warning_counts(), (0, 0));
2250    }
2251
2252    #[test]
2253    fn drain_events_reports_publish_diagnostics_updates() {
2254        let dir = tempfile::tempdir().unwrap();
2255        let root = std::fs::canonicalize(dir.path()).unwrap();
2256        let file = root.join("main.ts");
2257        std::fs::write(&file, "const x: number = 'nope';").unwrap();
2258
2259        let mut manager = LspManager::new();
2260        let diagnostic = lsp_types::Diagnostic {
2261            range: lsp_types::Range {
2262                start: lsp_types::Position {
2263                    line: 0,
2264                    character: 0,
2265                },
2266                end: lsp_types::Position {
2267                    line: 0,
2268                    character: 1,
2269                },
2270            },
2271            severity: Some(lsp_types::DiagnosticSeverity::ERROR),
2272            code: None,
2273            code_description: None,
2274            source: Some("test".into()),
2275            message: "boom".into(),
2276            related_information: None,
2277            tags: None,
2278            data: None,
2279        };
2280        let params = serde_json::to_value(lsp_types::PublishDiagnosticsParams {
2281            uri: uri_for_path(&file).unwrap(),
2282            diagnostics: vec![diagnostic],
2283            version: Some(1),
2284        })
2285        .unwrap();
2286        manager
2287            .event_tx
2288            .send(LspEvent::Notification {
2289                server_kind: ServerKind::TypeScript,
2290                root,
2291                method: "textDocument/publishDiagnostics".into(),
2292                params: Some(params),
2293            })
2294            .unwrap();
2295
2296        let drained = manager.drain_events();
2297
2298        assert!(drained.diagnostics_changed);
2299        assert_eq!(drained.events.len(), 1);
2300        assert_eq!(manager.warm_error_warning_counts(), (1, 0));
2301    }
2302}