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
244/// What a resident call graph answers for: the project it was built from
245/// and the protection state its inputs were decided under. A graph is never
246/// handed to a request of another project, and one filled in Community
247/// developer mode is not handed to a protected request (or the reverse).
248/// The serve-time gate is not part of this: it stays with the request, which
249/// decides the inputs the resident graph is compared with.
250#[derive(Debug, Clone, PartialEq, Eq)]
251struct BuildKey {
252    root: String,
253    protected: bool,
254}
255
256impl BuildKey {
257    fn for_request(project_root: &str) -> Self {
258        Self {
259            root: normalize_project_root(project_root),
260            protected: crate::core::context_admission::stored::source_authority_required(),
261        }
262    }
263}
264
265/// Resident builds kept at once; the least recently requested one that is
266/// not building goes first.
267const MAX_RESIDENT_BUILDS: usize = 4;
268
269/// The state of a project nobody requested yet.
270static IDLE: BuildState = BuildState::Idle;
271
272/// The resident builds, least recently requested first.
273#[derive(Default)]
274struct Builds {
275    entries: Vec<(BuildKey, BuildState)>,
276}
277
278impl Builds {
279    fn state(&self, key: &BuildKey) -> &BuildState {
280        self.entries
281            .iter()
282            .find(|(k, _)| k == key)
283            .map_or(&IDLE, |(_, state)| state)
284    }
285
286    /// The most recently requested build.
287    fn latest(&self) -> &BuildState {
288        self.entries.last().map_or(&IDLE, |(_, state)| state)
289    }
290
291    fn set(&mut self, key: BuildKey, state: BuildState) {
292        self.entries.retain(|(k, _)| *k != key);
293        if self.entries.len() >= MAX_RESIDENT_BUILDS {
294            let evict = self
295                .entries
296                .iter()
297                .position(|(_, state)| !matches!(state, BuildState::Building { .. }))
298                .unwrap_or(0);
299            self.entries.remove(evict);
300        }
301        self.entries.push((key, state));
302    }
303}
304
305static BUILD: OnceLock<Mutex<Builds>> = OnceLock::new();
306
307fn global_state() -> &'static Mutex<Builds> {
308    BUILD.get_or_init(|| Mutex::new(Builds::default()))
309}
310
311impl CallGraph {
312    pub fn new(project_root: &str) -> Self {
313        Self {
314            format_version: CALL_GRAPH_FORMAT,
315            project_root: normalize_project_root(project_root),
316            edges: Vec::new(),
317            file_hashes: HashMap::new(),
318        }
319    }
320
321    // -----------------------------------------------------------------------
322    // Parallel build — processes files via rayon thread pool
323    // -----------------------------------------------------------------------
324
325    pub fn build_parallel(
326        inputs: &CallGraphInputs,
327        progress: Option<(&AtomicUsize, &AtomicUsize)>,
328    ) -> Self {
329        let project_root = &inputs.project_root;
330        let symbols_by_file = group_symbols_by_file_owned(inputs);
331        let file_keys: Vec<String> = inputs.file_paths.clone();
332
333        let results: Vec<(String, String, Vec<CallEdge>)> = file_keys
334            .par_iter()
335            .filter_map(|rel_path| {
336                let abs_path = resolve_path(rel_path, project_root);
337                let content = std::fs::read_to_string(&abs_path).ok()?;
338                let hash = simple_hash(&content);
339
340                let ext = Path::new(rel_path)
341                    .extension()
342                    .and_then(|e| e.to_str())
343                    .unwrap_or("");
344
345                let analysis = deep_queries::analyze(&content, ext);
346                let file_symbols = symbols_by_file.get(rel_path.as_str());
347
348                let edges = edges_for_file(rel_path, &analysis.calls, file_symbols);
349
350                if let Some((done, edge_count)) = progress {
351                    done.fetch_add(1, Ordering::Relaxed);
352                    edge_count.fetch_add(edges.len(), Ordering::Relaxed);
353                }
354
355                Some((rel_path.clone(), hash, edges))
356            })
357            .collect();
358
359        let mut graph = Self::new(project_root);
360        let edge_capacity: usize = results.iter().map(|(_, _, e)| e.len()).sum();
361        graph.edges.reserve(edge_capacity);
362        graph.file_hashes.reserve(results.len());
363
364        for (path, hash, edges) in results {
365            graph.file_hashes.insert(path, hash);
366            graph.edges.extend(edges);
367        }
368
369        graph
370    }
371
372    // -----------------------------------------------------------------------
373    // Incremental parallel build — only re-analyzes changed files
374    // -----------------------------------------------------------------------
375
376    pub fn build_incremental_parallel(
377        inputs: &CallGraphInputs,
378        previous: &CallGraph,
379        progress: Option<(&AtomicUsize, &AtomicUsize)>,
380    ) -> Self {
381        let project_root = &inputs.project_root;
382        let symbols_by_file = group_symbols_by_file_owned(inputs);
383        let file_keys: Vec<String> = inputs.file_paths.clone();
384
385        let prev_edges_by_file = group_edges_by_file(&previous.edges);
386
387        let results: Vec<(String, String, Vec<CallEdge>)> = file_keys
388            .par_iter()
389            .filter_map(|rel_path| {
390                let abs_path = resolve_path(rel_path, project_root);
391                let content = std::fs::read_to_string(&abs_path).ok()?;
392                let hash = simple_hash(&content);
393                let changed = previous.file_hashes.get(rel_path.as_str()) != Some(&hash);
394
395                let edges = if changed {
396                    let ext = Path::new(rel_path)
397                        .extension()
398                        .and_then(|e| e.to_str())
399                        .unwrap_or("");
400
401                    let analysis = deep_queries::analyze(&content, ext);
402                    let file_symbols = symbols_by_file.get(rel_path.as_str());
403
404                    edges_for_file(rel_path, &analysis.calls, file_symbols)
405                } else {
406                    prev_edges_by_file
407                        .get(rel_path.as_str())
408                        .cloned()
409                        .unwrap_or_default()
410                };
411
412                if let Some((done, edge_count)) = progress {
413                    done.fetch_add(1, Ordering::Relaxed);
414                    edge_count.fetch_add(edges.len(), Ordering::Relaxed);
415                }
416
417                Some((rel_path.clone(), hash, edges))
418            })
419            .collect();
420
421        let mut graph = Self::new(project_root);
422        let edge_capacity: usize = results.iter().map(|(_, _, e)| e.len()).sum();
423        graph.edges.reserve(edge_capacity);
424        graph.file_hashes.reserve(results.len());
425
426        for (path, hash, edges) in results {
427            graph.file_hashes.insert(path, hash);
428            graph.edges.extend(edges);
429        }
430
431        graph
432    }
433
434    // -----------------------------------------------------------------------
435    // Public API: non-blocking access for the dashboard
436    // -----------------------------------------------------------------------
437
438    /// Returns the cached graph immediately, or `None` + starts a background build.
439    pub fn get_or_start_build(
440        project_root: &str,
441        inputs: Arc<CallGraphInputs>,
442    ) -> Result<Arc<CallGraph>, BuildProgress> {
443        let key = BuildKey::for_request(project_root);
444        let state = global_state();
445        let mut guard = state
446            .lock()
447            .unwrap_or_else(std::sync::PoisonError::into_inner);
448
449        match guard.state(&key) {
450            // The resident graph outlives the request that built it. It is
451            // found only under this request's project and protection state
452            // (`BuildKey`), and handed out only while every file it was built
453            // from is still in this request's inputs — those come from the
454            // gated graph facade (G04), so a file withdrawn since is missing
455            // there. Otherwise the graph is rebuilt over the current inputs.
456            BuildState::Ready(graph) if !holds_withdrawn_files(graph, &inputs) => {
457                return Ok(Arc::clone(graph));
458            }
459            BuildState::Ready(_) | BuildState::Idle => {}
460            BuildState::Building {
461                files_total,
462                files_done,
463                edges_found,
464            } => {
465                return Err(BuildProgress {
466                    status: "building",
467                    files_total: *files_total,
468                    files_done: files_done.load(Ordering::Relaxed),
469                    edges_found: edges_found.load(Ordering::Relaxed),
470                });
471            }
472            BuildState::Failed(msg) => {
473                tracing::warn!("[call_graph: previous build failed: {msg} — retrying]");
474            }
475        }
476
477        // Try serving from disk cache first (an exact file-set match, so a
478        // persisted graph with a withdrawn file is rebuilt, not served)
479        if let Some(cached) = Self::load(project_root)
480            && !cache_looks_stale(&cached, &inputs)
481        {
482            let arc = Arc::new(cached);
483            guard.set(key, BuildState::Ready(Arc::clone(&arc)));
484            return Ok(arc);
485        }
486
487        let files_total = inputs.file_paths.len();
488        let files_done = Arc::new(AtomicUsize::new(0));
489        let edges_found = Arc::new(AtomicUsize::new(0));
490
491        guard.set(
492            key.clone(),
493            BuildState::Building {
494                files_total,
495                files_done: Arc::clone(&files_done),
496                edges_found: Arc::clone(&edges_found),
497            },
498        );
499        drop(guard);
500
501        let root = key.root.clone();
502        let fd = Arc::clone(&files_done);
503        let ef = Arc::clone(&edges_found);
504
505        std::thread::spawn(move || {
506            let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
507                let previous = CallGraph::load(&root);
508                if let Some(prev) = &previous {
509                    CallGraph::build_incremental_parallel(&inputs, prev, Some((&fd, &ef)))
510                } else {
511                    CallGraph::build_parallel(&inputs, Some((&fd, &ef)))
512                }
513            }));
514
515            match result {
516                Ok(graph) => {
517                    let _ = graph.save();
518                    let arc = Arc::new(graph);
519                    if let Ok(mut g) = global_state().lock() {
520                        g.set(key, BuildState::Ready(Arc::clone(&arc)));
521                    }
522                    tracing::info!(
523                        "[call_graph: build complete — {} files, {} edges]",
524                        arc.file_hashes.len(),
525                        arc.edges.len()
526                    );
527                }
528                Err(e) => {
529                    let msg = format!("{e:?}");
530                    tracing::error!("[call_graph: build panicked: {msg}]");
531                    if let Ok(mut g) = global_state().lock() {
532                        g.set(key, BuildState::Failed(msg));
533                    }
534                }
535            }
536        });
537
538        Err(BuildProgress {
539            status: "building",
540            files_total,
541            files_done: 0,
542            edges_found: 0,
543        })
544    }
545
546    /// Returns the status of the most recently requested build without
547    /// starting anything: counts only, no file or symbol of any project.
548    pub fn build_status() -> BuildProgress {
549        let state = global_state();
550        let guard = state
551            .lock()
552            .unwrap_or_else(std::sync::PoisonError::into_inner);
553        match guard.latest() {
554            BuildState::Idle => BuildProgress {
555                status: "idle",
556                files_total: 0,
557                files_done: 0,
558                edges_found: 0,
559            },
560            BuildState::Building {
561                files_total,
562                files_done,
563                edges_found,
564            } => BuildProgress {
565                status: "building",
566                files_total: *files_total,
567                files_done: files_done.load(Ordering::Relaxed),
568                edges_found: edges_found.load(Ordering::Relaxed),
569            },
570            BuildState::Ready(graph) => BuildProgress {
571                status: "ready",
572                files_total: graph.file_hashes.len(),
573                files_done: graph.file_hashes.len(),
574                edges_found: graph.edges.len(),
575            },
576            BuildState::Failed(msg) => {
577                tracing::debug!("[call_graph: status check — failed: {msg}]");
578                BuildProgress {
579                    status: "error",
580                    files_total: 0,
581                    files_done: 0,
582                    edges_found: 0,
583                }
584            }
585        }
586    }
587
588    /// Force-invalidate every resident result so the next request of any
589    /// project triggers a rebuild.
590    pub fn invalidate() {
591        if let Ok(mut g) = global_state().lock() {
592            g.entries.clear();
593        }
594    }
595
596    // -----------------------------------------------------------------------
597    // Legacy synchronous API (kept for non-dashboard callers)
598    // -----------------------------------------------------------------------
599
600    pub fn build(inputs: &CallGraphInputs) -> Self {
601        Self::build_parallel(inputs, None)
602    }
603
604    pub fn build_incremental(inputs: &CallGraphInputs, previous: &CallGraph) -> Self {
605        Self::build_incremental_parallel(inputs, previous, None)
606    }
607
608    /// Edges calling `symbol`, however the call site spells it: a query for
609    /// `write` also finds `crate::config_io::write(..)` (see [`callee_matches`]).
610    pub fn callers_of(&self, symbol: &str) -> Vec<&CallEdge> {
611        self.edges
612            .iter()
613            .filter(|e| callee_matches(&e.callee_name, symbol))
614            .collect()
615    }
616
617    pub fn callees_of(&self, symbol: &str) -> Vec<&CallEdge> {
618        let sym_lower = symbol.to_lowercase();
619        self.edges
620            .iter()
621            .filter(|e| e.caller_symbol.to_lowercase() == sym_lower)
622            .collect()
623    }
624
625    // -----------------------------------------------------------------------
626    // Multi-hop BFS traversal
627    // -----------------------------------------------------------------------
628
629    /// BFS callers up to `max_depth` hops. Returns (symbol, file, line, depth) per node.
630    pub fn bfs_callers(&self, symbol: &str, max_depth: usize) -> Vec<BfsNode> {
631        self.bfs_traverse(symbol, max_depth, BfsDirection::Callers)
632    }
633
634    /// BFS callees up to `max_depth` hops. Returns (symbol, file, line, depth) per node.
635    pub fn bfs_callees(&self, symbol: &str, max_depth: usize) -> Vec<BfsNode> {
636        self.bfs_traverse(symbol, max_depth, BfsDirection::Callees)
637    }
638
639    fn bfs_traverse(&self, symbol: &str, max_depth: usize, dir: BfsDirection) -> Vec<BfsNode> {
640        use std::collections::{HashSet, VecDeque};
641
642        let mut visited: HashSet<String> = HashSet::new();
643        let mut queue: VecDeque<(String, usize)> = VecDeque::new();
644        let mut result: Vec<BfsNode> = Vec::new();
645
646        let start = symbol.to_lowercase();
647        visited.insert(start.clone());
648        queue.push_back((start, 0));
649
650        while let Some((current, depth)) = queue.pop_front() {
651            if depth >= max_depth {
652                continue;
653            }
654
655            let neighbors: Vec<&CallEdge> = match dir {
656                BfsDirection::Callers => self
657                    .edges
658                    .iter()
659                    .filter(|e| callee_matches(&e.callee_name, &current))
660                    .collect(),
661                BfsDirection::Callees => self
662                    .edges
663                    .iter()
664                    .filter(|e| e.caller_symbol.to_lowercase() == callee_segment(&current))
665                    .collect(),
666            };
667
668            for edge in neighbors {
669                let next_sym = match dir {
670                    BfsDirection::Callers => &edge.caller_symbol,
671                    BfsDirection::Callees => &edge.callee_name,
672                };
673                // Caller symbols are bare names, so a path callee continues the
674                // walk (and dedups) under its last segment.
675                let next_lower = callee_segment(next_sym).to_lowercase();
676
677                if !visited.insert(next_lower.clone()) {
678                    continue;
679                }
680
681                result.push(BfsNode {
682                    symbol: next_sym.clone(),
683                    file: edge.caller_file.clone(),
684                    line: edge.caller_line,
685                    depth: depth + 1,
686                    from_symbol: if depth == 0 {
687                        symbol.to_string()
688                    } else {
689                        current.clone()
690                    },
691                });
692
693                queue.push_back((next_lower, depth + 1));
694            }
695        }
696
697        result
698    }
699
700    /// Find shortest call path from `from` to `to` using BFS.
701    /// Returns None if no path exists (searched up to depth 10).
702    /// Find shortest call path from `from` to `to` using BFS.
703    /// Returns None if no path exists (searched up to depth 10).
704    pub fn find_call_path(&self, from: &str, to: &str) -> Option<Vec<PathHop>> {
705        use std::collections::{HashMap as BfsMap, VecDeque};
706
707        // Walk by bare names: caller symbols are bare, path callees continue
708        // under their last segment.
709        let from_lower = callee_segment(from).to_lowercase();
710        let to_lower = callee_segment(to).to_lowercase();
711
712        if from_lower == to_lower {
713            return Some(vec![PathHop {
714                symbol: from.to_string(),
715                file: String::new(),
716                line: 0,
717            }]);
718        }
719
720        const MAX_TRACE_DEPTH: usize = 10;
721
722        // (parent_symbol, file, line, depth)
723        let mut visited: BfsMap<String, (String, String, usize, usize)> = BfsMap::new();
724        let mut queue: VecDeque<String> = VecDeque::new();
725
726        visited.insert(from_lower.clone(), (String::new(), String::new(), 0, 0));
727        queue.push_back(from_lower.clone());
728
729        while let Some(current) = queue.pop_front() {
730            let current_depth = visited.get(&current).map_or(0, |e| e.3);
731            if current_depth >= MAX_TRACE_DEPTH {
732                continue;
733            }
734
735            let callees: Vec<&CallEdge> = self
736                .edges
737                .iter()
738                .filter(|e| e.caller_symbol.to_lowercase() == current)
739                .collect();
740
741            for edge in callees {
742                let next = callee_segment(&edge.callee_name).to_lowercase();
743                if visited.contains_key(&next) {
744                    continue;
745                }
746
747                visited.insert(
748                    next.clone(),
749                    (
750                        current.clone(),
751                        edge.caller_file.clone(),
752                        edge.caller_line,
753                        current_depth + 1,
754                    ),
755                );
756
757                if next == to_lower {
758                    return Some(Self::reconstruct_path(
759                        &visited,
760                        &from_lower,
761                        &to_lower,
762                        from,
763                        to,
764                    ));
765                }
766
767                queue.push_back(next);
768            }
769        }
770
771        None
772    }
773
774    fn reconstruct_path(
775        visited: &std::collections::HashMap<String, (String, String, usize, usize)>,
776        from_lower: &str,
777        to_lower: &str,
778        from_orig: &str,
779        to_orig: &str,
780    ) -> Vec<PathHop> {
781        let mut path = Vec::new();
782        let mut current = to_lower.to_string();
783
784        while current != from_lower {
785            let (parent, file, line, _depth) = &visited[&current];
786            let sym_name = if current == to_lower {
787                to_orig.to_string()
788            } else {
789                current.clone()
790            };
791            path.push(PathHop {
792                symbol: sym_name,
793                file: file.clone(),
794                line: *line,
795            });
796            current = parent.clone();
797        }
798
799        path.push(PathHop {
800            symbol: from_orig.to_string(),
801            file: String::new(),
802            line: 0,
803        });
804
805        path.reverse();
806        path
807    }
808
809    /// Count unique transitive callers up to `max_depth`.
810    pub fn transitive_caller_count(&self, symbol: &str, max_depth: usize) -> usize {
811        let nodes = self.bfs_callers(symbol, max_depth);
812        let mut unique: std::collections::HashSet<String> = std::collections::HashSet::new();
813        for node in &nodes {
814            unique.insert(node.symbol.to_lowercase());
815        }
816        unique.len()
817    }
818
819    pub fn save(&self) -> Result<(), String> {
820        let dir = call_graph_dir(&self.project_root)
821            .ok_or_else(|| "Cannot determine home directory".to_string())?;
822        std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
823        let json = serde_json::to_string(self).map_err(|e| e.to_string())?;
824        let compressed = zstd::encode_all(json.as_bytes(), 9).map_err(|e| format!("zstd: {e}"))?;
825        let target = dir.join("call_graph.json.zst");
826        let tmp = target.with_extension("zst.tmp");
827        std::fs::write(&tmp, &compressed).map_err(|e| e.to_string())?;
828        std::fs::rename(&tmp, &target).map_err(|e| e.to_string())?;
829        let _ = std::fs::remove_file(dir.join("call_graph.json"));
830        Ok(())
831    }
832
833    pub fn load(project_root: &str) -> Option<Self> {
834        Self::load_any_version(project_root).filter(|g| g.format_version == CALL_GRAPH_FORMAT)
835    }
836
837    fn load_any_version(project_root: &str) -> Option<Self> {
838        let dir = call_graph_dir(project_root)?;
839
840        let zst_path = dir.join("call_graph.json.zst");
841        if zst_path.exists() {
842            let compressed = std::fs::read(&zst_path).ok()?;
843            let data = zstd::decode_all(compressed.as_slice()).ok()?;
844            let content = String::from_utf8(data).ok()?;
845            return serde_json::from_str(&content).ok();
846        }
847
848        let json_path = dir.join("call_graph.json");
849        if json_path.exists() {
850            let content = std::fs::read_to_string(&json_path).ok()?;
851            let parsed: Self = serde_json::from_str(&content).ok()?;
852            // Auto-migrate: compress legacy JSON to zstd
853            if let Ok(compressed) = zstd::encode_all(content.as_bytes(), 9) {
854                let zst_tmp = zst_path.with_extension("zst.tmp");
855                if std::fs::write(&zst_tmp, &compressed).is_ok()
856                    && std::fs::rename(&zst_tmp, &zst_path).is_ok()
857                {
858                    let _ = std::fs::remove_file(&json_path);
859                }
860            }
861            return Some(parsed);
862        }
863
864        None
865    }
866
867    pub fn load_or_build(project_root: &str, inputs: &CallGraphInputs) -> Self {
868        if let Some(previous) = Self::load(project_root) {
869            Self::build_incremental(inputs, &previous)
870        } else {
871            Self::build(inputs)
872        }
873    }
874}
875
876// ---------------------------------------------------------------------------
877// Cache staleness check (fast — mtime-based, no content reads)
878// ---------------------------------------------------------------------------
879
880fn cache_looks_stale(cached: &CallGraph, inputs: &CallGraphInputs) -> bool {
881    if cached.file_hashes.len() != inputs.file_paths.len() {
882        return true;
883    }
884    let cached_files: std::collections::HashSet<&str> =
885        cached.file_hashes.keys().map(String::as_str).collect();
886    let index_files: std::collections::HashSet<&str> =
887        inputs.file_paths.iter().map(String::as_str).collect();
888    cached_files != index_files
889}
890
891/// Whether `cached` was built from a file that is not among `inputs` — the
892/// files the current request may use. Unlike [`cache_looks_stale`] this
893/// ignores files the build could not read, so a resident graph is not
894/// rebuilt on every request because of one unreadable file.
895fn holds_withdrawn_files(cached: &CallGraph, inputs: &CallGraphInputs) -> bool {
896    let current: std::collections::HashSet<&str> =
897        inputs.file_paths.iter().map(String::as_str).collect();
898    cached
899        .file_hashes
900        .keys()
901        .any(|file| !current.contains(file.as_str()))
902}
903
904// ---------------------------------------------------------------------------
905// Helpers
906// ---------------------------------------------------------------------------
907
908fn call_graph_dir(project_root: &str) -> Option<std::path::PathBuf> {
909    GraphProvider::index_dir(project_root)
910}
911
912fn group_edges_by_file(edges: &[CallEdge]) -> HashMap<&str, Vec<CallEdge>> {
913    let mut map: HashMap<&str, Vec<CallEdge>> = HashMap::new();
914    for edge in edges {
915        map.entry(edge.caller_file.as_str())
916            .or_default()
917            .push(edge.clone());
918    }
919    map
920}
921
922/// Owned version for safe `Send` across rayon threads.
923fn group_symbols_by_file_owned(inputs: &CallGraphInputs) -> HashMap<String, Vec<SymbolSpan>> {
924    let mut map: HashMap<String, Vec<SymbolSpan>> = HashMap::new();
925    for sym in &inputs.symbols {
926        map.entry(sym.file.clone()).or_default().push(sym.clone());
927    }
928    for syms in map.values_mut() {
929        syms.sort_by_key(|s| s.start_line);
930    }
931    map
932}
933
934fn find_enclosing_symbol_owned(file_symbols: Option<&Vec<SymbolSpan>>, line: usize) -> String {
935    let Some(syms) = file_symbols else {
936        return "<module>".to_string();
937    };
938    let mut best: Option<&SymbolSpan> = None;
939    for sym in syms {
940        if line >= sym.start_line && line <= sym.end_line {
941            match best {
942                None => best = Some(sym),
943                Some(prev) => {
944                    if (sym.end_line - sym.start_line) < (prev.end_line - prev.start_line) {
945                        best = Some(sym);
946                    }
947                }
948            }
949        }
950    }
951    best.map_or_else(|| "<module>".to_string(), |s| s.name.clone())
952}
953
954fn resolve_path(relative: &str, project_root: &str) -> String {
955    let p = Path::new(relative);
956    if p.is_absolute() && p.exists() {
957        return relative.to_string();
958    }
959    let relative = relative.trim_start_matches(['/', '\\']);
960    let joined = Path::new(project_root).join(relative);
961    joined.to_string_lossy().to_string()
962}
963
964fn simple_hash(content: &str) -> String {
965    use std::hash::{Hash, Hasher};
966    let mut hasher = std::collections::hash_map::DefaultHasher::new();
967    content.hash(&mut hasher);
968    format!("{:x}", hasher.finish())
969}
970
971/// Current content hashes of the indexed files — the same values a
972/// [`CallGraph`] records in `file_hashes` — without building or loading a
973/// call graph. For callers that need only the hashes (semantic cache keys
974/// and project revision), which is a fraction of a call-graph build.
975pub(crate) fn current_file_hashes(inputs: &CallGraphInputs) -> HashMap<String, String> {
976    inputs
977        .file_paths
978        .par_iter()
979        .filter_map(|rel| {
980            let content = std::fs::read_to_string(resolve_path(rel, &inputs.project_root)).ok()?;
981            Some((rel.clone(), simple_hash(&content)))
982        })
983        .collect()
984}
985
986// ---------------------------------------------------------------------------
987// Scope-aware callee resolution (#321)
988//
989// Call edges store callees as bare names, so attributing `Run`/`Get`/`Handle`
990// to a file by name alone links every same-named symbol (false positives).
991// These helpers resolve a callee to its defining file using the caller's
992// lexical scope and refuse to guess when a name stays ambiguous.
993// ---------------------------------------------------------------------------
994
995/// Build a `file -> imported files` adjacency from the project index's import
996/// and reexport edges, used to scope callee resolution to a caller's imports.
997pub fn build_import_adjacency(
998    inputs: &CallGraphInputs,
999) -> HashMap<String, std::collections::HashSet<String>> {
1000    let mut adj: HashMap<String, std::collections::HashSet<String>> = HashMap::new();
1001    for (from, to) in &inputs.import_edges {
1002        adj.entry(from.clone()).or_default().insert(to.clone());
1003    }
1004    adj
1005}
1006
1007/// Pick the defining file for a callee from candidate `def_files`, ranked by the
1008/// caller's lexical scope (most specific first):
1009///   1. the caller's own file,
1010///   2. exactly one file the caller imports,
1011///   3. exactly one file project-wide.
1012///
1013/// Returns `None` when the name stays ambiguous (never guesses).
1014fn rank_callee_def_file(
1015    def_files: &[&str],
1016    caller_file: &str,
1017    imports: &HashMap<String, std::collections::HashSet<String>>,
1018) -> Option<(String, ScopeMatch)> {
1019    if def_files.is_empty() {
1020        return None;
1021    }
1022    if def_files.contains(&caller_file) {
1023        return Some((caller_file.to_string(), ScopeMatch::SameFile));
1024    }
1025    if let Some(imported) = imports.get(caller_file) {
1026        let mut in_scope = def_files.iter().filter(|f| imported.contains(**f));
1027        if let Some(first) = in_scope.next()
1028            && in_scope.next().is_none()
1029        {
1030            return Some(((*first).to_string(), ScopeMatch::UniqueImport));
1031        }
1032    }
1033    if def_files.len() == 1 {
1034        return Some((def_files[0].to_string(), ScopeMatch::UniqueInProject));
1035    }
1036    None
1037}
1038
1039/// The identifier a callee name ends in: `crate::db::save` → `save`,
1040/// `pkg.Func` → `Func`, `save` → `save`.
1041pub fn callee_segment(name: &str) -> &str {
1042    name.rsplit(|c: char| c == ':' || c == '.')
1043        .next()
1044        .unwrap_or(name)
1045}
1046
1047/// Lower-cased path segments of a callee or query, without the relative
1048/// anchors that do not name anything (`crate`, `self`, `super`, `Self`):
1049/// `crate::config_io::write` → `["config_io", "write"]`.
1050fn path_segments(name: &str) -> Vec<String> {
1051    name.split(|c: char| c == ':' || c == '.')
1052        .filter(|s| !s.is_empty())
1053        .map(str::to_lowercase)
1054        .filter(|s| !matches!(s.as_str(), "crate" | "self" | "super"))
1055        .collect()
1056}
1057
1058/// Whether a call to `callee_name` is a call to the symbol named by `query`.
1059///
1060/// Edges keep the callee as written, so `crate::config_io::write(..)` and
1061/// `config_io::write(..)` must match a query for `write`, and a qualified query
1062/// (`config_io::write`) must match the bare and the qualified spelling. The
1063/// shorter path must be a segment suffix of the longer one, so `a::save` never
1064/// matches `b::save`.
1065pub fn callee_matches(callee_name: &str, query: &str) -> bool {
1066    let callee = path_segments(callee_name);
1067    let query = path_segments(query);
1068    if callee.is_empty() || query.is_empty() {
1069        return false;
1070    }
1071    let (short, long) = if callee.len() <= query.len() {
1072        (&callee, &query)
1073    } else {
1074        (&query, &callee)
1075    };
1076    long.ends_with(short)
1077}
1078
1079/// Narrow `defs` (files defining the callee's last segment) to the files the
1080/// callee's own path names: `config_io::write` → `…/config_io.rs` or
1081/// `…/config_io/mod.rs`; `CallGraph::build` → the file that also defines
1082/// `CallGraph`. Returns the single named file, or `None` when the qualifier
1083/// names no definition file or several (never guesses).
1084fn module_path_def_file<'a>(
1085    callee_name: &str,
1086    defs: &[&'a str],
1087    type_files: &HashMap<&str, Vec<&str>>,
1088) -> Option<&'a str> {
1089    let segments: Vec<&str> = callee_name
1090        .split(|c: char| c == ':' || c == '.')
1091        .filter(|s| !s.is_empty() && !matches!(*s, "crate" | "self" | "super" | "Self"))
1092        .collect();
1093    let qualifier = *segments
1094        .len()
1095        .checked_sub(2)
1096        .and_then(|i| segments.get(i))?;
1097    let names_module = |file: &str| -> bool {
1098        let path = Path::new(file);
1099        let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or("");
1100        if stem == qualifier {
1101            return true;
1102        }
1103        matches!(stem, "mod" | "index" | "__init__" | "lib")
1104            && path
1105                .parent()
1106                .and_then(|p| p.file_name())
1107                .and_then(|n| n.to_str())
1108                == Some(qualifier)
1109    };
1110    let type_defs = type_files.get(qualifier);
1111    let mut named = defs
1112        .iter()
1113        .copied()
1114        .filter(|d| names_module(d) || type_defs.is_some_and(|files| files.contains(d)));
1115    let first = named.next()?;
1116    named.next().is_none().then_some(first)
1117}
1118
1119/// Which scope step resolved a callee structurally — the strength of the
1120/// evidence. Same-file and imported definitions are bound by the caller's own
1121/// scope; a name that is merely unique project-wide may still be an external
1122/// function of the same name.
1123#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1124pub enum ScopeMatch {
1125    SameFile,
1126    UniqueImport,
1127    UniqueInProject,
1128    /// The call's own path names the defining module or type
1129    /// (`config_io::write` → `config_io.rs`), and exactly one such file
1130    /// defines the callee.
1131    ModulePath,
1132}
1133
1134/// Structural view of one call edge's callee.
1135#[derive(Debug, Clone, PartialEq, Eq)]
1136pub enum StructuralTarget {
1137    Resolved {
1138        file: String,
1139        via: ScopeMatch,
1140    },
1141    /// Several project definitions remain in scope; structure cannot decide.
1142    Ambiguous,
1143    /// No project symbol has this name (std, dependency, dynamic dispatch).
1144    Unknown,
1145}
1146
1147impl StructuralTarget {
1148    pub fn file(&self) -> Option<&str> {
1149        match self {
1150            Self::Resolved { file, .. } => Some(file),
1151            Self::Ambiguous | Self::Unknown => None,
1152        }
1153    }
1154}
1155
1156/// Resolve a single callee name to its defining file in the scope of `caller_file`.
1157pub fn resolve_callee_file(
1158    callee_name: &str,
1159    caller_file: &str,
1160    inputs: &CallGraphInputs,
1161    imports: &HashMap<String, std::collections::HashSet<String>>,
1162) -> Option<String> {
1163    let mut def_files: Vec<&str> = inputs
1164        .symbols
1165        .iter()
1166        .filter(|s| s.name == callee_name)
1167        .map(|s| s.file.as_str())
1168        .collect();
1169    def_files.sort_unstable();
1170    def_files.dedup();
1171    rank_callee_def_file(&def_files, caller_file, imports).map(|(file, _)| file)
1172}
1173
1174/// Resolve each edge's callee to its defining file in *that edge's own* caller
1175/// scope (index-aligned with `edges`). `None` = ambiguous or unknown; never
1176/// guesses. Use this for per-edge consumers (graph edges); the name-keyed
1177/// [`resolve_callee_files`] additionally drops names that differ across scopes.
1178pub fn resolve_edge_callee_files(
1179    inputs: &CallGraphInputs,
1180    edges: &[CallEdge],
1181) -> Vec<Option<String>> {
1182    resolve_edge_callee_targets(inputs, edges)
1183        .into_iter()
1184        .map(|t| t.file().map(str::to_string))
1185        .collect()
1186}
1187
1188/// Like [`resolve_edge_callee_files`], but keeps *why* each edge resolved —
1189/// or that it is ambiguous vs. unknown — for evidence grading and semantic
1190/// escalation.
1191pub fn resolve_edge_callee_targets(
1192    inputs: &CallGraphInputs,
1193    edges: &[CallEdge],
1194) -> Vec<StructuralTarget> {
1195    let callee_names: std::collections::HashSet<&str> = edges
1196        .iter()
1197        .flat_map(|e| [e.callee_name.as_str(), callee_segment(&e.callee_name)])
1198        .collect();
1199    if callee_names.is_empty() {
1200        return Vec::new();
1201    }
1202
1203    // Definition files per name: callee names, their last path segment, and
1204    // capitalised names (types a path like `CallGraph::build` may qualify by).
1205    let mut name_files: HashMap<&str, Vec<&str>> = HashMap::new();
1206    let mut type_files: HashMap<&str, Vec<&str>> = HashMap::new();
1207    for sym in &inputs.symbols {
1208        if callee_names.contains(sym.name.as_str()) {
1209            name_files
1210                .entry(sym.name.as_str())
1211                .or_default()
1212                .push(sym.file.as_str());
1213        }
1214        if sym.name.starts_with(char::is_uppercase) {
1215            type_files
1216                .entry(sym.name.as_str())
1217                .or_default()
1218                .push(sym.file.as_str());
1219        }
1220    }
1221    for files in name_files.values_mut().chain(type_files.values_mut()) {
1222        files.sort_unstable();
1223        files.dedup();
1224    }
1225
1226    let imports = build_import_adjacency(inputs);
1227    edges
1228        .iter()
1229        .map(|e| {
1230            // Only definitions the caller's language can call directly: a Rust
1231            // `run()` never binds to a shell script's `run`.
1232            let family = call_family(&e.caller_file);
1233            let segment = callee_segment(&e.callee_name);
1234            if segment.len() < e.callee_name.len() {
1235                // Path callee (`db::save`): bind it only when its own path names
1236                // exactly one defining file; otherwise it is a semantic
1237                // candidate, never a structural guess by bare name.
1238                let Some(defs) = name_files
1239                    .get(segment)
1240                    .map(|defs| same_family_defs(defs, family))
1241                    .filter(|d| !d.is_empty())
1242                else {
1243                    return StructuralTarget::Unknown;
1244                };
1245                // `Self::new()` / `self::helper()` name the caller's own type or
1246                // module: bound when the caller's file defines the callee.
1247                let own_scope = ["Self::", "self::"]
1248                    .iter()
1249                    .any(|p| e.callee_name.starts_with(p));
1250                if own_scope && defs.contains(&e.caller_file.as_str()) {
1251                    return StructuralTarget::Resolved {
1252                        file: e.caller_file.clone(),
1253                        via: ScopeMatch::SameFile,
1254                    };
1255                }
1256                return match module_path_def_file(&e.callee_name, &defs, &type_files) {
1257                    Some(file) => StructuralTarget::Resolved {
1258                        file: file.to_string(),
1259                        via: ScopeMatch::ModulePath,
1260                    },
1261                    None => StructuralTarget::Ambiguous,
1262                };
1263            }
1264            let defs = name_files
1265                .get(e.callee_name.as_str())
1266                .map(|defs| same_family_defs(defs, family))
1267                .filter(|d| !d.is_empty());
1268            match defs {
1269                None => StructuralTarget::Unknown,
1270                Some(defs) => match rank_callee_def_file(&defs, &e.caller_file, &imports) {
1271                    Some((file, via)) => StructuralTarget::Resolved { file, via },
1272                    None => StructuralTarget::Ambiguous,
1273                },
1274            }
1275        })
1276        .collect()
1277}
1278
1279/// Only definitions the caller's language `family` can call directly: a Rust
1280/// `run()` never binds to a shell script's `run`.
1281fn same_family_defs<'a>(defs: &[&'a str], family: Option<&str>) -> Vec<&'a str> {
1282    defs.iter()
1283        .copied()
1284        .filter(|d| family.is_none() || call_family(d).is_none_or(|f| Some(f) == family))
1285        .collect()
1286}
1287
1288/// Languages that call each other's definitions directly, by file; `None`
1289/// for files whose language is unknown (never filtered out).
1290fn call_family(path: &str) -> Option<&'static str> {
1291    let id = crate::core::language_capabilities::language_for_path(path)?.id_str();
1292    Some(match id {
1293        "typescript" | "javascript" | "vue" | "svelte" => "js",
1294        "c" | "cpp" => "c",
1295        "java" | "kotlin" | "scala" => "jvm",
1296        "lua" | "luau" => "lua",
1297        other => other,
1298    })
1299}
1300
1301/// Resolve callee names to a single defining file *when scope makes it
1302/// unambiguous across all call sites*. Names that resolve to different files
1303/// from different scopes are omitted, so callers never attribute a call to the
1304/// wrong file. Keyed by callee name to match the call graph's name-keyed nodes.
1305pub fn resolve_callee_files(
1306    inputs: &CallGraphInputs,
1307    edges: &[CallEdge],
1308) -> HashMap<String, String> {
1309    use std::collections::HashSet;
1310
1311    let mut resolved: HashMap<&str, HashSet<String>> = HashMap::new();
1312    for (e, file) in edges.iter().zip(resolve_edge_callee_files(inputs, edges)) {
1313        if let Some(file) = file {
1314            resolved
1315                .entry(e.callee_name.as_str())
1316                .or_default()
1317                .insert(file);
1318        }
1319    }
1320
1321    resolved
1322        .into_iter()
1323        .filter_map(|(name, files)| {
1324            (files.len() == 1).then(|| {
1325                (
1326                    name.to_string(),
1327                    files
1328                        .into_iter()
1329                        .next()
1330                        .expect("files.len() == 1 guarantees one element"),
1331                )
1332            })
1333        })
1334        .collect()
1335}
1336
1337#[cfg(test)]
1338#[path = "call_graph_tests.rs"]
1339pub mod tests;