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 warm_triggered: bool,
52 graph: Component,
53 bm25: Component,
54 semantic: Component,
58}
59
60impl ProjectBuild {
61 fn new() -> Self {
62 Self {
63 worker_running: false,
64 warm_triggered: false,
65 graph: Component::new(),
66 bm25: Component::new(),
67 semantic: Component::new(),
68 }
69 }
70}
71
72static REGISTRY: OnceLock<Mutex<HashMap<String, Arc<Mutex<ProjectBuild>>>>> = OnceLock::new();
80
81fn registry() -> &'static Mutex<HashMap<String, Arc<Mutex<ProjectBuild>>>> {
82 REGISTRY.get_or_init(|| Mutex::new(HashMap::new()))
83}
84
85fn entry_for(project_root: &str) -> Arc<Mutex<ProjectBuild>> {
86 let mut map = registry()
87 .lock()
88 .unwrap_or_else(std::sync::PoisonError::into_inner);
89 map.entry(project_root.to_string())
90 .or_insert_with(|| Arc::new(Mutex::new(ProjectBuild::new())))
91 .clone()
92}
93
94fn now_ms() -> u64 {
95 SystemTime::now()
96 .duration_since(UNIX_EPOCH)
97 .unwrap_or_default()
98 .as_millis() as u64
99}
100
101fn bm25_index_lock_name(root: &Path) -> String {
106 format!(
107 "bm25-idx-{}",
108 &crate::core::index_namespace::namespace_hash(root)[..8]
109 )
110}
111
112fn start_component(c: &mut Component) {
113 c.state = State::Building;
114 c.started_ms = Some(now_ms());
115 c.finished_ms = None;
116 c.duration_ms = None;
117 c.last_error = None;
118 c.note = None;
119}
120
121fn finish_ok(c: &mut Component) {
122 c.state = State::Ready;
123 let end = now_ms();
124 c.finished_ms = Some(end);
125 c.duration_ms = c.started_ms.map(|s| end.saturating_sub(s));
126}
127
128fn finish_err(c: &mut Component, e: String) {
129 c.state = State::Failed;
130 let end = now_ms();
131 c.finished_ms = Some(end);
132 c.duration_ms = c.started_ms.map(|s| end.saturating_sub(s));
133 c.last_error = Some(e);
134}
135
136#[derive(Debug, Clone, Copy, PartialEq, Eq)]
141pub enum WarmNeed {
142 None,
144 Search,
146 Heavy,
148}
149
150#[must_use]
154pub fn warm_need_for_tool(tool: &str) -> WarmNeed {
155 match tool {
156 "ctx_search" => WarmNeed::Search,
157 "ctx_graph"
159 | "ctx_callgraph"
160 | "ctx_routes"
161 | "ctx_repomap"
162 | "ctx_impact"
163 | "ctx_artifacts"
164 | "ctx_semantic_search"
165 | "ctx_provider"
166 | "ctx_compose"
167 | "ctx_explore"
168 | "ctx_review" => WarmNeed::Heavy,
169 _ => WarmNeed::None,
170 }
171}
172
173pub fn ensure_warm_for_tool(project_root: &str, tool: &str) -> bool {
180 if project_root.is_empty() {
181 return false;
182 }
183 match warm_need_for_tool(tool) {
184 WarmNeed::None => false,
185 WarmNeed::Search => {
186 crate::core::search_index::ensure_background(project_root, true, false);
189 false
190 }
191 WarmNeed::Heavy => {
192 let entry = entry_for(project_root);
193 let first_warm = {
194 let mut s = entry
195 .lock()
196 .unwrap_or_else(std::sync::PoisonError::into_inner);
197 if s.warm_triggered {
198 false
199 } else {
200 s.warm_triggered = true;
201 true
202 }
203 };
204 if first_warm {
205 ensure_all_background(project_root);
206 }
207 first_warm
208 }
209 }
210}
211
212const INDEXER_STACK_BYTES: usize = 16 * 1024 * 1024;
216
217fn nudge_daemon_index(project_root: &str) {
229 if crate::daemon::is_foreground_daemon() {
231 return;
232 }
233 let root = project_root.to_string();
234 let _ = std::thread::Builder::new()
235 .name("leanctx-index-nudge".to_string())
236 .spawn(move || {
237 if !crate::daemon::is_daemon_running() {
238 return;
239 }
240 let Ok(rt) = tokio::runtime::Runtime::new() else {
241 return;
242 };
243 let body = serde_json::json!({ "root": root }).to_string();
244 rt.block_on(async {
245 let _ = crate::daemon_client::try_daemon_request("POST", "/v1/index/ensure", &body)
246 .await;
247 });
248 });
249}
250
251fn try_claim_worker(project_root: &str) -> bool {
255 let state = entry_for(project_root);
256 let mut s = state
257 .lock()
258 .unwrap_or_else(std::sync::PoisonError::into_inner);
259 if s.worker_running {
260 false
261 } else {
262 s.worker_running = true;
263 true
264 }
265}
266
267pub fn ensure_all_background(project_root: &str) {
268 if !try_claim_worker(project_root) {
269 return;
270 }
271
272 if !crate::core::index_filter::cli_overlay_active() {
281 nudge_daemon_index(project_root);
282 }
283
284 let state = entry_for(project_root);
285 let root = project_root.to_string();
286 let indexer = move || run_build_worker(&root);
287
288 let spawned = std::thread::Builder::new()
292 .name("leanctx-index".to_string())
293 .stack_size(INDEXER_STACK_BYTES)
294 .spawn(indexer);
295 if spawned.is_err() {
296 let mut s = state
299 .lock()
300 .unwrap_or_else(std::sync::PoisonError::into_inner);
301 s.worker_running = false;
302 }
303}
304
305fn run_build_worker(root: &str) {
310 crate::core::memory_guard::start_guard(std::sync::Arc::new(|level| {
317 tracing::warn!(
318 "[build_worker] memory pressure: {level:?} — background tasks will throttle"
319 );
320 if level >= crate::core::memory_guard::PressureLevel::Hard {
321 crate::core::content_cache::clear();
322 }
323 crate::core::memory_guard::force_purge();
324 }));
325
326 let graph_state = entry_for(root);
332 let graph_root = root.to_string();
333 let build_graph = move || {
334 {
335 let mut s = graph_state
336 .lock()
337 .unwrap_or_else(std::sync::PoisonError::into_inner);
338 start_component(&mut s.graph);
339 }
340 let graph_result = std::panic::catch_unwind(|| {
341 let (idx, _cache) = graph_index::scan_with_content_cache(&graph_root);
342 if let Err(e) = idx.save() {
343 tracing::warn!("[index_orchestrator: graph save failed: {e}]");
344 }
345 crate::core::code_health::persist::refresh_if_stale(&graph_root, &idx);
346 });
347 if let Ok(()) = graph_result {
348 let mut s = graph_state
349 .lock()
350 .unwrap_or_else(std::sync::PoisonError::into_inner);
351 finish_ok(&mut s.graph);
352 } else {
353 let mut s = graph_state
354 .lock()
355 .unwrap_or_else(std::sync::PoisonError::into_inner);
356 finish_err(&mut s.graph, "graph index build panicked".to_string());
357 }
358 };
359
360 let bm25_state = entry_for(root);
361 let bm25_root = root.to_string();
362 let build_bm25 = move || {
363 {
364 let mut s = bm25_state
365 .lock()
366 .unwrap_or_else(std::sync::PoisonError::into_inner);
367 start_component(&mut s.bm25);
368 }
369 let bm = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
370 let root_pb = Path::new(&bm25_root);
371 let lock_name = bm25_index_lock_name(root_pb);
372 let _lock = crate::core::startup_guard::try_acquire_lock(
373 &lock_name,
374 std::time::Duration::from_millis(800),
375 std::time::Duration::from_mins(3),
376 );
377 if _lock.is_none() {
378 tracing::info!(
379 "[bm25: another process is building {bm25_root} — loading the shared index]"
380 );
381 let idx = BM25Index::load(root_pb).unwrap_or_default();
382 return (idx.doc_count, None);
383 }
384 let idx = BM25Index::load_or_build(root_pb);
385 let outcome = idx.save(root_pb);
386 (idx.doc_count, Some(outcome))
387 }));
388 if let Ok((doc_count, save_res)) = bm {
389 let mut s = bm25_state
390 .lock()
391 .unwrap_or_else(std::sync::PoisonError::into_inner);
392 finish_ok(&mut s.bm25);
393 s.bm25.note = Some(match save_res {
394 Some(outcome) => bm25_build_note(doc_count, &outcome),
395 None => format!(
396 "loaded shared BM25 index ({doc_count} chunks) — build in progress in another process"
397 ),
398 });
399 } else {
400 let mut s = bm25_state
401 .lock()
402 .unwrap_or_else(std::sync::PoisonError::into_inner);
403 finish_err(&mut s.bm25, "bm25 build panicked".to_string());
404 }
405 };
406
407 run_memory_bounded_phases(
408 build_graph,
409 build_bm25,
410 || crate::core::search_index::ensure_background(root, true, false),
411 || {
412 crate::core::content_cache::clear();
413 crate::core::memory_guard::force_purge();
414 },
415 );
416
417 crate::core::content_cache::trim_oldest_percent(75);
424 crate::core::memory_guard::force_purge();
425
426 let final_state = entry_for(root);
427 let mut s = final_state
428 .lock()
429 .unwrap_or_else(std::sync::PoisonError::into_inner);
430 s.worker_running = false;
431}
432
433fn run_memory_bounded_phases<G, B, S, R>(graph: G, bm25: B, search: S, mut reclaim: R)
436where
437 G: FnOnce(),
438 B: FnOnce(),
439 S: FnOnce(),
440 R: FnMut(),
441{
442 graph();
443 reclaim();
444 bm25();
445 reclaim();
446 search();
447}
448
449pub fn build_semantic(project_root: &str) {
454 let state = entry_for(project_root);
455 let root = Path::new(project_root);
456
457 {
458 let mut s = state
459 .lock()
460 .unwrap_or_else(std::sync::PoisonError::into_inner);
461 start_component(&mut s.semantic);
462 }
463
464 let bm25_idx = try_load_bm25_index(project_root);
465 match bm25_idx.as_ref() {
466 Some(idx) if idx.doc_count > 0 => {
467 let outcome = crate::core::embedding_index::build_or_update(root, idx);
468 let mut s = state
469 .lock()
470 .unwrap_or_else(std::sync::PoisonError::into_inner);
471 match outcome {
472 crate::core::embedding_index::EmbeddingBuildOutcome::Ready => {
473 finish_ok(&mut s.semantic);
474 }
475 crate::core::embedding_index::EmbeddingBuildOutcome::Skipped => {
476 finish_ok(&mut s.semantic);
477 s.semantic.note = Some(
478 "embeddings disabled by feature flag or config (search.dense_enabled / memory_profile)"
479 .to_string(),
480 );
481 }
482 crate::core::embedding_index::EmbeddingBuildOutcome::ModelNotAvailable(
483 ref reason,
484 ) => {
485 s.semantic.state = State::Idle;
486 s.semantic.note = Some(format!("embedding model not available: {reason}"));
487 }
488 crate::core::embedding_index::EmbeddingBuildOutcome::Failed => {
489 finish_err(
490 &mut s.semantic,
491 "embedding build failed (see logs)".to_string(),
492 );
493 }
494 }
495 }
496 _ => {
497 let mut s = state
498 .lock()
499 .unwrap_or_else(std::sync::PoisonError::into_inner);
500 s.semantic.state = State::Idle;
501 s.semantic.note =
502 Some("BM25 index is empty or unavailable — nothing to embed".to_string());
503 }
504 }
505}
506
507const MAX_EXTRA_ROOT_BUILDS: usize = 8;
511
512pub fn ensure_extra_roots_background(primary_root: &str, extra_roots: &[String]) {
513 let primary = Path::new(primary_root);
514 let mut queue: Vec<String> = Vec::new();
515 for root in extra_roots {
516 if queue.len() >= MAX_EXTRA_ROOT_BUILDS {
517 break;
518 }
519 let rp = Path::new(root);
520 if !rp.is_dir() {
521 continue;
522 }
523 if rp.starts_with(primary) {
525 continue;
526 }
527 if primary.starts_with(rp) {
529 continue;
530 }
531 queue.push(root.clone());
532 }
533 if queue.is_empty() {
534 return;
535 }
536
537 let spawned = std::thread::Builder::new()
546 .name("leanctx-extra-roots".to_string())
547 .stack_size(INDEXER_STACK_BYTES)
548 .spawn(move || {
549 for root in queue {
550 if crate::core::memory_guard::is_under_pressure()
551 || crate::core::memory_guard::abort_requested()
552 {
553 tracing::warn!(
554 "[index_orchestrator: skipping remaining extra-root builds under memory pressure]"
555 );
556 break;
557 }
558 if !try_claim_worker(&root) {
559 continue; }
561 nudge_daemon_index(&root);
562 run_build_worker(&root);
563 }
564 });
565 if let Err(e) = spawned {
566 tracing::warn!("[index_orchestrator: could not spawn extra-roots worker: {e}]");
567 }
568}
569
570fn bm25_build_note(
575 doc_count: usize,
576 save: &std::io::Result<crate::core::bm25_index::SaveOutcome>,
577) -> String {
578 use crate::core::bm25_index::SaveOutcome;
579 match save {
580 Ok(SaveOutcome::Persisted { compressed_bytes }) => format!(
581 "indexed {doc_count} chunks, {:.1} MB persisted",
582 *compressed_bytes as f64 / 1_048_576.0
583 ),
584 Ok(SaveOutcome::SkippedTooLarge {
585 compressed_bytes,
586 limit_bytes,
587 }) => format!(
588 "indexed {doc_count} chunks but NOT persisted to disk: compressed {:.1} MB exceeds the {:.0} MB cap. \
589 Raise it via LEAN_CTX_BM25_MAX_CACHE_MB (or bm25_max_cache_mb in config) or add extra_ignore_patterns, \
590 then run `lean-ctx reindex`. Until then the index is rebuilt from scratch on every cold start.",
591 *compressed_bytes as f64 / 1_048_576.0,
592 *limit_bytes as f64 / 1_048_576.0
593 ),
594 Err(e) => format!("indexed {doc_count} chunks but persisting failed: {e}"),
595 }
596}
597
598#[derive(Debug, Clone)]
601pub struct Bm25Summary {
602 pub state: &'static str,
603 pub elapsed_ms: Option<u64>,
605 pub note: Option<String>,
606 pub last_error: Option<String>,
607}
608
609#[derive(Debug, Clone)]
611pub struct SemanticSummary {
612 pub state: &'static str,
613 pub elapsed_ms: Option<u64>,
614 pub note: Option<String>,
615 pub last_error: Option<String>,
616}
617
618fn component_elapsed_and_state(c: &Component) -> (&'static str, Option<u64>) {
622 let elapsed_ms = if matches!(c.state, State::Building) {
623 c.started_ms.map(|start| now_ms().saturating_sub(start))
624 } else {
625 c.duration_ms
626 };
627 let state = match c.state {
628 State::Idle => "idle",
629 State::Building => "building",
630 State::Ready => "ready",
631 State::Failed => "failed",
632 };
633 (state, elapsed_ms)
634}
635
636pub fn semantic_summary(project_root: &str) -> SemanticSummary {
637 let entry = entry_for(project_root);
638 let s = entry
639 .lock()
640 .unwrap_or_else(std::sync::PoisonError::into_inner);
641 let c = &s.semantic;
642 let (state, elapsed_ms) = component_elapsed_and_state(c);
643 SemanticSummary {
644 state,
645 elapsed_ms,
646 note: c.note.clone(),
647 last_error: c.last_error.clone(),
648 }
649}
650
651pub fn bm25_summary(project_root: &str) -> Bm25Summary {
652 let entry = entry_for(project_root);
653 let s = entry
654 .lock()
655 .unwrap_or_else(std::sync::PoisonError::into_inner);
656 let c = &s.bm25;
657 let (state, elapsed_ms) = component_elapsed_and_state(c);
658 Bm25Summary {
659 state,
660 elapsed_ms,
661 note: c.note.clone(),
662 last_error: c.last_error.clone(),
663 }
664}
665
666pub fn try_load_graph_index(project_root: &str) -> Option<ProjectIndex> {
667 crate::core::graph_cache::get_cached(project_root).map(|arc| (*arc).clone())
670}
671
672pub fn try_load_bm25_index(project_root: &str) -> Option<BM25Index> {
673 BM25Index::load(Path::new(project_root))
674}
675
676pub fn is_building() -> bool {
678 let map = registry()
679 .lock()
680 .unwrap_or_else(std::sync::PoisonError::into_inner);
681 map.values().any(|entry| {
682 let st = entry
683 .lock()
684 .unwrap_or_else(std::sync::PoisonError::into_inner);
685 matches!(st.bm25.state, State::Building)
686 || matches!(st.graph.state, State::Building)
687 || matches!(st.semantic.state, State::Building)
688 })
689}
690
691#[derive(Debug, Serialize)]
692struct ComponentStatus<'a> {
693 state: &'a str,
694 started_ms: Option<u64>,
695 finished_ms: Option<u64>,
696 duration_ms: Option<u64>,
697 last_error: Option<&'a str>,
698 #[serde(skip_serializing_if = "Option::is_none")]
699 note: Option<&'a str>,
700}
701
702fn component_status(c: &Component) -> ComponentStatus<'_> {
703 ComponentStatus {
704 state: match c.state {
705 State::Idle => "idle",
706 State::Building => "building",
707 State::Ready => "ready",
708 State::Failed => "failed",
709 },
710 started_ms: c.started_ms,
711 finished_ms: c.finished_ms,
712 duration_ms: c.duration_ms,
713 last_error: c.last_error.as_deref(),
714 note: c.note.as_deref(),
715 }
716}
717
718#[derive(Debug, Serialize)]
719struct StatusResponse<'a> {
720 project_root: &'a str,
721 graph_index: ComponentStatus<'a>,
722 bm25_index: ComponentStatus<'a>,
723 semantic_index: ComponentStatus<'a>,
727 disk: DiskStatusAll,
728 #[serde(skip_serializing_if = "Option::is_none")]
731 index_filters: Option<String>,
732}
733
734#[derive(Debug, Serialize, Default)]
735pub struct DiskStatus {
736 pub exists: bool,
737 pub size_bytes: Option<u64>,
738 pub file_count: Option<u64>,
739 pub modified_at: Option<String>,
740}
741
742#[derive(Debug, Serialize, Default)]
743pub struct DiskStatusAll {
744 pub graph_index: DiskStatus,
745 pub bm25_index: DiskStatus,
746 pub code_graph: DiskStatus,
747 pub semantic_index: DiskStatus,
751}
752
753fn disk_status_for_graph(project_root: &str) -> DiskStatus {
754 let Some(dir) = graph_index::ProjectIndex::index_dir(project_root) else {
759 return DiskStatus::default();
760 };
761 let meta_file = dir.join("graph.meta.json");
762 if !meta_file.exists() {
763 return DiskStatus::default();
764 }
765 let meta = std::fs::metadata(&meta_file).ok();
766 let file_count =
767 graph_index::ProjectIndex::load(project_root).map(|idx| idx.files.len() as u64);
768 DiskStatus {
769 exists: true,
770 size_bytes: meta.as_ref().map(std::fs::Metadata::len),
771 file_count,
772 modified_at: meta.and_then(|m| m.modified().ok()).map(format_time),
773 }
774}
775
776fn disk_status_for_bm25(project_root: &str) -> DiskStatus {
777 let root = Path::new(project_root);
778 let path = BM25Index::index_file_path(root);
779 if !path.exists() {
780 return DiskStatus::default();
781 }
782 let meta = std::fs::metadata(&path).ok();
783 DiskStatus {
784 exists: true,
785 size_bytes: meta.as_ref().map(std::fs::Metadata::len),
786 file_count: None,
787 modified_at: meta.and_then(|m| m.modified().ok()).map(format_time),
788 }
789}
790
791fn disk_status_for_code_graph(project_root: &str) -> DiskStatus {
792 let dir = crate::core::property_graph::graph_dir(project_root);
793 let db_path = dir.join("graph.db");
794 if !db_path.exists() {
795 return DiskStatus::default();
796 }
797 let meta = std::fs::metadata(&db_path).ok();
798 let node_count = crate::core::property_graph::CodeGraph::open(project_root)
799 .ok()
800 .and_then(|g| {
801 g.connection()
802 .query_row("SELECT count(*) FROM nodes", [], |r| r.get::<_, i64>(0))
803 .ok()
804 .map(|c| c as u64)
805 });
806 DiskStatus {
807 exists: true,
808 size_bytes: meta.as_ref().map(std::fs::Metadata::len),
809 file_count: node_count,
810 modified_at: meta.and_then(|m| m.modified().ok()).map(format_time),
811 }
812}
813
814fn format_time(t: SystemTime) -> String {
815 let secs = t.duration_since(UNIX_EPOCH).unwrap_or_default().as_secs();
816 let dt = chrono::DateTime::from_timestamp(secs as i64, 0);
817 dt.map_or_else(
818 || format!("{secs}"),
819 |d| d.format("%Y-%m-%d %H:%M:%S UTC").to_string(),
820 )
821}
822
823pub fn disk_status_for_semantic(project_root: &str) -> DiskStatus {
824 let root = Path::new(project_root);
825 let dir = crate::core::index_namespace::vectors_dir(root);
826 let bin_path = dir.join("embeddings.bin");
827 if !bin_path.exists() {
828 return DiskStatus::default();
829 }
830 let meta = std::fs::metadata(&bin_path).ok();
831 DiskStatus {
832 exists: true,
833 size_bytes: meta.as_ref().map(std::fs::Metadata::len),
834 file_count: None,
835 modified_at: meta.and_then(|m| m.modified().ok()).map(format_time),
836 }
837}
838
839pub fn disk_status(project_root: &str) -> DiskStatusAll {
840 DiskStatusAll {
841 graph_index: disk_status_for_graph(project_root),
842 bm25_index: disk_status_for_bm25(project_root),
843 code_graph: disk_status_for_code_graph(project_root),
844 semantic_index: disk_status_for_semantic(project_root),
845 }
846}
847
848pub fn status_json(project_root: &str) -> String {
849 let disk = disk_status(project_root);
853 let state = entry_for(project_root);
854 let s = state
855 .lock()
856 .unwrap_or_else(std::sync::PoisonError::into_inner);
857 let res = StatusResponse {
858 project_root,
859 graph_index: component_status(&s.graph),
860 bm25_index: component_status(&s.bm25),
861 semantic_index: component_status(&s.semantic),
862 disk,
863 index_filters: crate::core::index_filter::IndexFileFilter::effective().summary(),
864 };
865 serde_json::to_string(&res).unwrap_or_else(|_| "{}".to_string())
866}
867
868#[cfg(test)]
869mod tests {
870 use super::*;
871
872 #[test]
873 fn status_json_is_valid_json() {
874 let s = status_json("/tmp");
875 let _: serde_json::Value = serde_json::from_str(&s).unwrap();
876 }
877
878 #[test]
879 fn background_build_phases_are_serialized_with_reclamation() {
880 let events = std::cell::RefCell::new(Vec::new());
881 run_memory_bounded_phases(
882 || events.borrow_mut().push("graph"),
883 || events.borrow_mut().push("bm25"),
884 || events.borrow_mut().push("search"),
885 || events.borrow_mut().push("reclaim"),
886 );
887 assert_eq!(
888 events.into_inner(),
889 ["graph", "reclaim", "bm25", "reclaim", "search"]
890 );
891 }
892
893 #[test]
894 fn warm_need_classifies_tools() {
895 for light in [
897 "ctx_read",
898 "ctx_shell",
899 "ctx_tree",
900 "ctx_knowledge",
901 "unknown_tool",
902 ] {
903 assert_eq!(warm_need_for_tool(light), WarmNeed::None, "{light}");
904 }
905 assert_eq!(warm_need_for_tool("ctx_search"), WarmNeed::Search);
907 for heavy in [
908 "ctx_graph",
909 "ctx_callgraph",
910 "ctx_routes",
911 "ctx_repomap",
912 "ctx_impact",
913 "ctx_artifacts",
914 "ctx_semantic_search",
915 "ctx_provider",
916 "ctx_compose",
917 "ctx_explore",
918 "ctx_review",
919 ] {
920 assert_eq!(warm_need_for_tool(heavy), WarmNeed::Heavy, "{heavy}");
921 }
922 }
923
924 #[test]
925 fn ensure_warm_lightweight_and_search_never_signal_first_warm() {
926 assert!(!ensure_warm_for_tool("", "ctx_graph"));
927 let tmp = tempfile::tempdir().unwrap();
928 let root = tmp.path().to_string_lossy().to_string();
929 assert!(!ensure_warm_for_tool(&root, "ctx_read"));
930 assert!(!ensure_warm_for_tool(&root, "ctx_search"));
931 }
932
933 #[test]
934 fn ensure_warm_heavy_is_once_per_root() {
935 let tmp = tempfile::tempdir().unwrap();
939 let root = tmp.path().to_string_lossy().to_string();
940 assert!(
941 ensure_warm_for_tool(&root, "ctx_callgraph"),
942 "first heavy warm must signal true"
943 );
944 assert!(
945 !ensure_warm_for_tool(&root, "ctx_callgraph"),
946 "second heavy warm must be deduped to false"
947 );
948 assert!(
949 !ensure_warm_for_tool(&root, "ctx_semantic_search"),
950 "any later heavy tool on the same root is also deduped"
951 );
952 }
953
954 #[test]
955 fn build_note_persisted_reports_size() {
956 let note = bm25_build_note(
957 42,
958 &Ok(crate::core::bm25_index::SaveOutcome::Persisted {
959 compressed_bytes: 3 * 1024 * 1024,
960 }),
961 );
962 assert!(
963 note.contains("42 chunks"),
964 "note should report chunk count: {note}"
965 );
966 assert!(
967 note.contains("persisted"),
968 "note should report persistence: {note}"
969 );
970 }
971
972 #[test]
973 fn build_note_too_large_carries_remedy() {
974 let note = bm25_build_note(
975 1000,
976 &Ok(crate::core::bm25_index::SaveOutcome::SkippedTooLarge {
977 compressed_bytes: 600 * 1024 * 1024,
978 limit_bytes: 512 * 1024 * 1024,
979 }),
980 );
981 assert!(
982 note.contains("NOT persisted"),
983 "must flag non-persistence: {note}"
984 );
985 assert!(
986 note.contains("LEAN_CTX_BM25_MAX_CACHE_MB") && note.contains("reindex"),
987 "too-large note must carry an actionable remedy: {note}"
988 );
989 }
990
991 #[test]
992 fn build_note_persist_error_is_reported() {
993 let note = bm25_build_note(7, &Err(std::io::Error::other("disk full")));
994 assert!(note.contains("persisting failed"), "note: {note}");
995 assert!(
996 note.contains("disk full"),
997 "note should include the io error: {note}"
998 );
999 }
1000
1001 #[test]
1002 fn bm25_summary_unknown_project_is_idle() {
1003 let tmp = tempfile::tempdir().unwrap();
1004 let summary = bm25_summary(tmp.path().to_string_lossy().as_ref());
1005 assert_eq!(summary.state, "idle");
1006 assert!(summary.note.is_none());
1007 assert!(summary.last_error.is_none());
1008 }
1009
1010 #[test]
1011 fn extra_roots_skips_subdirs_of_primary() {
1012 let tmp = tempfile::tempdir().unwrap();
1013 let primary = tmp.path().join("primary");
1014 std::fs::create_dir_all(&primary).unwrap();
1015 let sub = primary.join("subdir");
1016 std::fs::create_dir_all(&sub).unwrap();
1017 let external = tmp.path().join("external");
1018 std::fs::create_dir_all(&external).unwrap();
1019
1020 let primary_str = primary.to_string_lossy().to_string();
1021 let extra = vec![
1022 sub.to_string_lossy().to_string(),
1023 external.to_string_lossy().to_string(),
1024 ];
1025
1026 ensure_extra_roots_background(&primary_str, &extra);
1028 }
1029
1030 #[test]
1031 fn extra_roots_caps_at_max() {
1032 let tmp = tempfile::tempdir().unwrap();
1033 let primary = tmp.path().join("primary");
1034 std::fs::create_dir_all(&primary).unwrap();
1035
1036 let mut extra = Vec::new();
1037 for i in 0..20 {
1038 let d = tmp.path().join(format!("ext-{i}"));
1039 std::fs::create_dir_all(&d).unwrap();
1040 extra.push(d.to_string_lossy().to_string());
1041 }
1042
1043 let primary_str = primary.to_string_lossy().to_string();
1044 ensure_extra_roots_background(&primary_str, &extra);
1046 }
1047
1048 #[test]
1049 fn bm25_index_lock_name_is_per_repo_and_distinct_from_graph() {
1050 let a = bm25_index_lock_name(Path::new("/tmp/repo-a"));
1051 let b = bm25_index_lock_name(Path::new("/tmp/repo-b"));
1052 assert!(a.starts_with("bm25-idx-"), "unexpected lock name: {a}");
1053 assert_ne!(a, b, "lock name must be per-repo");
1054 assert_eq!(a, bm25_index_lock_name(Path::new("/tmp/repo-a")));
1056 let graph = format!(
1059 "graph-idx-{}",
1060 &crate::core::index_namespace::namespace_hash(Path::new("/tmp/repo-a"))[..8]
1061 );
1062 assert_ne!(a, graph, "bm25 and graph locks must be independent");
1063 }
1064}