cartog 0.8.1

Code graph indexer for LLM coding agents. Map your codebase, navigate by graph.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};

use anyhow::{bail, Context, Result};
use serde_json::Value;

use super::client::LspClient;
use super::servers::{find_servers, is_binary_available};

/// Max seconds to wait for an LSP server to finish loading its project model.
const READY_TIMEOUT_SECS: u64 = 60;

/// Seconds to wait for $/progress notifications before switching to probe-based detection.
const PROGRESS_DETECT_SECS: u64 = 5;

/// Manages running LSP server instances, one per language.
pub struct LspManager {
    root: PathBuf,
    clients: HashMap<String, (LspClient, &'static str)>, // (client, language_id)
}

impl LspManager {
    pub fn new(root: &Path) -> Self {
        Self {
            root: root.to_path_buf(),
            clients: HashMap::new(),
        }
    }

    /// Ensure the manager's root matches the given path.
    /// If different, shut down all servers (they were initialized for a different project root).
    pub fn ensure_root(&mut self, root: &Path) {
        if self.root != root {
            tracing::info!("LSP: project root changed, restarting servers");
            self.shutdown_all();
            self.root = root.to_path_buf();
        }
    }

    /// Start a language server for the given cartog language.
    /// Returns Ok(()) if started successfully, Err if server not available or failed to init.
    pub fn start(&mut self, language: &str) -> Result<()> {
        if self.clients.contains_key(language) {
            return Ok(());
        }

        let candidates = find_servers(language);
        if candidates.is_empty() {
            bail!("no LSP server configured for {language}");
        }

        // Try each candidate in order, use the first one available on PATH
        let spec = candidates.iter().find(|s| is_binary_available(s.binary));

        let spec = match spec {
            Some(s) => s,
            None => {
                // Show install hints for all candidates
                let hints: Vec<_> = candidates
                    .iter()
                    .map(|s| format!("{}: {}", s.binary, s.install_hint))
                    .collect();
                bail!(
                    "no LSP server found on PATH. Install one of:\n  {}",
                    hints.join("\n  ")
                );
            }
        };

        let child = Command::new(spec.binary)
            .args(spec.args)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::null())
            .current_dir(&self.root)
            .spawn()
            .with_context(|| format!("failed to spawn {}", spec.binary))?;

        let mut client = LspClient::new(child)?;

        tracing::info!("LSP: waiting for {} to load project...", spec.binary);
        self.initialize(&mut client)?;

        self.clients
            .insert(language.to_string(), (client, spec.language_id));
        Ok(())
    }

    /// Send textDocument/definition and return the target location.
    pub fn definition(
        &mut self,
        language: &str,
        file_path: &str,
        line: u32,
        character: u32,
    ) -> Result<Option<DefinitionLocation>> {
        let (client, _) = self
            .clients
            .get_mut(language)
            .with_context(|| format!("no running LSP client for {language}"))?;

        let uri = path_to_uri(&self.root.join(file_path));

        let result = client.send_request(
            "textDocument/definition",
            serde_json::json!({
                "textDocument": { "uri": uri },
                "position": { "line": line, "character": character },
            }),
        )?;

        parse_definition_response(&result, &self.root)
    }

    /// Notify the server that a file is open (required before definition requests).
    pub fn open_file(&mut self, language: &str, file_path: &str, content: &str) -> Result<()> {
        let (client, language_id) = self
            .clients
            .get_mut(language)
            .with_context(|| format!("no running LSP client for {language}"))?;

        let uri = path_to_uri(&self.root.join(file_path));

        client.send_notification(
            "textDocument/didOpen",
            serde_json::json!({
                "textDocument": {
                    "uri": uri,
                    "languageId": language_id,
                    "version": 1,
                    "text": content,
                },
            }),
        )
    }

    /// Notify the server that a file is closed (frees server-side resources).
    pub fn close_file(&mut self, language: &str, file_path: &str) -> Result<()> {
        let (client, _) = self
            .clients
            .get_mut(language)
            .with_context(|| format!("no running LSP client for {language}"))?;

        let uri = path_to_uri(&self.root.join(file_path));

        client.send_notification(
            "textDocument/didClose",
            serde_json::json!({
                "textDocument": { "uri": uri },
            }),
        )
    }

    /// Check if the client for a language is still alive.
    pub fn is_alive(&mut self, language: &str) -> bool {
        self.clients
            .get_mut(language)
            .is_some_and(|(c, _)| c.is_alive())
    }

    /// Gracefully shut down all running servers.
    pub fn shutdown_all(&mut self) {
        for (lang, (mut client, _)) in self.clients.drain() {
            if let Err(e) = client.send_request("shutdown", Value::Null) {
                tracing::debug!("shutdown failed for {lang}: {e:#}");
                let _ = client.child.kill();
                let _ = client.child.wait();
                continue;
            }
            let _ = client.send_notification("exit", Value::Null);

            // Poll for graceful exit, kill if it takes too long
            let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
            loop {
                match client.child.try_wait() {
                    Ok(Some(_)) => break, // exited
                    Ok(None) if std::time::Instant::now() < deadline => {
                        std::thread::sleep(std::time::Duration::from_millis(50));
                    }
                    _ => {
                        tracing::debug!("{lang} server did not exit, killing");
                        let _ = client.child.kill();
                        let _ = client.child.wait();
                        break;
                    }
                }
            }
        }
    }

    fn initialize(&self, client: &mut LspClient) -> Result<()> {
        let root_uri = path_to_uri(&self.root);

        let _result = client.send_request(
            "initialize",
            serde_json::json!({
                "processId": std::process::id(),
                "rootUri": root_uri,
                "capabilities": {
                    "window": {
                        "workDoneProgress": true
                    },
                    "textDocument": {
                        "definition": { "dynamicRegistration": false }
                    }
                },
            }),
        )?;

        client.send_notification("initialized", serde_json::json!({}))?;

        // Two-strategy readiness detection:
        // 1. Progress-based: wait for $/progress begin→end lifecycle (rust-analyzer)
        // 2. Probe-based fallback: if no progress within 5s, poll with definition requests
        self.wait_until_ready(client)?;

        Ok(())
    }

    /// Wait for the server to be ready.
    ///
    /// **Strategy 1 — Progress notifications** (servers like rust-analyzer):
    /// Track `$/progress` begin/end scopes. Ready when all scopes close + 2s quiesce.
    ///
    /// **Strategy 2 — Skip** (servers like typescript-language-server):
    /// If no `$/progress` arrives within 5s, proceed immediately. These servers
    /// respond to definition requests while loading (returning null for unloaded files).
    fn wait_until_ready(&self, client: &mut LspClient) -> Result<()> {
        let start = std::time::Instant::now();
        let deadline = start + std::time::Duration::from_secs(READY_TIMEOUT_SECS);

        // Phase 1: try progress-based detection
        if let Some(elapsed) = self.wait_via_progress(client, deadline)? {
            tracing::info!("LSP: ready ({elapsed:.1}s)");
            return Ok(());
        }

        // No progress support — proceed immediately (server handles requests while loading)
        if let Some(elapsed) = self.wait_no_progress() {
            tracing::info!("LSP: no progress support, proceeding after {elapsed:.0}s");
        }
        Ok(())
    }

    /// Wait for $/progress scopes to complete. Returns `Some(elapsed)` if ready,
    /// `None` if no progress was received within the first 5s (caller should fallback).
    fn wait_via_progress(
        &self,
        client: &mut LspClient,
        deadline: std::time::Instant,
    ) -> Result<Option<f32>> {
        let start = std::time::Instant::now();

        // Phase 1: wait up to PROGRESS_DETECT_SECS for any progress notification
        let detect_deadline = start + std::time::Duration::from_secs(PROGRESS_DETECT_SECS);
        let mut seen_any = false;

        client.recv_until(detect_deadline, |msg| {
            if msg.get("method").and_then(|m| m.as_str()) == Some("$/progress") {
                seen_any = true;
                return true; // got one — move to phase 2
            }
            false
        });

        if !seen_any {
            return Ok(None); // no progress support — caller should fallback
        }

        // Phase 2: track all progress scopes until completion
        let mut active_scopes: u32 = 1; // we already saw one begin
        let mut all_done_at: Option<std::time::Instant> = None;
        let quiesce = std::time::Duration::from_secs(2);
        let mut seen_titles = std::collections::HashSet::new();

        // Process the first notification we already received (it's in the buffer)
        // — actually recv_until consumed it via callback. We counted it as active_scopes=1.

        let done = client.recv_until(deadline, |msg| {
            let method = msg.get("method").and_then(|m| m.as_str());
            if method != Some("$/progress") {
                return all_done_at.is_some_and(|t| t.elapsed() >= quiesce);
            }

            let value = match msg.get("params").and_then(|p| p.get("value")) {
                Some(v) => v,
                None => return false,
            };

            match value.get("kind").and_then(|k| k.as_str()) {
                Some("begin") => {
                    let title = value
                        .get("title")
                        .and_then(|t| t.as_str())
                        .unwrap_or("loading");
                    if seen_titles.insert(title.to_string()) {
                        tracing::info!("LSP: {title}...");
                    }
                    active_scopes += 1;
                    all_done_at = None;
                }
                Some("report") => {
                    if let Some(msg) = value.get("message").and_then(|m| m.as_str()) {
                        tracing::debug!("LSP: {msg}");
                    }
                }
                Some("end") => {
                    active_scopes = active_scopes.saturating_sub(1);
                    tracing::debug!("LSP: scope ended (active={active_scopes})");
                    if active_scopes == 0 {
                        all_done_at = Some(std::time::Instant::now());
                    }
                }
                _ => {}
            }
            all_done_at.is_some_and(|t| t.elapsed() >= quiesce)
        });

        let elapsed = start.elapsed().as_secs_f32();
        if done {
            Ok(Some(elapsed))
        } else {
            tracing::info!("LSP: still loading after {elapsed:.0}s, proceeding anyway");
            Ok(Some(elapsed))
        }
    }

    /// Fallback for servers without `$/progress` support (e.g., typescript-language-server).
    /// These servers respond to definition requests immediately even while loading,
    /// returning null for unloaded files. No point in probing — proceed directly.
    fn wait_no_progress(&self) -> Option<f32> {
        Some(PROGRESS_DETECT_SECS as f32)
    }
}

impl Drop for LspManager {
    fn drop(&mut self) {
        self.shutdown_all();
    }
}

/// Parsed definition location from an LSP response.
#[derive(Debug)]
pub struct DefinitionLocation {
    /// Relative file path within project root.
    pub file_path: String,
    /// 1-based line number.
    pub line: u32,
}

fn path_to_uri(path: &Path) -> String {
    url::Url::from_file_path(path)
        .map(|u| u.to_string())
        .unwrap_or_else(|_| format!("file://{}", path.display()))
}

fn uri_to_path(uri: &str) -> Option<PathBuf> {
    url::Url::parse(uri)
        .ok()
        .and_then(|u| u.to_file_path().ok())
}

/// Parse a textDocument/definition response into a location.
/// Handles both single Location and Location[] responses.
fn parse_definition_response(result: &Value, root: &Path) -> Result<Option<DefinitionLocation>> {
    let location = if result.is_array() {
        result.get(0)
    } else if result.get("uri").is_some() {
        Some(result)
    } else {
        None
    };

    let Some(loc) = location else {
        return Ok(None);
    };

    let uri = loc
        .get("uri")
        .and_then(|u| u.as_str())
        .context("missing uri in Location")?;

    let abs_path = match uri_to_path(uri) {
        Some(p) => p,
        None => return Ok(None),
    };

    // Must be within project root
    let rel_path = match abs_path.strip_prefix(root) {
        Ok(rel) => rel.to_string_lossy().to_string(),
        Err(_) => {
            tracing::debug!("definition outside root: {uri}");
            return Ok(None);
        }
    };

    let line = loc
        .get("range")
        .and_then(|r| r.get("start"))
        .and_then(|s| s.get("line"))
        .and_then(|l| l.as_u64())
        .unwrap_or(0) as u32
        + 1; // LSP 0-based → cartog 1-based

    Ok(Some(DefinitionLocation {
        file_path: rel_path,
        line,
    }))
}

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

    #[test]
    fn test_path_to_uri() {
        assert_eq!(
            path_to_uri(Path::new("/home/user/project")),
            "file:///home/user/project"
        );
    }

    #[test]
    fn test_uri_to_path() {
        let p = uri_to_path("file:///home/user/project/src/main.rs").unwrap();
        assert_eq!(p, PathBuf::from("/home/user/project/src/main.rs"));
    }

    #[test]
    fn test_uri_to_path_non_file() {
        assert!(uri_to_path("https://example.com").is_none());
    }

    #[test]
    fn test_parse_definition_single_location() {
        let root = Path::new("/project");
        let result = serde_json::json!({
            "uri": "file:///project/src/auth.rs",
            "range": { "start": { "line": 10, "character": 4 }, "end": { "line": 10, "character": 20 } },
        });

        let loc = parse_definition_response(&result, root).unwrap().unwrap();
        assert_eq!(loc.file_path, "src/auth.rs");
        assert_eq!(loc.line, 11); // 0-based → 1-based
    }

    #[test]
    fn test_parse_definition_array() {
        let root = Path::new("/project");
        let result = serde_json::json!([
            {
                "uri": "file:///project/src/auth.rs",
                "range": { "start": { "line": 5, "character": 0 }, "end": { "line": 5, "character": 10 } },
            }
        ]);

        let loc = parse_definition_response(&result, root).unwrap().unwrap();
        assert_eq!(loc.file_path, "src/auth.rs");
        assert_eq!(loc.line, 6);
    }

    #[test]
    fn test_parse_definition_null() {
        let root = Path::new("/project");
        let result = Value::Null;

        assert!(parse_definition_response(&result, root).unwrap().is_none());
    }

    #[test]
    fn test_parse_definition_outside_root() {
        let root = Path::new("/project");
        let result = serde_json::json!({
            "uri": "file:///other/src/lib.rs",
            "range": { "start": { "line": 0, "character": 0 }, "end": { "line": 0, "character": 0 } },
        });

        assert!(parse_definition_response(&result, root).unwrap().is_none());
    }
}