1use 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
25const INDEX_VERSION: u32 = 7;
28
29use 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
43fn dir_has_project_marker(dir: &Path) -> bool {
49 crate::core::pathutil::has_project_marker(dir)
50}
51
52fn 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
72fn 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 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 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 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 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 "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 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 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 if !breadth_markers.iter().any(|m| p.join(m).exists())
207 && !dir_has_dotnet_project(p)
208 && !is_inside_project(p)
209 {
210 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
232fn 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 #[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 #[cfg(test)]
308 pub(crate) 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: chrono::Local::now().format("%Y-%m-%d %H:%M:%S").to_string(),
338 files: HashMap::new(),
339 edges: Vec::new(),
340 symbols: HashMap::new(),
341 interner: file_id::PathInterner::new(),
342 }
343 }
344
345 pub(crate) fn rebuild_interner(&mut self) {
349 let mut interner = file_id::PathInterner::with_capacity(self.files.len());
350 for key in self.files.keys() {
351 interner.intern(key);
352 }
353 self.interner = interner;
354 }
355
356 pub fn index_dir(project_root: &str) -> Option<std::path::PathBuf> {
357 let normalized = normalize_project_root(project_root);
358 let hash = crate::core::project_hash::hash_project_root(&normalized);
359 crate::core::data_dir::lean_ctx_data_dir()
360 .ok()
361 .map(|d| d.join("graphs").join(hash))
362 }
363
364 pub fn load(project_root: &str) -> Option<Self> {
370 let graph = crate::core::property_graph::CodeGraph::open(project_root).ok()?;
371 if graph.file_catalog_count().unwrap_or(0) == 0 {
372 return None;
373 }
374 let provider = crate::core::graph_provider::GraphProvider::PropertyGraph(graph);
375 let mut index = provider.materialize_project_index(project_root);
376 index.rebuild_interner();
377 Some(index)
378 }
379
380 pub fn save(&self) -> Result<(), String> {
385 crate::core::property_graph::mirror_index(&self.project_root, self)
386 .map_err(|e| e.to_string())
387 }
388
389 pub fn purge_stale_indices() {
392 let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() else {
393 return;
394 };
395 let graphs_dir = data_dir.join("graphs");
396 let Ok(entries) = std::fs::read_dir(&graphs_dir) else {
397 return;
398 };
399 let cfg = crate::core::config::Config::load();
400 let max_age_secs = cfg.archive_max_age_hours_effective() * 3600;
401
402 for entry in entries.filter_map(Result::ok) {
403 let path = entry.path();
404 if !path.is_dir() {
405 continue;
406 }
407 let meta = path.join("graph.meta.json");
411 let db = path.join("graph.db");
412 let index_file = if meta.exists() {
413 &meta
414 } else if db.exists() {
415 &db
416 } else {
417 continue;
418 };
419
420 let is_old = index_file
421 .metadata()
422 .and_then(|m| m.modified())
423 .is_ok_and(|mtime| {
424 mtime
425 .elapsed()
426 .is_ok_and(|age| age.as_secs() > max_age_secs)
427 });
428
429 if is_old {
430 tracing::info!("[graph_index: purging stale index at {}]", path.display());
431 let _ = std::fs::remove_dir_all(&path);
432 }
433 }
434 }
435
436 pub fn file_count(&self) -> usize {
437 self.files.len()
438 }
439
440 pub fn symbol_count(&self) -> usize {
441 self.symbols.len()
442 }
443
444 pub fn edge_count(&self) -> usize {
445 self.edges.len()
446 }
447
448 pub fn get_symbol(&self, key: &str) -> Option<&SymbolEntry> {
449 self.symbols.get(key)
450 }
451
452 pub fn get_reverse_deps(&self, path: &str, depth: usize) -> Vec<String> {
453 let mut result = Vec::new();
454 let mut visited = std::collections::HashSet::new();
455 let mut queue: Vec<(String, usize)> = vec![(path.to_string(), 0)];
456
457 while let Some((current, d)) = queue.pop() {
458 if d > depth || visited.contains(¤t) {
459 continue;
460 }
461 visited.insert(current.clone());
462 if current != path {
463 result.push(current.clone());
464 }
465
466 for edge in &self.edges {
467 if edge.to == current && edge.kind == "import" && !visited.contains(&edge.from) {
468 queue.push((edge.from.clone(), d + 1));
469 }
470 }
471 }
472 result
473 }
474
475 pub fn get_forward_deps(&self, path: &str, depth: usize) -> Vec<String> {
478 let mut result = Vec::new();
479 let mut visited = std::collections::HashSet::new();
480 let mut queue: Vec<(String, usize)> = vec![(path.to_string(), 0)];
481
482 while let Some((current, d)) = queue.pop() {
483 if d > depth || visited.contains(¤t) {
484 continue;
485 }
486 visited.insert(current.clone());
487 if current != path {
488 result.push(current.clone());
489 }
490
491 for edge in &self.edges {
492 if edge.from == current && edge.kind == "import" && !visited.contains(&edge.to) {
493 queue.push((edge.to.clone(), d + 1));
494 }
495 }
496 }
497 result
498 }
499
500 pub fn get_related(&self, path: &str, depth: usize) -> Vec<String> {
504 self.get_related_served(path, depth, &|_: &str| true)
505 }
506
507 pub(crate) fn get_related_served(
511 &self,
512 path: &str,
513 depth: usize,
514 served: &dyn Fn(&str) -> bool,
515 ) -> Vec<String> {
516 let mut result = Vec::new();
517 let mut visited = std::collections::HashSet::new();
518 let mut queue: Vec<(String, usize)> = vec![(path.to_string(), 0)];
519
520 while let Some((current, d)) = queue.pop() {
521 if d > depth || visited.contains(¤t) {
522 continue;
523 }
524 visited.insert(current.clone());
525 if current != path && !served(¤t) {
526 continue;
527 }
528 if current != path {
529 result.push(current.clone());
530 }
531
532 for edge in &self.edges {
533 if edge.from == current && !visited.contains(&edge.to) {
534 queue.push((edge.to.clone(), d + 1));
535 }
536 if edge.to == current && !visited.contains(&edge.from) {
537 queue.push((edge.from.clone(), d + 1));
538 }
539 }
540 }
541 result
542 }
543}
544
545pub fn load_or_build(project_root: &str) -> ProjectIndex {
549 if std::env::var("LEAN_CTX_NO_INDEX").is_ok() {
550 return ProjectIndex::load(project_root).unwrap_or_else(|| ProjectIndex::new(project_root));
551 }
552
553 let root_abs = if project_root.trim().is_empty() || project_root == "." {
556 std::env::current_dir().ok().map_or_else(
557 || ".".to_string(),
558 |p| normalize_project_root(&p.to_string_lossy()),
559 )
560 } else {
561 normalize_project_root(project_root)
562 };
563
564 if !is_safe_scan_root(&root_abs) {
565 return ProjectIndex::new(&root_abs);
566 }
567
568 if let Some(idx) = ProjectIndex::load(&root_abs)
570 && !idx.files.is_empty()
571 {
572 if index_looks_stale(&idx, &root_abs) {
573 tracing::warn!("[graph_index: stale index detected for {root_abs}; rebuilding]");
574 return scan(&root_abs);
575 }
576 return idx;
577 }
578
579 if let Ok(cwd) = std::env::current_dir() {
581 let cwd_str = normalize_project_root(&cwd.to_string_lossy());
582 if cwd_str != root_abs
583 && cwd_str.starts_with(&root_abs)
584 && let Some(idx) = ProjectIndex::load(&cwd_str)
585 && !idx.files.is_empty()
586 {
587 if index_looks_stale(&idx, &cwd_str) {
588 return scan(&cwd_str);
589 }
590 return idx;
591 }
592 }
593
594 scan(&root_abs)
595}
596
597fn index_looks_stale(index: &ProjectIndex, root_abs: &str) -> bool {
598 if index.files.is_empty() {
599 return true;
600 }
601
602 if index
605 .files
606 .keys()
607 .any(|rel| crate::core::io_boundary::is_secret_like(Path::new(rel)).is_some())
608 {
609 return true;
610 }
611
612 if let Ok(scan_time) =
614 chrono::NaiveDateTime::parse_from_str(&index.last_scan, "%Y-%m-%d %H:%M:%S")
615 {
616 let cfg = crate::core::config::Config::load();
617 let effective_hours = cfg.archive_max_age_hours_effective();
618 let max_age = chrono::Duration::hours(effective_hours as i64);
619 let now = chrono::Local::now().naive_local();
620 if now.signed_duration_since(scan_time) > max_age {
621 tracing::info!(
622 "[graph_index: index is older than {}h — marking stale]",
623 effective_hours
624 );
625 return true;
626 }
627 }
628
629 const CONTAMINATION_MARKERS: &[&str] = &[
632 "Desktop/",
633 "Documents/",
634 "Downloads/",
635 "Pictures/",
636 "Music/",
637 "Videos/",
638 "Movies/",
639 "Library/",
640 ".cache/",
641 "snap/",
642 ];
643 let contaminated = index.files.keys().take(200).any(|rel| {
644 CONTAMINATION_MARKERS
645 .iter()
646 .any(|m| rel.starts_with(m) || rel.contains(&format!("/{m}")))
647 });
648 if contaminated {
649 tracing::warn!(
650 "[graph_index: index contains files from user directories (Desktop/Documents/...) — \
651 marking stale to force clean rebuild]"
652 );
653 return true;
654 }
655
656 let root_path = Path::new(root_abs);
657 let sample_size = index.files.len().min(20);
659 for rel in index.files.keys().take(sample_size) {
660 let rel = rel.trim_start_matches(['/', '\\']);
661 if rel.is_empty() {
662 continue;
663 }
664 let abs = root_path.join(rel);
665 if !abs.exists() {
666 return true;
667 }
668 }
669
670 if source_content_changed_since_index(index, root_abs) {
675 tracing::info!("[graph_index: source content changed since last scan — marking stale]");
676 return true;
677 }
678
679 false
680}
681
682fn index_file_mtime(root_abs: &str) -> Option<std::time::SystemTime> {
688 let dir = ProjectIndex::index_dir(root_abs)?;
689 for name in ["graph.meta.json", "graph.db"] {
690 if let Ok(meta) = std::fs::metadata(dir.join(name))
691 && let Ok(modified) = meta.modified()
692 {
693 return Some(modified);
694 }
695 }
696 None
697}
698
699fn source_content_changed_since_index(index: &ProjectIndex, root_abs: &str) -> bool {
712 let Some(index_mtime) = index_file_mtime(root_abs) else {
713 return false;
715 };
716 let index_filter = crate::core::index_filter::IndexFileFilter::effective();
719 let walker = ignore::WalkBuilder::new(root_abs)
720 .hidden(crate::core::walk_filter::SKIP_HIDDEN_IN_CONTENT_WALK)
722 .git_ignore(index_filter.respect_gitignore)
723 .git_global(index_filter.respect_gitignore)
724 .git_exclude(index_filter.respect_gitignore)
725 .require_git(false)
726 .max_depth(Some(20))
727 .filter_entry(crate::core::walk_filter::keep_entry)
728 .build();
729 const MAX_VISIT: usize = 50_000;
730 const MAX_CONFIRM_READS: usize = 4_000;
731 let mut visited = 0usize;
732 let mut confirm_reads = 0usize;
733 for entry in walker.filter_map(std::result::Result::ok) {
734 visited += 1;
735 if visited > MAX_VISIT {
736 break;
737 }
738 if !entry.file_type().is_some_and(|ft| ft.is_file()) {
739 continue;
740 }
741 let path = entry.path();
742 let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
743 if !is_indexable_ext(ext) {
744 continue;
745 }
746 let Ok(meta) = entry.metadata() else { continue };
748 let Ok(modified) = meta.modified() else {
749 continue;
750 };
751 if modified <= index_mtime {
752 continue;
753 }
754 let rel = make_relative(&path.to_string_lossy(), root_abs);
756 if index_filter.is_excluded(&rel.replace('\\', "/"))
757 || crate::core::io_boundary::is_secret_like(Path::new(&rel)).is_some()
758 {
759 continue;
760 }
761 let Some(file_entry) = index.files.get(&rel) else {
762 return true;
764 };
765 confirm_reads += 1;
766 if confirm_reads > MAX_CONFIRM_READS {
767 return true;
769 }
770 match crate::core::text_decode::read_text(path) {
771 Ok(content) if compute_hash(&content) == file_entry.hash => {}
773 _ => return true,
775 }
776 }
777 false
778}
779
780pub fn purge_index(project_root: &str) {
786 if let Some(dir) = ProjectIndex::index_dir(project_root) {
787 for name in [
788 "graph.db",
789 "graph.db-wal",
790 "graph.db-shm",
791 "graph.meta.json",
792 "index.json.zst",
793 "index.json",
794 "call_graph.json.zst",
795 ] {
796 let _ = std::fs::remove_file(dir.join(name));
797 }
798 }
799}
800
801pub fn scan(project_root: &str) -> ProjectIndex {
802 scan_inner(project_root).0
803}
804
805pub fn scan_with_content_cache(project_root: &str) -> (ProjectIndex, HashMap<String, String>) {
806 scan_inner(project_root)
807}
808
809fn scan_inner(project_root: &str) -> (ProjectIndex, HashMap<String, String>) {
810 if std::env::var("LEAN_CTX_NO_INDEX").is_ok() {
811 tracing::info!("[graph_index: LEAN_CTX_NO_INDEX set — skipping scan]");
812 return (ProjectIndex::new(project_root), HashMap::new());
813 }
814
815 let project_root = normalize_project_root(project_root);
816
817 if !is_safe_scan_root(&project_root) {
818 tracing::debug!("[graph_index: scan aborted for unsafe root {project_root}]");
819 return (ProjectIndex::new(&project_root), HashMap::new());
820 }
821
822 let lock_name = format!(
823 "graph-idx-{}",
824 &crate::core::index_namespace::namespace_hash(Path::new(&project_root))[..8]
825 );
826 let _lock = crate::core::startup_guard::try_acquire_lock(
827 &lock_name,
828 std::time::Duration::from_millis(800),
829 std::time::Duration::from_mins(3),
830 );
831 if _lock.is_none() {
832 tracing::info!(
833 "[graph_index: another process is scanning {project_root} — returning cached or empty]"
834 );
835 return (
836 ProjectIndex::load(&project_root).unwrap_or_else(|| ProjectIndex::new(&project_root)),
837 HashMap::new(),
838 );
839 }
840
841 let existing = ProjectIndex::load(&project_root);
842 let mut index = ProjectIndex::new(&project_root);
843
844 let previous_symbols = existing
848 .as_ref()
849 .map(previous_symbols_by_file)
850 .unwrap_or_default();
851
852 let cfg = crate::core::config::Config::load();
853 let index_filter = crate::core::index_filter::IndexFileFilter::resolve(&cfg);
855
856 let walker = ignore::WalkBuilder::new(&project_root)
857 .hidden(crate::core::walk_filter::SKIP_HIDDEN_IN_CONTENT_WALK)
859 .git_ignore(index_filter.respect_gitignore)
860 .git_global(index_filter.respect_gitignore)
861 .git_exclude(index_filter.respect_gitignore)
862 .require_git(false)
863 .max_depth(Some(20))
864 .filter_entry(crate::core::walk_filter::keep_entry)
865 .build();
866
867 let extra_ignores: Vec<glob::Pattern> = cfg
868 .extra_ignore_patterns
869 .iter()
870 .filter_map(|p| glob::Pattern::new(p).ok())
871 .collect();
872
873 let mut scanned = 0usize;
874 let mut reused = 0usize;
875 let mut entries_visited = 0usize;
876 let mut content_cache: HashMap<String, String> = HashMap::new();
877 let mut content_cache_bytes: usize = 0;
878 const CONTENT_CACHE_MAX_BYTES: usize = 256 * 1024 * 1024; let max_files = if cfg.graph_index_max_files == 0 {
880 usize::MAX } else {
882 cfg.graph_index_max_files as usize
883 };
884 const MAX_ENTRIES_VISITED: usize = 500_000;
885 const MAX_FILE_SIZE_BYTES: u64 = 2 * 1024 * 1024; const SCAN_BATCH_FILES: usize = 500;
888 const SCAN_MIN_BATCH_FILES: usize = 1;
889 const SCAN_EST_TRANSIENT_PER_FILE: u64 = 192 * 1024;
893 let scan_deadline = std::time::Instant::now() + std::time::Duration::from_mins(5);
894
895 let mut targets: Vec<(String, String, String)> = Vec::new();
903 for entry in walker.filter_map(std::result::Result::ok) {
904 entries_visited += 1;
905 if entries_visited > MAX_ENTRIES_VISITED {
906 tracing::warn!(
907 "[graph_index: walked {entries_visited} entries — aborting scan to prevent \
908 runaway traversal. Indexed {} files so far.]",
909 targets.len()
910 );
911 break;
912 }
913 if entries_visited.is_multiple_of(5000) {
914 if std::time::Instant::now() > scan_deadline {
915 tracing::warn!(
916 "[graph_index: scan timeout (120s) after {entries_visited} entries — \
917 saving partial index with {} files]",
918 targets.len()
919 );
920 break;
921 }
922 if crate::core::memory_guard::abort_requested() {
923 tracing::warn!(
924 "[graph_index: memory pressure abort after {entries_visited} entries — \
925 saving partial index with {} files]",
926 targets.len()
927 );
928 break;
929 }
930 if crate::core::memory_guard::is_under_pressure() {
931 tracing::warn!(
932 "[graph_index: memory pressure detected at {entries_visited} entries — \
933 stopping scan with {} files]",
934 targets.len()
935 );
936 break;
937 }
938 if let Some(ref g) = _lock {
939 g.touch();
940 }
941 }
942
943 if !entry.file_type().is_some_and(|ft| ft.is_file()) {
944 continue;
945 }
946
947 if entry.path_is_symlink() {
948 continue;
949 }
950 let file_path = normalize_absolute_path(&entry.path().to_string_lossy());
951
952 if !std::path::Path::new(&file_path).starts_with(std::path::Path::new(&project_root)) {
953 continue;
954 }
955
956 if let Ok(meta) = std::fs::symlink_metadata(&file_path) {
957 if meta.file_type().is_symlink() || !meta.is_file() {
958 continue;
959 }
960 if meta.len() > MAX_FILE_SIZE_BYTES {
961 tracing::debug!(
962 "[graph_index: skipping {file_path} — {:.1}MB exceeds {}MB limit]",
963 meta.len() as f64 / 1_048_576.0,
964 MAX_FILE_SIZE_BYTES / (1024 * 1024),
965 );
966 continue;
967 }
968 }
969
970 let ext = Path::new(&file_path)
971 .extension()
972 .and_then(|e| e.to_str())
973 .unwrap_or("");
974
975 if !is_indexable_ext(ext) {
976 continue;
977 }
978
979 let rel = make_relative(&file_path, &project_root);
980 if crate::core::io_boundary::is_secret_like(Path::new(&rel)).is_some() {
984 continue;
985 }
986 if extra_ignores.iter().any(|p| p.matches(&rel)) {
987 continue;
988 }
989 if index_filter.is_excluded(&rel.replace('\\', "/")) {
990 continue;
991 }
992
993 if max_files != usize::MAX && targets.len() >= max_files {
994 tracing::info!(
995 "[graph_index: reached configured limit of {} files. Set graph_index_max_files = 0 for unlimited.]",
996 max_files
997 );
998 break;
999 }
1000
1001 let ext = ext.to_string();
1003 targets.push((file_path, rel, ext));
1004 }
1005
1006 let target_rels: Vec<String> = targets.iter().map(|(_, r, _)| r.clone()).collect();
1010 let admission = crate::core::index_admission::admit_files(
1011 crate::core::index_admission::BuildKind::GraphScan,
1012 std::path::Path::new(&project_root),
1013 &target_rels,
1014 );
1015 let parallel = admission.parallel_ok && !crate::core::memory_guard::is_under_pressure();
1016 let store_admission = StoreAdmission::current();
1018 let mut files_done = 0;
1019 while files_done < targets.len() {
1020 if crate::core::memory_guard::abort_requested() {
1021 tracing::warn!(
1022 "[graph_index: aborting scan after {files_done} files due to critical memory pressure]"
1023 );
1024 break;
1025 }
1026 if crate::core::memory_guard::is_under_pressure() {
1027 tracing::warn!(
1028 "[graph_index: stopping scan after {files_done} files due to memory pressure]"
1029 );
1030 break;
1031 }
1032 let batch_size = crate::core::memory_guard::adaptive_batch_size(
1033 SCAN_MIN_BATCH_FILES,
1034 SCAN_BATCH_FILES,
1035 SCAN_EST_TRANSIENT_PER_FILE,
1036 );
1037 let batch_end = (files_done + batch_size).min(targets.len());
1038 let results = process_scan_targets(
1039 &targets[files_done..batch_end],
1040 &previous_symbols,
1041 existing.as_ref(),
1042 parallel,
1043 &store_admission,
1044 );
1045 for r in results {
1046 if r.reused {
1047 reused += 1;
1048 } else {
1049 scanned += 1;
1050 }
1051 index.files.insert(r.rel.clone(), r.file_entry);
1052 for (key, sym) in r.symbols {
1053 index.symbols.insert(key, sym);
1054 }
1055 if content_cache_bytes < CONTENT_CACHE_MAX_BYTES {
1056 content_cache_bytes += r.content.len();
1057 content_cache.insert(r.rel, r.content);
1058 }
1059 }
1060 files_done = batch_end;
1061 crate::core::memory_guard::jemalloc_purge();
1062 }
1063
1064 index.rebuild_interner();
1065 build_edges_cached(&mut index, &content_cache, scan_deadline);
1068
1069 if let Err(e) = index.save() {
1070 tracing::warn!("could not save graph index: {e}");
1071 }
1072
1073 tracing::debug!(
1074 "[graph_index: {} files ({} scanned, {} reused), {} symbols, {} edges]",
1075 index.file_count(),
1076 scanned,
1077 reused,
1078 index.symbol_count(),
1079 index.edge_count()
1080 );
1081
1082 (index, content_cache)
1083}
1084
1085type PreviousSymbols<'a> = HashMap<&'a str, Vec<(&'a str, &'a SymbolEntry)>>;
1089
1090fn previous_symbols_by_file(index: &ProjectIndex) -> PreviousSymbols<'_> {
1091 let mut by_file: PreviousSymbols<'_> = HashMap::new();
1092 for (key, symbol) in &index.symbols {
1093 by_file
1094 .entry(symbol.file.as_str())
1095 .or_default()
1096 .push((key.as_str(), symbol));
1097 }
1098 by_file
1099}
1100
1101#[derive(Debug, PartialEq)]
1104struct ScanFileResult {
1105 rel: String,
1106 file_entry: FileEntry,
1107 symbols: Vec<(String, SymbolEntry)>,
1109 content: String,
1110 reused: bool,
1111}
1112
1113fn process_scan_file(
1117 file_path: &str,
1118 rel: &str,
1119 ext: &str,
1120 previous_symbols: &PreviousSymbols<'_>,
1121 existing: Option<&ProjectIndex>,
1122 admission: &StoreAdmission,
1123) -> Option<ScanFileResult> {
1124 if crate::core::memory_guard::abort_requested() {
1125 return None;
1126 }
1127 let content = crate::core::text_decode::read_text(file_path).ok()?;
1128 let hash = compute_hash(&content);
1129
1130 if let Some(old_entry) = existing.and_then(|p| p.files.get(rel))
1134 && old_entry.hash == hash
1135 {
1136 let symbols = previous_symbols
1137 .get(rel)
1138 .into_iter()
1139 .flatten()
1140 .map(|(key, symbol)| ((*key).to_string(), (*symbol).clone()))
1141 .collect();
1142 return Some(ScanFileResult {
1143 rel: rel.to_string(),
1144 file_entry: old_entry.clone(),
1145 symbols,
1146 content,
1147 reused: true,
1148 });
1149 }
1150
1151 if crate::core::memory_guard::abort_requested() {
1152 return None;
1153 }
1154
1155 let sigs = signatures::extract_signatures(&content, ext);
1156 let line_count = content.lines().count();
1157 let token_count = crate::core::tokens::count_tokens(&content);
1158 let summary = admission
1161 .admit(&extract_summary(&content), std::path::Path::new(file_path))
1162 .unwrap_or_default();
1163
1164 let exports: Vec<String> = sigs
1165 .iter()
1166 .filter(|s| s.is_exported)
1167 .map(|s| s.name.clone())
1168 .collect();
1169
1170 let file_entry = FileEntry {
1171 path: rel.to_string(),
1172 hash,
1173 language: ext.to_string(),
1174 line_count,
1175 token_count,
1176 exports,
1177 summary,
1178 };
1179
1180 let symbols: Vec<(String, SymbolEntry)> = sigs
1181 .iter()
1182 .map(|sig| {
1183 let (start, end) = sig
1184 .start_line
1185 .zip(sig.end_line)
1186 .unwrap_or_else(|| find_symbol_range(&content, sig));
1187 let key = format!("{rel}::{}", sig.name);
1188 (
1189 key,
1190 SymbolEntry {
1191 file: rel.to_string(),
1192 name: sig.name.clone(),
1193 kind: sig.kind.to_string(),
1194 start_line: start,
1195 end_line: end,
1196 is_exported: sig.is_exported,
1197 },
1198 )
1199 })
1200 .collect();
1201
1202 Some(ScanFileResult {
1203 rel: rel.to_string(),
1204 file_entry,
1205 symbols,
1206 content,
1207 reused: false,
1208 })
1209}
1210
1211fn process_scan_targets(
1216 targets: &[(String, String, String)],
1217 previous_symbols: &PreviousSymbols<'_>,
1218 existing: Option<&ProjectIndex>,
1219 parallel: bool,
1220 admission: &StoreAdmission,
1221) -> Vec<ScanFileResult> {
1222 if parallel {
1223 targets
1224 .par_iter()
1225 .filter_map(|(file_path, rel, ext)| {
1226 process_scan_file(file_path, rel, ext, previous_symbols, existing, admission)
1227 })
1228 .collect()
1229 } else {
1230 targets
1231 .iter()
1232 .filter_map(|(file_path, rel, ext)| {
1233 process_scan_file(file_path, rel, ext, previous_symbols, existing, admission)
1234 })
1235 .collect()
1236 }
1237}
1238
1239pub(crate) fn find_symbol_range(content: &str, sig: &signatures::Signature) -> (usize, usize) {
1240 let lines: Vec<&str> = content.lines().collect();
1241 let mut start = 0;
1242
1243 for (i, line) in lines.iter().enumerate() {
1244 if line.contains(&sig.name) {
1245 let trimmed = line.trim();
1246 let is_def = trimmed.starts_with("fn ")
1247 || trimmed.starts_with("pub fn ")
1248 || trimmed.starts_with("pub(crate) fn ")
1249 || trimmed.starts_with("async fn ")
1250 || trimmed.starts_with("pub async fn ")
1251 || trimmed.starts_with("struct ")
1252 || trimmed.starts_with("pub struct ")
1253 || trimmed.starts_with("enum ")
1254 || trimmed.starts_with("pub enum ")
1255 || trimmed.starts_with("trait ")
1256 || trimmed.starts_with("pub trait ")
1257 || trimmed.starts_with("impl ")
1258 || trimmed.starts_with("class ")
1259 || trimmed.starts_with("export class ")
1260 || trimmed.starts_with("export function ")
1261 || trimmed.starts_with("export async function ")
1262 || trimmed.starts_with("function ")
1263 || trimmed.starts_with("async function ")
1264 || trimmed.starts_with("def ")
1265 || trimmed.starts_with("async def ")
1266 || trimmed.starts_with("func ")
1267 || trimmed.starts_with("interface ")
1268 || trimmed.starts_with("export interface ")
1269 || trimmed.starts_with("type ")
1270 || trimmed.starts_with("export type ")
1271 || trimmed.starts_with("const ")
1272 || trimmed.starts_with("export const ")
1273 || trimmed.starts_with("fun ")
1274 || trimmed.starts_with("private fun ")
1275 || trimmed.starts_with("public fun ")
1276 || trimmed.starts_with("internal fun ")
1277 || trimmed.starts_with("class ")
1278 || trimmed.starts_with("data class ")
1279 || trimmed.starts_with("sealed class ")
1280 || trimmed.starts_with("sealed interface ")
1281 || trimmed.starts_with("enum class ")
1282 || trimmed.starts_with("object ")
1283 || trimmed.starts_with("private object ")
1284 || trimmed.starts_with("interface ")
1285 || trimmed.starts_with("typealias ")
1286 || trimmed.starts_with("private typealias ");
1287 if is_def {
1288 start = i + 1;
1289 break;
1290 }
1291 }
1292 }
1293
1294 if start == 0 {
1295 return (1, lines.len().min(20));
1296 }
1297
1298 let base_indent = lines
1299 .get(start - 1)
1300 .map_or(0, |l| l.len() - l.trim_start().len());
1301
1302 let mut end = start;
1303 let mut brace_depth: i32 = 0;
1304 let mut found_open = false;
1305
1306 for (i, line) in lines.iter().enumerate().skip(start - 1) {
1307 for ch in line.chars() {
1308 if ch == '{' {
1309 brace_depth += 1;
1310 found_open = true;
1311 } else if ch == '}' {
1312 brace_depth -= 1;
1313 }
1314 }
1315
1316 end = i + 1;
1317
1318 if found_open && brace_depth <= 0 {
1319 break;
1320 }
1321
1322 if !found_open && i > start {
1323 let indent = line.len() - line.trim_start().len();
1324 if indent <= base_indent && !line.trim().is_empty() && i > start {
1325 end = i;
1326 break;
1327 }
1328 }
1329
1330 if end - start > 200 {
1331 break;
1332 }
1333 }
1334
1335 (start, end)
1336}
1337
1338fn extract_summary(content: &str) -> String {
1339 for line in content.lines().take(20) {
1340 let trimmed = line.trim();
1341 if trimmed.is_empty()
1342 || trimmed.starts_with("//")
1343 || trimmed.starts_with('#')
1344 || trimmed.starts_with("/*")
1345 || trimmed.starts_with('*')
1346 || trimmed.starts_with("use ")
1347 || trimmed.starts_with("import ")
1348 || trimmed.starts_with("from ")
1349 || trimmed.starts_with("require(")
1350 || trimmed.starts_with("package ")
1351 {
1352 continue;
1353 }
1354 return trimmed.chars().take(120).collect();
1355 }
1356 String::new()
1357}
1358
1359fn compute_hash(content: &str) -> String {
1360 use std::collections::hash_map::DefaultHasher;
1361 use std::hash::{Hash, Hasher};
1362
1363 let mut hasher = DefaultHasher::new();
1364 content.hash(&mut hasher);
1365 format!("{:016x}", hasher.finish())
1366}
1367
1368#[cfg(test)]
1369fn short_hash(input: &str) -> String {
1370 use std::collections::hash_map::DefaultHasher;
1371 use std::hash::{Hash, Hasher};
1372
1373 let mut hasher = DefaultHasher::new();
1374 input.hash(&mut hasher);
1375 format!("{:08x}", hasher.finish() & 0xFFFF_FFFF)
1376}
1377
1378fn make_relative(path: &str, root: &str) -> String {
1379 graph_relative_key(path, root)
1380}
1381
1382fn is_indexable_ext(ext: &str) -> bool {
1383 crate::core::language_capabilities::is_indexable_ext(ext)
1384}
1385
1386#[cfg(test)]
1387fn kotlin_package_name(content: &str) -> Option<String> {
1388 content.lines().map(str::trim).find_map(|line| {
1389 line.strip_prefix("package ")
1390 .map(|rest| rest.trim().trim_end_matches(';').to_string())
1391 })
1392}