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
251pub fn ensure_all_background(project_root: &str) {
252 let state = entry_for(project_root);
253 let should_spawn = {
254 let mut s = state
255 .lock()
256 .unwrap_or_else(std::sync::PoisonError::into_inner);
257 if s.worker_running {
258 false
259 } else {
260 s.worker_running = true;
261 true
262 }
263 };
264
265 if !should_spawn {
266 return;
267 }
268
269 nudge_daemon_index(project_root);
274
275 let root = project_root.to_string();
276 let indexer = move || {
277 crate::core::search_index::ensure_background(&root, true, false);
280
281 let graph_state = entry_for(&root);
283 let graph_root = root.clone();
284 let graph_handle = std::thread::Builder::new()
285 .name("leanctx-graph".to_string())
286 .stack_size(INDEXER_STACK_BYTES)
287 .spawn(move || {
288 {
289 let mut s = graph_state
290 .lock()
291 .unwrap_or_else(std::sync::PoisonError::into_inner);
292 start_component(&mut s.graph);
293 }
294 let graph_result = std::panic::catch_unwind(|| {
295 let (idx, _cache) = graph_index::scan_with_content_cache(&graph_root);
296 if let Err(e) = idx.save() {
300 tracing::warn!("[index_orchestrator: graph save failed: {e}]");
301 }
302 });
303 if let Ok(()) = graph_result {
304 let mut s = graph_state
305 .lock()
306 .unwrap_or_else(std::sync::PoisonError::into_inner);
307 finish_ok(&mut s.graph);
308 } else {
309 let mut s = graph_state
310 .lock()
311 .unwrap_or_else(std::sync::PoisonError::into_inner);
312 finish_err(&mut s.graph, "graph index build panicked".to_string());
313 }
314 })
315 .expect("spawning graph index thread");
316
317 let bm25_state = entry_for(&root);
318 let bm25_root = root.clone();
319 let bm25_handle = std::thread::Builder::new()
320 .name("leanctx-bm25".to_string())
321 .stack_size(INDEXER_STACK_BYTES)
322 .spawn(move || {
323 {
324 let mut s = bm25_state
325 .lock()
326 .unwrap_or_else(std::sync::PoisonError::into_inner);
327 start_component(&mut s.bm25);
328 }
329 let bm = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
330 let root_pb = Path::new(&bm25_root);
331 let lock_name = bm25_index_lock_name(root_pb);
334 let _lock = crate::core::startup_guard::try_acquire_lock(
335 &lock_name,
336 std::time::Duration::from_millis(800),
337 std::time::Duration::from_mins(3),
338 );
339 if _lock.is_none() {
340 tracing::info!(
341 "[bm25: another process is building {bm25_root} — loading the shared index]"
342 );
343 let idx = BM25Index::load(root_pb).unwrap_or_default();
344 return (idx.doc_count, None);
345 }
346 let idx = BM25Index::load_or_build(root_pb);
347 let outcome = idx.save(root_pb);
348 (idx.doc_count, Some(outcome))
349 }));
350 if let Ok((doc_count, save_res)) = bm {
351 let mut s = bm25_state
352 .lock()
353 .unwrap_or_else(std::sync::PoisonError::into_inner);
354 finish_ok(&mut s.bm25);
355 s.bm25.note = Some(match save_res {
356 Some(outcome) => bm25_build_note(doc_count, &outcome),
357 None => format!(
358 "loaded shared BM25 index ({doc_count} chunks) — build in progress in another process"
359 ),
360 });
361 } else {
362 let mut s = bm25_state
363 .lock()
364 .unwrap_or_else(std::sync::PoisonError::into_inner);
365 finish_err(&mut s.bm25, "bm25 build panicked".to_string());
366 }
367 })
368 .expect("spawning BM25 index thread");
369
370 if let Err(e) = graph_handle.join() {
371 tracing::error!("[index_orchestrator: graph thread panicked: {e:?}]");
372 }
373 if let Err(e) = bm25_handle.join() {
374 tracing::error!("[index_orchestrator: BM25 thread panicked: {e:?}]");
375 }
376
377 let final_state = entry_for(&root);
378 let mut s = final_state
379 .lock()
380 .unwrap_or_else(std::sync::PoisonError::into_inner);
381 s.worker_running = false;
382 };
383
384 let spawned = std::thread::Builder::new()
388 .name("leanctx-index".to_string())
389 .stack_size(INDEXER_STACK_BYTES)
390 .spawn(indexer);
391 if spawned.is_err() {
392 let mut s = state
395 .lock()
396 .unwrap_or_else(std::sync::PoisonError::into_inner);
397 s.worker_running = false;
398 }
399}
400
401pub fn build_semantic(project_root: &str) {
406 let state = entry_for(project_root);
407 let root = Path::new(project_root);
408
409 {
410 let mut s = state
411 .lock()
412 .unwrap_or_else(std::sync::PoisonError::into_inner);
413 start_component(&mut s.semantic);
414 }
415
416 let bm25_idx = try_load_bm25_index(project_root);
417 match bm25_idx.as_ref() {
418 Some(idx) if idx.doc_count > 0 => {
419 let outcome = crate::core::embedding_index::build_or_update(root, idx);
420 let mut s = state
421 .lock()
422 .unwrap_or_else(std::sync::PoisonError::into_inner);
423 match outcome {
424 crate::core::embedding_index::EmbeddingBuildOutcome::Ready => {
425 finish_ok(&mut s.semantic);
426 }
427 crate::core::embedding_index::EmbeddingBuildOutcome::Skipped => {
428 finish_ok(&mut s.semantic);
429 s.semantic.note = Some(
430 "embeddings disabled by feature flag or config (search.dense_enabled / memory_profile)"
431 .to_string(),
432 );
433 }
434 crate::core::embedding_index::EmbeddingBuildOutcome::ModelNotAvailable(
435 ref reason,
436 ) => {
437 s.semantic.state = State::Idle;
438 s.semantic.note = Some(format!("embedding model not available: {reason}"));
439 }
440 crate::core::embedding_index::EmbeddingBuildOutcome::Failed => {
441 finish_err(
442 &mut s.semantic,
443 "embedding build failed (see logs)".to_string(),
444 );
445 }
446 }
447 }
448 _ => {
449 let mut s = state
450 .lock()
451 .unwrap_or_else(std::sync::PoisonError::into_inner);
452 s.semantic.state = State::Idle;
453 s.semantic.note =
454 Some("BM25 index is empty or unavailable — nothing to embed".to_string());
455 }
456 }
457}
458
459const MAX_EXTRA_ROOT_BUILDS: usize = 8;
463
464pub fn ensure_extra_roots_background(primary_root: &str, extra_roots: &[String]) {
465 let primary = Path::new(primary_root);
466 let mut built = 0;
467 for root in extra_roots {
468 if built >= MAX_EXTRA_ROOT_BUILDS {
469 break;
470 }
471 let rp = Path::new(root);
472 if !rp.is_dir() {
473 continue;
474 }
475 if rp.starts_with(primary) {
477 continue;
478 }
479 if primary.starts_with(rp) {
481 continue;
482 }
483 ensure_all_background(root);
484 built += 1;
485 }
486}
487
488fn bm25_build_note(
493 doc_count: usize,
494 save: &std::io::Result<crate::core::bm25_index::SaveOutcome>,
495) -> String {
496 use crate::core::bm25_index::SaveOutcome;
497 match save {
498 Ok(SaveOutcome::Persisted { compressed_bytes }) => format!(
499 "indexed {doc_count} chunks, {:.1} MB persisted",
500 *compressed_bytes as f64 / 1_048_576.0
501 ),
502 Ok(SaveOutcome::SkippedTooLarge {
503 compressed_bytes,
504 limit_bytes,
505 }) => format!(
506 "indexed {doc_count} chunks but NOT persisted to disk: compressed {:.1} MB exceeds the {:.0} MB cap. \
507 Raise it via LEAN_CTX_BM25_MAX_CACHE_MB (or bm25_max_cache_mb in config) or add extra_ignore_patterns, \
508 then run `lean-ctx reindex`. Until then the index is rebuilt from scratch on every cold start.",
509 *compressed_bytes as f64 / 1_048_576.0,
510 *limit_bytes as f64 / 1_048_576.0
511 ),
512 Err(e) => format!("indexed {doc_count} chunks but persisting failed: {e}"),
513 }
514}
515
516#[derive(Debug, Clone)]
519pub struct Bm25Summary {
520 pub state: &'static str,
521 pub elapsed_ms: Option<u64>,
523 pub note: Option<String>,
524 pub last_error: Option<String>,
525}
526
527#[derive(Debug, Clone)]
529pub struct SemanticSummary {
530 pub state: &'static str,
531 pub elapsed_ms: Option<u64>,
532 pub note: Option<String>,
533 pub last_error: Option<String>,
534}
535
536fn component_elapsed_and_state(c: &Component) -> (&'static str, Option<u64>) {
540 let elapsed_ms = if matches!(c.state, State::Building) {
541 c.started_ms.map(|start| now_ms().saturating_sub(start))
542 } else {
543 c.duration_ms
544 };
545 let state = match c.state {
546 State::Idle => "idle",
547 State::Building => "building",
548 State::Ready => "ready",
549 State::Failed => "failed",
550 };
551 (state, elapsed_ms)
552}
553
554pub fn semantic_summary(project_root: &str) -> SemanticSummary {
555 let entry = entry_for(project_root);
556 let s = entry
557 .lock()
558 .unwrap_or_else(std::sync::PoisonError::into_inner);
559 let c = &s.semantic;
560 let (state, elapsed_ms) = component_elapsed_and_state(c);
561 SemanticSummary {
562 state,
563 elapsed_ms,
564 note: c.note.clone(),
565 last_error: c.last_error.clone(),
566 }
567}
568
569pub fn bm25_summary(project_root: &str) -> Bm25Summary {
570 let entry = entry_for(project_root);
571 let s = entry
572 .lock()
573 .unwrap_or_else(std::sync::PoisonError::into_inner);
574 let c = &s.bm25;
575 let (state, elapsed_ms) = component_elapsed_and_state(c);
576 Bm25Summary {
577 state,
578 elapsed_ms,
579 note: c.note.clone(),
580 last_error: c.last_error.clone(),
581 }
582}
583
584pub fn try_load_graph_index(project_root: &str) -> Option<ProjectIndex> {
585 crate::core::graph_cache::get_cached(project_root).map(|arc| (*arc).clone())
588}
589
590pub fn try_load_bm25_index(project_root: &str) -> Option<BM25Index> {
591 BM25Index::load(Path::new(project_root))
592}
593
594pub fn is_building() -> bool {
596 let map = registry()
597 .lock()
598 .unwrap_or_else(std::sync::PoisonError::into_inner);
599 map.values().any(|entry| {
600 let st = entry
601 .lock()
602 .unwrap_or_else(std::sync::PoisonError::into_inner);
603 matches!(st.bm25.state, State::Building)
604 || matches!(st.graph.state, State::Building)
605 || matches!(st.semantic.state, State::Building)
606 })
607}
608
609#[derive(Debug, Serialize)]
610struct ComponentStatus<'a> {
611 state: &'a str,
612 started_ms: Option<u64>,
613 finished_ms: Option<u64>,
614 duration_ms: Option<u64>,
615 last_error: Option<&'a str>,
616 #[serde(skip_serializing_if = "Option::is_none")]
617 note: Option<&'a str>,
618}
619
620fn component_status(c: &Component) -> ComponentStatus<'_> {
621 ComponentStatus {
622 state: match c.state {
623 State::Idle => "idle",
624 State::Building => "building",
625 State::Ready => "ready",
626 State::Failed => "failed",
627 },
628 started_ms: c.started_ms,
629 finished_ms: c.finished_ms,
630 duration_ms: c.duration_ms,
631 last_error: c.last_error.as_deref(),
632 note: c.note.as_deref(),
633 }
634}
635
636#[derive(Debug, Serialize)]
637struct StatusResponse<'a> {
638 project_root: &'a str,
639 graph_index: ComponentStatus<'a>,
640 bm25_index: ComponentStatus<'a>,
641 semantic_index: ComponentStatus<'a>,
645 disk: DiskStatusAll,
646}
647
648#[derive(Debug, Serialize, Default)]
649pub struct DiskStatus {
650 pub exists: bool,
651 pub size_bytes: Option<u64>,
652 pub file_count: Option<u64>,
653 pub modified_at: Option<String>,
654}
655
656#[derive(Debug, Serialize, Default)]
657pub struct DiskStatusAll {
658 pub graph_index: DiskStatus,
659 pub bm25_index: DiskStatus,
660 pub code_graph: DiskStatus,
661 pub semantic_index: DiskStatus,
665}
666
667fn disk_status_for_graph(project_root: &str) -> DiskStatus {
668 let Some(dir) = graph_index::ProjectIndex::index_dir(project_root) else {
673 return DiskStatus::default();
674 };
675 let meta_file = dir.join("graph.meta.json");
676 if !meta_file.exists() {
677 return DiskStatus::default();
678 }
679 let meta = std::fs::metadata(&meta_file).ok();
680 let file_count =
681 graph_index::ProjectIndex::load(project_root).map(|idx| idx.files.len() as u64);
682 DiskStatus {
683 exists: true,
684 size_bytes: meta.as_ref().map(std::fs::Metadata::len),
685 file_count,
686 modified_at: meta.and_then(|m| m.modified().ok()).map(format_time),
687 }
688}
689
690fn disk_status_for_bm25(project_root: &str) -> DiskStatus {
691 let root = Path::new(project_root);
692 let path = BM25Index::index_file_path(root);
693 if !path.exists() {
694 return DiskStatus::default();
695 }
696 let meta = std::fs::metadata(&path).ok();
697 DiskStatus {
698 exists: true,
699 size_bytes: meta.as_ref().map(std::fs::Metadata::len),
700 file_count: None,
701 modified_at: meta.and_then(|m| m.modified().ok()).map(format_time),
702 }
703}
704
705fn disk_status_for_code_graph(project_root: &str) -> DiskStatus {
706 let dir = crate::core::property_graph::graph_dir(project_root);
707 let db_path = dir.join("graph.db");
708 if !db_path.exists() {
709 return DiskStatus::default();
710 }
711 let meta = std::fs::metadata(&db_path).ok();
712 let node_count = crate::core::property_graph::CodeGraph::open(project_root)
713 .ok()
714 .and_then(|g| {
715 g.connection()
716 .query_row("SELECT count(*) FROM nodes", [], |r| r.get::<_, i64>(0))
717 .ok()
718 .map(|c| c as u64)
719 });
720 DiskStatus {
721 exists: true,
722 size_bytes: meta.as_ref().map(std::fs::Metadata::len),
723 file_count: node_count,
724 modified_at: meta.and_then(|m| m.modified().ok()).map(format_time),
725 }
726}
727
728fn format_time(t: SystemTime) -> String {
729 let secs = t.duration_since(UNIX_EPOCH).unwrap_or_default().as_secs();
730 let dt = chrono::DateTime::from_timestamp(secs as i64, 0);
731 dt.map_or_else(
732 || format!("{secs}"),
733 |d| d.format("%Y-%m-%d %H:%M:%S UTC").to_string(),
734 )
735}
736
737pub fn disk_status_for_semantic(project_root: &str) -> DiskStatus {
738 let root = Path::new(project_root);
739 let dir = crate::core::index_namespace::vectors_dir(root);
740 let bin_path = dir.join("embeddings.bin");
741 if !bin_path.exists() {
742 return DiskStatus::default();
743 }
744 let meta = std::fs::metadata(&bin_path).ok();
745 DiskStatus {
746 exists: true,
747 size_bytes: meta.as_ref().map(std::fs::Metadata::len),
748 file_count: None,
749 modified_at: meta.and_then(|m| m.modified().ok()).map(format_time),
750 }
751}
752
753pub fn disk_status(project_root: &str) -> DiskStatusAll {
754 DiskStatusAll {
755 graph_index: disk_status_for_graph(project_root),
756 bm25_index: disk_status_for_bm25(project_root),
757 code_graph: disk_status_for_code_graph(project_root),
758 semantic_index: disk_status_for_semantic(project_root),
759 }
760}
761
762pub fn status_json(project_root: &str) -> String {
763 let disk = disk_status(project_root);
767 let state = entry_for(project_root);
768 let s = state
769 .lock()
770 .unwrap_or_else(std::sync::PoisonError::into_inner);
771 let res = StatusResponse {
772 project_root,
773 graph_index: component_status(&s.graph),
774 bm25_index: component_status(&s.bm25),
775 semantic_index: component_status(&s.semantic),
776 disk,
777 };
778 serde_json::to_string(&res).unwrap_or_else(|_| "{}".to_string())
779}
780
781#[cfg(test)]
782mod tests {
783 use super::*;
784
785 #[test]
786 fn status_json_is_valid_json() {
787 let s = status_json("/tmp");
788 let _: serde_json::Value = serde_json::from_str(&s).unwrap();
789 }
790
791 #[test]
792 fn warm_need_classifies_tools() {
793 for light in [
795 "ctx_read",
796 "ctx_shell",
797 "ctx_tree",
798 "ctx_knowledge",
799 "unknown_tool",
800 ] {
801 assert_eq!(warm_need_for_tool(light), WarmNeed::None, "{light}");
802 }
803 assert_eq!(warm_need_for_tool("ctx_search"), WarmNeed::Search);
805 for heavy in [
806 "ctx_graph",
807 "ctx_callgraph",
808 "ctx_routes",
809 "ctx_repomap",
810 "ctx_impact",
811 "ctx_artifacts",
812 "ctx_semantic_search",
813 "ctx_provider",
814 "ctx_compose",
815 "ctx_explore",
816 "ctx_review",
817 ] {
818 assert_eq!(warm_need_for_tool(heavy), WarmNeed::Heavy, "{heavy}");
819 }
820 }
821
822 #[test]
823 fn ensure_warm_lightweight_and_search_never_signal_first_warm() {
824 assert!(!ensure_warm_for_tool("", "ctx_graph"));
825 let tmp = tempfile::tempdir().unwrap();
826 let root = tmp.path().to_string_lossy().to_string();
827 assert!(!ensure_warm_for_tool(&root, "ctx_read"));
828 assert!(!ensure_warm_for_tool(&root, "ctx_search"));
829 }
830
831 #[test]
832 fn ensure_warm_heavy_is_once_per_root() {
833 let tmp = tempfile::tempdir().unwrap();
837 let root = tmp.path().to_string_lossy().to_string();
838 assert!(
839 ensure_warm_for_tool(&root, "ctx_callgraph"),
840 "first heavy warm must signal true"
841 );
842 assert!(
843 !ensure_warm_for_tool(&root, "ctx_callgraph"),
844 "second heavy warm must be deduped to false"
845 );
846 assert!(
847 !ensure_warm_for_tool(&root, "ctx_semantic_search"),
848 "any later heavy tool on the same root is also deduped"
849 );
850 }
851
852 #[test]
853 fn build_note_persisted_reports_size() {
854 let note = bm25_build_note(
855 42,
856 &Ok(crate::core::bm25_index::SaveOutcome::Persisted {
857 compressed_bytes: 3 * 1024 * 1024,
858 }),
859 );
860 assert!(
861 note.contains("42 chunks"),
862 "note should report chunk count: {note}"
863 );
864 assert!(
865 note.contains("persisted"),
866 "note should report persistence: {note}"
867 );
868 }
869
870 #[test]
871 fn build_note_too_large_carries_remedy() {
872 let note = bm25_build_note(
873 1000,
874 &Ok(crate::core::bm25_index::SaveOutcome::SkippedTooLarge {
875 compressed_bytes: 600 * 1024 * 1024,
876 limit_bytes: 512 * 1024 * 1024,
877 }),
878 );
879 assert!(
880 note.contains("NOT persisted"),
881 "must flag non-persistence: {note}"
882 );
883 assert!(
884 note.contains("LEAN_CTX_BM25_MAX_CACHE_MB") && note.contains("reindex"),
885 "too-large note must carry an actionable remedy: {note}"
886 );
887 }
888
889 #[test]
890 fn build_note_persist_error_is_reported() {
891 let note = bm25_build_note(7, &Err(std::io::Error::other("disk full")));
892 assert!(note.contains("persisting failed"), "note: {note}");
893 assert!(
894 note.contains("disk full"),
895 "note should include the io error: {note}"
896 );
897 }
898
899 #[test]
900 fn bm25_summary_unknown_project_is_idle() {
901 let tmp = tempfile::tempdir().unwrap();
902 let summary = bm25_summary(tmp.path().to_string_lossy().as_ref());
903 assert_eq!(summary.state, "idle");
904 assert!(summary.note.is_none());
905 assert!(summary.last_error.is_none());
906 }
907
908 #[test]
909 fn extra_roots_skips_subdirs_of_primary() {
910 let tmp = tempfile::tempdir().unwrap();
911 let primary = tmp.path().join("primary");
912 std::fs::create_dir_all(&primary).unwrap();
913 let sub = primary.join("subdir");
914 std::fs::create_dir_all(&sub).unwrap();
915 let external = tmp.path().join("external");
916 std::fs::create_dir_all(&external).unwrap();
917
918 let primary_str = primary.to_string_lossy().to_string();
919 let extra = vec![
920 sub.to_string_lossy().to_string(),
921 external.to_string_lossy().to_string(),
922 ];
923
924 ensure_extra_roots_background(&primary_str, &extra);
926 }
927
928 #[test]
929 fn extra_roots_caps_at_max() {
930 let tmp = tempfile::tempdir().unwrap();
931 let primary = tmp.path().join("primary");
932 std::fs::create_dir_all(&primary).unwrap();
933
934 let mut extra = Vec::new();
935 for i in 0..20 {
936 let d = tmp.path().join(format!("ext-{i}"));
937 std::fs::create_dir_all(&d).unwrap();
938 extra.push(d.to_string_lossy().to_string());
939 }
940
941 let primary_str = primary.to_string_lossy().to_string();
942 ensure_extra_roots_background(&primary_str, &extra);
944 }
945
946 #[test]
947 fn bm25_index_lock_name_is_per_repo_and_distinct_from_graph() {
948 let a = bm25_index_lock_name(Path::new("/tmp/repo-a"));
949 let b = bm25_index_lock_name(Path::new("/tmp/repo-b"));
950 assert!(a.starts_with("bm25-idx-"), "unexpected lock name: {a}");
951 assert_ne!(a, b, "lock name must be per-repo");
952 assert_eq!(a, bm25_index_lock_name(Path::new("/tmp/repo-a")));
954 let graph = format!(
957 "graph-idx-{}",
958 &crate::core::index_namespace::namespace_hash(Path::new("/tmp/repo-a"))[..8]
959 );
960 assert_ne!(a, graph, "bm25 and graph locks must be independent");
961 }
962}