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"
180 | "ctx_callgraph"
181 | "ctx_routes"
182 | "ctx_repomap"
183 | "ctx_impact"
184 | "ctx_artifacts"
185 | "ctx_semantic_search"
186 | "ctx_provider"
187 | "ctx_compose"
188 | "ctx_explore"
189 | "ctx_review" => WarmNeed::Heavy,
190 _ => WarmNeed::None,
191 }
192}
193
194pub fn ensure_warm_for_tool(project_root: &str, tool: &str) -> bool {
201 if project_root.is_empty() {
202 return false;
203 }
204 match warm_need_for_tool(tool) {
205 WarmNeed::None => false,
206 WarmNeed::Search => {
207 crate::core::search_index::ensure_background(project_root, true, false);
210 false
211 }
212 WarmNeed::Heavy => {
213 let entry = entry_for(project_root);
214 let first_warm = {
215 let mut s = entry
216 .lock()
217 .unwrap_or_else(std::sync::PoisonError::into_inner);
218 if s.warm_triggered {
219 false
220 } else {
221 s.warm_triggered = true;
222 true
223 }
224 };
225 if first_warm {
226 ensure_all_background(project_root);
227 }
228 first_warm
229 }
230 }
231}
232
233const INDEXER_STACK_BYTES: usize = 16 * 1024 * 1024;
237
238fn nudge_daemon_index(project_root: &str) {
250 if crate::daemon::is_foreground_daemon() {
252 return;
253 }
254 let root = project_root.to_string();
255 let _ = std::thread::Builder::new()
256 .name("leanctx-index-nudge".to_string())
257 .spawn(move || {
258 if !crate::daemon::is_daemon_running() {
259 return;
260 }
261 let Ok(rt) = tokio::runtime::Runtime::new() else {
262 return;
263 };
264 let body = serde_json::json!({ "root": root }).to_string();
265 rt.block_on(async {
266 let _ = crate::daemon_client::try_daemon_request("POST", "/v1/index/ensure", &body)
267 .await;
268 });
269 });
270}
271
272fn try_claim_worker(project_root: &str) -> bool {
276 let state = entry_for(project_root);
277 let mut s = state
278 .lock()
279 .unwrap_or_else(std::sync::PoisonError::into_inner);
280 if s.worker_running {
281 false
282 } else {
283 s.worker_running = true;
284 s.graph_run_done = false;
285 s.bm25_run_done = false;
286 true
287 }
288}
289
290pub fn ensure_all_background(project_root: &str) {
291 if !try_claim_worker(project_root) {
292 return;
293 }
294
295 if !crate::core::index_filter::cli_overlay_active() {
304 nudge_daemon_index(project_root);
305 }
306
307 let state = entry_for(project_root);
308 let root = project_root.to_string();
309 let indexer = move || run_build_worker(&root);
310
311 let spawned = std::thread::Builder::new()
315 .name("leanctx-index".to_string())
316 .stack_size(INDEXER_STACK_BYTES)
317 .spawn(indexer);
318 if spawned.is_err() {
319 let mut s = state
322 .lock()
323 .unwrap_or_else(std::sync::PoisonError::into_inner);
324 s.worker_running = false;
325 }
326}
327
328fn run_build_worker(root: &str) {
333 let _slot = WorkerSlot(root.to_string());
337
338 start_index_memory_guard("build_worker");
345
346 let graph_state = entry_for(root);
352 let graph_root = root.to_string();
353 let build_graph = move || {
354 {
355 let mut s = graph_state
356 .lock()
357 .unwrap_or_else(std::sync::PoisonError::into_inner);
358 start_component(&mut s.graph);
359 }
360 let guard = crate::core::index_progress::ProgressGuard::new(
362 graph_root.clone(),
363 crate::core::index_progress::IndexComponent::Graph,
364 );
365 guard.report(0, 0);
366 let graph_result = std::panic::catch_unwind(|| {
367 let (idx, _cache) = graph_index::scan_with_content_cache(&graph_root);
368 crate::core::code_health::persist::refresh_if_stale(&graph_root, &idx);
372 });
373 if graph_result.is_ok() {
374 let _ = std::panic::catch_unwind(|| {
377 crate::core::graph_enricher::refresh_semantic_edges_in_background(&graph_root);
378 });
379 }
380 drop(guard);
381 crate::core::telemetry_features::record(
382 crate::core::telemetry_features::Feature::GraphIndex,
383 graph_result.is_ok(),
384 );
385 {
386 let mut s = graph_state
387 .lock()
388 .unwrap_or_else(std::sync::PoisonError::into_inner);
389 if let Ok(()) = graph_result {
390 finish_ok(&mut s.graph);
391 } else {
392 finish_err(&mut s.graph, "graph index build panicked".to_string());
393 }
394 s.graph_run_done = true;
395 }
396 };
397
398 let bm25_state = entry_for(root);
399 let bm25_root = root.to_string();
400 let build_bm25 = move || {
401 {
402 let mut s = bm25_state
403 .lock()
404 .unwrap_or_else(std::sync::PoisonError::into_inner);
405 start_component(&mut s.bm25);
406 }
407 let _progress = crate::core::index_progress::ProgressGuard::new(
408 bm25_root.clone(),
409 crate::core::index_progress::IndexComponent::Bm25,
410 );
411 let bm = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
412 let root_pb = Path::new(&bm25_root);
413 let lock_name = bm25_index_lock_name(root_pb);
414 let _lock = crate::core::startup_guard::try_acquire_lock(
415 &lock_name,
416 std::time::Duration::from_millis(800),
417 std::time::Duration::from_mins(3),
418 );
419 if _lock.is_none() {
420 tracing::info!(
421 "[bm25: another process is building {bm25_root} — loading the shared index]"
422 );
423 let idx = BM25Index::load(root_pb).unwrap_or_default();
424 return (idx.doc_count, None);
425 }
426 let idx = BM25Index::load_or_build(root_pb);
427 let outcome = idx.save(root_pb);
428 (idx.doc_count, Some(outcome))
429 }));
430 if !matches!(bm, Ok((_, None))) {
432 crate::core::telemetry_features::record(
433 crate::core::telemetry_features::Feature::Bm25Index,
434 bm.is_ok(),
435 );
436 }
437 {
438 let mut s = bm25_state
439 .lock()
440 .unwrap_or_else(std::sync::PoisonError::into_inner);
441 if let Ok((doc_count, save_res)) = bm {
442 finish_ok(&mut s.bm25);
443 s.bm25.note = Some(match save_res {
444 Some(outcome) => bm25_build_note(doc_count, &outcome),
445 None => format!(
446 "loaded shared BM25 index ({doc_count} chunks) — build in progress in another process"
447 ),
448 });
449 } else {
450 finish_err(&mut s.bm25, "bm25 build panicked".to_string());
451 }
452 s.bm25_run_done = true;
453 }
454 };
455
456 run_memory_bounded_phases(
457 build_graph,
458 build_bm25,
459 || crate::core::search_index::ensure_background(root, true, false),
460 || {
461 crate::core::content_cache::clear();
462 crate::core::memory_guard::force_purge();
463 },
464 );
465
466 crate::core::content_cache::trim_oldest_percent(75);
473 crate::core::memory_guard::force_purge();
474}
475
476struct WorkerSlot(String);
479
480impl Drop for WorkerSlot {
481 fn drop(&mut self) {
482 let state = entry_for(&self.0);
483 let mut s = state
484 .lock()
485 .unwrap_or_else(std::sync::PoisonError::into_inner);
486 s.worker_running = false;
487 }
488}
489
490fn run_memory_bounded_phases<G, B, S, R>(graph: G, bm25: B, search: S, mut reclaim: R)
493where
494 G: FnOnce(),
495 B: FnOnce(),
496 S: FnOnce(),
497 R: FnMut(),
498{
499 graph();
500 reclaim();
501 bm25();
502 reclaim();
503 search();
504}
505
506pub fn build_semantic(project_root: &str) {
511 let state = entry_for(project_root);
512 let root = Path::new(project_root);
513
514 let Some(_lock) = crate::core::startup_guard::try_acquire_lock(
515 &semantic_index_lock_name(root),
516 std::time::Duration::ZERO,
517 SEMANTIC_LOCK_STALE_AFTER,
518 ) else {
519 let mut s = state
520 .lock()
521 .unwrap_or_else(std::sync::PoisonError::into_inner);
522 s.semantic.note = Some(
523 "another lean-ctx process is already building the semantic index for this project; \
524 it saves progress as it goes — check `lean-ctx index status` later"
525 .to_string(),
526 );
527 return;
528 };
529
530 {
531 let mut s = state
532 .lock()
533 .unwrap_or_else(std::sync::PoisonError::into_inner);
534 start_component(&mut s.semantic);
535 }
536
537 let _progress = crate::core::index_progress::ProgressGuard::new(
539 project_root.to_string(),
540 crate::core::index_progress::IndexComponent::Semantic,
541 );
542
543 let bm25_idx = try_load_bm25_index(project_root);
544 match bm25_idx.as_ref() {
545 Some(idx) if idx.doc_count > 0 => {
546 let outcome = crate::core::embedding_index::build_or_update(root, idx);
547 match outcome {
548 crate::core::embedding_index::EmbeddingBuildOutcome::Ready => {
549 crate::core::telemetry_features::record(
550 crate::core::telemetry_features::Feature::SemanticIndex,
551 true,
552 );
553 }
554 crate::core::embedding_index::EmbeddingBuildOutcome::Failed => {
555 crate::core::telemetry_features::record(
556 crate::core::telemetry_features::Feature::SemanticIndex,
557 false,
558 );
559 }
560 _ => {}
561 }
562 let mut s = state
563 .lock()
564 .unwrap_or_else(std::sync::PoisonError::into_inner);
565 match outcome {
566 crate::core::embedding_index::EmbeddingBuildOutcome::Ready => {
567 finish_ok(&mut s.semantic);
568 }
569 crate::core::embedding_index::EmbeddingBuildOutcome::Skipped => {
570 finish_ok(&mut s.semantic);
571 s.semantic.note = Some(
572 "embeddings disabled by feature flag or config (search.dense_enabled / memory_profile)"
573 .to_string(),
574 );
575 }
576 crate::core::embedding_index::EmbeddingBuildOutcome::ModelNotAvailable(
577 ref reason,
578 ) => {
579 s.semantic.state = State::Idle;
582 s.semantic.note = Some(format!("embedding model not available: {reason}"));
583 }
584 crate::core::embedding_index::EmbeddingBuildOutcome::Failed => {
585 finish_err(
586 &mut s.semantic,
587 "embedding build failed (see logs)".to_string(),
588 );
589 }
590 }
591 }
592 _ => {
593 let mut s = state
594 .lock()
595 .unwrap_or_else(std::sync::PoisonError::into_inner);
596 s.semantic.state = State::Idle;
598 s.semantic.note =
599 Some("BM25 index is empty or unavailable — nothing to embed".to_string());
600 }
601 }
602}
603
604pub fn build_semantic_background(project_root: &str) {
609 let root = project_root.to_string();
610 let spawned = std::thread::Builder::new()
611 .name("leanctx-semantic".to_string())
612 .stack_size(INDEXER_STACK_BYTES)
613 .spawn(move || {
614 start_index_memory_guard("semantic_build");
615 if !disk_status(&root).bm25_index.exists {
616 ensure_all_background(&root);
617 }
618 while progress_view(&root).graph_bm25_active() {
619 std::thread::sleep(std::time::Duration::from_millis(250));
620 }
621 build_semantic(&root);
622 });
623 if let Err(e) = spawned {
624 tracing::warn!("[index_orchestrator: could not spawn semantic worker: {e}]");
625 }
626}
627
628fn start_index_memory_guard(label: &'static str) {
630 crate::core::memory_guard::start_guard(std::sync::Arc::new(move |level| {
631 tracing::warn!("[{label}] memory pressure: {level:?} — background tasks will throttle");
632 if level >= crate::core::memory_guard::PressureLevel::Hard {
633 crate::core::content_cache::clear();
634 }
635 crate::core::memory_guard::force_purge();
636 true
637 }));
638}
639
640const MAX_EXTRA_ROOT_BUILDS: usize = 8;
644
645pub fn ensure_extra_roots_background(primary_root: &str, extra_roots: &[String]) {
646 let primary = Path::new(primary_root);
647 let mut queue: Vec<String> = Vec::new();
648 for root in extra_roots {
649 if queue.len() >= MAX_EXTRA_ROOT_BUILDS {
650 break;
651 }
652 let rp = Path::new(root);
653 if !rp.is_dir() {
654 continue;
655 }
656 if rp.starts_with(primary) {
658 continue;
659 }
660 if primary.starts_with(rp) {
662 continue;
663 }
664 queue.push(root.clone());
665 }
666 if queue.is_empty() {
667 return;
668 }
669
670 let spawned = std::thread::Builder::new()
679 .name("leanctx-extra-roots".to_string())
680 .stack_size(INDEXER_STACK_BYTES)
681 .spawn(move || {
682 for root in queue {
683 if crate::core::memory_guard::is_under_pressure()
684 || crate::core::memory_guard::abort_requested()
685 {
686 tracing::warn!(
687 "[index_orchestrator: skipping remaining extra-root builds under memory pressure]"
688 );
689 break;
690 }
691 if !try_claim_worker(&root) {
692 continue; }
694 nudge_daemon_index(&root);
695 run_build_worker(&root);
696 }
697 });
698 if let Err(e) = spawned {
699 tracing::warn!("[index_orchestrator: could not spawn extra-roots worker: {e}]");
700 }
701}
702
703fn bm25_build_note(
708 doc_count: usize,
709 save: &std::io::Result<crate::core::bm25_index::SaveOutcome>,
710) -> String {
711 use crate::core::bm25_index::SaveOutcome;
712 match save {
713 Ok(SaveOutcome::Persisted { compressed_bytes }) => format!(
714 "indexed {doc_count} chunks, {:.1} MB persisted",
715 *compressed_bytes as f64 / 1_048_576.0
716 ),
717 Ok(SaveOutcome::SkippedTooLarge {
718 compressed_bytes,
719 limit_bytes,
720 }) => format!(
721 "indexed {doc_count} chunks but NOT persisted to disk: compressed {:.1} MB exceeds the {:.0} MB cap. \
722 Raise it via LEAN_CTX_BM25_MAX_CACHE_MB (or bm25_max_cache_mb in config) or add extra_ignore_patterns, \
723 then run `lean-ctx reindex`. Until then the index is rebuilt from scratch on every cold start.",
724 *compressed_bytes as f64 / 1_048_576.0,
725 *limit_bytes as f64 / 1_048_576.0
726 ),
727 Err(e) => format!("indexed {doc_count} chunks but persisting failed: {e}"),
728 }
729}
730
731#[derive(Debug, Clone)]
734pub struct Bm25Summary {
735 pub state: &'static str,
736 pub elapsed_ms: Option<u64>,
738 pub note: Option<String>,
739 pub last_error: Option<String>,
740}
741
742#[derive(Debug, Clone)]
744pub struct SemanticSummary {
745 pub state: &'static str,
746 pub elapsed_ms: Option<u64>,
747 pub note: Option<String>,
748 pub last_error: Option<String>,
749}
750
751fn component_elapsed_and_state(c: &Component) -> (&'static str, Option<u64>) {
755 let elapsed_ms = if matches!(c.state, State::Building) {
756 c.started_ms.map(|start| now_ms().saturating_sub(start))
757 } else {
758 c.duration_ms
759 };
760 let state = match c.state {
761 State::Idle => "idle",
762 State::Building => "building",
763 State::Ready => "ready",
764 State::Failed => "failed",
765 };
766 (state, elapsed_ms)
767}
768
769pub fn semantic_summary(project_root: &str) -> SemanticSummary {
770 let entry = entry_for(project_root);
771 let s = entry
772 .lock()
773 .unwrap_or_else(std::sync::PoisonError::into_inner);
774 let c = &s.semantic;
775 let (state, elapsed_ms) = component_elapsed_and_state(c);
776 SemanticSummary {
777 state,
778 elapsed_ms,
779 note: c.note.clone(),
780 last_error: c.last_error.clone(),
781 }
782}
783
784pub fn bm25_summary(project_root: &str) -> Bm25Summary {
785 let entry = entry_for(project_root);
786 let s = entry
787 .lock()
788 .unwrap_or_else(std::sync::PoisonError::into_inner);
789 let c = &s.bm25;
790 let (state, elapsed_ms) = component_elapsed_and_state(c);
791 Bm25Summary {
792 state,
793 elapsed_ms,
794 note: c.note.clone(),
795 last_error: c.last_error.clone(),
796 }
797}
798
799pub fn try_load_graph_index(project_root: &str) -> Option<ProjectIndex> {
800 crate::core::graph_cache::get_cached(project_root).map(|arc| (*arc).clone())
803}
804
805pub fn try_load_bm25_index(project_root: &str) -> Option<BM25Index> {
806 BM25Index::load(Path::new(project_root))
807}
808
809#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
811pub struct SlotProgress {
812 pub building: bool,
813 pub done: u64,
814 pub total: u64,
815}
816
817impl SlotProgress {
818 pub fn is_determinate(&self) -> bool {
819 self.building && self.total > 0
820 }
821}
822
823#[derive(Debug, Clone, PartialEq, Eq)]
825pub struct ProgressView {
826 pub worker_running: bool,
827 pub graph_run_done: bool,
829 pub bm25_run_done: bool,
831 pub graph: SlotProgress,
832 pub bm25: SlotProgress,
833 pub semantic: SlotProgress,
834}
835
836impl ProgressView {
837 pub fn graph_bm25_active(&self) -> bool {
842 self.worker_running && !(self.graph_run_done && self.bm25_run_done)
843 }
844
845 pub fn semantic_active(&self) -> bool {
846 self.semantic.building
847 }
848}
849
850pub fn progress_view(project_root: &str) -> ProgressView {
852 use crate::core::index_progress::{self, IndexComponent};
853 let (worker_running, graph_run_done, bm25_run_done, graph_b, bm25_b, sem_b) = {
854 let state = entry_for(project_root);
855 let s = state
856 .lock()
857 .unwrap_or_else(std::sync::PoisonError::into_inner);
858 (
859 s.worker_running,
860 s.graph_run_done,
861 s.bm25_run_done,
862 matches!(s.graph.state, State::Building),
863 matches!(s.bm25.state, State::Building),
864 matches!(s.semantic.state, State::Building),
865 )
866 };
867 let g = index_progress::get(project_root, IndexComponent::Graph);
868 let b = index_progress::get(project_root, IndexComponent::Bm25);
869 let sem = index_progress::get(project_root, IndexComponent::Semantic);
870 ProgressView {
871 worker_running,
872 graph_run_done,
873 bm25_run_done,
874 graph: SlotProgress {
875 building: graph_b,
876 done: g.done,
877 total: g.total,
878 },
879 bm25: SlotProgress {
880 building: bm25_b,
881 done: b.done,
882 total: b.total,
883 },
884 semantic: SlotProgress {
885 building: sem_b,
886 done: sem.done,
887 total: sem.total,
888 },
889 }
890}
891
892pub fn is_building() -> bool {
894 let map = registry()
895 .lock()
896 .unwrap_or_else(std::sync::PoisonError::into_inner);
897 map.values().any(|entry| {
898 let st = entry
899 .lock()
900 .unwrap_or_else(std::sync::PoisonError::into_inner);
901 matches!(st.bm25.state, State::Building)
902 || matches!(st.graph.state, State::Building)
903 || matches!(st.semantic.state, State::Building)
904 })
905}
906
907#[derive(Debug, Serialize)]
908struct ComponentStatus<'a> {
909 state: &'a str,
910 started_ms: Option<u64>,
911 finished_ms: Option<u64>,
912 duration_ms: Option<u64>,
913 last_error: Option<&'a str>,
914 #[serde(skip_serializing_if = "Option::is_none")]
915 note: Option<&'a str>,
916 #[serde(skip_serializing_if = "Option::is_none")]
918 progress_done: Option<u64>,
919 #[serde(skip_serializing_if = "Option::is_none")]
921 progress_total: Option<u64>,
922}
923
924fn component_status(
925 c: &Component,
926 progress: crate::core::index_progress::ProgressSnapshot,
927) -> ComponentStatus<'_> {
928 let (progress_done, progress_total) = if matches!(c.state, State::Building) {
929 (Some(progress.done), Some(progress.total))
930 } else {
931 (None, None)
932 };
933 ComponentStatus {
934 state: match c.state {
935 State::Idle => "idle",
936 State::Building => "building",
937 State::Ready => "ready",
938 State::Failed => "failed",
939 },
940 started_ms: c.started_ms,
941 finished_ms: c.finished_ms,
942 duration_ms: c.duration_ms,
943 last_error: c.last_error.as_deref(),
944 note: c.note.as_deref(),
945 progress_done,
946 progress_total,
947 }
948}
949
950#[derive(Debug, Serialize)]
951struct StatusResponse<'a> {
952 project_root: &'a str,
953 graph_index: ComponentStatus<'a>,
954 bm25_index: ComponentStatus<'a>,
955 semantic_index: ComponentStatus<'a>,
959 disk: DiskStatusAll,
960 #[serde(skip_serializing_if = "Option::is_none")]
963 index_filters: Option<String>,
964}
965
966#[derive(Debug, Serialize, Default)]
967pub struct DiskStatus {
968 pub exists: bool,
969 pub size_bytes: Option<u64>,
970 pub file_count: Option<u64>,
971 pub modified_at: Option<String>,
972 #[serde(skip_serializing_if = "Option::is_none")]
976 pub partial_of: Option<u64>,
977}
978
979#[derive(Debug, Serialize, Default)]
980pub struct DiskStatusAll {
981 pub graph_index: DiskStatus,
982 pub bm25_index: DiskStatus,
983 pub code_graph: DiskStatus,
984 pub semantic_index: DiskStatus,
988}
989
990fn disk_status_for_graph(project_root: &str) -> DiskStatus {
991 let Some(dir) = graph_index::ProjectIndex::index_dir(project_root) else {
997 return DiskStatus::default();
998 };
999 let meta_file = dir.join("graph.meta.json");
1000 if !meta_file.exists() {
1001 return DiskStatus::default();
1002 }
1003 let meta = std::fs::metadata(&meta_file).ok();
1004 let file_count =
1005 graph_index::ProjectIndex::load(project_root).map(|idx| idx.files.len() as u64);
1006 DiskStatus {
1007 exists: true,
1008 size_bytes: None,
1009 file_count,
1010 modified_at: meta.and_then(|m| m.modified().ok()).map(format_time),
1011 partial_of: None,
1012 }
1013}
1014
1015fn disk_status_for_bm25(project_root: &str) -> DiskStatus {
1016 let root = Path::new(project_root);
1017 let path = BM25Index::index_file_path(root);
1018 if !path.exists() {
1019 return DiskStatus::default();
1020 }
1021 let meta = std::fs::metadata(&path).ok();
1022 DiskStatus {
1023 exists: true,
1024 size_bytes: meta.as_ref().map(std::fs::Metadata::len),
1025 file_count: BM25Index::persisted_chunk_count(root),
1026 modified_at: meta.and_then(|m| m.modified().ok()).map(format_time),
1027 partial_of: None,
1028 }
1029}
1030
1031fn disk_status_for_code_graph(project_root: &str) -> DiskStatus {
1032 let dir = crate::core::property_graph::graph_dir(project_root);
1033 let db_path = dir.join("graph.db");
1034 if !db_path.exists() {
1035 return DiskStatus::default();
1036 }
1037 let meta = std::fs::metadata(&db_path).ok();
1038 let node_count = crate::core::property_graph::CodeGraph::open(project_root)
1039 .ok()
1040 .and_then(|g| {
1041 g.connection()
1042 .query_row("SELECT count(*) FROM nodes", [], |r| r.get::<_, i64>(0))
1043 .ok()
1044 .map(|c| c as u64)
1045 });
1046 DiskStatus {
1047 exists: true,
1048 size_bytes: meta.as_ref().map(std::fs::Metadata::len),
1049 file_count: node_count,
1050 modified_at: meta.and_then(|m| m.modified().ok()).map(format_time),
1051 partial_of: None,
1052 }
1053}
1054
1055fn format_time(t: SystemTime) -> String {
1056 let secs = t.duration_since(UNIX_EPOCH).unwrap_or_default().as_secs();
1057 let dt = chrono::DateTime::from_timestamp(secs as i64, 0);
1058 dt.map_or_else(
1059 || format!("{secs}"),
1060 |d| d.format("%Y-%m-%d %H:%M:%S UTC").to_string(),
1061 )
1062}
1063
1064pub fn disk_status_for_semantic(project_root: &str) -> DiskStatus {
1065 let root = Path::new(project_root);
1066 let dir = crate::core::index_namespace::vectors_dir(root);
1067 let bin_path = dir.join("embeddings.bin");
1068 if !bin_path.exists() {
1069 return DiskStatus::default();
1070 }
1071 let meta = std::fs::metadata(&bin_path).ok();
1072 let partial = crate::core::embedding_index::partial_progress(root);
1073 DiskStatus {
1074 exists: true,
1075 size_bytes: meta.as_ref().map(std::fs::Metadata::len),
1076 file_count: partial.map(|(done, _)| done),
1077 modified_at: meta.and_then(|m| m.modified().ok()).map(format_time),
1078 partial_of: partial.map(|(_, total)| total),
1079 }
1080}
1081
1082pub fn disk_status(project_root: &str) -> DiskStatusAll {
1083 DiskStatusAll {
1084 graph_index: disk_status_for_graph(project_root),
1085 bm25_index: disk_status_for_bm25(project_root),
1086 code_graph: disk_status_for_code_graph(project_root),
1087 semantic_index: disk_status_for_semantic(project_root),
1088 }
1089}
1090
1091pub fn status_json(project_root: &str) -> String {
1092 let disk = disk_status(project_root);
1096 let state = entry_for(project_root);
1097 let s = state
1098 .lock()
1099 .unwrap_or_else(std::sync::PoisonError::into_inner);
1100 let graph_p = crate::core::index_progress::get(
1101 project_root,
1102 crate::core::index_progress::IndexComponent::Graph,
1103 );
1104 let bm25_p = crate::core::index_progress::get(
1105 project_root,
1106 crate::core::index_progress::IndexComponent::Bm25,
1107 );
1108 let semantic_p = crate::core::index_progress::get(
1109 project_root,
1110 crate::core::index_progress::IndexComponent::Semantic,
1111 );
1112 let res = StatusResponse {
1113 project_root,
1114 graph_index: component_status(&s.graph, graph_p),
1115 bm25_index: component_status(&s.bm25, bm25_p),
1116 semantic_index: component_status(&s.semantic, semantic_p),
1117 disk,
1118 index_filters: crate::core::index_filter::IndexFileFilter::effective().summary(),
1119 };
1120 serde_json::to_string(&res).unwrap_or_else(|_| "{}".to_string())
1121}
1122
1123#[cfg(test)]
1124mod tests {
1125 use super::*;
1126
1127 #[test]
1128 fn progress_view_graph_bm25_active_logic() {
1129 let idle = SlotProgress::default();
1130 let mut v = ProgressView {
1131 worker_running: true,
1132 graph_run_done: false,
1133 bm25_run_done: false,
1134 graph: idle,
1135 bm25: idle,
1136 semantic: idle,
1137 };
1138 assert!(v.graph_bm25_active(), "claimed, phases not done");
1139 v.graph_run_done = true;
1140 assert!(v.graph_bm25_active(), "graph done, bm25 pending");
1141 v.bm25_run_done = true;
1142 assert!(
1143 !v.graph_bm25_active(),
1144 "both phases done — search pre-warm must not keep wait open"
1145 );
1146 v.worker_running = false;
1147 assert!(!v.graph_bm25_active());
1148 v.graph_run_done = true;
1150 v.bm25_run_done = true;
1151 assert!(!v.graph_bm25_active());
1152 }
1153
1154 #[test]
1157 fn worker_slot_is_released_when_the_worker_panics() {
1158 let root = "/tmp/leanctx-worker-slot-panic-test";
1159 assert!(try_claim_worker(root));
1160 assert!(progress_view(root).graph_bm25_active());
1161 let result = std::panic::catch_unwind(|| {
1162 let _slot = WorkerSlot(root.to_string());
1163 panic!("simulated failure outside the phase catch_unwind");
1164 });
1165 assert!(result.is_err());
1166 let view = progress_view(root);
1167 assert!(!view.worker_running, "slot released by the guard");
1168 assert!(!view.graph_bm25_active(), "the CLI wait loop ends");
1169 assert!(try_claim_worker(root), "a later build can claim it again");
1170 drop(WorkerSlot(root.to_string()));
1171 }
1172
1173 #[test]
1174 fn status_json_is_valid_json() {
1175 let s = status_json("/tmp");
1176 let _: serde_json::Value = serde_json::from_str(&s).unwrap();
1177 }
1178
1179 #[test]
1180 fn background_build_phases_are_serialized_with_reclamation() {
1181 let events = std::cell::RefCell::new(Vec::new());
1182 run_memory_bounded_phases(
1183 || events.borrow_mut().push("graph"),
1184 || events.borrow_mut().push("bm25"),
1185 || events.borrow_mut().push("search"),
1186 || events.borrow_mut().push("reclaim"),
1187 );
1188 assert_eq!(
1189 events.into_inner(),
1190 ["graph", "reclaim", "bm25", "reclaim", "search"]
1191 );
1192 }
1193
1194 #[test]
1195 fn warm_need_classifies_tools() {
1196 for light in [
1198 "ctx_read",
1199 "ctx_shell",
1200 "ctx_tree",
1201 "ctx_knowledge",
1202 "unknown_tool",
1203 ] {
1204 assert_eq!(warm_need_for_tool(light), WarmNeed::None, "{light}");
1205 }
1206 assert_eq!(warm_need_for_tool("ctx_search"), WarmNeed::Search);
1208 for heavy in [
1209 "ctx_graph",
1210 "ctx_callgraph",
1211 "ctx_routes",
1212 "ctx_repomap",
1213 "ctx_impact",
1214 "ctx_artifacts",
1215 "ctx_semantic_search",
1216 "ctx_provider",
1217 "ctx_compose",
1218 "ctx_explore",
1219 "ctx_review",
1220 ] {
1221 assert_eq!(warm_need_for_tool(heavy), WarmNeed::Heavy, "{heavy}");
1222 }
1223 }
1224
1225 #[test]
1226 fn ensure_warm_lightweight_and_search_never_signal_first_warm() {
1227 assert!(!ensure_warm_for_tool("", "ctx_graph"));
1228 let tmp = tempfile::tempdir().unwrap();
1229 let root = tmp.path().to_string_lossy().to_string();
1230 assert!(!ensure_warm_for_tool(&root, "ctx_read"));
1231 assert!(!ensure_warm_for_tool(&root, "ctx_search"));
1232 }
1233
1234 #[test]
1235 fn ensure_warm_heavy_is_once_per_root() {
1236 let tmp = tempfile::tempdir().unwrap();
1240 let root = tmp.path().to_string_lossy().to_string();
1241 assert!(
1242 ensure_warm_for_tool(&root, "ctx_callgraph"),
1243 "first heavy warm must signal true"
1244 );
1245 assert!(
1246 !ensure_warm_for_tool(&root, "ctx_callgraph"),
1247 "second heavy warm must be deduped to false"
1248 );
1249 assert!(
1250 !ensure_warm_for_tool(&root, "ctx_semantic_search"),
1251 "any later heavy tool on the same root is also deduped"
1252 );
1253 }
1254
1255 #[test]
1256 fn build_note_persisted_reports_size() {
1257 let note = bm25_build_note(
1258 42,
1259 &Ok(crate::core::bm25_index::SaveOutcome::Persisted {
1260 compressed_bytes: 3 * 1024 * 1024,
1261 }),
1262 );
1263 assert!(
1264 note.contains("42 chunks"),
1265 "note should report chunk count: {note}"
1266 );
1267 assert!(
1268 note.contains("persisted"),
1269 "note should report persistence: {note}"
1270 );
1271 }
1272
1273 #[test]
1274 fn build_note_too_large_carries_remedy() {
1275 let note = bm25_build_note(
1276 1000,
1277 &Ok(crate::core::bm25_index::SaveOutcome::SkippedTooLarge {
1278 compressed_bytes: 600 * 1024 * 1024,
1279 limit_bytes: 512 * 1024 * 1024,
1280 }),
1281 );
1282 assert!(
1283 note.contains("NOT persisted"),
1284 "must flag non-persistence: {note}"
1285 );
1286 assert!(
1287 note.contains("LEAN_CTX_BM25_MAX_CACHE_MB") && note.contains("reindex"),
1288 "too-large note must carry an actionable remedy: {note}"
1289 );
1290 }
1291
1292 #[test]
1293 fn build_note_persist_error_is_reported() {
1294 let note = bm25_build_note(7, &Err(std::io::Error::other("disk full")));
1295 assert!(note.contains("persisting failed"), "note: {note}");
1296 assert!(
1297 note.contains("disk full"),
1298 "note should include the io error: {note}"
1299 );
1300 }
1301
1302 #[test]
1303 fn bm25_summary_unknown_project_is_idle() {
1304 let tmp = tempfile::tempdir().unwrap();
1305 let summary = bm25_summary(tmp.path().to_string_lossy().as_ref());
1306 assert_eq!(summary.state, "idle");
1307 assert!(summary.note.is_none());
1308 assert!(summary.last_error.is_none());
1309 }
1310
1311 #[test]
1312 fn extra_roots_skips_subdirs_of_primary() {
1313 let tmp = tempfile::tempdir().unwrap();
1314 let primary = tmp.path().join("primary");
1315 std::fs::create_dir_all(&primary).unwrap();
1316 let sub = primary.join("subdir");
1317 std::fs::create_dir_all(&sub).unwrap();
1318 let external = tmp.path().join("external");
1319 std::fs::create_dir_all(&external).unwrap();
1320
1321 let primary_str = primary.to_string_lossy().to_string();
1322 let extra = vec![
1323 sub.to_string_lossy().to_string(),
1324 external.to_string_lossy().to_string(),
1325 ];
1326
1327 ensure_extra_roots_background(&primary_str, &extra);
1329 }
1330
1331 #[test]
1332 fn extra_roots_caps_at_max() {
1333 let tmp = tempfile::tempdir().unwrap();
1334 let primary = tmp.path().join("primary");
1335 std::fs::create_dir_all(&primary).unwrap();
1336
1337 let mut extra = Vec::new();
1338 for i in 0..20 {
1339 let d = tmp.path().join(format!("ext-{i}"));
1340 std::fs::create_dir_all(&d).unwrap();
1341 extra.push(d.to_string_lossy().to_string());
1342 }
1343
1344 let primary_str = primary.to_string_lossy().to_string();
1345 ensure_extra_roots_background(&primary_str, &extra);
1347 }
1348
1349 #[test]
1350 fn bm25_index_lock_name_is_per_repo_and_distinct_from_graph() {
1351 let a = bm25_index_lock_name(Path::new("/tmp/repo-a"));
1352 let b = bm25_index_lock_name(Path::new("/tmp/repo-b"));
1353 assert!(a.starts_with("bm25-idx-"), "unexpected lock name: {a}");
1354 assert_ne!(a, b, "lock name must be per-repo");
1355 assert_eq!(a, bm25_index_lock_name(Path::new("/tmp/repo-a")));
1357 let graph = format!(
1360 "graph-idx-{}",
1361 &crate::core::index_namespace::namespace_hash(Path::new("/tmp/repo-a"))[..8]
1362 );
1363 assert_ne!(a, graph, "bm25 and graph locks must be independent");
1364 }
1365}