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    /// Cleared on worker claim; set when the graph phase of this run finishes.
49    /// Used by CLI wait loops so they do not exit during the claim→start gap
50    /// or the graph→BM25 handoff (search pre-warm keeps `worker_running`).
51    graph_run_done: bool,
52    /// Cleared on worker claim; set when the BM25 phase of this run finishes.
53    bm25_run_done: bool,
54    /// Set the first time a heavy-index tool lazily pre-warms this root (#152).
55    /// Prevents re-triggering a full rebuild on every subsequent dispatch — the
56    /// tools' own `load_or_build` paths handle staleness from then on.
57    warm_triggered: bool,
58    graph: Component,
59    bm25: Component,
60    /// Dense embedding index (semantic search). Built after BM25 as Phase 3.
61    /// Tracked separately so the orchestrator does not block on a missing ONNX
62    /// model — the status lets users see why semantic stays cold (#249).
63    semantic: Component,
64}
65
66impl ProjectBuild {
67    fn new() -> Self {
68        Self {
69            worker_running: false,
70            graph_run_done: true,
71            bm25_run_done: true,
72            warm_triggered: false,
73            graph: Component::new(),
74            bm25: Component::new(),
75            semantic: Component::new(),
76        }
77    }
78}
79
80// Lock ordering (see rust/LOCK_ORDERING.md):
81//   L1 = REGISTRY outer Mutex  (the HashMap guard)
82//   L2 = per-project Arc<Mutex<ProjectBuild>>  (inner guard)
83//
84// Invariant: L1 must NEVER be held while locking L2.
85// `entry_for()` enforces this by cloning the Arc and dropping L1 before
86// the caller acquires L2.
87static REGISTRY: OnceLock<Mutex<HashMap<String, Arc<Mutex<ProjectBuild>>>>> = OnceLock::new();
88
89fn registry() -> &'static Mutex<HashMap<String, Arc<Mutex<ProjectBuild>>>> {
90    REGISTRY.get_or_init(|| Mutex::new(HashMap::new()))
91}
92
93fn entry_for(project_root: &str) -> Arc<Mutex<ProjectBuild>> {
94    let mut map = registry()
95        .lock()
96        .unwrap_or_else(std::sync::PoisonError::into_inner);
97    map.entry(project_root.to_string())
98        .or_insert_with(|| Arc::new(Mutex::new(ProjectBuild::new())))
99        .clone()
100}
101
102fn now_ms() -> u64 {
103    SystemTime::now()
104        .duration_since(UNIX_EPOCH)
105        .unwrap_or_default()
106        .as_millis() as u64
107}
108
109/// Per-repo lock name for serializing the BM25 build across processes, mirroring
110/// the `graph-idx-<hash>` lock (see LOCK_ORDERING.md). The distinct `bm25-` vs
111/// `graph-` prefix keeps the graph and BM25 builds from serializing against each
112/// other while still preventing N processes from rebuilding either in parallel.
113fn bm25_index_lock_name(root: &Path) -> String {
114    format!(
115        "bm25-idx-{}",
116        &crate::core::index_namespace::namespace_hash(root)[..8]
117    )
118}
119
120fn start_component(c: &mut Component) {
121    c.state = State::Building;
122    c.started_ms = Some(now_ms());
123    c.finished_ms = None;
124    c.duration_ms = None;
125    c.last_error = None;
126    c.note = None;
127}
128
129fn finish_ok(c: &mut Component) {
130    c.state = State::Ready;
131    let end = now_ms();
132    c.finished_ms = Some(end);
133    c.duration_ms = c.started_ms.map(|s| end.saturating_sub(s));
134}
135
136fn finish_err(c: &mut Component, e: String) {
137    c.state = State::Failed;
138    let end = now_ms();
139    c.finished_ms = Some(end);
140    c.duration_ms = c.started_ms.map(|s| end.saturating_sub(s));
141    c.last_error = Some(e);
142}
143
144/// The index warmth a tool benefits from. Drives lazy, demand-driven warming
145/// (issue #152) so the server no longer scans the whole project eagerly on every
146/// `initialize` — a session that only uses `ctx_read`/`ctx_shell`/`ctx_tree`
147/// pays zero indexing cost.
148#[derive(Debug, Clone, Copy, PartialEq, Eq)]
149pub enum WarmNeed {
150    /// No prebuilt index needed.
151    None,
152    /// Only the resident line-search (trigram) index — cheap, used by `ctx_search`.
153    Search,
154    /// Full project indices (graph + BM25; this also warms the search index).
155    Heavy,
156}
157
158/// Classify a tool by the index warmth it benefits from. Unknown tools default
159/// to [`WarmNeed::None`]; a heavy tool mis-classified as `None` still works — it
160/// just builds its index synchronously on first use instead of being pre-warmed.
161#[must_use]
162pub fn warm_need_for_tool(tool: &str) -> WarmNeed {
163    match tool {
164        "ctx_search" => WarmNeed::Search,
165        // Tools that build/consume the graph, call-graph, BM25 or artifact index.
166        "ctx_graph"
167        | "ctx_callgraph"
168        | "ctx_routes"
169        | "ctx_repomap"
170        | "ctx_impact"
171        | "ctx_artifacts"
172        | "ctx_semantic_search"
173        | "ctx_provider"
174        | "ctx_compose"
175        | "ctx_explore"
176        | "ctx_review" => WarmNeed::Heavy,
177        _ => WarmNeed::None,
178    }
179}
180
181/// Lazily warm the indices a tool needs, deduped per root. Never blocks (all
182/// work is spawned in the background) and is safe to call on every dispatch.
183///
184/// Returns `true` only when this call is the *first* heavy pre-warm for `root`
185/// in this process — the caller can use that signal to warm secondary roots once
186/// without re-reading session state on every dispatch.
187pub fn ensure_warm_for_tool(project_root: &str, tool: &str) -> bool {
188    if project_root.is_empty() {
189        return false;
190    }
191    match warm_need_for_tool(tool) {
192        WarmNeed::None => false,
193        WarmNeed::Search => {
194            // The search index has its own TTL + background-rebuild dedup, so it
195            // is safe (and cheap) to nudge on every `ctx_search`.
196            crate::core::search_index::ensure_background(project_root, true, false);
197            false
198        }
199        WarmNeed::Heavy => {
200            let entry = entry_for(project_root);
201            let first_warm = {
202                let mut s = entry
203                    .lock()
204                    .unwrap_or_else(std::sync::PoisonError::into_inner);
205                if s.warm_triggered {
206                    false
207                } else {
208                    s.warm_triggered = true;
209                    true
210                }
211            };
212            if first_warm {
213                ensure_all_background(project_root);
214            }
215            first_warm
216        }
217    }
218}
219
220/// Stack size for background index workers. Large enough that deep ASTs and
221/// graph traversals cannot overflow it (the #378 SIGABRT class). The AST walks
222/// are iterative now too, so this is defense-in-depth.
223const INDEXER_STACK_BYTES: usize = 16 * 1024 * 1024;
224
225/// Fire-and-forget: ask a running daemon to own the index build for `root`
226/// (#460, shared-indexer-daemon / thin clients).
227///
228/// The daemon is the single long-lived, machine-wide indexer. Once it holds the
229/// per-repo `graph-idx`/`bm25-idx` build locks, every session load-shares its
230/// on-disk result instead of each running a full scan during a cold boot wave —
231/// turning N simultaneous index passes into ~one. Strictly additive and
232/// best-effort: it runs on its own thread (no ambient runtime to nest into), is
233/// skipped when we *are* the daemon or when no daemon is reachable, and never
234/// blocks the caller. The local build started right after remains the fallback,
235/// so indexing always works with no daemon present.
236fn nudge_daemon_index(project_root: &str) {
237    // The daemon must never delegate the build to itself.
238    if crate::daemon::is_foreground_daemon() {
239        return;
240    }
241    let root = project_root.to_string();
242    let _ = std::thread::Builder::new()
243        .name("leanctx-index-nudge".to_string())
244        .spawn(move || {
245            if !crate::daemon::is_daemon_running() {
246                return;
247            }
248            let Ok(rt) = tokio::runtime::Runtime::new() else {
249                return;
250            };
251            let body = serde_json::json!({ "root": root }).to_string();
252            rt.block_on(async {
253                let _ = crate::daemon_client::try_daemon_request("POST", "/v1/index/ensure", &body)
254                    .await;
255            });
256        });
257}
258
259/// Try to claim the per-root build slot. Returns `false` when a worker is
260/// already running for `project_root` (the claim is released by the build
261/// worker itself when it finishes).
262fn try_claim_worker(project_root: &str) -> bool {
263    let state = entry_for(project_root);
264    let mut s = state
265        .lock()
266        .unwrap_or_else(std::sync::PoisonError::into_inner);
267    if s.worker_running {
268        false
269    } else {
270        s.worker_running = true;
271        s.graph_run_done = false;
272        s.bm25_run_done = false;
273        true
274    }
275}
276
277pub fn ensure_all_background(project_root: &str) {
278    if !try_claim_worker(project_root) {
279        return;
280    }
281
282    // #460: hand the build to the daemon (the single machine-wide indexer) when
283    // one is running and we aren't it. Deduped naturally — we only reach here
284    // when this process is actually about to start a build. Purely additive: the
285    // local build below still runs and load-shares via the per-repo locks.
286    //
287    // #735 exception: with a per-run CLI filter overlay active, the daemon
288    // (which builds with *its* config, not the overlay) could overwrite the
289    // filtered result — the one-off run keeps the build local instead.
290    if !crate::core::index_filter::cli_overlay_active() {
291        nudge_daemon_index(project_root);
292    }
293
294    let state = entry_for(project_root);
295    let root = project_root.to_string();
296    let indexer = move || run_build_worker(&root);
297
298    // Indexing parses large ASTs and traverses graphs; give the worker a
299    // generous stack as defense-in-depth against deep-recursion overflow (the
300    // #378 SIGABRT class) and a name so it is identifiable in crash dumps.
301    let spawned = std::thread::Builder::new()
302        .name("leanctx-index".to_string())
303        .stack_size(INDEXER_STACK_BYTES)
304        .spawn(indexer);
305    if spawned.is_err() {
306        // The OS refused a new thread (rare). Clear the in-flight flag so a
307        // later trigger retries instead of assuming a build runs forever.
308        let mut s = state
309            .lock()
310            .unwrap_or_else(std::sync::PoisonError::into_inner);
311        s.worker_running = false;
312    }
313}
314
315/// Actual per-root build work. Heavy phases run in a fixed, memory-bounded order:
316/// graph → reclaim → BM25 → reclaim → resident search pre-warm. Blocking — callers
317/// own the threading. Requires the caller to have claimed the worker slot via
318/// [`try_claim_worker`]; releases it on exit.
319fn run_build_worker(root: &str) {
320    // #790: start memory guardian for daemon-spawned builds. Previously only
321    // the CLI path (index_cmd.rs) started the guardian, leaving background
322    // builds (MCP `ensure_all_background`, watcher, graph_coordinator) to run
323    // without RSS pressure checks — the guardian's abort/pressure flags never
324    // fired. `start_guard` is idempotent: a second call within the same
325    // process is a no-op.
326    crate::core::memory_guard::start_guard(std::sync::Arc::new(|level| {
327        tracing::warn!(
328            "[build_worker] memory pressure: {level:?} — background tasks will throttle"
329        );
330        if level >= crate::core::memory_guard::PressureLevel::Hard {
331            crate::core::content_cache::clear();
332        }
333        crate::core::memory_guard::force_purge();
334        true
335    }));
336
337    // Graph, BM25, and the resident search index each retain substantial live
338    // state. Running them concurrently defeats cache eviction because active
339    // builders still own their allocations. Keep phases strictly ordered and
340    // reclaim between them (#918); intra-phase Rayon parallelism remains intact.
341
342    let graph_state = entry_for(root);
343    let graph_root = root.to_string();
344    let build_graph = move || {
345        {
346            let mut s = graph_state
347                .lock()
348                .unwrap_or_else(std::sync::PoisonError::into_inner);
349            start_component(&mut s.graph);
350        }
351        // Graph scan has no reliable unit total → indeterminate. Guard clears on exit.
352        let guard = crate::core::index_progress::ProgressGuard::new(
353            graph_root.clone(),
354            crate::core::index_progress::IndexComponent::Graph,
355        );
356        guard.report(0, 0);
357        let graph_result = std::panic::catch_unwind(|| {
358            let (idx, _cache) = graph_index::scan_with_content_cache(&graph_root);
359            // scan_with_content_cache persists the freshly built ProjectIndex
360            // before returning it; mirroring the same unchanged index again here
361            // only repeats the property-graph mirror.
362            crate::core::code_health::persist::refresh_if_stale(&graph_root, &idx);
363        });
364        if graph_result.is_ok() {
365            // Evidence-graded call/implements edges on top of the fresh
366            // structure; a no-op unless a semantic backend can contribute.
367            let _ = std::panic::catch_unwind(|| {
368                crate::core::graph_enricher::refresh_semantic_edges_in_background(&graph_root);
369            });
370        }
371        drop(guard);
372        {
373            let mut s = graph_state
374                .lock()
375                .unwrap_or_else(std::sync::PoisonError::into_inner);
376            if let Ok(()) = graph_result {
377                finish_ok(&mut s.graph);
378            } else {
379                finish_err(&mut s.graph, "graph index build panicked".to_string());
380            }
381            s.graph_run_done = true;
382        }
383    };
384
385    let bm25_state = entry_for(root);
386    let bm25_root = root.to_string();
387    let build_bm25 = move || {
388        {
389            let mut s = bm25_state
390                .lock()
391                .unwrap_or_else(std::sync::PoisonError::into_inner);
392            start_component(&mut s.bm25);
393        }
394        let _progress = crate::core::index_progress::ProgressGuard::new(
395            bm25_root.clone(),
396            crate::core::index_progress::IndexComponent::Bm25,
397        );
398        let bm = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
399            let root_pb = Path::new(&bm25_root);
400            let lock_name = bm25_index_lock_name(root_pb);
401            let _lock = crate::core::startup_guard::try_acquire_lock(
402                &lock_name,
403                std::time::Duration::from_millis(800),
404                std::time::Duration::from_mins(3),
405            );
406            if _lock.is_none() {
407                tracing::info!(
408                    "[bm25: another process is building {bm25_root} — loading the shared index]"
409                );
410                let idx = BM25Index::load(root_pb).unwrap_or_default();
411                return (idx.doc_count, None);
412            }
413            let idx = BM25Index::load_or_build(root_pb);
414            let outcome = idx.save(root_pb);
415            (idx.doc_count, Some(outcome))
416        }));
417        {
418            let mut s = bm25_state
419                .lock()
420                .unwrap_or_else(std::sync::PoisonError::into_inner);
421            if let Ok((doc_count, save_res)) = bm {
422                finish_ok(&mut s.bm25);
423                s.bm25.note = Some(match save_res {
424                    Some(outcome) => bm25_build_note(doc_count, &outcome),
425                    None => format!(
426                        "loaded shared BM25 index ({doc_count} chunks) — build in progress in another process"
427                    ),
428                });
429            } else {
430                finish_err(&mut s.bm25, "bm25 build panicked".to_string());
431            }
432            s.bm25_run_done = true;
433        }
434    };
435
436    run_memory_bounded_phases(
437        build_graph,
438        build_bm25,
439        || crate::core::search_index::ensure_background(root, true, false),
440        || {
441            crate::core::content_cache::clear();
442            crate::core::memory_guard::force_purge();
443        },
444    );
445
446    // Post-build memory reclamation: the parallel build allocates large
447    // transient structures (file contents, token vectors, inverted postings).
448    // After merge+save these are freed, but jemalloc retains dirty pages in
449    // its arena — inflating RSS far past the logical working set. Purging
450    // immediately returns those pages to the OS, keeping the serve process
451    // close to the configured max_ram_percent target.
452    crate::core::content_cache::trim_oldest_percent(75);
453    crate::core::memory_guard::force_purge();
454
455    let final_state = entry_for(root);
456    let mut s = final_state
457        .lock()
458        .unwrap_or_else(std::sync::PoisonError::into_inner);
459    s.worker_running = false;
460}
461
462/// Execute index phases without overlapping their retained working sets.
463/// Kept as a small pure coordinator so ordering remains regression-testable.
464fn run_memory_bounded_phases<G, B, S, R>(graph: G, bm25: B, search: S, mut reclaim: R)
465where
466    G: FnOnce(),
467    B: FnOnce(),
468    S: FnOnce(),
469    R: FnMut(),
470{
471    graph();
472    reclaim();
473    bm25();
474    reclaim();
475    search();
476}
477
478/// Build only the semantic (dense embedding) index from the existing BM25 index.
479/// The BM25 index must already exist on disk — this function loads it and runs
480/// `embedding_index::build_or_update`. Updates the in-memory semantic component
481/// state on completion.
482pub fn build_semantic(project_root: &str) {
483    let state = entry_for(project_root);
484    let root = Path::new(project_root);
485
486    {
487        let mut s = state
488            .lock()
489            .unwrap_or_else(std::sync::PoisonError::into_inner);
490        start_component(&mut s.semantic);
491    }
492
493    // Guard clears progress on every exit (incl. early returns / panics).
494    let _progress = crate::core::index_progress::ProgressGuard::new(
495        project_root.to_string(),
496        crate::core::index_progress::IndexComponent::Semantic,
497    );
498
499    let bm25_idx = try_load_bm25_index(project_root);
500    match bm25_idx.as_ref() {
501        Some(idx) if idx.doc_count > 0 => {
502            let outcome = crate::core::embedding_index::build_or_update(root, idx);
503            let mut s = state
504                .lock()
505                .unwrap_or_else(std::sync::PoisonError::into_inner);
506            match outcome {
507                crate::core::embedding_index::EmbeddingBuildOutcome::Ready => {
508                    finish_ok(&mut s.semantic);
509                }
510                crate::core::embedding_index::EmbeddingBuildOutcome::Skipped => {
511                    finish_ok(&mut s.semantic);
512                    s.semantic.note = Some(
513                        "embeddings disabled by feature flag or config (search.dense_enabled / memory_profile)"
514                            .to_string(),
515                    );
516                }
517                crate::core::embedding_index::EmbeddingBuildOutcome::ModelNotAvailable(
518                    ref reason,
519                ) => {
520                    // Not a hard failure — semantic is optional. Surface the reason
521                    // so users know why dense search is cold (#249).
522                    s.semantic.state = State::Idle;
523                    s.semantic.note = Some(format!("embedding model not available: {reason}"));
524                }
525                crate::core::embedding_index::EmbeddingBuildOutcome::Failed => {
526                    finish_err(
527                        &mut s.semantic,
528                        "embedding build failed (see logs)".to_string(),
529                    );
530                }
531            }
532        }
533        _ => {
534            let mut s = state
535                .lock()
536                .unwrap_or_else(std::sync::PoisonError::into_inner);
537            // No BM25 docs → nothing to embed. Leave semantic Idle with a note.
538            s.semantic.state = State::Idle;
539            s.semantic.note =
540                Some("BM25 index is empty or unavailable — nothing to embed".to_string());
541        }
542    }
543}
544
545/// Ensure background indexing for all extra roots (in addition to the primary).
546/// Each extra root that is not a subdirectory of `primary_root` gets its own
547/// graph + BM25 index. Capped at `MAX_EXTRA_ROOT_BUILDS` to prevent runaway.
548const MAX_EXTRA_ROOT_BUILDS: usize = 8;
549
550pub fn ensure_extra_roots_background(primary_root: &str, extra_roots: &[String]) {
551    let primary = Path::new(primary_root);
552    let mut queue: Vec<String> = Vec::new();
553    for root in extra_roots {
554        if queue.len() >= MAX_EXTRA_ROOT_BUILDS {
555            break;
556        }
557        let rp = Path::new(root);
558        if !rp.is_dir() {
559            continue;
560        }
561        // Skip if extra_root is inside primary (already indexed by the primary scan)
562        if rp.starts_with(primary) {
563            continue;
564        }
565        // Skip if primary is inside this extra_root (avoid double-indexing the parent)
566        if primary.starts_with(rp) {
567            continue;
568        }
569        queue.push(root.clone());
570    }
571    if queue.is_empty() {
572        return;
573    }
574
575    // #685: build extra roots *sequentially* on one supervisor thread. The old
576    // per-root `ensure_all_background` fan-out ran up to MAX_EXTRA_ROOT_BUILDS
577    // graph+BM25 pairs concurrently (each with rayon pools inside) — on the
578    // reported multi-root setup (1M+ files across 6+ roots) the combined
579    // transient build state outran the guardian to 75 GB RSS. One root at a
580    // time keeps peak memory bounded to a single build while still warming
581    // every root; the guardian check between roots stops the queue as soon as
582    // pressure appears.
583    let spawned = std::thread::Builder::new()
584        .name("leanctx-extra-roots".to_string())
585        .stack_size(INDEXER_STACK_BYTES)
586        .spawn(move || {
587            for root in queue {
588                if crate::core::memory_guard::is_under_pressure()
589                    || crate::core::memory_guard::abort_requested()
590                {
591                    tracing::warn!(
592                        "[index_orchestrator: skipping remaining extra-root builds under memory pressure]"
593                    );
594                    break;
595                }
596                if !try_claim_worker(&root) {
597                    continue; // already building elsewhere
598                }
599                nudge_daemon_index(&root);
600                run_build_worker(&root);
601            }
602        });
603    if let Err(e) = spawned {
604        tracing::warn!("[index_orchestrator: could not spawn extra-roots worker: {e}]");
605    }
606}
607
608/// Build a human-readable outcome note for a finished BM25 build, including the
609/// indexed chunk count and whether the index was persisted to disk. A
610/// "too large" refusal carries the exact remedy so the operator (or agent) is
611/// never left guessing why search/ranking stays cold (issue #249).
612fn bm25_build_note(
613    doc_count: usize,
614    save: &std::io::Result<crate::core::bm25_index::SaveOutcome>,
615) -> String {
616    use crate::core::bm25_index::SaveOutcome;
617    match save {
618        Ok(SaveOutcome::Persisted { compressed_bytes }) => format!(
619            "indexed {doc_count} chunks, {:.1} MB persisted",
620            *compressed_bytes as f64 / 1_048_576.0
621        ),
622        Ok(SaveOutcome::SkippedTooLarge {
623            compressed_bytes,
624            limit_bytes,
625        }) => format!(
626            "indexed {doc_count} chunks but NOT persisted to disk: compressed {:.1} MB exceeds the {:.0} MB cap. \
627             Raise it via LEAN_CTX_BM25_MAX_CACHE_MB (or bm25_max_cache_mb in config) or add extra_ignore_patterns, \
628             then run `lean-ctx reindex`. Until then the index is rebuilt from scratch on every cold start.",
629            *compressed_bytes as f64 / 1_048_576.0,
630            *limit_bytes as f64 / 1_048_576.0
631        ),
632        Err(e) => format!("indexed {doc_count} chunks but persisting failed: {e}"),
633    }
634}
635
636/// Lightweight, allocation-frugal snapshot of the BM25 component for the
637/// in-call composer/search messaging. Avoids the heavier [`disk_status`] walk.
638#[derive(Debug, Clone)]
639pub struct Bm25Summary {
640    pub state: &'static str,
641    /// While building: elapsed so far. Otherwise: last build duration.
642    pub elapsed_ms: Option<u64>,
643    pub note: Option<String>,
644    pub last_error: Option<String>,
645}
646
647/// Lightweight snapshot of the semantic (dense embedding) component.
648#[derive(Debug, Clone)]
649pub struct SemanticSummary {
650    pub state: &'static str,
651    pub elapsed_ms: Option<u64>,
652    pub note: Option<String>,
653    pub last_error: Option<String>,
654}
655
656/// Shared helper: compute (state_str, elapsed_ms) for a component.
657/// Deduplicates the elapsed-while-building logic and state-to-string mapping
658/// between bm25_summary and semantic_summary.
659fn component_elapsed_and_state(c: &Component) -> (&'static str, Option<u64>) {
660    let elapsed_ms = if matches!(c.state, State::Building) {
661        c.started_ms.map(|start| now_ms().saturating_sub(start))
662    } else {
663        c.duration_ms
664    };
665    let state = match c.state {
666        State::Idle => "idle",
667        State::Building => "building",
668        State::Ready => "ready",
669        State::Failed => "failed",
670    };
671    (state, elapsed_ms)
672}
673
674pub fn semantic_summary(project_root: &str) -> SemanticSummary {
675    let entry = entry_for(project_root);
676    let s = entry
677        .lock()
678        .unwrap_or_else(std::sync::PoisonError::into_inner);
679    let c = &s.semantic;
680    let (state, elapsed_ms) = component_elapsed_and_state(c);
681    SemanticSummary {
682        state,
683        elapsed_ms,
684        note: c.note.clone(),
685        last_error: c.last_error.clone(),
686    }
687}
688
689pub fn bm25_summary(project_root: &str) -> Bm25Summary {
690    let entry = entry_for(project_root);
691    let s = entry
692        .lock()
693        .unwrap_or_else(std::sync::PoisonError::into_inner);
694    let c = &s.bm25;
695    let (state, elapsed_ms) = component_elapsed_and_state(c);
696    Bm25Summary {
697        state,
698        elapsed_ms,
699        note: c.note.clone(),
700        last_error: c.last_error.clone(),
701    }
702}
703
704pub fn try_load_graph_index(project_root: &str) -> Option<ProjectIndex> {
705    // Resident cache: avoids re-materializing the index from the property graph
706    // (SQLite query) on every graph-touching query. Returns an in-memory clone.
707    crate::core::graph_cache::get_cached(project_root).map(|arc| (*arc).clone())
708}
709
710pub fn try_load_bm25_index(project_root: &str) -> Option<BM25Index> {
711    BM25Index::load(Path::new(project_root))
712}
713
714/// Typed progress snapshot for one index component.
715#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
716pub struct SlotProgress {
717    pub building: bool,
718    pub done: u64,
719    pub total: u64,
720}
721
722impl SlotProgress {
723    pub fn is_determinate(&self) -> bool {
724        self.building && self.total > 0
725    }
726}
727
728/// Root-scoped view of index build progress for CLI wait loops.
729#[derive(Debug, Clone, PartialEq, Eq)]
730pub struct ProgressView {
731    pub worker_running: bool,
732    /// Graph phase of the current worker run has finished (ok or err).
733    pub graph_run_done: bool,
734    /// BM25 phase of the current worker run has finished (ok or err).
735    pub bm25_run_done: bool,
736    pub graph: SlotProgress,
737    pub bm25: SlotProgress,
738    pub semantic: SlotProgress,
739}
740
741impl ProgressView {
742    /// Graph + BM25 pipeline still in flight for this root.
743    ///
744    /// True from worker claim through BM25 completion — covers the claim→start
745    /// race and the graph→BM25 handoff without waiting for search pre-warm.
746    pub fn graph_bm25_active(&self) -> bool {
747        self.worker_running && !(self.graph_run_done && self.bm25_run_done)
748    }
749
750    pub fn semantic_active(&self) -> bool {
751        self.semantic.building
752    }
753}
754
755/// Snapshot progress for a project root (typed; no JSON scrape).
756pub fn progress_view(project_root: &str) -> ProgressView {
757    use crate::core::index_progress::{self, IndexComponent};
758    let (worker_running, graph_run_done, bm25_run_done, graph_b, bm25_b, sem_b) = {
759        let state = entry_for(project_root);
760        let s = state
761            .lock()
762            .unwrap_or_else(std::sync::PoisonError::into_inner);
763        (
764            s.worker_running,
765            s.graph_run_done,
766            s.bm25_run_done,
767            matches!(s.graph.state, State::Building),
768            matches!(s.bm25.state, State::Building),
769            matches!(s.semantic.state, State::Building),
770        )
771    };
772    let g = index_progress::get(project_root, IndexComponent::Graph);
773    let b = index_progress::get(project_root, IndexComponent::Bm25);
774    let sem = index_progress::get(project_root, IndexComponent::Semantic);
775    ProgressView {
776        worker_running,
777        graph_run_done,
778        bm25_run_done,
779        graph: SlotProgress {
780            building: graph_b,
781            done: g.done,
782            total: g.total,
783        },
784        bm25: SlotProgress {
785            building: bm25_b,
786            done: b.done,
787            total: b.total,
788        },
789        semantic: SlotProgress {
790            building: sem_b,
791            done: sem.done,
792            total: sem.total,
793        },
794    }
795}
796
797/// Returns true if any project is currently building its indices.
798pub fn is_building() -> bool {
799    let map = registry()
800        .lock()
801        .unwrap_or_else(std::sync::PoisonError::into_inner);
802    map.values().any(|entry| {
803        let st = entry
804            .lock()
805            .unwrap_or_else(std::sync::PoisonError::into_inner);
806        matches!(st.bm25.state, State::Building)
807            || matches!(st.graph.state, State::Building)
808            || matches!(st.semantic.state, State::Building)
809    })
810}
811
812#[derive(Debug, Serialize)]
813struct ComponentStatus<'a> {
814    state: &'a str,
815    started_ms: Option<u64>,
816    finished_ms: Option<u64>,
817    duration_ms: Option<u64>,
818    last_error: Option<&'a str>,
819    #[serde(skip_serializing_if = "Option::is_none")]
820    note: Option<&'a str>,
821    /// Units completed while `building` (files/chunks). Omitted when idle/ready.
822    #[serde(skip_serializing_if = "Option::is_none")]
823    progress_done: Option<u64>,
824    /// Total units; `Some(0)` while building means indeterminate.
825    #[serde(skip_serializing_if = "Option::is_none")]
826    progress_total: Option<u64>,
827}
828
829fn component_status(
830    c: &Component,
831    progress: crate::core::index_progress::ProgressSnapshot,
832) -> ComponentStatus<'_> {
833    let (progress_done, progress_total) = if matches!(c.state, State::Building) {
834        (Some(progress.done), Some(progress.total))
835    } else {
836        (None, None)
837    };
838    ComponentStatus {
839        state: match c.state {
840            State::Idle => "idle",
841            State::Building => "building",
842            State::Ready => "ready",
843            State::Failed => "failed",
844        },
845        started_ms: c.started_ms,
846        finished_ms: c.finished_ms,
847        duration_ms: c.duration_ms,
848        last_error: c.last_error.as_deref(),
849        note: c.note.as_deref(),
850        progress_done,
851        progress_total,
852    }
853}
854
855#[derive(Debug, Serialize)]
856struct StatusResponse<'a> {
857    project_root: &'a str,
858    graph_index: ComponentStatus<'a>,
859    bm25_index: ComponentStatus<'a>,
860    /// Dense embedding index built after BM25.  "idle" means the ONNX model
861    /// has not been downloaded yet or the embeddings feature was not compiled
862    /// in; "ready" means embeddings are persisted and search will use them.
863    semantic_index: ComponentStatus<'a>,
864    disk: DiskStatusAll,
865    /// Active corpus filter summary (#735). Omitted for the unfiltered
866    /// default, keeping default output byte-identical.
867    #[serde(skip_serializing_if = "Option::is_none")]
868    index_filters: Option<String>,
869}
870
871#[derive(Debug, Serialize, Default)]
872pub struct DiskStatus {
873    pub exists: bool,
874    pub size_bytes: Option<u64>,
875    pub file_count: Option<u64>,
876    pub modified_at: Option<String>,
877}
878
879#[derive(Debug, Serialize, Default)]
880pub struct DiskStatusAll {
881    pub graph_index: DiskStatus,
882    pub bm25_index: DiskStatus,
883    pub code_graph: DiskStatus,
884    /// On-disk embedding index (`embeddings.bin`).  Present when dense search
885    /// has been built at least once; absent when the model is not downloaded
886    /// yet or embeddings are disabled by config.
887    pub semantic_index: DiskStatus,
888}
889
890fn disk_status_for_graph(project_root: &str) -> DiskStatus {
891    // #696 C4: the property graph is the sole store. The logical graph-index
892    // view (file count) is timed by `graph.meta.json`, which the mirror stamps
893    // on every build; `disk_status_for_code_graph` reports the raw SQLite store
894    // (nodes, graph.db size) as a distinct facet. The meta file's own size is
895    // not the index size, so none is reported here (#1914).
896    let Some(dir) = graph_index::ProjectIndex::index_dir(project_root) else {
897        return DiskStatus::default();
898    };
899    let meta_file = dir.join("graph.meta.json");
900    if !meta_file.exists() {
901        return DiskStatus::default();
902    }
903    let meta = std::fs::metadata(&meta_file).ok();
904    let file_count =
905        graph_index::ProjectIndex::load(project_root).map(|idx| idx.files.len() as u64);
906    DiskStatus {
907        exists: true,
908        size_bytes: None,
909        file_count,
910        modified_at: meta.and_then(|m| m.modified().ok()).map(format_time),
911    }
912}
913
914fn disk_status_for_bm25(project_root: &str) -> DiskStatus {
915    let root = Path::new(project_root);
916    let path = BM25Index::index_file_path(root);
917    if !path.exists() {
918        return DiskStatus::default();
919    }
920    let meta = std::fs::metadata(&path).ok();
921    DiskStatus {
922        exists: true,
923        size_bytes: meta.as_ref().map(std::fs::Metadata::len),
924        file_count: BM25Index::persisted_chunk_count(root),
925        modified_at: meta.and_then(|m| m.modified().ok()).map(format_time),
926    }
927}
928
929fn disk_status_for_code_graph(project_root: &str) -> DiskStatus {
930    let dir = crate::core::property_graph::graph_dir(project_root);
931    let db_path = dir.join("graph.db");
932    if !db_path.exists() {
933        return DiskStatus::default();
934    }
935    let meta = std::fs::metadata(&db_path).ok();
936    let node_count = crate::core::property_graph::CodeGraph::open(project_root)
937        .ok()
938        .and_then(|g| {
939            g.connection()
940                .query_row("SELECT count(*) FROM nodes", [], |r| r.get::<_, i64>(0))
941                .ok()
942                .map(|c| c as u64)
943        });
944    DiskStatus {
945        exists: true,
946        size_bytes: meta.as_ref().map(std::fs::Metadata::len),
947        file_count: node_count,
948        modified_at: meta.and_then(|m| m.modified().ok()).map(format_time),
949    }
950}
951
952fn format_time(t: SystemTime) -> String {
953    let secs = t.duration_since(UNIX_EPOCH).unwrap_or_default().as_secs();
954    let dt = chrono::DateTime::from_timestamp(secs as i64, 0);
955    dt.map_or_else(
956        || format!("{secs}"),
957        |d| d.format("%Y-%m-%d %H:%M:%S UTC").to_string(),
958    )
959}
960
961pub fn disk_status_for_semantic(project_root: &str) -> DiskStatus {
962    let root = Path::new(project_root);
963    let dir = crate::core::index_namespace::vectors_dir(root);
964    let bin_path = dir.join("embeddings.bin");
965    if !bin_path.exists() {
966        return DiskStatus::default();
967    }
968    let meta = std::fs::metadata(&bin_path).ok();
969    DiskStatus {
970        exists: true,
971        size_bytes: meta.as_ref().map(std::fs::Metadata::len),
972        file_count: None,
973        modified_at: meta.and_then(|m| m.modified().ok()).map(format_time),
974    }
975}
976
977pub fn disk_status(project_root: &str) -> DiskStatusAll {
978    DiskStatusAll {
979        graph_index: disk_status_for_graph(project_root),
980        bm25_index: disk_status_for_bm25(project_root),
981        code_graph: disk_status_for_code_graph(project_root),
982        semantic_index: disk_status_for_semantic(project_root),
983    }
984}
985
986pub fn status_json(project_root: &str) -> String {
987    // Compute disk status first — may do SQLite I/O and must NOT hold L2
988    // (per-project Mutex) while doing so, or the background index worker
989    // cannot call finish_ok / set worker_running = false (#deadlock).
990    let disk = disk_status(project_root);
991    let state = entry_for(project_root);
992    let s = state
993        .lock()
994        .unwrap_or_else(std::sync::PoisonError::into_inner);
995    let graph_p = crate::core::index_progress::get(
996        project_root,
997        crate::core::index_progress::IndexComponent::Graph,
998    );
999    let bm25_p = crate::core::index_progress::get(
1000        project_root,
1001        crate::core::index_progress::IndexComponent::Bm25,
1002    );
1003    let semantic_p = crate::core::index_progress::get(
1004        project_root,
1005        crate::core::index_progress::IndexComponent::Semantic,
1006    );
1007    let res = StatusResponse {
1008        project_root,
1009        graph_index: component_status(&s.graph, graph_p),
1010        bm25_index: component_status(&s.bm25, bm25_p),
1011        semantic_index: component_status(&s.semantic, semantic_p),
1012        disk,
1013        index_filters: crate::core::index_filter::IndexFileFilter::effective().summary(),
1014    };
1015    serde_json::to_string(&res).unwrap_or_else(|_| "{}".to_string())
1016}
1017
1018#[cfg(test)]
1019mod tests {
1020    use super::*;
1021
1022    #[test]
1023    fn progress_view_graph_bm25_active_logic() {
1024        let idle = SlotProgress::default();
1025        let mut v = ProgressView {
1026            worker_running: true,
1027            graph_run_done: false,
1028            bm25_run_done: false,
1029            graph: idle,
1030            bm25: idle,
1031            semantic: idle,
1032        };
1033        assert!(v.graph_bm25_active(), "claimed, phases not done");
1034        v.graph_run_done = true;
1035        assert!(v.graph_bm25_active(), "graph done, bm25 pending");
1036        v.bm25_run_done = true;
1037        assert!(
1038            !v.graph_bm25_active(),
1039            "both phases done — search pre-warm must not keep wait open"
1040        );
1041        v.worker_running = false;
1042        assert!(!v.graph_bm25_active());
1043        // Idle project (never claimed this process)
1044        v.graph_run_done = true;
1045        v.bm25_run_done = true;
1046        assert!(!v.graph_bm25_active());
1047    }
1048
1049    #[test]
1050    fn status_json_is_valid_json() {
1051        let s = status_json("/tmp");
1052        let _: serde_json::Value = serde_json::from_str(&s).unwrap();
1053    }
1054
1055    #[test]
1056    fn background_build_phases_are_serialized_with_reclamation() {
1057        let events = std::cell::RefCell::new(Vec::new());
1058        run_memory_bounded_phases(
1059            || events.borrow_mut().push("graph"),
1060            || events.borrow_mut().push("bm25"),
1061            || events.borrow_mut().push("search"),
1062            || events.borrow_mut().push("reclaim"),
1063        );
1064        assert_eq!(
1065            events.into_inner(),
1066            ["graph", "reclaim", "bm25", "reclaim", "search"]
1067        );
1068    }
1069
1070    #[test]
1071    fn warm_need_classifies_tools() {
1072        // Lightweight tools must never trigger a project scan (#152).
1073        for light in [
1074            "ctx_read",
1075            "ctx_shell",
1076            "ctx_tree",
1077            "ctx_knowledge",
1078            "unknown_tool",
1079        ] {
1080            assert_eq!(warm_need_for_tool(light), WarmNeed::None, "{light}");
1081        }
1082        // ctx_search only needs the cheap trigram index.
1083        assert_eq!(warm_need_for_tool("ctx_search"), WarmNeed::Search);
1084        for heavy in [
1085            "ctx_graph",
1086            "ctx_callgraph",
1087            "ctx_routes",
1088            "ctx_repomap",
1089            "ctx_impact",
1090            "ctx_artifacts",
1091            "ctx_semantic_search",
1092            "ctx_provider",
1093            "ctx_compose",
1094            "ctx_explore",
1095            "ctx_review",
1096        ] {
1097            assert_eq!(warm_need_for_tool(heavy), WarmNeed::Heavy, "{heavy}");
1098        }
1099    }
1100
1101    #[test]
1102    fn ensure_warm_lightweight_and_search_never_signal_first_warm() {
1103        assert!(!ensure_warm_for_tool("", "ctx_graph"));
1104        let tmp = tempfile::tempdir().unwrap();
1105        let root = tmp.path().to_string_lossy().to_string();
1106        assert!(!ensure_warm_for_tool(&root, "ctx_read"));
1107        assert!(!ensure_warm_for_tool(&root, "ctx_search"));
1108    }
1109
1110    #[test]
1111    fn ensure_warm_heavy_is_once_per_root() {
1112        // The first heavy pre-warm signals `true` (so the caller warms extra
1113        // roots once); every subsequent call is a no-op `false`, preventing a
1114        // rebuild-on-every-dispatch storm.
1115        let tmp = tempfile::tempdir().unwrap();
1116        let root = tmp.path().to_string_lossy().to_string();
1117        assert!(
1118            ensure_warm_for_tool(&root, "ctx_callgraph"),
1119            "first heavy warm must signal true"
1120        );
1121        assert!(
1122            !ensure_warm_for_tool(&root, "ctx_callgraph"),
1123            "second heavy warm must be deduped to false"
1124        );
1125        assert!(
1126            !ensure_warm_for_tool(&root, "ctx_semantic_search"),
1127            "any later heavy tool on the same root is also deduped"
1128        );
1129    }
1130
1131    #[test]
1132    fn build_note_persisted_reports_size() {
1133        let note = bm25_build_note(
1134            42,
1135            &Ok(crate::core::bm25_index::SaveOutcome::Persisted {
1136                compressed_bytes: 3 * 1024 * 1024,
1137            }),
1138        );
1139        assert!(
1140            note.contains("42 chunks"),
1141            "note should report chunk count: {note}"
1142        );
1143        assert!(
1144            note.contains("persisted"),
1145            "note should report persistence: {note}"
1146        );
1147    }
1148
1149    #[test]
1150    fn build_note_too_large_carries_remedy() {
1151        let note = bm25_build_note(
1152            1000,
1153            &Ok(crate::core::bm25_index::SaveOutcome::SkippedTooLarge {
1154                compressed_bytes: 600 * 1024 * 1024,
1155                limit_bytes: 512 * 1024 * 1024,
1156            }),
1157        );
1158        assert!(
1159            note.contains("NOT persisted"),
1160            "must flag non-persistence: {note}"
1161        );
1162        assert!(
1163            note.contains("LEAN_CTX_BM25_MAX_CACHE_MB") && note.contains("reindex"),
1164            "too-large note must carry an actionable remedy: {note}"
1165        );
1166    }
1167
1168    #[test]
1169    fn build_note_persist_error_is_reported() {
1170        let note = bm25_build_note(7, &Err(std::io::Error::other("disk full")));
1171        assert!(note.contains("persisting failed"), "note: {note}");
1172        assert!(
1173            note.contains("disk full"),
1174            "note should include the io error: {note}"
1175        );
1176    }
1177
1178    #[test]
1179    fn bm25_summary_unknown_project_is_idle() {
1180        let tmp = tempfile::tempdir().unwrap();
1181        let summary = bm25_summary(tmp.path().to_string_lossy().as_ref());
1182        assert_eq!(summary.state, "idle");
1183        assert!(summary.note.is_none());
1184        assert!(summary.last_error.is_none());
1185    }
1186
1187    #[test]
1188    fn extra_roots_skips_subdirs_of_primary() {
1189        let tmp = tempfile::tempdir().unwrap();
1190        let primary = tmp.path().join("primary");
1191        std::fs::create_dir_all(&primary).unwrap();
1192        let sub = primary.join("subdir");
1193        std::fs::create_dir_all(&sub).unwrap();
1194        let external = tmp.path().join("external");
1195        std::fs::create_dir_all(&external).unwrap();
1196
1197        let primary_str = primary.to_string_lossy().to_string();
1198        let extra = vec![
1199            sub.to_string_lossy().to_string(),
1200            external.to_string_lossy().to_string(),
1201        ];
1202
1203        // Should not panic; subdirs are skipped, external is attempted
1204        ensure_extra_roots_background(&primary_str, &extra);
1205    }
1206
1207    #[test]
1208    fn extra_roots_caps_at_max() {
1209        let tmp = tempfile::tempdir().unwrap();
1210        let primary = tmp.path().join("primary");
1211        std::fs::create_dir_all(&primary).unwrap();
1212
1213        let mut extra = Vec::new();
1214        for i in 0..20 {
1215            let d = tmp.path().join(format!("ext-{i}"));
1216            std::fs::create_dir_all(&d).unwrap();
1217            extra.push(d.to_string_lossy().to_string());
1218        }
1219
1220        let primary_str = primary.to_string_lossy().to_string();
1221        // Should not spawn more than MAX_EXTRA_ROOT_BUILDS threads
1222        ensure_extra_roots_background(&primary_str, &extra);
1223    }
1224
1225    #[test]
1226    fn bm25_index_lock_name_is_per_repo_and_distinct_from_graph() {
1227        let a = bm25_index_lock_name(Path::new("/tmp/repo-a"));
1228        let b = bm25_index_lock_name(Path::new("/tmp/repo-b"));
1229        assert!(a.starts_with("bm25-idx-"), "unexpected lock name: {a}");
1230        assert_ne!(a, b, "lock name must be per-repo");
1231        // Stable for the same repo across calls.
1232        assert_eq!(a, bm25_index_lock_name(Path::new("/tmp/repo-a")));
1233        // Must NOT collide with the graph lock for the same repo, or the two
1234        // builds would serialize against each other unnecessarily.
1235        let graph = format!(
1236            "graph-idx-{}",
1237            &crate::core::index_namespace::namespace_hash(Path::new("/tmp/repo-a"))[..8]
1238        );
1239        assert_ne!(a, graph, "bm25 and graph locks must be independent");
1240    }
1241}