Skip to main content

lean_ctx/core/graph_index/
mod.rs

1// DEPRECATED: This module is being replaced by PropertyGraph (core/property_graph/).
2// New code should use GraphProvider (core/graph_provider.rs) instead of accessing
3// ProjectIndex directly. The dashboard now resolves graphs through
4// `graph_coordinator` (PropertyGraph-first); the remaining direct consumers are
5// the build pipeline (index_orchestrator) and the extractor itself.
6// See OPT-14/15 (#696) plan for the full migration path.
7
8use std::collections::HashMap;
9use std::path::Path;
10
11use rayon::prelude::*;
12use serde::{Deserialize, Serialize};
13
14use crate::core::context_admission::stores::StoreAdmission;
15use crate::core::import_resolver;
16use crate::core::signatures;
17mod edges;
18pub(crate) use edges::*;
19#[allow(unreachable_pub)]
20#[allow(dead_code)]
21pub(crate) mod file_id;
22#[cfg(test)]
23mod tests;
24
25/// 7: file summaries are admitted (E3); indexes from 6 may hold raw source
26/// lines and are rebuilt rather than reused.
27const INDEX_VERSION: u32 = 7;
28
29// Path-key utilities moved to `core::index_paths` (#682); re-exported so existing
30// `graph_index::…` call sites keep compiling during the migration.
31use crate::core::index_paths::normalize_absolute_path;
32pub use crate::core::index_paths::{graph_match_key, graph_relative_key, normalize_project_root};
33
34pub fn is_safe_scan_root_public(path: &str) -> bool {
35    is_safe_scan_root(path)
36}
37
38fn is_filesystem_root(path: &str) -> bool {
39    let p = Path::new(path);
40    p.parent().is_none() || (cfg!(windows) && p.parent() == Some(Path::new("")))
41}
42
43/// Returns `true` if `dir` contains a known project marker.
44///
45/// Delegates to the single TCC-guarded probe in `pathutil` (#356) so a
46/// launchd-standalone process never stats marker files under ~/Documents, and
47/// the marker set stays defined in exactly one place (`pathutil::PROJECT_MARKERS`).
48fn dir_has_project_marker(dir: &Path) -> bool {
49    crate::core::pathutil::has_project_marker(dir)
50}
51
52/// True if `p` or any ancestor strictly *below* `stop` contains a project
53/// marker. Subdirectories of a real project (e.g. `repo/rust/src`) are
54/// legitimate scan roots even though the marker lives at the repo root —
55/// refusing them produced WARN noise on every grep/ls inside ~/Documents
56/// projects (GL#438). `stop` itself is never checked, so a marker-less
57/// `~/Documents` stays refused.
58fn has_marker_in_ancestry(p: &Path, stop: &Path) -> bool {
59    let mut cur = Some(p);
60    while let Some(dir) = cur {
61        if dir == stop {
62            return false;
63        }
64        if dir_has_project_marker(dir) {
65            return true;
66        }
67        cur = dir.parent();
68    }
69    false
70}
71
72/// True if `p` or an ancestor carries a project marker. Below `$HOME` the walk
73/// stops before `$HOME` itself (a dotfiles repo there must not vouch for every
74/// home directory); elsewhere it stops before the filesystem root.
75fn is_inside_project(p: &Path) -> bool {
76    let home = dirs::home_dir()
77        .map(|home| std::path::PathBuf::from(normalize_project_root(&home.to_string_lossy())));
78    let stop = home
79        .filter(|home| p.starts_with(home))
80        .or_else(|| p.ancestors().last().map(Path::to_path_buf))
81        .unwrap_or_default();
82    has_marker_in_ancestry(p, &stop)
83}
84
85fn is_safe_scan_root(path: &str) -> bool {
86    let normalized = normalize_project_root(path);
87    let p = Path::new(&normalized);
88
89    // macOS TCC (#356): a launchd-standalone process must never stat or
90    // enumerate under ~/Documents/Desktop/Downloads. Refuse such roots before
91    // any marker probe / read_dir runs. Editor- and CLI-attached processes
92    // inherit a TCC grant and keep indexing those projects normally.
93    if !crate::core::pathutil::may_probe_path(p) {
94        return false;
95    }
96
97    if normalized == "/" || normalized == "\\" || is_filesystem_root(&normalized) {
98        tracing::warn!("[graph_index: refusing to scan filesystem root]");
99        return false;
100    }
101
102    if normalized == "." || normalized.is_empty() {
103        tracing::warn!("[graph_index: refusing to scan relative/empty root]");
104        return false;
105    }
106
107    if let Some(home) = dirs::home_dir() {
108        let home_norm = normalize_project_root(&home.to_string_lossy());
109        if normalized == home_norm {
110            use std::sync::Once;
111            static HOME_WARN: Once = Once::new();
112            HOME_WARN.call_once(|| {
113                tracing::warn!(
114                    "[graph_index: skipping — cannot index home directory {normalized}.\n  \
115                     Run from inside a project, or set LEAN_CTX_PROJECT_ROOT=/path/to/project]"
116                );
117            });
118            return false;
119        }
120        // macOS TCC: Documents/Desktop/Downloads pop a privacy prompt the moment
121        // we stat or enumerate inside them (#356). They are never valid scan roots,
122        // so refuse here before any has_marker stat or read_dir runs.
123        if crate::core::pathutil::is_tcc_sensitive_home_dir(p) {
124            tracing::warn!(
125                "[graph_index: refusing to scan {normalized} — macOS TCC-protected home dir]"
126            );
127            return false;
128        }
129        // Block common broad home subdirectories that are never valid project roots
130        let home_path = Path::new(&home_norm);
131        const BLOCKED_HOME_SUBDIRS: &[&str] = &[
132            "Desktop",
133            "Documents",
134            "Downloads",
135            "Pictures",
136            "Music",
137            "Videos",
138            "Movies",
139            "Library",
140            ".local",
141            ".cache",
142            ".config",
143            "snap",
144            "Applications",
145            // Cloud-sync roots: scanning these forces on-demand providers to
146            // hydrate (download) every placeholder file/folder (#363). iCloud's
147            // backing dir (~/Library/Mobile Documents) is already covered by
148            // "Library" above.
149            "OneDrive",
150            "Dropbox",
151            "Google Drive",
152        ];
153        for blocked in BLOCKED_HOME_SUBDIRS {
154            let blocked_path = home_path.join(blocked);
155            let is_inside_blocked = p == blocked_path || p.starts_with(&blocked_path);
156            // Markers may live in an *ancestor*: `repo/rust/src` is a legitimate
157            // scan root of the project rooted at `repo` (GL#438). Walk up to (but
158            // not past) the blocked dir itself, so `~/Documents` without any
159            // project stays refused.
160            let has_marker = has_marker_in_ancestry(p, &blocked_path);
161            if is_inside_blocked
162                && !has_marker
163                && !crate::core::pathutil::has_multi_repo_children(p)
164            {
165                tracing::warn!(
166                    "[graph_index: refusing to scan {normalized} — \
167                     inside home/{blocked} without project markers]"
168                );
169                return false;
170            }
171        }
172
173        // Block directories that are direct children of home without project markers
174        // (but allow multi-repo workspace parents like ~/code/)
175        if p.parent() == Some(home_path)
176            && !dir_has_project_marker(p)
177            && !crate::core::pathutil::has_multi_repo_children(p)
178        {
179            tracing::warn!(
180                "[graph_index: refusing to scan {normalized} — \
181                 direct child of home without project markers]"
182            );
183            return false;
184        }
185    }
186
187    let breadth_markers = [
188        ".git",
189        "Cargo.toml",
190        "package.json",
191        "go.mod",
192        "pyproject.toml",
193        "setup.py",
194        "Makefile",
195        "CMakeLists.txt",
196        "pnpm-workspace.yaml",
197        ".projectile",
198        "BUILD.bazel",
199        "go.work",
200    ];
201
202    // A wide source tree inside a project (`repo/rust/src/core`, markers only
203    // in an ancestor) is not a broad directory (#1984, as GL#438 above).
204    if !breadth_markers.iter().any(|m| p.join(m).exists())
205        && !dir_has_dotnet_project(p)
206        && !is_inside_project(p)
207    {
208        // Multi-repo workspace parent: >=2 children with project markers is always safe
209        if crate::core::pathutil::has_multi_repo_children(p) {
210            return true;
211        }
212
213        let child_count = std::fs::read_dir(p).map_or(0, |rd| {
214            rd.filter_map(Result::ok)
215                .filter(|e| e.path().is_dir())
216                .count()
217        });
218        if child_count > 50 {
219            tracing::warn!(
220                "[graph_index: {normalized} has no project markers and {child_count} subdirectories — \
221                 skipping scan to avoid indexing broad directories]"
222            );
223            return false;
224        }
225    }
226
227    true
228}
229
230/// True if the directory contains a .NET project/solution file (`*.csproj`,
231/// `*.sln`, `*.fsproj`, `*.vbproj`). Filenames vary, so we match by extension —
232/// these are strong project-root markers even when there is no `.git`.
233fn dir_has_dotnet_project(dir: &Path) -> bool {
234    std::fs::read_dir(dir).is_ok_and(|rd| {
235        rd.filter_map(Result::ok).any(|e| {
236            e.path()
237                .extension()
238                .and_then(|x| x.to_str())
239                .is_some_and(|x| {
240                    matches!(
241                        x.to_ascii_lowercase().as_str(),
242                        "csproj" | "sln" | "fsproj" | "vbproj"
243                    )
244                })
245        })
246    })
247}
248
249#[derive(Debug, Clone, Serialize, Deserialize)]
250pub struct ProjectIndex {
251    pub version: u32,
252    pub project_root: String,
253    pub last_scan: String,
254    pub files: HashMap<String, FileEntry>,
255    pub edges: Vec<IndexEdge>,
256    pub symbols: HashMap<String, SymbolEntry>,
257    /// Graph-local path interner: one owned allocation per distinct file path.
258    /// Populated during scan; used for O(1) path→id lookups in queries.
259    /// Skipped during serde — rebuilt from `files` keys on deserialization.
260    #[serde(skip)]
261    pub(crate) interner: file_id::PathInterner,
262}
263
264#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
265pub struct FileEntry {
266    pub path: String,
267    pub hash: String,
268    pub language: String,
269    pub line_count: usize,
270    pub token_count: usize,
271    pub exports: Vec<String>,
272    pub summary: String,
273}
274
275#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
276pub struct SymbolEntry {
277    pub file: String,
278    pub name: String,
279    pub kind: String,
280    pub start_line: usize,
281    pub end_line: usize,
282    pub is_exported: bool,
283}
284
285#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
286pub struct IndexEdge {
287    pub from: String,
288    pub to: String,
289    pub kind: String,
290    #[serde(default = "default_edge_weight")]
291    pub weight: f32,
292}
293
294fn default_edge_weight() -> f32 {
295    1.0
296}
297
298impl ProjectIndex {
299    pub fn new(project_root: &str) -> Self {
300        Self {
301            version: INDEX_VERSION,
302            project_root: normalize_project_root(project_root),
303            last_scan: chrono::Local::now().format("%Y-%m-%d %H:%M:%S").to_string(),
304            files: HashMap::new(),
305            edges: Vec::new(),
306            symbols: HashMap::new(),
307            interner: file_id::PathInterner::new(),
308        }
309    }
310
311    /// Rebuild the interner from the current `files` keys. Called after
312    /// deserialization or materialization from the property graph, where
313    /// `interner` is skipped/absent.
314    pub(crate) fn rebuild_interner(&mut self) {
315        let mut interner = file_id::PathInterner::with_capacity(self.files.len());
316        for key in self.files.keys() {
317            interner.intern(key);
318        }
319        self.interner = interner;
320    }
321
322    pub fn index_dir(project_root: &str) -> Option<std::path::PathBuf> {
323        let normalized = normalize_project_root(project_root);
324        let hash = crate::core::project_hash::hash_project_root(&normalized);
325        crate::core::data_dir::lean_ctx_data_dir()
326            .ok()
327            .map(|d| d.join("graphs").join(hash))
328    }
329
330    /// Reconstruct the index from the property graph — the sole persistence
331    /// store since #696 C4. The PG is a parity-proven lossless superset of the
332    /// former JSON index, so this is a faithful round-trip (see
333    /// `graph_provider::materialize_project_index` + its round-trip test).
334    /// `None` when the graph has not been built yet (empty file catalog).
335    pub fn load(project_root: &str) -> Option<Self> {
336        let graph = crate::core::property_graph::CodeGraph::open(project_root).ok()?;
337        if graph.file_catalog_count().unwrap_or(0) == 0 {
338            return None;
339        }
340        let provider = crate::core::graph_provider::GraphProvider::PropertyGraph(graph);
341        let mut index = provider.materialize_project_index(project_root);
342        index.rebuild_interner();
343        Some(index)
344    }
345
346    /// Persist the index by mirroring it into the property graph (the sole store
347    /// since #696 C4). Replaces the former `index.json.zst` write; the mirror
348    /// also stamps `graph.meta.json`, which the resident graph cache fingerprints
349    /// for invalidation.
350    pub fn save(&self) -> Result<(), String> {
351        crate::core::property_graph::mirror_index(&self.project_root, self)
352            .map_err(|e| e.to_string())
353    }
354
355    /// Remove all cached graph indices that are older than max_age_hours.
356    /// Called on startup/update to prevent stale data from persisting.
357    pub fn purge_stale_indices() {
358        let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() else {
359            return;
360        };
361        let graphs_dir = data_dir.join("graphs");
362        let Ok(entries) = std::fs::read_dir(&graphs_dir) else {
363            return;
364        };
365        let cfg = crate::core::config::Config::load();
366        let max_age_secs = cfg.archive_max_age_hours_effective() * 3600;
367
368        for entry in entries.filter_map(Result::ok) {
369            let path = entry.path();
370            if !path.is_dir() {
371                continue;
372            }
373            // #696 C4: the property graph (graph.db, stamped by graph.meta.json)
374            // is the sole store; age the directory by its last build instead of
375            // the retired JSON index.
376            let meta = path.join("graph.meta.json");
377            let db = path.join("graph.db");
378            let index_file = if meta.exists() {
379                &meta
380            } else if db.exists() {
381                &db
382            } else {
383                continue;
384            };
385
386            let is_old = index_file
387                .metadata()
388                .and_then(|m| m.modified())
389                .is_ok_and(|mtime| {
390                    mtime
391                        .elapsed()
392                        .is_ok_and(|age| age.as_secs() > max_age_secs)
393                });
394
395            if is_old {
396                tracing::info!("[graph_index: purging stale index at {}]", path.display());
397                let _ = std::fs::remove_dir_all(&path);
398            }
399        }
400    }
401
402    pub fn file_count(&self) -> usize {
403        self.files.len()
404    }
405
406    pub fn symbol_count(&self) -> usize {
407        self.symbols.len()
408    }
409
410    pub fn edge_count(&self) -> usize {
411        self.edges.len()
412    }
413
414    pub fn get_symbol(&self, key: &str) -> Option<&SymbolEntry> {
415        self.symbols.get(key)
416    }
417
418    pub fn get_reverse_deps(&self, path: &str, depth: usize) -> Vec<String> {
419        let mut result = Vec::new();
420        let mut visited = std::collections::HashSet::new();
421        let mut queue: Vec<(String, usize)> = vec![(path.to_string(), 0)];
422
423        while let Some((current, d)) = queue.pop() {
424            if d > depth || visited.contains(&current) {
425                continue;
426            }
427            visited.insert(current.clone());
428            if current != path {
429                result.push(current.clone());
430            }
431
432            for edge in &self.edges {
433                if edge.to == current && edge.kind == "import" && !visited.contains(&edge.from) {
434                    queue.push((edge.from.clone(), d + 1));
435                }
436            }
437        }
438        result
439    }
440
441    /// Forward import dependencies: files that `path` (transitively) imports.
442    /// Mirror of `get_reverse_deps` with the edge direction flipped.
443    pub fn get_forward_deps(&self, path: &str, depth: usize) -> Vec<String> {
444        let mut result = Vec::new();
445        let mut visited = std::collections::HashSet::new();
446        let mut queue: Vec<(String, usize)> = vec![(path.to_string(), 0)];
447
448        while let Some((current, d)) = queue.pop() {
449            if d > depth || visited.contains(&current) {
450                continue;
451            }
452            visited.insert(current.clone());
453            if current != path {
454                result.push(current.clone());
455            }
456
457            for edge in &self.edges {
458                if edge.from == current && edge.kind == "import" && !visited.contains(&edge.to) {
459                    queue.push((edge.to.clone(), d + 1));
460                }
461            }
462        }
463        result
464    }
465
466    pub fn get_related(&self, path: &str, depth: usize) -> Vec<String> {
467        let mut result = Vec::new();
468        let mut visited = std::collections::HashSet::new();
469        let mut queue: Vec<(String, usize)> = vec![(path.to_string(), 0)];
470
471        while let Some((current, d)) = queue.pop() {
472            if d > depth || visited.contains(&current) {
473                continue;
474            }
475            visited.insert(current.clone());
476            if current != path {
477                result.push(current.clone());
478            }
479
480            for edge in &self.edges {
481                if edge.from == current && !visited.contains(&edge.to) {
482                    queue.push((edge.to.clone(), d + 1));
483                }
484                if edge.to == current && !visited.contains(&edge.from) {
485                    queue.push((edge.from.clone(), d + 1));
486                }
487            }
488        }
489        result
490    }
491}
492
493/// Load the best available graph index, trying multiple root path variants.
494/// If no valid index exists, automatically scans the project to build one.
495/// This is the primary entry point — ensures zero-config usage.
496pub fn load_or_build(project_root: &str) -> ProjectIndex {
497    if std::env::var("LEAN_CTX_NO_INDEX").is_ok() {
498        return ProjectIndex::load(project_root).unwrap_or_else(|| ProjectIndex::new(project_root));
499    }
500
501    // Prefer stable absolute roots. Using "." as a cache key is fragile because
502    // it depends on the process cwd and can accidentally load the wrong project.
503    let root_abs = if project_root.trim().is_empty() || project_root == "." {
504        std::env::current_dir().ok().map_or_else(
505            || ".".to_string(),
506            |p| normalize_project_root(&p.to_string_lossy()),
507        )
508    } else {
509        normalize_project_root(project_root)
510    };
511
512    if !is_safe_scan_root(&root_abs) {
513        return ProjectIndex::new(&root_abs);
514    }
515
516    // Try the absolute/root-normalized path first.
517    if let Some(idx) = ProjectIndex::load(&root_abs)
518        && !idx.files.is_empty()
519    {
520        if index_looks_stale(&idx, &root_abs) {
521            tracing::warn!("[graph_index: stale index detected for {root_abs}; rebuilding]");
522            return scan(&root_abs);
523        }
524        return idx;
525    }
526
527    // CWD fallback: only use if CWD is a subdirectory of root_abs (same project)
528    if let Ok(cwd) = std::env::current_dir() {
529        let cwd_str = normalize_project_root(&cwd.to_string_lossy());
530        if cwd_str != root_abs
531            && cwd_str.starts_with(&root_abs)
532            && let Some(idx) = ProjectIndex::load(&cwd_str)
533            && !idx.files.is_empty()
534        {
535            if index_looks_stale(&idx, &cwd_str) {
536                return scan(&cwd_str);
537            }
538            return idx;
539        }
540    }
541
542    scan(&root_abs)
543}
544
545fn index_looks_stale(index: &ProjectIndex, root_abs: &str) -> bool {
546    if index.files.is_empty() {
547        return true;
548    }
549
550    // TTL check: rebuild if index is older than configured max_age_hours
551    if let Ok(scan_time) =
552        chrono::NaiveDateTime::parse_from_str(&index.last_scan, "%Y-%m-%d %H:%M:%S")
553    {
554        let cfg = crate::core::config::Config::load();
555        let effective_hours = cfg.archive_max_age_hours_effective();
556        let max_age = chrono::Duration::hours(effective_hours as i64);
557        let now = chrono::Local::now().naive_local();
558        if now.signed_duration_since(scan_time) > max_age {
559            tracing::info!(
560                "[graph_index: index is older than {}h — marking stale]",
561                effective_hours
562            );
563            return true;
564        }
565    }
566
567    // Contamination check: if index contains paths from common user directories,
568    // it was built from a too-broad root and must be rebuilt
569    const CONTAMINATION_MARKERS: &[&str] = &[
570        "Desktop/",
571        "Documents/",
572        "Downloads/",
573        "Pictures/",
574        "Music/",
575        "Videos/",
576        "Movies/",
577        "Library/",
578        ".cache/",
579        "snap/",
580    ];
581    let contaminated = index.files.keys().take(200).any(|rel| {
582        CONTAMINATION_MARKERS
583            .iter()
584            .any(|m| rel.starts_with(m) || rel.contains(&format!("/{m}")))
585    });
586    if contaminated {
587        tracing::warn!(
588            "[graph_index: index contains files from user directories (Desktop/Documents/...) — \
589             marking stale to force clean rebuild]"
590        );
591        return true;
592    }
593
594    let root_path = Path::new(root_abs);
595    // Sample up to 20 files for existence check (avoid scanning all files in large indices)
596    let sample_size = index.files.len().min(20);
597    for rel in index.files.keys().take(sample_size) {
598        let rel = rel.trim_start_matches(['/', '\\']);
599        if rel.is_empty() {
600            continue;
601        }
602        let abs = root_path.join(rel);
603        if !abs.exists() {
604            return true;
605        }
606    }
607
608    // Content-aware staleness: rescan only when source *content* actually
609    // changed. mtime is a cheap prefilter; the change is then confirmed against
610    // the stored content hash so a `touch`/checkout/format that leaves bytes
611    // unchanged never forces a needless rescan (covers edits and new files).
612    if source_content_changed_since_index(index, root_abs) {
613        tracing::info!("[graph_index: source content changed since last scan — marking stale]");
614        return true;
615    }
616
617    false
618}
619
620/// Modified time of the persisted index artifact, if one exists.
621///
622/// Since #696 C4 the property graph is the sole store, so staleness is measured
623/// against `graph.meta.json` (rewritten on every mirror) with the `graph.db`
624/// file as a fallback.
625fn index_file_mtime(root_abs: &str) -> Option<std::time::SystemTime> {
626    let dir = ProjectIndex::index_dir(root_abs)?;
627    for name in ["graph.meta.json", "graph.db"] {
628        if let Ok(meta) = std::fs::metadata(dir.join(name))
629            && let Ok(modified) = meta.modified()
630        {
631            return Some(modified);
632        }
633    }
634    None
635}
636
637/// Bounded staleness check that confirms *content* changes, not just mtimes.
638///
639/// An mtime newer than the persisted index only flags a *candidate*; the change
640/// is then confirmed by comparing the file's content hash against the stored
641/// `FileEntry.hash` (same `compute_hash` + `read_to_string` the scan uses, so
642/// the comparison is exact). This means a `touch`, `git checkout`, or formatter
643/// rewrite that leaves bytes unchanged no longer forces a needless rescan, while
644/// genuine edits and newly added files still mark the index stale.
645///
646/// Both the traversal and the number of confirming reads are capped: exceeding
647/// the read cap returns `true` (conservatively stale) instead of reading an
648/// unbounded amount. Removed files are handled by the earlier existence check.
649fn source_content_changed_since_index(index: &ProjectIndex, root_abs: &str) -> bool {
650    let Some(index_mtime) = index_file_mtime(root_abs) else {
651        // No persisted index yet — the existence/TTL checks above already decided.
652        return false;
653    };
654    // #735: excluded files must not flag the index stale (a change to CSV seed
655    // data would otherwise force needless graph rescans forever).
656    let index_filter = crate::core::index_filter::IndexFileFilter::effective();
657    let walker = ignore::WalkBuilder::new(root_abs)
658        // #1792: corpus membership follows git, not a leading dot.
659        .hidden(crate::core::walk_filter::SKIP_HIDDEN_IN_CONTENT_WALK)
660        .git_ignore(index_filter.respect_gitignore)
661        .git_global(index_filter.respect_gitignore)
662        .git_exclude(index_filter.respect_gitignore)
663        .require_git(false)
664        .max_depth(Some(20))
665        .filter_entry(crate::core::walk_filter::keep_entry)
666        .build();
667    const MAX_VISIT: usize = 50_000;
668    const MAX_CONFIRM_READS: usize = 4_000;
669    let mut visited = 0usize;
670    let mut confirm_reads = 0usize;
671    for entry in walker.filter_map(std::result::Result::ok) {
672        visited += 1;
673        if visited > MAX_VISIT {
674            break;
675        }
676        if !entry.file_type().is_some_and(|ft| ft.is_file()) {
677            continue;
678        }
679        let path = entry.path();
680        let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
681        if !is_indexable_ext(ext) {
682            continue;
683        }
684        // mtime prefilter: only files touched after the index are candidates.
685        let Ok(meta) = entry.metadata() else { continue };
686        let Ok(modified) = meta.modified() else {
687            continue;
688        };
689        if modified <= index_mtime {
690            continue;
691        }
692        // Candidate: confirm against the stored content hash.
693        let rel = make_relative(&path.to_string_lossy(), root_abs);
694        if index_filter.is_excluded(&rel.replace('\\', "/")) {
695            continue;
696        }
697        let Some(file_entry) = index.files.get(&rel) else {
698            // A newly added indexable file is genuinely new content.
699            return true;
700        };
701        confirm_reads += 1;
702        if confirm_reads > MAX_CONFIRM_READS {
703            // Too many candidates to verify cheaply — assume stale.
704            return true;
705        }
706        match crate::core::text_decode::read_text(path) {
707            // Bytes unchanged despite a newer mtime → not a real change.
708            Ok(content) if compute_hash(&content) == file_entry.hash => {}
709            // Edited content, or no longer readable as it was at scan time.
710            _ => return true,
711        }
712    }
713    false
714}
715
716/// Delete the persisted graph-index artifacts for a project so the next scan
717/// rebuilds from scratch. Backs `graph build --force`.
718///
719/// Since #696 C4 the property graph (`graph.db` + `graph.meta.json`) is the sole
720/// store; the legacy JSON names are still removed so upgrades clear stale files.
721pub fn purge_index(project_root: &str) {
722    if let Some(dir) = ProjectIndex::index_dir(project_root) {
723        for name in [
724            "graph.db",
725            "graph.db-wal",
726            "graph.db-shm",
727            "graph.meta.json",
728            "index.json.zst",
729            "index.json",
730            "call_graph.json.zst",
731        ] {
732            let _ = std::fs::remove_file(dir.join(name));
733        }
734    }
735}
736
737pub fn scan(project_root: &str) -> ProjectIndex {
738    scan_inner(project_root).0
739}
740
741pub fn scan_with_content_cache(project_root: &str) -> (ProjectIndex, HashMap<String, String>) {
742    scan_inner(project_root)
743}
744
745fn scan_inner(project_root: &str) -> (ProjectIndex, HashMap<String, String>) {
746    if std::env::var("LEAN_CTX_NO_INDEX").is_ok() {
747        tracing::info!("[graph_index: LEAN_CTX_NO_INDEX set — skipping scan]");
748        return (ProjectIndex::new(project_root), HashMap::new());
749    }
750
751    let project_root = normalize_project_root(project_root);
752
753    if !is_safe_scan_root(&project_root) {
754        tracing::debug!("[graph_index: scan aborted for unsafe root {project_root}]");
755        return (ProjectIndex::new(&project_root), HashMap::new());
756    }
757
758    let lock_name = format!(
759        "graph-idx-{}",
760        &crate::core::index_namespace::namespace_hash(Path::new(&project_root))[..8]
761    );
762    let _lock = crate::core::startup_guard::try_acquire_lock(
763        &lock_name,
764        std::time::Duration::from_millis(800),
765        std::time::Duration::from_mins(3),
766    );
767    if _lock.is_none() {
768        tracing::info!(
769            "[graph_index: another process is scanning {project_root} — returning cached or empty]"
770        );
771        return (
772            ProjectIndex::load(&project_root).unwrap_or_else(|| ProjectIndex::new(&project_root)),
773            HashMap::new(),
774        );
775    }
776
777    let existing = ProjectIndex::load(&project_root);
778    let mut index = ProjectIndex::new(&project_root);
779
780    // Borrow prior symbols instead of cloning every hash, key, and SymbolEntry up
781    // front. Reused symbols are cloned only for the current scan batch as they
782    // move into the replacement index, avoiding a third full-index copy.
783    let previous_symbols = existing
784        .as_ref()
785        .map(previous_symbols_by_file)
786        .unwrap_or_default();
787
788    let cfg = crate::core::config::Config::load();
789    // #735: shared corpus filter — same membership decision as the BM25 walk.
790    let index_filter = crate::core::index_filter::IndexFileFilter::resolve(&cfg);
791
792    let walker = ignore::WalkBuilder::new(&project_root)
793        // #1792: kept identical to the BM25 walk, as the comment above promises.
794        .hidden(crate::core::walk_filter::SKIP_HIDDEN_IN_CONTENT_WALK)
795        .git_ignore(index_filter.respect_gitignore)
796        .git_global(index_filter.respect_gitignore)
797        .git_exclude(index_filter.respect_gitignore)
798        .require_git(false)
799        .max_depth(Some(20))
800        .filter_entry(crate::core::walk_filter::keep_entry)
801        .build();
802
803    let extra_ignores: Vec<glob::Pattern> = cfg
804        .extra_ignore_patterns
805        .iter()
806        .filter_map(|p| glob::Pattern::new(p).ok())
807        .collect();
808
809    let mut scanned = 0usize;
810    let mut reused = 0usize;
811    let mut entries_visited = 0usize;
812    let mut content_cache: HashMap<String, String> = HashMap::new();
813    let mut content_cache_bytes: usize = 0;
814    const CONTENT_CACHE_MAX_BYTES: usize = 256 * 1024 * 1024; // #790: cap at 256MB
815    let max_files = if cfg.graph_index_max_files == 0 {
816        usize::MAX // unlimited
817    } else {
818        cfg.graph_index_max_files as usize
819    };
820    const MAX_ENTRIES_VISITED: usize = 500_000;
821    const MAX_FILE_SIZE_BYTES: u64 = 2 * 1024 * 1024; // 2 MB per file
822    /// Maximum phase-2 fan-out. Actual batches shrink with guardian headroom.
823    const SCAN_BATCH_FILES: usize = 500;
824    const SCAN_MIN_BATCH_FILES: usize = 1;
825    // Per-file scan: content string (~20 KB avg) + SHA-256 state +
826    // signature extraction + line/token counts. Lighter than BM25
827    // because no chunk splitting or lowered-token vectors are built.
828    const SCAN_EST_TRANSIENT_PER_FILE: u64 = 192 * 1024;
829    let scan_deadline = std::time::Instant::now() + std::time::Duration::from_mins(5);
830
831    // #934: two-phase scan. Phase 1 walks the tree sequentially (cheap; it
832    // carries the traversal caps / timeout / memory early-breaks) and collects
833    // the files to index. Phase 2 fans the expensive per-file signature
834    // extraction across a rayon pool — pure and thread-safe (the tree-sitter
835    // parser is `thread_local!`; `previous_symbols`/`existing` are read-only). Phase 3
836    // merges sequentially: `files`/`symbols` are keyed per file, so the result is
837    // identical to a sequential scan (edges are built and sorted afterwards).
838    let mut targets: Vec<(String, String, String)> = Vec::new();
839    for entry in walker.filter_map(std::result::Result::ok) {
840        entries_visited += 1;
841        if entries_visited > MAX_ENTRIES_VISITED {
842            tracing::warn!(
843                "[graph_index: walked {entries_visited} entries — aborting scan to prevent \
844                 runaway traversal. Indexed {} files so far.]",
845                targets.len()
846            );
847            break;
848        }
849        if entries_visited.is_multiple_of(5000) {
850            if std::time::Instant::now() > scan_deadline {
851                tracing::warn!(
852                    "[graph_index: scan timeout (120s) after {entries_visited} entries — \
853                     saving partial index with {} files]",
854                    targets.len()
855                );
856                break;
857            }
858            if crate::core::memory_guard::abort_requested() {
859                tracing::warn!(
860                    "[graph_index: memory pressure abort after {entries_visited} entries — \
861                     saving partial index with {} files]",
862                    targets.len()
863                );
864                break;
865            }
866            if crate::core::memory_guard::is_under_pressure() {
867                tracing::warn!(
868                    "[graph_index: memory pressure detected at {entries_visited} entries — \
869                     stopping scan with {} files]",
870                    targets.len()
871                );
872                break;
873            }
874            if let Some(ref g) = _lock {
875                g.touch();
876            }
877        }
878
879        if !entry.file_type().is_some_and(|ft| ft.is_file()) {
880            continue;
881        }
882
883        if entry.path_is_symlink() {
884            continue;
885        }
886        let file_path = normalize_absolute_path(&entry.path().to_string_lossy());
887
888        if !std::path::Path::new(&file_path).starts_with(std::path::Path::new(&project_root)) {
889            continue;
890        }
891
892        if let Ok(meta) = std::fs::symlink_metadata(&file_path) {
893            if meta.file_type().is_symlink() || !meta.is_file() {
894                continue;
895            }
896            if meta.len() > MAX_FILE_SIZE_BYTES {
897                tracing::debug!(
898                    "[graph_index: skipping {file_path} — {:.1}MB exceeds {}MB limit]",
899                    meta.len() as f64 / 1_048_576.0,
900                    MAX_FILE_SIZE_BYTES / (1024 * 1024),
901                );
902                continue;
903            }
904        }
905
906        let ext = Path::new(&file_path)
907            .extension()
908            .and_then(|e| e.to_str())
909            .unwrap_or("");
910
911        if !is_indexable_ext(ext) {
912            continue;
913        }
914
915        let rel = make_relative(&file_path, &project_root);
916        if extra_ignores.iter().any(|p| p.matches(&rel)) {
917            continue;
918        }
919        if index_filter.is_excluded(&rel.replace('\\', "/")) {
920            continue;
921        }
922
923        if max_files != usize::MAX && targets.len() >= max_files {
924            tracing::info!(
925                "[graph_index: reached configured limit of {} files. Set graph_index_max_files = 0 for unlimited.]",
926                max_files
927            );
928            break;
929        }
930
931        // Own `ext` before moving `file_path` (it borrows from it).
932        let ext = ext.to_string();
933        targets.push((file_path, rel, ext));
934    }
935
936    // #790: admission control — check if parallel fan-out fits memory headroom.
937    // Degrades to sequential (with per-file pressure breaks) on huge corpora,
938    // mirroring BM25's admission gate.
939    let target_rels: Vec<String> = targets.iter().map(|(_, r, _)| r.clone()).collect();
940    let admission = crate::core::index_admission::admit_files(
941        crate::core::index_admission::BuildKind::GraphScan,
942        std::path::Path::new(&project_root),
943        &target_rels,
944    );
945    let parallel = admission.parallel_ok && !crate::core::memory_guard::is_under_pressure();
946    // One gateway policy snapshot for the whole scan (E3: stored excerpts are admitted).
947    let store_admission = StoreAdmission::current();
948    let mut files_done = 0;
949    while files_done < targets.len() {
950        if crate::core::memory_guard::abort_requested() {
951            tracing::warn!(
952                "[graph_index: aborting scan after {files_done} files due to critical memory pressure]"
953            );
954            break;
955        }
956        if crate::core::memory_guard::is_under_pressure() {
957            tracing::warn!(
958                "[graph_index: stopping scan after {files_done} files due to memory pressure]"
959            );
960            break;
961        }
962        let batch_size = crate::core::memory_guard::adaptive_batch_size(
963            SCAN_MIN_BATCH_FILES,
964            SCAN_BATCH_FILES,
965            SCAN_EST_TRANSIENT_PER_FILE,
966        );
967        let batch_end = (files_done + batch_size).min(targets.len());
968        let results = process_scan_targets(
969            &targets[files_done..batch_end],
970            &previous_symbols,
971            existing.as_ref(),
972            parallel,
973            &store_admission,
974        );
975        for r in results {
976            if r.reused {
977                reused += 1;
978            } else {
979                scanned += 1;
980            }
981            index.files.insert(r.rel.clone(), r.file_entry);
982            for (key, sym) in r.symbols {
983                index.symbols.insert(key, sym);
984            }
985            if content_cache_bytes < CONTENT_CACHE_MAX_BYTES {
986                content_cache_bytes += r.content.len();
987                content_cache.insert(r.rel, r.content);
988            }
989        }
990        files_done = batch_end;
991        crate::core::memory_guard::jemalloc_purge();
992    }
993
994    index.rebuild_interner();
995    // #1494: the scan_deadline covers the entire indexing pipeline, including
996    // edge-building, so a ~7k-file tree cannot spin unbounded on CPU after IO.
997    build_edges_cached(&mut index, &content_cache, scan_deadline);
998
999    if let Err(e) = index.save() {
1000        tracing::warn!("could not save graph index: {e}");
1001    }
1002
1003    tracing::debug!(
1004        "[graph_index: {} files ({} scanned, {} reused), {} symbols, {} edges]",
1005        index.file_count(),
1006        scanned,
1007        reused,
1008        index.symbol_count(),
1009        index.edge_count()
1010    );
1011
1012    (index, content_cache)
1013}
1014
1015/// Borrowed previous-scan symbols grouped by file. This index stores only
1016/// references, so incremental scans do not clone the complete prior index before
1017/// processing starts.
1018type PreviousSymbols<'a> = HashMap<&'a str, Vec<(&'a str, &'a SymbolEntry)>>;
1019
1020fn previous_symbols_by_file(index: &ProjectIndex) -> PreviousSymbols<'_> {
1021    let mut by_file: PreviousSymbols<'_> = HashMap::new();
1022    for (key, symbol) in &index.symbols {
1023        by_file
1024            .entry(symbol.file.as_str())
1025            .or_default()
1026            .push((key.as_str(), symbol));
1027    }
1028    by_file
1029}
1030
1031/// One file's contribution to the scan, produced off-thread by
1032/// [`process_scan_file`] and merged sequentially by [`scan_inner`].
1033#[derive(Debug, PartialEq)]
1034struct ScanFileResult {
1035    rel: String,
1036    file_entry: FileEntry,
1037    /// `(key, symbol)` pairs in signature order; `key` is `"<rel>::<name>"`.
1038    symbols: Vec<(String, SymbolEntry)>,
1039    content: String,
1040    reused: bool,
1041}
1042
1043/// Pure, thread-safe per-file scan work: read, hash, reuse-check against the
1044/// previous index, then extract signatures + file metadata. Returns `None` when
1045/// the file cannot be read (the sequential scan would `continue` past it).
1046fn process_scan_file(
1047    file_path: &str,
1048    rel: &str,
1049    ext: &str,
1050    previous_symbols: &PreviousSymbols<'_>,
1051    existing: Option<&ProjectIndex>,
1052    admission: &StoreAdmission,
1053) -> Option<ScanFileResult> {
1054    if crate::core::memory_guard::abort_requested() {
1055        return None;
1056    }
1057    let content = crate::core::text_decode::read_text(file_path).ok()?;
1058    let hash = compute_hash(&content);
1059
1060    // Unchanged file with a prior entry: reuse verbatim (no re-parse). Clone
1061    // only this file's symbols into the replacement index; the complete prior
1062    // symbol table remains borrowed throughout the scan.
1063    if let Some(old_entry) = existing.and_then(|p| p.files.get(rel))
1064        && old_entry.hash == hash
1065    {
1066        let symbols = previous_symbols
1067            .get(rel)
1068            .into_iter()
1069            .flatten()
1070            .map(|(key, symbol)| ((*key).to_string(), (*symbol).clone()))
1071            .collect();
1072        return Some(ScanFileResult {
1073            rel: rel.to_string(),
1074            file_entry: old_entry.clone(),
1075            symbols,
1076            content,
1077            reused: true,
1078        });
1079    }
1080
1081    if crate::core::memory_guard::abort_requested() {
1082        return None;
1083    }
1084
1085    let sigs = signatures::extract_signatures(&content, ext);
1086    let line_count = content.lines().count();
1087    let token_count = crate::core::tokens::count_tokens(&content);
1088    // The summary is source text that enters a derived store (E3): it is
1089    // admitted like every other stored excerpt, and a restricted file has none.
1090    let summary = admission
1091        .admit(&extract_summary(&content), std::path::Path::new(file_path))
1092        .unwrap_or_default();
1093
1094    let exports: Vec<String> = sigs
1095        .iter()
1096        .filter(|s| s.is_exported)
1097        .map(|s| s.name.clone())
1098        .collect();
1099
1100    let file_entry = FileEntry {
1101        path: rel.to_string(),
1102        hash,
1103        language: ext.to_string(),
1104        line_count,
1105        token_count,
1106        exports,
1107        summary,
1108    };
1109
1110    let symbols: Vec<(String, SymbolEntry)> = sigs
1111        .iter()
1112        .map(|sig| {
1113            let (start, end) = sig
1114                .start_line
1115                .zip(sig.end_line)
1116                .unwrap_or_else(|| find_symbol_range(&content, sig));
1117            let key = format!("{rel}::{}", sig.name);
1118            (
1119                key,
1120                SymbolEntry {
1121                    file: rel.to_string(),
1122                    name: sig.name.clone(),
1123                    kind: sig.kind.to_string(),
1124                    start_line: start,
1125                    end_line: end,
1126                    is_exported: sig.is_exported,
1127                },
1128            )
1129        })
1130        .collect();
1131
1132    Some(ScanFileResult {
1133        rel: rel.to_string(),
1134        file_entry,
1135        symbols,
1136        content,
1137        reused: false,
1138    })
1139}
1140
1141/// Run [`process_scan_file`] over every target. `par_iter().collect()` preserves
1142/// input order, so the [`scan_inner`] merge is order-stable whether or not the
1143/// pool is used; the sequential branch is the memory-pressure fallback and an
1144/// equivalence anchor for the determinism tests.
1145fn process_scan_targets(
1146    targets: &[(String, String, String)],
1147    previous_symbols: &PreviousSymbols<'_>,
1148    existing: Option<&ProjectIndex>,
1149    parallel: bool,
1150    admission: &StoreAdmission,
1151) -> Vec<ScanFileResult> {
1152    if parallel {
1153        targets
1154            .par_iter()
1155            .filter_map(|(file_path, rel, ext)| {
1156                process_scan_file(file_path, rel, ext, previous_symbols, existing, admission)
1157            })
1158            .collect()
1159    } else {
1160        targets
1161            .iter()
1162            .filter_map(|(file_path, rel, ext)| {
1163                process_scan_file(file_path, rel, ext, previous_symbols, existing, admission)
1164            })
1165            .collect()
1166    }
1167}
1168
1169pub(crate) fn find_symbol_range(content: &str, sig: &signatures::Signature) -> (usize, usize) {
1170    let lines: Vec<&str> = content.lines().collect();
1171    let mut start = 0;
1172
1173    for (i, line) in lines.iter().enumerate() {
1174        if line.contains(&sig.name) {
1175            let trimmed = line.trim();
1176            let is_def = trimmed.starts_with("fn ")
1177                || trimmed.starts_with("pub fn ")
1178                || trimmed.starts_with("pub(crate) fn ")
1179                || trimmed.starts_with("async fn ")
1180                || trimmed.starts_with("pub async fn ")
1181                || trimmed.starts_with("struct ")
1182                || trimmed.starts_with("pub struct ")
1183                || trimmed.starts_with("enum ")
1184                || trimmed.starts_with("pub enum ")
1185                || trimmed.starts_with("trait ")
1186                || trimmed.starts_with("pub trait ")
1187                || trimmed.starts_with("impl ")
1188                || trimmed.starts_with("class ")
1189                || trimmed.starts_with("export class ")
1190                || trimmed.starts_with("export function ")
1191                || trimmed.starts_with("export async function ")
1192                || trimmed.starts_with("function ")
1193                || trimmed.starts_with("async function ")
1194                || trimmed.starts_with("def ")
1195                || trimmed.starts_with("async def ")
1196                || trimmed.starts_with("func ")
1197                || trimmed.starts_with("interface ")
1198                || trimmed.starts_with("export interface ")
1199                || trimmed.starts_with("type ")
1200                || trimmed.starts_with("export type ")
1201                || trimmed.starts_with("const ")
1202                || trimmed.starts_with("export const ")
1203                || trimmed.starts_with("fun ")
1204                || trimmed.starts_with("private fun ")
1205                || trimmed.starts_with("public fun ")
1206                || trimmed.starts_with("internal fun ")
1207                || trimmed.starts_with("class ")
1208                || trimmed.starts_with("data class ")
1209                || trimmed.starts_with("sealed class ")
1210                || trimmed.starts_with("sealed interface ")
1211                || trimmed.starts_with("enum class ")
1212                || trimmed.starts_with("object ")
1213                || trimmed.starts_with("private object ")
1214                || trimmed.starts_with("interface ")
1215                || trimmed.starts_with("typealias ")
1216                || trimmed.starts_with("private typealias ");
1217            if is_def {
1218                start = i + 1;
1219                break;
1220            }
1221        }
1222    }
1223
1224    if start == 0 {
1225        return (1, lines.len().min(20));
1226    }
1227
1228    let base_indent = lines
1229        .get(start - 1)
1230        .map_or(0, |l| l.len() - l.trim_start().len());
1231
1232    let mut end = start;
1233    let mut brace_depth: i32 = 0;
1234    let mut found_open = false;
1235
1236    for (i, line) in lines.iter().enumerate().skip(start - 1) {
1237        for ch in line.chars() {
1238            if ch == '{' {
1239                brace_depth += 1;
1240                found_open = true;
1241            } else if ch == '}' {
1242                brace_depth -= 1;
1243            }
1244        }
1245
1246        end = i + 1;
1247
1248        if found_open && brace_depth <= 0 {
1249            break;
1250        }
1251
1252        if !found_open && i > start {
1253            let indent = line.len() - line.trim_start().len();
1254            if indent <= base_indent && !line.trim().is_empty() && i > start {
1255                end = i;
1256                break;
1257            }
1258        }
1259
1260        if end - start > 200 {
1261            break;
1262        }
1263    }
1264
1265    (start, end)
1266}
1267
1268fn extract_summary(content: &str) -> String {
1269    for line in content.lines().take(20) {
1270        let trimmed = line.trim();
1271        if trimmed.is_empty()
1272            || trimmed.starts_with("//")
1273            || trimmed.starts_with('#')
1274            || trimmed.starts_with("/*")
1275            || trimmed.starts_with('*')
1276            || trimmed.starts_with("use ")
1277            || trimmed.starts_with("import ")
1278            || trimmed.starts_with("from ")
1279            || trimmed.starts_with("require(")
1280            || trimmed.starts_with("package ")
1281        {
1282            continue;
1283        }
1284        return trimmed.chars().take(120).collect();
1285    }
1286    String::new()
1287}
1288
1289fn compute_hash(content: &str) -> String {
1290    use std::collections::hash_map::DefaultHasher;
1291    use std::hash::{Hash, Hasher};
1292
1293    let mut hasher = DefaultHasher::new();
1294    content.hash(&mut hasher);
1295    format!("{:016x}", hasher.finish())
1296}
1297
1298#[cfg(test)]
1299fn short_hash(input: &str) -> String {
1300    use std::collections::hash_map::DefaultHasher;
1301    use std::hash::{Hash, Hasher};
1302
1303    let mut hasher = DefaultHasher::new();
1304    input.hash(&mut hasher);
1305    format!("{:08x}", hasher.finish() & 0xFFFF_FFFF)
1306}
1307
1308fn make_relative(path: &str, root: &str) -> String {
1309    graph_relative_key(path, root)
1310}
1311
1312fn is_indexable_ext(ext: &str) -> bool {
1313    crate::core::language_capabilities::is_indexable_ext(ext)
1314}
1315
1316#[cfg(test)]
1317fn kotlin_package_name(content: &str) -> Option<String> {
1318    content.lines().map(str::trim).find_map(|line| {
1319        line.strip_prefix("package ")
1320            .map(|rest| rest.trim().trim_end_matches(';').to_string())
1321    })
1322}