Skip to main content

reflex/
dependency.rs

1//! Dependency tracking and graph analysis
2//!
3//! This module provides functionality for tracking file dependencies (imports/includes)
4//! and analyzing the dependency graph of a codebase.
5//!
6//! # Architecture
7//!
8//! The system uses a "depth-1 storage" approach:
9//! - Only direct dependencies are stored in the database
10//! - Deeper relationships are computed on-demand via graph traversal
11//! - This provides O(n) storage while enabling any-depth queries
12//!
13//! # Example
14//!
15//! ```no_run
16//! use reflex::dependency::DependencyIndex;
17//! use reflex::cache::CacheManager;
18//!
19//! let cache = CacheManager::new(".");
20//! let deps = DependencyIndex::new(cache);
21//!
22//! // Get direct dependencies of a file
23//! let file_deps = deps.get_dependencies(42)?;
24//!
25//! // Get files that import this file (reverse lookup)
26//! let dependents = deps.get_dependents(42)?;
27//!
28//! // Traverse dependency graph to depth 3
29//! let transitive = deps.get_transitive_deps(42, 3)?;
30//! # Ok::<(), anyhow::Error>(())
31//! ```
32
33use anyhow::{Context, Result};
34use rusqlite::Connection;
35use std::collections::{HashMap, HashSet, VecDeque};
36use std::path::PathBuf;
37
38use crate::cache::CacheManager;
39use crate::models::{Dependency, DependencyInfo, ImportType};
40
41/// In-memory `path → file_id` lookup for the indexer's dependency phase.
42///
43/// Built once from the `files` table after the files transaction commits, then
44/// answers the same question as [`DependencyIndex::get_file_id_by_path`] without
45/// a SQLite connection per call: exact match first, then a unique suffix match.
46/// Before 2.0.0 every miss ran `SELECT … WHERE path LIKE '%' || ?`, a full scan
47/// of the `files` table, and a Kubernetes-sized tree spent ~500 s of a ~530 s
48/// index in that loop.
49///
50/// The suffix match is ASCII-case-insensitive, like SQLite `LIKE`, but `_` and
51/// `%` in the probe are literal. `LIKE` treated them as wildcards, so a probe of
52/// `foo_bar.h` also matched `fooXbar.h` and reported a false ambiguity; a
53/// filename's underscore is a character, not a pattern.
54pub struct PathResolver {
55    /// `path → id`, case-sensitive, the `path = ?` fast path.
56    exact: HashMap<String, i64>,
57    /// `(ASCII-lowercased, byte-reversed path, id)`, sorted by key, so every path
58    /// ending in a probe is a contiguous run found by binary search.
59    suffix: Vec<(Vec<u8>, i64)>,
60}
61
62impl PathResolver {
63    /// Load every `(id, path)` row from `files`.
64    pub fn from_conn(conn: &Connection) -> Result<Self> {
65        let mut stmt = conn
66            .prepare("SELECT id, path FROM files")
67            .context("Failed to prepare files query")?;
68        let rows = stmt
69            .query_map([], |row| {
70                Ok((row.get::<_, i64>(0)?, row.get::<_, String>(1)?))
71            })
72            .context("Failed to read files table")?
73            .collect::<std::result::Result<Vec<_>, _>>()
74            .context("Failed to read files rows")?;
75        Ok(Self::from_rows(rows))
76    }
77
78    /// Build from `(id, path)` pairs.
79    pub fn from_rows(rows: impl IntoIterator<Item = (i64, String)>) -> Self {
80        let rows = rows.into_iter();
81        let (lower, _) = rows.size_hint();
82        let mut exact = HashMap::with_capacity(lower);
83        let mut suffix = Vec::with_capacity(lower);
84        for (id, path) in rows {
85            suffix.push((Self::suffix_key(&path), id));
86            exact.insert(path, id);
87        }
88        suffix.sort_unstable();
89        Self { exact, suffix }
90    }
91
92    /// Number of paths known to the resolver.
93    pub fn len(&self) -> usize {
94        self.exact.len()
95    }
96
97    /// Whether the resolver knows no paths.
98    pub fn is_empty(&self) -> bool {
99        self.exact.is_empty()
100    }
101
102    fn suffix_key(path: &str) -> Vec<u8> {
103        path.bytes().rev().map(|b| b.to_ascii_lowercase()).collect()
104    }
105
106    /// Add `path` with `id` (replacing the id a known path had).
107    pub fn insert(&mut self, id: i64, path: &str) {
108        if let Some(old) = self.exact.insert(path.to_string(), id) {
109            self.remove_suffix(path, old);
110        }
111        let entry = (Self::suffix_key(path), id);
112        let at = self.suffix.partition_point(|e| *e < entry);
113        self.suffix.insert(at, entry);
114    }
115
116    /// Forget `path`.
117    pub fn remove(&mut self, path: &str) {
118        if let Some(id) = self.exact.remove(path) {
119            self.remove_suffix(path, id);
120        }
121    }
122
123    fn remove_suffix(&mut self, path: &str, id: i64) {
124        let entry = (Self::suffix_key(path), id);
125        if let Ok(at) = self.suffix.binary_search(&entry) {
126            self.suffix.remove(at);
127        }
128    }
129
130    /// The id of exactly `path` (after `normalize_path_for_lookup`), no suffix match.
131    pub fn get_exact(&self, path: &str) -> Option<i64> {
132        self.exact.get(&normalize_path_for_lookup(path)).copied()
133    }
134
135    /// Same contract as [`DependencyIndex::get_file_id_by_path`]: `Ok(Some)` on an
136    /// exact or unique-suffix match, `Ok(None)` on no match, `Err` when the suffix
137    /// is ambiguous.
138    pub fn get_file_id_by_path(&self, path: &str) -> Result<Option<i64>> {
139        let normalized = normalize_path_for_lookup(path);
140        if let Some(&id) = self.exact.get(&normalized) {
141            return Ok(Some(id));
142        }
143
144        // The whole path or a suffix of whole segments, ASCII case-insensitive:
145        // `a.h` matches `include/a.h`, not `lib/xa.h`
146        let probe = Self::suffix_key(&normalized);
147        let start = self
148            .suffix
149            .partition_point(|(key, _)| key.as_slice() < probe.as_slice());
150        let mut matches = self.suffix[start..]
151            .iter()
152            .take_while(|(key, _)| key.starts_with(&probe))
153            .filter(|(key, _)| key.len() == probe.len() || key[probe.len()] == b'/');
154        match (matches.next(), matches.next()) {
155            (None, _) => Ok(None),
156            (Some((_, id)), None) => Ok(Some(*id)),
157            (Some(_), Some(_)) => anyhow::bail!(
158                "Ambiguous path '{}' matches multiple files\n\nPlease be more specific.",
159                path
160            ),
161        }
162    }
163}
164
165/// Writes dependency and export rows on a connection inside a transaction the
166/// caller holds (the index run commits `files`, dependency and export rows once).
167///
168/// Statements are prepared once and reused. Until 2.0.0 the indexer opened a
169/// fresh connection for each lookup, each per-file `DELETE` and each per-file
170/// insert batch, committing (and fsyncing) twice per file and once per export row.
171pub struct DependencyWriter<'c> {
172    tx: &'c Connection,
173    deps: usize,
174    exports: usize,
175}
176
177impl<'c> DependencyWriter<'c> {
178    const INSERT_DEPENDENCY: &'static str = "INSERT INTO file_dependencies \
179         (file_id, imported_path, resolved_file_id, import_type, line_number, imported_symbols, \
180          resolved_package, resolved_member) \
181         VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
182    const INSERT_EXPORT: &'static str = "INSERT INTO file_exports \
183         (file_id, exported_symbol, source_path, resolved_source_id, line_number) \
184         VALUES (?, ?, ?, ?, ?)";
185
186    /// Write on `conn`, inside a transaction the caller holds.
187    pub fn new(conn: &'c Connection) -> Self {
188        Self {
189            tx: conn,
190            deps: 0,
191            exports: 0,
192        }
193    }
194
195    /// Drop every dependency row of `file_id`, then insert `deps`.
196    ///
197    /// Equivalent to `clear_dependencies` followed by `batch_insert_dependencies`.
198    pub fn replace_dependencies(&mut self, file_id: i64, deps: &[Dependency]) -> Result<()> {
199        self.tx
200            .prepare_cached("DELETE FROM file_dependencies WHERE file_id = ?")?
201            .execute([file_id])?;
202        if deps.is_empty() {
203            return Ok(());
204        }
205        let mut stmt = self.tx.prepare_cached(Self::INSERT_DEPENDENCY)?;
206        for dep in deps {
207            let symbols_json = dep
208                .imported_symbols
209                .as_ref()
210                .map(|syms| serde_json::to_string(syms).unwrap_or_else(|_| "[]".to_string()));
211            stmt.execute(rusqlite::params![
212                dep.file_id,
213                dep.imported_path,
214                dep.resolved_file_id,
215                import_type_str(&dep.import_type),
216                dep.line_number as i64,
217                symbols_json,
218                dep.resolved_package,
219                dep.resolved_member,
220            ])?;
221        }
222        self.deps += deps.len();
223        Ok(())
224    }
225
226    /// Drop every package membership of `file_id`, then record `members`
227    /// (`(package key, member)`; member `""` for a whole-directory package).
228    pub fn replace_members(&mut self, file_id: i64, members: &[(String, String)]) -> Result<()> {
229        self.tx
230            .prepare_cached("DELETE FROM package_members WHERE file_id = ?")?
231            .execute([file_id])?;
232        let mut stmt = self.tx.prepare_cached(
233            "INSERT OR IGNORE INTO package_members (package, member, file_id) VALUES (?, ?, ?)",
234        )?;
235        for (package, member) in members {
236            stmt.execute(rusqlite::params![package, member, file_id])?;
237        }
238        Ok(())
239    }
240
241    /// Drop every dependency, export and package-membership row (a full build
242    /// writes them all again).
243    pub fn clear_all(&mut self) -> Result<()> {
244        self.tx.execute_batch(
245            "DELETE FROM file_dependencies;
246             DELETE FROM file_exports;
247             DELETE FROM package_members;",
248        )?;
249        Ok(())
250    }
251
252    /// Drop every export row of `file_id` (exports have no key to replace them by).
253    pub fn clear_exports(&mut self, file_id: i64) -> Result<()> {
254        self.tx
255            .prepare_cached("DELETE FROM file_exports WHERE file_id = ?")?
256            .execute([file_id])?;
257        Ok(())
258    }
259
260    /// Insert one export row (same columns as [`DependencyIndex::insert_export`]).
261    pub fn insert_export(
262        &mut self,
263        file_id: i64,
264        exported_symbol: Option<&str>,
265        source_path: &str,
266        resolved_source_id: Option<i64>,
267        line_number: usize,
268    ) -> Result<()> {
269        self.tx
270            .prepare_cached(Self::INSERT_EXPORT)?
271            .execute(rusqlite::params![
272                file_id,
273                exported_symbol,
274                source_path,
275                resolved_source_id,
276                line_number as i64,
277            ])?;
278        self.exports += 1;
279        Ok(())
280    }
281
282    /// `(dependencies, exports)` written so far.
283    pub fn counts(&self) -> (usize, usize) {
284        (self.deps, self.exports)
285    }
286}
287
288fn import_type_str(import_type: &ImportType) -> &'static str {
289    match import_type {
290        ImportType::Internal => "internal",
291        ImportType::External => "external",
292        ImportType::Stdlib => "stdlib",
293        ImportType::ModDecl => "mod_decl",
294    }
295}
296
297/// Below this many internal imports a language's resolution rate is not reported.
298pub const LOW_RESOLUTION_MIN_IMPORTS: usize = 100;
299
300/// A language whose resolved share of internal imports is below this gets a warning.
301pub const LOW_RESOLUTION_RATE: f64 = 0.5;
302
303/// Internal imports of one language and how many resolve to an indexed file.
304#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
305pub struct LanguageResolution {
306    /// The `files.language` name (`Go`, `CSharp`, …).
307    pub language: String,
308    pub internal: usize,
309    pub resolved: usize,
310}
311
312impl LanguageResolution {
313    pub fn rate(&self) -> f64 {
314        if self.internal == 0 {
315            1.0
316        } else {
317            self.resolved as f64 / self.internal as f64
318        }
319    }
320
321    pub fn is_low(&self) -> bool {
322        self.internal >= LOW_RESOLUTION_MIN_IMPORTS && self.rate() < LOW_RESOLUTION_RATE
323    }
324
325    pub fn warning(&self) -> String {
326        let name = match self.language.as_str() {
327            "CSharp" => "C#",
328            "Cpp" => "C++",
329            other => other,
330        };
331        format!(
332            "{name}: {} of {} internal imports ({:.1}%) resolve to indexed files; \
333             islands, unused files, hotspots, cycles and dependents for {name} files are incomplete",
334            self.resolved,
335            self.internal,
336            self.rate() * 100.0
337        )
338    }
339}
340
341/// Manages dependency storage and graph operations
342pub struct DependencyIndex {
343    cache: Option<CacheManager>,
344    db_path: PathBuf,
345}
346
347impl DependencyIndex {
348    /// Create a new dependency index for the given cache
349    pub fn new(cache: CacheManager) -> Self {
350        let db_path = cache.path().join("meta.db");
351        Self {
352            cache: Some(cache),
353            db_path,
354        }
355    }
356
357    /// Create a dependency index pointing directly at a database file.
358    ///
359    /// Used by Pulse to run analysis against snapshot databases.
360    pub fn from_db_path(db_path: impl Into<PathBuf>) -> Self {
361        Self {
362            cache: None,
363            db_path: db_path.into(),
364        }
365    }
366
367    /// Get a reference to the cache manager.
368    ///
369    /// Panics if this index was created via `from_db_path()`.
370    pub fn get_cache(&self) -> &CacheManager {
371        self.cache
372            .as_ref()
373            .expect("DependencyIndex created with from_db_path has no CacheManager")
374    }
375
376    /// Open a database connection to the backing store.
377    fn open_conn(&self) -> Result<Connection> {
378        crate::cache::open_meta_db(&self.db_path).context("Failed to open database")
379    }
380
381    /// Insert a dependency into the database
382    ///
383    /// # Arguments
384    ///
385    /// * `file_id` - Source file ID
386    /// * `imported_path` - Import path as written in source
387    /// * `resolved_file_id` - Resolved target file ID (None if external/stdlib)
388    /// * `import_type` - Type of import (internal/external/stdlib)
389    /// * `line_number` - Line where import appears
390    /// * `imported_symbols` - Optional list of imported symbols
391    pub fn insert_dependency(
392        &self,
393        file_id: i64,
394        imported_path: String,
395        resolved_file_id: Option<i64>,
396        import_type: ImportType,
397        line_number: usize,
398        imported_symbols: Option<Vec<String>>,
399    ) -> Result<()> {
400        let conn = self.open_conn()?;
401
402        let import_type_str = match import_type {
403            ImportType::Internal => "internal",
404            ImportType::External => "external",
405            ImportType::Stdlib => "stdlib",
406            ImportType::ModDecl => "mod_decl",
407        };
408
409        let symbols_json = imported_symbols
410            .as_ref()
411            .map(|syms| serde_json::to_string(syms).unwrap_or_else(|_| "[]".to_string()));
412
413        conn.execute(
414            "INSERT INTO file_dependencies (file_id, imported_path, resolved_file_id, import_type, line_number, imported_symbols)
415             VALUES (?, ?, ?, ?, ?, ?)",
416            rusqlite::params![
417                file_id,
418                imported_path,
419                resolved_file_id,
420                import_type_str,
421                line_number as i64,
422                symbols_json,
423            ],
424        )?;
425
426        Ok(())
427    }
428
429    /// Insert an export into the database
430    ///
431    /// # Arguments
432    ///
433    /// * `file_id` - Source file ID containing the export statement
434    /// * `exported_symbol` - Symbol name being exported (None for wildcard exports)
435    /// * `source_path` - Path where the symbol is re-exported from
436    /// * `resolved_source_id` - Resolved target file ID (None if unresolved)
437    /// * `line_number` - Line where export appears
438    pub fn insert_export(
439        &self,
440        file_id: i64,
441        exported_symbol: Option<String>,
442        source_path: String,
443        resolved_source_id: Option<i64>,
444        line_number: usize,
445    ) -> Result<()> {
446        let conn = self.open_conn()?;
447
448        conn.execute(
449            "INSERT INTO file_exports (file_id, exported_symbol, source_path, resolved_source_id, line_number)
450             VALUES (?, ?, ?, ?, ?)",
451            rusqlite::params![
452                file_id,
453                exported_symbol,
454                source_path,
455                resolved_source_id,
456                line_number as i64,
457            ],
458        )?;
459
460        Ok(())
461    }
462
463    /// Batch insert multiple dependencies in a single transaction
464    ///
465    /// More efficient than individual inserts for bulk operations.
466    pub fn batch_insert_dependencies(&self, dependencies: &[Dependency]) -> Result<()> {
467        if dependencies.is_empty() {
468            return Ok(());
469        }
470
471        let mut conn = self.open_conn()?;
472
473        let tx = conn.transaction()?;
474
475        for dep in dependencies {
476            let import_type_str = match dep.import_type {
477                ImportType::Internal => "internal",
478                ImportType::External => "external",
479                ImportType::Stdlib => "stdlib",
480                ImportType::ModDecl => "mod_decl",
481            };
482
483            let symbols_json = dep
484                .imported_symbols
485                .as_ref()
486                .map(|syms| serde_json::to_string(syms).unwrap_or_else(|_| "[]".to_string()));
487
488            tx.execute(
489                DependencyWriter::INSERT_DEPENDENCY,
490                rusqlite::params![
491                    dep.file_id,
492                    dep.imported_path,
493                    dep.resolved_file_id,
494                    import_type_str,
495                    dep.line_number as i64,
496                    symbols_json,
497                    dep.resolved_package,
498                    dep.resolved_member,
499                ],
500            )?;
501        }
502
503        tx.commit()?;
504        log::debug!("Batch inserted {} dependencies", dependencies.len());
505        Ok(())
506    }
507
508    /// Get all direct dependencies for a file
509    ///
510    /// Returns a list of files/modules that this file imports.
511    pub fn get_dependencies(&self, file_id: i64) -> Result<Vec<Dependency>> {
512        let conn = self.open_conn()?;
513
514        let mut stmt = conn.prepare(
515            "SELECT file_id, imported_path, resolved_file_id, import_type, line_number, imported_symbols,
516                    resolved_package, resolved_member
517             FROM file_dependencies
518             WHERE file_id = ?
519             ORDER BY line_number",
520        )?;
521
522        let deps = stmt
523            .query_map([file_id], |row| {
524                let import_type_str: String = row.get(3)?;
525                let import_type = match import_type_str.as_str() {
526                    "internal" => ImportType::Internal,
527                    "external" => ImportType::External,
528                    "stdlib" => ImportType::Stdlib,
529                    "mod_decl" => ImportType::ModDecl,
530                    _ => ImportType::External,
531                };
532
533                let symbols_json: Option<String> = row.get(5)?;
534                let imported_symbols =
535                    symbols_json.and_then(|json| serde_json::from_str(&json).ok());
536
537                Ok(Dependency {
538                    file_id: row.get(0)?,
539                    imported_path: row.get(1)?,
540                    resolved_file_id: row.get(2)?,
541                    resolved_package: row.get(6)?,
542                    resolved_member: row.get(7)?,
543                    import_type,
544                    line_number: row.get::<_, i64>(4)? as usize,
545                    imported_symbols,
546                })
547            })?
548            .collect::<Result<Vec<_>, _>>()?;
549
550        Ok(deps)
551    }
552
553    /// Get all files that depend on this file (reverse lookup)
554    ///
555    /// Returns a list of file IDs that import this file.
556    /// Uses `resolved_file_id` column for instant SQL lookup (sub-10ms).
557    pub fn get_dependents(&self, file_id: i64) -> Result<Vec<i64>> {
558        let conn = self.open_conn()?;
559
560        // Pure SQL query on resolved_file_id (instant). Walk order: a full build
561        // numbers files in walk order, and ids are stable across updates.
562        let mut stmt = conn.prepare(
563            "SELECT f.id
564             FROM files f
565             WHERE f.id IN (SELECT src FROM import_edges WHERE dst = ?)
566             ORDER BY f.walk_seq",
567        )?;
568
569        let dependents: Vec<i64> = stmt
570            .query_map([file_id], |row| row.get(0))?
571            .collect::<Result<Vec<_>, _>>()?;
572
573        Ok(dependents)
574    }
575
576    /// The files `file_id` imports, each once, in (import row, target walk) order.
577    fn direct_targets(&self, file_id: i64) -> Result<Vec<i64>> {
578        let conn = self.open_conn()?;
579        let mut stmt = conn.prepare_cached(
580            "SELECT e.dst FROM import_edges e JOIN files t ON t.id = e.dst
581             WHERE e.src = ? ORDER BY e.dep_id, t.walk_seq",
582        )?;
583        let mut seen = HashSet::new();
584        let targets = stmt
585            .query_map([file_id], |row| row.get::<_, i64>(0))?
586            .collect::<Result<Vec<_>, _>>()?;
587        Ok(targets.into_iter().filter(|id| seen.insert(*id)).collect())
588    }
589
590    /// For each import of `file_id`, keyed by `(line, imported path)`, the paths of
591    /// the files it reaches: the import's own target first, then in walk order.
592    fn package_targets(&self, file_id: i64) -> Result<HashMap<(usize, String), Vec<String>>> {
593        let conn = self.open_conn()?;
594        let mut stmt = conn.prepare(
595            "SELECT d.line_number, d.imported_path, t.path
596             FROM import_edges e
597             JOIN file_dependencies d ON d.id = e.dep_id
598             JOIN files t ON t.id = e.dst
599             WHERE e.src = ?
600             ORDER BY d.id, t.id != COALESCE(d.resolved_file_id, -1), t.path",
601        )?;
602        let mut out: HashMap<(usize, String), Vec<String>> = HashMap::new();
603        let rows = stmt.query_map([file_id], |row| {
604            Ok((
605                row.get::<_, i64>(0)? as usize,
606                row.get::<_, String>(1)?,
607                row.get::<_, String>(2)?,
608            ))
609        })?;
610        for row in rows {
611            let (line, imported, path) = row?;
612            out.entry((line, imported)).or_default().push(path);
613        }
614        Ok(out)
615    }
616
617    /// Get dependencies as DependencyInfo (for API output)
618    ///
619    /// Converts internal Dependency records to simplified DependencyInfo
620    /// suitable for JSON output.
621    pub fn get_dependencies_info(&self, file_id: i64) -> Result<Vec<DependencyInfo>> {
622        let deps = self.get_dependencies(file_id)?;
623
624        let mut packages = self.package_targets(file_id)?;
625        let dep_infos = deps
626            .into_iter()
627            .map(|dep| {
628                // A package import, or one that reaches several files (a Python
629                // package and its submodules), lists the files it reaches
630                let reached = packages.remove(&(dep.line_number, dep.imported_path.clone()));
631                let resolved_paths = if dep.resolved_package.is_some() {
632                    Some(reached.unwrap_or_default())
633                } else {
634                    reached.filter(|paths| paths.len() > 1)
635                };
636                // Try to get the resolved path (all deps are internal now)
637                let path = if let Some(resolved_id) = dep.resolved_file_id {
638                    // Try to get the actual file path
639                    self.get_file_path(resolved_id).unwrap_or(dep.imported_path)
640                } else {
641                    dep.imported_path
642                };
643
644                DependencyInfo {
645                    path,
646                    line: Some(dep.line_number),
647                    symbols: dep.imported_symbols,
648                    resolved_paths,
649                }
650            })
651            .collect();
652
653        Ok(dep_infos)
654    }
655
656    /// Get transitive dependencies up to a given depth
657    ///
658    /// Traverses the dependency graph using BFS to find all dependencies
659    /// reachable within the specified depth.
660    /// Uses `resolved_file_id` column for instant SQL lookup (sub-100ms).
661    ///
662    /// # Arguments
663    ///
664    /// * `file_id` - Starting file ID
665    /// * `max_depth` - Maximum traversal depth (0 = only direct deps)
666    ///
667    /// # Returns
668    ///
669    /// HashMap mapping file_id to depth (distance from start file)
670    pub fn get_transitive_deps(
671        &self,
672        file_id: i64,
673        max_depth: usize,
674    ) -> Result<HashMap<i64, usize>> {
675        let mut visited = HashMap::new();
676        let mut queue = VecDeque::new();
677
678        // Start with the initial file at depth 0
679        queue.push_back((file_id, 0));
680        visited.insert(file_id, 0);
681
682        while let Some((current_id, depth)) = queue.pop_front() {
683            if depth >= max_depth {
684                continue;
685            }
686
687            for resolved_id in self.direct_targets(current_id)? {
688                // Only visit if we haven't seen it or found a shorter path
689                if let std::collections::hash_map::Entry::Vacant(e) = visited.entry(resolved_id) {
690                    e.insert(depth + 1);
691                    queue.push_back((resolved_id, depth + 1));
692                }
693            }
694        }
695
696        Ok(visited)
697    }
698
699    /// Detect circular dependencies in the entire codebase
700    ///
701    /// Uses depth-first search to find cycles in the dependency graph.
702    /// Uses `resolved_file_id` column for instant SQL lookup (sub-100ms).
703    ///
704    /// Returns a list of cycle paths, where each cycle is represented as
705    /// a vector of file IDs forming the cycle.
706    pub fn detect_circular_dependencies(&self) -> Result<Vec<Vec<i64>>> {
707        let conn = self.open_conn()?;
708
709        // Build in-memory dependency graph using resolved_file_id (instant)
710        let mut graph: HashMap<i64, Vec<i64>> = HashMap::new();
711
712        // Exclude mod_decl edges: `mod foo;` is parent→child ownership, not a usage dependency.
713        // Including them creates false positives when a child module uses `use crate::` (REF-88).
714        // Each file's edges in row order (= extraction order).
715        for (file_id, target_id) in load_edges(&conn, EdgeOrder::ImporterId, false)? {
716            graph.entry(file_id).or_default().push(target_id);
717        }
718
719        // Get all file IDs for traversal
720        let all_files = self.get_all_file_ids()?;
721
722        let mut visited = HashSet::new();
723        let mut rec_stack = HashSet::new();
724        let mut path = Vec::new();
725        let mut cycles = Vec::new();
726
727        for file_id in all_files {
728            if !visited.contains(&file_id) {
729                self.dfs_cycle_detect(
730                    file_id,
731                    &graph,
732                    &mut visited,
733                    &mut rec_stack,
734                    &mut path,
735                    &mut cycles,
736                )?;
737            }
738        }
739
740        Ok(cycles)
741    }
742
743    /// DFS for cycle detection over the pre-built graph. Iterative (a real Go or
744    /// Java graph is thousands of files deep), visiting in the order the recursive
745    /// version did, so the cycles come out the same.
746    fn dfs_cycle_detect(
747        &self,
748        start: i64,
749        graph: &HashMap<i64, Vec<i64>>,
750        visited: &mut HashSet<i64>,
751        rec_stack: &mut HashSet<i64>,
752        path: &mut Vec<i64>,
753        cycles: &mut Vec<Vec<i64>>,
754    ) -> Result<()> {
755        const NONE: &[i64] = &[];
756        // (node, index of its next neighbour)
757        let mut stack: Vec<(i64, usize)> = vec![(start, 0)];
758        visited.insert(start);
759        rec_stack.insert(start);
760        path.push(start);
761
762        while let Some((node, next)) = stack.last_mut() {
763            let neighbors = graph.get(node).map_or(NONE, Vec::as_slice);
764            if let Some(&target_id) = neighbors.get(*next) {
765                *next += 1;
766                if !visited.contains(&target_id) {
767                    visited.insert(target_id);
768                    rec_stack.insert(target_id);
769                    path.push(target_id);
770                    stack.push((target_id, 0));
771                } else if rec_stack.contains(&target_id) {
772                    // Found a cycle! Extract it from path
773                    if let Some(cycle_start) = path.iter().position(|&id| id == target_id) {
774                        cycles.push(path[cycle_start..].to_vec());
775                    }
776                }
777            } else {
778                let node = *node;
779                stack.pop();
780                path.pop();
781                rec_stack.remove(&node);
782            }
783        }
784
785        Ok(())
786    }
787
788    /// Get file paths for a list of file IDs
789    ///
790    /// Useful for converting file ID results to human-readable paths.
791    pub fn get_file_paths(&self, file_ids: &[i64]) -> Result<HashMap<i64, String>> {
792        let conn = self.open_conn()?;
793
794        let mut paths = HashMap::new();
795
796        for &file_id in file_ids {
797            if let Ok(path) =
798                conn.query_row("SELECT path FROM files WHERE id = ?", [file_id], |row| {
799                    row.get::<_, String>(0)
800                })
801            {
802                paths.insert(file_id, path);
803            }
804        }
805
806        Ok(paths)
807    }
808
809    /// `id → 1-based position in walk order` for the given ids: the id a full
810    /// build gives each file (it numbers files 1..N in walk order). Outputs that
811    /// sort or print ids use this, so they do not depend on update history.
812    pub fn walk_ranks(&self, file_ids: &[i64]) -> Result<HashMap<i64, i64>> {
813        let conn = self.open_conn()?;
814        let wanted: HashSet<i64> = file_ids.iter().copied().collect();
815        let mut stmt = conn.prepare("SELECT id FROM files ORDER BY walk_seq")?;
816        let mut ranks = HashMap::with_capacity(wanted.len());
817        let ids = stmt.query_map([], |row| row.get::<_, i64>(0))?;
818        for (i, id) in ids.enumerate() {
819            let id = id?;
820            if wanted.contains(&id) {
821                ranks.insert(id, i as i64 + 1);
822            }
823        }
824        Ok(ranks)
825    }
826
827    /// Get file path for a single file ID
828    fn get_file_path(&self, file_id: i64) -> Result<String> {
829        let conn = self.open_conn()?;
830
831        let path = conn.query_row("SELECT path FROM files WHERE id = ?", [file_id], |row| {
832            row.get::<_, String>(0)
833        })?;
834
835        Ok(path)
836    }
837
838    /// Get all file IDs in the database, in path order (the order the path index
839    /// has always returned them in; graph traversals start from them in this order)
840    fn get_all_file_ids(&self) -> Result<Vec<i64>> {
841        let conn = self.open_conn()?;
842
843        let mut stmt = conn.prepare(&format!(
844            "SELECT id FROM files WHERE {CODE_FILES} ORDER BY path"
845        ))?;
846        let file_ids = stmt
847            .query_map([], |row| row.get(0))?
848            .collect::<Result<Vec<_>, _>>()?;
849
850        Ok(file_ids)
851    }
852
853    /// Find hotspots (most imported files)
854    ///
855    /// Returns a list of (file_id, count) tuples sorted by import count descending.
856    ///
857    /// Uses `resolved_file_id` column for instant SQL aggregation (sub-100ms).
858    ///
859    /// # Arguments
860    ///
861    /// * `limit` - Maximum number of hotspots to return (None = all)
862    /// * `min_dependents` - Minimum number of imports required to be a hotspot (default: 2)
863    pub fn find_hotspots(
864        &self,
865        limit: Option<usize>,
866        min_dependents: usize,
867    ) -> Result<Vec<(i64, usize)>> {
868        let conn = self.open_conn()?;
869
870        // Distinct importers per file (a file importing a target twice counts once).
871        // Ties in walk order, which is the id order a full build produces.
872        let mut stmt = conn.prepare(
873            "SELECT e.dst, COUNT(DISTINCT e.src) as count, MIN(f.walk_seq) AS ws
874             FROM import_edges e
875             JOIN files f ON f.id = e.dst
876             GROUP BY e.dst
877             ORDER BY count DESC, ws",
878        )?;
879
880        // Get all hotspots and filter by minimum dependent count
881        let mut hotspots: Vec<(i64, usize)> = stmt
882            .query_map([], |row| {
883                Ok((row.get::<_, i64>(0)?, row.get::<_, i64>(1)? as usize))
884            })?
885            .collect::<Result<Vec<_>, _>>()?
886            .into_iter()
887            .filter(|(_, count)| *count >= min_dependents)
888            .collect();
889
890        // Apply limit if specified
891        if let Some(lim) = limit {
892            hotspots.truncate(lim);
893        }
894
895        Ok(hotspots)
896    }
897
898    /// Find unused files (files with no incoming dependencies)
899    ///
900    /// Files that are never imported are potential candidates for deletion.
901    /// Uses `resolved_file_id` column for instant SQL lookup (sub-10ms).
902    ///
903    /// **Barrel Export Resolution**: This function now follows barrel export chains
904    /// to detect files that are indirectly imported via re-exports. For example:
905    /// - `WithLabel.vue` exported by `packages/ui/components/index.ts`
906    /// - App imports `@packages/ui/components` (resolves to index.ts)
907    /// - This function follows the export chain and marks `WithLabel.vue` as used
908    pub fn find_unused_files(&self) -> Result<Vec<i64>> {
909        let conn = self.open_conn()?;
910
911        // Build set of used files by following barrel export chains
912        let mut used_files = HashSet::new();
913
914        // Step 1: Get all files directly referenced in resolved_file_id
915        let mut stmt = conn.prepare("SELECT DISTINCT dst FROM import_edges ORDER BY dst")?;
916
917        let direct_imports: Vec<i64> = stmt
918            .query_map([], |row| row.get(0))?
919            .collect::<Result<Vec<_>, _>>()?;
920
921        used_files.extend(&direct_imports);
922
923        // Step 2: For each direct import, follow barrel export chains
924        for file_id in direct_imports {
925            // Resolve through barrel exports to find all indirectly used files
926            let barrel_chain = self.resolve_through_barrel_exports(file_id)?;
927            used_files.extend(barrel_chain);
928        }
929
930        // Step 3: Get all files NOT in the used set, excluding known entry points.
931        // Entry points are always reachable by definition (they are the roots of the dep graph).
932        let mut stmt = conn.prepare(&format!(
933            "SELECT id, path FROM files WHERE {CODE_FILES} ORDER BY walk_seq"
934        ))?;
935        let all_files: Vec<(i64, String)> = stmt
936            .query_map([], |row| Ok((row.get(0)?, row.get(1)?)))?
937            .collect::<Result<Vec<_>, _>>()?;
938
939        // A package whose member is used or an entry point is used as a whole
940        // (`cmd/x/flags.go` beside `cmd/x/main.go`)
941        let entry_points: HashSet<i64> = all_files
942            .iter()
943            .filter(|(_, path)| is_entry_point(path))
944            .map(|(id, _)| *id)
945            .collect();
946        for group in sibling_groups(&conn)? {
947            if group
948                .iter()
949                .any(|id| used_files.contains(id) || entry_points.contains(id))
950            {
951                used_files.extend(group);
952            }
953        }
954
955        let unused: Vec<i64> = all_files
956            .into_iter()
957            .filter(|(id, path)| !used_files.contains(id) && !is_entry_point(path))
958            .map(|(id, _)| id)
959            .collect();
960
961        Ok(unused)
962    }
963
964    /// Resolve barrel export chains to find all files transitively exported from a given file
965    ///
966    /// Given a barrel file (e.g., `index.ts` that re-exports from other files), this function
967    /// follows the export chain to find all source files that are transitively exported.
968    ///
969    /// # Example
970    ///
971    /// If `packages/ui/components/index.ts` contains:
972    /// ```typescript
973    /// export { default as WithLabel } from './WithLabel.vue';
974    /// export { default as Button } from './Button.vue';
975    /// ```
976    ///
977    /// Then calling this with the file_id of `index.ts` will return the file IDs of
978    /// `WithLabel.vue` and `Button.vue`.
979    ///
980    /// # Arguments
981    ///
982    /// * `barrel_file_id` - File ID of the barrel file to start from
983    ///
984    /// # Returns
985    ///
986    /// Vec of file IDs that are transitively exported (includes the barrel file itself)
987    pub fn resolve_through_barrel_exports(&self, barrel_file_id: i64) -> Result<Vec<i64>> {
988        let conn = self.open_conn()?;
989
990        let mut resolved_files = Vec::new();
991        let mut visited = HashSet::new();
992        let mut queue = VecDeque::new();
993
994        // Start with the barrel file itself
995        queue.push_back(barrel_file_id);
996        visited.insert(barrel_file_id);
997
998        while let Some(current_id) = queue.pop_front() {
999            resolved_files.push(current_id);
1000
1001            // Get all exports from this file
1002            let mut stmt = conn.prepare(
1003                "SELECT resolved_source_id
1004                 FROM file_exports
1005                 WHERE file_id = ? AND resolved_source_id IS NOT NULL",
1006            )?;
1007
1008            let exported_files: Vec<i64> = stmt
1009                .query_map([current_id], |row| row.get(0))?
1010                .collect::<Result<Vec<_>, _>>()?;
1011
1012            // Follow each exported file
1013            for exported_id in exported_files {
1014                if !visited.contains(&exported_id) {
1015                    visited.insert(exported_id);
1016                    queue.push_back(exported_id);
1017                }
1018            }
1019        }
1020
1021        Ok(resolved_files)
1022    }
1023
1024    /// Find disconnected components (islands) in the dependency graph
1025    ///
1026    /// An "island" is a connected component - a group of files that depend on each
1027    /// other (directly or transitively) but have no dependencies to files outside
1028    /// the group.
1029    ///
1030    /// This is useful for identifying:
1031    /// - Independent subsystems that could be extracted as separate modules
1032    /// - Unreachable code clusters that might be dead code
1033    /// - Microservice boundaries in a monolith
1034    ///
1035    /// Returns a list of islands, where each island is a vector of file IDs.
1036    /// Islands are sorted by size (largest first).
1037    pub fn find_islands(&self) -> Result<Vec<Vec<i64>>> {
1038        let conn = self.open_conn()?;
1039
1040        // Build undirected dependency graph (A imports B => edge A-B and B-A)
1041        let mut graph: HashMap<i64, Vec<i64>> = HashMap::new();
1042
1043        // Rows in (importer walk order, row order): the order a full build inserts
1044        // them in. Adjacency order decides each island's member order.
1045        // Build adjacency list (undirected) directly from resolved IDs
1046        for (file_id, target_id) in load_edges(&conn, EdgeOrder::ImporterWalk, true)? {
1047            // Add edge in both directions for undirected graph
1048            graph.entry(file_id).or_default().push(target_id);
1049            graph.entry(target_id).or_default().push(file_id);
1050        }
1051
1052        // Files of one package belong together even when none imports another
1053        for group in sibling_groups(&conn)? {
1054            for pair in group.windows(2) {
1055                graph.entry(pair[0]).or_default().push(pair[1]);
1056                graph.entry(pair[1]).or_default().push(pair[0]);
1057            }
1058        }
1059
1060        // Get all file IDs (including isolated files with no dependencies)
1061        let all_files = self.get_all_file_ids()?;
1062
1063        // Ensure all files are in the graph (even if they have no edges)
1064        for file_id in &all_files {
1065            graph.entry(*file_id).or_default();
1066        }
1067
1068        // Find connected components using DFS
1069        let mut visited = HashSet::new();
1070        let mut islands = Vec::new();
1071
1072        for &file_id in &all_files {
1073            if !visited.contains(&file_id) {
1074                let mut island = Vec::new();
1075                self.dfs_island(&file_id, &graph, &mut visited, &mut island);
1076                islands.push(island);
1077            }
1078        }
1079
1080        // Sort islands by size (largest first)
1081        islands.sort_by_key(|a: &Vec<_>| std::cmp::Reverse(a.len()));
1082
1083        log::info!("Found {} islands (connected components)", islands.len());
1084
1085        Ok(islands)
1086    }
1087
1088    /// DFS for finding connected components (islands). Iterative, in the
1089    /// preorder the recursive version produced.
1090    fn dfs_island(
1091        &self,
1092        start: &i64,
1093        graph: &HashMap<i64, Vec<i64>>,
1094        visited: &mut HashSet<i64>,
1095        island: &mut Vec<i64>,
1096    ) {
1097        const NONE: &[i64] = &[];
1098        visited.insert(*start);
1099        island.push(*start);
1100        let mut stack: Vec<(i64, usize)> = vec![(*start, 0)];
1101        while let Some((node, next)) = stack.last_mut() {
1102            let neighbors = graph.get(node).map_or(NONE, Vec::as_slice);
1103            match neighbors.get(*next) {
1104                Some(&neighbor) => {
1105                    *next += 1;
1106                    if visited.insert(neighbor) {
1107                        island.push(neighbor);
1108                        stack.push((neighbor, 0));
1109                    }
1110                }
1111                None => {
1112                    stack.pop();
1113                }
1114            }
1115        }
1116    }
1117
1118    /// Build a cache of imported_path → file_id mappings for efficient lookup
1119    ///
1120    /// This method queries all unique imported_path values from the database
1121    /// and resolves each one to a file_id using fuzzy matching. The resulting
1122    /// cache enables O(1) lookups instead of repeated database queries.
1123    ///
1124    /// This is used internally by graph analysis operations (hotspots, circular
1125    /// dependencies, reverse lookups, etc.) to avoid O(N*M*K) query complexity.
1126    ///
1127    /// # Performance
1128    ///
1129    /// Building the cache requires O(N*M) queries where:
1130    /// - N = number of unique imported_path values (~1,000-5,000)
1131    /// - M = average number of path variants tried per path (~10)
1132    ///
1133    /// However, this is done ONCE upfront, enabling O(1) lookups for all
1134    /// subsequent operations. Without caching, each operation would make
1135    /// 10,000-100,000+ queries.
1136    ///
1137    /// # Returns
1138    ///
1139    /// HashMap mapping imported_path to resolved file_id (only includes
1140    /// successfully resolved paths; external/unresolved paths are omitted)
1141    #[allow(dead_code)]
1142    fn build_resolution_cache(&self) -> Result<HashMap<String, i64>> {
1143        let conn = self.open_conn()?;
1144
1145        // Get all unique imported_path values (single query)
1146        let mut stmt = conn.prepare("SELECT DISTINCT imported_path FROM file_dependencies")?;
1147
1148        let imported_paths: Vec<String> = stmt
1149            .query_map([], |row| row.get(0))?
1150            .collect::<Result<Vec<_>, _>>()?;
1151
1152        let total_paths = imported_paths.len();
1153        log::info!(
1154            "Building resolution cache for {} unique imported paths",
1155            total_paths
1156        );
1157
1158        // Resolve each imported_path once
1159        let mut cache = HashMap::new();
1160
1161        for imported_path in imported_paths {
1162            if let Ok(Some(file_id)) = self.resolve_imported_path_to_file_id(&imported_path) {
1163                cache.insert(imported_path, file_id);
1164            }
1165        }
1166
1167        log::info!(
1168            "Resolution cache built: {} resolved, {} unresolved",
1169            cache.len(),
1170            total_paths - cache.len()
1171        );
1172
1173        Ok(cache)
1174    }
1175
1176    /// Clear all dependencies for a file (used during incremental reindexing)
1177    pub fn clear_dependencies(&self, file_id: i64) -> Result<()> {
1178        let conn = self.open_conn()?;
1179
1180        conn.execute("DELETE FROM file_dependencies WHERE file_id = ?", [file_id])?;
1181
1182        Ok(())
1183    }
1184
1185    /// Resolve an imported path to a file ID using fuzzy matching
1186    ///
1187    /// This method converts an import path (e.g., namespace, module path) to various
1188    /// file path variants and tries to find a matching file using fuzzy path matching.
1189    ///
1190    /// # Arguments
1191    ///
1192    /// * `imported_path` - The import path as stored in the database
1193    ///   (e.g., "Rcm\\Http\\Controllers\\Controller", "crate::models", etc.)
1194    ///
1195    /// # Returns
1196    ///
1197    /// `Some(file_id)` if exactly one matching file is found, `None` otherwise
1198    ///
1199    /// # Examples
1200    ///
1201    /// - `Rcm\\Http\\Controllers\\Controller` → finds `services/php/rcm-backend/app/Http/Controllers/Controller.php`
1202    /// - `crate::models` → finds `src/models.rs`
1203    pub fn resolve_imported_path_to_file_id(&self, imported_path: &str) -> Result<Option<i64>> {
1204        let path_variants = generate_path_variants(imported_path);
1205
1206        for variant in &path_variants {
1207            if let Ok(Some(file_id)) = self.get_file_id_by_path(variant) {
1208                log::trace!(
1209                    "Resolved '{}' → '{}' (file_id: {})",
1210                    imported_path,
1211                    variant,
1212                    file_id
1213                );
1214                return Ok(Some(file_id));
1215            }
1216        }
1217
1218        Ok(None)
1219    }
1220
1221    /// Get file ID by path with fuzzy matching support
1222    ///
1223    /// Supports various path formats:
1224    /// - Exact paths: `services/php/app/Http/Controllers/FooController.php`
1225    /// - Relative paths: `./services/php/app/Http/Controllers/FooController.php`
1226    /// - Path fragments: `Controllers/FooController.php` or `FooController.php`
1227    /// - Absolute paths: `/home/user/project/services/php/.../FooController.php`
1228    ///
1229    /// Returns None if no matches found.
1230    /// Returns error if multiple matches found (ambiguous path fragment).
1231    pub fn get_file_id_by_path(&self, path: &str) -> Result<Option<i64>> {
1232        let conn = self.open_conn()?;
1233
1234        // Normalize path: strip ./ prefix, ../ prefix, and convert absolute to relative
1235        let normalized_path = normalize_path_for_lookup(path);
1236
1237        // Try exact match first (fast path)
1238        match conn.query_row(
1239            "SELECT id FROM files WHERE path = ?",
1240            [&normalized_path],
1241            |row| row.get::<_, i64>(0),
1242        ) {
1243            Ok(id) => return Ok(Some(id)),
1244            Err(rusqlite::Error::QueryReturnedNoRows) => {
1245                // No exact match, try suffix match
1246            }
1247            Err(e) => return Err(e.into()),
1248        }
1249
1250        // Try suffix match: files whose path ends with `/` + the normalized path
1251        // (whole segments; ASCII case-insensitive, as `PathResolver` matches)
1252        let mut stmt = conn.prepare(
1253            "SELECT id, path FROM files
1254             WHERE lower(path) = lower(?1)
1255                OR lower(substr(path, -(length(?1) + 1))) = lower('/' || ?1)",
1256        )?;
1257
1258        let matches: Vec<(i64, String)> = stmt
1259            .query_map([&normalized_path], |row| Ok((row.get(0)?, row.get(1)?)))?
1260            .collect::<Result<Vec<_>, _>>()?;
1261
1262        match matches.len() {
1263            0 => Ok(None),
1264            1 => Ok(Some(matches[0].0)),
1265            _ => {
1266                // Multiple matches - return error with suggestions
1267                let paths: Vec<String> = matches.iter().map(|(_, p)| p.clone()).collect();
1268                anyhow::bail!(
1269                    "Ambiguous path '{}' matches multiple files:\n  {}\n\nPlease be more specific.",
1270                    path,
1271                    paths.join("\n  ")
1272                );
1273            }
1274        }
1275    }
1276
1277    /// Internal imports per language (the `files.language` name) and how many of them
1278    /// resolve to an indexed file, in language order.
1279    ///
1280    /// The graph `analyze` and `get_dependencies` answer from holds only resolved
1281    /// imports, so a low rate means those answers are incomplete for that language.
1282    pub fn internal_resolution_by_language(&self) -> Result<Vec<LanguageResolution>> {
1283        let conn = self.open_conn()?;
1284        let mut stmt = conn.prepare(
1285            "SELECT f.language, COUNT(*),
1286                    SUM(d.resolved_file_id IS NOT NULL
1287                        OR EXISTS (SELECT 1 FROM package_members m
1288                                    WHERE m.package = d.resolved_package
1289                                      AND m.member = COALESCE(d.resolved_member, '')
1290                                      AND m.file_id != d.file_id))
1291             FROM file_dependencies d
1292             JOIN files f ON d.file_id = f.id
1293             WHERE d.import_type = 'internal'
1294               -- vendored code's own imports are not the project's graph
1295               AND f.vendored = 0
1296               -- C# calls every non-System using internal: leave out the NuGet ones,
1297               -- whose root namespace (`Newtonsoft` of `Newtonsoft.Json`) no file declares
1298               AND NOT (COALESCE(d.resolved_package, '') LIKE 'cs:%' AND NOT EXISTS (
1299                   SELECT 1 FROM package_members m,
1300                       (SELECT 'cs:' || CASE WHEN instr(substr(d.resolved_package, 4), '.') > 0
1301                            THEN substr(d.resolved_package, 4, instr(substr(d.resolved_package, 4), '.') - 1)
1302                            ELSE substr(d.resolved_package, 4) END AS root)
1303                   WHERE m.package = root
1304                      OR (m.package > root || '.' AND m.package < root || '/')))
1305             GROUP BY f.language
1306             ORDER BY f.language",
1307        )?;
1308        let rows = stmt.query_map([], |row| {
1309            Ok(LanguageResolution {
1310                language: row.get(0)?,
1311                internal: row.get::<_, i64>(1)? as usize,
1312                resolved: row.get::<_, i64>(2)? as usize,
1313            })
1314        })?;
1315        Ok(rows.collect::<Result<Vec<_>, _>>()?)
1316    }
1317
1318    /// The low-resolution warning for the language of the file at `path`, if any.
1319    /// Vendored code files (`files.vendored`, text tiers left out): searchable, but
1320    /// not in the import graph (see [`crate::vendor`]).
1321    pub fn vendored_file_count(&self) -> Result<usize> {
1322        let conn = self.open_conn()?;
1323        let n: i64 = conn.query_row(
1324            "SELECT COUNT(*) FROM files
1325             WHERE vendored = 1 AND language NOT IN ('Text', 'Lock', 'Generated', 'Unknown')",
1326            [],
1327            |r| r.get(0),
1328        )?;
1329        Ok(n as usize)
1330    }
1331
1332    /// The warnings a `get_dependencies` answer about `path` carries: the file is
1333    /// vendored (so it has no edges), or its language's graph is mostly missing.
1334    pub fn graph_warnings_for(&self, path: &str) -> Result<Vec<String>> {
1335        let Some(id) = self.get_file_id_by_path(path).ok().flatten() else {
1336            return Ok(Vec::new());
1337        };
1338        let conn = self.open_conn()?;
1339        let vendored: bool =
1340            conn.query_row("SELECT vendored FROM files WHERE id = ?", [id], |r| {
1341                r.get(0)
1342            })?;
1343        if vendored {
1344            return Ok(vec![format!(
1345                "{path} is vendored; vendored files are not in the import graph"
1346            )]);
1347        }
1348        Ok(self.low_resolution_warning_for(path)?.into_iter().collect())
1349    }
1350
1351    pub fn low_resolution_warning_for(&self, path: &str) -> Result<Option<String>> {
1352        let Some(id) = self.get_file_id_by_path(path).ok().flatten() else {
1353            return Ok(None);
1354        };
1355        let conn = self.open_conn()?;
1356        let language: Option<String> = conn
1357            .query_row("SELECT language FROM files WHERE id = ?", [id], |row| {
1358                row.get(0)
1359            })
1360            .ok();
1361        Ok(language.and_then(|language| {
1362            self.internal_resolution_by_language()
1363                .ok()?
1364                .into_iter()
1365                .find(|l| l.language == language && l.is_low())
1366                .map(|l| l.warning())
1367        }))
1368    }
1369
1370    /// One warning per language whose graph is mostly missing: at least
1371    /// [`LOW_RESOLUTION_MIN_IMPORTS`] internal imports, under [`LOW_RESOLUTION_RATE`]
1372    /// of them resolved. Front ends attach these to `analyze` and `get_dependencies`
1373    /// answers so a graph built from 0.3 % of the edges is never presented as fact.
1374    pub fn low_resolution_warnings(&self) -> Result<Vec<String>> {
1375        Ok(self
1376            .internal_resolution_by_language()?
1377            .iter()
1378            .filter(|l| l.is_low())
1379            .map(LanguageResolution::warning)
1380            .collect())
1381    }
1382
1383    /// Get all internal dependencies with their resolution status
1384    ///
1385    /// Returns detailed information about each internal dependency including source file,
1386    /// imported path, and whether it was successfully resolved.
1387    ///
1388    /// # Returns
1389    ///
1390    /// A vector of tuples: (source_file, imported_path, resolved_file_path)
1391    /// where resolved_file_path is None if the dependency couldn't be resolved.
1392    pub fn get_all_internal_dependencies(&self) -> Result<Vec<(String, String, Option<String>)>> {
1393        let conn = self.open_conn()?;
1394
1395        let mut stmt = conn.prepare(
1396            "SELECT
1397                f.path,
1398                d.imported_path,
1399                f2.path as resolved_path
1400            FROM file_dependencies d
1401            JOIN files f ON d.file_id = f.id
1402            LEFT JOIN files f2 ON d.resolved_file_id = f2.id
1403            WHERE d.import_type = 'internal'
1404            ORDER BY f.path",
1405        )?;
1406
1407        let mut deps = Vec::new();
1408
1409        let rows = stmt.query_map([], |row| {
1410            Ok((
1411                row.get::<_, String>(0)?,
1412                row.get::<_, String>(1)?,
1413                row.get::<_, Option<String>>(2)?,
1414            ))
1415        })?;
1416
1417        for row in rows {
1418            deps.push(row?);
1419        }
1420
1421        Ok(deps)
1422    }
1423
1424    /// Get total count of dependencies by type (for debugging)
1425    pub fn get_dependency_count_by_type(&self) -> Result<Vec<(String, usize)>> {
1426        let conn = self.open_conn()?;
1427
1428        let mut stmt = conn.prepare(
1429            "SELECT import_type, COUNT(*) as count
1430             FROM file_dependencies
1431             GROUP BY import_type
1432             ORDER BY import_type",
1433        )?;
1434
1435        let mut counts = Vec::new();
1436
1437        let rows = stmt.query_map([], |row| {
1438            Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)? as usize))
1439        })?;
1440
1441        for row in rows {
1442            counts.push(row?);
1443        }
1444
1445        Ok(counts)
1446    }
1447}
1448
1449/// The order [`load_edges`] returns edges in: the row order each graph reader read
1450/// `file_dependencies` in before package edges existed, so outputs are unchanged.
1451#[derive(Clone, Copy)]
1452enum EdgeOrder {
1453    /// By importer id, then import row (cycle detection).
1454    ImporterId,
1455    /// By importer walk position, then import row (islands).
1456    ImporterWalk,
1457}
1458
1459/// Every import edge `(importer, imported file)` once, file-resolved and
1460/// package-expanded (`import_edges`), targets of one import in walk order.
1461/// With `every_edge` false (cycle detection), Rust `mod foo;` edges (ownership
1462/// rather than use) and C# whole-namespace edges are left out.
1463fn load_edges(conn: &Connection, order: EdgeOrder, every_edge: bool) -> Result<Vec<(i64, i64)>> {
1464    let order_by = match order {
1465        EdgeOrder::ImporterId => "e.src, e.dep_id, t.walk_seq",
1466        EdgeOrder::ImporterWalk => "s.walk_seq, e.dep_id, t.walk_seq",
1467    };
1468    let filter = if every_edge {
1469        ""
1470    } else {
1471        // Cycles: a C# `using` reaches every file of a namespace, which is no
1472        // evidence that this file uses that one, and namespaces commonly use each
1473        // other; as file edges they made 11,130 "cycles" of dotnet/runtime.
1474        "WHERE e.import_type != 'mod_decl' AND (e.package IS NULL OR e.package NOT LIKE 'cs:%')"
1475    };
1476    let mut stmt = conn.prepare(&format!(
1477        "SELECT e.src, e.dst FROM import_edges e
1478         JOIN files s ON s.id = e.src
1479         JOIN files t ON t.id = e.dst
1480         {filter}
1481         ORDER BY {order_by}"
1482    ))?;
1483    let mut seen = HashSet::new();
1484    let edges = stmt
1485        .query_map([], |row| Ok((row.get::<_, i64>(0)?, row.get::<_, i64>(1)?)))?
1486        .collect::<Result<Vec<_>, _>>()?;
1487    Ok(edges.into_iter().filter(|e| seen.insert(*e)).collect())
1488}
1489
1490/// The member files of each Go package, in walk order. They compile as one unit
1491/// and use each other with no import, so islands and unused files treat each
1492/// group as connected. (JVM and C# packages are not: a namespace can span
1493/// unrelated projects.)
1494fn sibling_groups(conn: &Connection) -> Result<Vec<Vec<i64>>> {
1495    let mut stmt = conn.prepare(
1496        "SELECT m.package, m.file_id FROM package_members m
1497         JOIN files f ON f.id = m.file_id
1498         WHERE m.package LIKE 'go:%' AND f.vendored = 0
1499         ORDER BY m.package, f.walk_seq",
1500    )?;
1501    let mut groups: Vec<Vec<i64>> = Vec::new();
1502    let mut current: Option<String> = None;
1503    let rows = stmt.query_map([], |row| {
1504        Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)?))
1505    })?;
1506    for row in rows {
1507        let (package, id) = row?;
1508        if current.as_deref() != Some(package.as_str()) {
1509            groups.push(Vec::new());
1510            current = Some(package);
1511        }
1512        groups.last_mut().expect("pushed above").push(id);
1513    }
1514    Ok(groups)
1515}
1516
1517/// `files` rows that can take part in the import graph. Text, lock and generated
1518/// files have no import extraction, so as graph nodes they were only ever islands
1519/// and "unused" (every README and lock file on 2.1.0).
1520const CODE_FILES: &str =
1521    "language NOT IN ('Text', 'Lock', 'Generated', 'Unknown') AND vendored = 0";
1522
1523/// Return true if the given file path is a well-known project entry point.
1524///
1525/// Entry points are always reachable by definition and should never appear in the
1526/// "unused files" list even when nothing else imports them (REF-89).
1527fn is_entry_point(path: &str) -> bool {
1528    let p = path.replace('\\', "/");
1529    let p = p.as_str();
1530
1531    // Exact well-known Rust/generic entry points
1532    if matches!(
1533        p,
1534        "src/lib.rs" | "src/main.rs" | "build.rs" | "lib.rs" | "main.rs"
1535    ) {
1536        return true;
1537    }
1538
1539    // Test / bench / example / fixture directories, at any depth (`staging/x/test/`,
1540    // Maven's `src/test/`, a .NET `Foo.Tests/` project)
1541    let (dirs, filename) = match p.rsplit_once('/') {
1542        Some((dirs, name)) => (dirs, name),
1543        None => ("", p),
1544    };
1545    if dirs.split('/').any(|d| {
1546        matches!(
1547            d,
1548            "tests" | "test" | "benches" | "examples" | "testdata" | "__tests__"
1549        ) || d.ends_with(".Tests")
1550            || d.ends_with(".UnitTests")
1551    }) {
1552        return true;
1553    }
1554
1555    // Program entry points by language convention
1556    if matches!(
1557        filename,
1558        "main.go" | "Program.cs" | "__main__.py" | "manage.py" | "conftest.py" | "setup.py"
1559    ) {
1560        return true;
1561    }
1562
1563    // Files whose names follow common test/spec conventions
1564    let stem = filename.rsplit_once('.').map_or(filename, |(stem, _)| stem);
1565    filename.starts_with("test_")
1566        || filename.ends_with("_test.rs")
1567        || filename.ends_with("_spec.rs")
1568        || filename.ends_with("_test.go")
1569        || filename.ends_with("_test.py")
1570        || ((filename.ends_with(".java") || filename.ends_with(".kt") || filename.ends_with(".cs"))
1571            && (stem.ends_with("Test")
1572                || stem.ends_with("Tests")
1573                // Maven Failsafe integration tests: `FooIT`, not `EXIT`
1574                || stem
1575                    .strip_suffix("IT")
1576                    .and_then(|s| s.chars().last())
1577                    .is_some_and(char::is_lowercase)))
1578}
1579
1580/// Generate path variants for an import path
1581///
1582/// Converts a namespace/import path to multiple file path variants for fuzzy matching.
1583/// Tries progressively shorter paths to handle custom PSR-4 mappings.
1584///
1585/// Examples:
1586/// - `Rcm\\Http\\Controllers\\Controller` →
1587///   - `Rcm/Http/Controllers/Controller.php`
1588///   - `Http/Controllers/Controller.php`
1589///   - `Controllers/Controller.php`
1590///   - `Controller.php`
1591fn generate_path_variants(import_path: &str) -> Vec<String> {
1592    // Convert namespace separators to path separators
1593    let path = import_path.replace('\\', "/").replace("::", "/");
1594
1595    // Remove quotes if present (some languages quote import paths)
1596    let path = path.trim_matches('"').trim_matches('\'');
1597
1598    // Split into components
1599    let components: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
1600
1601    if components.is_empty() {
1602        return vec![];
1603    }
1604
1605    let mut variants = Vec::new();
1606
1607    // Generate progressively shorter paths
1608    // E.g., for "Rcm/Http/Controllers/Controller":
1609    // 1. Rcm/Http/Controllers/Controller.php (full path)
1610    // 2. Http/Controllers/Controller.php (without first component)
1611    // 3. Controllers/Controller.php (without first two)
1612    // 4. Controller.php (just the class name)
1613    for start_idx in 0..components.len() {
1614        let suffix = components[start_idx..].join("/");
1615
1616        // Try with .php extension (most common)
1617        if !suffix.ends_with(".php") {
1618            variants.push(format!("{}.php", suffix));
1619        } else {
1620            variants.push(suffix.clone());
1621        }
1622
1623        // Also try without extension (for languages that don't use extensions in imports)
1624        if !suffix.contains('.') {
1625            // Try common extensions
1626            variants.push(format!("{}.rs", suffix));
1627            variants.push(format!("{}.ts", suffix));
1628            variants.push(format!("{}.js", suffix));
1629            variants.push(format!("{}.py", suffix));
1630        }
1631    }
1632
1633    variants
1634}
1635
1636/// Normalize a path for fuzzy lookup
1637///
1638/// Strips common prefixes that might differ between query and database:
1639/// - `./` and `../` prefixes
1640/// - Absolute paths (converts to relative by taking only the path component)
1641///
1642/// Examples:
1643/// - `./services/foo.php` → `services/foo.php`
1644/// - `/home/user/project/services/foo.php` → `services/foo.php` (just filename portion)
1645/// - `GetCaseByBatchNumberController.php` → `GetCaseByBatchNumberController.php`
1646fn normalize_path_for_lookup(path: &str) -> String {
1647    // Strip ./ and ../ prefixes
1648    let mut normalized = path.trim_start_matches("./").to_string();
1649    if normalized.starts_with("../") {
1650        normalized = normalized.trim_start_matches("../").to_string();
1651    }
1652
1653    // If it's an absolute path, extract the relevant portion
1654    // This handles cases like `/home/user/Code/project/services/php/...`
1655    // We want to extract just `services/php/...` part
1656    if normalized.starts_with('/') || normalized.starts_with('\\') {
1657        // Common project markers (ordered by priority)
1658        let markers = ["services", "src", "app", "lib", "packages", "modules"];
1659
1660        let mut found_marker = false;
1661        for marker in &markers {
1662            if let Some(idx) = normalized.find(marker) {
1663                normalized = normalized[idx..].to_string();
1664                found_marker = true;
1665                break;
1666            }
1667        }
1668
1669        // If no marker found, just use the filename
1670        if !found_marker {
1671            use std::path::Path;
1672            let path_obj = Path::new(&normalized);
1673            if let Some(filename) = path_obj.file_name() {
1674                normalized = filename.to_string_lossy().to_string();
1675            }
1676        }
1677    }
1678
1679    normalized
1680}
1681
1682/// Resolve a Rust import path to an absolute file path
1683///
1684/// This function handles Rust-specific path resolution rules:
1685/// - `crate::` - Starts from crate root (src/lib.rs or src/main.rs)
1686/// - `super::` - Goes up one module level
1687/// - `self::` - Stays in current module
1688/// - `mod name` - Looks for name.rs or name/mod.rs
1689/// - External crates - Returns None
1690///
1691/// # Arguments
1692///
1693/// * `import_path` - The import path as written in source (e.g., "crate::models::Language")
1694/// * `current_file` - Path to the file containing the import (e.g., "src/query.rs")
1695/// * `project_root` - Root directory of the project
1696///
1697/// # Returns
1698///
1699/// `Some(path)` if the import resolves to a project file, `None` if it's external/stdlib
1700pub fn resolve_rust_import(
1701    import_path: &str,
1702    current_file: &str,
1703    project_root: &std::path::Path,
1704) -> Option<String> {
1705    use std::path::{Path, PathBuf};
1706
1707    // External crates and stdlib - don't resolve
1708    if !import_path.starts_with("crate::")
1709        && !import_path.starts_with("super::")
1710        && !import_path.starts_with("self::")
1711    {
1712        return None;
1713    }
1714
1715    let current_path = Path::new(current_file);
1716    let mut resolved_path: Option<PathBuf> = None;
1717
1718    if import_path.starts_with("crate::") {
1719        // Start from crate root (src/lib.rs or src/main.rs)
1720        let crate_root = if project_root.join("src/lib.rs").exists()
1721            || project_root.join("src/main.rs").exists()
1722        {
1723            project_root.join("src")
1724        } else {
1725            // Fallback to src/ directory
1726            project_root.join("src")
1727        };
1728
1729        let path_parts: Vec<&str> = import_path
1730            .strip_prefix("crate::")
1731            .unwrap()
1732            .split("::")
1733            .collect();
1734
1735        resolved_path = resolve_module_path(&crate_root, &path_parts);
1736    } else if import_path.starts_with("super::") {
1737        // Go up one directory from current file's parent (the current module's parent)
1738        if let Some(current_dir) = current_path.parent()
1739            && let Some(parent_dir) = current_dir.parent()
1740        {
1741            let path_parts: Vec<&str> = import_path
1742                .strip_prefix("super::")
1743                .unwrap()
1744                .split("::")
1745                .collect();
1746
1747            resolved_path = resolve_module_path(parent_dir, &path_parts);
1748        }
1749    } else if import_path.starts_with("self::") {
1750        // Stay in current directory
1751        if let Some(current_dir) = current_path.parent() {
1752            let path_parts: Vec<&str> = import_path
1753                .strip_prefix("self::")
1754                .unwrap()
1755                .split("::")
1756                .collect();
1757
1758            resolved_path = resolve_module_path(current_dir, &path_parts);
1759        }
1760    }
1761
1762    // Convert to string and make relative to project root.
1763    // Normalize to forward slashes so paths are deterministic across platforms.
1764    resolved_path.and_then(|p| {
1765        p.strip_prefix(project_root)
1766            .ok()
1767            .map(|rel| rel.to_string_lossy().replace('\\', "/"))
1768    })
1769}
1770
1771/// Resolve a module path given a starting directory and path components
1772///
1773/// Handles Rust's module system rules:
1774/// - `foo` → check foo.rs or foo/mod.rs
1775/// - `foo::bar` → check foo/bar.rs or foo/bar/mod.rs
1776fn resolve_module_path(
1777    start_dir: &std::path::Path,
1778    components: &[&str],
1779) -> Option<std::path::PathBuf> {
1780    if components.is_empty() {
1781        return None;
1782    }
1783
1784    let mut current = start_dir.to_path_buf();
1785
1786    // For all components except the last, they must be directories
1787    for &component in &components[..components.len() - 1] {
1788        // Try as a directory with mod.rs
1789        let dir_path = current.join(component);
1790        let mod_file = dir_path.join("mod.rs");
1791
1792        if mod_file.exists() {
1793            current = dir_path;
1794        } else {
1795            // Component must be a directory for nested paths
1796            return None;
1797        }
1798    }
1799
1800    // For the last component, try both file.rs and file/mod.rs
1801    let last_component = components.last().unwrap();
1802
1803    // Try as a single file
1804    let file_path = current.join(format!("{}.rs", last_component));
1805    if file_path.exists() {
1806        return Some(file_path);
1807    }
1808
1809    // Try as a directory with mod.rs
1810    let dir_path = current.join(last_component);
1811    let mod_file = dir_path.join("mod.rs");
1812    if mod_file.exists() {
1813        return Some(mod_file);
1814    }
1815
1816    None
1817}
1818
1819/// Resolve a `mod` declaration to a file path
1820///
1821/// For `mod parser;`, this checks for:
1822/// - `parser.rs` (sibling file)
1823/// - `parser/mod.rs` (directory module)
1824pub fn resolve_rust_mod_declaration(
1825    mod_name: &str,
1826    current_file: &str,
1827    _project_root: &std::path::Path,
1828) -> Option<String> {
1829    use std::path::Path;
1830
1831    let current_path = Path::new(current_file);
1832    let current_dir = current_path.parent()?;
1833
1834    // Try sibling file
1835    let sibling = current_dir.join(format!("{}.rs", mod_name));
1836    if sibling.exists() {
1837        return Some(sibling.to_string_lossy().replace('\\', "/"));
1838    }
1839
1840    // Try directory module
1841    let dir_mod = current_dir.join(mod_name).join("mod.rs");
1842    if dir_mod.exists() {
1843        return Some(dir_mod.to_string_lossy().replace('\\', "/"));
1844    }
1845
1846    None
1847}
1848
1849/// Resolve a PHP import path to a file path
1850///
1851/// This function handles PHP-specific namespace-to-file mapping:
1852/// - Converts backslash-separated namespaces to forward-slash paths
1853/// - Handles PSR-4 autoloading conventions
1854/// - Filters out external vendor namespaces (returns None for non-project code)
1855///
1856/// # Arguments
1857///
1858/// * `import_path` - PHP namespace path (e.g., "App\\Http\\Controllers\\UserController")
1859/// * `current_file` - Not used for PHP (PHP uses absolute namespaces)
1860/// * `project_root` - Root directory of the project
1861///
1862/// # Returns
1863///
1864/// `Some(path)` if the import resolves to a project file, `None` if it's external/stdlib
1865///
1866/// # Examples
1867///
1868/// - `App\\Http\\Controllers\\FooController` → `app/Http/Controllers/FooController.php`
1869/// - `App\\Models\\User` → `app/Models/User.php`
1870/// - `Illuminate\\Database\\Migration` → `None` (external vendor namespace)
1871pub fn resolve_php_import(
1872    import_path: &str,
1873    _current_file: &str,
1874    project_root: &std::path::Path,
1875) -> Option<String> {
1876    // External vendor namespaces (Laravel, Symfony, etc.) - don't resolve
1877    const VENDOR_NAMESPACES: &[&str] = &[
1878        "Illuminate\\",
1879        "Symfony\\",
1880        "Laravel\\",
1881        "Psr\\",
1882        "Doctrine\\",
1883        "Monolog\\",
1884        "PHPUnit\\",
1885        "Carbon\\",
1886        "GuzzleHttp\\",
1887        "Composer\\",
1888        "Predis\\",
1889        "League\\",
1890    ];
1891
1892    // Check if this is a vendor namespace
1893    for vendor_ns in VENDOR_NAMESPACES {
1894        if import_path.starts_with(vendor_ns) {
1895            return None;
1896        }
1897    }
1898
1899    // Convert namespace to file path
1900    // PHP namespaces use backslashes: App\Http\Controllers\FooController
1901    // Files use forward slashes: app/Http/Controllers/FooController.php
1902    let file_path = import_path.replace('\\', "/");
1903
1904    // Try common PSR-4 mappings (lowercase first component)
1905    // App\... → app/...
1906    // Database\... → database/...
1907    let path_candidates = vec![
1908        // Try with lowercase first component (PSR-4 standard)
1909        {
1910            let parts: Vec<&str> = file_path.split('/').collect();
1911            if let Some(first) = parts.first() {
1912                let mut result = vec![first.to_lowercase()];
1913                result.extend(parts[1..].iter().map(|s| s.to_string()));
1914                result.join("/") + ".php"
1915            } else {
1916                file_path.clone() + ".php"
1917            }
1918        },
1919        // Try exact path (some projects use exact case)
1920        file_path.clone() + ".php",
1921        // Try all lowercase (legacy projects)
1922        file_path.to_lowercase() + ".php",
1923    ];
1924
1925    // Check each candidate path
1926    for candidate in &path_candidates {
1927        let full_path = project_root.join(candidate);
1928        if full_path.exists() {
1929            // Return relative path
1930            return Some(candidate.clone());
1931        }
1932    }
1933
1934    // If no file found, return None (likely external or not yet created)
1935    None
1936}
1937
1938#[cfg(test)]
1939mod tests {
1940    use super::*;
1941    use tempfile::TempDir;
1942
1943    fn setup_test_cache() -> (TempDir, CacheManager) {
1944        let temp = TempDir::new().unwrap();
1945        let cache = CacheManager::new(temp.path());
1946        cache.init().unwrap();
1947
1948        // Add some test files
1949        cache.update_file("src/main.rs", "rust", 100).unwrap();
1950        cache.update_file("src/lib.rs", "rust", 50).unwrap();
1951        cache.update_file("src/utils.rs", "rust", 30).unwrap();
1952
1953        (temp, cache)
1954    }
1955
1956    /// A Go-style package import: one row keyed by package, expanded to every
1957    /// member file when the graph is read.
1958    #[test]
1959    fn package_import_links_every_member() {
1960        let temp = TempDir::new().unwrap();
1961        let cache = CacheManager::new(temp.path());
1962        cache.init().unwrap();
1963        cache.update_file("cmd/a.go", "Go", 10).unwrap();
1964        cache.update_file("pkg/b/b1.go", "Go", 10).unwrap();
1965        cache.update_file("pkg/b/b2.go", "Go", 10).unwrap();
1966        let index = DependencyIndex::new(cache);
1967        let id = |p: &str| index.get_file_id_by_path(p).unwrap().unwrap();
1968        let (a, b1, b2) = (id("cmd/a.go"), id("pkg/b/b1.go"), id("pkg/b/b2.go"));
1969        {
1970            let conn = index.open_conn().unwrap();
1971            let mut writer = DependencyWriter::new(&conn);
1972            for b in [b1, b2] {
1973                writer
1974                    .replace_members(b, &[("go:pkg/b".to_string(), String::new())])
1975                    .unwrap();
1976            }
1977            writer
1978                .replace_dependencies(
1979                    a,
1980                    &[Dependency {
1981                        file_id: a,
1982                        imported_path: "example.com/m/pkg/b".to_string(),
1983                        resolved_file_id: None,
1984                        resolved_package: Some("go:pkg/b".to_string()),
1985                        resolved_member: None,
1986                        import_type: ImportType::Internal,
1987                        line_number: 3,
1988                        imported_symbols: None,
1989                    }],
1990                )
1991                .unwrap();
1992        }
1993
1994        assert_eq!(index.get_dependents(b2).unwrap(), vec![a]);
1995        let mut reached: Vec<i64> = index
1996            .get_transitive_deps(a, 1)
1997            .unwrap()
1998            .into_keys()
1999            .collect();
2000        reached.sort();
2001        assert_eq!(reached, vec![a, b1, b2]);
2002        assert_eq!(index.find_islands().unwrap(), vec![vec![a, b1, b2]]);
2003        assert_eq!(
2004            index.find_hotspots(None, 1).unwrap(),
2005            vec![(b1, 1), (b2, 1)]
2006        );
2007        assert!(!index.find_unused_files().unwrap().contains(&b2));
2008        assert_eq!(
2009            index.internal_resolution_by_language().unwrap(),
2010            vec![LanguageResolution {
2011                language: "Go".to_string(),
2012                internal: 1,
2013                resolved: 1,
2014            }]
2015        );
2016        let info = index.get_dependencies_info(a).unwrap();
2017        assert_eq!(info.len(), 1, "one entry per import: {info:?}");
2018        assert_eq!(
2019            info[0].resolved_paths,
2020            Some(vec!["pkg/b/b1.go".to_string(), "pkg/b/b2.go".to_string()])
2021        );
2022    }
2023
2024    #[test]
2025    fn entry_points_cover_each_language() {
2026        for p in [
2027            "src/main.rs",
2028            "tests/a.rs",
2029            "staging/src/k8s.io/api/test/x.go",
2030            "cmd/kubelet/main.go",
2031            "pkg/a/a_test.go",
2032            "pkg/a/testdata/x.go",
2033            "module/src/test/java/org/x/FooTest.java",
2034            "module/src/main/java/org/x/FooIT.java",
2035            "app/src/main/kotlin/FooTests.kt",
2036            "src/App/Program.cs",
2037            "src/Foo.Tests/Bar.cs",
2038            "django/__main__.py",
2039            "manage.py",
2040            "pkg/conftest.py",
2041            "pkg/test_views.py",
2042            "pkg/views_test.py",
2043        ] {
2044            assert!(is_entry_point(p), "{p}");
2045        }
2046        for p in [
2047            "src/util.rs",
2048            "pkg/a/a.go",
2049            "pkg/latest/x.go",
2050            "src/main/java/org/x/EXIT.java",
2051            "src/main/java/org/x/Audit.java",
2052            "src/App/Contest.cs",
2053            "django/db/models.py",
2054        ] {
2055            assert!(!is_entry_point(p), "{p}");
2056        }
2057    }
2058
2059    #[test]
2060    fn test_insert_and_get_dependencies() {
2061        let (_temp, cache) = setup_test_cache();
2062        let deps_index = DependencyIndex::new(cache);
2063
2064        // Get file IDs
2065        let main_id = 1i64;
2066        let lib_id = 2i64;
2067
2068        // Insert a dependency: main.rs imports lib.rs
2069        deps_index
2070            .insert_dependency(
2071                main_id,
2072                "crate::lib".to_string(),
2073                Some(lib_id),
2074                ImportType::Internal,
2075                5,
2076                None,
2077            )
2078            .unwrap();
2079
2080        // Retrieve dependencies
2081        let deps = deps_index.get_dependencies(main_id).unwrap();
2082        assert_eq!(deps.len(), 1);
2083        assert_eq!(deps[0].imported_path, "crate::lib");
2084        assert_eq!(deps[0].resolved_file_id, Some(lib_id));
2085        assert_eq!(deps[0].import_type, ImportType::Internal);
2086    }
2087
2088    #[test]
2089    fn test_reverse_lookup() {
2090        let (_temp, cache) = setup_test_cache();
2091        let deps_index = DependencyIndex::new(cache);
2092
2093        let main_id = 1i64;
2094        let lib_id = 2i64;
2095        let utils_id = 3i64;
2096
2097        // main.rs imports lib.rs
2098        deps_index
2099            .insert_dependency(
2100                main_id,
2101                "crate::lib".to_string(),
2102                Some(lib_id),
2103                ImportType::Internal,
2104                5,
2105                None,
2106            )
2107            .unwrap();
2108
2109        // utils.rs also imports lib.rs
2110        deps_index
2111            .insert_dependency(
2112                utils_id,
2113                "crate::lib".to_string(),
2114                Some(lib_id),
2115                ImportType::Internal,
2116                3,
2117                None,
2118            )
2119            .unwrap();
2120
2121        // Get files that import lib.rs
2122        let dependents = deps_index.get_dependents(lib_id).unwrap();
2123        assert_eq!(dependents.len(), 2);
2124        assert!(dependents.contains(&main_id));
2125        assert!(dependents.contains(&utils_id));
2126    }
2127
2128    #[test]
2129    fn test_transitive_dependencies() {
2130        let (_temp, cache) = setup_test_cache();
2131        let deps_index = DependencyIndex::new(cache);
2132
2133        let file1 = 1i64;
2134        let file2 = 2i64;
2135        let file3 = 3i64;
2136
2137        // file1 → file2 → file3
2138        deps_index
2139            .insert_dependency(
2140                file1,
2141                "file2".to_string(),
2142                Some(file2),
2143                ImportType::Internal,
2144                1,
2145                None,
2146            )
2147            .unwrap();
2148
2149        deps_index
2150            .insert_dependency(
2151                file2,
2152                "file3".to_string(),
2153                Some(file3),
2154                ImportType::Internal,
2155                1,
2156                None,
2157            )
2158            .unwrap();
2159
2160        // Get transitive deps at depth 2
2161        let transitive = deps_index.get_transitive_deps(file1, 2).unwrap();
2162
2163        // Should include file1 (depth 0), file2 (depth 1), file3 (depth 2)
2164        assert_eq!(transitive.len(), 3);
2165        assert_eq!(transitive.get(&file1), Some(&0));
2166        assert_eq!(transitive.get(&file2), Some(&1));
2167        assert_eq!(transitive.get(&file3), Some(&2));
2168    }
2169
2170    #[test]
2171    fn test_batch_insert() {
2172        let (_temp, cache) = setup_test_cache();
2173        let deps_index = DependencyIndex::new(cache);
2174
2175        let deps = vec![
2176            Dependency {
2177                file_id: 1,
2178                imported_path: "std::collections".to_string(),
2179                resolved_file_id: None,
2180                resolved_package: None,
2181                resolved_member: None,
2182                import_type: ImportType::Stdlib,
2183                line_number: 1,
2184                imported_symbols: Some(vec!["HashMap".to_string()]),
2185            },
2186            Dependency {
2187                file_id: 1,
2188                imported_path: "crate::lib".to_string(),
2189                resolved_file_id: Some(2),
2190                resolved_package: None,
2191                resolved_member: None,
2192                import_type: ImportType::Internal,
2193                line_number: 2,
2194                imported_symbols: None,
2195            },
2196        ];
2197
2198        deps_index.batch_insert_dependencies(&deps).unwrap();
2199
2200        let retrieved = deps_index.get_dependencies(1).unwrap();
2201        assert_eq!(retrieved.len(), 2);
2202    }
2203
2204    #[test]
2205    fn test_clear_dependencies() {
2206        let (_temp, cache) = setup_test_cache();
2207        let deps_index = DependencyIndex::new(cache);
2208
2209        // Insert dependencies
2210        deps_index
2211            .insert_dependency(
2212                1,
2213                "crate::lib".to_string(),
2214                Some(2),
2215                ImportType::Internal,
2216                1,
2217                None,
2218            )
2219            .unwrap();
2220
2221        // Verify they exist
2222        assert_eq!(deps_index.get_dependencies(1).unwrap().len(), 1);
2223
2224        // Clear them
2225        deps_index.clear_dependencies(1).unwrap();
2226
2227        // Verify they're gone
2228        assert_eq!(deps_index.get_dependencies(1).unwrap().len(), 0);
2229    }
2230
2231    #[test]
2232    fn test_resolve_rust_import_crate() {
2233        use std::fs;
2234        use tempfile::TempDir;
2235
2236        let temp = TempDir::new().unwrap();
2237        let project_root = temp.path();
2238
2239        // Create directory structure
2240        fs::create_dir_all(project_root.join("src")).unwrap();
2241        fs::write(project_root.join("src/lib.rs"), "").unwrap();
2242        fs::write(project_root.join("src/models.rs"), "").unwrap();
2243
2244        // Test crate:: resolution
2245        let resolved = resolve_rust_import("crate::models", "src/query.rs", project_root);
2246
2247        assert_eq!(resolved, Some("src/models.rs".to_string()));
2248    }
2249
2250    #[test]
2251    fn test_resolve_rust_import_super() {
2252        use std::fs;
2253        use tempfile::TempDir;
2254
2255        let temp = TempDir::new().unwrap();
2256        let project_root = temp.path();
2257
2258        // Create directory structure: src/parsers/rust.rs needs to import src/models.rs
2259        fs::create_dir_all(project_root.join("src/parsers")).unwrap();
2260        fs::write(project_root.join("src/models.rs"), "").unwrap();
2261        fs::write(project_root.join("src/parsers/rust.rs"), "").unwrap();
2262
2263        // Test super:: resolution from parsers/rust.rs
2264        // Use absolute path for current_file
2265        let current_file = project_root.join("src/parsers/rust.rs");
2266        let resolved = resolve_rust_import(
2267            "super::models",
2268            &current_file.to_string_lossy(),
2269            project_root,
2270        );
2271
2272        assert_eq!(resolved, Some("src/models.rs".to_string()));
2273    }
2274
2275    #[test]
2276    fn test_resolve_rust_import_external() {
2277        use tempfile::TempDir;
2278
2279        let temp = TempDir::new().unwrap();
2280        let project_root = temp.path();
2281
2282        // External crates should return None
2283        let resolved = resolve_rust_import("serde::Serialize", "src/models.rs", project_root);
2284
2285        assert_eq!(resolved, None);
2286
2287        // Stdlib should return None
2288        let resolved =
2289            resolve_rust_import("std::collections::HashMap", "src/models.rs", project_root);
2290
2291        assert_eq!(resolved, None);
2292    }
2293
2294    #[test]
2295    fn test_resolve_rust_mod_declaration() {
2296        use std::fs;
2297        use tempfile::TempDir;
2298
2299        let temp = TempDir::new().unwrap();
2300        let project_root = temp.path();
2301
2302        // Create directory structure
2303        fs::create_dir_all(project_root.join("src")).unwrap();
2304        fs::write(project_root.join("src/lib.rs"), "").unwrap();
2305        fs::write(project_root.join("src/parser.rs"), "").unwrap();
2306
2307        // Test mod declaration resolution
2308        let resolved = resolve_rust_mod_declaration(
2309            "parser",
2310            &project_root.join("src/lib.rs").to_string_lossy(),
2311            project_root,
2312        );
2313
2314        assert!(resolved.is_some());
2315        assert!(resolved.unwrap().ends_with("src/parser.rs"));
2316    }
2317
2318    #[test]
2319    fn test_resolve_rust_import_nested() {
2320        use std::fs;
2321        use tempfile::TempDir;
2322
2323        let temp = TempDir::new().unwrap();
2324        let project_root = temp.path();
2325
2326        // Create directory structure: src/models/language.rs
2327        fs::create_dir_all(project_root.join("src/models")).unwrap();
2328        fs::write(project_root.join("src/models/mod.rs"), "").unwrap();
2329        fs::write(project_root.join("src/models/language.rs"), "").unwrap();
2330
2331        // Test nested module resolution
2332        let resolved = resolve_rust_import("crate::models::language", "src/query.rs", project_root);
2333
2334        assert_eq!(resolved, Some("src/models/language.rs".to_string()));
2335    }
2336}