Skip to main content

lean_ctx/core/
call_graph.rs

1use std::collections::HashMap;
2use std::path::Path;
3use std::sync::atomic::{AtomicUsize, Ordering};
4use std::sync::{Arc, Mutex, OnceLock};
5
6use rayon::prelude::*;
7use serde::{Deserialize, Serialize};
8
9use super::deep_queries;
10use super::graph_provider::GraphProvider;
11use super::index_paths::normalize_project_root;
12
13// ---------------------------------------------------------------------------
14// Data types
15// ---------------------------------------------------------------------------
16
17/// On-disk format of the persisted call graph. Bump whenever the meaning of a
18/// persisted field changes; [`CallGraph::load`] discards any other version, so
19/// the next build starts from scratch instead of reusing stale edges.
20/// v2: 1-based `caller_line` (v1 was off by one), callee position/receiver/method.
21const CALL_GRAPH_FORMAT: u32 = 2;
22
23#[derive(Debug, Clone, Serialize, Deserialize)]
24pub struct CallGraph {
25    /// Missing in pre-v2 caches → 0 → rejected by `load`.
26    #[serde(default)]
27    pub format_version: u32,
28    pub project_root: String,
29    pub edges: Vec<CallEdge>,
30    pub file_hashes: HashMap<String, String>,
31}
32
33#[derive(Debug, Clone, Default, Serialize, Deserialize)]
34pub struct CallEdge {
35    pub caller_file: String,
36    pub caller_symbol: String,
37    /// 1-based line of the call expression.
38    pub caller_line: usize,
39    pub callee_name: String,
40    /// Callee identifier position `(1-based line, 0-based byte column)` — where
41    /// a semantic backend resolves the call (see `CallSite::callee_pos`).
42    #[serde(default)]
43    pub callee_pos: Option<(usize, usize)>,
44    #[serde(default)]
45    pub receiver: Option<String>,
46    #[serde(default)]
47    pub is_method: bool,
48}
49
50/// Call edges of one analyzed file, each attributed to its enclosing symbol.
51/// Call-site and symbol lines are both 1-based.
52fn edges_for_file(
53    rel_path: &str,
54    calls: &[deep_queries::CallSite],
55    file_symbols: Option<&Vec<SymbolSpan>>,
56) -> Vec<CallEdge> {
57    calls
58        .iter()
59        .map(|call| CallEdge {
60            caller_file: rel_path.to_string(),
61            caller_symbol: find_enclosing_symbol_owned(file_symbols, call.line),
62            caller_line: call.line,
63            callee_name: call.callee.clone(),
64            callee_pos: call.callee_pos,
65            receiver: call.receiver.clone(),
66            is_method: call.is_method,
67        })
68        .collect()
69}
70
71/// Minimal symbol span the call-graph builder needs to attribute a call site to
72/// its enclosing symbol — backend-agnostic, decoupled from any graph store.
73#[derive(Debug, Clone, Default)]
74pub struct SymbolSpan {
75    pub file: String,
76    pub name: String,
77    pub start_line: usize,
78    pub end_line: usize,
79    /// Signature kind (`fn`, `method`, `trait`, `interface`, …).
80    pub kind: String,
81}
82
83/// Everything the call-graph builder reads, sourced from the [`GraphProvider`]
84/// facade (PropertyGraph). Replaces the former direct `ProjectIndex`
85/// dependency (#696): the file inventory, the symbol table (for enclosing-symbol
86/// attribution) and the import/reexport adjacency (for scope-aware callee
87/// resolution). Source content itself is still read fresh from disk per file.
88#[derive(Debug, Clone, Default)]
89pub struct CallGraphInputs {
90    pub project_root: String,
91    pub file_paths: Vec<String>,
92    pub symbols: Vec<SymbolSpan>,
93    /// `(from, to)` pairs for `import`/`reexport` edges only.
94    pub import_edges: Vec<(String, String)>,
95}
96
97impl CallGraphInputs {
98    /// Open the project graph (PropertyGraph, falling back to legacy) and
99    /// materialize call-graph inputs. Returns empty inputs (rooted at
100    /// `project_root`) when no graph is available yet — matching the old
101    /// behaviour of building from an empty index.
102    pub fn open(project_root: &str) -> Self {
103        match crate::core::graph_provider::open_or_build(project_root) {
104            Some(open) => Self::from_provider(project_root, &open.provider),
105            None => Self {
106                project_root: normalize_project_root(project_root),
107                ..Default::default()
108            },
109        }
110    }
111
112    /// Bridge for callers that already hold a freshly-scanned
113    /// [`ProjectIndex`](super::graph_index::ProjectIndex)
114    /// (repomap, dashboard coordinator) and want call-graph inputs consistent
115    /// with *that* scan rather than a possibly-lagging PropertyGraph. Removed in
116    /// #696 Phase D once those callers move to the facade/extractor wholesale.
117    pub fn from_project_index(index: &super::graph_index::ProjectIndex) -> Self {
118        let symbols = index
119            .symbols
120            .values()
121            .map(|s| SymbolSpan {
122                file: s.file.clone(),
123                name: s.name.clone(),
124                start_line: s.start_line,
125                end_line: s.end_line,
126                kind: s.kind.clone(),
127            })
128            .collect();
129        let import_edges = index
130            .edges
131            .iter()
132            .filter(|e| e.kind == "import" || e.kind == "reexport")
133            .map(|e| (e.from.clone(), e.to.clone()))
134            .collect();
135        Self {
136            project_root: index.project_root.clone(),
137            file_paths: index.files.keys().cloned().collect(),
138            symbols,
139            import_edges,
140        }
141    }
142
143    /// Materialize the builder inputs from a [`GraphProvider`] facade.
144    pub fn from_provider(project_root: &str, provider: &GraphProvider) -> Self {
145        let symbols = provider
146            .all_symbols()
147            .into_iter()
148            .map(|s| SymbolSpan {
149                file: s.file,
150                name: s.name,
151                start_line: s.start_line,
152                end_line: s.end_line,
153                kind: s.kind,
154            })
155            .collect();
156        let import_edges = provider
157            .edges()
158            .into_iter()
159            .filter(|e| e.kind == "import" || e.kind == "reexport")
160            .map(|e| (e.from, e.to))
161            .collect();
162        Self {
163            project_root: normalize_project_root(project_root),
164            file_paths: provider.file_paths(),
165            symbols,
166            import_edges,
167        }
168    }
169}
170
171#[derive(Debug, Clone)]
172pub struct BfsNode {
173    pub symbol: String,
174    pub file: String,
175    pub line: usize,
176    pub depth: usize,
177    pub from_symbol: String,
178}
179
180#[derive(Debug, Clone)]
181pub struct PathHop {
182    pub symbol: String,
183    pub file: String,
184    pub line: usize,
185}
186
187#[derive(Clone, Copy)]
188enum BfsDirection {
189    Callers,
190    Callees,
191}
192
193#[derive(Debug, Clone, Copy, PartialEq, Eq)]
194pub enum RiskLevel {
195    Low,
196    Medium,
197    High,
198    Critical,
199}
200
201impl RiskLevel {
202    pub fn from_caller_count(count: usize) -> Self {
203        match count {
204            0..=1 => Self::Low,
205            2..=4 => Self::Medium,
206            5..=10 => Self::High,
207            _ => Self::Critical,
208        }
209    }
210
211    pub fn label(self) -> &'static str {
212        match self {
213            Self::Low => "LOW",
214            Self::Medium => "MEDIUM",
215            Self::High => "HIGH",
216            Self::Critical => "CRITICAL",
217        }
218    }
219}
220
221// ---------------------------------------------------------------------------
222// Background build state (singleton per process)
223// ---------------------------------------------------------------------------
224
225#[derive(Debug, Clone, Serialize)]
226pub struct BuildProgress {
227    pub status: &'static str,
228    pub files_total: usize,
229    pub files_done: usize,
230    pub edges_found: usize,
231}
232
233enum BuildState {
234    Idle,
235    Building {
236        files_total: usize,
237        files_done: Arc<AtomicUsize>,
238        edges_found: Arc<AtomicUsize>,
239    },
240    Ready(Arc<CallGraph>),
241    Failed(String),
242}
243
244static BUILD: OnceLock<Mutex<BuildState>> = OnceLock::new();
245
246fn global_state() -> &'static Mutex<BuildState> {
247    BUILD.get_or_init(|| Mutex::new(BuildState::Idle))
248}
249
250impl CallGraph {
251    pub fn new(project_root: &str) -> Self {
252        Self {
253            format_version: CALL_GRAPH_FORMAT,
254            project_root: normalize_project_root(project_root),
255            edges: Vec::new(),
256            file_hashes: HashMap::new(),
257        }
258    }
259
260    // -----------------------------------------------------------------------
261    // Parallel build — processes files via rayon thread pool
262    // -----------------------------------------------------------------------
263
264    pub fn build_parallel(
265        inputs: &CallGraphInputs,
266        progress: Option<(&AtomicUsize, &AtomicUsize)>,
267    ) -> Self {
268        let project_root = &inputs.project_root;
269        let symbols_by_file = group_symbols_by_file_owned(inputs);
270        let file_keys: Vec<String> = inputs.file_paths.clone();
271
272        let results: Vec<(String, String, Vec<CallEdge>)> = file_keys
273            .par_iter()
274            .filter_map(|rel_path| {
275                let abs_path = resolve_path(rel_path, project_root);
276                let content = std::fs::read_to_string(&abs_path).ok()?;
277                let hash = simple_hash(&content);
278
279                let ext = Path::new(rel_path)
280                    .extension()
281                    .and_then(|e| e.to_str())
282                    .unwrap_or("");
283
284                let analysis = deep_queries::analyze(&content, ext);
285                let file_symbols = symbols_by_file.get(rel_path.as_str());
286
287                let edges = edges_for_file(rel_path, &analysis.calls, file_symbols);
288
289                if let Some((done, edge_count)) = progress {
290                    done.fetch_add(1, Ordering::Relaxed);
291                    edge_count.fetch_add(edges.len(), Ordering::Relaxed);
292                }
293
294                Some((rel_path.clone(), hash, edges))
295            })
296            .collect();
297
298        let mut graph = Self::new(project_root);
299        let edge_capacity: usize = results.iter().map(|(_, _, e)| e.len()).sum();
300        graph.edges.reserve(edge_capacity);
301        graph.file_hashes.reserve(results.len());
302
303        for (path, hash, edges) in results {
304            graph.file_hashes.insert(path, hash);
305            graph.edges.extend(edges);
306        }
307
308        graph
309    }
310
311    // -----------------------------------------------------------------------
312    // Incremental parallel build — only re-analyzes changed files
313    // -----------------------------------------------------------------------
314
315    pub fn build_incremental_parallel(
316        inputs: &CallGraphInputs,
317        previous: &CallGraph,
318        progress: Option<(&AtomicUsize, &AtomicUsize)>,
319    ) -> Self {
320        let project_root = &inputs.project_root;
321        let symbols_by_file = group_symbols_by_file_owned(inputs);
322        let file_keys: Vec<String> = inputs.file_paths.clone();
323
324        let prev_edges_by_file = group_edges_by_file(&previous.edges);
325
326        let results: Vec<(String, String, Vec<CallEdge>)> = file_keys
327            .par_iter()
328            .filter_map(|rel_path| {
329                let abs_path = resolve_path(rel_path, project_root);
330                let content = std::fs::read_to_string(&abs_path).ok()?;
331                let hash = simple_hash(&content);
332                let changed = previous.file_hashes.get(rel_path.as_str()) != Some(&hash);
333
334                let edges = if changed {
335                    let ext = Path::new(rel_path)
336                        .extension()
337                        .and_then(|e| e.to_str())
338                        .unwrap_or("");
339
340                    let analysis = deep_queries::analyze(&content, ext);
341                    let file_symbols = symbols_by_file.get(rel_path.as_str());
342
343                    edges_for_file(rel_path, &analysis.calls, file_symbols)
344                } else {
345                    prev_edges_by_file
346                        .get(rel_path.as_str())
347                        .cloned()
348                        .unwrap_or_default()
349                };
350
351                if let Some((done, edge_count)) = progress {
352                    done.fetch_add(1, Ordering::Relaxed);
353                    edge_count.fetch_add(edges.len(), Ordering::Relaxed);
354                }
355
356                Some((rel_path.clone(), hash, edges))
357            })
358            .collect();
359
360        let mut graph = Self::new(project_root);
361        let edge_capacity: usize = results.iter().map(|(_, _, e)| e.len()).sum();
362        graph.edges.reserve(edge_capacity);
363        graph.file_hashes.reserve(results.len());
364
365        for (path, hash, edges) in results {
366            graph.file_hashes.insert(path, hash);
367            graph.edges.extend(edges);
368        }
369
370        graph
371    }
372
373    // -----------------------------------------------------------------------
374    // Public API: non-blocking access for the dashboard
375    // -----------------------------------------------------------------------
376
377    /// Returns the cached graph immediately, or `None` + starts a background build.
378    pub fn get_or_start_build(
379        project_root: &str,
380        inputs: Arc<CallGraphInputs>,
381    ) -> Result<Arc<CallGraph>, BuildProgress> {
382        let state = global_state();
383        let mut guard = state
384            .lock()
385            .unwrap_or_else(std::sync::PoisonError::into_inner);
386
387        match &*guard {
388            BuildState::Ready(graph) => return Ok(Arc::clone(graph)),
389            BuildState::Building {
390                files_total,
391                files_done,
392                edges_found,
393            } => {
394                return Err(BuildProgress {
395                    status: "building",
396                    files_total: *files_total,
397                    files_done: files_done.load(Ordering::Relaxed),
398                    edges_found: edges_found.load(Ordering::Relaxed),
399                });
400            }
401            BuildState::Failed(msg) => {
402                tracing::warn!("[call_graph: previous build failed: {msg} — retrying]");
403            }
404            BuildState::Idle => {}
405        }
406
407        // Try serving from disk cache first
408        if let Some(cached) = Self::load(project_root)
409            && !cache_looks_stale(&cached, &inputs)
410        {
411            let arc = Arc::new(cached);
412            *guard = BuildState::Ready(Arc::clone(&arc));
413            return Ok(arc);
414        }
415
416        let files_total = inputs.file_paths.len();
417        let files_done = Arc::new(AtomicUsize::new(0));
418        let edges_found = Arc::new(AtomicUsize::new(0));
419
420        *guard = BuildState::Building {
421            files_total,
422            files_done: Arc::clone(&files_done),
423            edges_found: Arc::clone(&edges_found),
424        };
425        drop(guard);
426
427        let root = normalize_project_root(project_root);
428        let fd = Arc::clone(&files_done);
429        let ef = Arc::clone(&edges_found);
430
431        std::thread::spawn(move || {
432            let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
433                let previous = CallGraph::load(&root);
434                if let Some(prev) = &previous {
435                    CallGraph::build_incremental_parallel(&inputs, prev, Some((&fd, &ef)))
436                } else {
437                    CallGraph::build_parallel(&inputs, Some((&fd, &ef)))
438                }
439            }));
440
441            match result {
442                Ok(graph) => {
443                    let _ = graph.save();
444                    let arc = Arc::new(graph);
445                    if let Ok(mut g) = global_state().lock() {
446                        *g = BuildState::Ready(Arc::clone(&arc));
447                    }
448                    tracing::info!(
449                        "[call_graph: build complete — {} files, {} edges]",
450                        arc.file_hashes.len(),
451                        arc.edges.len()
452                    );
453                }
454                Err(e) => {
455                    let msg = format!("{e:?}");
456                    tracing::error!("[call_graph: build panicked: {msg}]");
457                    if let Ok(mut g) = global_state().lock() {
458                        *g = BuildState::Failed(msg);
459                    }
460                }
461            }
462        });
463
464        Err(BuildProgress {
465            status: "building",
466            files_total,
467            files_done: 0,
468            edges_found: 0,
469        })
470    }
471
472    /// Returns current build status without starting anything.
473    pub fn build_status() -> BuildProgress {
474        let state = global_state();
475        let guard = state
476            .lock()
477            .unwrap_or_else(std::sync::PoisonError::into_inner);
478        match &*guard {
479            BuildState::Idle => BuildProgress {
480                status: "idle",
481                files_total: 0,
482                files_done: 0,
483                edges_found: 0,
484            },
485            BuildState::Building {
486                files_total,
487                files_done,
488                edges_found,
489            } => BuildProgress {
490                status: "building",
491                files_total: *files_total,
492                files_done: files_done.load(Ordering::Relaxed),
493                edges_found: edges_found.load(Ordering::Relaxed),
494            },
495            BuildState::Ready(graph) => BuildProgress {
496                status: "ready",
497                files_total: graph.file_hashes.len(),
498                files_done: graph.file_hashes.len(),
499                edges_found: graph.edges.len(),
500            },
501            BuildState::Failed(msg) => {
502                tracing::debug!("[call_graph: status check — failed: {msg}]");
503                BuildProgress {
504                    status: "error",
505                    files_total: 0,
506                    files_done: 0,
507                    edges_found: 0,
508                }
509            }
510        }
511    }
512
513    /// Force-invalidate the cached result so next request triggers a rebuild.
514    pub fn invalidate() {
515        if let Ok(mut g) = global_state().lock() {
516            *g = BuildState::Idle;
517        }
518    }
519
520    // -----------------------------------------------------------------------
521    // Legacy synchronous API (kept for non-dashboard callers)
522    // -----------------------------------------------------------------------
523
524    pub fn build(inputs: &CallGraphInputs) -> Self {
525        Self::build_parallel(inputs, None)
526    }
527
528    pub fn build_incremental(inputs: &CallGraphInputs, previous: &CallGraph) -> Self {
529        Self::build_incremental_parallel(inputs, previous, None)
530    }
531
532    pub fn callers_of(&self, symbol: &str) -> Vec<&CallEdge> {
533        let sym_lower = symbol.to_lowercase();
534        self.edges
535            .iter()
536            .filter(|e| e.callee_name.to_lowercase() == sym_lower)
537            .collect()
538    }
539
540    pub fn callees_of(&self, symbol: &str) -> Vec<&CallEdge> {
541        let sym_lower = symbol.to_lowercase();
542        self.edges
543            .iter()
544            .filter(|e| e.caller_symbol.to_lowercase() == sym_lower)
545            .collect()
546    }
547
548    // -----------------------------------------------------------------------
549    // Multi-hop BFS traversal
550    // -----------------------------------------------------------------------
551
552    /// BFS callers up to `max_depth` hops. Returns (symbol, file, line, depth) per node.
553    pub fn bfs_callers(&self, symbol: &str, max_depth: usize) -> Vec<BfsNode> {
554        self.bfs_traverse(symbol, max_depth, BfsDirection::Callers)
555    }
556
557    /// BFS callees up to `max_depth` hops. Returns (symbol, file, line, depth) per node.
558    pub fn bfs_callees(&self, symbol: &str, max_depth: usize) -> Vec<BfsNode> {
559        self.bfs_traverse(symbol, max_depth, BfsDirection::Callees)
560    }
561
562    fn bfs_traverse(&self, symbol: &str, max_depth: usize, dir: BfsDirection) -> Vec<BfsNode> {
563        use std::collections::{HashSet, VecDeque};
564
565        let mut visited: HashSet<String> = HashSet::new();
566        let mut queue: VecDeque<(String, usize)> = VecDeque::new();
567        let mut result: Vec<BfsNode> = Vec::new();
568
569        let start = symbol.to_lowercase();
570        visited.insert(start.clone());
571        queue.push_back((start, 0));
572
573        while let Some((current, depth)) = queue.pop_front() {
574            if depth >= max_depth {
575                continue;
576            }
577
578            let neighbors: Vec<&CallEdge> = match dir {
579                BfsDirection::Callers => self
580                    .edges
581                    .iter()
582                    .filter(|e| e.callee_name.to_lowercase() == current)
583                    .collect(),
584                BfsDirection::Callees => self
585                    .edges
586                    .iter()
587                    .filter(|e| e.caller_symbol.to_lowercase() == current)
588                    .collect(),
589            };
590
591            for edge in neighbors {
592                let next_sym = match dir {
593                    BfsDirection::Callers => &edge.caller_symbol,
594                    BfsDirection::Callees => &edge.callee_name,
595                };
596                let next_lower = next_sym.to_lowercase();
597
598                if !visited.insert(next_lower.clone()) {
599                    continue;
600                }
601
602                result.push(BfsNode {
603                    symbol: next_sym.clone(),
604                    file: edge.caller_file.clone(),
605                    line: edge.caller_line,
606                    depth: depth + 1,
607                    from_symbol: if depth == 0 {
608                        symbol.to_string()
609                    } else {
610                        current.clone()
611                    },
612                });
613
614                queue.push_back((next_lower, depth + 1));
615            }
616        }
617
618        result
619    }
620
621    /// Find shortest call path from `from` to `to` using BFS.
622    /// Returns None if no path exists (searched up to depth 10).
623    /// Find shortest call path from `from` to `to` using BFS.
624    /// Returns None if no path exists (searched up to depth 10).
625    pub fn find_call_path(&self, from: &str, to: &str) -> Option<Vec<PathHop>> {
626        use std::collections::{HashMap as BfsMap, VecDeque};
627
628        let from_lower = from.to_lowercase();
629        let to_lower = to.to_lowercase();
630
631        if from_lower == to_lower {
632            return Some(vec![PathHop {
633                symbol: from.to_string(),
634                file: String::new(),
635                line: 0,
636            }]);
637        }
638
639        const MAX_TRACE_DEPTH: usize = 10;
640
641        // (parent_symbol, file, line, depth)
642        let mut visited: BfsMap<String, (String, String, usize, usize)> = BfsMap::new();
643        let mut queue: VecDeque<String> = VecDeque::new();
644
645        visited.insert(from_lower.clone(), (String::new(), String::new(), 0, 0));
646        queue.push_back(from_lower.clone());
647
648        while let Some(current) = queue.pop_front() {
649            let current_depth = visited.get(&current).map_or(0, |e| e.3);
650            if current_depth >= MAX_TRACE_DEPTH {
651                continue;
652            }
653
654            let callees: Vec<&CallEdge> = self
655                .edges
656                .iter()
657                .filter(|e| e.caller_symbol.to_lowercase() == current)
658                .collect();
659
660            for edge in callees {
661                let next = edge.callee_name.to_lowercase();
662                if visited.contains_key(&next) {
663                    continue;
664                }
665
666                visited.insert(
667                    next.clone(),
668                    (
669                        current.clone(),
670                        edge.caller_file.clone(),
671                        edge.caller_line,
672                        current_depth + 1,
673                    ),
674                );
675
676                if next == to_lower {
677                    return Some(Self::reconstruct_path(
678                        &visited,
679                        &from_lower,
680                        &to_lower,
681                        from,
682                        to,
683                    ));
684                }
685
686                queue.push_back(next);
687            }
688        }
689
690        None
691    }
692
693    fn reconstruct_path(
694        visited: &std::collections::HashMap<String, (String, String, usize, usize)>,
695        from_lower: &str,
696        to_lower: &str,
697        from_orig: &str,
698        to_orig: &str,
699    ) -> Vec<PathHop> {
700        let mut path = Vec::new();
701        let mut current = to_lower.to_string();
702
703        while current != from_lower {
704            let (parent, file, line, _depth) = &visited[&current];
705            let sym_name = if current == to_lower {
706                to_orig.to_string()
707            } else {
708                current.clone()
709            };
710            path.push(PathHop {
711                symbol: sym_name,
712                file: file.clone(),
713                line: *line,
714            });
715            current = parent.clone();
716        }
717
718        path.push(PathHop {
719            symbol: from_orig.to_string(),
720            file: String::new(),
721            line: 0,
722        });
723
724        path.reverse();
725        path
726    }
727
728    /// Count unique transitive callers up to `max_depth`.
729    pub fn transitive_caller_count(&self, symbol: &str, max_depth: usize) -> usize {
730        let nodes = self.bfs_callers(symbol, max_depth);
731        let mut unique: std::collections::HashSet<String> = std::collections::HashSet::new();
732        for node in &nodes {
733            unique.insert(node.symbol.to_lowercase());
734        }
735        unique.len()
736    }
737
738    pub fn save(&self) -> Result<(), String> {
739        let dir = call_graph_dir(&self.project_root)
740            .ok_or_else(|| "Cannot determine home directory".to_string())?;
741        std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
742        let json = serde_json::to_string(self).map_err(|e| e.to_string())?;
743        let compressed = zstd::encode_all(json.as_bytes(), 9).map_err(|e| format!("zstd: {e}"))?;
744        let target = dir.join("call_graph.json.zst");
745        let tmp = target.with_extension("zst.tmp");
746        std::fs::write(&tmp, &compressed).map_err(|e| e.to_string())?;
747        std::fs::rename(&tmp, &target).map_err(|e| e.to_string())?;
748        let _ = std::fs::remove_file(dir.join("call_graph.json"));
749        Ok(())
750    }
751
752    pub fn load(project_root: &str) -> Option<Self> {
753        Self::load_any_version(project_root).filter(|g| g.format_version == CALL_GRAPH_FORMAT)
754    }
755
756    fn load_any_version(project_root: &str) -> Option<Self> {
757        let dir = call_graph_dir(project_root)?;
758
759        let zst_path = dir.join("call_graph.json.zst");
760        if zst_path.exists() {
761            let compressed = std::fs::read(&zst_path).ok()?;
762            let data = zstd::decode_all(compressed.as_slice()).ok()?;
763            let content = String::from_utf8(data).ok()?;
764            return serde_json::from_str(&content).ok();
765        }
766
767        let json_path = dir.join("call_graph.json");
768        if json_path.exists() {
769            let content = std::fs::read_to_string(&json_path).ok()?;
770            let parsed: Self = serde_json::from_str(&content).ok()?;
771            // Auto-migrate: compress legacy JSON to zstd
772            if let Ok(compressed) = zstd::encode_all(content.as_bytes(), 9) {
773                let zst_tmp = zst_path.with_extension("zst.tmp");
774                if std::fs::write(&zst_tmp, &compressed).is_ok()
775                    && std::fs::rename(&zst_tmp, &zst_path).is_ok()
776                {
777                    let _ = std::fs::remove_file(&json_path);
778                }
779            }
780            return Some(parsed);
781        }
782
783        None
784    }
785
786    pub fn load_or_build(project_root: &str, inputs: &CallGraphInputs) -> Self {
787        if let Some(previous) = Self::load(project_root) {
788            Self::build_incremental(inputs, &previous)
789        } else {
790            Self::build(inputs)
791        }
792    }
793}
794
795// ---------------------------------------------------------------------------
796// Cache staleness check (fast — mtime-based, no content reads)
797// ---------------------------------------------------------------------------
798
799fn cache_looks_stale(cached: &CallGraph, inputs: &CallGraphInputs) -> bool {
800    if cached.file_hashes.len() != inputs.file_paths.len() {
801        return true;
802    }
803    let cached_files: std::collections::HashSet<&str> =
804        cached.file_hashes.keys().map(String::as_str).collect();
805    let index_files: std::collections::HashSet<&str> =
806        inputs.file_paths.iter().map(String::as_str).collect();
807    cached_files != index_files
808}
809
810// ---------------------------------------------------------------------------
811// Helpers
812// ---------------------------------------------------------------------------
813
814fn call_graph_dir(project_root: &str) -> Option<std::path::PathBuf> {
815    GraphProvider::index_dir(project_root)
816}
817
818fn group_edges_by_file(edges: &[CallEdge]) -> HashMap<&str, Vec<CallEdge>> {
819    let mut map: HashMap<&str, Vec<CallEdge>> = HashMap::new();
820    for edge in edges {
821        map.entry(edge.caller_file.as_str())
822            .or_default()
823            .push(edge.clone());
824    }
825    map
826}
827
828/// Owned version for safe `Send` across rayon threads.
829fn group_symbols_by_file_owned(inputs: &CallGraphInputs) -> HashMap<String, Vec<SymbolSpan>> {
830    let mut map: HashMap<String, Vec<SymbolSpan>> = HashMap::new();
831    for sym in &inputs.symbols {
832        map.entry(sym.file.clone()).or_default().push(sym.clone());
833    }
834    for syms in map.values_mut() {
835        syms.sort_by_key(|s| s.start_line);
836    }
837    map
838}
839
840fn find_enclosing_symbol_owned(file_symbols: Option<&Vec<SymbolSpan>>, line: usize) -> String {
841    let Some(syms) = file_symbols else {
842        return "<module>".to_string();
843    };
844    let mut best: Option<&SymbolSpan> = None;
845    for sym in syms {
846        if line >= sym.start_line && line <= sym.end_line {
847            match best {
848                None => best = Some(sym),
849                Some(prev) => {
850                    if (sym.end_line - sym.start_line) < (prev.end_line - prev.start_line) {
851                        best = Some(sym);
852                    }
853                }
854            }
855        }
856    }
857    best.map_or_else(|| "<module>".to_string(), |s| s.name.clone())
858}
859
860fn resolve_path(relative: &str, project_root: &str) -> String {
861    let p = Path::new(relative);
862    if p.is_absolute() && p.exists() {
863        return relative.to_string();
864    }
865    let relative = relative.trim_start_matches(['/', '\\']);
866    let joined = Path::new(project_root).join(relative);
867    joined.to_string_lossy().to_string()
868}
869
870fn simple_hash(content: &str) -> String {
871    use std::hash::{Hash, Hasher};
872    let mut hasher = std::collections::hash_map::DefaultHasher::new();
873    content.hash(&mut hasher);
874    format!("{:x}", hasher.finish())
875}
876
877/// Current content hashes of the indexed files — the same values a
878/// [`CallGraph`] records in `file_hashes` — without building or loading a
879/// call graph. For callers that need only the hashes (semantic cache keys
880/// and project revision), which is a fraction of a call-graph build.
881pub(crate) fn current_file_hashes(inputs: &CallGraphInputs) -> HashMap<String, String> {
882    inputs
883        .file_paths
884        .par_iter()
885        .filter_map(|rel| {
886            let content = std::fs::read_to_string(resolve_path(rel, &inputs.project_root)).ok()?;
887            Some((rel.clone(), simple_hash(&content)))
888        })
889        .collect()
890}
891
892// ---------------------------------------------------------------------------
893// Scope-aware callee resolution (#321)
894//
895// Call edges store callees as bare names, so attributing `Run`/`Get`/`Handle`
896// to a file by name alone links every same-named symbol (false positives).
897// These helpers resolve a callee to its defining file using the caller's
898// lexical scope and refuse to guess when a name stays ambiguous.
899// ---------------------------------------------------------------------------
900
901/// Build a `file -> imported files` adjacency from the project index's import
902/// and reexport edges, used to scope callee resolution to a caller's imports.
903pub fn build_import_adjacency(
904    inputs: &CallGraphInputs,
905) -> HashMap<String, std::collections::HashSet<String>> {
906    let mut adj: HashMap<String, std::collections::HashSet<String>> = HashMap::new();
907    for (from, to) in &inputs.import_edges {
908        adj.entry(from.clone()).or_default().insert(to.clone());
909    }
910    adj
911}
912
913/// Pick the defining file for a callee from candidate `def_files`, ranked by the
914/// caller's lexical scope (most specific first):
915///   1. the caller's own file,
916///   2. exactly one file the caller imports,
917///   3. exactly one file project-wide.
918///
919/// Returns `None` when the name stays ambiguous (never guesses).
920fn rank_callee_def_file(
921    def_files: &[&str],
922    caller_file: &str,
923    imports: &HashMap<String, std::collections::HashSet<String>>,
924) -> Option<(String, ScopeMatch)> {
925    if def_files.is_empty() {
926        return None;
927    }
928    if def_files.contains(&caller_file) {
929        return Some((caller_file.to_string(), ScopeMatch::SameFile));
930    }
931    if let Some(imported) = imports.get(caller_file) {
932        let mut in_scope = def_files.iter().filter(|f| imported.contains(**f));
933        if let Some(first) = in_scope.next()
934            && in_scope.next().is_none()
935        {
936            return Some(((*first).to_string(), ScopeMatch::UniqueImport));
937        }
938    }
939    if def_files.len() == 1 {
940        return Some((def_files[0].to_string(), ScopeMatch::UniqueInProject));
941    }
942    None
943}
944
945/// The identifier a callee name ends in: `crate::db::save` → `save`,
946/// `pkg.Func` → `Func`, `save` → `save`.
947pub fn callee_segment(name: &str) -> &str {
948    name.rsplit(|c: char| c == ':' || c == '.')
949        .next()
950        .unwrap_or(name)
951}
952
953/// Which scope step resolved a callee structurally — the strength of the
954/// evidence. Same-file and imported definitions are bound by the caller's own
955/// scope; a name that is merely unique project-wide may still be an external
956/// function of the same name.
957#[derive(Debug, Clone, Copy, PartialEq, Eq)]
958pub enum ScopeMatch {
959    SameFile,
960    UniqueImport,
961    UniqueInProject,
962}
963
964/// Structural view of one call edge's callee.
965#[derive(Debug, Clone, PartialEq, Eq)]
966pub enum StructuralTarget {
967    Resolved {
968        file: String,
969        via: ScopeMatch,
970    },
971    /// Several project definitions remain in scope; structure cannot decide.
972    Ambiguous,
973    /// No project symbol has this name (std, dependency, dynamic dispatch).
974    Unknown,
975}
976
977impl StructuralTarget {
978    pub fn file(&self) -> Option<&str> {
979        match self {
980            Self::Resolved { file, .. } => Some(file),
981            Self::Ambiguous | Self::Unknown => None,
982        }
983    }
984}
985
986/// Resolve a single callee name to its defining file in the scope of `caller_file`.
987pub fn resolve_callee_file(
988    callee_name: &str,
989    caller_file: &str,
990    inputs: &CallGraphInputs,
991    imports: &HashMap<String, std::collections::HashSet<String>>,
992) -> Option<String> {
993    let mut def_files: Vec<&str> = inputs
994        .symbols
995        .iter()
996        .filter(|s| s.name == callee_name)
997        .map(|s| s.file.as_str())
998        .collect();
999    def_files.sort_unstable();
1000    def_files.dedup();
1001    rank_callee_def_file(&def_files, caller_file, imports).map(|(file, _)| file)
1002}
1003
1004/// Resolve each edge's callee to its defining file in *that edge's own* caller
1005/// scope (index-aligned with `edges`). `None` = ambiguous or unknown; never
1006/// guesses. Use this for per-edge consumers (graph edges); the name-keyed
1007/// [`resolve_callee_files`] additionally drops names that differ across scopes.
1008pub fn resolve_edge_callee_files(
1009    inputs: &CallGraphInputs,
1010    edges: &[CallEdge],
1011) -> Vec<Option<String>> {
1012    resolve_edge_callee_targets(inputs, edges)
1013        .into_iter()
1014        .map(|t| t.file().map(str::to_string))
1015        .collect()
1016}
1017
1018/// Like [`resolve_edge_callee_files`], but keeps *why* each edge resolved —
1019/// or that it is ambiguous vs. unknown — for evidence grading and semantic
1020/// escalation.
1021pub fn resolve_edge_callee_targets(
1022    inputs: &CallGraphInputs,
1023    edges: &[CallEdge],
1024) -> Vec<StructuralTarget> {
1025    let callee_names: std::collections::HashSet<&str> =
1026        edges.iter().map(|e| e.callee_name.as_str()).collect();
1027    if callee_names.is_empty() {
1028        return Vec::new();
1029    }
1030
1031    let mut name_files: HashMap<&str, Vec<&str>> = HashMap::new();
1032    for sym in &inputs.symbols {
1033        if callee_names.contains(sym.name.as_str()) {
1034            name_files
1035                .entry(sym.name.as_str())
1036                .or_default()
1037                .push(sym.file.as_str());
1038        }
1039    }
1040    for files in name_files.values_mut() {
1041        files.sort_unstable();
1042        files.dedup();
1043    }
1044
1045    // Path callees (`db::save`) keep their full path as name, so a plain
1046    // name lookup never finds them. Their last segment being defined in the
1047    // project makes them a semantic candidate — never a structural guess.
1048    let segment_defined: std::collections::HashSet<&str> =
1049        inputs.symbols.iter().map(|s| s.name.as_str()).collect();
1050    let last_segment = |name: &str| -> Option<String> {
1051        let seg = callee_segment(name);
1052        (seg.len() < name.len() && segment_defined.contains(seg)).then(|| seg.to_string())
1053    };
1054
1055    let imports = build_import_adjacency(inputs);
1056    edges
1057        .iter()
1058        .map(|e| {
1059            // Only definitions the caller's language can call directly: a Rust
1060            // `run()` never binds to a shell script's `run`.
1061            let family = call_family(&e.caller_file);
1062            let defs: Option<Vec<&str>> = name_files.get(e.callee_name.as_str()).map(|defs| {
1063                defs.iter()
1064                    .copied()
1065                    .filter(|d| {
1066                        family.is_none() || call_family(d).is_none_or(|f| Some(f) == family)
1067                    })
1068                    .collect()
1069            });
1070            match defs.filter(|d| !d.is_empty()) {
1071                None if last_segment(&e.callee_name).is_some() => StructuralTarget::Ambiguous,
1072                None => StructuralTarget::Unknown,
1073                Some(defs) => match rank_callee_def_file(&defs, &e.caller_file, &imports) {
1074                    Some((file, via)) => StructuralTarget::Resolved { file, via },
1075                    None => StructuralTarget::Ambiguous,
1076                },
1077            }
1078        })
1079        .collect()
1080}
1081
1082/// Languages that call each other's definitions directly, by file; `None`
1083/// for files whose language is unknown (never filtered out).
1084fn call_family(path: &str) -> Option<&'static str> {
1085    let id = crate::core::language_capabilities::language_for_path(path)?.id_str();
1086    Some(match id {
1087        "typescript" | "javascript" | "vue" | "svelte" => "js",
1088        "c" | "cpp" => "c",
1089        "java" | "kotlin" | "scala" => "jvm",
1090        "lua" | "luau" => "lua",
1091        other => other,
1092    })
1093}
1094
1095/// Resolve callee names to a single defining file *when scope makes it
1096/// unambiguous across all call sites*. Names that resolve to different files
1097/// from different scopes are omitted, so callers never attribute a call to the
1098/// wrong file. Keyed by callee name to match the call graph's name-keyed nodes.
1099pub fn resolve_callee_files(
1100    inputs: &CallGraphInputs,
1101    edges: &[CallEdge],
1102) -> HashMap<String, String> {
1103    use std::collections::HashSet;
1104
1105    let mut resolved: HashMap<&str, HashSet<String>> = HashMap::new();
1106    for (e, file) in edges.iter().zip(resolve_edge_callee_files(inputs, edges)) {
1107        if let Some(file) = file {
1108            resolved
1109                .entry(e.callee_name.as_str())
1110                .or_default()
1111                .insert(file);
1112        }
1113    }
1114
1115    resolved
1116        .into_iter()
1117        .filter_map(|(name, files)| {
1118            (files.len() == 1).then(|| {
1119                (
1120                    name.to_string(),
1121                    files
1122                        .into_iter()
1123                        .next()
1124                        .expect("files.len() == 1 guarantees one element"),
1125                )
1126            })
1127        })
1128        .collect()
1129}
1130
1131#[cfg(test)]
1132#[path = "call_graph_tests.rs"]
1133pub mod tests;