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