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 start_component(c: &mut Component) {
121 c.state = State::Building;
122 c.started_ms = Some(now_ms());
123 c.finished_ms = None;
124 c.duration_ms = None;
125 c.last_error = None;
126 c.note = None;
127}
128
129fn finish_ok(c: &mut Component) {
130 c.state = State::Ready;
131 let end = now_ms();
132 c.finished_ms = Some(end);
133 c.duration_ms = c.started_ms.map(|s| end.saturating_sub(s));
134}
135
136fn finish_err(c: &mut Component, e: String) {
137 c.state = State::Failed;
138 let end = now_ms();
139 c.finished_ms = Some(end);
140 c.duration_ms = c.started_ms.map(|s| end.saturating_sub(s));
141 c.last_error = Some(e);
142}
143
144#[derive(Debug, Clone, Copy, PartialEq, Eq)]
149pub enum WarmNeed {
150 None,
152 Search,
154 Heavy,
156}
157
158#[must_use]
162pub fn warm_need_for_tool(tool: &str) -> WarmNeed {
163 match tool {
164 "ctx_search" => WarmNeed::Search,
165 "ctx_graph"
167 | "ctx_callgraph"
168 | "ctx_routes"
169 | "ctx_repomap"
170 | "ctx_impact"
171 | "ctx_artifacts"
172 | "ctx_semantic_search"
173 | "ctx_provider"
174 | "ctx_compose"
175 | "ctx_explore"
176 | "ctx_review" => WarmNeed::Heavy,
177 _ => WarmNeed::None,
178 }
179}
180
181pub fn ensure_warm_for_tool(project_root: &str, tool: &str) -> bool {
188 if project_root.is_empty() {
189 return false;
190 }
191 match warm_need_for_tool(tool) {
192 WarmNeed::None => false,
193 WarmNeed::Search => {
194 crate::core::search_index::ensure_background(project_root, true, false);
197 false
198 }
199 WarmNeed::Heavy => {
200 let entry = entry_for(project_root);
201 let first_warm = {
202 let mut s = entry
203 .lock()
204 .unwrap_or_else(std::sync::PoisonError::into_inner);
205 if s.warm_triggered {
206 false
207 } else {
208 s.warm_triggered = true;
209 true
210 }
211 };
212 if first_warm {
213 ensure_all_background(project_root);
214 }
215 first_warm
216 }
217 }
218}
219
220const INDEXER_STACK_BYTES: usize = 16 * 1024 * 1024;
224
225fn nudge_daemon_index(project_root: &str) {
237 if crate::daemon::is_foreground_daemon() {
239 return;
240 }
241 let root = project_root.to_string();
242 let _ = std::thread::Builder::new()
243 .name("leanctx-index-nudge".to_string())
244 .spawn(move || {
245 if !crate::daemon::is_daemon_running() {
246 return;
247 }
248 let Ok(rt) = tokio::runtime::Runtime::new() else {
249 return;
250 };
251 let body = serde_json::json!({ "root": root }).to_string();
252 rt.block_on(async {
253 let _ = crate::daemon_client::try_daemon_request("POST", "/v1/index/ensure", &body)
254 .await;
255 });
256 });
257}
258
259fn try_claim_worker(project_root: &str) -> bool {
263 let state = entry_for(project_root);
264 let mut s = state
265 .lock()
266 .unwrap_or_else(std::sync::PoisonError::into_inner);
267 if s.worker_running {
268 false
269 } else {
270 s.worker_running = true;
271 s.graph_run_done = false;
272 s.bm25_run_done = false;
273 true
274 }
275}
276
277pub fn ensure_all_background(project_root: &str) {
278 if !try_claim_worker(project_root) {
279 return;
280 }
281
282 if !crate::core::index_filter::cli_overlay_active() {
291 nudge_daemon_index(project_root);
292 }
293
294 let state = entry_for(project_root);
295 let root = project_root.to_string();
296 let indexer = move || run_build_worker(&root);
297
298 let spawned = std::thread::Builder::new()
302 .name("leanctx-index".to_string())
303 .stack_size(INDEXER_STACK_BYTES)
304 .spawn(indexer);
305 if spawned.is_err() {
306 let mut s = state
309 .lock()
310 .unwrap_or_else(std::sync::PoisonError::into_inner);
311 s.worker_running = false;
312 }
313}
314
315fn run_build_worker(root: &str) {
320 crate::core::memory_guard::start_guard(std::sync::Arc::new(|level| {
327 tracing::warn!(
328 "[build_worker] memory pressure: {level:?} — background tasks will throttle"
329 );
330 if level >= crate::core::memory_guard::PressureLevel::Hard {
331 crate::core::content_cache::clear();
332 }
333 crate::core::memory_guard::force_purge();
334 true
335 }));
336
337 let graph_state = entry_for(root);
343 let graph_root = root.to_string();
344 let build_graph = move || {
345 {
346 let mut s = graph_state
347 .lock()
348 .unwrap_or_else(std::sync::PoisonError::into_inner);
349 start_component(&mut s.graph);
350 }
351 let guard = crate::core::index_progress::ProgressGuard::new(
353 graph_root.clone(),
354 crate::core::index_progress::IndexComponent::Graph,
355 );
356 guard.report(0, 0);
357 let graph_result = std::panic::catch_unwind(|| {
358 let (idx, _cache) = graph_index::scan_with_content_cache(&graph_root);
359 crate::core::code_health::persist::refresh_if_stale(&graph_root, &idx);
363 });
364 if graph_result.is_ok() {
365 let _ = std::panic::catch_unwind(|| {
368 crate::core::graph_enricher::refresh_semantic_edges_in_background(&graph_root);
369 });
370 }
371 drop(guard);
372 {
373 let mut s = graph_state
374 .lock()
375 .unwrap_or_else(std::sync::PoisonError::into_inner);
376 if let Ok(()) = graph_result {
377 finish_ok(&mut s.graph);
378 } else {
379 finish_err(&mut s.graph, "graph index build panicked".to_string());
380 }
381 s.graph_run_done = true;
382 }
383 };
384
385 let bm25_state = entry_for(root);
386 let bm25_root = root.to_string();
387 let build_bm25 = move || {
388 {
389 let mut s = bm25_state
390 .lock()
391 .unwrap_or_else(std::sync::PoisonError::into_inner);
392 start_component(&mut s.bm25);
393 }
394 let _progress = crate::core::index_progress::ProgressGuard::new(
395 bm25_root.clone(),
396 crate::core::index_progress::IndexComponent::Bm25,
397 );
398 let bm = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
399 let root_pb = Path::new(&bm25_root);
400 let lock_name = bm25_index_lock_name(root_pb);
401 let _lock = crate::core::startup_guard::try_acquire_lock(
402 &lock_name,
403 std::time::Duration::from_millis(800),
404 std::time::Duration::from_mins(3),
405 );
406 if _lock.is_none() {
407 tracing::info!(
408 "[bm25: another process is building {bm25_root} — loading the shared index]"
409 );
410 let idx = BM25Index::load(root_pb).unwrap_or_default();
411 return (idx.doc_count, None);
412 }
413 let idx = BM25Index::load_or_build(root_pb);
414 let outcome = idx.save(root_pb);
415 (idx.doc_count, Some(outcome))
416 }));
417 {
418 let mut s = bm25_state
419 .lock()
420 .unwrap_or_else(std::sync::PoisonError::into_inner);
421 if let Ok((doc_count, save_res)) = bm {
422 finish_ok(&mut s.bm25);
423 s.bm25.note = Some(match save_res {
424 Some(outcome) => bm25_build_note(doc_count, &outcome),
425 None => format!(
426 "loaded shared BM25 index ({doc_count} chunks) — build in progress in another process"
427 ),
428 });
429 } else {
430 finish_err(&mut s.bm25, "bm25 build panicked".to_string());
431 }
432 s.bm25_run_done = true;
433 }
434 };
435
436 run_memory_bounded_phases(
437 build_graph,
438 build_bm25,
439 || crate::core::search_index::ensure_background(root, true, false),
440 || {
441 crate::core::content_cache::clear();
442 crate::core::memory_guard::force_purge();
443 },
444 );
445
446 crate::core::content_cache::trim_oldest_percent(75);
453 crate::core::memory_guard::force_purge();
454
455 let final_state = entry_for(root);
456 let mut s = final_state
457 .lock()
458 .unwrap_or_else(std::sync::PoisonError::into_inner);
459 s.worker_running = false;
460}
461
462fn run_memory_bounded_phases<G, B, S, R>(graph: G, bm25: B, search: S, mut reclaim: R)
465where
466 G: FnOnce(),
467 B: FnOnce(),
468 S: FnOnce(),
469 R: FnMut(),
470{
471 graph();
472 reclaim();
473 bm25();
474 reclaim();
475 search();
476}
477
478pub fn build_semantic(project_root: &str) {
483 let state = entry_for(project_root);
484 let root = Path::new(project_root);
485
486 {
487 let mut s = state
488 .lock()
489 .unwrap_or_else(std::sync::PoisonError::into_inner);
490 start_component(&mut s.semantic);
491 }
492
493 let _progress = crate::core::index_progress::ProgressGuard::new(
495 project_root.to_string(),
496 crate::core::index_progress::IndexComponent::Semantic,
497 );
498
499 let bm25_idx = try_load_bm25_index(project_root);
500 match bm25_idx.as_ref() {
501 Some(idx) if idx.doc_count > 0 => {
502 let outcome = crate::core::embedding_index::build_or_update(root, idx);
503 let mut s = state
504 .lock()
505 .unwrap_or_else(std::sync::PoisonError::into_inner);
506 match outcome {
507 crate::core::embedding_index::EmbeddingBuildOutcome::Ready => {
508 finish_ok(&mut s.semantic);
509 }
510 crate::core::embedding_index::EmbeddingBuildOutcome::Skipped => {
511 finish_ok(&mut s.semantic);
512 s.semantic.note = Some(
513 "embeddings disabled by feature flag or config (search.dense_enabled / memory_profile)"
514 .to_string(),
515 );
516 }
517 crate::core::embedding_index::EmbeddingBuildOutcome::ModelNotAvailable(
518 ref reason,
519 ) => {
520 s.semantic.state = State::Idle;
523 s.semantic.note = Some(format!("embedding model not available: {reason}"));
524 }
525 crate::core::embedding_index::EmbeddingBuildOutcome::Failed => {
526 finish_err(
527 &mut s.semantic,
528 "embedding build failed (see logs)".to_string(),
529 );
530 }
531 }
532 }
533 _ => {
534 let mut s = state
535 .lock()
536 .unwrap_or_else(std::sync::PoisonError::into_inner);
537 s.semantic.state = State::Idle;
539 s.semantic.note =
540 Some("BM25 index is empty or unavailable — nothing to embed".to_string());
541 }
542 }
543}
544
545const MAX_EXTRA_ROOT_BUILDS: usize = 8;
549
550pub fn ensure_extra_roots_background(primary_root: &str, extra_roots: &[String]) {
551 let primary = Path::new(primary_root);
552 let mut queue: Vec<String> = Vec::new();
553 for root in extra_roots {
554 if queue.len() >= MAX_EXTRA_ROOT_BUILDS {
555 break;
556 }
557 let rp = Path::new(root);
558 if !rp.is_dir() {
559 continue;
560 }
561 if rp.starts_with(primary) {
563 continue;
564 }
565 if primary.starts_with(rp) {
567 continue;
568 }
569 queue.push(root.clone());
570 }
571 if queue.is_empty() {
572 return;
573 }
574
575 let spawned = std::thread::Builder::new()
584 .name("leanctx-extra-roots".to_string())
585 .stack_size(INDEXER_STACK_BYTES)
586 .spawn(move || {
587 for root in queue {
588 if crate::core::memory_guard::is_under_pressure()
589 || crate::core::memory_guard::abort_requested()
590 {
591 tracing::warn!(
592 "[index_orchestrator: skipping remaining extra-root builds under memory pressure]"
593 );
594 break;
595 }
596 if !try_claim_worker(&root) {
597 continue; }
599 nudge_daemon_index(&root);
600 run_build_worker(&root);
601 }
602 });
603 if let Err(e) = spawned {
604 tracing::warn!("[index_orchestrator: could not spawn extra-roots worker: {e}]");
605 }
606}
607
608fn bm25_build_note(
613 doc_count: usize,
614 save: &std::io::Result<crate::core::bm25_index::SaveOutcome>,
615) -> String {
616 use crate::core::bm25_index::SaveOutcome;
617 match save {
618 Ok(SaveOutcome::Persisted { compressed_bytes }) => format!(
619 "indexed {doc_count} chunks, {:.1} MB persisted",
620 *compressed_bytes as f64 / 1_048_576.0
621 ),
622 Ok(SaveOutcome::SkippedTooLarge {
623 compressed_bytes,
624 limit_bytes,
625 }) => format!(
626 "indexed {doc_count} chunks but NOT persisted to disk: compressed {:.1} MB exceeds the {:.0} MB cap. \
627 Raise it via LEAN_CTX_BM25_MAX_CACHE_MB (or bm25_max_cache_mb in config) or add extra_ignore_patterns, \
628 then run `lean-ctx reindex`. Until then the index is rebuilt from scratch on every cold start.",
629 *compressed_bytes as f64 / 1_048_576.0,
630 *limit_bytes as f64 / 1_048_576.0
631 ),
632 Err(e) => format!("indexed {doc_count} chunks but persisting failed: {e}"),
633 }
634}
635
636#[derive(Debug, Clone)]
639pub struct Bm25Summary {
640 pub state: &'static str,
641 pub elapsed_ms: Option<u64>,
643 pub note: Option<String>,
644 pub last_error: Option<String>,
645}
646
647#[derive(Debug, Clone)]
649pub struct SemanticSummary {
650 pub state: &'static str,
651 pub elapsed_ms: Option<u64>,
652 pub note: Option<String>,
653 pub last_error: Option<String>,
654}
655
656fn component_elapsed_and_state(c: &Component) -> (&'static str, Option<u64>) {
660 let elapsed_ms = if matches!(c.state, State::Building) {
661 c.started_ms.map(|start| now_ms().saturating_sub(start))
662 } else {
663 c.duration_ms
664 };
665 let state = match c.state {
666 State::Idle => "idle",
667 State::Building => "building",
668 State::Ready => "ready",
669 State::Failed => "failed",
670 };
671 (state, elapsed_ms)
672}
673
674pub fn semantic_summary(project_root: &str) -> SemanticSummary {
675 let entry = entry_for(project_root);
676 let s = entry
677 .lock()
678 .unwrap_or_else(std::sync::PoisonError::into_inner);
679 let c = &s.semantic;
680 let (state, elapsed_ms) = component_elapsed_and_state(c);
681 SemanticSummary {
682 state,
683 elapsed_ms,
684 note: c.note.clone(),
685 last_error: c.last_error.clone(),
686 }
687}
688
689pub fn bm25_summary(project_root: &str) -> Bm25Summary {
690 let entry = entry_for(project_root);
691 let s = entry
692 .lock()
693 .unwrap_or_else(std::sync::PoisonError::into_inner);
694 let c = &s.bm25;
695 let (state, elapsed_ms) = component_elapsed_and_state(c);
696 Bm25Summary {
697 state,
698 elapsed_ms,
699 note: c.note.clone(),
700 last_error: c.last_error.clone(),
701 }
702}
703
704pub fn try_load_graph_index(project_root: &str) -> Option<ProjectIndex> {
705 crate::core::graph_cache::get_cached(project_root).map(|arc| (*arc).clone())
708}
709
710pub fn try_load_bm25_index(project_root: &str) -> Option<BM25Index> {
711 BM25Index::load(Path::new(project_root))
712}
713
714#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
716pub struct SlotProgress {
717 pub building: bool,
718 pub done: u64,
719 pub total: u64,
720}
721
722impl SlotProgress {
723 pub fn is_determinate(&self) -> bool {
724 self.building && self.total > 0
725 }
726}
727
728#[derive(Debug, Clone, PartialEq, Eq)]
730pub struct ProgressView {
731 pub worker_running: bool,
732 pub graph_run_done: bool,
734 pub bm25_run_done: bool,
736 pub graph: SlotProgress,
737 pub bm25: SlotProgress,
738 pub semantic: SlotProgress,
739}
740
741impl ProgressView {
742 pub fn graph_bm25_active(&self) -> bool {
747 self.worker_running && !(self.graph_run_done && self.bm25_run_done)
748 }
749
750 pub fn semantic_active(&self) -> bool {
751 self.semantic.building
752 }
753}
754
755pub fn progress_view(project_root: &str) -> ProgressView {
757 use crate::core::index_progress::{self, IndexComponent};
758 let (worker_running, graph_run_done, bm25_run_done, graph_b, bm25_b, sem_b) = {
759 let state = entry_for(project_root);
760 let s = state
761 .lock()
762 .unwrap_or_else(std::sync::PoisonError::into_inner);
763 (
764 s.worker_running,
765 s.graph_run_done,
766 s.bm25_run_done,
767 matches!(s.graph.state, State::Building),
768 matches!(s.bm25.state, State::Building),
769 matches!(s.semantic.state, State::Building),
770 )
771 };
772 let g = index_progress::get(project_root, IndexComponent::Graph);
773 let b = index_progress::get(project_root, IndexComponent::Bm25);
774 let sem = index_progress::get(project_root, IndexComponent::Semantic);
775 ProgressView {
776 worker_running,
777 graph_run_done,
778 bm25_run_done,
779 graph: SlotProgress {
780 building: graph_b,
781 done: g.done,
782 total: g.total,
783 },
784 bm25: SlotProgress {
785 building: bm25_b,
786 done: b.done,
787 total: b.total,
788 },
789 semantic: SlotProgress {
790 building: sem_b,
791 done: sem.done,
792 total: sem.total,
793 },
794 }
795}
796
797pub fn is_building() -> bool {
799 let map = registry()
800 .lock()
801 .unwrap_or_else(std::sync::PoisonError::into_inner);
802 map.values().any(|entry| {
803 let st = entry
804 .lock()
805 .unwrap_or_else(std::sync::PoisonError::into_inner);
806 matches!(st.bm25.state, State::Building)
807 || matches!(st.graph.state, State::Building)
808 || matches!(st.semantic.state, State::Building)
809 })
810}
811
812#[derive(Debug, Serialize)]
813struct ComponentStatus<'a> {
814 state: &'a str,
815 started_ms: Option<u64>,
816 finished_ms: Option<u64>,
817 duration_ms: Option<u64>,
818 last_error: Option<&'a str>,
819 #[serde(skip_serializing_if = "Option::is_none")]
820 note: Option<&'a str>,
821 #[serde(skip_serializing_if = "Option::is_none")]
823 progress_done: Option<u64>,
824 #[serde(skip_serializing_if = "Option::is_none")]
826 progress_total: Option<u64>,
827}
828
829fn component_status(
830 c: &Component,
831 progress: crate::core::index_progress::ProgressSnapshot,
832) -> ComponentStatus<'_> {
833 let (progress_done, progress_total) = if matches!(c.state, State::Building) {
834 (Some(progress.done), Some(progress.total))
835 } else {
836 (None, None)
837 };
838 ComponentStatus {
839 state: match c.state {
840 State::Idle => "idle",
841 State::Building => "building",
842 State::Ready => "ready",
843 State::Failed => "failed",
844 },
845 started_ms: c.started_ms,
846 finished_ms: c.finished_ms,
847 duration_ms: c.duration_ms,
848 last_error: c.last_error.as_deref(),
849 note: c.note.as_deref(),
850 progress_done,
851 progress_total,
852 }
853}
854
855#[derive(Debug, Serialize)]
856struct StatusResponse<'a> {
857 project_root: &'a str,
858 graph_index: ComponentStatus<'a>,
859 bm25_index: ComponentStatus<'a>,
860 semantic_index: ComponentStatus<'a>,
864 disk: DiskStatusAll,
865 #[serde(skip_serializing_if = "Option::is_none")]
868 index_filters: Option<String>,
869}
870
871#[derive(Debug, Serialize, Default)]
872pub struct DiskStatus {
873 pub exists: bool,
874 pub size_bytes: Option<u64>,
875 pub file_count: Option<u64>,
876 pub modified_at: Option<String>,
877}
878
879#[derive(Debug, Serialize, Default)]
880pub struct DiskStatusAll {
881 pub graph_index: DiskStatus,
882 pub bm25_index: DiskStatus,
883 pub code_graph: DiskStatus,
884 pub semantic_index: DiskStatus,
888}
889
890fn disk_status_for_graph(project_root: &str) -> DiskStatus {
891 let Some(dir) = graph_index::ProjectIndex::index_dir(project_root) else {
897 return DiskStatus::default();
898 };
899 let meta_file = dir.join("graph.meta.json");
900 if !meta_file.exists() {
901 return DiskStatus::default();
902 }
903 let meta = std::fs::metadata(&meta_file).ok();
904 let file_count =
905 graph_index::ProjectIndex::load(project_root).map(|idx| idx.files.len() as u64);
906 DiskStatus {
907 exists: true,
908 size_bytes: None,
909 file_count,
910 modified_at: meta.and_then(|m| m.modified().ok()).map(format_time),
911 }
912}
913
914fn disk_status_for_bm25(project_root: &str) -> DiskStatus {
915 let root = Path::new(project_root);
916 let path = BM25Index::index_file_path(root);
917 if !path.exists() {
918 return DiskStatus::default();
919 }
920 let meta = std::fs::metadata(&path).ok();
921 DiskStatus {
922 exists: true,
923 size_bytes: meta.as_ref().map(std::fs::Metadata::len),
924 file_count: BM25Index::persisted_chunk_count(root),
925 modified_at: meta.and_then(|m| m.modified().ok()).map(format_time),
926 }
927}
928
929fn disk_status_for_code_graph(project_root: &str) -> DiskStatus {
930 let dir = crate::core::property_graph::graph_dir(project_root);
931 let db_path = dir.join("graph.db");
932 if !db_path.exists() {
933 return DiskStatus::default();
934 }
935 let meta = std::fs::metadata(&db_path).ok();
936 let node_count = crate::core::property_graph::CodeGraph::open(project_root)
937 .ok()
938 .and_then(|g| {
939 g.connection()
940 .query_row("SELECT count(*) FROM nodes", [], |r| r.get::<_, i64>(0))
941 .ok()
942 .map(|c| c as u64)
943 });
944 DiskStatus {
945 exists: true,
946 size_bytes: meta.as_ref().map(std::fs::Metadata::len),
947 file_count: node_count,
948 modified_at: meta.and_then(|m| m.modified().ok()).map(format_time),
949 }
950}
951
952fn format_time(t: SystemTime) -> String {
953 let secs = t.duration_since(UNIX_EPOCH).unwrap_or_default().as_secs();
954 let dt = chrono::DateTime::from_timestamp(secs as i64, 0);
955 dt.map_or_else(
956 || format!("{secs}"),
957 |d| d.format("%Y-%m-%d %H:%M:%S UTC").to_string(),
958 )
959}
960
961pub fn disk_status_for_semantic(project_root: &str) -> DiskStatus {
962 let root = Path::new(project_root);
963 let dir = crate::core::index_namespace::vectors_dir(root);
964 let bin_path = dir.join("embeddings.bin");
965 if !bin_path.exists() {
966 return DiskStatus::default();
967 }
968 let meta = std::fs::metadata(&bin_path).ok();
969 DiskStatus {
970 exists: true,
971 size_bytes: meta.as_ref().map(std::fs::Metadata::len),
972 file_count: None,
973 modified_at: meta.and_then(|m| m.modified().ok()).map(format_time),
974 }
975}
976
977pub fn disk_status(project_root: &str) -> DiskStatusAll {
978 DiskStatusAll {
979 graph_index: disk_status_for_graph(project_root),
980 bm25_index: disk_status_for_bm25(project_root),
981 code_graph: disk_status_for_code_graph(project_root),
982 semantic_index: disk_status_for_semantic(project_root),
983 }
984}
985
986pub fn status_json(project_root: &str) -> String {
987 let disk = disk_status(project_root);
991 let state = entry_for(project_root);
992 let s = state
993 .lock()
994 .unwrap_or_else(std::sync::PoisonError::into_inner);
995 let graph_p = crate::core::index_progress::get(
996 project_root,
997 crate::core::index_progress::IndexComponent::Graph,
998 );
999 let bm25_p = crate::core::index_progress::get(
1000 project_root,
1001 crate::core::index_progress::IndexComponent::Bm25,
1002 );
1003 let semantic_p = crate::core::index_progress::get(
1004 project_root,
1005 crate::core::index_progress::IndexComponent::Semantic,
1006 );
1007 let res = StatusResponse {
1008 project_root,
1009 graph_index: component_status(&s.graph, graph_p),
1010 bm25_index: component_status(&s.bm25, bm25_p),
1011 semantic_index: component_status(&s.semantic, semantic_p),
1012 disk,
1013 index_filters: crate::core::index_filter::IndexFileFilter::effective().summary(),
1014 };
1015 serde_json::to_string(&res).unwrap_or_else(|_| "{}".to_string())
1016}
1017
1018#[cfg(test)]
1019mod tests {
1020 use super::*;
1021
1022 #[test]
1023 fn progress_view_graph_bm25_active_logic() {
1024 let idle = SlotProgress::default();
1025 let mut v = ProgressView {
1026 worker_running: true,
1027 graph_run_done: false,
1028 bm25_run_done: false,
1029 graph: idle,
1030 bm25: idle,
1031 semantic: idle,
1032 };
1033 assert!(v.graph_bm25_active(), "claimed, phases not done");
1034 v.graph_run_done = true;
1035 assert!(v.graph_bm25_active(), "graph done, bm25 pending");
1036 v.bm25_run_done = true;
1037 assert!(
1038 !v.graph_bm25_active(),
1039 "both phases done — search pre-warm must not keep wait open"
1040 );
1041 v.worker_running = false;
1042 assert!(!v.graph_bm25_active());
1043 v.graph_run_done = true;
1045 v.bm25_run_done = true;
1046 assert!(!v.graph_bm25_active());
1047 }
1048
1049 #[test]
1050 fn status_json_is_valid_json() {
1051 let s = status_json("/tmp");
1052 let _: serde_json::Value = serde_json::from_str(&s).unwrap();
1053 }
1054
1055 #[test]
1056 fn background_build_phases_are_serialized_with_reclamation() {
1057 let events = std::cell::RefCell::new(Vec::new());
1058 run_memory_bounded_phases(
1059 || events.borrow_mut().push("graph"),
1060 || events.borrow_mut().push("bm25"),
1061 || events.borrow_mut().push("search"),
1062 || events.borrow_mut().push("reclaim"),
1063 );
1064 assert_eq!(
1065 events.into_inner(),
1066 ["graph", "reclaim", "bm25", "reclaim", "search"]
1067 );
1068 }
1069
1070 #[test]
1071 fn warm_need_classifies_tools() {
1072 for light in [
1074 "ctx_read",
1075 "ctx_shell",
1076 "ctx_tree",
1077 "ctx_knowledge",
1078 "unknown_tool",
1079 ] {
1080 assert_eq!(warm_need_for_tool(light), WarmNeed::None, "{light}");
1081 }
1082 assert_eq!(warm_need_for_tool("ctx_search"), WarmNeed::Search);
1084 for heavy in [
1085 "ctx_graph",
1086 "ctx_callgraph",
1087 "ctx_routes",
1088 "ctx_repomap",
1089 "ctx_impact",
1090 "ctx_artifacts",
1091 "ctx_semantic_search",
1092 "ctx_provider",
1093 "ctx_compose",
1094 "ctx_explore",
1095 "ctx_review",
1096 ] {
1097 assert_eq!(warm_need_for_tool(heavy), WarmNeed::Heavy, "{heavy}");
1098 }
1099 }
1100
1101 #[test]
1102 fn ensure_warm_lightweight_and_search_never_signal_first_warm() {
1103 assert!(!ensure_warm_for_tool("", "ctx_graph"));
1104 let tmp = tempfile::tempdir().unwrap();
1105 let root = tmp.path().to_string_lossy().to_string();
1106 assert!(!ensure_warm_for_tool(&root, "ctx_read"));
1107 assert!(!ensure_warm_for_tool(&root, "ctx_search"));
1108 }
1109
1110 #[test]
1111 fn ensure_warm_heavy_is_once_per_root() {
1112 let tmp = tempfile::tempdir().unwrap();
1116 let root = tmp.path().to_string_lossy().to_string();
1117 assert!(
1118 ensure_warm_for_tool(&root, "ctx_callgraph"),
1119 "first heavy warm must signal true"
1120 );
1121 assert!(
1122 !ensure_warm_for_tool(&root, "ctx_callgraph"),
1123 "second heavy warm must be deduped to false"
1124 );
1125 assert!(
1126 !ensure_warm_for_tool(&root, "ctx_semantic_search"),
1127 "any later heavy tool on the same root is also deduped"
1128 );
1129 }
1130
1131 #[test]
1132 fn build_note_persisted_reports_size() {
1133 let note = bm25_build_note(
1134 42,
1135 &Ok(crate::core::bm25_index::SaveOutcome::Persisted {
1136 compressed_bytes: 3 * 1024 * 1024,
1137 }),
1138 );
1139 assert!(
1140 note.contains("42 chunks"),
1141 "note should report chunk count: {note}"
1142 );
1143 assert!(
1144 note.contains("persisted"),
1145 "note should report persistence: {note}"
1146 );
1147 }
1148
1149 #[test]
1150 fn build_note_too_large_carries_remedy() {
1151 let note = bm25_build_note(
1152 1000,
1153 &Ok(crate::core::bm25_index::SaveOutcome::SkippedTooLarge {
1154 compressed_bytes: 600 * 1024 * 1024,
1155 limit_bytes: 512 * 1024 * 1024,
1156 }),
1157 );
1158 assert!(
1159 note.contains("NOT persisted"),
1160 "must flag non-persistence: {note}"
1161 );
1162 assert!(
1163 note.contains("LEAN_CTX_BM25_MAX_CACHE_MB") && note.contains("reindex"),
1164 "too-large note must carry an actionable remedy: {note}"
1165 );
1166 }
1167
1168 #[test]
1169 fn build_note_persist_error_is_reported() {
1170 let note = bm25_build_note(7, &Err(std::io::Error::other("disk full")));
1171 assert!(note.contains("persisting failed"), "note: {note}");
1172 assert!(
1173 note.contains("disk full"),
1174 "note should include the io error: {note}"
1175 );
1176 }
1177
1178 #[test]
1179 fn bm25_summary_unknown_project_is_idle() {
1180 let tmp = tempfile::tempdir().unwrap();
1181 let summary = bm25_summary(tmp.path().to_string_lossy().as_ref());
1182 assert_eq!(summary.state, "idle");
1183 assert!(summary.note.is_none());
1184 assert!(summary.last_error.is_none());
1185 }
1186
1187 #[test]
1188 fn extra_roots_skips_subdirs_of_primary() {
1189 let tmp = tempfile::tempdir().unwrap();
1190 let primary = tmp.path().join("primary");
1191 std::fs::create_dir_all(&primary).unwrap();
1192 let sub = primary.join("subdir");
1193 std::fs::create_dir_all(&sub).unwrap();
1194 let external = tmp.path().join("external");
1195 std::fs::create_dir_all(&external).unwrap();
1196
1197 let primary_str = primary.to_string_lossy().to_string();
1198 let extra = vec![
1199 sub.to_string_lossy().to_string(),
1200 external.to_string_lossy().to_string(),
1201 ];
1202
1203 ensure_extra_roots_background(&primary_str, &extra);
1205 }
1206
1207 #[test]
1208 fn extra_roots_caps_at_max() {
1209 let tmp = tempfile::tempdir().unwrap();
1210 let primary = tmp.path().join("primary");
1211 std::fs::create_dir_all(&primary).unwrap();
1212
1213 let mut extra = Vec::new();
1214 for i in 0..20 {
1215 let d = tmp.path().join(format!("ext-{i}"));
1216 std::fs::create_dir_all(&d).unwrap();
1217 extra.push(d.to_string_lossy().to_string());
1218 }
1219
1220 let primary_str = primary.to_string_lossy().to_string();
1221 ensure_extra_roots_background(&primary_str, &extra);
1223 }
1224
1225 #[test]
1226 fn bm25_index_lock_name_is_per_repo_and_distinct_from_graph() {
1227 let a = bm25_index_lock_name(Path::new("/tmp/repo-a"));
1228 let b = bm25_index_lock_name(Path::new("/tmp/repo-b"));
1229 assert!(a.starts_with("bm25-idx-"), "unexpected lock name: {a}");
1230 assert_ne!(a, b, "lock name must be per-repo");
1231 assert_eq!(a, bm25_index_lock_name(Path::new("/tmp/repo-a")));
1233 let graph = format!(
1236 "graph-idx-{}",
1237 &crate::core::index_namespace::namespace_hash(Path::new("/tmp/repo-a"))[..8]
1238 );
1239 assert_ne!(a, graph, "bm25 and graph locks must be independent");
1240 }
1241}