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