1use std::collections::HashMap;
2use std::path::Path;
3use std::sync::{Arc, Mutex, OnceLock};
4use std::time::{SystemTime, UNIX_EPOCH};
5
6use serde::Serialize;
7
8use crate::core::bm25_index::BM25Index;
9use crate::core::graph_index::{self, ProjectIndex};
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12enum State {
13 Idle,
14 Building,
15 Ready,
16 Failed,
17}
18
19#[derive(Debug, Clone)]
20struct Component {
21 state: State,
22 started_ms: Option<u64>,
23 finished_ms: Option<u64>,
24 duration_ms: Option<u64>,
25 last_error: Option<String>,
26 note: Option<String>,
30}
31
32impl Component {
33 fn new() -> Self {
34 Self {
35 state: State::Idle,
36 started_ms: None,
37 finished_ms: None,
38 duration_ms: None,
39 last_error: None,
40 note: None,
41 }
42 }
43}
44
45#[derive(Debug)]
46struct ProjectBuild {
47 worker_running: bool,
48 graph_run_done: bool,
52 bm25_run_done: bool,
54 warm_triggered: bool,
58 graph: Component,
59 bm25: Component,
60 semantic: Component,
64}
65
66impl ProjectBuild {
67 fn new() -> Self {
68 Self {
69 worker_running: false,
70 graph_run_done: true,
71 bm25_run_done: true,
72 warm_triggered: false,
73 graph: Component::new(),
74 bm25: Component::new(),
75 semantic: Component::new(),
76 }
77 }
78}
79
80static REGISTRY: OnceLock<Mutex<HashMap<String, Arc<Mutex<ProjectBuild>>>>> = OnceLock::new();
88
89fn registry() -> &'static Mutex<HashMap<String, Arc<Mutex<ProjectBuild>>>> {
90 REGISTRY.get_or_init(|| Mutex::new(HashMap::new()))
91}
92
93fn entry_for(project_root: &str) -> Arc<Mutex<ProjectBuild>> {
94 let mut map = registry()
95 .lock()
96 .unwrap_or_else(std::sync::PoisonError::into_inner);
97 map.entry(project_root.to_string())
98 .or_insert_with(|| Arc::new(Mutex::new(ProjectBuild::new())))
99 .clone()
100}
101
102fn now_ms() -> u64 {
103 SystemTime::now()
104 .duration_since(UNIX_EPOCH)
105 .unwrap_or_default()
106 .as_millis() as u64
107}
108
109fn bm25_index_lock_name(root: &Path) -> String {
114 format!(
115 "bm25-idx-{}",
116 &crate::core::index_namespace::namespace_hash(root)[..8]
117 )
118}
119
120fn semantic_index_lock_name(root: &Path) -> String {
123 format!(
124 "semantic-idx-{}",
125 &crate::core::index_namespace::namespace_hash(root)[..8]
126 )
127}
128
129const SEMANTIC_LOCK_STALE_AFTER: std::time::Duration = std::time::Duration::from_hours(24);
132
133fn start_component(c: &mut Component) {
134 c.state = State::Building;
135 c.started_ms = Some(now_ms());
136 c.finished_ms = None;
137 c.duration_ms = None;
138 c.last_error = None;
139 c.note = None;
140}
141
142fn finish_ok(c: &mut Component) {
143 c.state = State::Ready;
144 let end = now_ms();
145 c.finished_ms = Some(end);
146 c.duration_ms = c.started_ms.map(|s| end.saturating_sub(s));
147}
148
149fn finish_err(c: &mut Component, e: String) {
150 c.state = State::Failed;
151 let end = now_ms();
152 c.finished_ms = Some(end);
153 c.duration_ms = c.started_ms.map(|s| end.saturating_sub(s));
154 c.last_error = Some(e);
155}
156
157#[derive(Debug, Clone, Copy, PartialEq, Eq)]
162pub enum WarmNeed {
163 None,
165 Search,
167 Heavy,
169}
170
171#[must_use]
175pub fn warm_need_for_tool(tool: &str) -> WarmNeed {
176 match tool {
177 "ctx_search" => WarmNeed::Search,
178 "ctx_graph" | "ctx_callgraph" | "ctx_artifacts" | "ctx_provider" | "ctx_compose" => {
180 WarmNeed::Heavy
181 }
182 _ => WarmNeed::None,
183 }
184}
185
186pub fn ensure_warm_for_tool(project_root: &str, tool: &str) -> bool {
193 if project_root.is_empty() {
194 return false;
195 }
196 match warm_need_for_tool(tool) {
197 WarmNeed::None => false,
198 WarmNeed::Search => {
199 crate::core::search_index::ensure_background(project_root, true, false);
202 false
203 }
204 WarmNeed::Heavy => {
205 let entry = entry_for(project_root);
206 let first_warm = {
207 let mut s = entry
208 .lock()
209 .unwrap_or_else(std::sync::PoisonError::into_inner);
210 if s.warm_triggered {
211 false
212 } else {
213 s.warm_triggered = true;
214 true
215 }
216 };
217 if first_warm {
218 ensure_all_background(project_root);
219 }
220 first_warm
221 }
222 }
223}
224
225const INDEXER_STACK_BYTES: usize = 16 * 1024 * 1024;
229
230fn nudge_daemon_index(project_root: &str) {
242 if crate::daemon::is_foreground_daemon() {
244 return;
245 }
246 let root = project_root.to_string();
247 let _ = std::thread::Builder::new()
248 .name("leanctx-index-nudge".to_string())
249 .spawn(move || {
250 if !crate::daemon::is_daemon_running() {
251 return;
252 }
253 let Ok(rt) = tokio::runtime::Runtime::new() else {
254 return;
255 };
256 let body = serde_json::json!({ "root": root }).to_string();
257 rt.block_on(async {
258 let _ = crate::daemon_client::try_daemon_request("POST", "/v1/index/ensure", &body)
259 .await;
260 });
261 });
262}
263
264fn try_claim_worker(project_root: &str) -> bool {
268 let state = entry_for(project_root);
269 let mut s = state
270 .lock()
271 .unwrap_or_else(std::sync::PoisonError::into_inner);
272 if s.worker_running {
273 false
274 } else {
275 s.worker_running = true;
276 s.graph_run_done = false;
277 s.bm25_run_done = false;
278 true
279 }
280}
281
282pub fn ensure_all_background(project_root: &str) {
283 if !try_claim_worker(project_root) {
284 return;
285 }
286
287 if !crate::core::index_filter::cli_overlay_active() {
296 nudge_daemon_index(project_root);
297 }
298
299 let state = entry_for(project_root);
300 let root = project_root.to_string();
301 let indexer = move || run_build_worker(&root);
302
303 let spawned = std::thread::Builder::new()
307 .name("leanctx-index".to_string())
308 .stack_size(INDEXER_STACK_BYTES)
309 .spawn(indexer);
310 if spawned.is_err() {
311 let mut s = state
314 .lock()
315 .unwrap_or_else(std::sync::PoisonError::into_inner);
316 s.worker_running = false;
317 }
318}
319
320fn run_build_worker(root: &str) {
325 let _slot = WorkerSlot(root.to_string());
329
330 start_index_memory_guard("build_worker");
337
338 let graph_state = entry_for(root);
344 let graph_root = root.to_string();
345 let build_graph = move || {
346 {
347 let mut s = graph_state
348 .lock()
349 .unwrap_or_else(std::sync::PoisonError::into_inner);
350 start_component(&mut s.graph);
351 }
352 let guard = crate::core::index_progress::ProgressGuard::new(
354 graph_root.clone(),
355 crate::core::index_progress::IndexComponent::Graph,
356 );
357 guard.report(0, 0);
358 let graph_result = std::panic::catch_unwind(|| {
359 let (idx, _cache) = graph_index::scan_with_content_cache(&graph_root);
360 crate::core::code_health::persist::refresh_if_stale(&graph_root, &idx);
364 });
365 if graph_result.is_ok() {
366 let _ = std::panic::catch_unwind(|| {
369 crate::core::graph_enricher::refresh_semantic_edges_in_background(&graph_root);
370 });
371 }
372 drop(guard);
373 crate::core::telemetry_features::record(
374 crate::core::telemetry_features::Feature::GraphIndex,
375 graph_result.is_ok(),
376 );
377 {
378 let mut s = graph_state
379 .lock()
380 .unwrap_or_else(std::sync::PoisonError::into_inner);
381 if let Ok(()) = graph_result {
382 finish_ok(&mut s.graph);
383 } else {
384 finish_err(&mut s.graph, "graph index build panicked".to_string());
385 }
386 s.graph_run_done = true;
387 }
388 };
389
390 let bm25_state = entry_for(root);
391 let bm25_root = root.to_string();
392 let build_bm25 = move || {
393 {
394 let mut s = bm25_state
395 .lock()
396 .unwrap_or_else(std::sync::PoisonError::into_inner);
397 start_component(&mut s.bm25);
398 }
399 let _progress = crate::core::index_progress::ProgressGuard::new(
400 bm25_root.clone(),
401 crate::core::index_progress::IndexComponent::Bm25,
402 );
403 let bm = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
404 let root_pb = Path::new(&bm25_root);
405 let lock_name = bm25_index_lock_name(root_pb);
406 let _lock = crate::core::startup_guard::try_acquire_lock(
407 &lock_name,
408 std::time::Duration::from_millis(800),
409 std::time::Duration::from_mins(3),
410 );
411 if _lock.is_none() {
412 tracing::info!(
413 "[bm25: another process is building {bm25_root} — loading the shared index]"
414 );
415 let idx = BM25Index::load(root_pb).unwrap_or_default();
416 return (idx.doc_count, None);
417 }
418 let idx = BM25Index::load_or_build(root_pb);
419 let outcome = idx.save(root_pb);
420 (idx.doc_count, Some(outcome))
421 }));
422 if !matches!(bm, Ok((_, None))) {
424 crate::core::telemetry_features::record(
425 crate::core::telemetry_features::Feature::Bm25Index,
426 bm.is_ok(),
427 );
428 }
429 {
430 let mut s = bm25_state
431 .lock()
432 .unwrap_or_else(std::sync::PoisonError::into_inner);
433 if let Ok((doc_count, save_res)) = bm {
434 finish_ok(&mut s.bm25);
435 s.bm25.note = Some(match save_res {
436 Some(outcome) => bm25_build_note(doc_count, &outcome),
437 None => format!(
438 "loaded shared BM25 index ({doc_count} chunks) — build in progress in another process"
439 ),
440 });
441 } else {
442 finish_err(&mut s.bm25, "bm25 build panicked".to_string());
443 }
444 s.bm25_run_done = true;
445 }
446 };
447
448 run_memory_bounded_phases(
449 build_graph,
450 build_bm25,
451 || crate::core::search_index::ensure_background(root, true, false),
452 || {
453 crate::core::content_cache::clear();
454 crate::core::memory_guard::force_purge();
455 },
456 );
457
458 crate::core::content_cache::trim_oldest_percent(75);
465 crate::core::memory_guard::force_purge();
466}
467
468struct WorkerSlot(String);
471
472impl Drop for WorkerSlot {
473 fn drop(&mut self) {
474 let state = entry_for(&self.0);
475 let mut s = state
476 .lock()
477 .unwrap_or_else(std::sync::PoisonError::into_inner);
478 s.worker_running = false;
479 }
480}
481
482fn run_memory_bounded_phases<G, B, S, R>(graph: G, bm25: B, search: S, mut reclaim: R)
485where
486 G: FnOnce(),
487 B: FnOnce(),
488 S: FnOnce(),
489 R: FnMut(),
490{
491 graph();
492 reclaim();
493 bm25();
494 reclaim();
495 search();
496}
497
498pub fn build_semantic(project_root: &str) {
503 let state = entry_for(project_root);
504 let root = Path::new(project_root);
505
506 let Some(_lock) = crate::core::startup_guard::try_acquire_lock(
507 &semantic_index_lock_name(root),
508 std::time::Duration::ZERO,
509 SEMANTIC_LOCK_STALE_AFTER,
510 ) else {
511 let mut s = state
512 .lock()
513 .unwrap_or_else(std::sync::PoisonError::into_inner);
514 s.semantic.note = Some(
515 "another lean-ctx process is already building the semantic index for this project; \
516 it saves progress as it goes — check `lean-ctx index status` later"
517 .to_string(),
518 );
519 return;
520 };
521
522 {
523 let mut s = state
524 .lock()
525 .unwrap_or_else(std::sync::PoisonError::into_inner);
526 start_component(&mut s.semantic);
527 }
528
529 let _progress = crate::core::index_progress::ProgressGuard::new(
531 project_root.to_string(),
532 crate::core::index_progress::IndexComponent::Semantic,
533 );
534
535 let bm25_idx = try_load_bm25_index(project_root);
536 match bm25_idx.as_ref() {
537 Some(idx) if idx.doc_count > 0 => {
538 let outcome = crate::core::embedding_index::build_or_update(root, idx);
539 match outcome {
540 crate::core::embedding_index::EmbeddingBuildOutcome::Ready => {
541 crate::core::telemetry_features::record(
542 crate::core::telemetry_features::Feature::SemanticIndex,
543 true,
544 );
545 }
546 crate::core::embedding_index::EmbeddingBuildOutcome::Failed => {
547 crate::core::telemetry_features::record(
548 crate::core::telemetry_features::Feature::SemanticIndex,
549 false,
550 );
551 }
552 _ => {}
553 }
554 let mut s = state
555 .lock()
556 .unwrap_or_else(std::sync::PoisonError::into_inner);
557 match outcome {
558 crate::core::embedding_index::EmbeddingBuildOutcome::Ready => {
559 finish_ok(&mut s.semantic);
560 }
561 crate::core::embedding_index::EmbeddingBuildOutcome::Skipped => {
562 finish_ok(&mut s.semantic);
563 s.semantic.note = Some(
564 "embeddings disabled by feature flag or config (search.dense_enabled / memory_profile)"
565 .to_string(),
566 );
567 }
568 crate::core::embedding_index::EmbeddingBuildOutcome::ModelNotAvailable(
569 ref reason,
570 ) => {
571 s.semantic.state = State::Idle;
574 s.semantic.note = Some(format!("embedding model not available: {reason}"));
575 }
576 crate::core::embedding_index::EmbeddingBuildOutcome::Failed => {
577 finish_err(
578 &mut s.semantic,
579 "embedding build failed (see logs)".to_string(),
580 );
581 }
582 }
583 }
584 _ => {
585 let mut s = state
586 .lock()
587 .unwrap_or_else(std::sync::PoisonError::into_inner);
588 s.semantic.state = State::Idle;
590 s.semantic.note =
591 Some("BM25 index is empty or unavailable — nothing to embed".to_string());
592 }
593 }
594}
595
596pub fn build_semantic_background(project_root: &str) {
601 let root = project_root.to_string();
602 let spawned = std::thread::Builder::new()
603 .name("leanctx-semantic".to_string())
604 .stack_size(INDEXER_STACK_BYTES)
605 .spawn(move || {
606 start_index_memory_guard("semantic_build");
607 if !disk_status(&root).bm25_index.exists {
608 ensure_all_background(&root);
609 }
610 while progress_view(&root).graph_bm25_active() {
611 std::thread::sleep(std::time::Duration::from_millis(250));
612 }
613 build_semantic(&root);
614 });
615 if let Err(e) = spawned {
616 tracing::warn!("[index_orchestrator: could not spawn semantic worker: {e}]");
617 }
618}
619
620fn start_index_memory_guard(label: &'static str) {
626 crate::core::memory_guard::start_guard(std::sync::Arc::new(move |level| {
627 tracing::warn!("[{label}] memory pressure: {level:?} — background tasks will throttle");
628 let reclaimed = crate::core::eviction_orchestrator::on_memory_pressure(level);
629 crate::core::memory_guard::force_purge();
630 reclaimed
631 }));
632}
633
634const MAX_EXTRA_ROOT_BUILDS: usize = 8;
638
639pub fn ensure_extra_roots_background(primary_root: &str, extra_roots: &[String]) {
640 let primary = Path::new(primary_root);
641 let mut queue: Vec<String> = Vec::new();
642 for root in extra_roots {
643 if queue.len() >= MAX_EXTRA_ROOT_BUILDS {
644 break;
645 }
646 let rp = Path::new(root);
647 if !rp.is_dir() {
648 continue;
649 }
650 if rp.starts_with(primary) {
652 continue;
653 }
654 if primary.starts_with(rp) {
656 continue;
657 }
658 queue.push(root.clone());
659 }
660 if queue.is_empty() {
661 return;
662 }
663
664 let spawned = std::thread::Builder::new()
673 .name("leanctx-extra-roots".to_string())
674 .stack_size(INDEXER_STACK_BYTES)
675 .spawn(move || {
676 for root in queue {
677 if crate::core::memory_guard::is_under_pressure()
678 || crate::core::memory_guard::abort_requested()
679 {
680 tracing::warn!(
681 "[index_orchestrator: skipping remaining extra-root builds under memory pressure]"
682 );
683 break;
684 }
685 if !try_claim_worker(&root) {
686 continue; }
688 nudge_daemon_index(&root);
689 run_build_worker(&root);
690 }
691 });
692 if let Err(e) = spawned {
693 tracing::warn!("[index_orchestrator: could not spawn extra-roots worker: {e}]");
694 }
695}
696
697fn bm25_build_note(
702 doc_count: usize,
703 save: &std::io::Result<crate::core::bm25_index::SaveOutcome>,
704) -> String {
705 use crate::core::bm25_index::SaveOutcome;
706 match save {
707 Ok(SaveOutcome::Persisted { compressed_bytes }) => format!(
708 "indexed {doc_count} chunks, {:.1} MB persisted",
709 *compressed_bytes as f64 / 1_048_576.0
710 ),
711 Ok(SaveOutcome::SkippedTooLarge {
712 compressed_bytes,
713 limit_bytes,
714 }) => format!(
715 "indexed {doc_count} chunks but NOT persisted to disk: compressed {:.1} MB exceeds the {:.0} MB cap. \
716 Raise it via LEAN_CTX_BM25_MAX_CACHE_MB (or bm25_max_cache_mb in config) or add extra_ignore_patterns, \
717 then run `lean-ctx reindex`. Until then the index is rebuilt from scratch on every cold start.",
718 *compressed_bytes as f64 / 1_048_576.0,
719 *limit_bytes as f64 / 1_048_576.0
720 ),
721 Err(e) => format!("indexed {doc_count} chunks but persisting failed: {e}"),
722 }
723}
724
725#[derive(Debug, Clone)]
728pub struct Bm25Summary {
729 pub state: &'static str,
730 pub elapsed_ms: Option<u64>,
732 pub note: Option<String>,
733 pub last_error: Option<String>,
734}
735
736#[derive(Debug, Clone)]
738pub struct SemanticSummary {
739 pub state: &'static str,
740 pub elapsed_ms: Option<u64>,
741 pub note: Option<String>,
742 pub last_error: Option<String>,
743}
744
745fn component_elapsed_and_state(c: &Component) -> (&'static str, Option<u64>) {
749 let elapsed_ms = if matches!(c.state, State::Building) {
750 c.started_ms.map(|start| now_ms().saturating_sub(start))
751 } else {
752 c.duration_ms
753 };
754 let state = match c.state {
755 State::Idle => "idle",
756 State::Building => "building",
757 State::Ready => "ready",
758 State::Failed => "failed",
759 };
760 (state, elapsed_ms)
761}
762
763pub fn semantic_summary(project_root: &str) -> SemanticSummary {
764 let entry = entry_for(project_root);
765 let s = entry
766 .lock()
767 .unwrap_or_else(std::sync::PoisonError::into_inner);
768 let c = &s.semantic;
769 let (state, elapsed_ms) = component_elapsed_and_state(c);
770 SemanticSummary {
771 state,
772 elapsed_ms,
773 note: c.note.clone(),
774 last_error: c.last_error.clone(),
775 }
776}
777
778pub fn bm25_summary(project_root: &str) -> Bm25Summary {
779 let entry = entry_for(project_root);
780 let s = entry
781 .lock()
782 .unwrap_or_else(std::sync::PoisonError::into_inner);
783 let c = &s.bm25;
784 let (state, elapsed_ms) = component_elapsed_and_state(c);
785 Bm25Summary {
786 state,
787 elapsed_ms,
788 note: c.note.clone(),
789 last_error: c.last_error.clone(),
790 }
791}
792
793pub fn try_load_graph_index(project_root: &str) -> Option<ProjectIndex> {
794 crate::core::graph_cache::get_cached(project_root).map(|arc| (*arc).clone())
797}
798
799pub fn try_load_bm25_index(project_root: &str) -> Option<BM25Index> {
800 BM25Index::load(Path::new(project_root))
801}
802
803#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
805pub struct SlotProgress {
806 pub building: bool,
807 pub done: u64,
808 pub total: u64,
809}
810
811impl SlotProgress {
812 pub fn is_determinate(&self) -> bool {
813 self.building && self.total > 0
814 }
815}
816
817#[derive(Debug, Clone, PartialEq, Eq)]
819pub struct ProgressView {
820 pub worker_running: bool,
821 pub graph_run_done: bool,
823 pub bm25_run_done: bool,
825 pub graph: SlotProgress,
826 pub bm25: SlotProgress,
827 pub semantic: SlotProgress,
828}
829
830impl ProgressView {
831 pub fn graph_bm25_active(&self) -> bool {
836 self.worker_running && !(self.graph_run_done && self.bm25_run_done)
837 }
838
839 pub fn semantic_active(&self) -> bool {
840 self.semantic.building
841 }
842}
843
844pub fn progress_view(project_root: &str) -> ProgressView {
846 use crate::core::index_progress::{self, IndexComponent};
847 let (worker_running, graph_run_done, bm25_run_done, graph_b, bm25_b, sem_b) = {
848 let state = entry_for(project_root);
849 let s = state
850 .lock()
851 .unwrap_or_else(std::sync::PoisonError::into_inner);
852 (
853 s.worker_running,
854 s.graph_run_done,
855 s.bm25_run_done,
856 matches!(s.graph.state, State::Building),
857 matches!(s.bm25.state, State::Building),
858 matches!(s.semantic.state, State::Building),
859 )
860 };
861 let g = index_progress::get(project_root, IndexComponent::Graph);
862 let b = index_progress::get(project_root, IndexComponent::Bm25);
863 let sem = index_progress::get(project_root, IndexComponent::Semantic);
864 ProgressView {
865 worker_running,
866 graph_run_done,
867 bm25_run_done,
868 graph: SlotProgress {
869 building: graph_b,
870 done: g.done,
871 total: g.total,
872 },
873 bm25: SlotProgress {
874 building: bm25_b,
875 done: b.done,
876 total: b.total,
877 },
878 semantic: SlotProgress {
879 building: sem_b,
880 done: sem.done,
881 total: sem.total,
882 },
883 }
884}
885
886pub fn is_building() -> bool {
888 let map = registry()
889 .lock()
890 .unwrap_or_else(std::sync::PoisonError::into_inner);
891 map.values().any(|entry| {
892 let st = entry
893 .lock()
894 .unwrap_or_else(std::sync::PoisonError::into_inner);
895 matches!(st.bm25.state, State::Building)
896 || matches!(st.graph.state, State::Building)
897 || matches!(st.semantic.state, State::Building)
898 })
899}
900
901#[derive(Debug, Serialize)]
902struct ComponentStatus<'a> {
903 state: &'a str,
904 started_ms: Option<u64>,
905 finished_ms: Option<u64>,
906 duration_ms: Option<u64>,
907 last_error: Option<&'a str>,
908 #[serde(skip_serializing_if = "Option::is_none")]
909 note: Option<&'a str>,
910 #[serde(skip_serializing_if = "Option::is_none")]
912 progress_done: Option<u64>,
913 #[serde(skip_serializing_if = "Option::is_none")]
915 progress_total: Option<u64>,
916}
917
918fn component_status(
919 c: &Component,
920 progress: crate::core::index_progress::ProgressSnapshot,
921) -> ComponentStatus<'_> {
922 let (progress_done, progress_total) = if matches!(c.state, State::Building) {
923 (Some(progress.done), Some(progress.total))
924 } else {
925 (None, None)
926 };
927 ComponentStatus {
928 state: match c.state {
929 State::Idle => "idle",
930 State::Building => "building",
931 State::Ready => "ready",
932 State::Failed => "failed",
933 },
934 started_ms: c.started_ms,
935 finished_ms: c.finished_ms,
936 duration_ms: c.duration_ms,
937 last_error: c.last_error.as_deref(),
938 note: c.note.as_deref(),
939 progress_done,
940 progress_total,
941 }
942}
943
944#[derive(Debug, Serialize)]
945struct StatusResponse<'a> {
946 project_root: &'a str,
947 graph_index: ComponentStatus<'a>,
948 bm25_index: ComponentStatus<'a>,
949 semantic_index: ComponentStatus<'a>,
953 disk: DiskStatusAll,
954 #[serde(skip_serializing_if = "Option::is_none")]
957 index_filters: Option<String>,
958}
959
960#[derive(Debug, Serialize, Default)]
961pub struct DiskStatus {
962 pub exists: bool,
963 pub size_bytes: Option<u64>,
964 pub file_count: Option<u64>,
965 pub modified_at: Option<String>,
966 #[serde(skip_serializing_if = "Option::is_none")]
970 pub partial_of: Option<u64>,
971}
972
973#[derive(Debug, Serialize, Default)]
974pub struct DiskStatusAll {
975 pub graph_index: DiskStatus,
976 pub bm25_index: DiskStatus,
977 pub code_graph: DiskStatus,
978 pub semantic_index: DiskStatus,
982}
983
984fn disk_status_for_graph(project_root: &str) -> DiskStatus {
985 let Some(dir) = graph_index::ProjectIndex::index_dir(project_root) else {
991 return DiskStatus::default();
992 };
993 let meta_file = dir.join("graph.meta.json");
994 if !meta_file.exists() {
995 return DiskStatus::default();
996 }
997 let meta = std::fs::metadata(&meta_file).ok();
998 let file_count =
999 graph_index::ProjectIndex::load(project_root).map(|idx| idx.files.len() as u64);
1000 DiskStatus {
1001 exists: true,
1002 size_bytes: None,
1003 file_count,
1004 modified_at: meta.and_then(|m| m.modified().ok()).map(format_time),
1005 partial_of: None,
1006 }
1007}
1008
1009fn disk_status_for_bm25(project_root: &str) -> DiskStatus {
1010 let root = Path::new(project_root);
1011 let path = BM25Index::index_file_path(root);
1012 if !path.exists() {
1013 return DiskStatus::default();
1014 }
1015 let meta = std::fs::metadata(&path).ok();
1016 DiskStatus {
1017 exists: true,
1018 size_bytes: meta.as_ref().map(std::fs::Metadata::len),
1019 file_count: BM25Index::persisted_chunk_count(root),
1020 modified_at: meta.and_then(|m| m.modified().ok()).map(format_time),
1021 partial_of: None,
1022 }
1023}
1024
1025fn disk_status_for_code_graph(project_root: &str) -> DiskStatus {
1026 let dir = crate::core::property_graph::graph_dir(project_root);
1027 let db_path = dir.join("graph.db");
1028 if !db_path.exists() {
1029 return DiskStatus::default();
1030 }
1031 let meta = std::fs::metadata(&db_path).ok();
1032 let node_count = crate::core::property_graph::CodeGraph::open(project_root)
1033 .ok()
1034 .and_then(|g| {
1035 g.connection()
1036 .query_row("SELECT count(*) FROM nodes", [], |r| r.get::<_, i64>(0))
1037 .ok()
1038 .map(|c| c as u64)
1039 });
1040 DiskStatus {
1041 exists: true,
1042 size_bytes: meta.as_ref().map(std::fs::Metadata::len),
1043 file_count: node_count,
1044 modified_at: meta.and_then(|m| m.modified().ok()).map(format_time),
1045 partial_of: None,
1046 }
1047}
1048
1049fn format_time(t: SystemTime) -> String {
1050 let secs = t.duration_since(UNIX_EPOCH).unwrap_or_default().as_secs();
1051 let dt = chrono::DateTime::from_timestamp(secs as i64, 0);
1052 dt.map_or_else(
1053 || format!("{secs}"),
1054 |d| d.format("%Y-%m-%d %H:%M:%S UTC").to_string(),
1055 )
1056}
1057
1058pub fn disk_status_for_semantic(project_root: &str) -> DiskStatus {
1059 let root = Path::new(project_root);
1060 let dir = crate::core::index_namespace::vectors_dir(root);
1061 let bin_path = dir.join("embeddings.bin");
1062 if !bin_path.exists() {
1063 return DiskStatus::default();
1064 }
1065 let meta = std::fs::metadata(&bin_path).ok();
1066 let partial = crate::core::embedding_index::partial_progress(root);
1067 DiskStatus {
1068 exists: true,
1069 size_bytes: meta.as_ref().map(std::fs::Metadata::len),
1070 file_count: partial.map(|(done, _)| done),
1071 modified_at: meta.and_then(|m| m.modified().ok()).map(format_time),
1072 partial_of: partial.map(|(_, total)| total),
1073 }
1074}
1075
1076pub fn disk_status(project_root: &str) -> DiskStatusAll {
1077 DiskStatusAll {
1078 graph_index: disk_status_for_graph(project_root),
1079 bm25_index: disk_status_for_bm25(project_root),
1080 code_graph: disk_status_for_code_graph(project_root),
1081 semantic_index: disk_status_for_semantic(project_root),
1082 }
1083}
1084
1085pub fn status_json(project_root: &str) -> String {
1086 let disk = disk_status(project_root);
1090 let state = entry_for(project_root);
1091 let s = state
1092 .lock()
1093 .unwrap_or_else(std::sync::PoisonError::into_inner);
1094 let graph_p = crate::core::index_progress::get(
1095 project_root,
1096 crate::core::index_progress::IndexComponent::Graph,
1097 );
1098 let bm25_p = crate::core::index_progress::get(
1099 project_root,
1100 crate::core::index_progress::IndexComponent::Bm25,
1101 );
1102 let semantic_p = crate::core::index_progress::get(
1103 project_root,
1104 crate::core::index_progress::IndexComponent::Semantic,
1105 );
1106 let res = StatusResponse {
1107 project_root,
1108 graph_index: component_status(&s.graph, graph_p),
1109 bm25_index: component_status(&s.bm25, bm25_p),
1110 semantic_index: component_status(&s.semantic, semantic_p),
1111 disk,
1112 index_filters: crate::core::index_filter::IndexFileFilter::effective().summary(),
1113 };
1114 serde_json::to_string(&res).unwrap_or_else(|_| "{}".to_string())
1115}
1116
1117#[cfg(test)]
1118mod tests {
1119 use super::*;
1120
1121 #[test]
1122 fn progress_view_graph_bm25_active_logic() {
1123 let idle = SlotProgress::default();
1124 let mut v = ProgressView {
1125 worker_running: true,
1126 graph_run_done: false,
1127 bm25_run_done: false,
1128 graph: idle,
1129 bm25: idle,
1130 semantic: idle,
1131 };
1132 assert!(v.graph_bm25_active(), "claimed, phases not done");
1133 v.graph_run_done = true;
1134 assert!(v.graph_bm25_active(), "graph done, bm25 pending");
1135 v.bm25_run_done = true;
1136 assert!(
1137 !v.graph_bm25_active(),
1138 "both phases done — search pre-warm must not keep wait open"
1139 );
1140 v.worker_running = false;
1141 assert!(!v.graph_bm25_active());
1142 v.graph_run_done = true;
1144 v.bm25_run_done = true;
1145 assert!(!v.graph_bm25_active());
1146 }
1147
1148 #[test]
1151 fn worker_slot_is_released_when_the_worker_panics() {
1152 let root = "/tmp/leanctx-worker-slot-panic-test";
1153 assert!(try_claim_worker(root));
1154 assert!(progress_view(root).graph_bm25_active());
1155 let result = std::panic::catch_unwind(|| {
1156 let _slot = WorkerSlot(root.to_string());
1157 panic!("simulated failure outside the phase catch_unwind");
1158 });
1159 assert!(result.is_err());
1160 let view = progress_view(root);
1161 assert!(!view.worker_running, "slot released by the guard");
1162 assert!(!view.graph_bm25_active(), "the CLI wait loop ends");
1163 assert!(try_claim_worker(root), "a later build can claim it again");
1164 drop(WorkerSlot(root.to_string()));
1165 }
1166
1167 #[test]
1168 fn status_json_is_valid_json() {
1169 let s = status_json("/tmp");
1170 let _: serde_json::Value = serde_json::from_str(&s).unwrap();
1171 }
1172
1173 #[test]
1174 fn background_build_phases_are_serialized_with_reclamation() {
1175 let events = std::cell::RefCell::new(Vec::new());
1176 run_memory_bounded_phases(
1177 || events.borrow_mut().push("graph"),
1178 || events.borrow_mut().push("bm25"),
1179 || events.borrow_mut().push("search"),
1180 || events.borrow_mut().push("reclaim"),
1181 );
1182 assert_eq!(
1183 events.into_inner(),
1184 ["graph", "reclaim", "bm25", "reclaim", "search"]
1185 );
1186 }
1187
1188 #[test]
1189 fn warm_need_classifies_tools() {
1190 for light in [
1192 "ctx_read",
1193 "ctx_shell",
1194 "ctx_tree",
1195 "ctx_knowledge",
1196 "unknown_tool",
1197 ] {
1198 assert_eq!(warm_need_for_tool(light), WarmNeed::None, "{light}");
1199 }
1200 assert_eq!(warm_need_for_tool("ctx_search"), WarmNeed::Search);
1202 for heavy in [
1203 "ctx_graph",
1204 "ctx_callgraph",
1205 "ctx_artifacts",
1206 "ctx_provider",
1207 "ctx_compose",
1208 ] {
1209 assert_eq!(warm_need_for_tool(heavy), WarmNeed::Heavy, "{heavy}");
1210 }
1211 }
1212
1213 #[test]
1214 fn ensure_warm_lightweight_and_search_never_signal_first_warm() {
1215 assert!(!ensure_warm_for_tool("", "ctx_graph"));
1216 let tmp = tempfile::tempdir().unwrap();
1217 let root = tmp.path().to_string_lossy().to_string();
1218 assert!(!ensure_warm_for_tool(&root, "ctx_read"));
1219 assert!(!ensure_warm_for_tool(&root, "ctx_search"));
1220 }
1221
1222 #[test]
1223 fn ensure_warm_heavy_is_once_per_root() {
1224 let tmp = tempfile::tempdir().unwrap();
1228 let root = tmp.path().to_string_lossy().to_string();
1229 assert!(
1230 ensure_warm_for_tool(&root, "ctx_callgraph"),
1231 "first heavy warm must signal true"
1232 );
1233 assert!(
1234 !ensure_warm_for_tool(&root, "ctx_callgraph"),
1235 "second heavy warm must be deduped to false"
1236 );
1237 assert!(
1238 !ensure_warm_for_tool(&root, "ctx_compose"),
1239 "any later heavy tool on the same root is also deduped"
1240 );
1241 }
1242
1243 #[test]
1244 fn build_note_persisted_reports_size() {
1245 let note = bm25_build_note(
1246 42,
1247 &Ok(crate::core::bm25_index::SaveOutcome::Persisted {
1248 compressed_bytes: 3 * 1024 * 1024,
1249 }),
1250 );
1251 assert!(
1252 note.contains("42 chunks"),
1253 "note should report chunk count: {note}"
1254 );
1255 assert!(
1256 note.contains("persisted"),
1257 "note should report persistence: {note}"
1258 );
1259 }
1260
1261 #[test]
1262 fn build_note_too_large_carries_remedy() {
1263 let note = bm25_build_note(
1264 1000,
1265 &Ok(crate::core::bm25_index::SaveOutcome::SkippedTooLarge {
1266 compressed_bytes: 600 * 1024 * 1024,
1267 limit_bytes: 512 * 1024 * 1024,
1268 }),
1269 );
1270 assert!(
1271 note.contains("NOT persisted"),
1272 "must flag non-persistence: {note}"
1273 );
1274 assert!(
1275 note.contains("LEAN_CTX_BM25_MAX_CACHE_MB") && note.contains("reindex"),
1276 "too-large note must carry an actionable remedy: {note}"
1277 );
1278 }
1279
1280 #[test]
1281 fn build_note_persist_error_is_reported() {
1282 let note = bm25_build_note(7, &Err(std::io::Error::other("disk full")));
1283 assert!(note.contains("persisting failed"), "note: {note}");
1284 assert!(
1285 note.contains("disk full"),
1286 "note should include the io error: {note}"
1287 );
1288 }
1289
1290 #[test]
1291 fn bm25_summary_unknown_project_is_idle() {
1292 let tmp = tempfile::tempdir().unwrap();
1293 let summary = bm25_summary(tmp.path().to_string_lossy().as_ref());
1294 assert_eq!(summary.state, "idle");
1295 assert!(summary.note.is_none());
1296 assert!(summary.last_error.is_none());
1297 }
1298
1299 #[test]
1300 fn extra_roots_skips_subdirs_of_primary() {
1301 let tmp = tempfile::tempdir().unwrap();
1302 let primary = tmp.path().join("primary");
1303 std::fs::create_dir_all(&primary).unwrap();
1304 let sub = primary.join("subdir");
1305 std::fs::create_dir_all(&sub).unwrap();
1306 let external = tmp.path().join("external");
1307 std::fs::create_dir_all(&external).unwrap();
1308
1309 let primary_str = primary.to_string_lossy().to_string();
1310 let extra = vec![
1311 sub.to_string_lossy().to_string(),
1312 external.to_string_lossy().to_string(),
1313 ];
1314
1315 ensure_extra_roots_background(&primary_str, &extra);
1317 }
1318
1319 #[test]
1320 fn extra_roots_caps_at_max() {
1321 let tmp = tempfile::tempdir().unwrap();
1322 let primary = tmp.path().join("primary");
1323 std::fs::create_dir_all(&primary).unwrap();
1324
1325 let mut extra = Vec::new();
1326 for i in 0..20 {
1327 let d = tmp.path().join(format!("ext-{i}"));
1328 std::fs::create_dir_all(&d).unwrap();
1329 extra.push(d.to_string_lossy().to_string());
1330 }
1331
1332 let primary_str = primary.to_string_lossy().to_string();
1333 ensure_extra_roots_background(&primary_str, &extra);
1335 }
1336
1337 #[test]
1338 fn bm25_index_lock_name_is_per_repo_and_distinct_from_graph() {
1339 let a = bm25_index_lock_name(Path::new("/tmp/repo-a"));
1340 let b = bm25_index_lock_name(Path::new("/tmp/repo-b"));
1341 assert!(a.starts_with("bm25-idx-"), "unexpected lock name: {a}");
1342 assert_ne!(a, b, "lock name must be per-repo");
1343 assert_eq!(a, bm25_index_lock_name(Path::new("/tmp/repo-a")));
1345 let graph = format!(
1348 "graph-idx-{}",
1349 &crate::core::index_namespace::namespace_hash(Path::new("/tmp/repo-a"))[..8]
1350 );
1351 assert_ne!(a, graph, "bm25 and graph locks must be independent");
1352 }
1353}