Skip to main content

lean_ctx/core/
index_orchestrator.rs

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    /// Human-readable outcome detail surfaced to operators (e.g. doc count +
27    /// persisted size, or the "not persisted: too large …" remedy). Independent
28    /// of `last_error` so a *successful* build can still carry a warning note.
29    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    /// Set the first time a heavy-index tool lazily pre-warms this root (#152).
49    /// Prevents re-triggering a full rebuild on every subsequent dispatch — the
50    /// tools' own `load_or_build` paths handle staleness from then on.
51    warm_triggered: bool,
52    graph: Component,
53    bm25: Component,
54    /// Dense embedding index (semantic search). Built after BM25 as Phase 3.
55    /// Tracked separately so the orchestrator does not block on a missing ONNX
56    /// model — the status lets users see why semantic stays cold (#249).
57    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
72// Lock ordering (see rust/LOCK_ORDERING.md):
73//   L1 = REGISTRY outer Mutex  (the HashMap guard)
74//   L2 = per-project Arc<Mutex<ProjectBuild>>  (inner guard)
75//
76// Invariant: L1 must NEVER be held while locking L2.
77// `entry_for()` enforces this by cloning the Arc and dropping L1 before
78// the caller acquires L2.
79static 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
101/// Per-repo lock name for serializing the BM25 build across processes, mirroring
102/// the `graph-idx-<hash>` lock (see LOCK_ORDERING.md). The distinct `bm25-` vs
103/// `graph-` prefix keeps the graph and BM25 builds from serializing against each
104/// other while still preventing N processes from rebuilding either in parallel.
105fn 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/// The index warmth a tool benefits from. Drives lazy, demand-driven warming
137/// (issue #152) so the server no longer scans the whole project eagerly on every
138/// `initialize` — a session that only uses `ctx_read`/`ctx_shell`/`ctx_tree`
139/// pays zero indexing cost.
140#[derive(Debug, Clone, Copy, PartialEq, Eq)]
141pub enum WarmNeed {
142    /// No prebuilt index needed.
143    None,
144    /// Only the resident line-search (trigram) index — cheap, used by `ctx_search`.
145    Search,
146    /// Full project indices (graph + BM25; this also warms the search index).
147    Heavy,
148}
149
150/// Classify a tool by the index warmth it benefits from. Unknown tools default
151/// to [`WarmNeed::None`]; a heavy tool mis-classified as `None` still works — it
152/// just builds its index synchronously on first use instead of being pre-warmed.
153#[must_use]
154pub fn warm_need_for_tool(tool: &str) -> WarmNeed {
155    match tool {
156        "ctx_search" => WarmNeed::Search,
157        // Tools that build/consume the graph, call-graph, BM25 or artifact index.
158        "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
173/// Lazily warm the indices a tool needs, deduped per root. Never blocks (all
174/// work is spawned in the background) and is safe to call on every dispatch.
175///
176/// Returns `true` only when this call is the *first* heavy pre-warm for `root`
177/// in this process — the caller can use that signal to warm secondary roots once
178/// without re-reading session state on every dispatch.
179pub 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            // The search index has its own TTL + background-rebuild dedup, so it
187            // is safe (and cheap) to nudge on every `ctx_search`.
188            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
212/// Stack size for background index workers. Large enough that deep ASTs and
213/// graph traversals cannot overflow it (the #378 SIGABRT class). The AST walks
214/// are iterative now too, so this is defense-in-depth.
215const INDEXER_STACK_BYTES: usize = 16 * 1024 * 1024;
216
217/// Fire-and-forget: ask a running daemon to own the index build for `root`
218/// (#460, shared-indexer-daemon / thin clients).
219///
220/// The daemon is the single long-lived, machine-wide indexer. Once it holds the
221/// per-repo `graph-idx`/`bm25-idx` build locks, every session load-shares its
222/// on-disk result instead of each running a full scan during a cold boot wave —
223/// turning N simultaneous index passes into ~one. Strictly additive and
224/// best-effort: it runs on its own thread (no ambient runtime to nest into), is
225/// skipped when we *are* the daemon or when no daemon is reachable, and never
226/// blocks the caller. The local build started right after remains the fallback,
227/// so indexing always works with no daemon present.
228fn nudge_daemon_index(project_root: &str) {
229    // The daemon must never delegate the build to itself.
230    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
251/// Try to claim the per-root build slot. Returns `false` when a worker is
252/// already running for `project_root` (the claim is released by the build
253/// worker itself when it finishes).
254fn 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    // #460: hand the build to the daemon (the single machine-wide indexer) when
273    // one is running and we aren't it. Deduped naturally — we only reach here
274    // when this process is actually about to start a build. Purely additive: the
275    // local build below still runs and load-shares via the per-repo locks.
276    //
277    // #735 exception: with a per-run CLI filter overlay active, the daemon
278    // (which builds with *its* config, not the overlay) could overwrite the
279    // filtered result — the one-off run keeps the build local instead.
280    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    // Indexing parses large ASTs and traverses graphs; give the worker a
289    // generous stack as defense-in-depth against deep-recursion overflow (the
290    // #378 SIGABRT class) and a name so it is identifiable in crash dumps.
291    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        // The OS refused a new thread (rare). Clear the in-flight flag so a
297        // later trigger retries instead of assuming a build runs forever.
298        let mut s = state
299            .lock()
300            .unwrap_or_else(std::sync::PoisonError::into_inner);
301        s.worker_running = false;
302    }
303}
304
305/// The actual per-root build work: search-index pre-warm, then graph + BM25 in
306/// parallel (two threads for *one* root), joined before returning. Blocking —
307/// callers own the threading. Requires the caller to have claimed the worker
308/// slot via [`try_claim_worker`]; releases it on exit.
309fn run_build_worker(root: &str) {
310    // Pre-warm the resident line-search index in parallel (own thread,
311    // deduped internally) so the first ctx_search hits the fast path.
312    crate::core::search_index::ensure_background(root, true, false);
313
314    // ---- Parallel Phase: Graph + BM25 (for this one root) ----
315    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                // #696 C4: the property graph is the sole store. `save()` mirrors
330                // the freshly scanned index into PG (stamping `graph.meta.json`) in
331                // this same reliable worker, so PG inherits the scan's build reliability.
332                if let Err(e) = idx.save() {
333                    tracing::warn!("[index_orchestrator: graph save failed: {e}]");
334                }
335                // Code Health: refresh the persisted NavigabilityScore from the
336                // same freshly-indexed state (gated by a source fingerprint, so a
337                // no-op when nothing changed). Off the hot path; never panics.
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        .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                // Cross-instance build coordination: serialize the (expensive) BM25
369                // build per repo, mirroring the `graph-idx` lock in graph_index.
370                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    let final_state = entry_for(root);
415    let mut s = final_state
416        .lock()
417        .unwrap_or_else(std::sync::PoisonError::into_inner);
418    s.worker_running = false;
419}
420
421/// Build only the semantic (dense embedding) index from the existing BM25 index.
422/// The BM25 index must already exist on disk — this function loads it and runs
423/// `embedding_index::build_or_update`. Updates the in-memory semantic component
424/// state on completion.
425pub fn build_semantic(project_root: &str) {
426    let state = entry_for(project_root);
427    let root = Path::new(project_root);
428
429    {
430        let mut s = state
431            .lock()
432            .unwrap_or_else(std::sync::PoisonError::into_inner);
433        start_component(&mut s.semantic);
434    }
435
436    let bm25_idx = try_load_bm25_index(project_root);
437    match bm25_idx.as_ref() {
438        Some(idx) if idx.doc_count > 0 => {
439            let outcome = crate::core::embedding_index::build_or_update(root, idx);
440            let mut s = state
441                .lock()
442                .unwrap_or_else(std::sync::PoisonError::into_inner);
443            match outcome {
444                crate::core::embedding_index::EmbeddingBuildOutcome::Ready => {
445                    finish_ok(&mut s.semantic);
446                }
447                crate::core::embedding_index::EmbeddingBuildOutcome::Skipped => {
448                    finish_ok(&mut s.semantic);
449                    s.semantic.note = Some(
450                        "embeddings disabled by feature flag or config (search.dense_enabled / memory_profile)"
451                            .to_string(),
452                    );
453                }
454                crate::core::embedding_index::EmbeddingBuildOutcome::ModelNotAvailable(
455                    ref reason,
456                ) => {
457                    s.semantic.state = State::Idle;
458                    s.semantic.note = Some(format!("embedding model not available: {reason}"));
459                }
460                crate::core::embedding_index::EmbeddingBuildOutcome::Failed => {
461                    finish_err(
462                        &mut s.semantic,
463                        "embedding build failed (see logs)".to_string(),
464                    );
465                }
466            }
467        }
468        _ => {
469            let mut s = state
470                .lock()
471                .unwrap_or_else(std::sync::PoisonError::into_inner);
472            s.semantic.state = State::Idle;
473            s.semantic.note =
474                Some("BM25 index is empty or unavailable — nothing to embed".to_string());
475        }
476    }
477}
478
479/// Ensure background indexing for all extra roots (in addition to the primary).
480/// Each extra root that is not a subdirectory of `primary_root` gets its own
481/// graph + BM25 index. Capped at `MAX_EXTRA_ROOT_BUILDS` to prevent runaway.
482const MAX_EXTRA_ROOT_BUILDS: usize = 8;
483
484pub fn ensure_extra_roots_background(primary_root: &str, extra_roots: &[String]) {
485    let primary = Path::new(primary_root);
486    let mut queue: Vec<String> = Vec::new();
487    for root in extra_roots {
488        if queue.len() >= MAX_EXTRA_ROOT_BUILDS {
489            break;
490        }
491        let rp = Path::new(root);
492        if !rp.is_dir() {
493            continue;
494        }
495        // Skip if extra_root is inside primary (already indexed by the primary scan)
496        if rp.starts_with(primary) {
497            continue;
498        }
499        // Skip if primary is inside this extra_root (avoid double-indexing the parent)
500        if primary.starts_with(rp) {
501            continue;
502        }
503        queue.push(root.clone());
504    }
505    if queue.is_empty() {
506        return;
507    }
508
509    // #685: build extra roots *sequentially* on one supervisor thread. The old
510    // per-root `ensure_all_background` fan-out ran up to MAX_EXTRA_ROOT_BUILDS
511    // graph+BM25 pairs concurrently (each with rayon pools inside) — on the
512    // reported multi-root setup (1M+ files across 6+ roots) the combined
513    // transient build state outran the guardian to 75 GB RSS. One root at a
514    // time keeps peak memory bounded to a single build while still warming
515    // every root; the guardian check between roots stops the queue as soon as
516    // pressure appears.
517    let spawned = std::thread::Builder::new()
518        .name("leanctx-extra-roots".to_string())
519        .stack_size(INDEXER_STACK_BYTES)
520        .spawn(move || {
521            for root in queue {
522                if crate::core::memory_guard::is_under_pressure()
523                    || crate::core::memory_guard::abort_requested()
524                {
525                    tracing::warn!(
526                        "[index_orchestrator: skipping remaining extra-root builds under memory pressure]"
527                    );
528                    break;
529                }
530                if !try_claim_worker(&root) {
531                    continue; // already building elsewhere
532                }
533                nudge_daemon_index(&root);
534                run_build_worker(&root);
535            }
536        });
537    if let Err(e) = spawned {
538        tracing::warn!("[index_orchestrator: could not spawn extra-roots worker: {e}]");
539    }
540}
541
542/// Build a human-readable outcome note for a finished BM25 build, including the
543/// indexed chunk count and whether the index was persisted to disk. A
544/// "too large" refusal carries the exact remedy so the operator (or agent) is
545/// never left guessing why search/ranking stays cold (issue #249).
546fn bm25_build_note(
547    doc_count: usize,
548    save: &std::io::Result<crate::core::bm25_index::SaveOutcome>,
549) -> String {
550    use crate::core::bm25_index::SaveOutcome;
551    match save {
552        Ok(SaveOutcome::Persisted { compressed_bytes }) => format!(
553            "indexed {doc_count} chunks, {:.1} MB persisted",
554            *compressed_bytes as f64 / 1_048_576.0
555        ),
556        Ok(SaveOutcome::SkippedTooLarge {
557            compressed_bytes,
558            limit_bytes,
559        }) => format!(
560            "indexed {doc_count} chunks but NOT persisted to disk: compressed {:.1} MB exceeds the {:.0} MB cap. \
561             Raise it via LEAN_CTX_BM25_MAX_CACHE_MB (or bm25_max_cache_mb in config) or add extra_ignore_patterns, \
562             then run `lean-ctx reindex`. Until then the index is rebuilt from scratch on every cold start.",
563            *compressed_bytes as f64 / 1_048_576.0,
564            *limit_bytes as f64 / 1_048_576.0
565        ),
566        Err(e) => format!("indexed {doc_count} chunks but persisting failed: {e}"),
567    }
568}
569
570/// Lightweight, allocation-frugal snapshot of the BM25 component for the
571/// in-call composer/search messaging. Avoids the heavier [`disk_status`] walk.
572#[derive(Debug, Clone)]
573pub struct Bm25Summary {
574    pub state: &'static str,
575    /// While building: elapsed so far. Otherwise: last build duration.
576    pub elapsed_ms: Option<u64>,
577    pub note: Option<String>,
578    pub last_error: Option<String>,
579}
580
581/// Lightweight snapshot of the semantic (dense embedding) component.
582#[derive(Debug, Clone)]
583pub struct SemanticSummary {
584    pub state: &'static str,
585    pub elapsed_ms: Option<u64>,
586    pub note: Option<String>,
587    pub last_error: Option<String>,
588}
589
590/// Shared helper: compute (state_str, elapsed_ms) for a component.
591/// Deduplicates the elapsed-while-building logic and state-to-string mapping
592/// between bm25_summary and semantic_summary.
593fn component_elapsed_and_state(c: &Component) -> (&'static str, Option<u64>) {
594    let elapsed_ms = if matches!(c.state, State::Building) {
595        c.started_ms.map(|start| now_ms().saturating_sub(start))
596    } else {
597        c.duration_ms
598    };
599    let state = match c.state {
600        State::Idle => "idle",
601        State::Building => "building",
602        State::Ready => "ready",
603        State::Failed => "failed",
604    };
605    (state, elapsed_ms)
606}
607
608pub fn semantic_summary(project_root: &str) -> SemanticSummary {
609    let entry = entry_for(project_root);
610    let s = entry
611        .lock()
612        .unwrap_or_else(std::sync::PoisonError::into_inner);
613    let c = &s.semantic;
614    let (state, elapsed_ms) = component_elapsed_and_state(c);
615    SemanticSummary {
616        state,
617        elapsed_ms,
618        note: c.note.clone(),
619        last_error: c.last_error.clone(),
620    }
621}
622
623pub fn bm25_summary(project_root: &str) -> Bm25Summary {
624    let entry = entry_for(project_root);
625    let s = entry
626        .lock()
627        .unwrap_or_else(std::sync::PoisonError::into_inner);
628    let c = &s.bm25;
629    let (state, elapsed_ms) = component_elapsed_and_state(c);
630    Bm25Summary {
631        state,
632        elapsed_ms,
633        note: c.note.clone(),
634        last_error: c.last_error.clone(),
635    }
636}
637
638pub fn try_load_graph_index(project_root: &str) -> Option<ProjectIndex> {
639    // Resident cache: avoids re-materializing the index from the property graph
640    // (SQLite query) on every graph-touching query. Returns an in-memory clone.
641    crate::core::graph_cache::get_cached(project_root).map(|arc| (*arc).clone())
642}
643
644pub fn try_load_bm25_index(project_root: &str) -> Option<BM25Index> {
645    BM25Index::load(Path::new(project_root))
646}
647
648/// Returns true if any project is currently building its indices.
649pub fn is_building() -> bool {
650    let map = registry()
651        .lock()
652        .unwrap_or_else(std::sync::PoisonError::into_inner);
653    map.values().any(|entry| {
654        let st = entry
655            .lock()
656            .unwrap_or_else(std::sync::PoisonError::into_inner);
657        matches!(st.bm25.state, State::Building)
658            || matches!(st.graph.state, State::Building)
659            || matches!(st.semantic.state, State::Building)
660    })
661}
662
663#[derive(Debug, Serialize)]
664struct ComponentStatus<'a> {
665    state: &'a str,
666    started_ms: Option<u64>,
667    finished_ms: Option<u64>,
668    duration_ms: Option<u64>,
669    last_error: Option<&'a str>,
670    #[serde(skip_serializing_if = "Option::is_none")]
671    note: Option<&'a str>,
672}
673
674fn component_status(c: &Component) -> ComponentStatus<'_> {
675    ComponentStatus {
676        state: match c.state {
677            State::Idle => "idle",
678            State::Building => "building",
679            State::Ready => "ready",
680            State::Failed => "failed",
681        },
682        started_ms: c.started_ms,
683        finished_ms: c.finished_ms,
684        duration_ms: c.duration_ms,
685        last_error: c.last_error.as_deref(),
686        note: c.note.as_deref(),
687    }
688}
689
690#[derive(Debug, Serialize)]
691struct StatusResponse<'a> {
692    project_root: &'a str,
693    graph_index: ComponentStatus<'a>,
694    bm25_index: ComponentStatus<'a>,
695    /// Dense embedding index built after BM25.  "idle" means the ONNX model
696    /// has not been downloaded yet or the embeddings feature was not compiled
697    /// in; "ready" means embeddings are persisted and search will use them.
698    semantic_index: ComponentStatus<'a>,
699    disk: DiskStatusAll,
700    /// Active corpus filter summary (#735). Omitted for the unfiltered
701    /// default, keeping default output byte-identical.
702    #[serde(skip_serializing_if = "Option::is_none")]
703    index_filters: Option<String>,
704}
705
706#[derive(Debug, Serialize, Default)]
707pub struct DiskStatus {
708    pub exists: bool,
709    pub size_bytes: Option<u64>,
710    pub file_count: Option<u64>,
711    pub modified_at: Option<String>,
712}
713
714#[derive(Debug, Serialize, Default)]
715pub struct DiskStatusAll {
716    pub graph_index: DiskStatus,
717    pub bm25_index: DiskStatus,
718    pub code_graph: DiskStatus,
719    /// On-disk embedding index (`embeddings.bin`).  Present when dense search
720    /// has been built at least once; absent when the model is not downloaded
721    /// yet or embeddings are disabled by config.
722    pub semantic_index: DiskStatus,
723}
724
725fn disk_status_for_graph(project_root: &str) -> DiskStatus {
726    // #696 C4: the property graph is the sole store. The logical graph-index
727    // view (file count) is sized/timed by `graph.meta.json`, which the mirror
728    // stamps on every build; `disk_status_for_code_graph` reports the raw
729    // SQLite store (nodes, graph.db) as a distinct facet.
730    let Some(dir) = graph_index::ProjectIndex::index_dir(project_root) else {
731        return DiskStatus::default();
732    };
733    let meta_file = dir.join("graph.meta.json");
734    if !meta_file.exists() {
735        return DiskStatus::default();
736    }
737    let meta = std::fs::metadata(&meta_file).ok();
738    let file_count =
739        graph_index::ProjectIndex::load(project_root).map(|idx| idx.files.len() as u64);
740    DiskStatus {
741        exists: true,
742        size_bytes: meta.as_ref().map(std::fs::Metadata::len),
743        file_count,
744        modified_at: meta.and_then(|m| m.modified().ok()).map(format_time),
745    }
746}
747
748fn disk_status_for_bm25(project_root: &str) -> DiskStatus {
749    let root = Path::new(project_root);
750    let path = BM25Index::index_file_path(root);
751    if !path.exists() {
752        return DiskStatus::default();
753    }
754    let meta = std::fs::metadata(&path).ok();
755    DiskStatus {
756        exists: true,
757        size_bytes: meta.as_ref().map(std::fs::Metadata::len),
758        file_count: None,
759        modified_at: meta.and_then(|m| m.modified().ok()).map(format_time),
760    }
761}
762
763fn disk_status_for_code_graph(project_root: &str) -> DiskStatus {
764    let dir = crate::core::property_graph::graph_dir(project_root);
765    let db_path = dir.join("graph.db");
766    if !db_path.exists() {
767        return DiskStatus::default();
768    }
769    let meta = std::fs::metadata(&db_path).ok();
770    let node_count = crate::core::property_graph::CodeGraph::open(project_root)
771        .ok()
772        .and_then(|g| {
773            g.connection()
774                .query_row("SELECT count(*) FROM nodes", [], |r| r.get::<_, i64>(0))
775                .ok()
776                .map(|c| c as u64)
777        });
778    DiskStatus {
779        exists: true,
780        size_bytes: meta.as_ref().map(std::fs::Metadata::len),
781        file_count: node_count,
782        modified_at: meta.and_then(|m| m.modified().ok()).map(format_time),
783    }
784}
785
786fn format_time(t: SystemTime) -> String {
787    let secs = t.duration_since(UNIX_EPOCH).unwrap_or_default().as_secs();
788    let dt = chrono::DateTime::from_timestamp(secs as i64, 0);
789    dt.map_or_else(
790        || format!("{secs}"),
791        |d| d.format("%Y-%m-%d %H:%M:%S UTC").to_string(),
792    )
793}
794
795pub fn disk_status_for_semantic(project_root: &str) -> DiskStatus {
796    let root = Path::new(project_root);
797    let dir = crate::core::index_namespace::vectors_dir(root);
798    let bin_path = dir.join("embeddings.bin");
799    if !bin_path.exists() {
800        return DiskStatus::default();
801    }
802    let meta = std::fs::metadata(&bin_path).ok();
803    DiskStatus {
804        exists: true,
805        size_bytes: meta.as_ref().map(std::fs::Metadata::len),
806        file_count: None,
807        modified_at: meta.and_then(|m| m.modified().ok()).map(format_time),
808    }
809}
810
811pub fn disk_status(project_root: &str) -> DiskStatusAll {
812    DiskStatusAll {
813        graph_index: disk_status_for_graph(project_root),
814        bm25_index: disk_status_for_bm25(project_root),
815        code_graph: disk_status_for_code_graph(project_root),
816        semantic_index: disk_status_for_semantic(project_root),
817    }
818}
819
820pub fn status_json(project_root: &str) -> String {
821    // Compute disk status first — may do SQLite I/O and must NOT hold L2
822    // (per-project Mutex) while doing so, or the background index worker
823    // cannot call finish_ok / set worker_running = false (#deadlock).
824    let disk = disk_status(project_root);
825    let state = entry_for(project_root);
826    let s = state
827        .lock()
828        .unwrap_or_else(std::sync::PoisonError::into_inner);
829    let res = StatusResponse {
830        project_root,
831        graph_index: component_status(&s.graph),
832        bm25_index: component_status(&s.bm25),
833        semantic_index: component_status(&s.semantic),
834        disk,
835        index_filters: crate::core::index_filter::IndexFileFilter::effective().summary(),
836    };
837    serde_json::to_string(&res).unwrap_or_else(|_| "{}".to_string())
838}
839
840#[cfg(test)]
841mod tests {
842    use super::*;
843
844    #[test]
845    fn status_json_is_valid_json() {
846        let s = status_json("/tmp");
847        let _: serde_json::Value = serde_json::from_str(&s).unwrap();
848    }
849
850    #[test]
851    fn warm_need_classifies_tools() {
852        // Lightweight tools must never trigger a project scan (#152).
853        for light in [
854            "ctx_read",
855            "ctx_shell",
856            "ctx_tree",
857            "ctx_knowledge",
858            "unknown_tool",
859        ] {
860            assert_eq!(warm_need_for_tool(light), WarmNeed::None, "{light}");
861        }
862        // ctx_search only needs the cheap trigram index.
863        assert_eq!(warm_need_for_tool("ctx_search"), WarmNeed::Search);
864        for heavy in [
865            "ctx_graph",
866            "ctx_callgraph",
867            "ctx_routes",
868            "ctx_repomap",
869            "ctx_impact",
870            "ctx_artifacts",
871            "ctx_semantic_search",
872            "ctx_provider",
873            "ctx_compose",
874            "ctx_explore",
875            "ctx_review",
876        ] {
877            assert_eq!(warm_need_for_tool(heavy), WarmNeed::Heavy, "{heavy}");
878        }
879    }
880
881    #[test]
882    fn ensure_warm_lightweight_and_search_never_signal_first_warm() {
883        assert!(!ensure_warm_for_tool("", "ctx_graph"));
884        let tmp = tempfile::tempdir().unwrap();
885        let root = tmp.path().to_string_lossy().to_string();
886        assert!(!ensure_warm_for_tool(&root, "ctx_read"));
887        assert!(!ensure_warm_for_tool(&root, "ctx_search"));
888    }
889
890    #[test]
891    fn ensure_warm_heavy_is_once_per_root() {
892        // The first heavy pre-warm signals `true` (so the caller warms extra
893        // roots once); every subsequent call is a no-op `false`, preventing a
894        // rebuild-on-every-dispatch storm.
895        let tmp = tempfile::tempdir().unwrap();
896        let root = tmp.path().to_string_lossy().to_string();
897        assert!(
898            ensure_warm_for_tool(&root, "ctx_callgraph"),
899            "first heavy warm must signal true"
900        );
901        assert!(
902            !ensure_warm_for_tool(&root, "ctx_callgraph"),
903            "second heavy warm must be deduped to false"
904        );
905        assert!(
906            !ensure_warm_for_tool(&root, "ctx_semantic_search"),
907            "any later heavy tool on the same root is also deduped"
908        );
909    }
910
911    #[test]
912    fn build_note_persisted_reports_size() {
913        let note = bm25_build_note(
914            42,
915            &Ok(crate::core::bm25_index::SaveOutcome::Persisted {
916                compressed_bytes: 3 * 1024 * 1024,
917            }),
918        );
919        assert!(
920            note.contains("42 chunks"),
921            "note should report chunk count: {note}"
922        );
923        assert!(
924            note.contains("persisted"),
925            "note should report persistence: {note}"
926        );
927    }
928
929    #[test]
930    fn build_note_too_large_carries_remedy() {
931        let note = bm25_build_note(
932            1000,
933            &Ok(crate::core::bm25_index::SaveOutcome::SkippedTooLarge {
934                compressed_bytes: 600 * 1024 * 1024,
935                limit_bytes: 512 * 1024 * 1024,
936            }),
937        );
938        assert!(
939            note.contains("NOT persisted"),
940            "must flag non-persistence: {note}"
941        );
942        assert!(
943            note.contains("LEAN_CTX_BM25_MAX_CACHE_MB") && note.contains("reindex"),
944            "too-large note must carry an actionable remedy: {note}"
945        );
946    }
947
948    #[test]
949    fn build_note_persist_error_is_reported() {
950        let note = bm25_build_note(7, &Err(std::io::Error::other("disk full")));
951        assert!(note.contains("persisting failed"), "note: {note}");
952        assert!(
953            note.contains("disk full"),
954            "note should include the io error: {note}"
955        );
956    }
957
958    #[test]
959    fn bm25_summary_unknown_project_is_idle() {
960        let tmp = tempfile::tempdir().unwrap();
961        let summary = bm25_summary(tmp.path().to_string_lossy().as_ref());
962        assert_eq!(summary.state, "idle");
963        assert!(summary.note.is_none());
964        assert!(summary.last_error.is_none());
965    }
966
967    #[test]
968    fn extra_roots_skips_subdirs_of_primary() {
969        let tmp = tempfile::tempdir().unwrap();
970        let primary = tmp.path().join("primary");
971        std::fs::create_dir_all(&primary).unwrap();
972        let sub = primary.join("subdir");
973        std::fs::create_dir_all(&sub).unwrap();
974        let external = tmp.path().join("external");
975        std::fs::create_dir_all(&external).unwrap();
976
977        let primary_str = primary.to_string_lossy().to_string();
978        let extra = vec![
979            sub.to_string_lossy().to_string(),
980            external.to_string_lossy().to_string(),
981        ];
982
983        // Should not panic; subdirs are skipped, external is attempted
984        ensure_extra_roots_background(&primary_str, &extra);
985    }
986
987    #[test]
988    fn extra_roots_caps_at_max() {
989        let tmp = tempfile::tempdir().unwrap();
990        let primary = tmp.path().join("primary");
991        std::fs::create_dir_all(&primary).unwrap();
992
993        let mut extra = Vec::new();
994        for i in 0..20 {
995            let d = tmp.path().join(format!("ext-{i}"));
996            std::fs::create_dir_all(&d).unwrap();
997            extra.push(d.to_string_lossy().to_string());
998        }
999
1000        let primary_str = primary.to_string_lossy().to_string();
1001        // Should not spawn more than MAX_EXTRA_ROOT_BUILDS threads
1002        ensure_extra_roots_background(&primary_str, &extra);
1003    }
1004
1005    #[test]
1006    fn bm25_index_lock_name_is_per_repo_and_distinct_from_graph() {
1007        let a = bm25_index_lock_name(Path::new("/tmp/repo-a"));
1008        let b = bm25_index_lock_name(Path::new("/tmp/repo-b"));
1009        assert!(a.starts_with("bm25-idx-"), "unexpected lock name: {a}");
1010        assert_ne!(a, b, "lock name must be per-repo");
1011        // Stable for the same repo across calls.
1012        assert_eq!(a, bm25_index_lock_name(Path::new("/tmp/repo-a")));
1013        // Must NOT collide with the graph lock for the same repo, or the two
1014        // builds would serialize against each other unnecessarily.
1015        let graph = format!(
1016            "graph-idx-{}",
1017            &crate::core::index_namespace::namespace_hash(Path::new("/tmp/repo-a"))[..8]
1018        );
1019        assert_ne!(a, graph, "bm25 and graph locks must be independent");
1020    }
1021}