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;
22pub mod rust_modules;
23#[cfg(test)]
24mod tests;
25
26const INDEX_VERSION: u32 = 8;
31
32use 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
46fn dir_has_project_marker(dir: &Path) -> bool {
52 crate::core::pathutil::has_project_marker(dir)
53}
54
55fn 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
75fn 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 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 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 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 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 "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 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 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 if !breadth_markers.iter().any(|m| p.join(m).exists())
210 && !dir_has_dotnet_project(p)
211 && !is_inside_project(p)
212 {
213 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
235fn 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 #[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 #[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 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 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 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 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 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(¤t) {
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 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(¤t) {
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 pub fn get_related(&self, path: &str, depth: usize) -> Vec<String> {
509 self.get_related_served(path, depth, &|_: &str| true)
510 }
511
512 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(¤t) {
527 continue;
528 }
529 visited.insert(current.clone());
530 if current != path && !served(¤t) {
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
550pub 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 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 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 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 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 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 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 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 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
687fn 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
704fn source_content_changed_since_index(index: &ProjectIndex, root_abs: &str) -> bool {
717 let Some(index_mtime) = index_file_mtime(root_abs) else {
718 return false;
720 };
721 let index_filter = crate::core::index_filter::IndexFileFilter::effective();
724 let walker = ignore::WalkBuilder::new(root_abs)
725 .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 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 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 return true;
769 };
770 confirm_reads += 1;
771 if confirm_reads > MAX_CONFIRM_READS {
772 return true;
774 }
775 match crate::core::text_decode::read_text(path) {
776 Ok(content) if compute_hash(&content) == file_entry.hash => {}
778 _ => return true,
780 }
781 }
782 false
783}
784
785pub 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 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 let index_filter = crate::core::index_filter::IndexFileFilter::resolve(&cfg);
861
862 let walker = ignore::WalkBuilder::new(&project_root)
863 .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; let max_files = if cfg.graph_index_max_files == 0 {
886 usize::MAX } 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; const SCAN_BATCH_FILES: usize = 500;
894 const SCAN_MIN_BATCH_FILES: usize = 1;
895 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 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 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 let ext = ext.to_string();
1009 targets.push((file_path, rel, ext));
1010 }
1011
1012 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 let store_admission = StoreAdmission::current();
1024 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 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
1100type 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#[derive(Debug, PartialEq)]
1119struct ScanFileResult {
1120 rel: String,
1121 file_entry: FileEntry,
1122 symbols: Vec<(String, SymbolEntry)>,
1124 content: String,
1125 reused: bool,
1126}
1127
1128fn 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 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 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
1230fn 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 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}