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