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