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