Skip to main content

perspt_agent/
lsp.rs

1//! Native LSP Client
2//!
3//! Lightweight JSON-RPC client for Language Server Protocol communication.
4//! Provides the "Sensor Architecture" for SRBN stability monitoring.
5
6use anyhow::{Context, Result};
7use lsp_types::{Diagnostic, DiagnosticSeverity, InitializeParams, InitializeResult};
8use serde::Deserialize;
9use serde_json::{Value, json};
10use std::collections::HashMap;
11use std::path::Path;
12use std::process::Stdio;
13use std::sync::Arc;
14use std::sync::atomic::{AtomicU64, Ordering};
15use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
16use tokio::process::{Child, ChildStdin, Command};
17use tokio::sync::{Mutex, oneshot};
18
19use perspt_core::plugin::LspConfig;
20use perspt_sandbox::{ProcessPolicy, ProcessSandbox};
21
22/// Type alias for pending LSP requests map
23type PendingRequests = Arc<Mutex<HashMap<u64, oneshot::Sender<Result<Value>>>>>;
24/// Type alias for diagnostics map
25type DiagnosticsMap = Arc<Mutex<HashMap<String, Vec<Diagnostic>>>>;
26
27/// Simplified document symbol information for agent use
28#[derive(Debug, Clone)]
29pub struct DocumentSymbolInfo {
30    /// Symbol name (e.g., function name, class name)
31    pub name: String,
32    /// Symbol kind (e.g., "Function", "Class", "Variable")
33    pub kind: String,
34    /// Range in the document
35    pub range: lsp_types::Range,
36    /// Optional detail (e.g., type signature)
37    pub detail: Option<String>,
38}
39
40/// LSP Client for real-time diagnostics and symbol information
41pub struct LspClient {
42    /// Server stdin writer
43    stdin: Option<Arc<Mutex<ChildStdin>>>,
44    /// Request ID counter
45    request_id: AtomicU64,
46    /// Pending requests (ID -> Sender)
47    pending_requests: Arc<Mutex<HashMap<u64, oneshot::Sender<Result<Value>>>>>,
48    /// Cached diagnostics per file
49    diagnostics: Arc<Mutex<HashMap<String, Vec<Diagnostic>>>>,
50    /// Server name (e.g., "rust-analyzer", "pyright")
51    server_name: String,
52    /// Language ID for textDocument/didOpen (e.g., "rust", "python")
53    language_id: String,
54    /// Keep track of the process to kill it on drop
55    process: Option<Child>,
56    /// Whether the server is initialized
57    initialized: bool,
58    /// Explicit reduced-isolation mode inherited from the agent run.
59    allow_unisolated: bool,
60}
61
62impl LspClient {
63    /// Create a new LSP client (not connected)
64    pub fn new(server_name: &str) -> Self {
65        Self {
66            stdin: None,
67            request_id: AtomicU64::new(1),
68            pending_requests: Arc::new(Mutex::new(HashMap::new())),
69            diagnostics: Arc::new(Mutex::new(HashMap::new())),
70            server_name: server_name.to_string(),
71            language_id: String::new(),
72            process: None,
73            initialized: false,
74            allow_unisolated: false,
75        }
76    }
77
78    /// Create a new LSP client from a plugin's LspConfig.
79    ///
80    /// Stores the language_id so `did_open` can tag documents correctly
81    /// without guessing from file extensions.
82    pub fn from_config(config: &LspConfig) -> Self {
83        Self {
84            stdin: None,
85            request_id: AtomicU64::new(1),
86            pending_requests: Arc::new(Mutex::new(HashMap::new())),
87            diagnostics: Arc::new(Mutex::new(HashMap::new())),
88            server_name: config.server_binary.clone(),
89            language_id: config.language_id.clone(),
90            process: None,
91            initialized: false,
92            allow_unisolated: false,
93        }
94    }
95
96    pub(crate) fn allow_unisolated(mut self, allow: bool) -> Self {
97        self.allow_unisolated = allow;
98        self
99    }
100
101    /// Get the command for a known language server
102    fn get_server_command(server_name: &str) -> Option<(&'static str, Vec<&'static str>)> {
103        match server_name {
104            "rust-analyzer" => Some(("rust-analyzer", vec![])),
105            "pyright" => Some(("pyright-langserver", vec!["--stdio"])),
106            // ty is installed via uv, so use uvx to run it
107            "ty" => Some(("uvx", vec!["ty", "server"])),
108            "typescript" => Some(("typescript-language-server", vec!["--stdio"])),
109            "gopls" => Some(("gopls", vec!["serve"])),
110            _ => None,
111        }
112    }
113
114    /// Start the language server process
115    pub async fn start(&mut self, workspace_root: &Path) -> Result<()> {
116        let (cmd, args) = Self::get_server_command(&self.server_name)
117            .context(format!("Unknown language server: {}", self.server_name))?;
118
119        let args_owned: Vec<String> = args.iter().map(|s| s.to_string()).collect();
120        self.start_process(cmd, &args_owned, workspace_root).await
121    }
122
123    /// Start using a plugin's LspConfig.
124    ///
125    /// Preferred over `start()` when a `LanguagePlugin` is available, because
126    /// it uses the config's binary and args directly — no lookup table needed.
127    pub async fn start_with_config(
128        &mut self,
129        config: &LspConfig,
130        workspace_root: &Path,
131    ) -> Result<()> {
132        self.start_process(&config.server_binary, &config.args, workspace_root)
133            .await
134    }
135
136    /// Internal: spawn the LSP child process, wire up stdio, run initialize.
137    async fn start_process(
138        &mut self,
139        cmd: &str,
140        args: &[String],
141        workspace_root: &Path,
142    ) -> Result<()> {
143        log::info!("Starting LSP server: {} {:?}", cmd, args);
144
145        let policy = if self.allow_unisolated {
146            ProcessPolicy::inspection(workspace_root).best_effort()
147        } else {
148            ProcessPolicy::inspection(workspace_root)
149        };
150        let prepared = ProcessSandbox::new(cmd, args.to_vec(), policy)?.prepare_invocation()?;
151        let mut child = Command::new(&prepared.program);
152        child
153            .args(&prepared.args)
154            .current_dir(&prepared.working_dir)
155            .env_clear()
156            .envs(&prepared.environment)
157            .stdin(Stdio::piped())
158            .stdout(Stdio::piped())
159            .stderr(Stdio::piped());
160        let mut child = child.spawn().context(format!("Failed to start {}", cmd))?;
161
162        let stdin = child.stdin.take().context("No stdin")?;
163        let stdout = child.stdout.take().context("No stdout")?;
164        let stderr = child.stderr.take().context("No stderr")?;
165
166        // Handle stderr logging in background
167        tokio::spawn(async move {
168            let mut reader = BufReader::new(stderr).lines();
169            while let Ok(Some(line)) = reader.next_line().await {
170                log::debug!("[LSP stderr] {}", line);
171            }
172        });
173
174        // Handle stdout message loop
175        let pending_requests = self.pending_requests.clone();
176        let diagnostics = self.diagnostics.clone();
177
178        tokio::spawn(async move {
179            let mut reader = BufReader::new(stdout);
180            loop {
181                // Read headers
182                let mut content_length = 0;
183                loop {
184                    let mut line = String::new();
185                    match reader.read_line(&mut line).await {
186                        Ok(0) => return, // EOF
187                        Ok(_) => {
188                            if line == "\r\n" {
189                                break;
190                            }
191                            if line.starts_with("Content-Length:")
192                                && let Ok(len) = line
193                                    .trim_start_matches("Content-Length:")
194                                    .trim()
195                                    .parse::<usize>()
196                            {
197                                content_length = len;
198                            }
199                        }
200                        Err(e) => {
201                            log::error!("Error reading LSP header: {}", e);
202                            return;
203                        }
204                    }
205                }
206
207                if content_length == 0 {
208                    continue;
209                }
210
211                // Read body
212                let mut body = vec![0u8; content_length];
213                match reader.read_exact(&mut body).await {
214                    Ok(_) => {
215                        if let Ok(value) = serde_json::from_slice::<Value>(&body) {
216                            Self::handle_message(value, &pending_requests, &diagnostics).await;
217                        }
218                    }
219                    Err(e) => {
220                        log::error!("Error reading LSP body: {}", e);
221                        return;
222                    }
223                }
224            }
225        });
226
227        self.stdin = Some(Arc::new(Mutex::new(stdin)));
228        self.process = Some(child);
229        self.initialized = false;
230
231        // Send initialize request
232        self.initialize(workspace_root).await?;
233
234        Ok(())
235    }
236
237    /// Handle incoming LSP message
238    async fn handle_message(
239        msg: Value,
240        pending_requests: &PendingRequests,
241        diagnostics: &DiagnosticsMap,
242    ) {
243        if let Some(id) = msg.get("id").and_then(|id| id.as_u64()) {
244            // It's a response
245            let mut pending = pending_requests.lock().await;
246            if let Some(tx) = pending.remove(&id) {
247                if let Some(error) = msg.get("error") {
248                    let _ = tx.send(Err(anyhow::anyhow!("LSP error: {}", error)));
249                } else if let Some(result) = msg.get("result") {
250                    let _ = tx.send(Ok(result.clone()));
251                } else {
252                    let _ = tx.send(Ok(Value::Null));
253                }
254            }
255        } else if let Some(method) = msg.get("method").and_then(|m| m.as_str()) {
256            // It's a notification
257            if method == "textDocument/publishDiagnostics"
258                && let Some(params) = msg.get("params")
259                && let (Some(uri), Some(diags)) = (
260                    params.get("uri").and_then(|u| u.as_str()),
261                    params
262                        .get("diagnostics")
263                        .and_then(|d| serde_json::from_value::<Vec<Diagnostic>>(d.clone()).ok()),
264                )
265            {
266                // Normalize URI to file path
267                let path = uri.trim_start_matches("file://");
268
269                // For ty/lsp, path might be absolute or relative, ensure we match broadly
270                // Store exactly what we got for now
271                let mut diag_map = diagnostics.lock().await;
272
273                // Also try to simplify the key to just filename for easier lookup
274                // This assumes unique filenames which is a simplification but useful
275                if let Some(filename) = Path::new(path).file_name() {
276                    let filename_str = filename.to_string_lossy().to_string();
277                    diag_map.insert(filename_str, diags.clone());
278                }
279
280                diag_map.insert(path.to_string(), diags);
281                log::info!("Updated diagnostics for {}", path);
282            }
283        }
284    }
285
286    /// Send the initialize request
287    #[allow(deprecated)]
288    async fn initialize(&mut self, workspace_root: &Path) -> Result<InitializeResult> {
289        // Build a file:// URI from the path
290        let path_str = workspace_root.to_string_lossy();
291        #[cfg(target_os = "windows")]
292        let uri_string = format!("file:///{}", path_str.replace('\\', "/"));
293        #[cfg(not(target_os = "windows"))]
294        let uri_string = format!("file://{}", path_str);
295
296        let root_uri: lsp_types::Uri = uri_string
297            .parse()
298            .map_err(|e| anyhow::anyhow!("Failed to parse URI: {:?}", e))?;
299
300        let params = InitializeParams {
301            root_uri: Some(root_uri),
302            capabilities: lsp_types::ClientCapabilities::default(),
303            ..Default::default()
304        };
305
306        let result: InitializeResult = self
307            .send_request("initialize", serde_json::to_value(params)?)
308            .await?;
309
310        // Send initialized notification
311        self.send_notification("initialized", json!({})).await?;
312        self.initialized = true;
313
314        log::info!("LSP server initialized: {:?}", result.server_info);
315        Ok(result)
316    }
317
318    /// Send a JSON-RPC request
319    async fn send_request<T: for<'de> Deserialize<'de>>(
320        &mut self,
321        method: &str,
322        params: Value,
323    ) -> Result<T> {
324        let id = self.request_id.fetch_add(1, Ordering::SeqCst);
325        let (tx, rx) = oneshot::channel();
326
327        // Register pending request
328        {
329            let mut pending = self.pending_requests.lock().await;
330            pending.insert(id, tx);
331        }
332
333        let request = json!({
334            "jsonrpc": "2.0",
335            "id": id,
336            "method": method,
337            "params": params
338        });
339
340        if let Err(e) = self.write_message(&request).await {
341            // Cleanup on error
342            let mut pending = self.pending_requests.lock().await;
343            pending.remove(&id);
344            return Err(e);
345        }
346
347        // Wait for response
348        let result = rx.await??;
349        Ok(serde_json::from_value(result)?)
350    }
351
352    /// Send a JSON-RPC notification
353    async fn send_notification(&mut self, method: &str, params: Value) -> Result<()> {
354        let notification = json!({
355            "jsonrpc": "2.0",
356            "method": method,
357            "params": params
358        });
359
360        self.write_message(&notification).await
361    }
362
363    /// Write a message to the server stdin
364    async fn write_message(&mut self, msg: &Value) -> Result<()> {
365        let content = serde_json::to_string(msg)?;
366        let message = format!("Content-Length: {}\r\n\r\n{}", content.len(), content);
367
368        if let Some(ref stdin_arc) = self.stdin {
369            let mut stdin = stdin_arc.lock().await;
370            stdin.write_all(message.as_bytes()).await?;
371            stdin.flush().await?;
372            Ok(())
373        } else {
374            Err(anyhow::anyhow!("LSP stdin not available"))
375        }
376    }
377
378    /// Get diagnostics for a file
379    /// Get diagnostics for a file
380    pub async fn get_diagnostics(&self, path: &str) -> Vec<Diagnostic> {
381        let map = self.diagnostics.lock().await;
382
383        // Collect cached diagnostics from any matching key
384        let mut cached = Vec::new();
385
386        // 1. Exact match
387        if let Some(diags) = map.get(path) {
388            cached = diags.clone();
389        }
390        // 2. Clean path (no file://)
391        else if let Some(diags) = map.get(path.trim_start_matches("file://")) {
392            cached = diags.clone();
393        }
394        // 3. URI format
395        else if !path.starts_with("file://") {
396            let uri = format!("file://{}", path);
397            if let Some(diags) = map.get(&uri) {
398                cached = diags.clone();
399            }
400        }
401
402        // 4. Filename fallback (only if still empty/not found)
403        if cached.is_empty()
404            && let Some(filename) = Path::new(path).file_name()
405        {
406            let filename_str = filename.to_string_lossy();
407            if let Some(diags) = map.get(filename_str.as_ref()) {
408                cached = diags.clone();
409            }
410        }
411
412        // If we found diagnostics, verify they aren't empty?
413        // Actually, valid code has empty diagnostics.
414        // But for 'ty', we want to be paranoid if it reports nothing.
415        if !cached.is_empty() {
416            return cached;
417        }
418
419        // Trust but Verify: If cached is empty (meaning LSP says "clean" or "unknown"),
420        // AND we are using `ty`, double-check with CLI.
421        // This is crucial for stability monitoring to avoid false negatives from async races.
422        if self.server_name == "ty" {
423            // Drop lock before await
424            drop(map);
425            return self.run_type_check(path).await;
426        }
427
428        Vec::new()
429    }
430
431    /// Run ty check CLI to get diagnostics for a file
432    async fn run_type_check(&self, path: &str) -> Vec<Diagnostic> {
433        use std::process::Command;
434
435        log::debug!("Running ty check on: {}", path);
436
437        // ty check doesn't support JSON output yet, so we parse the default output
438        let output = Command::new("uvx").args(["ty", "check", path]).output();
439
440        match output {
441            Ok(output) => {
442                let stdout = String::from_utf8_lossy(&output.stdout);
443                let stderr = String::from_utf8_lossy(&output.stderr);
444
445                log::debug!("ty check status: {}", output.status);
446                if !stdout.is_empty() {
447                    log::debug!("ty check stdout: {}", stdout);
448                }
449                if !stderr.is_empty() {
450                    log::debug!("ty check stderr: {}", stderr);
451                }
452
453                // Parse the output (ty outputs diagnostics to stderr in text format, but we check both)
454                let combined = format!("{}\n{}", stdout, stderr);
455                self.parse_ty_output(&combined, path)
456            }
457            Err(e) => {
458                log::warn!("Failed to run ty check: {}", e);
459                Vec::new()
460            }
461        }
462    }
463
464    /// Parse ty check text output into diagnostics
465    fn parse_ty_output(&self, output: &str, _path: &str) -> Vec<Diagnostic> {
466        let mut diagnostics = Vec::new();
467
468        // Look for lines like:
469        // error[invalid-return-type]: Return type does not match returned value
470        // ---> main.py:7:12
471
472        let lines: Vec<&str> = output.lines().collect();
473        let mut i = 0;
474
475        while i < lines.len() {
476            let line = lines[i];
477
478            // Check for error/warning prefix
479            if line.contains("error") || line.contains("warning") {
480                // Heuristic parsing for severity
481                let severity = if line.contains("error") {
482                    Some(DiagnosticSeverity::ERROR)
483                } else if line.contains("warning") {
484                    Some(DiagnosticSeverity::WARNING)
485                } else {
486                    Some(DiagnosticSeverity::INFORMATION)
487                };
488
489                // Extract message
490                // Try to find the message part after "error:" or "error[...]:"
491                let message = if let Some(idx) = line.find("]: ") {
492                    line[idx + 3..].to_string()
493                } else if let Some(idx) = line.find(": ") {
494                    line[idx + 2..].to_string()
495                } else {
496                    line.to_string()
497                };
498
499                // Look for location in next lines
500                let mut line_num = 0;
501                let mut col_num = 0;
502
503                // Scan up to 3 following lines for location
504                for j in 1..4 {
505                    if i + j < lines.len() {
506                        let next_line = lines[i + j];
507                        if next_line.trim().starts_with("-->") {
508                            // Parse:   --> main.py:7:12
509                            // or: --> main.py:7:12
510                            if let Some(parts) = next_line.split("-->").nth(1) {
511                                let parts: Vec<&str> = parts.trim().split(':').collect();
512                                if parts.len() >= 3 {
513                                    // parts[0] is filename
514                                    line_num = parts[1].parse().unwrap_or(0);
515                                    col_num = parts[2].parse().unwrap_or(0);
516                                }
517                            }
518                            break;
519                        }
520                    }
521                }
522
523                diagnostics.push(Diagnostic {
524                    range: lsp_types::Range {
525                        start: lsp_types::Position {
526                            line: if line_num > 0 { line_num - 1 } else { 0 },
527                            character: if col_num > 0 { col_num - 1 } else { 0 },
528                        },
529                        end: lsp_types::Position {
530                            line: if line_num > 0 { line_num - 1 } else { 0 },
531                            character: if col_num > 0 { col_num } else { 1 },
532                        },
533                    },
534                    severity,
535                    message,
536                    ..Default::default()
537                });
538            }
539
540            i += 1;
541        }
542
543        if !diagnostics.is_empty() {
544            log::info!("ty check found {} diagnostics", diagnostics.len());
545        }
546
547        diagnostics
548    }
549
550    /// Calculate syntactic energy from diagnostics
551    ///
552    /// V_syn = sum(severity_weight * count)
553    /// Error = 1.0, Warning = 0.1, Hint = 0.01
554    pub fn calculate_syntactic_energy(diagnostics: &[Diagnostic]) -> f32 {
555        diagnostics
556            .iter()
557            .map(|d| match d.severity {
558                Some(DiagnosticSeverity::ERROR) => 1.0,
559                Some(DiagnosticSeverity::WARNING) => 0.1,
560                Some(DiagnosticSeverity::INFORMATION) => 0.01,
561                Some(DiagnosticSeverity::HINT) => 0.001,
562                _ => 0.1, // Default for unknown or None
563            })
564            .sum()
565    }
566
567    /// Check if the server is running and initialized
568    pub fn is_ready(&self) -> bool {
569        self.initialized && self.process.is_some()
570    }
571
572    /// Notify language server that a file was opened
573    pub async fn did_open(&mut self, path: &std::path::Path, content: &str) -> Result<()> {
574        if !self.is_ready() {
575            return Ok(());
576        }
577
578        let uri = format!("file://{}", path.display());
579
580        // Prefer the language_id from plugin config; fall back to extension guess
581        let language_id = if !self.language_id.is_empty() {
582            self.language_id.as_str()
583        } else {
584            match path.extension().and_then(|e| e.to_str()) {
585                Some("py") => "python",
586                Some("rs") => "rust",
587                Some("js") => "javascript",
588                Some("ts") => "typescript",
589                Some("go") => "go",
590                _ => "plaintext",
591            }
592        };
593
594        self.send_notification(
595            "textDocument/didOpen",
596            json!({
597                "textDocument": {
598                    "uri": uri,
599                    "languageId": language_id,
600                    "version": 1,
601                    "text": content
602                }
603            }),
604        )
605        .await
606    }
607
608    /// Notify language server that a file changed
609    pub async fn did_change(
610        &mut self,
611        path: &std::path::Path,
612        content: &str,
613        version: i32,
614    ) -> Result<()> {
615        if !self.is_ready() {
616            return Ok(());
617        }
618
619        let uri = format!("file://{}", path.display());
620
621        self.send_notification(
622            "textDocument/didChange",
623            json!({
624                "textDocument": {
625                    "uri": uri,
626                    "version": version
627                },
628                "contentChanges": [{
629                    "text": content
630                }]
631            }),
632        )
633        .await
634    }
635
636    // =========================================================================
637    // Enhanced LSP Tools (PSP-4 Phase 2)
638    // =========================================================================
639
640    /// Go to definition of symbol at position
641    /// Uses textDocument/definition LSP request
642    pub async fn goto_definition(
643        &mut self,
644        path: &Path,
645        line: u32,
646        character: u32,
647    ) -> Option<Vec<lsp_types::Location>> {
648        if !self.is_ready() {
649            return None;
650        }
651
652        let uri = format!("file://{}", path.display());
653
654        let params = json!({
655            "textDocument": { "uri": uri },
656            "position": { "line": line, "character": character }
657        });
658
659        match self
660            .send_request::<Option<lsp_types::GotoDefinitionResponse>>(
661                "textDocument/definition",
662                params,
663            )
664            .await
665        {
666            Ok(Some(response)) => {
667                // Convert GotoDefinitionResponse to Vec<Location>
668                match response {
669                    lsp_types::GotoDefinitionResponse::Scalar(loc) => Some(vec![loc]),
670                    lsp_types::GotoDefinitionResponse::Array(locs) => Some(locs),
671                    lsp_types::GotoDefinitionResponse::Link(links) => Some(
672                        links
673                            .into_iter()
674                            .map(|l| lsp_types::Location {
675                                uri: l.target_uri,
676                                range: l.target_selection_range,
677                            })
678                            .collect(),
679                    ),
680                }
681            }
682            Ok(None) => None,
683            Err(e) => {
684                log::warn!("goto_definition failed: {}", e);
685                None
686            }
687        }
688    }
689
690    /// Find all references to symbol at position
691    /// Uses textDocument/references LSP request
692    pub async fn find_references(
693        &mut self,
694        path: &Path,
695        line: u32,
696        character: u32,
697        include_declaration: bool,
698    ) -> Vec<lsp_types::Location> {
699        if !self.is_ready() {
700            return Vec::new();
701        }
702
703        let uri = format!("file://{}", path.display());
704
705        let params = json!({
706            "textDocument": { "uri": uri },
707            "position": { "line": line, "character": character },
708            "context": { "includeDeclaration": include_declaration }
709        });
710
711        match self
712            .send_request::<Option<Vec<lsp_types::Location>>>("textDocument/references", params)
713            .await
714        {
715            Ok(Some(locs)) => locs,
716            Ok(None) => Vec::new(),
717            Err(e) => {
718                log::warn!("find_references failed: {}", e);
719                Vec::new()
720            }
721        }
722    }
723
724    /// Get hover information (type, docs) at position
725    /// Uses textDocument/hover LSP request
726    pub async fn hover(&mut self, path: &Path, line: u32, character: u32) -> Option<String> {
727        if !self.is_ready() {
728            return None;
729        }
730
731        let uri = format!("file://{}", path.display());
732
733        let params = json!({
734            "textDocument": { "uri": uri },
735            "position": { "line": line, "character": character }
736        });
737
738        match self
739            .send_request::<Option<lsp_types::Hover>>("textDocument/hover", params)
740            .await
741        {
742            Ok(Some(hover)) => {
743                // Extract text from hover contents
744                match hover.contents {
745                    lsp_types::HoverContents::Scalar(content) => {
746                        Some(Self::extract_marked_string(&content))
747                    }
748                    lsp_types::HoverContents::Array(contents) => Some(
749                        contents
750                            .iter()
751                            .map(Self::extract_marked_string)
752                            .collect::<Vec<_>>()
753                            .join("\n"),
754                    ),
755                    lsp_types::HoverContents::Markup(markup) => Some(markup.value),
756                }
757            }
758            Ok(None) => None,
759            Err(e) => {
760                log::warn!("hover failed: {}", e);
761                None
762            }
763        }
764    }
765
766    /// Extract text from MarkedString
767    fn extract_marked_string(content: &lsp_types::MarkedString) -> String {
768        match content {
769            lsp_types::MarkedString::String(s) => s.clone(),
770            lsp_types::MarkedString::LanguageString(ls) => {
771                format!("```{}\n{}\n```", ls.language, ls.value)
772            }
773        }
774    }
775
776    /// Get all symbols in a document
777    /// Uses textDocument/documentSymbol LSP request
778    pub async fn get_symbols(&mut self, path: &Path) -> Vec<DocumentSymbolInfo> {
779        if !self.is_ready() {
780            return Vec::new();
781        }
782
783        let uri = format!("file://{}", path.display());
784
785        let params = json!({
786            "textDocument": { "uri": uri }
787        });
788
789        match self
790            .send_request::<Option<lsp_types::DocumentSymbolResponse>>(
791                "textDocument/documentSymbol",
792                params,
793            )
794            .await
795        {
796            Ok(Some(response)) => match response {
797                lsp_types::DocumentSymbolResponse::Flat(symbols) => symbols
798                    .into_iter()
799                    .map(|s| DocumentSymbolInfo {
800                        name: s.name,
801                        kind: format!("{:?}", s.kind),
802                        range: s.location.range,
803                        detail: None,
804                    })
805                    .collect(),
806                lsp_types::DocumentSymbolResponse::Nested(symbols) => {
807                    Self::flatten_document_symbols(&symbols)
808                }
809            },
810            Ok(None) => Vec::new(),
811            Err(e) => {
812                log::warn!("get_symbols failed: {}", e);
813                Vec::new()
814            }
815        }
816    }
817
818    /// Flatten nested document symbols into a list
819    fn flatten_document_symbols(symbols: &[lsp_types::DocumentSymbol]) -> Vec<DocumentSymbolInfo> {
820        let mut result = Vec::new();
821        for sym in symbols {
822            result.push(DocumentSymbolInfo {
823                name: sym.name.clone(),
824                kind: format!("{:?}", sym.kind),
825                range: sym.range,
826                detail: sym.detail.clone(),
827            });
828            // Recursively add children
829            if let Some(ref children) = sym.children {
830                result.extend(Self::flatten_document_symbols(children));
831            }
832        }
833        result
834    }
835
836    /// Shutdown the language server
837    pub async fn shutdown(&mut self) -> Result<()> {
838        if let Some(ref mut process) = self.process {
839            let _ = process.kill().await;
840        }
841        self.process = None;
842        self.initialized = false;
843        Ok(())
844    }
845}
846
847impl Drop for LspClient {
848    fn drop(&mut self) {
849        if let Some(ref mut process) = self.process {
850            let _ = process.start_kill();
851        }
852    }
853}
854
855#[cfg(test)]
856mod tests {
857    use super::*;
858    use lsp_types::Range;
859
860    #[test]
861    fn test_syntactic_energy_calculation() {
862        let diagnostics = vec![
863            Diagnostic {
864                range: Range::default(),
865                severity: Some(DiagnosticSeverity::ERROR),
866                message: "error".to_string(),
867                ..Default::default()
868            },
869            Diagnostic {
870                range: Range::default(),
871                severity: Some(DiagnosticSeverity::WARNING),
872                message: "warning".to_string(),
873                ..Default::default()
874            },
875        ];
876
877        let energy = LspClient::calculate_syntactic_energy(&diagnostics);
878        assert!((energy - 1.1).abs() < 0.001);
879    }
880}