Skip to main content

aptu_coder_core/
analyze_focused.rs

1// SPDX-FileCopyrightText: 2026 aptu-coder contributors
2// SPDX-License-Identifier: Apache-2.0
3//! Focused analysis: call-graph traversal, import lookup, and wildcard resolution.
4
5use crate::analyze::{
6    AnalyzeError, CallChainEntry, FileAnalysisOutput, FocusedAnalysisConfig, FocusedAnalysisOutput,
7    MAX_FILE_SIZE_BYTES,
8};
9use crate::cache::StructuralGraphCache;
10use crate::formatter::{format_focused_internal, format_focused_summary_internal};
11use crate::graph::store::GraphDiskStore;
12use crate::graph::structural::StructuralGraph;
13use crate::graph::{CallGraph, InternalCallChain};
14use crate::lang::language_for_extension;
15use crate::parser::SemanticExtractor;
16use crate::test_detection::is_test_file;
17use crate::traversal::{WalkEntry, walk_directory};
18use crate::types::{ImplTraitInfo, ImportInfo, SemanticAnalysis, SymbolMatchMode};
19use rayon::prelude::*;
20use std::path::{Path, PathBuf};
21use std::sync::Arc;
22use std::sync::atomic::{AtomicUsize, Ordering};
23use tokio_util::sync::CancellationToken;
24use tracing::instrument;
25
26/// Internal parameters for focused analysis phases.
27#[derive(Clone)]
28pub(crate) struct InternalFocusedParams {
29    pub(crate) focus: String,
30    pub(crate) match_mode: SymbolMatchMode,
31    pub(crate) follow_depth: u32,
32    pub(crate) ast_recursion_limit: Option<usize>,
33    pub(crate) use_summary: bool,
34    pub(crate) impl_only: Option<bool>,
35    pub(crate) def_use: bool,
36    pub(crate) parse_timeout_micros: Option<u64>,
37}
38
39/// Type alias for analysis results: (`file_path`, `semantic_analysis`) pairs, impl-trait info, and precomputed file hashes.
40type FileAnalysisBatch = (
41    Vec<(PathBuf, SemanticAnalysis)>,
42    Vec<ImplTraitInfo>,
43    Vec<(PathBuf, blake3::Hash)>,
44);
45
46/// Phase 1: Collect semantic analysis for all files in parallel.
47fn collect_file_analysis(
48    entries: &[WalkEntry],
49    progress: &Arc<AtomicUsize>,
50    ct: &CancellationToken,
51    ast_recursion_limit: Option<usize>,
52    parse_timeout_micros: Option<u64>,
53) -> Result<FileAnalysisBatch, AnalyzeError> {
54    // Check if already cancelled
55    if ct.is_cancelled() {
56        return Err(AnalyzeError::Cancelled);
57    }
58
59    // Use pre-walked entries (passed by caller)
60    // Collect semantic analysis for all files in parallel
61    let file_entries: Vec<&WalkEntry> = entries
62        .iter()
63        .filter(|e| !e.is_dir && !e.is_symlink)
64        .collect();
65
66    // Collect per-file timeout events so they can be surfaced as AnalyzeError::ParseTimeout.
67    let timed_out: std::sync::Mutex<Vec<(PathBuf, u64)>> = std::sync::Mutex::new(Vec::new());
68
69    // Collect content hashes from successful reads for cache-key computation
70    let hashes: std::sync::Mutex<Vec<(PathBuf, blake3::Hash)>> = std::sync::Mutex::new(Vec::new());
71
72    let analysis_results: Vec<(PathBuf, SemanticAnalysis)> = file_entries
73        .par_iter()
74        .filter_map(|entry| {
75            // Check cancellation per file
76            if ct.is_cancelled() {
77                return None;
78            }
79
80            let ext = entry.path.extension().and_then(|e| e.to_str());
81
82            // Check file size before reading
83            if entry.path.metadata().map(|m| m.len()).unwrap_or(0) > MAX_FILE_SIZE_BYTES {
84                tracing::debug!("skipping large file: {}", entry.path.display());
85                progress.fetch_add(1, Ordering::Relaxed);
86                return None;
87            }
88
89            // Try to read file content
90            let Ok(source) = std::fs::read_to_string(&entry.path) else {
91                progress.fetch_add(1, Ordering::Relaxed);
92                return None;
93            };
94
95            // Record content hash (source.as_bytes() is byte-identical to raw file bytes for valid UTF-8)
96            if let Ok(mut h) = hashes.lock() {
97                h.push((entry.path.clone(), blake3::hash(source.as_bytes())));
98            }
99
100            // Detect language and extract semantic information
101            let language = if let Some(ext_str) = ext {
102                language_for_extension(ext_str)
103                    .map_or_else(|| "unknown".to_string(), std::string::ToString::to_string)
104            } else {
105                "unknown".to_string()
106            };
107
108            match SemanticExtractor::extract(
109                &source,
110                &language,
111                ast_recursion_limit,
112                parse_timeout_micros,
113            ) {
114                Ok(mut semantic) => {
115                    // Populate file path on references
116                    for r in &mut semantic.references {
117                        r.location = entry.path.display().to_string();
118                    }
119                    // Populate file path on impl_traits (already extracted during SemanticExtractor::extract)
120                    for trait_info in &mut semantic.impl_traits {
121                        trait_info.path.clone_from(&entry.path);
122                    }
123                    progress.fetch_add(1, Ordering::Relaxed);
124                    Some((entry.path.clone(), semantic))
125                }
126                Err(crate::parser::ParserError::Timeout(micros)) => {
127                    tracing::warn!(
128                        "parse timeout exceeded for {}: {} microseconds",
129                        entry.path.display(),
130                        micros
131                    );
132                    if let Ok(mut v) = timed_out.lock() {
133                        v.push((entry.path.clone(), micros));
134                    }
135                    progress.fetch_add(1, Ordering::Relaxed);
136                    None
137                }
138                Err(_) => {
139                    progress.fetch_add(1, Ordering::Relaxed);
140                    None
141                }
142            }
143        })
144        .collect();
145
146    // Check if cancelled after parallel processing
147    if ct.is_cancelled() {
148        return Err(AnalyzeError::Cancelled);
149    }
150
151    // Surface the first timeout as AnalyzeError::ParseTimeout so callers can detect it.
152    if let Ok(mut v) = timed_out.lock()
153        && let Some((path, micros)) = v.drain(..).next()
154    {
155        return Err(AnalyzeError::ParseTimeout { path, micros });
156    }
157
158    // Collect all impl-trait info from analysis results
159    let all_impl_traits: Vec<ImplTraitInfo> = analysis_results
160        .iter()
161        .flat_map(|(_, sem)| sem.impl_traits.iter().cloned())
162        .collect();
163
164    // Extract precomputed hashes
165    let precomputed_hashes = hashes.into_inner().unwrap_or_default();
166
167    Ok((analysis_results, all_impl_traits, precomputed_hashes))
168}
169
170/// Phase 2: Build call graph from analysis results.
171fn build_call_graph(
172    analysis_results: Vec<(PathBuf, SemanticAnalysis)>,
173    all_impl_traits: &[ImplTraitInfo],
174) -> Result<CallGraph, AnalyzeError> {
175    // Build call graph. Always build without impl_only filter first so we can
176    // record the unfiltered caller count before discarding those edges.
177    CallGraph::build_from_results(
178        analysis_results,
179        all_impl_traits,
180        false, // filter applied below after counting
181    )
182    .map_err(std::convert::Into::into)
183}
184
185/// Cache key from file content hashes. Reuses precomputed hashes when available,
186/// falls back to reading unhashed files. Returns None if any unhashed file cannot be read.
187fn compute_cache_key(
188    root: &Path,
189    entries: &[WalkEntry],
190    precomputed: &[(PathBuf, blake3::Hash)],
191) -> Option<String> {
192    // Build a map for O(1) lookup of precomputed hashes
193    let mut hash_map = std::collections::HashMap::new();
194    for (path, hash) in precomputed {
195        hash_map.insert(path.as_path(), *hash);
196    }
197
198    let mut hashes = Vec::new();
199    for e in entries {
200        if !e.is_dir && !e.is_symlink {
201            let hash = if let Some(h) = hash_map.get(e.path.as_path()) {
202                *h
203            } else {
204                // File was skipped or failed to read in collect_file_analysis; fall back to reading
205                let bytes = std::fs::read(&e.path).ok()?;
206                blake3::hash(&bytes)
207            };
208            hashes.push((e.path.clone(), hash));
209        }
210    }
211    Some(GraphDiskStore::cache_key(root, &hashes))
212}
213
214/// Create a GraphDiskStore from env var or XDG data home default.
215fn create_graph_store() -> GraphDiskStore {
216    let data_home = std::env::var_os("XDG_DATA_HOME")
217        .map(PathBuf::from)
218        .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".local/share")))
219        .unwrap_or_default();
220    let base = std::env::var("APTU_CODER_DISK_CACHE_DIR")
221        .map(PathBuf::from)
222        .unwrap_or_else(|_| data_home.join("aptu-coder").join("analysis-cache"));
223    let max_bytes = std::env::var("APTU_CODER_DISK_CACHE_MAX_BYTES")
224        .ok()
225        .and_then(|s| s.parse::<u64>().ok())
226        .unwrap_or(crate::graph::store::DEFAULT_MAX_DISK_CACHE_BYTES);
227    GraphDiskStore::new_with_max_bytes(base, max_bytes)
228}
229
230/// Phase 3: Resolve symbol and apply `impl_only` filter.
231/// Returns (`resolved_focus`, `unfiltered_caller_count`, `impl_trait_caller_count`).
232/// CRITICAL: Must capture `unfiltered_caller_count` BEFORE `retain()`, then apply `retain()`,
233/// then compute `impl_trait_caller_count`.
234fn resolve_symbol(
235    graph: &mut CallGraph,
236    params: &InternalFocusedParams,
237) -> Result<(String, usize, usize), AnalyzeError> {
238    // Resolve symbol name using the requested match mode.
239    let resolved_focus = if params.match_mode == SymbolMatchMode::Exact {
240        let exists = graph.definitions.contains_key(&params.focus)
241            || graph.callers.contains_key(&params.focus)
242            || graph.callees.contains_key(&params.focus);
243        if exists {
244            params.focus.clone()
245        } else {
246            return Err(crate::graph::GraphError::SymbolNotFound {
247                symbol: params.focus.clone(),
248                hint: "Try match_mode=insensitive for a case-insensitive search, or match_mode=prefix to list symbols starting with this name.".to_string(),
249            }
250            .into());
251        }
252    } else {
253        graph.resolve_symbol_indexed(&params.focus, &params.match_mode)?
254    };
255
256    // Count unique callers for the focus symbol before applying impl_only filter.
257    let unfiltered_caller_count = graph.callers.get(&resolved_focus).map_or(0, |edges| {
258        edges
259            .iter()
260            .map(|e| &e.neighbor_name)
261            .collect::<std::collections::HashSet<_>>()
262            .len()
263    });
264
265    // Apply impl_only filter now if requested, then count filtered callers.
266    // Filter all caller adjacency lists so traversal and formatting are consistently
267    // restricted to impl-trait edges regardless of follow_depth.
268    let impl_trait_caller_count = if params.impl_only.unwrap_or(false) {
269        for edges in graph.callers.values_mut() {
270            edges.retain(|e| e.is_impl_trait);
271        }
272        graph.callers.get(&resolved_focus).map_or(0, |edges| {
273            edges
274                .iter()
275                .map(|e| &e.neighbor_name)
276                .collect::<std::collections::HashSet<_>>()
277                .len()
278        })
279    } else {
280        unfiltered_caller_count
281    };
282
283    Ok((
284        resolved_focus,
285        unfiltered_caller_count,
286        impl_trait_caller_count,
287    ))
288}
289
290/// Type alias for `compute_chains` return type: (`formatted_output`, `prod_chains`, `test_chains`, `outgoing_chains`, `def_count`).
291type ChainComputeResult = (
292    String,
293    Vec<InternalCallChain>,
294    Vec<InternalCallChain>,
295    Vec<InternalCallChain>,
296    usize,
297);
298
299/// Helper function to convert InternalCallChain data to CallChainEntry vec.
300/// Takes the first (depth-1) element of each chain and converts it to a CallChainEntry.
301/// Returns None if chains is empty, otherwise returns a vec of up to 10 entries.
302pub(crate) fn chains_to_entries(
303    chains: &[InternalCallChain],
304    root: Option<&std::path::Path>,
305) -> Option<Vec<CallChainEntry>> {
306    if chains.is_empty() {
307        return None;
308    }
309    let entries: Vec<CallChainEntry> = chains
310        .iter()
311        .take(10)
312        .filter_map(|chain| {
313            let (symbol, path, line) = chain.chain.first()?;
314            let file = match root {
315                Some(root) => path
316                    .strip_prefix(root)
317                    .unwrap_or(path.as_path())
318                    .to_string_lossy()
319                    .into_owned(),
320                None => path.to_string_lossy().into_owned(),
321            };
322            Some(CallChainEntry {
323                symbol: symbol.clone(),
324                file,
325                line: *line,
326            })
327        })
328        .collect();
329    if entries.is_empty() {
330        None
331    } else {
332        Some(entries)
333    }
334}
335
336/// Phase 4: Compute chains and format output.
337fn compute_chains(
338    graph: &CallGraph,
339    resolved_focus: &str,
340    root: &Path,
341    params: &InternalFocusedParams,
342    unfiltered_caller_count: usize,
343    impl_trait_caller_count: usize,
344    def_use_sites: &[crate::types::DefUseSite],
345) -> Result<ChainComputeResult, AnalyzeError> {
346    // Compute chain data for pagination (always, regardless of summary mode)
347    let def_count = graph.definitions.get(resolved_focus).map_or(0, Vec::len);
348    let incoming_chains = graph.find_incoming_chains(resolved_focus, params.follow_depth)?;
349    let outgoing_chains = graph.find_outgoing_chains(resolved_focus, params.follow_depth)?;
350
351    let (prod_chains, test_chains): (Vec<_>, Vec<_>) =
352        incoming_chains.iter().cloned().partition(|chain| {
353            chain
354                .chain
355                .first()
356                .is_none_or(|(name, path, _)| !is_test_file(path) && !name.starts_with("test_"))
357        });
358
359    // Format output with pre-computed chains
360    let mut formatted = if params.use_summary {
361        format_focused_summary_internal(
362            graph,
363            resolved_focus,
364            params.follow_depth,
365            Some(root),
366            Some(&incoming_chains),
367            Some(&outgoing_chains),
368            def_use_sites,
369        )?
370    } else {
371        format_focused_internal(
372            graph,
373            resolved_focus,
374            params.follow_depth,
375            Some(root),
376            Some(&incoming_chains),
377            Some(&outgoing_chains),
378            def_use_sites,
379        )?
380    };
381
382    // Add FILTER header if impl_only filter was applied
383    if params.impl_only.unwrap_or(false) {
384        let filter_header = format!(
385            "FILTER: impl_only=true ({impl_trait_caller_count} of {unfiltered_caller_count} callers shown)\n",
386        );
387        formatted = format!("{filter_header}{formatted}");
388    }
389
390    Ok((
391        formatted,
392        prod_chains,
393        test_chains,
394        outgoing_chains,
395        def_count,
396    ))
397}
398
399/// Analyze a symbol's call graph across a directory with progress tracking.
400// public API; callers expect owned semantics
401#[allow(clippy::needless_pass_by_value)]
402pub fn analyze_focused_with_progress(
403    root: &Path,
404    params: &FocusedAnalysisConfig,
405    progress: Arc<AtomicUsize>,
406    ct: CancellationToken,
407) -> Result<FocusedAnalysisOutput, AnalyzeError> {
408    let entries = walk_directory(root, params.max_depth)?;
409    let internal_params = InternalFocusedParams {
410        focus: params.focus.clone(),
411        match_mode: params.match_mode.clone(),
412        follow_depth: params.follow_depth,
413        ast_recursion_limit: params.ast_recursion_limit,
414        use_summary: params.use_summary,
415        impl_only: params.impl_only,
416        def_use: params.def_use,
417        parse_timeout_micros: params.parse_timeout_micros,
418    };
419    analyze_focused_with_progress_with_entries_internal(
420        root,
421        params.max_depth,
422        &progress,
423        &ct,
424        &internal_params,
425        &entries,
426        None,
427    )
428}
429
430/// Internal implementation of focused analysis using pre-walked entries and params struct.
431#[instrument(skip_all, fields(path = %root.display(), symbol = %params.focus))]
432fn analyze_focused_with_progress_with_entries_internal(
433    root: &Path,
434    _max_depth: Option<u32>,
435    progress: &Arc<AtomicUsize>,
436    ct: &CancellationToken,
437    params: &InternalFocusedParams,
438    entries: &[WalkEntry],
439    structural_graph_cache: Option<&StructuralGraphCache>,
440) -> Result<FocusedAnalysisOutput, AnalyzeError> {
441    // Check if already cancelled
442    if ct.is_cancelled() {
443        return Err(AnalyzeError::Cancelled);
444    }
445
446    // Check if path is a file (hint to use directory)
447    if root.is_file() {
448        let formatted =
449            "Single-file focus not supported. Please provide a directory path for cross-file call graph analysis.\n"
450                .to_string();
451        return Ok(FocusedAnalysisOutput {
452            formatted,
453            next_cursor: None,
454            prod_chains: vec![],
455            test_chains: vec![],
456            outgoing_chains: vec![],
457            def_count: 0,
458            unfiltered_caller_count: 0,
459            impl_trait_caller_count: 0,
460            callers: None,
461            test_callers: None,
462            callees: None,
463            def_use_sites: vec![],
464            cache_tier: None,
465        });
466    }
467
468    // Phase 1: Collect file analysis
469    let (analysis_results, all_impl_traits, precomputed_hashes) = collect_file_analysis(
470        entries,
471        progress,
472        ct,
473        params.ast_recursion_limit,
474        params.parse_timeout_micros,
475    )?;
476
477    // Compute cache key for structural graph store (best-effort, degrades silently)
478    let cache_key = compute_cache_key(root, entries, &precomputed_hashes);
479
480    // Check for cancellation before building the call graph (phase 2)
481    if ct.is_cancelled() {
482        return Err(AnalyzeError::Cancelled);
483    }
484
485    // Phase 2: Build call graph (clone analysis_results for structural graph storage)
486    let mut graph = build_call_graph(analysis_results.clone(), &all_impl_traits)?;
487
488    // Best-effort: warm L1 cache hit, warm L2 disk cache hit, or cold miss build+persist.
489    // On L1 hit: skip rebuild. On L2 hit: build L1 entry from L2. On miss: build both.
490    // I/O errors degrade silently; the focused call-graph result is unaffected.
491    if let Some(key) = &cache_key {
492        if let Some(_graph) = structural_graph_cache.and_then(|c| c.get(key)) {
493            tracing::debug!(key, "structural graph cache hit (warm L1)");
494        } else {
495            let store = create_graph_store();
496            if let Some(graph) = store.get(key) {
497                tracing::debug!(key, "structural graph cache hit (warm L2)");
498                if let Some(cache) = structural_graph_cache {
499                    cache.put(key.clone(), Arc::new(graph));
500                }
501            } else {
502                let sg_entries: Vec<FileAnalysisOutput> = analysis_results
503                    .into_iter()
504                    .map(|(p, s)| {
505                        FileAnalysisOutput::new(
506                            p.to_string_lossy().into_owned(),
507                            String::new(),
508                            s,
509                            0,
510                            None,
511                        )
512                    })
513                    .collect();
514                let graph = Arc::new(StructuralGraph::build_from_analysis(&sg_entries));
515                store.put(key, &graph);
516                if let Some(cache) = structural_graph_cache {
517                    cache.put(key.clone(), graph);
518                }
519            }
520        }
521    }
522
523    // Check for cancellation before resolving the symbol (phase 3)
524    if ct.is_cancelled() {
525        return Err(AnalyzeError::Cancelled);
526    }
527
528    // Phase 3: Resolve symbol and apply impl_only filter.
529    // When def_use=true and the symbol is not in the call graph (e.g. a variable),
530    // fall through to def-use extraction instead of returning SymbolNotFound.
531    let resolve_result = resolve_symbol(&mut graph, params);
532    if let Err(AnalyzeError::Graph(crate::graph::GraphError::SymbolNotFound { .. })) =
533        &resolve_result
534    {
535        // Deliberately not collapsed: resolve_result must stay alive past this block
536        // so that the `?` below can propagate non-SymbolNotFound errors.
537        if params.def_use {
538            let def_use_sites =
539                collect_def_use_sites(entries, &params.focus, params.ast_recursion_limit, root, ct);
540            if def_use_sites.is_empty() {
541                // Symbol not found anywhere (neither in call graph nor as def/use site).
542                // Propagate the original SymbolNotFound error instead of returning an
543                // empty success response.
544                if let Err(e) = resolve_result {
545                    return Err(e);
546                }
547                unreachable!("resolve_result is Ok only when symbol was found");
548            }
549            use std::fmt::Write as _;
550            let mut formatted = String::new();
551            let _ = writeln!(
552                formatted,
553                "FOCUS: {} (0 defs, 0 callers, 0 callees)",
554                params.focus
555            );
556            {
557                let writes = def_use_sites
558                    .iter()
559                    .filter(|s| {
560                        matches!(
561                            s.kind,
562                            crate::types::DefUseKind::Write | crate::types::DefUseKind::WriteRead
563                        )
564                    })
565                    .count();
566                let reads = def_use_sites
567                    .iter()
568                    .filter(|s| s.kind == crate::types::DefUseKind::Read)
569                    .count();
570                let _ = writeln!(
571                    formatted,
572                    "DEF-USE SITES  {}  ({} total: {} writes, {} reads)",
573                    params.focus,
574                    def_use_sites.len(),
575                    writes,
576                    reads
577                );
578            }
579            return Ok(FocusedAnalysisOutput {
580                formatted,
581                next_cursor: None,
582                callers: None,
583                test_callers: None,
584                callees: None,
585                prod_chains: vec![],
586                test_chains: vec![],
587                outgoing_chains: vec![],
588                def_count: 0,
589                unfiltered_caller_count: 0,
590                impl_trait_caller_count: 0,
591                def_use_sites,
592                cache_tier: None,
593            });
594        }
595    }
596    let (resolved_focus, unfiltered_caller_count, impl_trait_caller_count) = resolve_result?;
597
598    // Check for cancellation before computing chains (phase 4)
599    if ct.is_cancelled() {
600        return Err(AnalyzeError::Cancelled);
601    }
602
603    // Phase 5 (optional, before formatting): Def-use site extraction.
604    // Use params.focus (the raw user-supplied string) rather than resolved_focus
605    // so that variable/field names that are not in the call graph still work.
606    let def_use_sites = if params.def_use {
607        collect_def_use_sites(entries, &params.focus, params.ast_recursion_limit, root, ct)
608    } else {
609        Vec::new()
610    };
611
612    // Phase 4: Compute chains and format output (includes def_use_sites in one pass)
613    let (formatted, prod_chains, test_chains, outgoing_chains, def_count) = compute_chains(
614        &graph,
615        &resolved_focus,
616        root,
617        params,
618        unfiltered_caller_count,
619        impl_trait_caller_count,
620        &def_use_sites,
621    )?;
622
623    // Compute depth-1 chains for structured output fields (always direct relationships only,
624    // regardless of `follow_depth` used for the text-formatted output).
625    let (depth1_callers, depth1_test_callers, depth1_callees) = if params.follow_depth <= 1 {
626        // Chains already at depth 1; reuse the partitioned vecs.
627        let callers = chains_to_entries(&prod_chains, Some(root));
628        let test_callers = chains_to_entries(&test_chains, Some(root));
629        let callees = chains_to_entries(&outgoing_chains, Some(root));
630        (callers, test_callers, callees)
631    } else {
632        // follow_depth > 1: re-query at depth 1 to get only direct edges.
633        let incoming1 = graph
634            .find_incoming_chains(&resolved_focus, 1)
635            .unwrap_or_default();
636        let outgoing1 = graph
637            .find_outgoing_chains(&resolved_focus, 1)
638            .unwrap_or_default();
639        let (prod1, test1): (Vec<_>, Vec<_>) = incoming1.into_iter().partition(|chain| {
640            chain
641                .chain
642                .first()
643                .is_none_or(|(name, path, _)| !is_test_file(path) && !name.starts_with("test_"))
644        });
645        let callers = chains_to_entries(&prod1, Some(root));
646        let test_callers = chains_to_entries(&test1, Some(root));
647        let callees = chains_to_entries(&outgoing1, Some(root));
648        (callers, test_callers, callees)
649    };
650
651    Ok(FocusedAnalysisOutput {
652        formatted,
653        next_cursor: None,
654        callers: depth1_callers,
655        test_callers: depth1_test_callers,
656        callees: depth1_callees,
657        prod_chains,
658        test_chains,
659        outgoing_chains,
660        def_count,
661        unfiltered_caller_count,
662        impl_trait_caller_count,
663        def_use_sites,
664        cache_tier: None,
665    })
666}
667
668/// Phase 5: Extract def-use sites for `symbol` across all entries.
669/// Writes go before reads; within each kind ordered by file, line, then column.
670fn collect_def_use_sites(
671    entries: &[WalkEntry],
672    symbol: &str,
673    ast_recursion_limit: Option<usize>,
674    root: &std::path::Path,
675    ct: &CancellationToken,
676) -> Vec<crate::types::DefUseSite> {
677    use crate::parser::SemanticExtractor;
678
679    let file_entries: Vec<&WalkEntry> = entries
680        .iter()
681        .filter(|e| !e.is_dir && !e.is_symlink)
682        .collect();
683
684    let mut sites: Vec<crate::types::DefUseSite> = file_entries
685        .par_iter()
686        .filter_map(|entry| {
687            if ct.is_cancelled() {
688                return None;
689            }
690
691            // Check file size before reading
692            if entry.path.metadata().map(|m| m.len()).unwrap_or(0) > MAX_FILE_SIZE_BYTES {
693                tracing::debug!("skipping large file: {}", entry.path.display());
694                return None;
695            }
696
697            let Ok(source) = std::fs::read_to_string(&entry.path) else {
698                return None;
699            };
700            let ext = entry
701                .path
702                .extension()
703                .and_then(|e| e.to_str())
704                .unwrap_or("");
705            let lang = crate::lang::language_for_extension(ext)?;
706            let file_path = entry
707                .path
708                .strip_prefix(root)
709                .unwrap_or(&entry.path)
710                .display()
711                .to_string();
712            let sites = SemanticExtractor::extract_def_use_for_file(
713                &source,
714                lang,
715                symbol,
716                &file_path,
717                ast_recursion_limit,
718            );
719            if sites.is_empty() { None } else { Some(sites) }
720        })
721        .flatten()
722        .collect();
723
724    // Writes before reads; within each kind: file, line, then column for deterministic order
725    sites.sort_by(|a, b| {
726        use crate::types::DefUseKind;
727        let kind_ord = |k: &DefUseKind| match k {
728            DefUseKind::Write | DefUseKind::WriteRead => 0,
729            DefUseKind::Read => 1,
730        };
731        kind_ord(&a.kind)
732            .cmp(&kind_ord(&b.kind))
733            .then_with(|| a.file.cmp(&b.file))
734            .then_with(|| a.line.cmp(&b.line))
735            .then_with(|| a.column.cmp(&b.column))
736    });
737
738    sites
739}
740
741/// Analyze a symbol's call graph using pre-walked directory entries.
742pub fn analyze_focused_with_progress_with_entries(
743    root: &Path,
744    params: &FocusedAnalysisConfig,
745    progress: &Arc<AtomicUsize>,
746    ct: &CancellationToken,
747    entries: &[WalkEntry],
748    structural_graph_cache: Option<&StructuralGraphCache>,
749) -> Result<FocusedAnalysisOutput, AnalyzeError> {
750    let internal_params = InternalFocusedParams {
751        focus: params.focus.clone(),
752        match_mode: params.match_mode.clone(),
753        follow_depth: params.follow_depth,
754        ast_recursion_limit: params.ast_recursion_limit,
755        use_summary: params.use_summary,
756        impl_only: params.impl_only,
757        def_use: params.def_use,
758        parse_timeout_micros: params.parse_timeout_micros,
759    };
760    analyze_focused_with_progress_with_entries_internal(
761        root,
762        params.max_depth,
763        progress,
764        ct,
765        &internal_params,
766        entries,
767        structural_graph_cache,
768    )
769}
770
771#[instrument(skip_all, fields(path = %root.display(), symbol = %focus))]
772pub fn analyze_focused(
773    root: &Path,
774    focus: &str,
775    follow_depth: u32,
776    max_depth: Option<u32>,
777    ast_recursion_limit: Option<usize>,
778) -> Result<FocusedAnalysisOutput, AnalyzeError> {
779    let entries = walk_directory(root, max_depth)?;
780    let counter = Arc::new(AtomicUsize::new(0));
781    let ct = CancellationToken::new();
782    let params = FocusedAnalysisConfig {
783        focus: focus.to_string(),
784        match_mode: SymbolMatchMode::Exact,
785        follow_depth,
786        max_depth,
787        ast_recursion_limit,
788        use_summary: false,
789        impl_only: None,
790        def_use: false,
791        parse_timeout_micros: None,
792    };
793    analyze_focused_with_progress_with_entries(root, &params, &counter, &ct, &entries, None)
794}
795
796/// Analyze a single file and return a minimal fixed schema (name, line count, language,
797/// functions, imports) for lightweight code understanding.
798#[instrument(skip_all, fields(path))]
799pub fn analyze_module_file(path: &str) -> Result<crate::types::ModuleInfo, AnalyzeError> {
800    // Check file size before reading
801    if Path::new(path).metadata().map(|m| m.len()).unwrap_or(0) > MAX_FILE_SIZE_BYTES {
802        tracing::debug!("skipping large file: {}", path);
803        return Err(AnalyzeError::Parser(
804            crate::parser::ParserError::ParseError("file too large".to_string()),
805        ));
806    }
807
808    let source = std::fs::read_to_string(path)
809        .map_err(|e| AnalyzeError::Parser(crate::parser::ParserError::ParseError(e.to_string())))?;
810
811    let file_path = Path::new(path);
812    let name = file_path
813        .file_name()
814        .and_then(|s| s.to_str())
815        .unwrap_or("unknown")
816        .to_string();
817
818    let line_count = source.lines().count();
819
820    let language = file_path
821        .extension()
822        .and_then(|e| e.to_str())
823        .and_then(language_for_extension)
824        .ok_or_else(|| {
825            AnalyzeError::Parser(crate::parser::ParserError::UnsupportedLanguage(
826                file_path
827                    .extension()
828                    .and_then(|e| e.to_str())
829                    .unwrap_or("(no extension)")
830                    .to_string(),
831            ))
832        })?;
833
834    let mut module_info = SemanticExtractor::extract_module_info(&source, language, None)?;
835    module_info.name = name;
836    module_info.line_count = line_count;
837
838    Ok(module_info)
839}
840
841/// Scan a directory for files that import a given module path.
842///
843/// For each non-directory walk entry, extracts imports via [`SemanticExtractor`] and
844/// checks whether `module` matches `ImportInfo.module` or appears in `ImportInfo.items`.
845/// Returns a [`FocusedAnalysisOutput`] whose `formatted` field lists matching files.
846pub fn analyze_import_lookup(
847    root: &Path,
848    module: &str,
849    entries: &[WalkEntry],
850    ast_recursion_limit: Option<usize>,
851) -> Result<FocusedAnalysisOutput, AnalyzeError> {
852    let matches: Vec<(PathBuf, usize)> = entries
853        .par_iter()
854        .filter_map(|entry| {
855            if entry.is_dir || entry.is_symlink {
856                tracing::debug!("skipping symlink: {}", entry.path.display());
857                return None;
858            }
859            let ext = entry
860                .path
861                .extension()
862                .and_then(|e| e.to_str())
863                .and_then(crate::lang::language_for_extension)?;
864            let source = std::fs::read_to_string(&entry.path).ok()?;
865            let semantic =
866                SemanticExtractor::extract(&source, ext, ast_recursion_limit, None).ok()?;
867            for import in &semantic.imports {
868                if import.module == module || import.items.iter().any(|item| item == module) {
869                    return Some((entry.path.clone(), import.line));
870                }
871            }
872            None
873        })
874        .collect();
875
876    let mut text = format!("IMPORT_LOOKUP: {module}\n");
877    text.push_str(&format!("ROOT: {}\n", root.display()));
878    text.push_str(&format!("MATCHES: {}\n", matches.len()));
879    for (path, line) in &matches {
880        let rel = path.strip_prefix(root).unwrap_or(path);
881        text.push_str(&format!("  {}:{line}\n", rel.display()));
882    }
883
884    Ok(FocusedAnalysisOutput {
885        formatted: text,
886        next_cursor: None,
887        prod_chains: vec![],
888        test_chains: vec![],
889        outgoing_chains: vec![],
890        def_count: 0,
891        unfiltered_caller_count: 0,
892        impl_trait_caller_count: 0,
893        callers: None,
894        test_callers: None,
895        callees: None,
896        def_use_sites: vec![],
897        cache_tier: None,
898    })
899}
900
901/// Resolve Python wildcard imports to actual symbol names.
902///
903/// For each import with items=`["*"]`, this function:
904/// 1. Parses the relative dots (if any) and climbs the directory tree
905/// 2. Finds the target .py file or __init__.py
906/// 3. Extracts symbols (functions and classes) from the target
907/// 4. Honors __all__ if defined, otherwise uses function+class names
908///
909/// All resolution failures are non-fatal: debug-logged and the wildcard is preserved.
910pub(crate) fn resolve_wildcard_imports(file_path: &Path, imports: &mut [ImportInfo]) {
911    use std::collections::HashMap;
912
913    let mut resolved_cache: HashMap<PathBuf, Vec<String>> = HashMap::new();
914    let Ok(file_path_canonical) = file_path.canonicalize() else {
915        tracing::debug!(file = ?file_path, "unable to canonicalize current file path");
916        return;
917    };
918
919    for import in imports.iter_mut() {
920        if import.items != ["*"] {
921            continue;
922        }
923        resolve_single_wildcard(import, file_path, &file_path_canonical, &mut resolved_cache);
924    }
925}
926
927/// Validate and canonicalize a wildcard target path, checking for self-references.
928/// Returns the canonical path if valid, or None if validation fails.
929fn validate_wildcard_target(
930    target_to_read: &Path,
931    file_path_canonical: &Path,
932    module: &str,
933) -> Option<PathBuf> {
934    let Ok(canonical) = target_to_read.canonicalize() else {
935        tracing::debug!(target = ?target_to_read, import = %module, "unable to canonicalize path");
936        return None;
937    };
938
939    if canonical == file_path_canonical {
940        tracing::debug!(target = ?canonical, import = %module, "cannot import from self");
941        return None;
942    }
943
944    Some(canonical)
945}
946
947/// Resolve one wildcard import in place. On any failure the import is left unchanged.
948fn resolve_single_wildcard(
949    import: &mut ImportInfo,
950    file_path: &Path,
951    file_path_canonical: &Path,
952    resolved_cache: &mut std::collections::HashMap<PathBuf, Vec<String>>,
953) {
954    let module = import.module.clone();
955    let dot_count = module.chars().take_while(|c| *c == '.').count();
956    if dot_count == 0 {
957        return;
958    }
959    let module_path = module.trim_start_matches('.');
960
961    let Some(target_to_read) = locate_target_file(file_path, dot_count, module_path, &module)
962    else {
963        return;
964    };
965
966    let Some(canonical) = validate_wildcard_target(&target_to_read, file_path_canonical, &module)
967    else {
968        return;
969    };
970
971    if let Some(cached) = resolved_cache.get(&canonical) {
972        tracing::debug!(import = %module, symbols_count = cached.len(), "using cached symbols");
973        import.items.clone_from(cached);
974        return;
975    }
976
977    if let Some(symbols) = parse_target_symbols(&target_to_read, &module) {
978        tracing::debug!(import = %module, resolved_count = symbols.len(), "wildcard import resolved");
979        import.items.clone_from(&symbols);
980        resolved_cache.insert(canonical, symbols);
981    }
982}
983
984/// Locate the .py file that a wildcard import refers to. Returns None if not found.
985fn locate_target_file(
986    file_path: &Path,
987    dot_count: usize,
988    module_path: &str,
989    module: &str,
990) -> Option<PathBuf> {
991    let mut target_dir = file_path.parent()?.to_path_buf();
992
993    for _ in 1..dot_count {
994        if !target_dir.pop() {
995            tracing::debug!(import = %module, "unable to climb {} levels", dot_count.saturating_sub(1));
996            return None;
997        }
998    }
999
1000    let target_file = if module_path.is_empty() {
1001        target_dir.join("__init__.py")
1002    } else {
1003        let rel_path = module_path.replace('.', "/");
1004        target_dir.join(format!("{rel_path}.py"))
1005    };
1006
1007    if target_file.exists() {
1008        Some(target_file)
1009    } else if target_file.with_extension("").is_dir() {
1010        let init = target_file.with_extension("").join("__init__.py");
1011        if init.exists() { Some(init) } else { None }
1012    } else {
1013        tracing::debug!(target = ?target_file, import = %module, "target file not found");
1014        None
1015    }
1016}
1017
1018/// Build a tree-sitter parser for Python and parse the source code.
1019fn build_parser_for_file(source: &str) -> Option<tree_sitter::Tree> {
1020    use tree_sitter::Parser;
1021
1022    let lang_info = crate::languages::get_language_info("python")?;
1023    let mut parser = Parser::new();
1024    if parser.set_language(&lang_info.language).is_err() {
1025        return None;
1026    }
1027    parser.parse(source, None)
1028}
1029
1030/// Extract all public symbols from a parsed tree (functions and classes).
1031fn extract_all_symbols(tree: &tree_sitter::Tree, source: &str) -> Vec<String> {
1032    let mut symbols = Vec::new();
1033    let root = tree.root_node();
1034    let mut cursor = root.walk();
1035    for child in root.children(&mut cursor) {
1036        if matches!(child.kind(), "function_definition" | "class_definition")
1037            && let Some(name_node) = child.child_by_field_name("name")
1038        {
1039            let name = source[name_node.start_byte()..name_node.end_byte()].to_string();
1040            if !name.starts_with('_') {
1041                symbols.push(name);
1042            }
1043        }
1044    }
1045    symbols
1046}
1047
1048/// Try to resolve symbols from __all__ or fallback to function/class extraction.
1049fn resolve_symbols_from_tree(tree: &tree_sitter::Tree, source: &str, module: &str) -> Vec<String> {
1050    let mut symbols = Vec::new();
1051    extract_all_from_tree(tree, source, &mut symbols);
1052    if !symbols.is_empty() {
1053        tracing::debug!(import = %module, symbols = ?symbols, "using __all__ symbols");
1054        return symbols;
1055    }
1056
1057    // Fallback: extract functions/classes from the tree
1058    let symbols = extract_all_symbols(tree, source);
1059    tracing::debug!(import = %module, fallback_symbols = ?symbols, "using fallback function/class names");
1060    symbols
1061}
1062
1063/// Read and parse a target .py file, returning its exported symbols.
1064fn parse_target_symbols(target_path: &Path, module: &str) -> Option<Vec<String>> {
1065    // Check file size before reading
1066    if target_path.metadata().map(|m| m.len()).unwrap_or(0) > MAX_FILE_SIZE_BYTES {
1067        tracing::debug!("skipping large file: {}", target_path.display());
1068        return None;
1069    }
1070
1071    let source = match std::fs::read_to_string(target_path) {
1072        Ok(s) => s,
1073        Err(e) => {
1074            tracing::debug!(target = ?target_path, import = %module, error = %e, "unable to read target file");
1075            return None;
1076        }
1077    };
1078
1079    // Parse once with tree-sitter
1080    let tree = build_parser_for_file(&source)?;
1081
1082    // Try to extract __all__ or fallback to function/class extraction
1083    let symbols = resolve_symbols_from_tree(&tree, &source, module);
1084    Some(symbols)
1085}
1086
1087/// Extract __all__ from a tree-sitter tree.
1088fn extract_all_from_tree(tree: &tree_sitter::Tree, source: &str, result: &mut Vec<String>) {
1089    let root = tree.root_node();
1090    let mut cursor = root.walk();
1091    for child in root.children(&mut cursor) {
1092        if child.kind() == "simple_statement" {
1093            // simple_statement contains assignment and other statement types
1094            let mut simple_cursor = child.walk();
1095            for simple_child in child.children(&mut simple_cursor) {
1096                if simple_child.kind() == "assignment"
1097                    && let Some(left) = simple_child.child_by_field_name("left")
1098                {
1099                    let target_text = source[left.start_byte()..left.end_byte()].trim();
1100                    if target_text == "__all__"
1101                        && let Some(right) = simple_child.child_by_field_name("right")
1102                    {
1103                        extract_string_list_from_list_node(&right, source, result);
1104                    }
1105                }
1106            }
1107        } else if child.kind() == "expression_statement" {
1108            // Fallback for older Python AST structures
1109            let mut stmt_cursor = child.walk();
1110            for stmt_child in child.children(&mut stmt_cursor) {
1111                if stmt_child.kind() == "assignment"
1112                    && let Some(left) = stmt_child.child_by_field_name("left")
1113                {
1114                    let target_text = source[left.start_byte()..left.end_byte()].trim();
1115                    if target_text == "__all__"
1116                        && let Some(right) = stmt_child.child_by_field_name("right")
1117                    {
1118                        extract_string_list_from_list_node(&right, source, result);
1119                    }
1120                }
1121            }
1122        }
1123    }
1124}
1125
1126/// Extract string literals from a Python list node.
1127fn extract_string_list_from_list_node(
1128    list_node: &tree_sitter::Node,
1129    source: &str,
1130    result: &mut Vec<String>,
1131) {
1132    let mut cursor = list_node.walk();
1133    for child in list_node.named_children(&mut cursor) {
1134        if child.kind() == "string" {
1135            let raw = source[child.start_byte()..child.end_byte()].trim();
1136            // Strip quotes: "name" -> name
1137            let unquoted = raw.trim_matches('"').trim_matches('\'').to_string();
1138            if !unquoted.is_empty() {
1139                result.push(unquoted);
1140            }
1141        }
1142    }
1143}
1144
1145#[cfg(test)]
1146mod tests {
1147    use super::*;
1148
1149    #[test]
1150    fn test_structural_graph_cache_warm_hit() {
1151        // Create temp dir and a test file
1152        let temp_dir = tempfile::tempdir().expect("tempdir");
1153        let test_file = tempfile::NamedTempFile::new_in(temp_dir.path()).expect("tempfile");
1154        std::fs::write(&test_file.path(), "fn main() {}").expect("write");
1155
1156        // Walk the directory to get entries
1157        let entries = walk_directory(temp_dir.path(), None).expect("walk");
1158
1159        // Set up a cache and params
1160        let cache = StructuralGraphCache::new(10);
1161        let progress = Arc::new(AtomicUsize::new(0));
1162        let ct = CancellationToken::new();
1163        let config = FocusedAnalysisConfig {
1164            focus: "main".to_string(),
1165            match_mode: SymbolMatchMode::Exact,
1166            follow_depth: 2,
1167            max_depth: None,
1168            ast_recursion_limit: None,
1169            use_summary: false,
1170            impl_only: None,
1171            def_use: false,
1172            parse_timeout_micros: None,
1173        };
1174
1175        // Call 1 - should populate cache
1176        let _ = analyze_focused_with_progress_with_entries(
1177            temp_dir.path(),
1178            &config,
1179            &progress,
1180            &ct,
1181            &entries,
1182            Some(&cache),
1183        );
1184
1185        // Check cache was populated by computing the key and verifying it exists
1186        if let Some(key) = compute_cache_key(temp_dir.path(), &entries, &[]) {
1187            assert!(
1188                cache.get(&key).is_some(),
1189                "structural graph cache should be populated after first call"
1190            );
1191
1192            // Call 2 - should hit the L1 cache (won't build again)
1193            let progress2 = Arc::new(AtomicUsize::new(0));
1194            let _ = analyze_focused_with_progress_with_entries(
1195                temp_dir.path(),
1196                &config,
1197                &progress2,
1198                &ct,
1199                &entries,
1200                Some(&cache),
1201            );
1202
1203            // Cache should still have exactly one entry
1204            assert!(
1205                cache.get(&key).is_some(),
1206                "structural graph cache hit should work on second call"
1207            );
1208        }
1209    }
1210}