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::search_index::ensure_background(root, true, false);
313
314 let sequential = crate::core::memory_guard::is_under_pressure();
318 if sequential {
319 tracing::info!(
320 "[index_orchestrator: memory pressure detected — running graph → BM25 sequentially]"
321 );
322 }
323
324 let graph_state = entry_for(root);
325 let graph_root = root.to_string();
326 let build_graph = move || {
327 {
328 let mut s = graph_state
329 .lock()
330 .unwrap_or_else(std::sync::PoisonError::into_inner);
331 start_component(&mut s.graph);
332 }
333 let graph_result = std::panic::catch_unwind(|| {
334 let (idx, _cache) = graph_index::scan_with_content_cache(&graph_root);
335 if let Err(e) = idx.save() {
336 tracing::warn!("[index_orchestrator: graph save failed: {e}]");
337 }
338 crate::core::code_health::persist::refresh_if_stale(&graph_root, &idx);
339 });
340 if let Ok(()) = graph_result {
341 let mut s = graph_state
342 .lock()
343 .unwrap_or_else(std::sync::PoisonError::into_inner);
344 finish_ok(&mut s.graph);
345 } else {
346 let mut s = graph_state
347 .lock()
348 .unwrap_or_else(std::sync::PoisonError::into_inner);
349 finish_err(&mut s.graph, "graph index build panicked".to_string());
350 }
351 };
352
353 let bm25_state = entry_for(root);
354 let bm25_root = root.to_string();
355 let build_bm25 = move || {
356 {
357 let mut s = bm25_state
358 .lock()
359 .unwrap_or_else(std::sync::PoisonError::into_inner);
360 start_component(&mut s.bm25);
361 }
362 let bm = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
363 let root_pb = Path::new(&bm25_root);
364 let lock_name = bm25_index_lock_name(root_pb);
365 let _lock = crate::core::startup_guard::try_acquire_lock(
366 &lock_name,
367 std::time::Duration::from_millis(800),
368 std::time::Duration::from_mins(3),
369 );
370 if _lock.is_none() {
371 tracing::info!(
372 "[bm25: another process is building {bm25_root} — loading the shared index]"
373 );
374 let idx = BM25Index::load(root_pb).unwrap_or_default();
375 return (idx.doc_count, None);
376 }
377 let idx = BM25Index::load_or_build(root_pb);
378 let outcome = idx.save(root_pb);
379 (idx.doc_count, Some(outcome))
380 }));
381 if let Ok((doc_count, save_res)) = bm {
382 let mut s = bm25_state
383 .lock()
384 .unwrap_or_else(std::sync::PoisonError::into_inner);
385 finish_ok(&mut s.bm25);
386 s.bm25.note = Some(match save_res {
387 Some(outcome) => bm25_build_note(doc_count, &outcome),
388 None => format!(
389 "loaded shared BM25 index ({doc_count} chunks) — build in progress in another process"
390 ),
391 });
392 } else {
393 let mut s = bm25_state
394 .lock()
395 .unwrap_or_else(std::sync::PoisonError::into_inner);
396 finish_err(&mut s.bm25, "bm25 build panicked".to_string());
397 }
398 };
399
400 if sequential {
401 build_graph();
402 crate::core::content_cache::clear();
403 crate::core::memory_guard::force_purge();
404 build_bm25();
405 } else {
406 let graph_handle = std::thread::Builder::new()
407 .name("leanctx-graph".to_string())
408 .stack_size(INDEXER_STACK_BYTES)
409 .spawn(build_graph)
410 .expect("spawning graph index thread");
411 let bm25_handle = std::thread::Builder::new()
412 .name("leanctx-bm25".to_string())
413 .stack_size(INDEXER_STACK_BYTES)
414 .spawn(build_bm25)
415 .expect("spawning BM25 index thread");
416 if let Err(e) = graph_handle.join() {
417 tracing::error!("[index_orchestrator: graph thread panicked: {e:?}]");
418 }
419 if let Err(e) = bm25_handle.join() {
420 tracing::error!("[index_orchestrator: BM25 thread panicked: {e:?}]");
421 }
422 }
423
424 crate::core::content_cache::trim_oldest_percent(75);
431 crate::core::memory_guard::force_purge();
432
433 let final_state = entry_for(root);
434 let mut s = final_state
435 .lock()
436 .unwrap_or_else(std::sync::PoisonError::into_inner);
437 s.worker_running = false;
438}
439
440pub fn build_semantic(project_root: &str) {
445 let state = entry_for(project_root);
446 let root = Path::new(project_root);
447
448 {
449 let mut s = state
450 .lock()
451 .unwrap_or_else(std::sync::PoisonError::into_inner);
452 start_component(&mut s.semantic);
453 }
454
455 let bm25_idx = try_load_bm25_index(project_root);
456 match bm25_idx.as_ref() {
457 Some(idx) if idx.doc_count > 0 => {
458 let outcome = crate::core::embedding_index::build_or_update(root, idx);
459 let mut s = state
460 .lock()
461 .unwrap_or_else(std::sync::PoisonError::into_inner);
462 match outcome {
463 crate::core::embedding_index::EmbeddingBuildOutcome::Ready => {
464 finish_ok(&mut s.semantic);
465 }
466 crate::core::embedding_index::EmbeddingBuildOutcome::Skipped => {
467 finish_ok(&mut s.semantic);
468 s.semantic.note = Some(
469 "embeddings disabled by feature flag or config (search.dense_enabled / memory_profile)"
470 .to_string(),
471 );
472 }
473 crate::core::embedding_index::EmbeddingBuildOutcome::ModelNotAvailable(
474 ref reason,
475 ) => {
476 s.semantic.state = State::Idle;
477 s.semantic.note = Some(format!("embedding model not available: {reason}"));
478 }
479 crate::core::embedding_index::EmbeddingBuildOutcome::Failed => {
480 finish_err(
481 &mut s.semantic,
482 "embedding build failed (see logs)".to_string(),
483 );
484 }
485 }
486 }
487 _ => {
488 let mut s = state
489 .lock()
490 .unwrap_or_else(std::sync::PoisonError::into_inner);
491 s.semantic.state = State::Idle;
492 s.semantic.note =
493 Some("BM25 index is empty or unavailable — nothing to embed".to_string());
494 }
495 }
496}
497
498const MAX_EXTRA_ROOT_BUILDS: usize = 8;
502
503pub fn ensure_extra_roots_background(primary_root: &str, extra_roots: &[String]) {
504 let primary = Path::new(primary_root);
505 let mut queue: Vec<String> = Vec::new();
506 for root in extra_roots {
507 if queue.len() >= MAX_EXTRA_ROOT_BUILDS {
508 break;
509 }
510 let rp = Path::new(root);
511 if !rp.is_dir() {
512 continue;
513 }
514 if rp.starts_with(primary) {
516 continue;
517 }
518 if primary.starts_with(rp) {
520 continue;
521 }
522 queue.push(root.clone());
523 }
524 if queue.is_empty() {
525 return;
526 }
527
528 let spawned = std::thread::Builder::new()
537 .name("leanctx-extra-roots".to_string())
538 .stack_size(INDEXER_STACK_BYTES)
539 .spawn(move || {
540 for root in queue {
541 if crate::core::memory_guard::is_under_pressure()
542 || crate::core::memory_guard::abort_requested()
543 {
544 tracing::warn!(
545 "[index_orchestrator: skipping remaining extra-root builds under memory pressure]"
546 );
547 break;
548 }
549 if !try_claim_worker(&root) {
550 continue; }
552 nudge_daemon_index(&root);
553 run_build_worker(&root);
554 }
555 });
556 if let Err(e) = spawned {
557 tracing::warn!("[index_orchestrator: could not spawn extra-roots worker: {e}]");
558 }
559}
560
561fn bm25_build_note(
566 doc_count: usize,
567 save: &std::io::Result<crate::core::bm25_index::SaveOutcome>,
568) -> String {
569 use crate::core::bm25_index::SaveOutcome;
570 match save {
571 Ok(SaveOutcome::Persisted { compressed_bytes }) => format!(
572 "indexed {doc_count} chunks, {:.1} MB persisted",
573 *compressed_bytes as f64 / 1_048_576.0
574 ),
575 Ok(SaveOutcome::SkippedTooLarge {
576 compressed_bytes,
577 limit_bytes,
578 }) => format!(
579 "indexed {doc_count} chunks but NOT persisted to disk: compressed {:.1} MB exceeds the {:.0} MB cap. \
580 Raise it via LEAN_CTX_BM25_MAX_CACHE_MB (or bm25_max_cache_mb in config) or add extra_ignore_patterns, \
581 then run `lean-ctx reindex`. Until then the index is rebuilt from scratch on every cold start.",
582 *compressed_bytes as f64 / 1_048_576.0,
583 *limit_bytes as f64 / 1_048_576.0
584 ),
585 Err(e) => format!("indexed {doc_count} chunks but persisting failed: {e}"),
586 }
587}
588
589#[derive(Debug, Clone)]
592pub struct Bm25Summary {
593 pub state: &'static str,
594 pub elapsed_ms: Option<u64>,
596 pub note: Option<String>,
597 pub last_error: Option<String>,
598}
599
600#[derive(Debug, Clone)]
602pub struct SemanticSummary {
603 pub state: &'static str,
604 pub elapsed_ms: Option<u64>,
605 pub note: Option<String>,
606 pub last_error: Option<String>,
607}
608
609fn component_elapsed_and_state(c: &Component) -> (&'static str, Option<u64>) {
613 let elapsed_ms = if matches!(c.state, State::Building) {
614 c.started_ms.map(|start| now_ms().saturating_sub(start))
615 } else {
616 c.duration_ms
617 };
618 let state = match c.state {
619 State::Idle => "idle",
620 State::Building => "building",
621 State::Ready => "ready",
622 State::Failed => "failed",
623 };
624 (state, elapsed_ms)
625}
626
627pub fn semantic_summary(project_root: &str) -> SemanticSummary {
628 let entry = entry_for(project_root);
629 let s = entry
630 .lock()
631 .unwrap_or_else(std::sync::PoisonError::into_inner);
632 let c = &s.semantic;
633 let (state, elapsed_ms) = component_elapsed_and_state(c);
634 SemanticSummary {
635 state,
636 elapsed_ms,
637 note: c.note.clone(),
638 last_error: c.last_error.clone(),
639 }
640}
641
642pub fn bm25_summary(project_root: &str) -> Bm25Summary {
643 let entry = entry_for(project_root);
644 let s = entry
645 .lock()
646 .unwrap_or_else(std::sync::PoisonError::into_inner);
647 let c = &s.bm25;
648 let (state, elapsed_ms) = component_elapsed_and_state(c);
649 Bm25Summary {
650 state,
651 elapsed_ms,
652 note: c.note.clone(),
653 last_error: c.last_error.clone(),
654 }
655}
656
657pub fn try_load_graph_index(project_root: &str) -> Option<ProjectIndex> {
658 crate::core::graph_cache::get_cached(project_root).map(|arc| (*arc).clone())
661}
662
663pub fn try_load_bm25_index(project_root: &str) -> Option<BM25Index> {
664 BM25Index::load(Path::new(project_root))
665}
666
667pub fn is_building() -> bool {
669 let map = registry()
670 .lock()
671 .unwrap_or_else(std::sync::PoisonError::into_inner);
672 map.values().any(|entry| {
673 let st = entry
674 .lock()
675 .unwrap_or_else(std::sync::PoisonError::into_inner);
676 matches!(st.bm25.state, State::Building)
677 || matches!(st.graph.state, State::Building)
678 || matches!(st.semantic.state, State::Building)
679 })
680}
681
682#[derive(Debug, Serialize)]
683struct ComponentStatus<'a> {
684 state: &'a str,
685 started_ms: Option<u64>,
686 finished_ms: Option<u64>,
687 duration_ms: Option<u64>,
688 last_error: Option<&'a str>,
689 #[serde(skip_serializing_if = "Option::is_none")]
690 note: Option<&'a str>,
691}
692
693fn component_status(c: &Component) -> ComponentStatus<'_> {
694 ComponentStatus {
695 state: match c.state {
696 State::Idle => "idle",
697 State::Building => "building",
698 State::Ready => "ready",
699 State::Failed => "failed",
700 },
701 started_ms: c.started_ms,
702 finished_ms: c.finished_ms,
703 duration_ms: c.duration_ms,
704 last_error: c.last_error.as_deref(),
705 note: c.note.as_deref(),
706 }
707}
708
709#[derive(Debug, Serialize)]
710struct StatusResponse<'a> {
711 project_root: &'a str,
712 graph_index: ComponentStatus<'a>,
713 bm25_index: ComponentStatus<'a>,
714 semantic_index: ComponentStatus<'a>,
718 disk: DiskStatusAll,
719 #[serde(skip_serializing_if = "Option::is_none")]
722 index_filters: Option<String>,
723}
724
725#[derive(Debug, Serialize, Default)]
726pub struct DiskStatus {
727 pub exists: bool,
728 pub size_bytes: Option<u64>,
729 pub file_count: Option<u64>,
730 pub modified_at: Option<String>,
731}
732
733#[derive(Debug, Serialize, Default)]
734pub struct DiskStatusAll {
735 pub graph_index: DiskStatus,
736 pub bm25_index: DiskStatus,
737 pub code_graph: DiskStatus,
738 pub semantic_index: DiskStatus,
742}
743
744fn disk_status_for_graph(project_root: &str) -> DiskStatus {
745 let Some(dir) = graph_index::ProjectIndex::index_dir(project_root) else {
750 return DiskStatus::default();
751 };
752 let meta_file = dir.join("graph.meta.json");
753 if !meta_file.exists() {
754 return DiskStatus::default();
755 }
756 let meta = std::fs::metadata(&meta_file).ok();
757 let file_count =
758 graph_index::ProjectIndex::load(project_root).map(|idx| idx.files.len() as u64);
759 DiskStatus {
760 exists: true,
761 size_bytes: meta.as_ref().map(std::fs::Metadata::len),
762 file_count,
763 modified_at: meta.and_then(|m| m.modified().ok()).map(format_time),
764 }
765}
766
767fn disk_status_for_bm25(project_root: &str) -> DiskStatus {
768 let root = Path::new(project_root);
769 let path = BM25Index::index_file_path(root);
770 if !path.exists() {
771 return DiskStatus::default();
772 }
773 let meta = std::fs::metadata(&path).ok();
774 DiskStatus {
775 exists: true,
776 size_bytes: meta.as_ref().map(std::fs::Metadata::len),
777 file_count: None,
778 modified_at: meta.and_then(|m| m.modified().ok()).map(format_time),
779 }
780}
781
782fn disk_status_for_code_graph(project_root: &str) -> DiskStatus {
783 let dir = crate::core::property_graph::graph_dir(project_root);
784 let db_path = dir.join("graph.db");
785 if !db_path.exists() {
786 return DiskStatus::default();
787 }
788 let meta = std::fs::metadata(&db_path).ok();
789 let node_count = crate::core::property_graph::CodeGraph::open(project_root)
790 .ok()
791 .and_then(|g| {
792 g.connection()
793 .query_row("SELECT count(*) FROM nodes", [], |r| r.get::<_, i64>(0))
794 .ok()
795 .map(|c| c as u64)
796 });
797 DiskStatus {
798 exists: true,
799 size_bytes: meta.as_ref().map(std::fs::Metadata::len),
800 file_count: node_count,
801 modified_at: meta.and_then(|m| m.modified().ok()).map(format_time),
802 }
803}
804
805fn format_time(t: SystemTime) -> String {
806 let secs = t.duration_since(UNIX_EPOCH).unwrap_or_default().as_secs();
807 let dt = chrono::DateTime::from_timestamp(secs as i64, 0);
808 dt.map_or_else(
809 || format!("{secs}"),
810 |d| d.format("%Y-%m-%d %H:%M:%S UTC").to_string(),
811 )
812}
813
814pub fn disk_status_for_semantic(project_root: &str) -> DiskStatus {
815 let root = Path::new(project_root);
816 let dir = crate::core::index_namespace::vectors_dir(root);
817 let bin_path = dir.join("embeddings.bin");
818 if !bin_path.exists() {
819 return DiskStatus::default();
820 }
821 let meta = std::fs::metadata(&bin_path).ok();
822 DiskStatus {
823 exists: true,
824 size_bytes: meta.as_ref().map(std::fs::Metadata::len),
825 file_count: None,
826 modified_at: meta.and_then(|m| m.modified().ok()).map(format_time),
827 }
828}
829
830pub fn disk_status(project_root: &str) -> DiskStatusAll {
831 DiskStatusAll {
832 graph_index: disk_status_for_graph(project_root),
833 bm25_index: disk_status_for_bm25(project_root),
834 code_graph: disk_status_for_code_graph(project_root),
835 semantic_index: disk_status_for_semantic(project_root),
836 }
837}
838
839pub fn status_json(project_root: &str) -> String {
840 let disk = disk_status(project_root);
844 let state = entry_for(project_root);
845 let s = state
846 .lock()
847 .unwrap_or_else(std::sync::PoisonError::into_inner);
848 let res = StatusResponse {
849 project_root,
850 graph_index: component_status(&s.graph),
851 bm25_index: component_status(&s.bm25),
852 semantic_index: component_status(&s.semantic),
853 disk,
854 index_filters: crate::core::index_filter::IndexFileFilter::effective().summary(),
855 };
856 serde_json::to_string(&res).unwrap_or_else(|_| "{}".to_string())
857}
858
859#[cfg(test)]
860mod tests {
861 use super::*;
862
863 #[test]
864 fn status_json_is_valid_json() {
865 let s = status_json("/tmp");
866 let _: serde_json::Value = serde_json::from_str(&s).unwrap();
867 }
868
869 #[test]
870 fn warm_need_classifies_tools() {
871 for light in [
873 "ctx_read",
874 "ctx_shell",
875 "ctx_tree",
876 "ctx_knowledge",
877 "unknown_tool",
878 ] {
879 assert_eq!(warm_need_for_tool(light), WarmNeed::None, "{light}");
880 }
881 assert_eq!(warm_need_for_tool("ctx_search"), WarmNeed::Search);
883 for heavy in [
884 "ctx_graph",
885 "ctx_callgraph",
886 "ctx_routes",
887 "ctx_repomap",
888 "ctx_impact",
889 "ctx_artifacts",
890 "ctx_semantic_search",
891 "ctx_provider",
892 "ctx_compose",
893 "ctx_explore",
894 "ctx_review",
895 ] {
896 assert_eq!(warm_need_for_tool(heavy), WarmNeed::Heavy, "{heavy}");
897 }
898 }
899
900 #[test]
901 fn ensure_warm_lightweight_and_search_never_signal_first_warm() {
902 assert!(!ensure_warm_for_tool("", "ctx_graph"));
903 let tmp = tempfile::tempdir().unwrap();
904 let root = tmp.path().to_string_lossy().to_string();
905 assert!(!ensure_warm_for_tool(&root, "ctx_read"));
906 assert!(!ensure_warm_for_tool(&root, "ctx_search"));
907 }
908
909 #[test]
910 fn ensure_warm_heavy_is_once_per_root() {
911 let tmp = tempfile::tempdir().unwrap();
915 let root = tmp.path().to_string_lossy().to_string();
916 assert!(
917 ensure_warm_for_tool(&root, "ctx_callgraph"),
918 "first heavy warm must signal true"
919 );
920 assert!(
921 !ensure_warm_for_tool(&root, "ctx_callgraph"),
922 "second heavy warm must be deduped to false"
923 );
924 assert!(
925 !ensure_warm_for_tool(&root, "ctx_semantic_search"),
926 "any later heavy tool on the same root is also deduped"
927 );
928 }
929
930 #[test]
931 fn build_note_persisted_reports_size() {
932 let note = bm25_build_note(
933 42,
934 &Ok(crate::core::bm25_index::SaveOutcome::Persisted {
935 compressed_bytes: 3 * 1024 * 1024,
936 }),
937 );
938 assert!(
939 note.contains("42 chunks"),
940 "note should report chunk count: {note}"
941 );
942 assert!(
943 note.contains("persisted"),
944 "note should report persistence: {note}"
945 );
946 }
947
948 #[test]
949 fn build_note_too_large_carries_remedy() {
950 let note = bm25_build_note(
951 1000,
952 &Ok(crate::core::bm25_index::SaveOutcome::SkippedTooLarge {
953 compressed_bytes: 600 * 1024 * 1024,
954 limit_bytes: 512 * 1024 * 1024,
955 }),
956 );
957 assert!(
958 note.contains("NOT persisted"),
959 "must flag non-persistence: {note}"
960 );
961 assert!(
962 note.contains("LEAN_CTX_BM25_MAX_CACHE_MB") && note.contains("reindex"),
963 "too-large note must carry an actionable remedy: {note}"
964 );
965 }
966
967 #[test]
968 fn build_note_persist_error_is_reported() {
969 let note = bm25_build_note(7, &Err(std::io::Error::other("disk full")));
970 assert!(note.contains("persisting failed"), "note: {note}");
971 assert!(
972 note.contains("disk full"),
973 "note should include the io error: {note}"
974 );
975 }
976
977 #[test]
978 fn bm25_summary_unknown_project_is_idle() {
979 let tmp = tempfile::tempdir().unwrap();
980 let summary = bm25_summary(tmp.path().to_string_lossy().as_ref());
981 assert_eq!(summary.state, "idle");
982 assert!(summary.note.is_none());
983 assert!(summary.last_error.is_none());
984 }
985
986 #[test]
987 fn extra_roots_skips_subdirs_of_primary() {
988 let tmp = tempfile::tempdir().unwrap();
989 let primary = tmp.path().join("primary");
990 std::fs::create_dir_all(&primary).unwrap();
991 let sub = primary.join("subdir");
992 std::fs::create_dir_all(&sub).unwrap();
993 let external = tmp.path().join("external");
994 std::fs::create_dir_all(&external).unwrap();
995
996 let primary_str = primary.to_string_lossy().to_string();
997 let extra = vec![
998 sub.to_string_lossy().to_string(),
999 external.to_string_lossy().to_string(),
1000 ];
1001
1002 ensure_extra_roots_background(&primary_str, &extra);
1004 }
1005
1006 #[test]
1007 fn extra_roots_caps_at_max() {
1008 let tmp = tempfile::tempdir().unwrap();
1009 let primary = tmp.path().join("primary");
1010 std::fs::create_dir_all(&primary).unwrap();
1011
1012 let mut extra = Vec::new();
1013 for i in 0..20 {
1014 let d = tmp.path().join(format!("ext-{i}"));
1015 std::fs::create_dir_all(&d).unwrap();
1016 extra.push(d.to_string_lossy().to_string());
1017 }
1018
1019 let primary_str = primary.to_string_lossy().to_string();
1020 ensure_extra_roots_background(&primary_str, &extra);
1022 }
1023
1024 #[test]
1025 fn bm25_index_lock_name_is_per_repo_and_distinct_from_graph() {
1026 let a = bm25_index_lock_name(Path::new("/tmp/repo-a"));
1027 let b = bm25_index_lock_name(Path::new("/tmp/repo-b"));
1028 assert!(a.starts_with("bm25-idx-"), "unexpected lock name: {a}");
1029 assert_ne!(a, b, "lock name must be per-repo");
1030 assert_eq!(a, bm25_index_lock_name(Path::new("/tmp/repo-a")));
1032 let graph = format!(
1035 "graph-idx-{}",
1036 &crate::core::index_namespace::namespace_hash(Path::new("/tmp/repo-a"))[..8]
1037 );
1038 assert_ne!(a, graph, "bm25 and graph locks must be independent");
1039 }
1040}