Skip to main content

aft/
context.rs

1use std::collections::{BTreeMap, BTreeSet, VecDeque};
2use std::io::{self, BufWriter};
3use std::path::{Component, Path, PathBuf};
4use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
5use std::sync::{mpsc, Arc, Mutex, RwLock, TryLockError, Weak};
6use std::time::{Duration, Instant, SystemTime};
7
8use lsp_types::FileChangeType;
9use notify::RecommendedWatcher;
10use rusqlite::Connection;
11use serde::Serialize;
12
13use crate::artifact_owner::{
14    ArtifactOwnerLease, ArtifactOwnerLeaseRegistration, ArtifactOwnerMode, ArtifactOwnerStatus,
15};
16use crate::backup::hash_session;
17use crate::backup::BackupStore;
18use crate::bash_background::{BgCompletion, BgTaskHealthCounts, BgTaskRegistry};
19use crate::callgraph_store::{CallGraphStore, CallGraphStoreError, ReadonlyCallGraphStore};
20use crate::checkpoint::CheckpointStore;
21use crate::config::Config;
22use crate::harness::Harness;
23use crate::inspect::{
24    InspectCategory, InspectManager, InspectSnapshot, Tier2RefreshScheduler, Tier2TriggerReason,
25};
26use crate::language::LanguageProvider;
27use crate::lsp::manager::{LspManager, StaleDiagnosticsMark};
28use crate::lsp::registry::is_config_file_path_with_custom;
29use crate::parser::{SharedSymbolCache, SymbolCache, TreeSitterProvider};
30use crate::protocol::{
31    ConfigureWarningsFrame, ProgressFrame, PushFrame, StatusChangedFrame, StatusPayload,
32};
33use crate::watcher_filter::WatcherJoinOutcome;
34use crate::watcher_filter::{SharedGitignore, WatcherDispatchEvent, WatcherThreadHandle};
35
36pub type ProgressSender = Arc<Box<dyn Fn(PushFrame) + Send + Sync>>;
37pub type SharedProgressSender = Arc<Mutex<Option<ProgressSender>>>;
38pub type SharedStdoutWriter = Arc<Mutex<BufWriter<io::Stdout>>>;
39const STATUS_DEBOUNCE_MS: u64 = 1_000;
40
41/// Canonicalize a path that may no longer exist (pending callgraph paths
42/// legitimately include deleted files): canonicalize the nearest existing
43/// ancestor of the ORIGINAL spelling and re-append the missing tail, so alias
44/// spellings (macOS /var vs /private/var) normalize even for dead paths.
45///
46/// Symlink semantics match the callgraph store's `normalize_file_path`
47/// (filesystem-first): `root/link/../x` where `link` targets a foreign
48/// directory canonicalizes to the FOREIGN parent, not a lexical `root/x`.
49/// Lexical `.`/`..` resolution applies only past the deepest existing
50/// component (a nonexistent component cannot be a symlink) and to the tail
51/// appended onto an already-canonical, symlink-free base.
52/// Component-wise lenient canonicalization with filesystem-first semantics
53/// (matching the callgraph store's `normalize_file_path`): each existing
54/// component — including symlinks — resolves through the filesystem; genuinely
55/// absent components accumulate on a missing stack and resolve lexically. `..`
56/// pops the missing stack first, and only when the stack is empty does it take
57/// the parent of the canonical base (symlink-free, so a lexical parent is
58/// sound there). Handles re-entry: in `dead/../link/../x`, `dead/..` drains
59/// back to the existing base and `link` (a symlink) resolves through the
60/// filesystem instead of being erased lexically.
61///
62/// Returns `None` — and containment fails closed — where realpath would not
63/// resolve either: a dangling symlink or other filesystem error on an existing
64/// component (the store falls back to the raw spelling for those, which
65/// `relative_path` keeps as an absolute out-of-root key), and `..` traversal
66/// through a non-directory (realpath ENOTDIR).
67fn canonicalize_lenient(path: &Path) -> Option<PathBuf> {
68    use std::path::Component;
69    if let Ok(canonical) = std::fs::canonicalize(path) {
70        return Some(canonical);
71    }
72    let mut resolved = PathBuf::new();
73    let mut missing: Vec<std::ffi::OsString> = Vec::new();
74    for component in path.components() {
75        match component {
76            Component::Prefix(_) | Component::RootDir => {
77                resolved.push(component.as_os_str());
78                // Canonicalize the anchor so a missing child directly under a
79                // drive/UNC root compares in the same (verbatim) spelling as a
80                // canonicalized root on Windows; "/" is a no-op on Unix.
81                if let Ok(canonical_anchor) = std::fs::canonicalize(&resolved) {
82                    resolved = canonical_anchor;
83                }
84            }
85            Component::CurDir => {}
86            Component::ParentDir => {
87                if missing.pop().is_none() {
88                    if !resolved.as_os_str().is_empty() && !resolved.is_dir() {
89                        // `file/..` — realpath rejects with ENOTDIR.
90                        return None;
91                    }
92                    resolved.pop();
93                }
94            }
95            Component::Normal(name) => {
96                if missing.is_empty() {
97                    let candidate = resolved.join(name);
98                    match std::fs::canonicalize(&candidate) {
99                        Ok(canonical) => resolved = canonical,
100                        Err(_) => match std::fs::symlink_metadata(&candidate) {
101                            // Genuinely absent: lexical from here until `..`
102                            // drains back.
103                            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
104                                missing.push(name.to_owned())
105                            }
106                            // Exists but does not canonicalize (dangling
107                            // symlink) or the probe itself failed: fail closed.
108                            _ => return None,
109                        },
110                    }
111                } else {
112                    missing.push(name.to_owned());
113                }
114            }
115        }
116    }
117    for name in missing {
118        resolved.push(name);
119    }
120    Some(resolved)
121}
122
123/// Root-containment check for pending callgraph replay paths.
124///
125/// Relative paths are project-root-relative by the callgraph store's own
126/// contract (`normalize_file_path`), so they are resolved against each root
127/// rather than the process CWD. Both sides are lenient-canonicalized
128/// (component-wise, filesystem-first) before the prefix comparison: raw-spelling
129/// acceptance would let `root/../foreign` or a symlinked escape pass, and a
130/// bare textual check false-drops alias spellings (macOS /var vs
131/// /private/var) and deleted files.
132fn pending_path_in_roots(path: &Path, roots: &[PathBuf]) -> bool {
133    if path.is_relative() {
134        // Project-root-relative by contract, and only for prefix-free
135        // spellings: Windows drive-relative (`C:foo`) and root-relative
136        // (`\foo`) forms are "relative" to std but `join` replaces the root
137        // for them, resolving through the drive CWD instead of the project.
138        let has_prefix_or_root = path.components().next().is_some_and(|component| {
139            matches!(
140                component,
141                std::path::Component::Prefix(_) | std::path::Component::RootDir
142            )
143        });
144        if has_prefix_or_root {
145            return false;
146        }
147        // A lexical escape via `..` still fails the canonical prefix check
148        // after joining. Unresolvable spellings fail closed.
149        return roots.iter().any(|root| {
150            let joined = root.join(path);
151            match (canonicalize_lenient(&joined), canonicalize_lenient(root)) {
152                (Some(path), Some(root)) => path.starts_with(&root),
153                _ => false,
154            }
155        });
156    }
157    let Some(canonical_path) = canonicalize_lenient(path) else {
158        return false;
159    };
160    roots.iter().any(|root| {
161        canonicalize_lenient(root)
162            .is_some_and(|canonical_root| canonical_path.starts_with(&canonical_root))
163    })
164}
165
166/// Serializes the daemon's bound/unbound transition with admission of deferred
167/// root work. The lock covers only the bounded decision and worker-start commit;
168/// call sites must not wait for worker completion or run a scan while holding it.
169#[derive(Clone, Default)]
170pub(crate) struct SubcLifecycleAdmission {
171    unbound: Arc<parking_lot::Mutex<bool>>,
172}
173
174impl SubcLifecycleAdmission {
175    fn mark_bound(&self) {
176        *self.unbound.lock() = false;
177    }
178
179    fn mark_unbound(&self, configure_generation: &AtomicU64) {
180        let mut unbound = self.unbound.lock();
181        if !*unbound {
182            *unbound = true;
183            configure_generation.fetch_add(1, Ordering::SeqCst);
184        }
185    }
186
187    pub(crate) fn is_current(&self, generation: &AtomicU64, expected: u64) -> bool {
188        let unbound = self.unbound.lock();
189        !*unbound && generation.load(Ordering::SeqCst) == expected
190    }
191
192    fn advance_generation(&self, generation: &AtomicU64) -> u64 {
193        let _unbound = self.unbound.lock();
194        generation.fetch_add(1, Ordering::SeqCst).wrapping_add(1)
195    }
196
197    pub(crate) fn run_if_current<R>(
198        &self,
199        generation: &AtomicU64,
200        expected: u64,
201        action: impl FnOnce() -> R,
202    ) -> Option<R> {
203        let unbound = self.unbound.lock();
204        if *unbound || generation.load(Ordering::SeqCst) != expected {
205            return None;
206        }
207        Some(action())
208    }
209
210    pub(crate) fn is_bound(&self) -> bool {
211        !*self.unbound.lock()
212    }
213
214    fn try_is_bound(&self) -> Option<bool> {
215        self.unbound.try_lock().map(|unbound| !*unbound)
216    }
217
218    fn is_unbound(&self) -> bool {
219        !self.is_bound()
220    }
221
222    fn run_if_unbound<R>(&self, action: impl FnOnce() -> R) -> Option<R> {
223        let unbound = self.unbound.lock();
224        if !*unbound {
225            return None;
226        }
227        Some(action())
228    }
229}
230
231const GRACEFUL_SHUTDOWN_SEARCH_BUILD_WAIT: Duration = Duration::from_secs(5);
232const GRACEFUL_SHUTDOWN_SEARCH_BUILD_POLL: Duration = Duration::from_millis(10);
233
234/// Agent status-bar counts — the IDE-style "status bar" surfaced to the agent
235/// on every tool result (emit-on-change). `errors`/`warnings` are read LIVE
236/// from the continuously-drained LSP diagnostics store; the Tier-2 counts
237/// (`dead_code`/`unused_exports`/`duplicates`) and `todos` are last-known,
238/// refreshed when `aft_inspect` runs or a background Tier-2 scan completes.
239/// `tier2_stale` marks the Tier-2 counts as not-yet-reconciled with the latest
240/// edits (rendered with a `~` marker so the agent never reads them as live).
241#[derive(Debug, Clone, Default, PartialEq, Eq)]
242pub struct StatusBarCounts {
243    pub errors: usize,
244    pub warnings: usize,
245    pub dead_code: usize,
246    pub unused_exports: usize,
247    pub duplicates: usize,
248    pub todos: usize,
249    pub tier2_stale: bool,
250}
251
252/// Last-known Tier-2 + todos counts, refreshed off the hot path. `errors` and
253/// `warnings` are intentionally NOT cached here — they're read live per attach.
254///
255/// Each Tier-2 category is `Option`: `None` means "no scan has ever produced a
256/// count for this category", so we never fabricate a `0`. The bar is only
257/// surfaced once all three Tier-2 categories hold a real value — a partially
258/// completed cold scan (e.g. dead_code done, unused_exports/duplicates still
259/// running) must not render `D<real> U0 C0` and lie about project health (#1).
260#[derive(Debug, Clone, Default)]
261struct StatusBarTier2 {
262    dead_code: Option<usize>,
263    unused_exports: Option<usize>,
264    duplicates: Option<usize>,
265    todos: Option<usize>,
266    stale: bool,
267    generation: u64,
268    /// True when the latest dead_code aggregate reported `callgraph_available:
269    /// false` (the callgraph store was not ready when dead_code scanned). Health
270    /// uses this to tell "tier2 still building" apart from "tier2 complete except
271    /// dead_code, which is blocked on the callgraph store" — the latter must not
272    /// report "building" forever, because nothing recomputes dead_code until the
273    /// callgraph store becomes ready.
274    dead_code_blocked_on_callgraph: bool,
275}
276
277#[derive(Debug, Clone, Default)]
278struct StatusBarCache {
279    valid: bool,
280    diagnostics_generation: u64,
281    tier2_generation: u64,
282    tsconfig_generation: u64,
283    counts: Option<StatusBarCounts>,
284}
285
286#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
287#[serde(rename_all = "snake_case")]
288pub enum RootHealthState {
289    Ready,
290    Busy,
291}
292
293#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
294pub struct HealthComponentSnapshot {
295    pub status: &'static str,
296}
297
298#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
299pub struct Tier2HealthSnapshot {
300    pub status: &'static str,
301}
302
303#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
304pub struct RootHealthSnapshot {
305    pub project_root: String,
306    pub actor_count: usize,
307    pub state: RootHealthState,
308    #[serde(skip_serializing_if = "Option::is_none")]
309    pub search_index: Option<HealthComponentSnapshot>,
310    #[serde(skip_serializing_if = "Option::is_none")]
311    pub semantic_index: Option<HealthComponentSnapshot>,
312    #[serde(skip_serializing_if = "Option::is_none")]
313    pub callgraph_store: Option<HealthComponentSnapshot>,
314    #[serde(skip_serializing_if = "Option::is_none")]
315    pub tier2: Option<Tier2HealthSnapshot>,
316    #[serde(skip_serializing_if = "Option::is_none")]
317    pub bash: Option<BgTaskHealthCounts>,
318}
319
320impl RootHealthSnapshot {
321    fn busy(project_root: &Path) -> Self {
322        Self {
323            project_root: project_root.display().to_string(),
324            actor_count: 1,
325            state: RootHealthState::Busy,
326            search_index: None,
327            semantic_index: None,
328            callgraph_store: None,
329            tier2: None,
330            bash: None,
331        }
332    }
333
334    pub fn is_fully_ready(&self) -> bool {
335        let component_is_satisfied =
336            |status: &HealthComponentSnapshot| matches!(status.status, "ready" | "disabled");
337        let tier2_is_satisfied =
338            |tier2: &Tier2HealthSnapshot| matches!(tier2.status, "ready" | "disabled");
339
340        matches!(self.state, RootHealthState::Ready)
341            && self
342                .search_index
343                .as_ref()
344                .is_some_and(component_is_satisfied)
345            && self
346                .semantic_index
347                .as_ref()
348                .is_some_and(component_is_satisfied)
349            && self
350                .callgraph_store
351                .as_ref()
352                .is_some_and(component_is_satisfied)
353            && self.tier2.as_ref().is_some_and(tier2_is_satisfied)
354    }
355}
356
357pub struct StatusEmitter {
358    latest: Arc<Mutex<Option<StatusPayload>>>,
359    notify: mpsc::Sender<()>,
360}
361
362#[derive(Clone, Debug, Default)]
363struct ConfigureWarmState {
364    generation: u64,
365    key: Option<String>,
366}
367
368#[derive(Debug)]
369struct ConfigurePhaseTiming {
370    phase: &'static str,
371    started_at: Instant,
372    completed: Vec<(&'static str, Duration)>,
373}
374
375impl Default for ConfigurePhaseTiming {
376    fn default() -> Self {
377        Self {
378            phase: "idle",
379            started_at: Instant::now(),
380            completed: Vec::new(),
381        }
382    }
383}
384
385#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
386pub(crate) enum WatcherDrainApplyPhase {
387    #[default]
388    PendingTier2,
389    PendingIndexes,
390    SymbolCache,
391    Callgraph,
392    SearchIndex,
393    SemanticIndex,
394    LspDiagnostics,
395    Complete,
396}
397
398#[derive(Debug, Default)]
399pub(crate) enum WatcherDrainPhase {
400    #[default]
401    Collect,
402    Apply {
403        stage: WatcherDrainApplyPhase,
404        paths: VecDeque<PathBuf>,
405        remaining: usize,
406        oversized_inline_batch: bool,
407    },
408}
409
410#[derive(Debug)]
411pub(crate) struct WatcherDrainSliceState {
412    pub(crate) configure_generation: u64,
413    /// Content identity of the configuration this continuation was built
414    /// under. A lifecycle-only generation change (route unbind/rebind with an
415    /// equivalent config) preserves the continuation by REBASING it onto the
416    /// new generation; a content change discards it (the new configuration
417    /// rebuilds artifacts wholesale).
418    pub(crate) configure_content_generation: u64,
419    pub(crate) phase: WatcherDrainPhase,
420    pub(crate) pending_paths: VecDeque<PathBuf>,
421    pub(crate) ignore_changed: bool,
422    pub(crate) rescan_required: bool,
423    pub(crate) status_changed: bool,
424    pub(crate) scheduler_changed_path_count: usize,
425    pub(crate) semantic_refresh_paths: Vec<PathBuf>,
426    pub(crate) path_slice_count: usize,
427}
428
429/// Pending watcher-derived reconciliation state taken out of the context for
430/// a transactional TTL teardown: committed (dropped) once eviction succeeds,
431/// restored when a secondary blocker aborts the eviction.
432pub(crate) struct PendingReconciliationState {
433    search: BTreeSet<PathBuf>,
434    callgraph: BTreeSet<PathBuf>,
435    tier2: BTreeSet<PathBuf>,
436    semantic: BTreeSet<PathBuf>,
437    corpus_refresh: bool,
438}
439
440impl WatcherDrainSliceState {
441    pub(crate) fn new(configure_generation: u64, configure_content_generation: u64) -> Self {
442        Self {
443            configure_generation,
444            configure_content_generation,
445            phase: WatcherDrainPhase::Collect,
446            pending_paths: VecDeque::new(),
447            ignore_changed: false,
448            rescan_required: false,
449            status_changed: false,
450            scheduler_changed_path_count: 0,
451            semantic_refresh_paths: Vec::new(),
452            path_slice_count: 0,
453        }
454    }
455
456    pub(crate) fn has_pending_work(&self) -> bool {
457        !matches!(self.phase, WatcherDrainPhase::Collect)
458            || !self.pending_paths.is_empty()
459            || self.ignore_changed
460            || self.rescan_required
461    }
462}
463
464#[doc(hidden)]
465pub enum CallGraphStoreBuildEvent {
466    Ready {
467        store: CallGraphStore,
468        fulfilled_force_token: Option<u64>,
469        publication_epoch: u64,
470    },
471    Settled,
472}
473
474struct CallGraphStoreBuildSettlement {
475    tx: crossbeam_channel::Sender<CallGraphStoreBuildEvent>,
476    sent: bool,
477    force_token: Option<u64>,
478    publication_epoch: u64,
479}
480
481impl CallGraphStoreBuildSettlement {
482    fn new(
483        tx: crossbeam_channel::Sender<CallGraphStoreBuildEvent>,
484        force_token: Option<u64>,
485        publication_epoch: u64,
486    ) -> Self {
487        Self {
488            tx,
489            sent: false,
490            force_token,
491            publication_epoch,
492        }
493    }
494
495    fn ready(&mut self, store: CallGraphStore) {
496        let _ = self.tx.send(CallGraphStoreBuildEvent::Ready {
497            store,
498            fulfilled_force_token: self.force_token,
499            publication_epoch: self.publication_epoch,
500        });
501        self.sent = true;
502    }
503}
504
505impl Drop for CallGraphStoreBuildSettlement {
506    fn drop(&mut self) {
507        if !self.sent {
508            let _ = self.tx.send(CallGraphStoreBuildEvent::Settled);
509        }
510    }
511}
512
513#[derive(Clone, Debug)]
514pub(crate) struct ConfigureMaintenanceJob {
515    pub(crate) generation: u64,
516    pub(crate) root_path: PathBuf,
517    pub(crate) canonical_cache_root: PathBuf,
518    pub(crate) harness: Harness,
519    pub(crate) storage_root: PathBuf,
520    pub(crate) harness_dir: PathBuf,
521    pub(crate) session_id: String,
522    pub(crate) home_match: bool,
523    pub(crate) format_tool_cache_clear_needed: bool,
524    pub(crate) run_bash_replay: bool,
525    pub(crate) refresh_project_runtime: bool,
526    pub(crate) sync_bash_compress_flag: bool,
527    pub(crate) reset_filter_registry: bool,
528    pub(crate) clear_failed_spawns: bool,
529    pub(crate) warm_callgraph_store: bool,
530    /// Advance disk-publication epochs in the post-ack configure tail. This can
531    /// wait for an already-committing writer, so it must never run on bind.
532    pub(crate) supersede_artifact_persistence: bool,
533    /// One-shot gates for artifact workers created during configure. The
534    /// configure tail opens them only after the bind response has been produced.
535    pub(crate) artifact_load_starts: Vec<crossbeam_channel::Sender<()>>,
536}
537
538impl StatusEmitter {
539    fn new(progress_sender: SharedProgressSender) -> Self {
540        let (notify, rx) = mpsc::channel();
541        let latest = Arc::new(Mutex::new(None));
542        let latest_for_thread = Arc::clone(&latest);
543        std::thread::spawn(move || {
544            status_debounce_loop(rx, latest_for_thread, progress_sender);
545        });
546        Self { latest, notify }
547    }
548
549    pub fn signal(&self, snapshot: StatusPayload) {
550        if let Ok(mut latest) = self.latest.lock() {
551            *latest = Some(snapshot);
552        }
553        let _ = self.notify.send(());
554    }
555}
556
557fn status_debounce_loop(
558    rx: mpsc::Receiver<()>,
559    latest: Arc<Mutex<Option<StatusPayload>>>,
560    progress_sender: SharedProgressSender,
561) {
562    while rx.recv().is_ok() {
563        let deadline = Instant::now() + Duration::from_millis(STATUS_DEBOUNCE_MS);
564        while let Some(remaining) = deadline.checked_duration_since(Instant::now()) {
565            match rx.recv_timeout(remaining) {
566                Ok(()) => continue,
567                Err(mpsc::RecvTimeoutError::Timeout) => break,
568                Err(mpsc::RecvTimeoutError::Disconnected) => return,
569            }
570        }
571
572        let snapshot = latest.lock().ok().and_then(|mut latest| latest.take());
573        let Some(snapshot) = snapshot else { continue };
574        let sender = progress_sender
575            .lock()
576            .ok()
577            .and_then(|sender| sender.clone());
578        if let Some(sender) = sender {
579            sender(PushFrame::StatusChanged(StatusChangedFrame::new(
580                None, snapshot,
581            )));
582        }
583    }
584}
585use crate::cache_freshness::FileFreshness;
586use crate::search_index::SearchIndex;
587use crate::semantic_index::{EmbeddingEntry, SemanticIndex};
588
589// `SemanticIndexStatus::Ready` exposes a unique `refreshing` path list. Keep
590// per-path queue accounting separately so repeated edits to the same file do not
591// let an older refresh completion remove the path while newer work is pending.
592#[derive(Debug, Default, Clone)]
593#[doc(hidden)]
594pub struct SemanticRefreshAccounting {
595    #[doc(hidden)]
596    pub pending: usize,
597    #[doc(hidden)]
598    pub in_flight: usize,
599}
600
601#[derive(Debug, Default)]
602struct SemanticRefreshCircuit {
603    consecutive_transient_failures: AtomicUsize,
604    open: AtomicBool,
605    probe_in_flight: AtomicBool,
606    probe_ready: AtomicBool,
607    probe_token: AtomicU64,
608}
609
610#[derive(Clone, Copy, Debug, Default)]
611pub(crate) struct SemanticColdSeedResume {
612    request_tier2: bool,
613    warm_callgraph: bool,
614}
615
616fn ensure_refreshing_path(refreshing: &mut Vec<PathBuf>, path: PathBuf) {
617    if !refreshing.iter().any(|existing| existing == &path) {
618        refreshing.push(path);
619        refreshing.sort();
620    }
621}
622
623fn remove_refreshing_path(refreshing: &mut Vec<PathBuf>, path: &Path) {
624    refreshing.retain(|existing| existing != path);
625}
626
627#[derive(Debug, Clone)]
628pub enum SemanticIndexStatus {
629    Disabled,
630    Building {
631        /// Cold-build only — index is not queryable.
632        stage: String,
633        files: Option<usize>,
634        entries_done: Option<usize>,
635        entries_total: Option<usize>,
636    },
637    Ready {
638        /// Files currently being re-embedded after recent edits. The index is
639        /// still queryable; results for these files may be temporarily missing.
640        refreshing: Vec<PathBuf>,
641        /// Per-root queue accounting for repeated refreshes of the same path.
642        /// Kept on the status value so two AppContexts in one process cannot
643        /// share refresh-completion state.
644        #[doc(hidden)]
645        accounting: BTreeMap<PathBuf, SemanticRefreshAccounting>,
646    },
647    Failed(String),
648}
649
650impl SemanticIndexStatus {
651    pub fn ready() -> Self {
652        Self::Ready {
653            refreshing: Vec::new(),
654            accounting: BTreeMap::new(),
655        }
656    }
657
658    pub fn add_refreshing_file(&mut self, path: PathBuf) {
659        if let Self::Ready {
660            refreshing,
661            accounting,
662        } = self
663        {
664            let state = accounting.entry(path.clone()).or_default();
665            state.pending = state.pending.saturating_add(1);
666            ensure_refreshing_path(refreshing, path);
667        }
668    }
669
670    pub fn start_refreshing_file(&mut self, path: PathBuf) {
671        if let Self::Ready {
672            refreshing,
673            accounting,
674        } = self
675        {
676            let state = accounting.entry(path.clone()).or_default();
677            if state.pending == 0 {
678                state.pending = 1;
679            }
680            if state.in_flight == 0 {
681                state.in_flight = state.pending;
682            }
683            ensure_refreshing_path(refreshing, path);
684        }
685    }
686
687    pub fn cancel_refreshing_file(&mut self, path: &Path) {
688        self.finish_refreshing_file(path, false);
689    }
690
691    /// Take every file currently tracked as refreshing, clearing the
692    /// accounting. Used when the refresh worker is cancelled outright: the
693    /// caller re-queues the paths for a replacement worker.
694    pub fn take_refreshing_files(&mut self) -> Vec<PathBuf> {
695        if let Self::Ready {
696            refreshing,
697            accounting,
698        } = self
699        {
700            accounting.clear();
701            std::mem::take(refreshing)
702        } else {
703            Vec::new()
704        }
705    }
706
707    /// True while a corpus-wide (not per-file) refresh is running.
708    pub fn corpus_refresh_in_flight(&self) -> bool {
709        matches!(self, Self::Building { stage, .. } if stage == "refreshing_corpus")
710    }
711
712    pub fn complete_refreshing_file(&mut self, path: &Path) {
713        self.finish_refreshing_file(path, true);
714    }
715
716    pub fn remove_refreshing_file(&mut self, path: &Path) {
717        self.complete_refreshing_file(path);
718    }
719
720    fn finish_refreshing_file(&mut self, path: &Path, complete_in_flight: bool) {
721        if let Self::Ready {
722            refreshing,
723            accounting,
724        } = self
725        {
726            let mut keep_refreshing = false;
727            if let Some(state) = accounting.get_mut(path) {
728                let finished = if complete_in_flight {
729                    state.in_flight.max(1)
730                } else {
731                    1
732                };
733                state.pending = state.pending.saturating_sub(finished);
734                if complete_in_flight {
735                    state.in_flight = 0;
736                } else {
737                    state.in_flight = state.in_flight.min(state.pending);
738                }
739                keep_refreshing = state.pending > 0;
740                if !keep_refreshing {
741                    accounting.remove(path);
742                }
743            }
744
745            if !keep_refreshing {
746                remove_refreshing_path(refreshing, path);
747            }
748        }
749    }
750
751    pub fn refreshing_count(&self) -> usize {
752        match self {
753            Self::Ready { refreshing, .. } => refreshing.len(),
754            _ => 0,
755        }
756    }
757}
758
759pub enum SemanticIndexEvent {
760    Progress {
761        stage: String,
762        files: Option<usize>,
763        entries_done: Option<usize>,
764        entries_total: Option<usize>,
765    },
766    /// Emitted when the semantic worker avoids or pauses full project corpus
767    /// collection before reaching terminal Ready/Failed, such as after loading a
768    /// cached index or while waiting to retry an embedding backend with no vectors
769    /// retained. Work that was waiting for the full index can proceed.
770    ColdSeedGateCleared,
771    Ready(SemanticIndex),
772    Failed(String),
773}
774
775#[derive(Debug, Clone)]
776pub enum SemanticRefreshRequest {
777    Files {
778        paths: Vec<PathBuf>,
779    },
780    /// Refresh the whole semantic corpus on the refresh worker. The worker owns
781    /// the project walk so watcher/configure drains never do corpus-scale work
782    /// on the single dispatch thread before scheduling embedding.
783    Corpus,
784}
785
786#[derive(Debug)]
787pub enum SemanticRefreshEvent {
788    Started {
789        paths: Vec<PathBuf>,
790    },
791    CorpusStarted {
792        files: usize,
793    },
794    Completed {
795        added_entries: Vec<EmbeddingEntry>,
796        updated_metadata: Vec<(PathBuf, FileFreshness)>,
797        completed_paths: Vec<PathBuf>,
798    },
799    CorpusCompleted {
800        index: SemanticIndex,
801        changed: usize,
802        added: usize,
803        deleted: usize,
804        total_processed: usize,
805    },
806    Failed {
807        paths: Vec<PathBuf>,
808        error: String,
809    },
810    CorpusFailed {
811        error: String,
812    },
813}
814
815pub(crate) struct ReceiverTerminalGuard {
816    terminal_epoch: Arc<AtomicU64>,
817    epoch: u64,
818}
819
820impl ReceiverTerminalGuard {
821    fn new(terminal_epoch: Arc<AtomicU64>, epoch: u64) -> Self {
822        Self {
823            terminal_epoch,
824            epoch,
825        }
826    }
827}
828
829impl Drop for ReceiverTerminalGuard {
830    fn drop(&mut self) {
831        self.terminal_epoch.fetch_max(self.epoch, Ordering::SeqCst);
832    }
833}
834
835pub type SemanticRefreshWorkerSlot = Arc<Mutex<Option<std::thread::JoinHandle<()>>>>;
836
837struct PathRestrictionContext {
838    raw_root: PathBuf,
839    resolved_root: PathBuf,
840    path_for_resolution: PathBuf,
841}
842
843/// Normalize a path by resolving `.` and `..` components lexically,
844/// without touching the filesystem. This prevents path traversal
845/// attacks when `fs::canonicalize` fails (e.g. for non-existent paths).
846fn normalize_path(path: &Path) -> PathBuf {
847    let mut result = PathBuf::new();
848    for component in path.components() {
849        match component {
850            Component::ParentDir => {
851                // Pop the last component unless we're at root or have no components
852                if !result.pop() {
853                    result.push(component);
854                }
855            }
856            Component::CurDir => {} // Skip `.`
857            _ => result.push(component),
858        }
859    }
860    result
861}
862
863fn resolve_with_existing_ancestors(path: &Path) -> PathBuf {
864    let mut existing = path.to_path_buf();
865    let mut tail_segments = Vec::new();
866
867    while !existing.exists() {
868        if let Some(name) = existing.file_name() {
869            tail_segments.push(name.to_owned());
870        } else {
871            break;
872        }
873
874        existing = match existing.parent() {
875            Some(parent) => parent.to_path_buf(),
876            None => break,
877        };
878    }
879
880    let mut resolved = std::fs::canonicalize(&existing).unwrap_or(existing);
881    for segment in tail_segments.into_iter().rev() {
882        resolved.push(segment);
883    }
884
885    resolved
886}
887
888fn path_error_response(
889    req_id: &str,
890    path: &Path,
891    resolved_root: &Path,
892) -> crate::protocol::Response {
893    crate::protocol::Response::error(
894        req_id,
895        "path_outside_root",
896        format!(
897            "path '{}' is outside the project root '{}'",
898            path.display(),
899            resolved_root.display()
900        ),
901    )
902}
903
904/// Walk `candidate` component-by-component. For any component that is a
905/// symlink on disk, iteratively follow the full chain (up to 40 hops) and
906/// reject if any hop's resolved target lies outside `resolved_root`.
907///
908/// This is the fallback path used when `fs::canonicalize` fails (e.g. on
909/// Linux with broken symlink chains pointing to non-existent destinations).
910/// On macOS `canonicalize` also fails for broken symlinks but the returned
911/// `/var/...` tempdir paths diverge from `resolved_root`'s `/private/var/...`
912/// form, so we must accept either form when deciding which symlinks to check.
913fn reject_escaping_symlink(
914    req_id: &str,
915    original_path: &Path,
916    candidate: &Path,
917    resolved_root: &Path,
918    raw_root: &Path,
919) -> Result<(), crate::protocol::Response> {
920    let mut current = PathBuf::new();
921
922    for component in candidate.components() {
923        current.push(component);
924
925        let Ok(metadata) = std::fs::symlink_metadata(&current) else {
926            continue;
927        };
928
929        if !metadata.file_type().is_symlink() {
930            continue;
931        }
932
933        // Only check symlinks that live inside the project root. This skips
934        // OS-level prefix symlinks (macOS /var → /private/var) that are not
935        // inside our project directory and whose "escaping" is harmless.
936        //
937        // We compare against BOTH the canonicalized root (resolved_root, e.g.
938        // /private/var/.../project) AND the raw root (e.g. /var/.../project)
939        // because tempdir() returns raw paths while fs::canonicalize returns
940        // the resolved form — and our `current` may be in either form.
941        let inside_root = current.starts_with(resolved_root) || current.starts_with(raw_root);
942        if !inside_root {
943            continue;
944        }
945
946        iterative_follow_chain(req_id, original_path, &current, resolved_root)?;
947    }
948
949    Ok(())
950}
951
952/// Iteratively follow a symlink chain from `link` and reject if any hop's
953/// resolved target is outside `resolved_root`. Depth-capped at 40 hops.
954fn iterative_follow_chain(
955    req_id: &str,
956    original_path: &Path,
957    start: &Path,
958    resolved_root: &Path,
959) -> Result<(), crate::protocol::Response> {
960    let mut link = start.to_path_buf();
961    let mut depth = 0usize;
962
963    loop {
964        if depth > 40 {
965            return Err(path_error_response(req_id, original_path, resolved_root));
966        }
967
968        let target = match std::fs::read_link(&link) {
969            Ok(t) => t,
970            Err(_) => {
971                // Can't read the link — treat as escaping to be safe.
972                return Err(path_error_response(req_id, original_path, resolved_root));
973            }
974        };
975
976        let resolved_target = if target.is_absolute() {
977            normalize_path(&target)
978        } else {
979            let parent = link.parent().unwrap_or_else(|| Path::new(""));
980            normalize_path(&parent.join(&target))
981        };
982
983        // Check boundary: use canonicalized target when available (handles
984        // macOS /var → /private/var aliasing), fall back to the normalized
985        // path when canonicalize fails (e.g. broken symlink on Linux).
986        let canonical_target =
987            std::fs::canonicalize(&resolved_target).unwrap_or_else(|_| resolved_target.clone());
988
989        if !canonical_target.starts_with(resolved_root)
990            && !resolved_target.starts_with(resolved_root)
991        {
992            return Err(path_error_response(req_id, original_path, resolved_root));
993        }
994
995        // If the target is itself a symlink, follow the next hop.
996        match std::fs::symlink_metadata(&resolved_target) {
997            Ok(meta) if meta.file_type().is_symlink() => {
998                link = resolved_target;
999                depth += 1;
1000            }
1001            _ => break, // Non-symlink or non-existent target — chain ends here.
1002        }
1003    }
1004
1005    Ok(())
1006}
1007
1008pub type LanguageProviderFactory = fn() -> Box<dyn LanguageProvider>;
1009
1010pub fn default_language_provider_factory() -> Box<dyn LanguageProvider> {
1011    Box::new(TreeSitterProvider::new())
1012}
1013
1014fn database_path_key(path: &Path) -> PathBuf {
1015    if let Ok(canonical) = std::fs::canonicalize(path) {
1016        return canonical;
1017    }
1018    let Some(parent) = path.parent() else {
1019        return path.to_path_buf();
1020    };
1021    let canonical_parent = std::fs::canonicalize(parent).unwrap_or_else(|_| parent.to_path_buf());
1022    path.file_name()
1023        .map(|name| canonical_parent.join(name))
1024        .unwrap_or_else(|| canonical_parent.join(path))
1025}
1026
1027/// Process-global services shared by all project actors in this AFT process.
1028///
1029/// `App` owns only true process services. Per-root caches and the live
1030/// language provider instance stay in [`AppContext`].
1031pub struct App {
1032    /// One process-wide handle for the current AFT database. Every project
1033    /// actor points at this handle so roots do not open duplicate SQLite/WAL
1034    /// descriptors for the same database.
1035    db: parking_lot::Mutex<Option<(PathBuf, Arc<Mutex<Connection>>)>>,
1036    active_watchers: AtomicUsize,
1037    active_actor_roots: AtomicUsize,
1038    open_routes: AtomicUsize,
1039    lsp_child_registry: crate::lsp::child_registry::LspChildRegistry,
1040    stdout_writer: SharedStdoutWriter,
1041    provider_factory: LanguageProviderFactory,
1042    /// Weak actor references let status attribute process RSS across roots
1043    /// without making the process-global App own per-root caches.
1044    memory_contexts: parking_lot::Mutex<BTreeMap<PathBuf, Weak<AppContext>>>,
1045}
1046
1047impl App {
1048    pub fn new(provider_factory: LanguageProviderFactory) -> Self {
1049        Self {
1050            db: parking_lot::Mutex::new(None),
1051            active_watchers: AtomicUsize::new(0),
1052            active_actor_roots: AtomicUsize::new(0),
1053            open_routes: AtomicUsize::new(0),
1054            lsp_child_registry: crate::lsp::child_registry::LspChildRegistry::new(),
1055            stdout_writer: Arc::new(Mutex::new(BufWriter::new(io::stdout()))),
1056            provider_factory,
1057            memory_contexts: parking_lot::Mutex::new(BTreeMap::new()),
1058        }
1059    }
1060
1061    /// Create the shared process `App` handle required by the actor split.
1062    pub fn shared(provider_factory: LanguageProviderFactory) -> Arc<Self> {
1063        Arc::new(Self::new(provider_factory))
1064    }
1065
1066    pub fn default_shared() -> Arc<Self> {
1067        Self::shared(default_language_provider_factory)
1068    }
1069
1070    pub fn create_provider(&self) -> Box<dyn LanguageProvider> {
1071        (self.provider_factory)()
1072    }
1073
1074    pub fn lsp_child_registry(&self) -> crate::lsp::child_registry::LspChildRegistry {
1075        self.lsp_child_registry.clone()
1076    }
1077
1078    pub fn stdout_writer(&self) -> SharedStdoutWriter {
1079        Arc::clone(&self.stdout_writer)
1080    }
1081
1082    pub(crate) fn register_memory_context(&self, root: PathBuf, ctx: &Arc<AppContext>) {
1083        let mut contexts = self.memory_contexts.lock();
1084        contexts.retain(|_, context| context.strong_count() > 0);
1085        contexts.insert(root, Arc::downgrade(ctx));
1086    }
1087
1088    pub(crate) fn unregister_memory_context(&self, root: &Path, ctx: &Arc<AppContext>) {
1089        let mut contexts = self.memory_contexts.lock();
1090        let removes_current = contexts
1091            .get(root)
1092            .and_then(Weak::upgrade)
1093            .is_some_and(|registered| Arc::ptr_eq(&registered, ctx));
1094        if removes_current {
1095            contexts.remove(root);
1096        }
1097    }
1098
1099    /// Snapshot process roots without waiting behind actor registration. A busy
1100    /// registry is surfaced as a named status gap by the memory snapshot.
1101    pub(crate) fn try_memory_contexts(&self) -> Option<Vec<(PathBuf, Arc<AppContext>)>> {
1102        let contexts = self.memory_contexts.try_lock()?;
1103        Some(
1104            contexts
1105                .iter()
1106                .filter_map(|(root, context)| {
1107                    context.upgrade().map(|context| (root.clone(), context))
1108                })
1109                .collect(),
1110        )
1111    }
1112
1113    /// Return the process-shared database handle, opening it only when the
1114    /// requested path is not already resident. The connection mutex serializes
1115    /// transactions from all roots; callers never hold the App lock while using
1116    /// the returned connection.
1117    pub fn open_db(&self, path: &Path) -> Result<Arc<Mutex<Connection>>, crate::db::OpenError> {
1118        let key = database_path_key(path);
1119        let mut slot = self.db.lock();
1120        if let Some((existing_path, conn)) = slot.as_ref() {
1121            if existing_path == &key {
1122                return Ok(Arc::clone(conn));
1123            }
1124        }
1125
1126        let conn = Arc::new(Mutex::new(crate::db::open(path)?));
1127        *slot = Some((key, Arc::clone(&conn)));
1128        Ok(conn)
1129    }
1130
1131    pub fn set_db(&self, conn: Arc<Mutex<Connection>>) {
1132        *self.db.lock() = Some((PathBuf::new(), conn));
1133    }
1134
1135    pub fn clear_db(&self) {
1136        *self.db.lock() = None;
1137    }
1138
1139    /// Clear the shared handle only when it still refers to `path`. A failed
1140    /// reconfigure for one root must not tear down a database used by another
1141    /// root.
1142    pub fn clear_db_for_path(&self, path: &Path) {
1143        let key = database_path_key(path);
1144        let mut slot = self.db.lock();
1145        if slot.as_ref().is_some_and(|(existing_path, _)| {
1146            existing_path.as_os_str().is_empty() || existing_path == &key
1147        }) {
1148            *slot = None;
1149        }
1150    }
1151
1152    pub fn db(&self) -> Option<Arc<Mutex<Connection>>> {
1153        self.db.lock().as_ref().map(|(_, conn)| Arc::clone(conn))
1154    }
1155
1156    pub(crate) fn watcher_started(&self) {
1157        self.active_watchers.fetch_add(1, Ordering::SeqCst);
1158    }
1159
1160    pub(crate) fn watcher_stopped(&self) {
1161        self.active_watchers
1162            .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |count| {
1163                Some(count.saturating_sub(1))
1164            })
1165            .ok();
1166    }
1167
1168    /// Number of live watcher filter runtimes registered by this process.
1169    /// A runtime remains counted until its OS watcher thread has actually exited.
1170    pub fn watcher_count(&self) -> usize {
1171        self.active_watchers.load(Ordering::SeqCst)
1172    }
1173
1174    pub(crate) fn actor_root_registered(&self) {
1175        self.active_actor_roots.fetch_add(1, Ordering::SeqCst);
1176    }
1177
1178    pub(crate) fn actor_root_unregistered(&self) {
1179        self.active_actor_roots
1180            .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |count| {
1181                Some(count.saturating_sub(1))
1182            })
1183            .ok();
1184    }
1185
1186    pub fn actor_root_count(&self) -> usize {
1187        self.active_actor_roots.load(Ordering::SeqCst)
1188    }
1189
1190    pub(crate) fn set_open_route_count(&self, count: usize) {
1191        self.open_routes.store(count, Ordering::SeqCst);
1192    }
1193
1194    pub fn open_route_count(&self) -> usize {
1195        self.open_routes.load(Ordering::SeqCst)
1196    }
1197}
1198
1199impl Default for App {
1200    fn default() -> Self {
1201        Self::new(default_language_provider_factory)
1202    }
1203}
1204
1205const _: fn() = || {
1206    fn assert_send_sync<T: Send + Sync>() {}
1207    fn assert_send<T: Send>() {}
1208
1209    assert_send_sync::<App>();
1210    assert_send_sync::<AppContext>();
1211    assert_send::<crate::lsp::manager::LspManager>();
1212    assert_send::<crate::semantic_index::EmbeddingModel>();
1213};
1214
1215#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1216enum GitEntryKind {
1217    Missing,
1218    File,
1219    Directory,
1220    Other,
1221}
1222
1223#[derive(Clone, Debug, PartialEq, Eq)]
1224struct GitEntrySignature {
1225    kind: GitEntryKind,
1226    modified: Option<SystemTime>,
1227}
1228
1229#[derive(Clone, Debug)]
1230struct WorktreeBridgeCacheEntry {
1231    git_entry: GitEntrySignature,
1232    is_worktree_bridge: bool,
1233    git_common_dir: Option<PathBuf>,
1234}
1235
1236pub(crate) const BORROWED_INDEX_CACHE_CAPACITY: usize = 4;
1237
1238#[derive(Clone, Debug, PartialEq, Eq)]
1239struct BorrowedIndexCacheKey {
1240    canonical_root: PathBuf,
1241    artifact: crate::readonly_artifacts::BorrowedArtifactGeneration,
1242}
1243
1244#[derive(Clone, Debug)]
1245enum BorrowedIndexCacheValue {
1246    Search(crate::readonly_artifacts::ReadOnlyArtifact<Arc<SearchIndex>>),
1247    Semantic(crate::readonly_artifacts::ReadOnlyArtifact<Arc<SemanticIndex>>),
1248}
1249
1250#[derive(Debug, Default)]
1251struct BorrowedIndexCache {
1252    entries: VecDeque<(BorrowedIndexCacheKey, BorrowedIndexCacheValue)>,
1253    resolved_roots: VecDeque<(PathBuf, GitEntrySignature)>,
1254}
1255
1256impl BorrowedIndexCache {
1257    fn search(
1258        &mut self,
1259        key: &BorrowedIndexCacheKey,
1260    ) -> Option<crate::readonly_artifacts::ReadOnlyArtifact<Arc<SearchIndex>>> {
1261        let position = self.entries.iter().position(|(candidate, value)| {
1262            candidate == key && matches!(value, BorrowedIndexCacheValue::Search(_))
1263        })?;
1264        let entry = self.entries.remove(position)?;
1265        let BorrowedIndexCacheValue::Search(index) = &entry.1 else {
1266            return None;
1267        };
1268        let index = (*index).clone();
1269        self.entries.push_back(entry);
1270        Some(index)
1271    }
1272
1273    fn semantic(
1274        &mut self,
1275        key: &BorrowedIndexCacheKey,
1276    ) -> Option<crate::readonly_artifacts::ReadOnlyArtifact<Arc<SemanticIndex>>> {
1277        let position = self.entries.iter().position(|(candidate, value)| {
1278            candidate == key && matches!(value, BorrowedIndexCacheValue::Semantic(_))
1279        })?;
1280        let entry = self.entries.remove(position)?;
1281        let BorrowedIndexCacheValue::Semantic(index) = &entry.1 else {
1282            return None;
1283        };
1284        let index = (*index).clone();
1285        self.entries.push_back(entry);
1286        Some(index)
1287    }
1288
1289    fn insert(&mut self, key: BorrowedIndexCacheKey, value: BorrowedIndexCacheValue) {
1290        self.entries.retain(|(candidate, _)| {
1291            candidate.canonical_root != key.canonical_root
1292                || candidate.artifact.path != key.artifact.path
1293        });
1294        self.entries.push_back((key, value));
1295        while self.entries.len() > BORROWED_INDEX_CACHE_CAPACITY {
1296            self.entries.pop_front();
1297        }
1298    }
1299
1300    fn resolved_root(&mut self, requested_root: &Path) -> Option<PathBuf> {
1301        let position = self
1302            .resolved_roots
1303            .iter()
1304            .position(|(candidate, _)| candidate == requested_root)?;
1305        let entry = self.resolved_roots.remove(position)?;
1306        if entry.1 != git_entry_signature(requested_root) {
1307            return None;
1308        }
1309        let root = entry.0.clone();
1310        self.resolved_roots.push_back(entry);
1311        Some(root)
1312    }
1313
1314    fn remember_resolved_root(&mut self, root: PathBuf) {
1315        self.resolved_roots
1316            .retain(|(candidate, _)| candidate != &root);
1317        let signature = git_entry_signature(&root);
1318        self.resolved_roots.push_back((root, signature));
1319        while self.resolved_roots.len() > BORROWED_INDEX_CACHE_CAPACITY {
1320            self.resolved_roots.pop_front();
1321        }
1322    }
1323
1324    fn clear(&mut self) {
1325        self.entries.clear();
1326        self.resolved_roots.clear();
1327    }
1328}
1329
1330fn git_entry_signature(project_root: &Path) -> GitEntrySignature {
1331    match std::fs::symlink_metadata(project_root.join(".git")) {
1332        Ok(metadata) => GitEntrySignature {
1333            kind: if metadata.file_type().is_file() {
1334                GitEntryKind::File
1335            } else if metadata.file_type().is_dir() {
1336                GitEntryKind::Directory
1337            } else {
1338                GitEntryKind::Other
1339            },
1340            modified: metadata.modified().ok(),
1341        },
1342        Err(error) if error.kind() == io::ErrorKind::NotFound => GitEntrySignature {
1343            kind: GitEntryKind::Missing,
1344            modified: None,
1345        },
1346        Err(_) => GitEntrySignature {
1347            kind: GitEntryKind::Other,
1348            modified: None,
1349        },
1350    }
1351}
1352
1353/// Shared application context threaded through all command handlers.
1354///
1355/// Holds the language provider, backup/checkpoint stores, and configuration.
1356/// Constructed once at startup and passed by
1357/// reference to `dispatch`.
1358///
1359/// Write-rarely stores use `parking_lot::Mutex` for interior mutability so this
1360/// context can become thread-safe while preserving the current single-request
1361/// dispatch behavior. `config` is a thread-safe owned snapshot so future
1362/// read-only dispatch can hold configuration across other work without holding
1363/// a lock guard.
1364pub struct AppContext {
1365    app: Arc<App>,
1366    provider: Box<dyn LanguageProvider>,
1367    backup: parking_lot::Mutex<BackupStore>,
1368    checkpoint: parking_lot::Mutex<CheckpointStore>,
1369    config: RwLock<Arc<Config>>,
1370    force_restrict_requests: parking_lot::Mutex<BTreeMap<String, usize>>,
1371    pub harness: parking_lot::Mutex<Option<Harness>>,
1372    canonical_cache_root: parking_lot::Mutex<Option<PathBuf>>,
1373    is_worktree_bridge: parking_lot::Mutex<bool>,
1374    git_common_dir: parking_lot::Mutex<Option<PathBuf>>,
1375    shared_artifacts_read_only: AtomicBool,
1376    callgraph_writer: AtomicBool,
1377    inspect_writer: AtomicBool,
1378    artifact_owner_status: parking_lot::Mutex<Option<ArtifactOwnerStatus>>,
1379    artifact_owner_lease: parking_lot::Mutex<Option<ArtifactOwnerLeaseRegistration>>,
1380    /// Reasons (if any) why heavy AFT subsystems were auto-disabled for the
1381    /// current project root. Populated by `handle_configure` based on the
1382    /// canonical project root. Each reason is a stable machine-readable string
1383    /// (e.g. `"home_root"`, `"watcher_unavailable"`) so the plugin can render
1384    /// distinct degraded-mode UI states without re-deriving the reason locally.
1385    /// Empty when the project is healthy / full-featured.
1386    degraded_reasons: parking_lot::Mutex<Vec<String>>,
1387    /// Configure-time gate for project-wide scans, builds, and watcher-driven
1388    /// refreshes that would otherwise walk the whole root. `handle_configure`
1389    /// closes it for degraded home roots and every heavy-work entry point reads
1390    /// the same atomic so the decision cannot drift after configure returns.
1391    heavy_root_work_allowed: Arc<AtomicBool>,
1392    callgraph_store: RwLock<Option<Arc<ReadonlyCallGraphStore>>>,
1393    callgraph_store_force_requested: AtomicU64,
1394    callgraph_store_force_fulfilled: AtomicU64,
1395    callgraph_store_rx:
1396        parking_lot::Mutex<Option<crossbeam_channel::Receiver<CallGraphStoreBuildEvent>>>,
1397    callgraph_store_rx_generation: AtomicU64,
1398    callgraph_store_rx_epoch: AtomicU64,
1399    callgraph_persist_epoch: crate::root_cache::ArtifactPublishEpoch,
1400    callgraph_legacy_migration_summary_logged: Arc<AtomicBool>,
1401    pending_callgraph_store_paths: crate::callgraph_store::PendingCallGraphStorePaths,
1402    search_index: RwLock<Option<SearchIndex>>,
1403    search_index_rx: RwLock<Option<crossbeam_channel::Receiver<SearchIndex>>>,
1404    search_index_rx_generation: AtomicU64,
1405    search_index_rx_epoch: AtomicU64,
1406    search_index_rx_terminal_epoch: Arc<AtomicU64>,
1407    /// `(configure_generation, automatic_replacement_attempts)`. Caps the
1408    /// drain-path replacement of a search-index load whose worker disconnected
1409    /// without delivering an index, so a persistently failing worker cannot be
1410    /// relaunched in a loop on the drain thread. Resets when the configure
1411    /// generation advances.
1412    search_index_disconnect_reschedule: parking_lot::Mutex<(u64, u32)>,
1413    search_persist_epoch: crate::root_cache::ArtifactPublishEpoch,
1414    pending_search_index_paths: parking_lot::Mutex<BTreeSet<PathBuf>>,
1415    symbol_cache: SharedSymbolCache,
1416    inspect_manager: Arc<InspectManager>,
1417    tier2_refresh_scheduler: parking_lot::Mutex<Tier2RefreshScheduler>,
1418    pending_tier2_paths: parking_lot::Mutex<BTreeSet<PathBuf>>,
1419    semantic_index: RwLock<Option<SemanticIndex>>,
1420    semantic_index_rx: parking_lot::Mutex<Option<crossbeam_channel::Receiver<SemanticIndexEvent>>>,
1421    semantic_index_rx_generation: AtomicU64,
1422    semantic_index_rx_epoch: AtomicU64,
1423    semantic_index_rx_terminal_epoch: Arc<AtomicU64>,
1424    semantic_persist_epoch: crate::root_cache::ArtifactPublishEpoch,
1425    semantic_persist_lock: Arc<parking_lot::Mutex<()>>,
1426    semantic_index_status: RwLock<SemanticIndexStatus>,
1427    /// Serializes missing-artifact checks with receiver installation so
1428    /// concurrent fallback queries cannot start duplicate reload workers.
1429    artifact_reload_lock: parking_lot::Mutex<()>,
1430    /// True while this context has a cold semantic seed scheduled or actively
1431    /// collecting/embedding/persisting the full project corpus. The semantic
1432    /// worker clears it as soon as it proves the cached/incremental path is in use.
1433    semantic_cold_seed_active: Arc<AtomicBool>,
1434    /// Monotonic generation that prevents a superseded semantic worker from
1435    /// reopening the cold-seed gate after a later configure has reset it.
1436    semantic_cold_seed_generation: Arc<AtomicU64>,
1437    semantic_fingerprint_generation: Arc<AtomicU64>,
1438    semantic_callgraph_warm_deferred: AtomicBool,
1439    pending_semantic_index_paths: Arc<parking_lot::Mutex<BTreeSet<PathBuf>>>,
1440    pending_semantic_corpus_refresh: parking_lot::Mutex<bool>,
1441    semantic_refresh_tx:
1442        Arc<parking_lot::Mutex<Option<crossbeam_channel::Sender<SemanticRefreshRequest>>>>,
1443    semantic_refresh_event_rx:
1444        parking_lot::Mutex<Option<crossbeam_channel::Receiver<SemanticRefreshEvent>>>,
1445    semantic_refresh_generation: AtomicU64,
1446    semantic_refresh_epoch: AtomicU64,
1447    semantic_refresh_build_epoch: AtomicU64,
1448    semantic_refresh_worker: parking_lot::Mutex<Option<SemanticRefreshWorkerSlot>>,
1449    semantic_refresh_retry_attempts: parking_lot::Mutex<BTreeMap<PathBuf, usize>>,
1450    semantic_refresh_circuit: Arc<SemanticRefreshCircuit>,
1451    semantic_embedding_model: parking_lot::Mutex<Option<crate::semantic_index::EmbeddingModel>>,
1452    watcher_runtime_lock: parking_lot::Mutex<()>,
1453    watcher: parking_lot::Mutex<Option<RecommendedWatcher>>,
1454    watcher_rx: parking_lot::Mutex<Option<crossbeam_channel::Receiver<WatcherDispatchEvent>>>,
1455    watcher_drain_slice: parking_lot::Mutex<Option<WatcherDrainSliceState>>,
1456    watcher_thread: parking_lot::Mutex<Option<WatcherThreadHandle>>,
1457    lsp_manager: parking_lot::Mutex<LspManager>,
1458    configure_generation: Arc<AtomicU64>,
1459    /// Advances only when the warm configuration changes, not on route
1460    /// teardown. Already-admitted workers use it to decide whether their disk
1461    /// artifact is still configuration-compatible after becoming unbound.
1462    configure_content_generation: Arc<AtomicU64>,
1463    /// Set only by the daemon route lifecycle. Standalone contexts remain bound.
1464    /// Deferred maintenance uses the same gate for the state check and admission.
1465    subc_lifecycle: SubcLifecycleAdmission,
1466    configure_warm_state: parking_lot::Mutex<ConfigureWarmState>,
1467    configure_phase_timing: parking_lot::Mutex<ConfigurePhaseTiming>,
1468    configured_session_roots: parking_lot::Mutex<BTreeSet<(PathBuf, String)>>,
1469    configure_maintenance_jobs: parking_lot::Mutex<VecDeque<ConfigureMaintenanceJob>>,
1470    artifact_cache_keys: parking_lot::Mutex<BTreeMap<PathBuf, String>>,
1471    artifact_cache_key_derivations: AtomicU64,
1472    borrowed_index_cache: parking_lot::Mutex<BorrowedIndexCache>,
1473    /// Successful git worktree probes, keyed by canonical root and guarded by
1474    /// the root's `.git` entry shape and modification time.
1475    worktree_bridge_cache: parking_lot::Mutex<BTreeMap<PathBuf, WorktreeBridgeCacheEntry>>,
1476    #[cfg(test)]
1477    worktree_bridge_probe_spawns: AtomicU64,
1478    #[cfg(test)]
1479    force_worktree_bridge_reprobe: AtomicBool,
1480    /// Last-seen value of `InspectManager::reuse_completion_count()`, so the
1481    /// per-request inspect drain can detect watcher-driven Tier-2 scans that
1482    /// finished since the previous tick and refresh the status bar (#3).
1483    last_seen_reuse_completions: AtomicU64,
1484    configure_warnings_tx: crossbeam_channel::Sender<(u64, ConfigureWarningsFrame)>,
1485    configure_warnings_rx: crossbeam_channel::Receiver<(u64, ConfigureWarningsFrame)>,
1486    /// Per-context push sender slot. Status and background-bash emitters share
1487    /// this Arc so a sender installed after construction is observed at emit time.
1488    progress_sender: SharedProgressSender,
1489    status_emitter: StatusEmitter,
1490    /// Last status-bar payload attached to a tool response for this project root.
1491    /// Deduping here (not in a process-global static) lets daemon roots emit the
1492    /// same counts independently.
1493    status_bar_last_emitted: RwLock<Option<StatusBarCounts>>,
1494    status_bar_cached: RwLock<StatusBarCache>,
1495    compression_aggregates: Arc<crate::db::compression_events::CompressionAggregateCache>,
1496    bash_background: BgTaskRegistry,
1497    #[cfg(unix)]
1498    escalation_grants: parking_lot::Mutex<crate::sandbox_spawn::EscalationGrantStore>,
1499    /// Thread-safe registry of TOML output filters. Lazy-built on first
1500    /// access; populated atomically via `RwLock`. Shared between command
1501    /// handlers (which use it through `filter_registry()` -> read guard) and
1502    /// the `BgTaskRegistry` watchdog thread (which uses it through
1503    /// `compress::compress_with_registry`). Reloaded when configure changes
1504    /// the project root or storage_dir; see [`AppContext::reset_filter_registry`].
1505    filter_registry: crate::compress::SharedFilterRegistry,
1506    filter_registry_rebuild_count: AtomicU64,
1507    /// Set to true once the filter_registry has been populated. Avoids
1508    /// double-loading on hot paths without holding a write lock.
1509    filter_registry_loaded: std::sync::atomic::AtomicBool,
1510    /// Live `experimental.bash.compress` flag, kept in sync with `config`
1511    /// from the configure handler. Exposed via [`AppContext::bash_compress_flag`]
1512    /// so the BgTaskRegistry's watchdog-thread compressor can read it without
1513    /// holding the config refcell.
1514    bash_compress_flag: Arc<std::sync::atomic::AtomicBool>,
1515    /// Project gitignore matcher, rebuilt by [`AppContext::rebuild_gitignore`]
1516    /// whenever `project_root` changes or a watcher event reports a
1517    /// `.gitignore` write. Used by the watcher event filter to decide which
1518    /// path-changes are interesting to AFT's caches. `None` when no project
1519    /// root is configured or when the project has no gitignore files; in that
1520    /// case the watcher falls back to a small hardcoded infra-directory skip.
1521    gitignore: SharedGitignore,
1522    gitignore_generation: Arc<AtomicU64>,
1523    /// Last-known Tier-2 + todos counts for the agent status bar, refreshed off
1524    /// the hot path (on `aft_inspect` reads and background Tier-2 completions).
1525    /// Errors/warnings are read live and not stored here.
1526    status_bar_tier2: RwLock<StatusBarTier2>,
1527    /// Persistent TypeScript-project membership cache for the status-bar E/W
1528    /// count. The bar reads E/W live on every tool result, so resolving the
1529    /// nearest tsconfig (read + parse + glob-compile) per drain is too costly;
1530    /// this memoizes per tsconfig dir. Invalidated wholesale on any
1531    /// tsconfig-like watcher event and on `configure`. Owned here (not in
1532    /// `DiagnosticsStore`, which stays raw policy-free) per the v0.35 council.
1533    tsconfig_membership:
1534        parking_lot::Mutex<crate::lsp::tsconfig_membership::TsconfigMembershipCache>,
1535}
1536
1537/// RAII guard for a server-owned request-scoped path-restriction override.
1538///
1539/// Guards are refcounted by request id so duplicated ids over-restrict until the
1540/// last worker exits, rather than letting one completion disable another
1541/// in-flight request's containment.
1542pub struct ForceRestrictGuard<'a> {
1543    ctx: &'a AppContext,
1544    req_id: String,
1545}
1546
1547impl Drop for ForceRestrictGuard<'_> {
1548    fn drop(&mut self) {
1549        self.ctx.release_force_restrict(&self.req_id);
1550    }
1551}
1552
1553impl Drop for AppContext {
1554    fn drop(&mut self) {
1555        self.artifact_owner_lease.get_mut().take();
1556        if let Some(runtime) = self.watcher_thread.get_mut().take() {
1557            let root = self
1558                .canonical_cache_root
1559                .get_mut()
1560                .clone()
1561                .or_else(|| {
1562                    self.config
1563                        .get_mut()
1564                        .unwrap_or_else(std::sync::PoisonError::into_inner)
1565                        .project_root
1566                        .clone()
1567                })
1568                .unwrap_or_else(|| PathBuf::from("<unconfigured>"));
1569            Self::spawn_watcher_shutdown(Arc::clone(&self.app), root, runtime);
1570        }
1571    }
1572}
1573
1574/// Result of requesting the persisted callgraph store for a store-backed op.
1575///
1576/// The five edge-query ops never block the request thread on a cold build:
1577/// a genuine cold build is kicked off in the background and `Building` is
1578/// returned so the agent retries, mirroring how semantic search reports a
1579/// build in progress. Warm restarts open the on-disk DB synchronously, so
1580/// `Building` is only ever seen during a true first cold build.
1581pub enum CallgraphStoreAccess {
1582    /// Store is resident and queryable.
1583    Ready(Arc<ReadonlyCallGraphStore>),
1584    /// A cold build is in flight (or was just started); retry shortly.
1585    Building,
1586    /// Not configured, or a read-only worktree whose store was never built.
1587    Unavailable,
1588    /// A store open/build check failed with a real error (DB/IO).
1589    Error(CallGraphStoreError),
1590}
1591
1592#[derive(Clone, Copy)]
1593enum CallgraphBackgroundWork {
1594    Ensure,
1595    ForceRebuild(u64),
1596    LegacyMigration,
1597}
1598
1599#[cfg(test)]
1600struct CallgraphBuildStartGate {
1601    root: PathBuf,
1602    reached: crossbeam_channel::Sender<()>,
1603    release: crossbeam_channel::Receiver<()>,
1604}
1605
1606#[cfg(test)]
1607static CALLGRAPH_BUILD_START_GATE: std::sync::OnceLock<
1608    parking_lot::Mutex<Option<CallgraphBuildStartGate>>,
1609> = std::sync::OnceLock::new();
1610
1611#[cfg(test)]
1612fn install_callgraph_build_start_gate(
1613    root: PathBuf,
1614) -> (
1615    crossbeam_channel::Receiver<()>,
1616    crossbeam_channel::Sender<()>,
1617) {
1618    let (reached_tx, reached_rx) = crossbeam_channel::bounded(1);
1619    let (release_tx, release_rx) = crossbeam_channel::bounded(1);
1620    *CALLGRAPH_BUILD_START_GATE
1621        .get_or_init(|| parking_lot::Mutex::new(None))
1622        .lock() = Some(CallgraphBuildStartGate {
1623        root,
1624        reached: reached_tx,
1625        release: release_rx,
1626    });
1627    (reached_rx, release_tx)
1628}
1629
1630#[cfg(test)]
1631fn wait_on_callgraph_build_start_gate(root: &Path) {
1632    let mut slot = CALLGRAPH_BUILD_START_GATE
1633        .get_or_init(|| parking_lot::Mutex::new(None))
1634        .lock();
1635    if !slot.as_ref().is_some_and(|gate| gate.root == root) {
1636        return;
1637    }
1638    let gate = slot.take();
1639    drop(slot);
1640    if let Some(gate) = gate {
1641        let _ = gate.reached.send(());
1642        let _ = gate.release.recv_timeout(Duration::from_secs(5));
1643    }
1644}
1645
1646#[cfg(not(test))]
1647fn wait_on_callgraph_build_start_gate(_root: &Path) {}
1648
1649#[cfg(test)]
1650static REMOVE_CALLGRAPH_POINTER_BEFORE_INLINE_REOPEN: AtomicBool = AtomicBool::new(false);
1651
1652#[cfg(test)]
1653struct RemoveCallgraphPointerBeforeInlineReopenGuard;
1654
1655#[cfg(test)]
1656impl Drop for RemoveCallgraphPointerBeforeInlineReopenGuard {
1657    fn drop(&mut self) {
1658        REMOVE_CALLGRAPH_POINTER_BEFORE_INLINE_REOPEN.store(false, Ordering::SeqCst);
1659    }
1660}
1661
1662#[cfg(test)]
1663fn remove_callgraph_pointer_before_inline_reopen_for_test(
1664    callgraph_dir: &Path,
1665    store: &CallGraphStore,
1666) {
1667    if REMOVE_CALLGRAPH_POINTER_BEFORE_INLINE_REOPEN.swap(false, Ordering::SeqCst) {
1668        let pointer = callgraph_dir.join(format!("{}.current", store.project_key()));
1669        std::fs::remove_file(pointer).expect("remove callgraph pointer before inline reopen");
1670    }
1671}
1672
1673#[cfg(not(test))]
1674fn remove_callgraph_pointer_before_inline_reopen_for_test(
1675    _callgraph_dir: &Path,
1676    _store: &CallGraphStore,
1677) {
1678}
1679
1680/// Inline wait window for a callgraph-store cold build before returning
1681/// `Building`. Default `0` (pure-async: never block the request thread).
1682/// Tests set `AFT_CALLGRAPH_BUILD_WAIT_MS` large so small fixture builds
1683/// resolve to `Ready` synchronously and exercise query correctness directly.
1684fn callgraph_build_wait_window() -> Duration {
1685    std::env::var("AFT_CALLGRAPH_BUILD_WAIT_MS")
1686        .ok()
1687        .and_then(|raw| raw.parse::<u64>().ok())
1688        .map(Duration::from_millis)
1689        .unwrap_or(Duration::ZERO)
1690}
1691
1692static CALLGRAPH_COLD_BUILD_SPAWN_COUNT: AtomicUsize = AtomicUsize::new(0);
1693
1694#[doc(hidden)]
1695pub fn reset_callgraph_cold_build_spawn_count_for_test() {
1696    CALLGRAPH_COLD_BUILD_SPAWN_COUNT.store(0, Ordering::SeqCst);
1697}
1698
1699#[doc(hidden)]
1700pub fn callgraph_cold_build_spawn_count_for_test() -> usize {
1701    CALLGRAPH_COLD_BUILD_SPAWN_COUNT.load(Ordering::SeqCst)
1702}
1703
1704impl AppContext {
1705    pub fn new(provider: Box<dyn LanguageProvider>, config: Config) -> Self {
1706        Self::with_app_and_provider(App::default_shared(), provider, config)
1707    }
1708
1709    pub fn from_app(app: Arc<App>, config: Config) -> Self {
1710        let provider = app.create_provider();
1711        Self::with_app_and_provider(app, provider, config)
1712    }
1713
1714    pub fn with_app_and_provider(
1715        app: Arc<App>,
1716        provider: Box<dyn LanguageProvider>,
1717        config: Config,
1718    ) -> Self {
1719        let bash_compress_enabled = config.experimental_bash_compress;
1720        let (configure_warnings_tx, configure_warnings_rx) = crossbeam_channel::unbounded();
1721        let progress_sender: SharedProgressSender = Arc::new(Mutex::new(None));
1722        let status_emitter = StatusEmitter::new(Arc::clone(&progress_sender));
1723        let heavy_root_work_allowed = Arc::new(AtomicBool::new(true));
1724        let symbol_cache = provider
1725            .as_any()
1726            .downcast_ref::<TreeSitterProvider>()
1727            .map(|provider| provider.symbol_cache())
1728            .unwrap_or_else(|| Arc::new(std::sync::RwLock::new(SymbolCache::new())));
1729        let mut lsp_manager = LspManager::new();
1730        lsp_manager.set_child_registry(app.lsp_child_registry());
1731        // Apply the configured diagnostic LRU cap (default 5000, 0 = unbounded)
1732        // so the documented `lsp.diagnostic_cache_size` knob takes effect.
1733        lsp_manager.set_diagnostic_capacity(config.diagnostic_cache_size);
1734        let bash_background = BgTaskRegistry::new(Arc::clone(&progress_sender));
1735        let compression_aggregates = bash_background.compression_aggregate_cache();
1736        let context = AppContext {
1737            app: Arc::clone(&app),
1738            provider,
1739            backup: parking_lot::Mutex::new(BackupStore::new()),
1740            checkpoint: parking_lot::Mutex::new(CheckpointStore::new()),
1741            config: RwLock::new(Arc::new(config)),
1742            force_restrict_requests: parking_lot::Mutex::new(BTreeMap::new()),
1743            harness: parking_lot::Mutex::new(None),
1744            canonical_cache_root: parking_lot::Mutex::new(None),
1745            is_worktree_bridge: parking_lot::Mutex::new(false),
1746            git_common_dir: parking_lot::Mutex::new(None),
1747            shared_artifacts_read_only: AtomicBool::new(false),
1748            callgraph_writer: AtomicBool::new(true),
1749            inspect_writer: AtomicBool::new(true),
1750            artifact_owner_status: parking_lot::Mutex::new(None),
1751            artifact_owner_lease: parking_lot::Mutex::new(None),
1752            degraded_reasons: parking_lot::Mutex::new(Vec::new()),
1753            heavy_root_work_allowed: Arc::clone(&heavy_root_work_allowed),
1754            callgraph_store: RwLock::new(None),
1755            callgraph_store_force_requested: AtomicU64::new(0),
1756            callgraph_store_force_fulfilled: AtomicU64::new(0),
1757            callgraph_store_rx: parking_lot::Mutex::new(None),
1758            callgraph_store_rx_generation: AtomicU64::new(0),
1759            callgraph_store_rx_epoch: AtomicU64::new(0),
1760            callgraph_persist_epoch: crate::root_cache::ArtifactPublishEpoch::default(),
1761            callgraph_legacy_migration_summary_logged: Arc::new(AtomicBool::new(false)),
1762            pending_callgraph_store_paths: Arc::new(parking_lot::Mutex::new(BTreeSet::new())),
1763            search_index: RwLock::new(None),
1764            search_index_rx: RwLock::new(None),
1765            search_index_rx_generation: AtomicU64::new(0),
1766            search_index_rx_epoch: AtomicU64::new(0),
1767            search_index_rx_terminal_epoch: Arc::new(AtomicU64::new(0)),
1768            search_index_disconnect_reschedule: parking_lot::Mutex::new((0, 0)),
1769            search_persist_epoch: crate::root_cache::ArtifactPublishEpoch::default(),
1770            pending_search_index_paths: parking_lot::Mutex::new(BTreeSet::new()),
1771            symbol_cache,
1772            inspect_manager: Arc::new(InspectManager::with_heavy_root_work_gate(Arc::clone(
1773                &heavy_root_work_allowed,
1774            ))),
1775            tier2_refresh_scheduler: parking_lot::Mutex::new(Tier2RefreshScheduler::new()),
1776            pending_tier2_paths: parking_lot::Mutex::new(BTreeSet::new()),
1777            semantic_index: RwLock::new(None),
1778            semantic_index_rx: parking_lot::Mutex::new(None),
1779            semantic_index_rx_generation: AtomicU64::new(0),
1780            semantic_index_rx_epoch: AtomicU64::new(0),
1781            semantic_index_rx_terminal_epoch: Arc::new(AtomicU64::new(0)),
1782            semantic_persist_epoch: crate::root_cache::ArtifactPublishEpoch::default(),
1783            semantic_persist_lock: Arc::new(parking_lot::Mutex::new(())),
1784            semantic_index_status: RwLock::new(SemanticIndexStatus::Disabled),
1785            artifact_reload_lock: parking_lot::Mutex::new(()),
1786            semantic_cold_seed_active: Arc::new(AtomicBool::new(false)),
1787            semantic_cold_seed_generation: Arc::new(AtomicU64::new(0)),
1788            semantic_fingerprint_generation: Arc::new(AtomicU64::new(0)),
1789            semantic_callgraph_warm_deferred: AtomicBool::new(false),
1790            pending_semantic_index_paths: Arc::new(parking_lot::Mutex::new(BTreeSet::new())),
1791            pending_semantic_corpus_refresh: parking_lot::Mutex::new(false),
1792            semantic_refresh_tx: Arc::new(parking_lot::Mutex::new(None)),
1793            semantic_refresh_event_rx: parking_lot::Mutex::new(None),
1794            semantic_refresh_generation: AtomicU64::new(0),
1795            semantic_refresh_epoch: AtomicU64::new(0),
1796            semantic_refresh_build_epoch: AtomicU64::new(0),
1797            semantic_refresh_worker: parking_lot::Mutex::new(None),
1798            semantic_refresh_retry_attempts: parking_lot::Mutex::new(BTreeMap::new()),
1799            semantic_refresh_circuit: Arc::new(SemanticRefreshCircuit::default()),
1800            semantic_embedding_model: parking_lot::Mutex::new(None),
1801            watcher_runtime_lock: parking_lot::Mutex::new(()),
1802            watcher: parking_lot::Mutex::new(None),
1803            watcher_rx: parking_lot::Mutex::new(None),
1804            watcher_drain_slice: parking_lot::Mutex::new(None),
1805            watcher_thread: parking_lot::Mutex::new(None),
1806            lsp_manager: parking_lot::Mutex::new(lsp_manager),
1807            configure_generation: Arc::new(AtomicU64::new(0)),
1808            configure_content_generation: Arc::new(AtomicU64::new(0)),
1809            subc_lifecycle: SubcLifecycleAdmission::default(),
1810            configure_warm_state: parking_lot::Mutex::new(ConfigureWarmState::default()),
1811            configure_phase_timing: parking_lot::Mutex::new(ConfigurePhaseTiming::default()),
1812            configured_session_roots: parking_lot::Mutex::new(BTreeSet::new()),
1813            configure_maintenance_jobs: parking_lot::Mutex::new(VecDeque::new()),
1814            artifact_cache_keys: parking_lot::Mutex::new(BTreeMap::new()),
1815            artifact_cache_key_derivations: AtomicU64::new(0),
1816            borrowed_index_cache: parking_lot::Mutex::new(BorrowedIndexCache::default()),
1817            worktree_bridge_cache: parking_lot::Mutex::new(BTreeMap::new()),
1818            #[cfg(test)]
1819            worktree_bridge_probe_spawns: AtomicU64::new(0),
1820            #[cfg(test)]
1821            force_worktree_bridge_reprobe: AtomicBool::new(false),
1822            last_seen_reuse_completions: AtomicU64::new(0),
1823            configure_warnings_tx,
1824            configure_warnings_rx,
1825            progress_sender: Arc::clone(&progress_sender),
1826            status_emitter,
1827            status_bar_last_emitted: RwLock::new(None),
1828            status_bar_cached: RwLock::new(StatusBarCache::default()),
1829            compression_aggregates,
1830            bash_background,
1831            #[cfg(unix)]
1832            escalation_grants: parking_lot::Mutex::new(
1833                crate::sandbox_spawn::EscalationGrantStore::default(),
1834            ),
1835            filter_registry: Arc::new(std::sync::RwLock::new(
1836                crate::compress::toml_filter::FilterRegistry::default(),
1837            )),
1838            filter_registry_rebuild_count: AtomicU64::new(0),
1839            filter_registry_loaded: std::sync::atomic::AtomicBool::new(false),
1840            bash_compress_flag: Arc::new(std::sync::atomic::AtomicBool::new(bash_compress_enabled)),
1841            gitignore: Arc::new(std::sync::RwLock::new(None)),
1842            gitignore_generation: Arc::new(AtomicU64::new(0)),
1843            status_bar_tier2: RwLock::new(StatusBarTier2::default()),
1844            tsconfig_membership: parking_lot::Mutex::new(
1845                crate::lsp::tsconfig_membership::TsconfigMembershipCache::new(),
1846            ),
1847        };
1848        crate::logging::sync_storage_root(context.storage_dir());
1849        context
1850    }
1851
1852    /// Current agent status-bar counts. Generation identities are checked before
1853    /// project scoping or tsconfig membership work, so unchanged responses reuse
1854    /// the last honest aggregate from the continuously drained stores.
1855    pub fn status_bar_counts(&self) -> Option<StatusBarCounts> {
1856        let tier2 = self
1857            .status_bar_tier2
1858            .read()
1859            .unwrap_or_else(std::sync::PoisonError::into_inner)
1860            .clone();
1861        let tsconfig_generation = self.tsconfig_membership.lock().generation();
1862        let lsp = self.lsp_manager.lock();
1863        let diagnostics_generation = lsp.diagnostics_generation();
1864
1865        {
1866            let cached = self
1867                .status_bar_cached
1868                .read()
1869                .unwrap_or_else(std::sync::PoisonError::into_inner);
1870            if cached.valid
1871                && cached.diagnostics_generation == diagnostics_generation
1872                && cached.tier2_generation == tier2.generation
1873                && cached.tsconfig_generation == tsconfig_generation
1874            {
1875                return cached.counts.clone();
1876            }
1877        }
1878
1879        let previous_authoritative = self
1880            .status_bar_cached
1881            .read()
1882            .unwrap_or_else(std::sync::PoisonError::into_inner)
1883            .counts
1884            .as_ref()
1885            .map(|counts| (counts.errors, counts.warnings));
1886        let counts = match (tier2.dead_code, tier2.unused_exports, tier2.duplicates) {
1887            (Some(dead_code), Some(unused_exports), Some(duplicates)) => {
1888                let ((current_errors, current_warnings), provisional) =
1889                    match self.canonical_cache_root_opt() {
1890                        Some(root) => {
1891                            // The cache root is identity-domain (bare-canonical,
1892                            // verbatim on Windows) while diagnostics store keys are
1893                            // normalized; normalize a comparison-local copy or the
1894                            // starts_with filter drops every diagnostic.
1895                            let root = crate::inspect::job::normalize_path(&root);
1896                            let mut membership = self.tsconfig_membership.lock();
1897                            lsp.filtered_error_warning_counts_with_provisional(|file| {
1898                                file.starts_with(&root) && !membership.should_skip_diagnostics(file)
1899                            })
1900                        }
1901                        None => lsp.warm_error_warning_counts_with_provisional(),
1902                    };
1903                // A warming report can replace an older authoritative entry. Do
1904                // not turn that transient gap into E/W=0; keep the last values
1905                // until the server publishes after quiescence.
1906                let (errors, warnings) = if provisional {
1907                    previous_authoritative.unwrap_or((current_errors, current_warnings))
1908                } else {
1909                    (current_errors, current_warnings)
1910                };
1911                Some(StatusBarCounts {
1912                    errors,
1913                    warnings,
1914                    dead_code,
1915                    unused_exports,
1916                    duplicates,
1917                    todos: tier2.todos.unwrap_or(0),
1918                    tier2_stale: tier2.stale,
1919                })
1920            }
1921            _ => None,
1922        };
1923
1924        *self
1925            .status_bar_cached
1926            .write()
1927            .unwrap_or_else(std::sync::PoisonError::into_inner) = StatusBarCache {
1928            valid: true,
1929            diagnostics_generation,
1930            tier2_generation: tier2.generation,
1931            tsconfig_generation,
1932            counts: counts.clone(),
1933        };
1934        counts
1935    }
1936
1937    pub fn try_health_snapshot(&self, project_root: &Path) -> RootHealthSnapshot {
1938        // Read lifecycle state before taking artifact locks. Worker admission takes
1939        // the lifecycle lock first and then installs artifact receivers, so the
1940        // reverse order here would deadlock a health poll against worker startup.
1941        let heavy_root_work_allowed = match self.try_heavy_root_work_allowed() {
1942            Some(allowed) => allowed,
1943            None => return RootHealthSnapshot::busy(project_root),
1944        };
1945        let config = match self.config.try_read() {
1946            Ok(guard) => Arc::clone(&*guard),
1947            Err(_) => return RootHealthSnapshot::busy(project_root),
1948        };
1949        let search_index = match self.search_index.try_read() {
1950            Ok(guard) => guard,
1951            Err(_) => return RootHealthSnapshot::busy(project_root),
1952        };
1953        let search_index_rx = match self.search_index_rx.try_read() {
1954            Ok(guard) => guard,
1955            Err(_) => return RootHealthSnapshot::busy(project_root),
1956        };
1957        let semantic_status = match self.semantic_index_status.try_read() {
1958            Ok(guard) => guard,
1959            Err(_) => return RootHealthSnapshot::busy(project_root),
1960        };
1961        let callgraph_store = match self.callgraph_store.try_read() {
1962            Ok(guard) => guard,
1963            Err(_) => return RootHealthSnapshot::busy(project_root),
1964        };
1965        let callgraph_store_rx = match self.callgraph_store_rx.try_lock() {
1966            Some(guard) => guard,
1967            None => return RootHealthSnapshot::busy(project_root),
1968        };
1969        let tier2 = match self.status_bar_tier2.try_read() {
1970            Ok(guard) => guard,
1971            Err(_) => return RootHealthSnapshot::busy(project_root),
1972        };
1973        let bash = match self.bash_background.try_health_counts() {
1974            Some(counts) => counts,
1975            None => return RootHealthSnapshot::busy(project_root),
1976        };
1977
1978        // Borrow-only roots (mason worktrees, read-only siblings) never
1979        // materialize an in-RAM index or spawn a build: queries go through the
1980        // read-only disk openers against the shared artifact. Reporting them
1981        // as "building" is a permanent lie that keeps module health degraded
1982        // whenever any worktree is bound.
1983        let borrows_shared_artifacts = self.shared_artifacts_read_only.load(Ordering::SeqCst);
1984        let search_index_status = if search_index
1985            .as_ref()
1986            .is_some_and(|index| index.ready || index.build_denied)
1987            || (borrows_shared_artifacts && config.search_index)
1988        {
1989            "ready"
1990        } else if config.search_index
1991            || search_index.as_ref().is_some()
1992            || search_index_rx.as_ref().is_some()
1993        {
1994            "building"
1995        } else {
1996            "disabled"
1997        };
1998        let semantic_index_status = match &*semantic_status {
1999            SemanticIndexStatus::Ready { .. } => "ready",
2000            SemanticIndexStatus::Building { .. } => "building",
2001            SemanticIndexStatus::Disabled => "disabled",
2002            SemanticIndexStatus::Failed(_) => "degraded",
2003        };
2004        let callgraph_writer = self.callgraph_writer.load(Ordering::SeqCst);
2005        let callgraph_store_status = if !heavy_root_work_allowed {
2006            "disabled"
2007        } else if callgraph_store.as_ref().is_some() {
2008            "ready"
2009        } else if !callgraph_writer && config.callgraph_store {
2010            // Read-only roots never cold-build; they query the shared store
2011            // via ReadonlyCallGraphStore on demand. "building" would never
2012            // resolve.
2013            "ready"
2014        } else if callgraph_store_rx.is_some() || config.callgraph_store {
2015            "building"
2016        } else {
2017            "disabled"
2018        };
2019        // dead_code is suppressed (reports `None`) while the callgraph store is
2020        // not ready, so a root whose only missing category is dead_code would
2021        // otherwise stay "building" forever: nothing recomputes dead_code until
2022        // the callgraph store becomes ready. Treat that blocked-on-callgraph case
2023        // as complete and let the callgraph component's own status tell the
2024        // callgraph story, instead of double-reporting it here as a permanent
2025        // "building".
2026        let dead_code_blocked_on_callgraph = tier2.dead_code_blocked_on_callgraph;
2027        let tier2_complete = (tier2.dead_code.is_some() || dead_code_blocked_on_callgraph)
2028            && tier2.unused_exports.is_some()
2029            && tier2.duplicates.is_some()
2030            && !tier2.stale;
2031        let tier2_has_aggregates = tier2.dead_code.is_some()
2032            || tier2.unused_exports.is_some()
2033            || tier2.duplicates.is_some();
2034        let tier2_refresh_gated = borrows_shared_artifacts
2035            || !heavy_root_work_allowed
2036            || !self.inspect_writer.load(Ordering::SeqCst)
2037            || !self.inspect_manager.automatic_tier2_refresh_enabled();
2038        let tier2_status = if tier2_complete {
2039            "ready"
2040        } else if !config.inspect.enabled || !tier2_has_aggregates || tier2_refresh_gated {
2041            // A partial snapshot can only be "building" when this root is
2042            // allowed to run the refresh that would complete it.
2043            "disabled"
2044        } else {
2045            "building"
2046        };
2047
2048        RootHealthSnapshot {
2049            project_root: project_root.display().to_string(),
2050            actor_count: 1,
2051            state: RootHealthState::Ready,
2052            search_index: Some(HealthComponentSnapshot {
2053                status: search_index_status,
2054            }),
2055            semantic_index: Some(HealthComponentSnapshot {
2056                status: semantic_index_status,
2057            }),
2058            callgraph_store: Some(HealthComponentSnapshot {
2059                status: callgraph_store_status,
2060            }),
2061            tier2: Some(Tier2HealthSnapshot {
2062                status: tier2_status,
2063            }),
2064            bash: Some(bash),
2065        }
2066    }
2067
2068    pub fn should_emit_status_bar(&self, counts: &StatusBarCounts) -> bool {
2069        let mut last = self
2070            .status_bar_last_emitted
2071            .write()
2072            .unwrap_or_else(std::sync::PoisonError::into_inner);
2073        if last.as_ref() == Some(counts) {
2074            return false;
2075        }
2076        *last = Some(counts.clone());
2077        true
2078    }
2079
2080    /// Invalidate the status-bar tsconfig-membership cache. Called from the
2081    /// watcher seam when a tsconfig-like file changes and from `configure`
2082    /// when the project root changes, so the next bar count re-reads from disk.
2083    pub fn clear_tsconfig_membership_cache(&self) {
2084        self.tsconfig_membership.lock().clear();
2085    }
2086
2087    #[cfg(test)]
2088    pub fn tsconfig_membership_clear_generation_for_test(&self) -> u64 {
2089        self.tsconfig_membership.lock().generation()
2090    }
2091
2092    /// Mark the status-bar Tier-2 counts stale (rendered with `~`) without
2093    /// changing the numbers — called when the watcher sees a source-file change,
2094    /// so the bar honestly signals the counts predate the latest edit until the
2095    /// next background scan completes. Returns true only when the visible stale
2096    /// bit flips. No-op before the first populate.
2097    pub fn mark_status_bar_tier2_stale(&self) -> bool {
2098        let mut tier2 = self
2099            .status_bar_tier2
2100            .write()
2101            .unwrap_or_else(std::sync::PoisonError::into_inner);
2102        // No-op before the first full populate (nothing real to mark stale).
2103        if tier2.dead_code.is_some() && tier2.unused_exports.is_some() && tier2.duplicates.is_some()
2104        {
2105            let changed = !tier2.stale;
2106            tier2.stale = true;
2107            if changed {
2108                tier2.generation = tier2.generation.wrapping_add(1);
2109            }
2110            return changed;
2111        }
2112        false
2113    }
2114
2115    /// Refresh the cached Tier-2 + todos counts for the status bar. Each count
2116    /// is `Option`: `None` preserves the last-known value (the category wasn't
2117    /// recomputed or has no real aggregate yet) so we never overwrite a real
2118    /// count with a fabricated `0`. `stale` marks the Tier-2 numbers as
2119    /// not-yet-reconciled with the latest edits.
2120    pub fn update_status_bar_tier2(
2121        &self,
2122        dead_code: Option<usize>,
2123        unused_exports: Option<usize>,
2124        duplicates: Option<usize>,
2125        todos: Option<usize>,
2126        stale: bool,
2127    ) {
2128        let mut tier2 = self
2129            .status_bar_tier2
2130            .write()
2131            .unwrap_or_else(std::sync::PoisonError::into_inner);
2132        let previous = (
2133            tier2.dead_code,
2134            tier2.unused_exports,
2135            tier2.duplicates,
2136            tier2.todos,
2137            tier2.stale,
2138        );
2139        if let Some(dead_code) = dead_code {
2140            tier2.dead_code = Some(dead_code);
2141        }
2142        if let Some(unused_exports) = unused_exports {
2143            tier2.unused_exports = Some(unused_exports);
2144        }
2145        if let Some(duplicates) = duplicates {
2146            tier2.duplicates = Some(duplicates);
2147        }
2148        if let Some(todos) = todos {
2149            tier2.todos = Some(todos);
2150        }
2151        tier2.stale = stale;
2152        let current = (
2153            tier2.dead_code,
2154            tier2.unused_exports,
2155            tier2.duplicates,
2156            tier2.todos,
2157            tier2.stale,
2158        );
2159        if current != previous {
2160            tier2.generation = tier2.generation.wrapping_add(1);
2161        }
2162    }
2163
2164    /// Record whether the latest dead_code aggregate was suppressed because the
2165    /// callgraph store was not ready (`callgraph_available:false`). Kept separate
2166    /// from [`update_status_bar_tier2`] because the flag is health metadata, not a
2167    /// status-bar count: it never renders in the bar and need not bump the
2168    /// count-generation used for status-bar cache invalidation.
2169    pub(crate) fn set_status_bar_tier2_dead_code_blocked_on_callgraph(&self, blocked: bool) {
2170        let mut tier2 = self
2171            .status_bar_tier2
2172            .write()
2173            .unwrap_or_else(std::sync::PoisonError::into_inner);
2174        tier2.dead_code_blocked_on_callgraph = blocked;
2175    }
2176
2177    /// Borrow the cached project gitignore matcher. Returns `None` when no
2178    /// project_root is configured or when the project has no gitignore files.
2179    pub fn gitignore(&self) -> Option<Arc<ignore::gitignore::Gitignore>> {
2180        self.gitignore
2181            .read()
2182            .unwrap_or_else(|poisoned| poisoned.into_inner())
2183            .clone()
2184    }
2185
2186    /// Shared gitignore matcher handle for the watcher filter thread.
2187    pub fn shared_gitignore(&self) -> SharedGitignore {
2188        Arc::clone(&self.gitignore)
2189    }
2190
2191    /// Monotonic generation bumped after every matcher rebuild/clear. The
2192    /// watcher filter thread uses it to wait until the main thread has rebuilt
2193    /// ignore rules after it reports an ignore-file change.
2194    pub fn gitignore_generation(&self) -> Arc<AtomicU64> {
2195        Arc::clone(&self.gitignore_generation)
2196    }
2197
2198    fn set_gitignore(&self, matcher: Option<Arc<ignore::gitignore::Gitignore>>) {
2199        *self
2200            .gitignore
2201            .write()
2202            .unwrap_or_else(|poisoned| poisoned.into_inner()) = matcher;
2203        self.gitignore_generation.fetch_add(1, Ordering::SeqCst);
2204    }
2205
2206    /// Rebuild the gitignore matcher from the current `project_root` and
2207    /// cache it. Called by the configure handler whenever the project root
2208    /// changes, and by the watcher event drain when a `.gitignore` file
2209    /// itself is modified.
2210    ///
2211    /// The builder honors:
2212    /// - `<project_root>/.gitignore`
2213    /// - Git's global excludes file (the same source used by `ignore::WalkBuilder`)
2214    /// - the repository's real `info/exclude` file, resolved through Git's
2215    ///   common dir for linked worktrees
2216    /// - nested `.gitignore` files (each `.gitignore` discovered during
2217    ///   the recursive walk)
2218    ///
2219    /// Stores `None` if there's no project_root or no matchable gitignore
2220    /// files. Logs build errors but never fails configure.
2221    /// Clear any cached gitignore matcher without rebuilding.
2222    ///
2223    /// Used by `handle_configure` in degraded mode (e.g. `project_root == $HOME`)
2224    /// where running the gitignore-discovery walk would exceed the configure
2225    /// budget. The watcher event filter falls back to the hardcoded infra-dir
2226    /// skip list when no matcher is present.
2227    pub fn clear_gitignore(&self) {
2228        self.set_gitignore(None);
2229    }
2230
2231    pub fn rebuild_gitignore(&self) {
2232        use ignore::gitignore::GitignoreBuilder;
2233        use std::path::Path;
2234        let root_raw = match self.config().project_root.clone() {
2235            Some(r) => r,
2236            None => {
2237                self.set_gitignore(None);
2238                return;
2239            }
2240        };
2241        // Canonicalize the root so symlink-prefix mismatches don't cause
2242        // `Gitignore::matched_path_or_any_parents` to panic on watcher event
2243        // paths. macOS routinely surfaces `/private/var/...` while `project_root`
2244        // arrives as `/var/...` (a symlink to `/private/var`); the `ignore`
2245        // crate's matcher panics when a query path isn't lexically under the
2246        // matcher's root. Canonicalizing both ends (here for root, naturally
2247        // for watcher events on macOS) keeps them in the same prefix space.
2248        let root = std::fs::canonicalize(&root_raw).unwrap_or(root_raw);
2249        let mut builder = GitignoreBuilder::new(&root);
2250        // Git's global excludes file — keep the live watcher matcher aligned
2251        // with the project walkers (`WalkBuilder::git_global(true)`). The
2252        // ignore crate exposes the same path discovery it uses internally, so
2253        // this handles the default XDG location and configured excludesFile.
2254        if let Some(global_ignore) = ignore::gitignore::gitconfig_excludes_path() {
2255            if global_ignore.is_file() {
2256                if let Some(err) = builder.add(&global_ignore) {
2257                    crate::slog_warn!(
2258                        "global gitignore parse error in {}: {}",
2259                        global_ignore.display(),
2260                        err
2261                    );
2262                }
2263            }
2264        }
2265        // Add root .gitignore (the most common case)
2266        let root_ignore = Path::new(&root).join(".gitignore");
2267        if root_ignore.exists() {
2268            if let Some(err) = builder.add(&root_ignore) {
2269                crate::slog_warn!(
2270                    "gitignore parse error in {}: {}",
2271                    root_ignore.display(),
2272                    err
2273                );
2274            }
2275        }
2276        // Root .aftignore — AFT-specific ignores layered on top of .gitignore.
2277        // Lets users exclude paths git can't (e.g. submodules) from AFT's
2278        // walks/indexes. Honored by the watcher matcher too, so edits under an
2279        // aftignored path don't trigger reindexing.
2280        let root_aftignore = Path::new(&root).join(".aftignore");
2281        if root_aftignore.exists() {
2282            if let Some(err) = builder.add(&root_aftignore) {
2283                crate::slog_warn!(
2284                    "aftignore parse error in {}: {}",
2285                    root_aftignore.display(),
2286                    err
2287                );
2288            }
2289        }
2290        // .git/info/exclude — manually added because GitignoreBuilder::new()
2291        // does not auto-discover it (verified against ignore-0.4.25 source).
2292        // In linked worktrees this lives under the repository common dir, not
2293        // under `<worktree>/.git/info/exclude` (where `.git` is only a file).
2294        let info_exclude = self
2295            .git_common_dir
2296            .lock()
2297            .clone()
2298            .unwrap_or_else(|| Path::new(&root).join(".git"))
2299            .join("info")
2300            .join("exclude");
2301        if info_exclude.exists() {
2302            if let Some(err) = builder.add(&info_exclude) {
2303                crate::slog_warn!(
2304                    "gitignore parse error in {}: {}",
2305                    info_exclude.display(),
2306                    err
2307                );
2308            }
2309        }
2310        // Walk the project to pick up nested .gitignore/.aftignore files at
2311        // arbitrary depth. The main project walkers honor deeply nested ignore
2312        // files, so the watcher matcher must do the same or live invalidation
2313        // can disagree with startup indexing. Skip obvious infra dirs so we
2314        // don't accidentally load a vendored repo's ignore file as ours.
2315        let walker = ignore::WalkBuilder::new(&root)
2316            .standard_filters(true)
2317            // Hidden files are filtered by default, but `.gitignore` starts with
2318            // `.` so we need to traverse "hidden" entries to find nested ones.
2319            // No `max_depth`: nested `.gitignore`/`.aftignore` files are honored
2320            // at arbitrary depth (see configure_watcher_honors_deep_nested_aftignore).
2321            // The walk is pruned by standard gitignore filters plus the infra
2322            // skip below; configure never runs this against `$HOME` (guarded by
2323            // `home_match`), and tests use bounded roots rather than `/`.
2324            .hidden(false)
2325            .filter_entry(|entry| {
2326                let name = entry.file_name().to_string_lossy();
2327                !matches!(
2328                    name.as_ref(),
2329                    "node_modules" | "target" | ".git" | ".opencode" | ".alfonso"
2330                )
2331            })
2332            .build();
2333        for entry in walker.flatten() {
2334            let file_name = entry.file_name();
2335            let is_nested_gitignore = file_name == ".gitignore" && entry.path() != root_ignore;
2336            let is_nested_aftignore = file_name == ".aftignore" && entry.path() != root_aftignore;
2337            if is_nested_gitignore || is_nested_aftignore {
2338                if let Some(err) = builder.add(entry.path()) {
2339                    crate::slog_warn!(
2340                        "nested ignore parse error in {}: {}",
2341                        entry.path().display(),
2342                        err
2343                    );
2344                }
2345            }
2346        }
2347        match builder.build() {
2348            Ok(gi) => {
2349                let count = gi.num_ignores();
2350                if count > 0 {
2351                    crate::slog_info!("gitignore matcher built: {} pattern(s)", count);
2352                    self.set_gitignore(Some(Arc::new(gi)));
2353                } else {
2354                    self.set_gitignore(None);
2355                }
2356            }
2357            Err(err) => {
2358                crate::slog_warn!("gitignore matcher build failed: {}", err);
2359                self.set_gitignore(None);
2360            }
2361        }
2362    }
2363
2364    /// Shared atomic mirror of `experimental.bash.compress`. Updated by the
2365    /// configure handler. Read by the BgTaskRegistry compressor closure.
2366    pub fn bash_compress_flag(&self) -> Arc<std::sync::atomic::AtomicBool> {
2367        Arc::clone(&self.bash_compress_flag)
2368    }
2369
2370    /// Update the shared `bash_compress_flag` mirror. Call this from the
2371    /// configure handler whenever `experimental.bash.compress` changes so the
2372    /// BgTaskRegistry watchdog sees the new value on the next completion.
2373    pub fn sync_bash_compress_flag(&self) {
2374        let value = self.config().experimental_bash_compress;
2375        self.bash_compress_flag
2376            .store(value, std::sync::atomic::Ordering::Relaxed);
2377    }
2378
2379    pub fn set_bash_compress_enabled(&self, enabled: bool) {
2380        self.update_config(|config| {
2381            config.experimental_bash_compress = enabled;
2382        });
2383        self.bash_compress_flag
2384            .store(enabled, std::sync::atomic::Ordering::Relaxed);
2385    }
2386
2387    /// Read-only access to the TOML filter registry, building it lazily on
2388    /// first use. Returns an `RwLockReadGuard` that callers can `lookup`
2389    /// against directly.
2390    pub fn filter_registry(
2391        &self,
2392    ) -> std::sync::RwLockReadGuard<'_, crate::compress::toml_filter::FilterRegistry> {
2393        self.ensure_filter_registry_loaded();
2394        match self.filter_registry.read() {
2395            Ok(g) => g,
2396            Err(poisoned) => poisoned.into_inner(),
2397        }
2398    }
2399
2400    /// Returns the shared `Arc<RwLock<FilterRegistry>>` handle so threads
2401    /// outside `AppContext` (notably the bash watchdog) can read it without
2402    /// touching the rest of the context.
2403    pub fn shared_filter_registry(&self) -> crate::compress::SharedFilterRegistry {
2404        self.ensure_filter_registry_loaded();
2405        Arc::clone(&self.filter_registry)
2406    }
2407
2408    /// Force a fresh load of the TOML filter registry. Called when configure
2409    /// changes the project root, storage_dir, or trust state so subsequent
2410    /// `compress::compress` calls pick up new filters.
2411    pub fn reset_filter_registry(&self) {
2412        let new_registry = crate::compress::build_registry_for_context(self);
2413        self.filter_registry_rebuild_count
2414            .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
2415        match self.filter_registry.write() {
2416            Ok(mut slot) => *slot = new_registry,
2417            Err(poisoned) => *poisoned.into_inner() = new_registry,
2418        }
2419        self.filter_registry_loaded
2420            .store(true, std::sync::atomic::Ordering::Release);
2421    }
2422
2423    fn ensure_filter_registry_loaded(&self) {
2424        use std::sync::atomic::Ordering;
2425        if self.filter_registry_loaded.load(Ordering::Acquire) {
2426            return;
2427        }
2428        // Build outside the lock to avoid blocking other readers during a
2429        // multi-file TOML parse.
2430        let new_registry = crate::compress::build_registry_for_context(self);
2431        self.filter_registry_rebuild_count
2432            .fetch_add(1, Ordering::SeqCst);
2433        if let Ok(mut slot) = self.filter_registry.write() {
2434            *slot = new_registry;
2435            self.filter_registry_loaded.store(true, Ordering::Release);
2436        }
2437    }
2438
2439    #[cfg(test)]
2440    pub fn filter_registry_rebuild_count_for_test(&self) -> u64 {
2441        self.filter_registry_rebuild_count.load(Ordering::SeqCst)
2442    }
2443
2444    pub fn app(&self) -> Arc<App> {
2445        Arc::clone(&self.app)
2446    }
2447
2448    /// Clone the LSP child registry handle. Used by main.rs to give the
2449    /// signal handler thread a way to SIGKILL LSP children on shutdown.
2450    pub fn lsp_child_registry(&self) -> crate::lsp::child_registry::LspChildRegistry {
2451        self.app.lsp_child_registry()
2452    }
2453
2454    pub fn stdout_writer(&self) -> SharedStdoutWriter {
2455        self.app.stdout_writer()
2456    }
2457
2458    pub fn set_progress_sender(&self, sender: Option<ProgressSender>) {
2459        if let Ok(mut progress_sender) = self.progress_sender.lock() {
2460            *progress_sender = sender;
2461        }
2462    }
2463
2464    pub fn emit_progress(&self, frame: ProgressFrame) {
2465        let Ok(progress_sender) = self.progress_sender.lock().map(|sender| sender.clone()) else {
2466            return;
2467        };
2468        if let Some(sender) = progress_sender.as_ref() {
2469            sender(PushFrame::Progress(frame));
2470        }
2471    }
2472
2473    pub fn status_emitter(&self) -> &StatusEmitter {
2474        &self.status_emitter
2475    }
2476
2477    /// Get a clone of the current progress sender for use from background
2478    /// threads. Returns `None` when the main loop hasn't installed one (tests,
2479    /// CLI without push frames).
2480    ///
2481    /// Used by `configure`'s deferred file-walk thread to push warnings after
2482    /// configure has already returned, so configure latency stays sub-100 ms
2483    /// even on huge directories.
2484    pub fn progress_sender_handle(&self) -> Option<ProgressSender> {
2485        self.progress_sender
2486            .lock()
2487            .ok()
2488            .and_then(|sender| sender.clone())
2489    }
2490
2491    pub fn advance_configure_generation(&self) -> u64 {
2492        self.subc_lifecycle
2493            .advance_generation(self.configure_generation.as_ref())
2494    }
2495
2496    pub(crate) fn mark_subc_bound(&self) {
2497        self.subc_lifecycle.mark_bound();
2498    }
2499
2500    pub(crate) fn mark_subc_unbound(&self) {
2501        self.subc_lifecycle
2502            .mark_unbound(self.configure_generation.as_ref());
2503    }
2504
2505    #[doc(hidden)]
2506    pub fn subc_unbound_quiesced(&self) -> bool {
2507        self.subc_lifecycle.is_unbound()
2508    }
2509
2510    pub(crate) fn subc_lifecycle_admission(&self) -> SubcLifecycleAdmission {
2511        self.subc_lifecycle.clone()
2512    }
2513
2514    pub(crate) fn run_if_subc_bound_generation<R>(
2515        &self,
2516        expected_generation: u64,
2517        action: impl FnOnce() -> R,
2518    ) -> Option<R> {
2519        self.subc_lifecycle.run_if_current(
2520            self.configure_generation.as_ref(),
2521            expected_generation,
2522            action,
2523        )
2524    }
2525
2526    /// Record the warm-maintenance key for a successful configure and return
2527    /// the generation this configure operates under.
2528    ///
2529    /// An unchanged key ADOPTS the running generation without advancing it:
2530    /// in-flight build workers gate their publish on the generation flag being
2531    /// unchanged, so advancing on an equivalent rebind would silently discard
2532    /// every adopted build's result at completion (the receiver never
2533    /// resolves, and long builds can never finish under rebind traffic). Only
2534    /// a genuinely different warm config advances the generation, which is
2535    /// what cancels superseded in-flight builds.
2536    pub fn note_configure_warm_key(&self, key: String) -> (u64, bool) {
2537        let mut state = self.configure_warm_state.lock();
2538        let equivalent = state.key.as_ref().is_some_and(|previous| *previous == key);
2539        let generation = if equivalent {
2540            self.configure_generation()
2541        } else {
2542            self.configure_content_generation
2543                .fetch_add(1, Ordering::SeqCst);
2544            self.advance_configure_generation()
2545        };
2546        state.generation = generation;
2547        state.key = Some(key);
2548        (generation, equivalent)
2549    }
2550
2551    pub(crate) fn configure_warm_key_matches(&self, key: &str) -> bool {
2552        self.configure_warm_state
2553            .lock()
2554            .key
2555            .as_deref()
2556            .is_some_and(|current| current == key)
2557    }
2558
2559    pub(crate) fn invalidate_configure_warm_state(&self) {
2560        self.configure_warm_state.lock().key = None;
2561    }
2562
2563    pub fn note_configure_session_binding(&self, root: PathBuf, session_id: String) -> bool {
2564        self.configured_session_roots
2565            .lock()
2566            .insert((root, session_id))
2567    }
2568
2569    /// Undo [`Self::note_configure_session_binding`] when the maintenance job
2570    /// carrying the session's bash replay was dropped as stale: the session has
2571    /// not actually been replayed, so its next bind must count as first again.
2572    pub fn forget_configure_session_binding(&self, root: &Path, session_id: &str) {
2573        self.configured_session_roots
2574            .lock()
2575            .remove(&(root.to_path_buf(), session_id.to_string()));
2576    }
2577
2578    /// Cheap emptiness probes for the maintenance scheduler: a drain kind with
2579    /// no pending work is not enqueued at all, so idle roots stop paying a
2580    /// dispatch cycle per kind per tick. Every probe is lock-free or try-lock
2581    /// (a contended source reports "maybe work" and the kind is enqueued —
2582    /// fail-open keeps the skip an optimization, never a correctness gate).
2583    pub fn watcher_drain_has_work(&self) -> bool {
2584        let receiver_pending = self
2585            .watcher_rx
2586            .lock()
2587            .as_ref()
2588            .is_some_and(|rx| !rx.is_empty());
2589        receiver_pending
2590            || self
2591                .watcher_drain_slice
2592                .lock()
2593                .as_ref()
2594                .is_some_and(WatcherDrainSliceState::has_pending_work)
2595    }
2596
2597    pub fn lsp_drain_has_work(&self) -> bool {
2598        match self.lsp_manager.try_lock() {
2599            Some(lsp) => lsp.has_pending_events(),
2600            // Contended: the manager is busy, so events may be queuing.
2601            None => true,
2602        }
2603    }
2604
2605    pub fn completion_drains_have_work(&self) -> bool {
2606        let search_pending = self
2607            .search_index_rx
2608            .try_read()
2609            .map(|slot| {
2610                slot.as_ref().is_some_and(|receiver| {
2611                    !receiver.is_empty()
2612                        || self.search_index_rx_terminal_epoch.load(Ordering::SeqCst)
2613                            == self.search_index_rx_epoch()
2614                })
2615            })
2616            .unwrap_or(true);
2617        if search_pending {
2618            return true;
2619        }
2620        if self
2621            .callgraph_store_rx
2622            .lock()
2623            .as_ref()
2624            .is_some_and(|rx| !rx.is_empty())
2625        {
2626            return true;
2627        }
2628        if self
2629            .semantic_index_rx
2630            .lock()
2631            .as_ref()
2632            .is_some_and(|receiver| {
2633                !receiver.is_empty()
2634                    || self.semantic_index_rx_terminal_epoch.load(Ordering::SeqCst)
2635                        == self.semantic_index_rx_epoch()
2636            })
2637        {
2638            return true;
2639        }
2640        if self
2641            .semantic_refresh_event_rx
2642            .lock()
2643            .as_ref()
2644            .is_some_and(|rx| !rx.is_empty())
2645        {
2646            return true;
2647        }
2648        if self.semantic_refresh_probe_ready() && self.semantic_refresh_event_rx.lock().is_some() {
2649            return true;
2650        }
2651        if self
2652            .semantic_refresh_worker
2653            .lock()
2654            .as_ref()
2655            .is_some_and(|worker_slot| match worker_slot.try_lock() {
2656                Ok(handle) => handle
2657                    .as_ref()
2658                    .is_some_and(std::thread::JoinHandle::is_finished),
2659                Err(std::sync::TryLockError::WouldBlock) => true,
2660                Err(std::sync::TryLockError::Poisoned(_)) => true,
2661            })
2662        {
2663            return true;
2664        }
2665        self.inspect_manager().has_pending_completions() || self.has_new_reuse_completions()
2666    }
2667
2668    pub fn configure_tail_has_work(&self) -> bool {
2669        !self.configure_maintenance_jobs.lock().is_empty() || !self.configure_warnings_rx.is_empty()
2670    }
2671
2672    pub(crate) fn enqueue_configure_maintenance(&self, job: ConfigureMaintenanceJob) {
2673        self.configure_maintenance_jobs.lock().push_back(job);
2674    }
2675
2676    pub(crate) fn drain_configure_maintenance(&self) -> Vec<ConfigureMaintenanceJob> {
2677        self.configure_maintenance_jobs.lock().drain(..).collect()
2678    }
2679
2680    #[cfg(test)]
2681    pub(crate) fn configure_maintenance_job_count_for_test(&self) -> usize {
2682        self.configure_maintenance_jobs.lock().len()
2683    }
2684
2685    /// Peek the memoized artifact key without deriving it. Passive readers
2686    /// (status snapshots) use this so reporting never spawns a git probe.
2687    pub fn cached_artifact_cache_key(&self, canonical_root: &Path) -> Option<String> {
2688        self.artifact_cache_keys.lock().get(canonical_root).cloned()
2689    }
2690
2691    /// Return a worktree probe result only while the root's `.git` marker still
2692    /// matches the marker present when the successful probe was cached.
2693    pub(crate) fn cached_worktree_bridge(
2694        &self,
2695        canonical_root: &Path,
2696    ) -> Option<(bool, Option<PathBuf>)> {
2697        #[cfg(test)]
2698        if self.force_worktree_bridge_reprobe.load(Ordering::SeqCst) {
2699            return None;
2700        }
2701
2702        let signature = git_entry_signature(canonical_root);
2703        self.worktree_bridge_cache
2704            .lock()
2705            .get(canonical_root)
2706            .filter(|entry| entry.git_entry == signature)
2707            .map(|entry| (entry.is_worktree_bridge, entry.git_common_dir.clone()))
2708    }
2709
2710    /// Cache only successful git worktree probes. Failed probes remain retryable
2711    /// because a transient process or filesystem error must not become sticky.
2712    pub(crate) fn cache_worktree_bridge(
2713        &self,
2714        canonical_root: &Path,
2715        is_worktree_bridge: bool,
2716        git_common_dir: PathBuf,
2717    ) {
2718        self.worktree_bridge_cache.lock().insert(
2719            canonical_root.to_path_buf(),
2720            WorktreeBridgeCacheEntry {
2721                git_entry: git_entry_signature(canonical_root),
2722                is_worktree_bridge,
2723                git_common_dir: Some(git_common_dir),
2724            },
2725        );
2726    }
2727
2728    #[cfg(test)]
2729    pub(crate) fn record_worktree_bridge_probe_spawn_for_test(&self) {
2730        self.worktree_bridge_probe_spawns
2731            .fetch_add(1, Ordering::SeqCst);
2732    }
2733
2734    #[cfg(test)]
2735    pub(crate) fn worktree_bridge_probe_spawns_for_test(&self) -> u64 {
2736        self.worktree_bridge_probe_spawns.load(Ordering::SeqCst)
2737    }
2738
2739    #[cfg(test)]
2740    pub(crate) fn force_worktree_bridge_reprobe_for_test(&self, enabled: bool) {
2741        self.force_worktree_bridge_reprobe
2742            .store(enabled, Ordering::SeqCst);
2743    }
2744
2745    pub fn memoized_artifact_cache_key(&self, canonical_root: &Path) -> String {
2746        let mut keys = self.artifact_cache_keys.lock();
2747        if let Some(key) = keys.get(canonical_root).cloned() {
2748            return key;
2749        }
2750        let key = crate::search_index::artifact_cache_key(canonical_root);
2751        self.artifact_cache_key_derivations
2752            .fetch_add(1, Ordering::SeqCst);
2753        keys.insert(canonical_root.to_path_buf(), key.clone());
2754        key
2755    }
2756
2757    pub fn memoized_artifact_cache_key_for_configure(
2758        &self,
2759        raw_root: &Path,
2760        canonical_root: &Path,
2761        storage_root: &Path,
2762        git_common_dir: Option<&Path>,
2763    ) -> Result<String, crate::search_index::ArtifactCacheKeyProbeError> {
2764        {
2765            let keys = self.artifact_cache_keys.lock();
2766            if let Some(key) = keys
2767                .get(canonical_root)
2768                .or_else(|| keys.get(raw_root))
2769                .cloned()
2770            {
2771                return Ok(key);
2772            }
2773        }
2774
2775        let key = crate::search_index::artifact_cache_key_with_memo(
2776            canonical_root,
2777            raw_root,
2778            storage_root,
2779            git_common_dir,
2780        )?;
2781        self.artifact_cache_key_derivations
2782            .fetch_add(1, Ordering::SeqCst);
2783        let mut keys = self.artifact_cache_keys.lock();
2784        keys.insert(canonical_root.to_path_buf(), key.clone());
2785        keys.insert(raw_root.to_path_buf(), key.clone());
2786        Ok(key)
2787    }
2788
2789    #[cfg(test)]
2790    pub fn artifact_cache_key_derivation_count_for_test(&self) -> u64 {
2791        self.artifact_cache_key_derivations.load(Ordering::SeqCst)
2792    }
2793
2794    pub(crate) fn resolve_external_git_root(
2795        &self,
2796        project_root: &Path,
2797        requested_path: &str,
2798    ) -> Result<PathBuf, crate::readonly_artifacts::GitRootResolutionError> {
2799        let raw_path = Path::new(requested_path);
2800        let canonical_requested = if raw_path.is_absolute() {
2801            std::fs::canonicalize(raw_path).ok()
2802        } else {
2803            None
2804        };
2805        if let Some(root) = canonical_requested
2806            .as_deref()
2807            .and_then(|root| self.borrowed_index_cache.lock().resolved_root(root))
2808        {
2809            return Ok(root);
2810        }
2811
2812        let root = crate::readonly_artifacts::resolve_git_root_from_user_path(
2813            project_root,
2814            requested_path,
2815        )?;
2816        if canonical_requested.as_deref() == Some(root.as_path()) {
2817            self.borrowed_index_cache
2818                .lock()
2819                .remember_resolved_root(root.clone());
2820        }
2821        Ok(root)
2822    }
2823
2824    pub(crate) fn open_borrowed_search_index(
2825        &self,
2826        external_root: &Path,
2827        storage_dir: Option<&Path>,
2828    ) -> crate::readonly_artifacts::ReadOnlyArtifact<Arc<SearchIndex>> {
2829        let canonical_root =
2830            std::fs::canonicalize(external_root).unwrap_or_else(|_| external_root.to_path_buf());
2831        let project_key = self.memoized_artifact_cache_key(&canonical_root);
2832        let Some(artifact) = crate::readonly_artifacts::search_index_artifact_generation_with_key(
2833            &project_key,
2834            storage_dir,
2835        ) else {
2836            return crate::readonly_artifacts::ReadOnlyArtifact::Absent;
2837        };
2838        let key = BorrowedIndexCacheKey {
2839            canonical_root: canonical_root.clone(),
2840            artifact,
2841        };
2842        let mut cache = self.borrowed_index_cache.lock();
2843        if let Some(index) = cache.search(&key) {
2844            return index;
2845        }
2846
2847        let opened = crate::readonly_artifacts::open_search_index_read_only_with_key(
2848            &canonical_root,
2849            storage_dir,
2850            &project_key,
2851        )
2852        .map(Arc::new);
2853        if !matches!(opened, crate::readonly_artifacts::ReadOnlyArtifact::Absent) {
2854            cache.insert(key, BorrowedIndexCacheValue::Search(opened.clone()));
2855        }
2856        opened
2857    }
2858
2859    pub(crate) fn open_borrowed_semantic_index(
2860        &self,
2861        external_root: &Path,
2862        storage_dir: Option<&Path>,
2863    ) -> crate::readonly_artifacts::ReadOnlyArtifact<Arc<SemanticIndex>> {
2864        let canonical_root =
2865            std::fs::canonicalize(external_root).unwrap_or_else(|_| external_root.to_path_buf());
2866        let project_key = self.memoized_artifact_cache_key(&canonical_root);
2867        let Some(artifact) = crate::readonly_artifacts::semantic_index_artifact_generation_with_key(
2868            &project_key,
2869            storage_dir,
2870        ) else {
2871            return crate::readonly_artifacts::ReadOnlyArtifact::Absent;
2872        };
2873        let key = BorrowedIndexCacheKey {
2874            canonical_root: canonical_root.clone(),
2875            artifact,
2876        };
2877        let mut cache = self.borrowed_index_cache.lock();
2878        if let Some(index) = cache.semantic(&key) {
2879            return index;
2880        }
2881
2882        let opened = crate::readonly_artifacts::open_semantic_index_read_only_with_key(
2883            &canonical_root,
2884            storage_dir,
2885            &project_key,
2886        )
2887        .map(Arc::new);
2888        if !matches!(opened, crate::readonly_artifacts::ReadOnlyArtifact::Absent) {
2889            cache.insert(key, BorrowedIndexCacheValue::Semantic(opened.clone()));
2890        }
2891        opened
2892    }
2893
2894    #[cfg(test)]
2895    pub(crate) fn borrowed_index_cache_len_for_test(&self) -> usize {
2896        self.borrowed_index_cache.lock().entries.len()
2897    }
2898
2899    pub fn configure_generation(&self) -> u64 {
2900        self.configure_generation.load(Ordering::SeqCst)
2901    }
2902
2903    pub fn configure_generation_flag(&self) -> Arc<AtomicU64> {
2904        Arc::clone(&self.configure_generation)
2905    }
2906
2907    pub(crate) fn configure_content_generation(&self) -> u64 {
2908        self.configure_content_generation.load(Ordering::SeqCst)
2909    }
2910
2911    pub(crate) fn configure_content_generation_flag(&self) -> Arc<AtomicU64> {
2912        Arc::clone(&self.configure_content_generation)
2913    }
2914
2915    pub(crate) fn begin_configure_ack_phase(&self, phase: &'static str) {
2916        let now = Instant::now();
2917        let mut timing = self.configure_phase_timing.lock();
2918        if phase == "canonicalize" {
2919            timing.completed.clear();
2920        } else if timing.phase != "idle" && timing.phase != "ack_ready" {
2921            let previous = timing.phase;
2922            let elapsed = now.saturating_duration_since(timing.started_at);
2923            timing.completed.push((previous, elapsed));
2924        }
2925        timing.phase = phase;
2926        timing.started_at = now;
2927    }
2928
2929    pub(crate) fn configure_ack_phase_snapshot(&self) -> String {
2930        let timing = self.configure_phase_timing.lock();
2931        let mut parts = timing
2932            .completed
2933            .iter()
2934            .map(|(phase, elapsed)| format!("{phase}={}ms", elapsed.as_millis()))
2935            .collect::<Vec<_>>();
2936        parts.push(format!(
2937            "{}={}ms",
2938            timing.phase,
2939            timing.started_at.elapsed().as_millis()
2940        ));
2941        parts.join(",")
2942    }
2943
2944    pub fn advance_semantic_fingerprint_generation(&self) -> u64 {
2945        self.semantic_fingerprint_generation
2946            .fetch_add(1, Ordering::SeqCst)
2947            .wrapping_add(1)
2948    }
2949
2950    pub fn semantic_fingerprint_generation(&self) -> u64 {
2951        self.semantic_fingerprint_generation.load(Ordering::SeqCst)
2952    }
2953
2954    pub fn semantic_fingerprint_generation_flag(&self) -> Arc<AtomicU64> {
2955        Arc::clone(&self.semantic_fingerprint_generation)
2956    }
2957
2958    pub fn configure_warnings_sender(
2959        &self,
2960    ) -> crossbeam_channel::Sender<(u64, ConfigureWarningsFrame)> {
2961        self.configure_warnings_tx.clone()
2962    }
2963
2964    pub fn drain_configure_warnings(&self) -> Vec<(u64, ConfigureWarningsFrame)> {
2965        let mut warnings = Vec::new();
2966        while let Ok(warning) = self.configure_warnings_rx.try_recv() {
2967            warnings.push(warning);
2968        }
2969        warnings
2970    }
2971
2972    pub fn bash_background(&self) -> &BgTaskRegistry {
2973        &self.bash_background
2974    }
2975
2976    #[cfg(unix)]
2977    pub(crate) fn escalation_grants(
2978        &self,
2979    ) -> &parking_lot::Mutex<crate::sandbox_spawn::EscalationGrantStore> {
2980        &self.escalation_grants
2981    }
2982
2983    pub fn drain_bg_completions(&self) -> Vec<BgCompletion> {
2984        self.bash_background.drain_completions()
2985    }
2986
2987    /// Access the language provider.
2988    pub fn provider(&self) -> &dyn LanguageProvider {
2989        self.provider.as_ref()
2990    }
2991
2992    /// Access the backup store.
2993    pub fn backup(&self) -> &parking_lot::Mutex<BackupStore> {
2994        &self.backup
2995    }
2996
2997    /// Access the checkpoint store.
2998    pub fn checkpoint(&self) -> &parking_lot::Mutex<CheckpointStore> {
2999        &self.checkpoint
3000    }
3001
3002    pub fn set_db(&self, conn: Arc<Mutex<Connection>>) {
3003        self.app.set_db(conn);
3004        self.compression_aggregates.clear();
3005    }
3006
3007    pub fn clear_db(&self) {
3008        self.app.clear_db();
3009        self.compression_aggregates.clear();
3010    }
3011
3012    pub fn db(&self) -> Option<Arc<Mutex<Connection>>> {
3013        self.app.db()
3014    }
3015
3016    pub(crate) fn compression_aggregate_cache(
3017        &self,
3018    ) -> &crate::db::compression_events::CompressionAggregateCache {
3019        self.compression_aggregates.as_ref()
3020    }
3021
3022    /// Access an owned configuration snapshot.
3023    pub fn config(&self) -> Arc<Config> {
3024        let guard = match self.config.read() {
3025            Ok(guard) => guard,
3026            Err(poisoned) => poisoned.into_inner(),
3027        };
3028        Arc::clone(&*guard)
3029    }
3030
3031    /// Atomically publish a fully-built configuration snapshot.
3032    pub fn set_config(&self, config: Config) {
3033        let next = Arc::new(config);
3034        match self.config.write() {
3035            Ok(mut guard) => *guard = next,
3036            Err(poisoned) => *poisoned.into_inner() = next,
3037        }
3038    }
3039
3040    /// Clone-mutate-publish the current configuration without returning a guard.
3041    pub fn update_config(&self, update: impl FnOnce(&mut Config)) {
3042        let mut next = self.config().as_ref().clone();
3043        update(&mut next);
3044        self.set_config(next);
3045    }
3046
3047    pub fn force_restrict_guard(&self, req_id: &str) -> ForceRestrictGuard<'_> {
3048        let mut requests = self.force_restrict_requests.lock();
3049        *requests.entry(req_id.to_string()).or_insert(0) += 1;
3050        ForceRestrictGuard {
3051            ctx: self,
3052            req_id: req_id.to_string(),
3053        }
3054    }
3055
3056    pub fn with_force_restrict<R>(&self, req_id: &str, f: impl FnOnce() -> R) -> R {
3057        let _guard = self.force_restrict_guard(req_id);
3058        f()
3059    }
3060
3061    pub fn request_force_restrict(&self, req_id: &str) -> bool {
3062        self.force_restrict_requests.lock().contains_key(req_id)
3063    }
3064
3065    fn release_force_restrict(&self, req_id: &str) {
3066        let mut requests = self.force_restrict_requests.lock();
3067        match requests.get_mut(req_id) {
3068            Some(count) if *count > 1 => *count -= 1,
3069            Some(_) => {
3070                requests.remove(req_id);
3071            }
3072            None => {}
3073        }
3074    }
3075
3076    pub fn set_harness(&self, harness: Harness) {
3077        self.bash_background.set_harness(harness.clone());
3078        *self.harness.lock() = Some(harness);
3079    }
3080
3081    pub fn harness_opt(&self) -> Option<Harness> {
3082        self.harness.lock().clone()
3083    }
3084
3085    pub fn harness(&self) -> Harness {
3086        self.harness_opt()
3087            .expect("harness set by configure before any tool call")
3088    }
3089
3090    pub fn storage_dir(&self) -> PathBuf {
3091        crate::bash_background::storage_dir(self.config().storage_dir.as_deref())
3092    }
3093
3094    pub fn harness_dir(&self) -> PathBuf {
3095        self.storage_dir().join(self.harness().storage_segment())
3096    }
3097
3098    pub fn inspect_dir(&self) -> PathBuf {
3099        if let Some(root) = self
3100            .canonical_cache_root_opt()
3101            .or_else(|| self.config().project_root.clone())
3102        {
3103            self.storage_dir()
3104                .join("inspect")
3105                .join(crate::path_identity::project_scope_key(&root))
3106        } else {
3107            self.storage_dir().join("inspect").join("unconfigured")
3108        }
3109    }
3110
3111    pub fn bash_tasks_dir(&self, session_id: &str) -> PathBuf {
3112        self.harness_dir()
3113            .join("bash-tasks")
3114            .join(hash_session(session_id))
3115    }
3116
3117    pub fn backups_dir(&self, session_id: &str, path_hash: &str) -> PathBuf {
3118        self.harness_dir()
3119            .join("backups")
3120            .join(hash_session(session_id))
3121            .join(path_hash)
3122    }
3123
3124    pub fn filters_dir(&self) -> PathBuf {
3125        self.harness_dir().join("filters")
3126    }
3127
3128    /// HOST-GLOBAL — NOT under harness_dir. Read by trust.rs across both harnesses.
3129    pub fn trust_file(&self) -> PathBuf {
3130        self.storage_dir().join("trusted-filter-projects.json")
3131    }
3132
3133    pub fn set_canonical_cache_root(&self, root: PathBuf) {
3134        debug_assert!(root.is_absolute());
3135        let root_changed = {
3136            let mut current = self.canonical_cache_root.lock();
3137            let changed = current.as_deref() != Some(root.as_path());
3138            *current = Some(root);
3139            changed
3140        };
3141        if root_changed {
3142            let mut tier2 = self
3143                .status_bar_tier2
3144                .write()
3145                .unwrap_or_else(std::sync::PoisonError::into_inner);
3146            let generation = tier2.generation.wrapping_add(1);
3147            *tier2 = StatusBarTier2 {
3148                generation,
3149                ..StatusBarTier2::default()
3150            };
3151            *self
3152                .status_bar_last_emitted
3153                .write()
3154                .unwrap_or_else(std::sync::PoisonError::into_inner) = None;
3155        }
3156    }
3157
3158    pub fn canonical_cache_root(&self) -> PathBuf {
3159        self.canonical_cache_root
3160            .lock()
3161            .clone()
3162            .expect("canonical_cache_root accessed before handle_configure")
3163    }
3164
3165    pub fn canonical_cache_root_opt(&self) -> Option<PathBuf> {
3166        self.canonical_cache_root.lock().clone()
3167    }
3168
3169    pub fn set_cache_role(&self, is_worktree_bridge: bool, git_common_dir: Option<PathBuf>) {
3170        *self.is_worktree_bridge.lock() = is_worktree_bridge;
3171        *self.git_common_dir.lock() = git_common_dir;
3172        // The configure-time worktree probe already applies the test seam, so
3173        // automatic Tier-2 scheduling follows the same effective root role as
3174        // callgraph cold-build gating while explicit inspect demand stays enabled.
3175        self.inspect_manager
3176            .set_automatic_tier2_refresh_allowed(!is_worktree_bridge);
3177        let artifact_read_only = self.shared_artifacts_read_only.load(Ordering::SeqCst);
3178        self.callgraph_writer
3179            .store(!is_worktree_bridge && !artifact_read_only, Ordering::SeqCst);
3180    }
3181
3182    pub fn set_artifact_owner(
3183        &self,
3184        status: Option<ArtifactOwnerStatus>,
3185        lease: Option<ArtifactOwnerLease>,
3186    ) {
3187        let read_only = status
3188            .as_ref()
3189            .is_some_and(|status| status.mode == ArtifactOwnerMode::ReadOnly);
3190        self.shared_artifacts_read_only
3191            .store(read_only, Ordering::SeqCst);
3192        self.callgraph_writer
3193            .store(!self.is_worktree_bridge() && !read_only, Ordering::SeqCst);
3194        self.inspect_writer.store(true, Ordering::SeqCst);
3195        *self.artifact_owner_status.lock() = status;
3196        *self.artifact_owner_lease.lock() = lease.map(crate::artifact_owner::register_heartbeat);
3197    }
3198
3199    pub fn set_cache_writer_capabilities(&self, callgraph_writer: bool, inspect_writer: bool) {
3200        self.callgraph_writer
3201            .store(callgraph_writer, Ordering::SeqCst);
3202        self.inspect_writer.store(inspect_writer, Ordering::SeqCst);
3203    }
3204
3205    pub fn callgraph_writer(&self) -> bool {
3206        self.callgraph_writer.load(Ordering::SeqCst)
3207    }
3208
3209    pub fn inspect_writer(&self) -> bool {
3210        self.inspect_writer.load(Ordering::SeqCst)
3211    }
3212
3213    pub fn shared_artifacts_read_only(&self) -> bool {
3214        !self.callgraph_writer()
3215    }
3216
3217    pub fn artifact_owner_status(&self) -> Option<ArtifactOwnerStatus> {
3218        self.artifact_owner_status.lock().clone()
3219    }
3220
3221    pub fn is_worktree_bridge(&self) -> bool {
3222        *self.is_worktree_bridge.lock()
3223    }
3224
3225    pub fn git_common_dir(&self) -> Option<PathBuf> {
3226        self.git_common_dir.lock().clone()
3227    }
3228
3229    /// Replace the current degraded-mode reasons. Empty vec = full-featured
3230    /// mode (no degradation). Called by `handle_configure` after deciding
3231    /// which subsystems to disable for this project root.
3232    pub fn set_degraded_reasons(&self, reasons: Vec<String>) {
3233        *self.degraded_reasons.lock() = reasons;
3234    }
3235
3236    pub fn set_heavy_root_work_allowed(&self, allowed: bool) {
3237        self.heavy_root_work_allowed
3238            .store(allowed, Ordering::SeqCst);
3239    }
3240
3241    pub fn heavy_root_work_allowed(&self) -> bool {
3242        self.heavy_root_work_allowed.load(Ordering::SeqCst) && !self.subc_lifecycle.is_unbound()
3243    }
3244
3245    fn try_heavy_root_work_allowed(&self) -> Option<bool> {
3246        if !self.heavy_root_work_allowed.load(Ordering::SeqCst) {
3247            return Some(false);
3248        }
3249        self.subc_lifecycle.try_is_bound()
3250    }
3251
3252    pub fn add_degraded_reason(&self, reason: impl Into<String>) -> bool {
3253        let reason = reason.into();
3254        let mut reasons = self.degraded_reasons.lock();
3255        if reasons.iter().any(|existing| existing == &reason) {
3256            return false;
3257        }
3258        reasons.push(reason);
3259        true
3260    }
3261
3262    /// Snapshot of current degraded-mode reasons. Order is stable
3263    /// (insertion order from `set_degraded_reasons`) so UI rendering and
3264    /// snapshot diffs are deterministic.
3265    pub fn degraded_reasons(&self) -> Vec<String> {
3266        self.degraded_reasons.lock().clone()
3267    }
3268
3269    /// True iff at least one degraded reason is recorded.
3270    pub fn is_degraded(&self) -> bool {
3271        !self.degraded_reasons.lock().is_empty()
3272    }
3273
3274    pub fn cache_role(&self) -> &'static str {
3275        if self.canonical_cache_root.lock().is_none() {
3276            "not_initialized"
3277        } else if self.is_worktree_bridge() {
3278            "worktree"
3279        } else if self.shared_artifacts_read_only.load(Ordering::SeqCst) {
3280            "read_only"
3281        } else {
3282            "main"
3283        }
3284    }
3285
3286    /// Access the persisted call graph store.
3287    pub fn callgraph_store(&self) -> &RwLock<Option<Arc<ReadonlyCallGraphStore>>> {
3288        &self.callgraph_store
3289    }
3290
3291    pub fn mark_callgraph_store_force_rebuild(&self) -> u64 {
3292        self.callgraph_store_force_requested
3293            .fetch_add(1, Ordering::SeqCst)
3294            .wrapping_add(1)
3295    }
3296
3297    pub(crate) fn pending_callgraph_store_force_token(&self) -> Option<u64> {
3298        let requested = self.callgraph_store_force_requested.load(Ordering::SeqCst);
3299        let fulfilled = self.callgraph_store_force_fulfilled.load(Ordering::SeqCst);
3300        (requested > fulfilled).then_some(requested)
3301    }
3302
3303    pub fn fulfill_callgraph_store_force_token(&self, token: u64) {
3304        self.callgraph_store_force_fulfilled
3305            .fetch_max(token, Ordering::SeqCst);
3306    }
3307
3308    pub fn callgraph_store_dir(&self) -> PathBuf {
3309        if let Some(root) = self.callgraph_project_root() {
3310            self.storage_dir()
3311                .join("callgraph")
3312                .join(self.memoized_artifact_cache_key(&root))
3313        } else {
3314            self.storage_dir().join("callgraph").join("unconfigured")
3315        }
3316    }
3317
3318    pub fn ensure_callgraph_store(
3319        &self,
3320    ) -> Result<Option<Arc<ReadonlyCallGraphStore>>, CallGraphStoreError> {
3321        self.ensure_callgraph_store_with_flag(true)
3322    }
3323
3324    fn ensure_callgraph_store_with_flag(
3325        &self,
3326        respect_config_flag: bool,
3327    ) -> Result<Option<Arc<ReadonlyCallGraphStore>>, CallGraphStoreError> {
3328        if respect_config_flag && !self.config().callgraph_store {
3329            return Ok(None);
3330        }
3331        if !self.heavy_root_work_allowed() {
3332            return Ok(None);
3333        }
3334        self.revalidate_callgraph_store_generation();
3335        let force_token = self.pending_callgraph_store_force_token();
3336        if force_token.is_none() {
3337            if let Some(store) = {
3338                let guard = self
3339                    .callgraph_store
3340                    .read()
3341                    .unwrap_or_else(std::sync::PoisonError::into_inner);
3342                guard.as_ref().map(Arc::clone)
3343            } {
3344                self.schedule_legacy_callgraph_migration_if_needed(
3345                    store.as_ref(),
3346                    store.project_root().to_path_buf(),
3347                    self.callgraph_store_dir(),
3348                );
3349                return Ok(Some(store));
3350            }
3351        }
3352
3353        let Some(project_root) = self.callgraph_project_root() else {
3354            return Ok(None);
3355        };
3356        let callgraph_dir = self.callgraph_store_dir();
3357
3358        // Preserve a readable legacy fallback while writer-capable processes
3359        // migrate it on the cold-build lane. Opening before the writer path is
3360        // also the cheap fast path for an already-published root generation.
3361        if force_token.is_none() {
3362            if let Some(store) =
3363                CallGraphStore::open_readonly(callgraph_dir.clone(), project_root.clone())?
3364            {
3365                let store = Arc::new(store);
3366                {
3367                    let mut guard = self
3368                        .callgraph_store
3369                        .write()
3370                        .unwrap_or_else(std::sync::PoisonError::into_inner);
3371                    *guard = Some(Arc::clone(&store));
3372                }
3373                self.schedule_legacy_callgraph_migration_if_needed(
3374                    store.as_ref(),
3375                    project_root,
3376                    callgraph_dir,
3377                );
3378                return Ok(Some(store));
3379            }
3380        }
3381
3382        if !self.callgraph_writer() {
3383            return Ok(None);
3384        }
3385        let build_generation = self.configure_generation();
3386        let persist_epoch_flag = self.callgraph_persist_epoch_flag();
3387        let Some(persist_epoch) = self
3388            .run_if_subc_bound_generation(build_generation, || self.next_callgraph_persist_epoch())
3389        else {
3390            return Ok(None);
3391        };
3392        let files = crate::callgraph::walk_project_files(&project_root).collect::<Vec<_>>();
3393        let (store, _stats) = crate::callgraph_store::with_publish_epoch(
3394            persist_epoch_flag.clone(),
3395            persist_epoch,
3396            || {
3397                if force_token.is_some() {
3398                    CallGraphStore::force_cold_build_with_lease_chunked(
3399                        callgraph_dir.clone(),
3400                        project_root.clone(),
3401                        &files,
3402                        self.config().callgraph_chunk_size,
3403                    )
3404                    .map(|(store, _stats)| (store, ()))
3405                } else {
3406                    CallGraphStore::ensure_built_with_lease_chunked(
3407                        callgraph_dir.clone(),
3408                        project_root.clone(),
3409                        &files,
3410                        self.config().callgraph_chunk_size,
3411                    )
3412                    .map(|(store, _stats)| (store, ()))
3413                }
3414            },
3415        )?;
3416        drop(store);
3417
3418        let Some(store) = CallGraphStore::open_readonly(callgraph_dir, project_root)? else {
3419            return Ok(None);
3420        };
3421        let store = Arc::new(store);
3422        self.run_if_subc_bound_generation(build_generation, || {
3423            if persist_epoch_flag.current() != persist_epoch {
3424                return None;
3425            }
3426            let mut guard = self
3427                .callgraph_store
3428                .write()
3429                .unwrap_or_else(std::sync::PoisonError::into_inner);
3430            *guard = Some(Arc::clone(&store));
3431            if let Some(force_token) = force_token {
3432                self.fulfill_callgraph_store_force_token(force_token);
3433            }
3434            Some(Arc::clone(&store))
3435        })
3436        .flatten()
3437        .map_or(Ok(None), |store| Ok(Some(store)))
3438    }
3439
3440    /// Resolve the project root used for the callgraph store: prefer the
3441    /// canonical cache root, falling back to the configured project root.
3442    pub fn callgraph_project_root(&self) -> Option<PathBuf> {
3443        self.canonical_cache_root_opt().or_else(|| {
3444            self.config()
3445                .project_root
3446                .clone()
3447                .map(|root| std::fs::canonicalize(&root).unwrap_or(root))
3448        })
3449    }
3450
3451    /// Drop a cached reader when another process published a newer generation.
3452    /// The next access reopens through the pointer and converges to that
3453    /// generation instead of serving a stale long-lived connection.
3454    pub fn revalidate_callgraph_store_generation(&self) {
3455        let (superseded, legacy_fallback) = {
3456            let guard = self
3457                .callgraph_store
3458                .read()
3459                .unwrap_or_else(std::sync::PoisonError::into_inner);
3460            guard
3461                .as_ref()
3462                .map(|store| (!store.is_current(), store.is_legacy_fallback()))
3463                .unwrap_or((false, false))
3464        };
3465        if !superseded {
3466            return;
3467        }
3468        // A local migration publishes its pointer just before sending the new
3469        // store to the main-loop drain. Keep queries on the fallback during that
3470        // narrow handoff instead of reporting a transient Building state.
3471        if legacy_fallback && self.callgraph_store_rx.lock().is_some() {
3472            return;
3473        }
3474        let mut guard = self
3475            .callgraph_store
3476            .write()
3477            .unwrap_or_else(std::sync::PoisonError::into_inner);
3478        *guard = None;
3479    }
3480
3481    pub fn callgraph_store_for_ops(&self) -> CallgraphStoreAccess {
3482        if !self.heavy_root_work_allowed() {
3483            return CallgraphStoreAccess::Unavailable;
3484        }
3485        let operation_generation = self.configure_generation();
3486
3487        // Converge to a newer generation another process (or a local cold
3488        // rebuild) may have published: if our resident store is superseded, drop
3489        // it so the open path below reopens via the pointer. Cheap pointer read.
3490        self.revalidate_callgraph_store_generation();
3491        let force_token = self.pending_callgraph_store_force_token();
3492        if force_token.is_none() {
3493            if let Some(store) = {
3494                let guard = self
3495                    .callgraph_store
3496                    .read()
3497                    .unwrap_or_else(std::sync::PoisonError::into_inner);
3498                guard.as_ref().map(Arc::clone)
3499            } {
3500                self.schedule_legacy_callgraph_migration_if_needed(
3501                    store.as_ref(),
3502                    store.project_root().to_path_buf(),
3503                    self.callgraph_store_dir(),
3504                );
3505                return CallgraphStoreAccess::Ready(store);
3506            }
3507        }
3508
3509        // A background build is already running; don't start a second one.
3510        if self.callgraph_store_rx.lock().is_some() {
3511            return CallgraphStoreAccess::Building;
3512        }
3513
3514        let Some(project_root) = self.callgraph_project_root() else {
3515            return CallgraphStoreAccess::Unavailable;
3516        };
3517        let callgraph_dir = self.callgraph_store_dir();
3518
3519        if force_token.is_none() {
3520            match CallGraphStore::open_readonly(callgraph_dir.clone(), project_root.clone()) {
3521                Ok(Some(store)) => {
3522                    let store = Arc::new(store);
3523                    let installed = self.run_if_subc_bound_generation(operation_generation, || {
3524                        let mut guard = self
3525                            .callgraph_store
3526                            .write()
3527                            .unwrap_or_else(std::sync::PoisonError::into_inner);
3528                        *guard = Some(Arc::clone(&store));
3529                        Arc::clone(&store)
3530                    });
3531                    let Some(store) = installed else {
3532                        return CallgraphStoreAccess::Unavailable;
3533                    };
3534                    self.schedule_legacy_callgraph_migration_if_needed(
3535                        store.as_ref(),
3536                        project_root.clone(),
3537                        callgraph_dir.clone(),
3538                    );
3539                    return CallgraphStoreAccess::Ready(store);
3540                }
3541                Ok(None) => {
3542                    if !self.callgraph_writer() {
3543                        return CallgraphStoreAccess::Unavailable;
3544                    }
3545                }
3546                Err(error) => {
3547                    if !self.callgraph_writer() {
3548                        return CallgraphStoreAccess::Unavailable;
3549                    }
3550                    crate::slog_warn!(
3551                        "callgraph read-only open failed before writer promotion: {}",
3552                        error
3553                    );
3554                }
3555            }
3556        } else if !self.callgraph_writer() {
3557            return CallgraphStoreAccess::Unavailable;
3558        }
3559
3560        if self.semantic_cold_seed_active() {
3561            self.defer_callgraph_store_warm_for_semantic_cold_seed();
3562            return CallgraphStoreAccess::Building;
3563        }
3564
3565        // Cold build required: run it off the request thread and return
3566        // `Building` so the agent retries (the watcher keeps the store fresh
3567        // once it lands). By default this never blocks the request thread.
3568        //
3569        // `AFT_CALLGRAPH_BUILD_WAIT_MS` (default 0) optionally waits a bounded
3570        // window inline for the build to land before returning `Building`; tests
3571        // set it large so fixture builds resolve to `Ready` synchronously.
3572        let work = if let Some(force_token) = force_token {
3573            CallgraphBackgroundWork::ForceRebuild(force_token)
3574        } else {
3575            CallgraphBackgroundWork::Ensure
3576        };
3577        if !self.spawn_callgraph_store_cold_build(project_root.clone(), callgraph_dir.clone(), work)
3578        {
3579            return CallgraphStoreAccess::Building;
3580        }
3581
3582        let wait = callgraph_build_wait_window();
3583        if !wait.is_zero() {
3584            let (received, receiver_generation, receiver_epoch) = {
3585                let rx_ref = self.callgraph_store_rx.lock();
3586                let Some(rx) = rx_ref.as_ref() else {
3587                    return CallgraphStoreAccess::Building;
3588                };
3589                (
3590                    rx.recv_timeout(wait),
3591                    self.callgraph_store_rx_generation(),
3592                    self.callgraph_store_rx_epoch(),
3593                )
3594            };
3595            match received {
3596                Ok(CallGraphStoreBuildEvent::Ready {
3597                    store,
3598                    fulfilled_force_token,
3599                    publication_epoch,
3600                }) => {
3601                    if self.callgraph_persist_epoch_flag().current() != publication_epoch {
3602                        // Superseded publication: a newer configure owns the
3603                        // pointer. Clear the receiver and report Building so the
3604                        // replacement build's event installs instead.
3605                        drop(store);
3606                        let _ = self.with_current_callgraph_store_rx(
3607                            receiver_generation,
3608                            receiver_epoch,
3609                            |receiver| {
3610                                *receiver = None;
3611                            },
3612                        );
3613                        return CallgraphStoreAccess::Building;
3614                    }
3615                    // The completed build owns the writer lease until dropped;
3616                    // release it before reopening the published generation.
3617                    remove_callgraph_pointer_before_inline_reopen_for_test(&callgraph_dir, &store);
3618                    drop(store);
3619                    let reopened =
3620                        CallGraphStore::open_readonly(callgraph_dir.clone(), project_root.clone());
3621                    let mut pending = Vec::new();
3622                    let outcome = self.with_current_callgraph_store_rx(
3623                        receiver_generation,
3624                        receiver_epoch,
3625                        |receiver| {
3626                            *receiver = None;
3627                            match reopened {
3628                                Ok(Some(store)) => {
3629                                    let ready = Arc::new(store);
3630                                    pending = self.take_pending_callgraph_store_paths();
3631                                    *self
3632                                        .callgraph_store
3633                                        .write()
3634                                        .unwrap_or_else(std::sync::PoisonError::into_inner) =
3635                                        Some(Arc::clone(&ready));
3636                                    if let Some(force_token) = fulfilled_force_token {
3637                                        self.fulfill_callgraph_store_force_token(force_token);
3638                                    }
3639                                    CallgraphStoreAccess::Ready(ready)
3640                                }
3641                                Ok(None) => CallgraphStoreAccess::Building,
3642                                Err(error) => CallgraphStoreAccess::Error(error),
3643                            }
3644                        },
3645                    );
3646                    let Some(outcome) = outcome else {
3647                        return if self.subc_unbound_quiesced()
3648                            || self.configure_generation() != receiver_generation
3649                        {
3650                            CallgraphStoreAccess::Unavailable
3651                        } else {
3652                            CallgraphStoreAccess::Building
3653                        };
3654                    };
3655                    if !pending.is_empty() {
3656                        let _ = self.enqueue_callgraph_store_refresh(pending);
3657                    }
3658                    if matches!(&outcome, CallgraphStoreAccess::Ready(_)) {
3659                        let _ = self.request_tier2_refresh_pull();
3660                    }
3661                    return outcome;
3662                }
3663                Ok(CallGraphStoreBuildEvent::Settled) => {
3664                    let _ = self.with_current_callgraph_store_rx(
3665                        receiver_generation,
3666                        receiver_epoch,
3667                        |receiver| *receiver = None,
3668                    );
3669                    return CallgraphStoreAccess::Building;
3670                }
3671                Err(crossbeam_channel::RecvTimeoutError::Timeout) => {}
3672                Err(crossbeam_channel::RecvTimeoutError::Disconnected) => {
3673                    let _ = self.with_current_callgraph_store_rx(
3674                        receiver_generation,
3675                        receiver_epoch,
3676                        |receiver| *receiver = None,
3677                    );
3678                }
3679            }
3680        }
3681        CallgraphStoreAccess::Building
3682    }
3683
3684    fn schedule_legacy_callgraph_migration_if_needed(
3685        &self,
3686        store: &ReadonlyCallGraphStore,
3687        project_root: PathBuf,
3688        callgraph_dir: PathBuf,
3689    ) {
3690        if !store.is_legacy_fallback()
3691            || !self.callgraph_writer()
3692            || !self.heavy_root_work_allowed()
3693        {
3694            return;
3695        }
3696        if self.semantic_cold_seed_active() {
3697            self.defer_callgraph_store_warm_for_semantic_cold_seed();
3698            return;
3699        }
3700        let _ = self.spawn_callgraph_store_cold_build(
3701            project_root,
3702            callgraph_dir,
3703            CallgraphBackgroundWork::LegacyMigration,
3704        );
3705    }
3706
3707    fn configured_callgraph_keys(&self, current_root: &Path) -> BTreeSet<String> {
3708        let mut roots = self
3709            .configured_session_roots
3710            .lock()
3711            .iter()
3712            .map(|(root, _session)| root.clone())
3713            .collect::<BTreeSet<_>>();
3714        roots.insert(current_root.to_path_buf());
3715        roots
3716            .iter()
3717            .map(|root| crate::search_index::artifact_cache_key(root))
3718            .collect()
3719    }
3720
3721    /// Atomically mark root-keyed callgraph maintenance in flight and spawn it
3722    /// on the cold-build lane. The same receiver/install path handles cold
3723    /// builds and legacy migrations, so watcher edits are queued and replayed
3724    /// against whichever root-keyed generation publishes.
3725    fn spawn_callgraph_store_cold_build(
3726        &self,
3727        project_root: PathBuf,
3728        callgraph_dir: PathBuf,
3729        work: CallgraphBackgroundWork,
3730    ) -> bool {
3731        if !self.heavy_root_work_allowed() || !self.callgraph_writer() {
3732            return false;
3733        }
3734        let generation = self.configure_generation();
3735        self.run_if_subc_bound_generation(generation, || {
3736            self.spawn_callgraph_store_cold_build_admitted(project_root, callgraph_dir, work)
3737        })
3738        .unwrap_or(false)
3739    }
3740
3741    /// Start a callgraph worker after lifecycle admission has been acquired.
3742    fn spawn_callgraph_store_cold_build_admitted(
3743        &self,
3744        project_root: PathBuf,
3745        callgraph_dir: PathBuf,
3746        work: CallgraphBackgroundWork,
3747    ) -> bool {
3748        let session_id = crate::log_ctx::current_session();
3749        let chunk_size = self.config().callgraph_chunk_size;
3750        let build_generation = self.configure_generation();
3751        let generation_flag = self.configure_generation_flag();
3752        let configured_keys = self.configured_callgraph_keys(&project_root);
3753        let summary_logged = Arc::clone(&self.callgraph_legacy_migration_summary_logged);
3754
3755        let mut rx_guard = self.callgraph_store_rx.lock();
3756        if rx_guard.is_some() {
3757            return false;
3758        }
3759
3760        let Some(permit) = crate::cold_build_limiter::try_acquire() else {
3761            crate::slog_info!(
3762                "callgraph store background work deferred by cold build limit ({})",
3763                crate::cold_build_limiter::limit()
3764            );
3765            return false;
3766        };
3767
3768        let force_token = match work {
3769            CallgraphBackgroundWork::ForceRebuild(token) => Some(token),
3770            CallgraphBackgroundWork::Ensure | CallgraphBackgroundWork::LegacyMigration => None,
3771        };
3772        let (tx, rx) = crossbeam_channel::unbounded::<CallGraphStoreBuildEvent>();
3773        self.note_callgraph_store_rx_generation(build_generation);
3774        self.next_callgraph_store_rx_epoch();
3775        *rx_guard = Some(rx);
3776        let persist_epoch = self.next_callgraph_persist_epoch();
3777        let persist_epoch_flag = self.callgraph_persist_epoch_flag();
3778
3779        CALLGRAPH_COLD_BUILD_SPAWN_COUNT.fetch_add(1, Ordering::SeqCst);
3780
3781        std::thread::spawn(move || {
3782            let _permit = permit;
3783            let mut settlement = CallGraphStoreBuildSettlement::new(tx, force_token, persist_epoch);
3784            crate::log_ctx::with_session(session_id, || {
3785                wait_on_callgraph_build_start_gate(&project_root);
3786                if persist_epoch_flag.current() != persist_epoch {
3787                    crate::slog_info!(
3788                        "callgraph store background work skipped for superseded epoch {}",
3789                        persist_epoch
3790                    );
3791                    return;
3792                }
3793                let built = crate::callgraph_store::with_publish_epoch(
3794                    persist_epoch_flag,
3795                    persist_epoch,
3796                    || match work {
3797                        CallgraphBackgroundWork::LegacyMigration => {
3798                            CallGraphStore::migrate_legacy_with_lease(
3799                                callgraph_dir.clone(),
3800                                project_root.clone(),
3801                            )
3802                        }
3803                        CallgraphBackgroundWork::ForceRebuild(_) => {
3804                            let files = crate::callgraph::walk_project_files(&project_root)
3805                                .collect::<Vec<_>>();
3806                            CallGraphStore::force_cold_build_with_lease_chunked(
3807                                callgraph_dir.clone(),
3808                                project_root.clone(),
3809                                &files,
3810                                chunk_size,
3811                            )
3812                            .map(|(store, _)| Some(store))
3813                        }
3814                        CallgraphBackgroundWork::Ensure => {
3815                            let files = crate::callgraph::walk_project_files(&project_root)
3816                                .collect::<Vec<_>>();
3817                            CallGraphStore::ensure_built_with_lease_chunked(
3818                                callgraph_dir.clone(),
3819                                project_root.clone(),
3820                                &files,
3821                                chunk_size,
3822                            )
3823                            .map(|(store, _)| Some(store))
3824                        }
3825                    },
3826                );
3827                match built {
3828                    Ok(Some(store)) => {
3829                        if store.is_legacy_migration() {
3830                            match crate::callgraph_store::all_legacy_partitions_migrated_for_keys(
3831                                &callgraph_dir,
3832                                &configured_keys,
3833                            ) {
3834                                Ok(true)
3835                                    if summary_logged
3836                                        .compare_exchange(
3837                                            false,
3838                                            true,
3839                                            Ordering::SeqCst,
3840                                            Ordering::SeqCst,
3841                                        )
3842                                        .is_ok() =>
3843                                {
3844                                    crate::slog_info!(
3845                                        "all legacy callgraph partitions migrated for configured roots"
3846                                    );
3847                                }
3848                                Ok(_) => {}
3849                                Err(error) => crate::slog_warn!(
3850                                    "failed to inspect legacy callgraph migration completion: {}",
3851                                    error
3852                                ),
3853                            }
3854                        }
3855                        if generation_flag.load(Ordering::SeqCst) == build_generation {
3856                            settlement.ready(store);
3857                        } else {
3858                            crate::slog_info!(
3859                                "callgraph store warm build result discarded for stale generation {}",
3860                                build_generation
3861                            );
3862                        }
3863                    }
3864                    Ok(None) => {}
3865                    Err(crate::callgraph_store::CallGraphStoreError::Superseded) => {
3866                        crate::slog_info!(
3867                            "callgraph store disk publication skipped for superseded epoch {}",
3868                            persist_epoch
3869                        );
3870                    }
3871                    Err(error) => {
3872                        crate::slog_warn!("callgraph store background work failed: {}", error);
3873                    }
3874                }
3875            });
3876        });
3877        true
3878    }
3879
3880    /// Access the callgraph-store background-build receiver (drained by the
3881    /// main loop once the cold build completes).
3882    pub fn callgraph_store_rx(
3883        &self,
3884    ) -> &parking_lot::Mutex<Option<crossbeam_channel::Receiver<CallGraphStoreBuildEvent>>> {
3885        &self.callgraph_store_rx
3886    }
3887
3888    /// Commit a dequeued result only while its lifecycle and receiver identity
3889    /// remain current. Lifecycle admission is intentionally acquired first,
3890    /// matching worker-start paths and preventing a lock-order cycle.
3891    #[doc(hidden)]
3892    pub fn with_current_callgraph_store_rx<R>(
3893        &self,
3894        generation: u64,
3895        epoch: u64,
3896        action: impl FnOnce(&mut Option<crossbeam_channel::Receiver<CallGraphStoreBuildEvent>>) -> R,
3897    ) -> Option<R> {
3898        self.run_if_subc_bound_generation(generation, || {
3899            let mut receiver = self.callgraph_store_rx.lock();
3900            if receiver.is_none()
3901                || self.callgraph_store_rx_generation() != generation
3902                || self.callgraph_store_rx_epoch() != epoch
3903            {
3904                return None;
3905            }
3906            Some(action(&mut receiver))
3907        })
3908        .flatten()
3909    }
3910
3911    pub(crate) fn retire_callgraph_store_rx(&self) {
3912        let mut receiver = self.callgraph_store_rx.lock();
3913        *receiver = None;
3914        self.next_callgraph_store_rx_epoch();
3915    }
3916
3917    pub(crate) fn note_callgraph_store_rx_generation(&self, generation: u64) {
3918        self.callgraph_store_rx_generation
3919            .store(generation, Ordering::SeqCst);
3920    }
3921
3922    #[doc(hidden)]
3923    pub fn callgraph_store_rx_generation(&self) -> u64 {
3924        self.callgraph_store_rx_generation.load(Ordering::SeqCst)
3925    }
3926
3927    pub(crate) fn next_callgraph_store_rx_epoch(&self) -> u64 {
3928        self.callgraph_store_rx_epoch
3929            .fetch_add(1, Ordering::SeqCst)
3930            .wrapping_add(1)
3931    }
3932
3933    #[doc(hidden)]
3934    pub fn callgraph_store_rx_epoch(&self) -> u64 {
3935        self.callgraph_store_rx_epoch.load(Ordering::SeqCst)
3936    }
3937
3938    pub(crate) fn next_callgraph_persist_epoch(&self) -> u64 {
3939        self.callgraph_persist_epoch.next()
3940    }
3941
3942    #[doc(hidden)]
3943    pub fn callgraph_persist_epoch_flag(&self) -> crate::root_cache::ArtifactPublishEpoch {
3944        self.callgraph_persist_epoch.clone()
3945    }
3946
3947    /// Record source-file paths that could not be applied to the writable store
3948    /// so the next ready-store replay can refresh them.
3949    pub fn add_pending_callgraph_store_paths<I>(&self, paths: I)
3950    where
3951        I: IntoIterator<Item = PathBuf>,
3952    {
3953        self.pending_callgraph_store_paths.lock().extend(paths);
3954    }
3955
3956    pub fn enqueue_callgraph_store_refresh<I>(&self, paths: I) -> bool
3957    where
3958        I: IntoIterator<Item = PathBuf>,
3959    {
3960        let generation = self.configure_generation();
3961        self.enqueue_callgraph_store_refresh_for_generation(paths, generation)
3962    }
3963
3964    pub(crate) fn enqueue_callgraph_store_refresh_for_generation<I>(
3965        &self,
3966        paths: I,
3967        generation: u64,
3968    ) -> bool
3969    where
3970        I: IntoIterator<Item = PathBuf>,
3971    {
3972        let paths = paths.into_iter().collect::<Vec<_>>();
3973        if paths.is_empty() {
3974            return true;
3975        }
3976        self.run_if_subc_bound_generation(generation, || {
3977            if !self.callgraph_writer() {
3978                self.add_pending_callgraph_store_paths(paths);
3979                return false;
3980            }
3981            let Some(project_root) = self.callgraph_project_root() else {
3982                self.add_pending_callgraph_store_paths(paths);
3983                return false;
3984            };
3985
3986            // The ticket fences the batch against lifecycle transitions and
3987            // cold-build publications: a superseded batch defers its paths to
3988            // the pending sink instead of committing into a store generation
3989            // that a newer configure no longer owns.
3990            let ticket = crate::callgraph_store::CallgraphRefreshTicket::new(
3991                self.subc_lifecycle_admission(),
3992                self.configure_generation_flag(),
3993                generation,
3994                self.callgraph_persist_epoch_flag(),
3995                self.callgraph_persist_epoch_flag().current(),
3996            );
3997            crate::callgraph_store::enqueue_callgraph_store_refresh_fenced(
3998                self.callgraph_store_dir(),
3999                project_root,
4000                paths,
4001                Arc::clone(&self.pending_callgraph_store_paths),
4002                ticket,
4003            )
4004        })
4005        .unwrap_or(false)
4006    }
4007
4008    /// Take and clear paths waiting for a ready writable store.
4009    ///
4010    /// Paths outside the current project root are dropped: the pending sink is
4011    /// shared with detached refresh batches, so a batch superseded by a root
4012    /// change can defer paths from the PREVIOUS root after configure cleared
4013    /// the sink. Replaying those would index foreign files into the new root's
4014    /// store (refresh accepts absolute out-of-root paths).
4015    pub fn take_pending_callgraph_store_paths(&self) -> Vec<PathBuf> {
4016        let roots: Vec<PathBuf> = [
4017            self.canonical_cache_root_opt(),
4018            self.config().project_root.clone(),
4019        ]
4020        .into_iter()
4021        .flatten()
4022        .collect();
4023        std::mem::take(&mut *self.pending_callgraph_store_paths.lock())
4024            .into_iter()
4025            .filter(|path| {
4026                let in_root = pending_path_in_roots(path, &roots);
4027                if !in_root {
4028                    crate::slog_debug!(
4029                        "dropping pending callgraph path outside current root: {}",
4030                        path.display()
4031                    );
4032                }
4033                in_root
4034            })
4035            .collect()
4036    }
4037
4038    /// Access the search index.
4039    pub fn search_index(&self) -> &RwLock<Option<SearchIndex>> {
4040        &self.search_index
4041    }
4042
4043    /// Access the search-index build receiver.
4044    pub fn search_index_rx(&self) -> &RwLock<Option<crossbeam_channel::Receiver<SearchIndex>>> {
4045        &self.search_index_rx
4046    }
4047
4048    pub(crate) fn install_search_index_rx(
4049        &self,
4050        receiver: crossbeam_channel::Receiver<SearchIndex>,
4051        generation: u64,
4052    ) -> u64 {
4053        let mut slot = self
4054            .search_index_rx
4055            .write()
4056            .unwrap_or_else(std::sync::PoisonError::into_inner);
4057        self.note_search_index_rx_generation(generation);
4058        let epoch = self.next_search_index_rx_epoch();
4059        *slot = Some(receiver);
4060        epoch
4061    }
4062
4063    pub(crate) fn search_index_rx_terminal_guard(&self, epoch: u64) -> ReceiverTerminalGuard {
4064        ReceiverTerminalGuard::new(Arc::clone(&self.search_index_rx_terminal_epoch), epoch)
4065    }
4066
4067    /// Keep generation/epoch validation and receiver mutation under the same
4068    /// lock used by receiver installation.
4069    pub(crate) fn with_current_search_index_rx<R>(
4070        &self,
4071        generation: u64,
4072        epoch: u64,
4073        action: impl FnOnce(&mut Option<crossbeam_channel::Receiver<SearchIndex>>) -> R,
4074    ) -> Option<R> {
4075        self.run_if_subc_bound_generation(generation, || {
4076            let mut receiver = self
4077                .search_index_rx
4078                .write()
4079                .unwrap_or_else(std::sync::PoisonError::into_inner);
4080            if receiver.is_none()
4081                || self.search_index_rx_generation() != generation
4082                || self.search_index_rx_epoch() != epoch
4083            {
4084                return None;
4085            }
4086            Some(action(&mut receiver))
4087        })
4088        .flatten()
4089    }
4090
4091    pub(crate) fn retire_search_index_rx(&self) {
4092        let mut receiver = self
4093            .search_index_rx
4094            .write()
4095            .unwrap_or_else(std::sync::PoisonError::into_inner);
4096        *receiver = None;
4097        self.next_search_index_rx_epoch();
4098    }
4099
4100    pub(crate) fn note_search_index_rx_generation(&self, generation: u64) {
4101        self.search_index_rx_generation
4102            .store(generation, Ordering::SeqCst);
4103    }
4104
4105    pub(crate) fn search_index_rx_generation(&self) -> u64 {
4106        self.search_index_rx_generation.load(Ordering::SeqCst)
4107    }
4108
4109    pub(crate) fn next_search_index_rx_epoch(&self) -> u64 {
4110        self.search_index_rx_epoch
4111            .fetch_add(1, Ordering::SeqCst)
4112            .wrapping_add(1)
4113    }
4114
4115    pub(crate) fn search_index_rx_epoch(&self) -> u64 {
4116        self.search_index_rx_epoch.load(Ordering::SeqCst)
4117    }
4118
4119    /// Allow one automatic search-index replacement load per configure
4120    /// generation. The drain disconnect path calls this before rescheduling a
4121    /// load whose worker exited without delivering an index; capping it at one
4122    /// prevents a persistently failing worker from being relaunched in a loop on
4123    /// the drain thread. After the cap is hit, the query-triggered reload
4124    /// (`trigger_search_index_reload_if_evicted`) remains the recovery path.
4125    pub(crate) fn allow_search_index_disconnect_reschedule(&self) -> bool {
4126        const MAX_REPLACEMENTS_PER_GENERATION: u32 = 1;
4127        let generation = self.configure_generation();
4128        let mut state = self.search_index_disconnect_reschedule.lock();
4129        if state.0 != generation {
4130            *state = (generation, 0);
4131        }
4132        if state.1 >= MAX_REPLACEMENTS_PER_GENERATION {
4133            return false;
4134        }
4135        state.1 += 1;
4136        true
4137    }
4138
4139    pub(crate) fn next_search_persist_epoch(&self) -> u64 {
4140        self.search_persist_epoch.next()
4141    }
4142
4143    pub(crate) fn search_persist_epoch_flag(&self) -> crate::root_cache::ArtifactPublishEpoch {
4144        self.search_persist_epoch.clone()
4145    }
4146
4147    pub fn add_pending_search_index_paths<I>(&self, paths: I)
4148    where
4149        I: IntoIterator<Item = PathBuf>,
4150    {
4151        let paths = paths.into_iter().collect::<Vec<_>>();
4152        if !paths.is_empty() {
4153            self.invalidate_warm_verify_memo();
4154            self.pending_search_index_paths.lock().extend(paths);
4155        }
4156    }
4157
4158    pub fn take_pending_search_index_paths(&self) -> Vec<PathBuf> {
4159        std::mem::take(&mut *self.pending_search_index_paths.lock())
4160            .into_iter()
4161            .collect()
4162    }
4163
4164    pub fn add_pending_semantic_index_paths<I>(&self, paths: I)
4165    where
4166        I: IntoIterator<Item = PathBuf>,
4167    {
4168        let paths = paths.into_iter().collect::<Vec<_>>();
4169        if !paths.is_empty() {
4170            self.invalidate_warm_verify_memo();
4171            self.pending_semantic_index_paths.lock().extend(paths);
4172        }
4173    }
4174
4175    pub(crate) fn invalidate_warm_verify_memo(&self) {
4176        if let Some(root) = self.canonical_cache_root_opt() {
4177            crate::cache_freshness::invalidate_verify_memo(&root);
4178        }
4179    }
4180
4181    pub fn take_pending_semantic_index_paths(&self) -> Vec<PathBuf> {
4182        std::mem::take(&mut *self.pending_semantic_index_paths.lock())
4183            .into_iter()
4184            .collect()
4185    }
4186
4187    pub fn mark_pending_semantic_corpus_refresh(&self) {
4188        *self.pending_semantic_corpus_refresh.lock() = true;
4189    }
4190
4191    pub fn take_pending_semantic_corpus_refresh(&self) -> bool {
4192        std::mem::take(&mut *self.pending_semantic_corpus_refresh.lock())
4193    }
4194
4195    pub fn clear_pending_index_updates(&self) {
4196        self.pending_search_index_paths.lock().clear();
4197        self.pending_callgraph_store_paths.lock().clear();
4198        self.pending_tier2_paths.lock().clear();
4199        self.pending_semantic_index_paths.lock().clear();
4200        *self.pending_semantic_corpus_refresh.lock() = false;
4201    }
4202
4203    /// Take the retained pending reconciliation state for a transactional
4204    /// teardown. The caller commits the disposal by dropping the returned
4205    /// state after eviction succeeds, or restores it with
4206    /// [`Self::restore_pending_reconciliation_state`] when eviction is blocked
4207    /// by a secondary blocker (running bash, in-flight builds): the paths are
4208    /// the only repair record for consumed watcher events, and the root may
4209    /// rebind before the next reap attempt.
4210    pub(crate) fn take_pending_reconciliation_state(&self) -> PendingReconciliationState {
4211        PendingReconciliationState {
4212            search: std::mem::take(&mut *self.pending_search_index_paths.lock()),
4213            callgraph: std::mem::take(&mut *self.pending_callgraph_store_paths.lock()),
4214            tier2: std::mem::take(&mut *self.pending_tier2_paths.lock()),
4215            semantic: std::mem::take(&mut *self.pending_semantic_index_paths.lock()),
4216            corpus_refresh: std::mem::take(&mut *self.pending_semantic_corpus_refresh.lock()),
4217        }
4218    }
4219
4220    pub(crate) fn restore_pending_reconciliation_state(&self, state: PendingReconciliationState) {
4221        self.pending_search_index_paths.lock().extend(state.search);
4222        self.pending_callgraph_store_paths
4223            .lock()
4224            .extend(state.callgraph);
4225        self.pending_tier2_paths.lock().extend(state.tier2);
4226        self.pending_semantic_index_paths
4227            .lock()
4228            .extend(state.semantic);
4229        if state.corpus_refresh {
4230            *self.pending_semantic_corpus_refresh.lock() = true;
4231        }
4232    }
4233
4234    /// Cancel artifact work that no longer has a bound daemon route to consume it.
4235    /// `mark_subc_unbound` advances the generation under the lifecycle admission
4236    /// gate before this cleanup runs. Clearing receivers lets a later rebind
4237    /// schedule fresh work instead of adopting a disconnected worker forever.
4238    ///
4239    /// Pending watcher-derived path sets are RETAINED: a pre-unbind artifact
4240    /// worker may legitimately finish generation-safe disk persistence during
4241    /// the unbound window (content generation and persist epochs deliberately
4242    /// do not advance on route teardown), and those paths are the only record
4243    /// that its artifact is content-stale. Rebind replays them. Disposal of
4244    /// pending state belongs to non-equivalent configure and TTL eviction
4245    /// (transactional take in the TTL reaper), whose strict invalidation
4246    /// subsumes their purpose.
4247    pub(crate) fn cancel_unbound_artifact_work(&self) {
4248        // A cancelled non-ready search corpus refresh left the resident index
4249        // marked not-ready; retiring its receiver alone would strand it
4250        // (equivalent rebind only reloads a MISSING index). Drop the resident
4251        // index too so the rebind's artifact setup reloads from disk and the
4252        // retained pending paths repair it on install.
4253        let search_refresh_cancelled = self
4254            .search_index_rx
4255            .read()
4256            .unwrap_or_else(std::sync::PoisonError::into_inner)
4257            .is_some();
4258        self.retire_search_index_rx();
4259        if search_refresh_cancelled {
4260            let mut resident = self
4261                .search_index
4262                .write()
4263                .unwrap_or_else(std::sync::PoisonError::into_inner);
4264            if resident.as_ref().is_some_and(|index| !index.ready) {
4265                *resident = None;
4266            }
4267        }
4268        self.retire_callgraph_store_rx();
4269        let semantic_cancelled = self.semantic_index_rx.lock().is_some();
4270        self.retire_semantic_index_rx();
4271        let semantic_refresh_cancelled = self.semantic_refresh_event_rx.lock().is_some();
4272        self.clear_semantic_refresh_worker();
4273        self.reset_semantic_cold_seed_gate_for_configure();
4274        let _ = self.inspect_manager.discard_completions();
4275        let _ = self.take_new_reuse_completions();
4276        if semantic_cancelled || semantic_refresh_cancelled {
4277            let has_index = self
4278                .semantic_index
4279                .read()
4280                .unwrap_or_else(std::sync::PoisonError::into_inner)
4281                .is_some();
4282            // In-flight refreshing files were consumed from the watcher; the
4283            // cancelled worker will never re-embed them. Transfer them to the
4284            // retained pending set so the rebind's replacement worker does.
4285            {
4286                let mut status = self
4287                    .semantic_index_status
4288                    .write()
4289                    .unwrap_or_else(std::sync::PoisonError::into_inner);
4290                let refreshing = status.take_refreshing_files();
4291                if !refreshing.is_empty() {
4292                    self.pending_semantic_index_paths.lock().extend(refreshing);
4293                }
4294                if status.corpus_refresh_in_flight() {
4295                    *self.pending_semantic_corpus_refresh.lock() = true;
4296                }
4297                *status = if has_index {
4298                    SemanticIndexStatus::ready()
4299                } else {
4300                    SemanticIndexStatus::Disabled
4301                };
4302            }
4303        }
4304    }
4305
4306    /// Gate every watcher-maintained artifact after the last route detaches. Files
4307    /// may change before the watcher is restored, so a later bind must reconcile
4308    /// from disk instead of serving retained snapshots that missed those edits.
4309    pub(crate) fn invalidate_artifacts_after_watcher_gap(&self) {
4310        self.next_search_persist_epoch();
4311        self.next_semantic_persist_epoch();
4312        self.next_callgraph_persist_epoch();
4313
4314        self.search_index
4315            .write()
4316            .unwrap_or_else(std::sync::PoisonError::into_inner)
4317            .take();
4318        self.semantic_index
4319            .write()
4320            .unwrap_or_else(std::sync::PoisonError::into_inner)
4321            .take();
4322        self.callgraph_store
4323            .write()
4324            .unwrap_or_else(std::sync::PoisonError::into_inner)
4325            .take();
4326        // Keep semantic status reloadable when the feature is enabled: the
4327        // query path's self-healing reload only fires from Ready (or Failed on
4328        // read-only roots), so Disabled would strand an already-bound root
4329        // with no way back short of a reconfigure. The advanced persist epoch
4330        // and strict verify memo force the reload to re-verify from disk.
4331        *self
4332            .semantic_index_status
4333            .write()
4334            .unwrap_or_else(std::sync::PoisonError::into_inner) = if self.config().semantic_search {
4335            SemanticIndexStatus::ready()
4336        } else {
4337            SemanticIndexStatus::Disabled
4338        };
4339        // A force token is only fulfillable by a local writer build; read-only
4340        // roots follow the owner's published pointer and would be stuck
4341        // permanently unavailable behind an unfulfillable token.
4342        if self.callgraph_writer() {
4343            self.mark_callgraph_store_force_rebuild();
4344        }
4345
4346        if let Some(root) = self
4347            .canonical_cache_root_opt()
4348            .or_else(|| self.config().project_root.clone())
4349        {
4350            crate::cache_freshness::invalidate_verify_memo_strict(&root);
4351        }
4352        self.borrowed_index_cache.lock().clear();
4353        self.inspect_manager.evict_idle_caches();
4354        self.reset_symbol_cache();
4355        self.clear_tsconfig_membership_cache();
4356    }
4357
4358    fn drain_search_index_events_for_graceful_shutdown(&self) {
4359        crate::runtime_drain::drain_watcher_events(self);
4360        crate::runtime_drain::drain_search_index_events(self);
4361    }
4362
4363    fn search_index_build_in_progress(&self) -> bool {
4364        self.search_index_rx()
4365            .read()
4366            .unwrap_or_else(std::sync::PoisonError::into_inner)
4367            .is_some()
4368    }
4369
4370    /// Graceful EOF teardown can afford a bounded wait for an already running
4371    /// search rebuild to publish. Poll the observable receiver state
4372    /// directly instead of relying on fixed sleeps in callers or tests.
4373    fn wait_for_search_index_build_to_settle_on_graceful_shutdown(&self) {
4374        crate::runtime_drain::note_search_rebuild_shutdown_wait_for_test();
4375        let deadline = Instant::now() + GRACEFUL_SHUTDOWN_SEARCH_BUILD_WAIT;
4376        while self.search_index_build_in_progress() && Instant::now() < deadline {
4377            let remaining = deadline.saturating_duration_since(Instant::now());
4378            std::thread::sleep(remaining.min(GRACEFUL_SHUTDOWN_SEARCH_BUILD_POLL));
4379            self.drain_search_index_events_for_graceful_shutdown();
4380        }
4381    }
4382
4383    /// Flush the owner-side trigram delta during an orderly transport shutdown.
4384    /// EOF/Goodbye teardown uses this best-effort path; signal and panic exits
4385    /// intentionally skip it so abrupt shutdown never waits on slow recovery work.
4386    #[doc(hidden)]
4387    pub fn flush_search_index_on_graceful_shutdown(&self) -> bool {
4388        if self.shared_artifacts_read_only() {
4389            return false;
4390        }
4391
4392        self.drain_search_index_events_for_graceful_shutdown();
4393        if self.search_index_build_in_progress() {
4394            self.wait_for_search_index_build_to_settle_on_graceful_shutdown();
4395            self.drain_search_index_events_for_graceful_shutdown();
4396        }
4397
4398        if self.search_index_build_in_progress() {
4399            return false;
4400        }
4401
4402        let Some(canonical_root) = self.canonical_cache_root_opt() else {
4403            return false;
4404        };
4405        let config = self.config();
4406        let project_key = self.memoized_artifact_cache_key(&canonical_root);
4407        let cache_dir = crate::search_index::resolve_cache_dir_with_key(
4408            &project_key,
4409            config.storage_dir.as_deref(),
4410        );
4411
4412        {
4413            let search_index = self
4414                .search_index()
4415                .read()
4416                .unwrap_or_else(std::sync::PoisonError::into_inner);
4417            let Some(index) = search_index.as_ref() else {
4418                return false;
4419            };
4420            if !index.ready || !index.has_pending_disk_changes() {
4421                return false;
4422            }
4423        }
4424
4425        let _cache_lock = match crate::search_index::CacheLock::try_acquire_for_shutdown(
4426            &cache_dir,
4427            &canonical_root,
4428        ) {
4429            Ok(lock) => lock,
4430            Err(error) => {
4431                crate::slog_warn!(
4432                    "search index: skipped shutdown flush because cache lock was unavailable: {}",
4433                    error
4434                );
4435                return false;
4436            }
4437        };
4438
4439        let mut search_index = self
4440            .search_index()
4441            .write()
4442            .unwrap_or_else(std::sync::PoisonError::into_inner);
4443        let Some(index) = search_index.as_mut() else {
4444            return false;
4445        };
4446        if !index.ready || !index.has_pending_disk_changes() {
4447            return false;
4448        }
4449
4450        let git_head = index.stored_git_head().map(str::to_owned);
4451        index.write_to_disk(&cache_dir, git_head.as_deref())
4452    }
4453
4454    pub fn inspect_manager(&self) -> Arc<InspectManager> {
4455        Arc::clone(&self.inspect_manager)
4456    }
4457
4458    pub fn add_pending_tier2_paths<I>(&self, paths: I)
4459    where
4460        I: IntoIterator<Item = PathBuf>,
4461    {
4462        self.pending_tier2_paths.lock().extend(paths);
4463    }
4464
4465    pub fn pending_tier2_paths(&self) -> Vec<PathBuf> {
4466        self.pending_tier2_paths.lock().iter().cloned().collect()
4467    }
4468
4469    pub fn remove_pending_tier2_paths<I>(&self, paths: I)
4470    where
4471        I: IntoIterator<Item = PathBuf>,
4472    {
4473        let mut pending = self.pending_tier2_paths.lock();
4474        for path in paths {
4475            pending.remove(&path);
4476        }
4477    }
4478
4479    /// Returns true when one or more watcher-driven (reuse-path) Tier-2 scans
4480    /// have completed since the last call, advancing the last-seen marker. The
4481    /// per-request inspect drain uses this to refresh the status bar after a
4482    /// background scan — those completions bypass `drain_completions`.
4483    /// Peek variant of `take_new_reuse_completions`: reports whether new reuse
4484    /// completions exist WITHOUT consuming the observation, so the maintenance
4485    /// scheduler's skip probe cannot swallow a status-bar refresh.
4486    pub fn has_new_reuse_completions(&self) -> bool {
4487        self.inspect_manager.reuse_completion_count()
4488            != self.last_seen_reuse_completions.load(Ordering::SeqCst)
4489    }
4490
4491    pub fn take_new_reuse_completions(&self) -> bool {
4492        let current = self.inspect_manager.reuse_completion_count();
4493        let previous = self
4494            .last_seen_reuse_completions
4495            .swap(current, Ordering::SeqCst);
4496        current != previous
4497    }
4498
4499    pub fn reset_tier2_refresh_scheduler(&self) {
4500        self.reset_tier2_refresh_scheduler_at(Instant::now());
4501    }
4502
4503    #[doc(hidden)]
4504    pub fn reset_tier2_refresh_scheduler_at(&self, now: Instant) {
4505        self.tier2_refresh_scheduler
4506            .lock()
4507            .reset_after_configure(now);
4508    }
4509
4510    pub fn request_tier2_refresh_pull(&self) -> bool {
4511        let can_schedule = self.inspect_writer()
4512            && self.heavy_root_work_allowed()
4513            && self.inspect_manager.automatic_tier2_refresh_allowed();
4514        self.tier2_refresh_scheduler
4515            .lock()
4516            .request_pull(can_schedule)
4517    }
4518
4519    pub fn tick_tier2_refresh_scheduler(
4520        &self,
4521        changed_path_count: usize,
4522    ) -> Option<Tier2TriggerReason> {
4523        self.tick_tier2_refresh_scheduler_at(Instant::now(), changed_path_count)
4524    }
4525
4526    #[doc(hidden)]
4527    pub fn tick_tier2_refresh_scheduler_at(
4528        &self,
4529        now: Instant,
4530        changed_path_count: usize,
4531    ) -> Option<Tier2TriggerReason> {
4532        let manager = self.inspect_manager();
4533        let can_write = self.inspect_writer()
4534            && self.heavy_root_work_allowed()
4535            && manager.automatic_tier2_refresh_allowed();
4536        let in_flight = manager.tier2_any_in_flight();
4537        let semantic_cold_seed_active = self.semantic_cold_seed_active();
4538        let decision = self.tier2_refresh_scheduler.lock().tick_with_semantic_gate(
4539            now,
4540            changed_path_count,
4541            can_write,
4542            in_flight,
4543            semantic_cold_seed_active,
4544        );
4545
4546        if let Some(reason) = decision {
4547            self.start_tier2_refresh(reason, manager);
4548        }
4549
4550        decision
4551    }
4552
4553    pub fn note_tier2_refresh_started(&self) {
4554        self.note_tier2_refresh_started_at(Instant::now());
4555    }
4556
4557    #[doc(hidden)]
4558    pub fn note_tier2_refresh_started_at(&self, now: Instant) {
4559        self.tier2_refresh_scheduler
4560            .lock()
4561            .note_external_scan_started(now);
4562    }
4563
4564    pub fn tier2_trigger_reason(&self) -> Option<&'static str> {
4565        self.tier2_refresh_scheduler
4566            .lock()
4567            .last_trigger_reason()
4568            .map(Tier2TriggerReason::as_str)
4569    }
4570
4571    #[doc(hidden)]
4572    pub fn tier2_pull_demand_pending(&self) -> bool {
4573        self.tier2_refresh_scheduler.lock().pull_demand_pending()
4574    }
4575
4576    fn start_tier2_refresh(&self, reason: Tier2TriggerReason, manager: Arc<InspectManager>) {
4577        let generation = self.configure_generation();
4578        if !self.inspect_writer()
4579            || !self.heavy_root_work_allowed()
4580            || !manager.automatic_tier2_refresh_allowed()
4581            || !self.config().inspect.enabled
4582        {
4583            return;
4584        }
4585        let _ = self.run_if_subc_bound_generation(generation, || {
4586            self.start_tier2_refresh_admitted(reason, manager);
4587        });
4588    }
4589
4590    fn start_tier2_refresh_admitted(
4591        &self,
4592        reason: Tier2TriggerReason,
4593        manager: Arc<InspectManager>,
4594    ) {
4595        let Some(snapshot) = self.tier2_refresh_snapshot() else {
4596            return;
4597        };
4598        let categories = InspectCategory::active()
4599            .iter()
4600            .copied()
4601            .filter(|category| category.is_tier2())
4602            .collect::<Vec<_>>();
4603        let submission =
4604            manager.submit_tier2_run_with_reuse_serial_background(snapshot, categories);
4605        if !submission.deferred_categories.is_empty() {
4606            self.tier2_refresh_scheduler.lock().note_dispatch_deferred();
4607            crate::slog_info!(
4608                "tier2 refresh deferred by cold build limit: categories={:?}",
4609                submission
4610                    .deferred_categories
4611                    .iter()
4612                    .map(|category| category.as_str())
4613                    .collect::<Vec<_>>()
4614            );
4615        }
4616        if submission.has_new_work() {
4617            crate::slog_info!(
4618                "tier2 refresh scheduled: reason={}, categories={:?}",
4619                reason.as_str(),
4620                submission
4621                    .newly_queued_categories
4622                    .iter()
4623                    .map(|category| category.as_str())
4624                    .collect::<Vec<_>>()
4625            );
4626        }
4627        for error in submission.errors {
4628            crate::slog_warn!(
4629                "tier2 refresh schedule failed for {}: {}",
4630                error.category,
4631                error.message
4632            );
4633        }
4634    }
4635
4636    fn tier2_refresh_snapshot(&self) -> Option<InspectSnapshot> {
4637        self.harness_opt()?;
4638        let config = self.config();
4639        let project_root = config
4640            .project_root
4641            .clone()
4642            .unwrap_or_else(|| std::env::current_dir().unwrap_or_default());
4643        // Normalized, not bare-canonical: scoped diagnostics compare
4644        // LSP-reported paths (normalized form) against this root with
4645        // starts_with, and a verbatim root on Windows matches nothing.
4646        let project_root = crate::inspect::job::canonicalize_normalized(&project_root);
4647        Some(InspectSnapshot::new(
4648            project_root,
4649            self.inspect_dir(),
4650            config,
4651            self.symbol_cache(),
4652        ))
4653    }
4654
4655    /// Access the shared symbol cache.
4656    pub fn symbol_cache(&self) -> SharedSymbolCache {
4657        Arc::clone(&self.symbol_cache)
4658    }
4659
4660    /// Clear the shared symbol cache and return the new active generation.
4661    pub fn reset_symbol_cache(&self) -> u64 {
4662        self.symbol_cache
4663            .write()
4664            .map(|mut cache| cache.reset())
4665            .unwrap_or(0)
4666    }
4667
4668    /// Access the semantic search index.
4669    pub fn semantic_index(&self) -> &RwLock<Option<SemanticIndex>> {
4670        &self.semantic_index
4671    }
4672
4673    /// Access the semantic-index build receiver.
4674    pub fn semantic_index_rx(
4675        &self,
4676    ) -> &parking_lot::Mutex<Option<crossbeam_channel::Receiver<SemanticIndexEvent>>> {
4677        &self.semantic_index_rx
4678    }
4679
4680    pub(crate) fn install_semantic_index_rx(
4681        &self,
4682        receiver: crossbeam_channel::Receiver<SemanticIndexEvent>,
4683        generation: u64,
4684    ) -> u64 {
4685        let mut slot = self.semantic_index_rx.lock();
4686        self.note_semantic_index_rx_generation(generation);
4687        let epoch = self.next_semantic_index_rx_epoch();
4688        *slot = Some(receiver);
4689        epoch
4690    }
4691
4692    pub(crate) fn semantic_index_rx_terminal_guard(&self, epoch: u64) -> ReceiverTerminalGuard {
4693        ReceiverTerminalGuard::new(Arc::clone(&self.semantic_index_rx_terminal_epoch), epoch)
4694    }
4695
4696    /// Keep generation/epoch validation and receiver mutation under the same
4697    /// lock used by receiver installation.
4698    pub(crate) fn with_current_semantic_index_rx<R>(
4699        &self,
4700        generation: u64,
4701        epoch: u64,
4702        action: impl FnOnce(&mut Option<crossbeam_channel::Receiver<SemanticIndexEvent>>) -> R,
4703    ) -> Option<R> {
4704        self.run_if_subc_bound_generation(generation, || {
4705            let mut receiver = self.semantic_index_rx.lock();
4706            if receiver.is_none()
4707                || self.semantic_index_rx_generation() != generation
4708                || self.semantic_index_rx_epoch() != epoch
4709            {
4710                return None;
4711            }
4712            Some(action(&mut receiver))
4713        })
4714        .flatten()
4715    }
4716
4717    pub(crate) fn retire_semantic_index_rx(&self) {
4718        let mut receiver = self.semantic_index_rx.lock();
4719        *receiver = None;
4720        self.next_semantic_index_rx_epoch();
4721    }
4722
4723    /// Retire a build receiver only if no replacement changed its epoch after
4724    /// the caller inspected it. `None` means a newer receiver won the race;
4725    /// `Some(false)` means the inspected epoch is still current but empty.
4726    pub(crate) fn retire_semantic_index_rx_if_epoch(&self, expected_epoch: u64) -> Option<bool> {
4727        let mut receiver = self.semantic_index_rx.lock();
4728        if self.semantic_index_rx_epoch() != expected_epoch {
4729            return None;
4730        }
4731        let retired = receiver.take().is_some();
4732        if retired {
4733            self.next_semantic_index_rx_epoch();
4734        }
4735        Some(retired)
4736    }
4737
4738    pub(crate) fn note_semantic_index_rx_generation(&self, generation: u64) {
4739        self.semantic_index_rx_generation
4740            .store(generation, Ordering::SeqCst);
4741    }
4742
4743    pub(crate) fn semantic_index_rx_generation(&self) -> u64 {
4744        self.semantic_index_rx_generation.load(Ordering::SeqCst)
4745    }
4746
4747    pub(crate) fn next_semantic_index_rx_epoch(&self) -> u64 {
4748        self.semantic_index_rx_epoch
4749            .fetch_add(1, Ordering::SeqCst)
4750            .wrapping_add(1)
4751    }
4752
4753    pub(crate) fn semantic_index_rx_epoch(&self) -> u64 {
4754        self.semantic_index_rx_epoch.load(Ordering::SeqCst)
4755    }
4756
4757    pub(crate) fn next_semantic_persist_epoch(&self) -> u64 {
4758        self.semantic_persist_epoch.next()
4759    }
4760
4761    pub(crate) fn semantic_persist_epoch_flag(&self) -> crate::root_cache::ArtifactPublishEpoch {
4762        self.semantic_persist_epoch.clone()
4763    }
4764
4765    pub(crate) fn semantic_persist_lock(&self) -> Arc<parking_lot::Mutex<()>> {
4766        Arc::clone(&self.semantic_persist_lock)
4767    }
4768
4769    pub fn semantic_index_status(&self) -> &RwLock<SemanticIndexStatus> {
4770        &self.semantic_index_status
4771    }
4772
4773    pub(crate) fn artifact_reload_guard(&self) -> parking_lot::MutexGuard<'_, ()> {
4774        self.artifact_reload_lock.lock()
4775    }
4776
4777    /// Reset this context's cold semantic seed gate for a newly accepted
4778    /// configure and return the generation token for the worker being spawned.
4779    pub fn reset_semantic_cold_seed_gate_for_configure(&self) -> u64 {
4780        self.semantic_cold_seed_active
4781            .store(false, Ordering::SeqCst);
4782        self.semantic_callgraph_warm_deferred
4783            .store(false, Ordering::SeqCst);
4784        self.semantic_cold_seed_generation
4785            .fetch_add(1, Ordering::SeqCst)
4786            .wrapping_add(1)
4787    }
4788
4789    pub fn semantic_cold_seed_active_flag(&self) -> Arc<AtomicBool> {
4790        Arc::clone(&self.semantic_cold_seed_active)
4791    }
4792
4793    pub fn semantic_cold_seed_generation_flag(&self) -> Arc<AtomicU64> {
4794        Arc::clone(&self.semantic_cold_seed_generation)
4795    }
4796
4797    pub fn semantic_cold_seed_generation(&self) -> u64 {
4798        self.semantic_cold_seed_generation.load(Ordering::SeqCst)
4799    }
4800
4801    pub fn semantic_cold_seed_active(&self) -> bool {
4802        self.semantic_cold_seed_active.load(Ordering::SeqCst)
4803    }
4804
4805    pub fn schedule_semantic_cold_seed_gate_for_configure(&self) {
4806        self.semantic_cold_seed_active.store(true, Ordering::SeqCst);
4807    }
4808
4809    pub fn defer_callgraph_store_warm_for_semantic_cold_seed(&self) {
4810        self.semantic_callgraph_warm_deferred
4811            .store(true, Ordering::SeqCst);
4812    }
4813
4814    fn semantic_callgraph_warm_deferred(&self) -> bool {
4815        self.semantic_callgraph_warm_deferred.load(Ordering::SeqCst)
4816    }
4817
4818    /// Clear the cold-seed gate and resume work that was intentionally held back
4819    /// while the full semantic corpus was accumulating. This entry point is used
4820    /// by the code that drains events from the semantic worker.
4821    pub fn clear_semantic_cold_seed_gate_and_resume_deferred_work(&self) {
4822        self.resume_semantic_cold_seed_deferred_work(false);
4823    }
4824
4825    /// Resume work after the semantic worker has already cleared the atomic gate
4826    /// itself, such as on cached-index load or before a retry backoff sleep.
4827    pub fn resume_deferred_work_after_semantic_cold_seed_gate_cleared(&self) {
4828        self.resume_semantic_cold_seed_deferred_work(true);
4829    }
4830
4831    pub(crate) fn take_semantic_cold_seed_resume(&self, force: bool) -> SemanticColdSeedResume {
4832        let was_active = self.semantic_cold_seed_active.swap(false, Ordering::SeqCst);
4833        let warm_callgraph = self
4834            .semantic_callgraph_warm_deferred
4835            .swap(false, Ordering::SeqCst);
4836        SemanticColdSeedResume {
4837            request_tier2: force || was_active || warm_callgraph,
4838            warm_callgraph,
4839        }
4840    }
4841
4842    pub(crate) fn apply_semantic_cold_seed_resume(&self, resume: SemanticColdSeedResume) {
4843        if resume.request_tier2 {
4844            let _ = self.request_tier2_refresh_pull();
4845        }
4846
4847        if !resume.warm_callgraph
4848            || !self.config().callgraph_store
4849            || !self.heavy_root_work_allowed()
4850        {
4851            return;
4852        }
4853
4854        match self.callgraph_store_for_ops() {
4855            CallgraphStoreAccess::Ready(_) => {
4856                crate::slog_debug!(
4857                    "deferred callgraph store warm completed after semantic cold seed gate cleared"
4858                );
4859            }
4860            CallgraphStoreAccess::Building => {
4861                crate::slog_info!(
4862                    "deferred callgraph store warm scheduled after semantic cold seed gate cleared"
4863                );
4864            }
4865            CallgraphStoreAccess::Unavailable => {
4866                crate::slog_info!(
4867                    "deferred callgraph store warm unavailable after semantic cold seed gate cleared"
4868                );
4869            }
4870            CallgraphStoreAccess::Error(error) => {
4871                crate::slog_warn!(
4872                    "deferred callgraph store warm failed after semantic cold seed gate cleared: {}",
4873                    error
4874                );
4875            }
4876        }
4877    }
4878
4879    fn resume_semantic_cold_seed_deferred_work(&self, force: bool) {
4880        let resume = self.take_semantic_cold_seed_resume(force);
4881        self.apply_semantic_cold_seed_resume(resume);
4882    }
4883
4884    #[doc(hidden)]
4885    pub fn set_semantic_cold_seed_active_for_test(&self, active: bool) {
4886        self.semantic_cold_seed_active
4887            .store(active, Ordering::SeqCst);
4888    }
4889
4890    #[doc(hidden)]
4891    pub fn semantic_callgraph_warm_deferred_for_test(&self) -> bool {
4892        self.semantic_callgraph_warm_deferred()
4893    }
4894
4895    pub fn install_semantic_refresh_worker(
4896        &self,
4897        sender: crossbeam_channel::Sender<SemanticRefreshRequest>,
4898        event_rx: crossbeam_channel::Receiver<SemanticRefreshEvent>,
4899        worker_slot: SemanticRefreshWorkerSlot,
4900    ) {
4901        self.install_semantic_refresh_worker_for_build_epoch(
4902            sender,
4903            event_rx,
4904            worker_slot,
4905            self.semantic_index_rx_epoch(),
4906        );
4907    }
4908
4909    pub(crate) fn install_semantic_refresh_worker_for_build_epoch(
4910        &self,
4911        sender: crossbeam_channel::Sender<SemanticRefreshRequest>,
4912        event_rx: crossbeam_channel::Receiver<SemanticRefreshEvent>,
4913        worker_slot: SemanticRefreshWorkerSlot,
4914        build_epoch: u64,
4915    ) {
4916        self.clear_semantic_refresh_worker();
4917        {
4918            let mut receiver = self.semantic_refresh_event_rx.lock();
4919            let mut request = self.semantic_refresh_tx.lock();
4920            let mut worker = self.semantic_refresh_worker.lock();
4921            self.semantic_refresh_generation
4922                .store(self.configure_generation(), Ordering::SeqCst);
4923            self.semantic_refresh_epoch.fetch_add(1, Ordering::SeqCst);
4924            self.semantic_refresh_build_epoch
4925                .store(build_epoch, Ordering::SeqCst);
4926            *receiver = Some(event_rx);
4927            *request = Some(sender);
4928            *worker = Some(worker_slot);
4929        }
4930    }
4931
4932    pub(crate) fn semantic_refresh_generation(&self) -> u64 {
4933        self.semantic_refresh_generation.load(Ordering::SeqCst)
4934    }
4935
4936    pub(crate) fn semantic_refresh_epoch(&self) -> u64 {
4937        self.semantic_refresh_epoch.load(Ordering::SeqCst)
4938    }
4939
4940    /// Serialize refresh event commit with worker replacement. The receiver
4941    /// lock also couples the generation and epoch to the dequeued channel.
4942    pub(crate) fn with_current_semantic_refresh_rx<R>(
4943        &self,
4944        generation: u64,
4945        epoch: u64,
4946        action: impl FnOnce() -> R,
4947    ) -> Option<R> {
4948        self.run_if_subc_bound_generation(generation, || {
4949            let receiver = self.semantic_refresh_event_rx.lock();
4950            if receiver.is_none()
4951                || self.semantic_refresh_generation() != generation
4952                || self.semantic_refresh_epoch() != epoch
4953            {
4954                return None;
4955            }
4956            Some(action())
4957        })
4958        .flatten()
4959    }
4960
4961    pub(crate) fn clear_semantic_refresh_worker_if_current(
4962        &self,
4963        generation: u64,
4964        epoch: u64,
4965    ) -> Option<u64> {
4966        let worker_slot = {
4967            let mut receiver = self.semantic_refresh_event_rx.lock();
4968            if receiver.is_none()
4969                || self.semantic_refresh_generation() != generation
4970                || self.semantic_refresh_epoch() != epoch
4971            {
4972                return None;
4973            }
4974            let disconnected_build_epoch = self.semantic_refresh_build_epoch.load(Ordering::SeqCst);
4975            self.semantic_refresh_build_epoch.store(0, Ordering::SeqCst);
4976            let mut request = self.semantic_refresh_tx.lock();
4977            let mut worker = self.semantic_refresh_worker.lock();
4978            *receiver = None;
4979            *request = None;
4980            self.semantic_refresh_epoch.fetch_add(1, Ordering::SeqCst);
4981            self.invalidate_semantic_refresh_probe();
4982            (worker.take(), disconnected_build_epoch)
4983        };
4984        if let Some(worker_slot) = worker_slot.0 {
4985            if let Ok(mut handle) = worker_slot.lock() {
4986                drop(handle.take());
4987            }
4988        }
4989        Some(worker_slot.1)
4990    }
4991
4992    pub fn clear_semantic_refresh_worker(&self) {
4993        let worker_slot = {
4994            let mut receiver = self.semantic_refresh_event_rx.lock();
4995            let mut request = self.semantic_refresh_tx.lock();
4996            let mut worker = self.semantic_refresh_worker.lock();
4997            *receiver = None;
4998            *request = None;
4999            self.semantic_refresh_epoch.fetch_add(1, Ordering::SeqCst);
5000            self.semantic_refresh_build_epoch.store(0, Ordering::SeqCst);
5001            self.invalidate_semantic_refresh_probe();
5002            worker.take()
5003        };
5004        if let Some(worker_slot) = worker_slot {
5005            if let Ok(mut handle) = worker_slot.lock() {
5006                drop(handle.take());
5007            }
5008        }
5009    }
5010
5011    pub fn semantic_refresh_sender(
5012        &self,
5013    ) -> Option<crossbeam_channel::Sender<SemanticRefreshRequest>> {
5014        self.semantic_refresh_tx.lock().clone()
5015    }
5016
5017    pub(crate) fn semantic_refresh_retry_slots(
5018        &self,
5019    ) -> (
5020        Arc<parking_lot::Mutex<Option<crossbeam_channel::Sender<SemanticRefreshRequest>>>>,
5021        Arc<parking_lot::Mutex<BTreeSet<PathBuf>>>,
5022    ) {
5023        (
5024            Arc::clone(&self.semantic_refresh_tx),
5025            Arc::clone(&self.pending_semantic_index_paths),
5026        )
5027    }
5028
5029    pub fn semantic_refresh_event_rx(
5030        &self,
5031    ) -> &parking_lot::Mutex<Option<crossbeam_channel::Receiver<SemanticRefreshEvent>>> {
5032        &self.semantic_refresh_event_rx
5033    }
5034
5035    pub fn with_semantic_refresh_retry_attempts_mut<R>(
5036        &self,
5037        f: impl FnOnce(&mut BTreeMap<PathBuf, usize>) -> R,
5038    ) -> R {
5039        let mut attempts = self.semantic_refresh_retry_attempts.lock();
5040        f(&mut attempts)
5041    }
5042
5043    pub fn clear_semantic_refresh_retry_attempts(&self, paths: &[PathBuf]) {
5044        let mut attempts = self.semantic_refresh_retry_attempts.lock();
5045        for path in paths {
5046            attempts.remove(path);
5047        }
5048    }
5049
5050    pub fn clear_all_semantic_refresh_retry_attempts(&self) {
5051        self.semantic_refresh_retry_attempts.lock().clear();
5052    }
5053
5054    pub fn semantic_refresh_circuit_is_open(&self) -> bool {
5055        self.semantic_refresh_circuit.open.load(Ordering::SeqCst)
5056    }
5057
5058    pub fn record_semantic_refresh_transient_failure(&self, trip_threshold: usize) -> bool {
5059        let failures = self
5060            .semantic_refresh_circuit
5061            .consecutive_transient_failures
5062            .fetch_add(1, Ordering::SeqCst)
5063            .saturating_add(1);
5064        if failures >= trip_threshold
5065            && !self
5066                .semantic_refresh_circuit
5067                .open
5068                .swap(true, Ordering::SeqCst)
5069        {
5070            crate::slog_warn!(
5071                "embedding backend appears down; suspending active retries, will resume on next change or successful probe"
5072            );
5073        }
5074        self.semantic_refresh_circuit_is_open()
5075    }
5076
5077    pub fn trip_semantic_refresh_circuit(&self, trip_threshold: usize) {
5078        self.semantic_refresh_circuit
5079            .consecutive_transient_failures
5080            .store(trip_threshold, Ordering::SeqCst);
5081        if !self
5082            .semantic_refresh_circuit
5083            .open
5084            .swap(true, Ordering::SeqCst)
5085        {
5086            crate::slog_warn!(
5087                "embedding backend appears down; suspending active retries, will resume on next change or successful probe"
5088            );
5089        }
5090    }
5091
5092    pub fn reset_semantic_refresh_transient_failure_count(&self) {
5093        self.semantic_refresh_circuit
5094            .consecutive_transient_failures
5095            .store(0, Ordering::SeqCst);
5096    }
5097
5098    pub fn reset_semantic_refresh_circuit_after_success(&self) {
5099        self.reset_semantic_refresh_transient_failure_count();
5100        self.semantic_refresh_circuit
5101            .probe_ready
5102            .store(false, Ordering::SeqCst);
5103        if self
5104            .semantic_refresh_circuit
5105            .open
5106            .swap(false, Ordering::SeqCst)
5107        {
5108            crate::slog_info!("embedding backend recovered; resuming normal refresh retries");
5109        }
5110    }
5111
5112    pub fn semantic_refresh_transient_failure_count(&self) -> usize {
5113        self.semantic_refresh_circuit
5114            .consecutive_transient_failures
5115            .load(Ordering::SeqCst)
5116    }
5117
5118    pub fn semantic_refresh_probe_is_scheduled(&self) -> bool {
5119        self.semantic_refresh_circuit
5120            .probe_in_flight
5121            .load(Ordering::SeqCst)
5122            || self.semantic_refresh_probe_ready()
5123    }
5124
5125    pub fn semantic_refresh_probe_ready(&self) -> bool {
5126        self.semantic_refresh_circuit
5127            .probe_ready
5128            .load(Ordering::SeqCst)
5129    }
5130
5131    pub fn take_semantic_refresh_probe_ready(&self) -> bool {
5132        self.semantic_refresh_circuit
5133            .probe_ready
5134            .swap(false, Ordering::SeqCst)
5135    }
5136
5137    fn invalidate_semantic_refresh_probe(&self) {
5138        self.semantic_refresh_circuit
5139            .probe_token
5140            .fetch_add(1, Ordering::SeqCst);
5141        self.semantic_refresh_circuit
5142            .probe_ready
5143            .store(false, Ordering::SeqCst);
5144        self.semantic_refresh_circuit
5145            .probe_in_flight
5146            .store(false, Ordering::SeqCst);
5147    }
5148
5149    pub fn ensure_semantic_refresh_probe_scheduled(&self, delay: Duration) {
5150        let receiver = self.semantic_refresh_event_rx.lock();
5151        if receiver.is_none()
5152            || self
5153                .semantic_refresh_circuit
5154                .probe_ready
5155                .load(Ordering::SeqCst)
5156            || self
5157                .semantic_refresh_circuit
5158                .probe_in_flight
5159                .swap(true, Ordering::SeqCst)
5160        {
5161            return;
5162        }
5163        let probe_token = self
5164            .semantic_refresh_circuit
5165            .probe_token
5166            .fetch_add(1, Ordering::SeqCst)
5167            .wrapping_add(1);
5168        drop(receiver);
5169
5170        let circuit = Arc::clone(&self.semantic_refresh_circuit);
5171        let session_id = crate::log_ctx::current_session();
5172        std::thread::spawn(move || {
5173            crate::log_ctx::with_session(session_id, || {
5174                std::thread::sleep(delay);
5175                if circuit.probe_token.load(Ordering::SeqCst) == probe_token {
5176                    circuit.probe_ready.store(true, Ordering::SeqCst);
5177                    circuit.probe_in_flight.store(false, Ordering::SeqCst);
5178                }
5179            });
5180        });
5181    }
5182
5183    /// Access the cached semantic embedding model.
5184    pub fn semantic_embedding_model(
5185        &self,
5186    ) -> &parking_lot::Mutex<Option<crate::semantic_index::EmbeddingModel>> {
5187        &self.semantic_embedding_model
5188    }
5189
5190    /// Access the file watcher handle (kept alive to continue watching).
5191    pub fn watcher(&self) -> &parking_lot::Mutex<Option<RecommendedWatcher>> {
5192        &self.watcher
5193    }
5194
5195    /// Access the pre-filtered watcher event receiver.
5196    pub fn watcher_rx(
5197        &self,
5198    ) -> &parking_lot::Mutex<Option<crossbeam_channel::Receiver<WatcherDispatchEvent>>> {
5199        &self.watcher_rx
5200    }
5201
5202    /// Access continuation state for the bounded watcher drain.
5203    pub(crate) fn watcher_drain_slice(
5204        &self,
5205    ) -> &parking_lot::Mutex<Option<WatcherDrainSliceState>> {
5206        &self.watcher_drain_slice
5207    }
5208
5209    /// Include partially consumed dispatch events when reporting drain backlog.
5210    pub fn watcher_drain_pending_path_count(&self) -> usize {
5211        self.watcher_drain_slice.lock().as_ref().map_or(0, |state| {
5212            let active_paths = match &state.phase {
5213                WatcherDrainPhase::Collect => 0,
5214                WatcherDrainPhase::Apply { paths, .. } => paths.len(),
5215            };
5216            active_paths + state.pending_paths.len()
5217        })
5218    }
5219
5220    /// Number of path-budgeted watcher batches since this runtime was installed.
5221    pub fn watcher_drain_path_slice_count(&self) -> usize {
5222        self.watcher_drain_slice
5223            .lock()
5224            .as_ref()
5225            .map_or(0, |state| state.path_slice_count)
5226    }
5227
5228    /// Install a watcher filter thread and its dispatch receiver. The caller
5229    /// must have stopped any previous watcher runtime first.
5230    pub fn install_watcher_runtime(
5231        &self,
5232        rx: crossbeam_channel::Receiver<WatcherDispatchEvent>,
5233        runtime: WatcherThreadHandle,
5234    ) {
5235        let _runtime_guard = self.watcher_runtime_lock.lock();
5236        let replaced = self.watcher_thread.lock().replace(runtime);
5237        self.app.watcher_started();
5238        if let Some(runtime) = replaced {
5239            Self::spawn_watcher_shutdown(Arc::clone(&self.app), self.watcher_root_path(), runtime);
5240        }
5241        *self.watcher_rx.lock() = Some(rx);
5242        *self.watcher_drain_slice.lock() = None;
5243    }
5244
5245    fn watcher_root_path(&self) -> PathBuf {
5246        self.canonical_cache_root_opt()
5247            .or_else(|| self.config().project_root.clone())
5248            .unwrap_or_else(|| PathBuf::from("<unconfigured>"))
5249    }
5250
5251    fn spawn_watcher_shutdown(app: Arc<App>, root: PathBuf, runtime: WatcherThreadHandle) {
5252        const JOIN_TIMEOUT: Duration = Duration::from_secs(2);
5253        // Signal the watcher before scheduling the joiner so teardown does not
5254        // depend on a newly spawned thread winning CPU time under fleet load.
5255        runtime.request_shutdown();
5256        std::thread::spawn(
5257            move || match runtime.shutdown_and_join_timeout(JOIN_TIMEOUT) {
5258                WatcherJoinOutcome::Joined => {
5259                    app.watcher_stopped();
5260                    crate::slog_info!("watcher stopped: {}", root.display());
5261                }
5262                WatcherJoinOutcome::TimedOut(join) => {
5263                    crate::slog_warn!(
5264                        "watcher stop timed out after {} ms: {}",
5265                        JOIN_TIMEOUT.as_millis(),
5266                        root.display()
5267                    );
5268                    std::thread::spawn(move || {
5269                        let _ = join.join();
5270                        app.watcher_stopped();
5271                        crate::slog_info!("watcher stopped: {}", root.display());
5272                    });
5273                }
5274            },
5275        );
5276    }
5277
5278    fn take_watcher_runtime(&self) -> Option<WatcherThreadHandle> {
5279        let _runtime_guard = self.watcher_runtime_lock.lock();
5280        let runtime = self.watcher_thread.lock().take();
5281        *self.watcher_rx.lock() = None;
5282        *self.watcher_drain_slice.lock() = None;
5283        *self.watcher.lock() = None;
5284        runtime
5285    }
5286
5287    /// Stop the watcher runtime without waiting on its OS thread. Shutdown and
5288    /// the bounded join run on a detached reaper so configure and transport
5289    /// loops never wait on FSEvents or inotify teardown.
5290    pub fn stop_watcher_runtime(&self) {
5291        if let Some(runtime) = self.take_watcher_runtime() {
5292            Self::spawn_watcher_shutdown(Arc::clone(&self.app), self.watcher_root_path(), runtime);
5293        }
5294    }
5295
5296    /// Request watcher shutdown without joining on the executor lane.
5297    pub fn stop_watcher_runtime_in_background(&self) {
5298        self.stop_watcher_runtime();
5299    }
5300
5301    /// Remove a watcher runtime whose OS thread already exited (backend
5302    /// failure while the root was unbound and drains were suppressed).
5303    /// Returns true when a finished corpse was actually removed so the caller
5304    /// can apply watcher-gap invalidation exactly once.
5305    pub(crate) fn take_finished_watcher_runtime(&self) -> bool {
5306        let runtime = {
5307            let _runtime_guard = self.watcher_runtime_lock.lock();
5308            let finished = self
5309                .watcher_thread
5310                .lock()
5311                .as_ref()
5312                .is_some_and(|runtime| runtime.is_finished());
5313            if !finished {
5314                return false;
5315            }
5316            let runtime = self.watcher_thread.lock().take();
5317            *self.watcher_rx.lock() = None;
5318            *self.watcher_drain_slice.lock() = None;
5319            *self.watcher.lock() = None;
5320            runtime
5321        };
5322        if let Some(runtime) = runtime {
5323            Self::spawn_watcher_shutdown(Arc::clone(&self.app), self.watcher_root_path(), runtime);
5324        }
5325        true
5326    }
5327
5328    /// Process-scoped watcher count used by maintenance diagnostics and
5329    /// regression tests. A runtime remains counted until its thread exits.
5330    pub fn watcher_registry_count(&self) -> usize {
5331        self.app.watcher_count()
5332    }
5333
5334    pub(crate) fn watcher_runtime_active(&self) -> bool {
5335        let _runtime_guard = self.watcher_runtime_lock.lock();
5336        // A finished thread is a dead runtime even while its handle is still
5337        // installed (the backend can fail while drains are suppressed for an
5338        // unbound root, leaving the queued error undrained). Treating it as
5339        // active would block watcher restoration on rebind.
5340        let thread_live = self
5341            .watcher_thread
5342            .lock()
5343            .as_ref()
5344            .is_some_and(|runtime| !runtime.is_finished());
5345        thread_live && self.watcher_rx.lock().is_some()
5346    }
5347
5348    /// Return whether artifact eviction would discard work that still needs a
5349    /// live handle. Callers use this as the single safety gate before clearing
5350    /// resident stores and inspect caches.
5351    pub fn artifact_eviction_blocked(&self) -> bool {
5352        let semantic_refresh_in_flight = match &*self
5353            .semantic_index_status
5354            .read()
5355            .unwrap_or_else(std::sync::PoisonError::into_inner)
5356        {
5357            SemanticIndexStatus::Building { .. } => true,
5358            SemanticIndexStatus::Ready { refreshing, .. } => !refreshing.is_empty(),
5359            SemanticIndexStatus::Disabled | SemanticIndexStatus::Failed(_) => false,
5360        };
5361        if crate::runtime_drain::any_build_in_flight(self)
5362            || semantic_refresh_in_flight
5363            || self.inspect_manager.tier2_any_in_flight()
5364            || !self.bash_background.running_tasks().is_empty()
5365            || !self.pending_callgraph_store_paths.lock().is_empty()
5366            || !self.pending_search_index_paths.lock().is_empty()
5367            || !self.pending_tier2_paths.lock().is_empty()
5368            || !self.pending_semantic_index_paths.lock().is_empty()
5369            || *self.pending_semantic_corpus_refresh.lock()
5370        {
5371            return true;
5372        }
5373
5374        let search_has_pending_disk_changes = self
5375            .search_index
5376            .read()
5377            .unwrap_or_else(std::sync::PoisonError::into_inner)
5378            .as_ref()
5379            .is_some_and(SearchIndex::has_pending_disk_changes);
5380        search_has_pending_disk_changes
5381    }
5382
5383    /// Drop idle root-scoped artifact handles. Persistent data remains on disk;
5384    /// artifact-backed query paths schedule a background reload on first use.
5385    /// Returns false when an active build, bash task, inspect scan, or pending
5386    /// disk update makes eviction unsafe.
5387    pub fn evict_idle_artifacts(&self) -> bool {
5388        if self.artifact_eviction_blocked() {
5389            return false;
5390        }
5391
5392        self.callgraph_store
5393            .write()
5394            .unwrap_or_else(std::sync::PoisonError::into_inner)
5395            .take();
5396        self.search_index
5397            .write()
5398            .unwrap_or_else(std::sync::PoisonError::into_inner)
5399            .take();
5400        self.semantic_index
5401            .write()
5402            .unwrap_or_else(std::sync::PoisonError::into_inner)
5403            .take();
5404        self.borrowed_index_cache.lock().clear();
5405        self.inspect_manager.evict_idle_caches();
5406        self.reset_symbol_cache();
5407        self.clear_tsconfig_membership_cache();
5408        true
5409    }
5410
5411    /// Test seam for the serialized real-watcher integration suite. Production
5412    /// callers cannot trigger it without the explicit test-only environment flag.
5413    #[doc(hidden)]
5414    pub fn force_idle_teardown_for_test(self: &Arc<Self>) -> bool {
5415        if std::env::var("AFT_TEST_ALLOW_FORCE_IDLE_REAP").as_deref() != Ok("1") {
5416            return false;
5417        }
5418        if !self.evict_idle_artifacts() {
5419            return false;
5420        }
5421        self.stop_watcher_runtime_in_background();
5422        self.invalidate_artifacts_after_watcher_gap();
5423        true
5424    }
5425
5426    /// Release resources that can be recreated by an equivalent later bind.
5427    /// LSP shutdown can wait on child processes, so all work stays off the
5428    /// executor and subc frame loops.
5429    pub(crate) fn release_idle_reopenable_resources_in_background(self: &Arc<Self>) {
5430        let ctx = Arc::clone(self);
5431        std::thread::spawn(move || {
5432            if !ctx.subc_unbound_quiesced() {
5433                return;
5434            }
5435            {
5436                let mut lsp = ctx.lsp_manager.lock();
5437                if !ctx.subc_unbound_quiesced() {
5438                    return;
5439                }
5440                lsp.shutdown_all();
5441            }
5442            let _ = ctx.subc_lifecycle.run_if_unbound(|| {
5443                ctx.bash_background.clear_db_pool();
5444                ctx.backup.lock().clear_db_pool();
5445            });
5446        });
5447    }
5448
5449    /// Final cleanup for an actor whose project directory no longer exists.
5450    /// The executor invokes this only after proving the actor has no queued or
5451    /// running jobs, and always from a detached teardown thread.
5452    pub(crate) fn teardown_deleted_root(&self) {
5453        self.bash_background.detach();
5454        self.bash_background.clear_db_pool();
5455        self.backup.lock().clear_db_pool();
5456        self.lsp_manager.lock().shutdown_all();
5457    }
5458
5459    /// Access the LSP manager.
5460    pub fn lsp(&self) -> parking_lot::MutexGuard<'_, LspManager> {
5461        self.lsp_manager.lock()
5462    }
5463
5464    /// Notify LSP servers that a file was written.
5465    /// Call this after write_format_validate in command handlers.
5466    pub fn lsp_notify_file_changed(&self, file_path: &Path, content: &str) {
5467        let config = self.config();
5468        if let Some(mut lsp) = self.lsp_manager.try_lock() {
5469            if let Err(e) = lsp.notify_file_changed_if_running(file_path, content, &config) {
5470                crate::slog_warn!("sync error for {}: {}", file_path.display(), e);
5471            }
5472        }
5473    }
5474
5475    /// Drop cached LSP diagnostics for a deleted/renamed-away file so its
5476    /// errors/warnings don't linger in the warm set (no server republishes for
5477    /// a vanished path), keeping the status bar and `aft_inspect` honest.
5478    /// Returns true if any entry was removed. Best-effort: a contended borrow is
5479    /// skipped silently (the watcher drain retries on subsequent events).
5480    pub fn lsp_clear_diagnostics_for_file(&self, file_path: &Path) -> bool {
5481        if let Some(mut lsp) = self.lsp_manager.try_lock() {
5482            lsp.clear_diagnostics_for_file(file_path)
5483        } else {
5484            false
5485        }
5486    }
5487
5488    /// Mark diagnostics stale for a file changed outside AFT's text-sync path.
5489    /// Best-effort: a contended LSP lock is skipped and the next watcher event
5490    /// or scoped diagnostics pull can reconcile the file.
5491    pub fn lsp_mark_diagnostics_stale_for_file(&self, file_path: &Path) -> StaleDiagnosticsMark {
5492        if let Some(mut lsp) = self.lsp_manager.try_lock() {
5493            lsp.mark_diagnostics_stale_for_file(file_path)
5494        } else {
5495            StaleDiagnosticsMark::default()
5496        }
5497    }
5498
5499    /// Resync a watcher-stale diagnosed file with the active LSP server.
5500    ///
5501    /// `workspace/didChangeWatchedFiles` tells servers that the filesystem
5502    /// changed, but it does not update an already-open document's in-memory text.
5503    /// Sending the normal didOpen/didChange path gives push-only servers a chance
5504    /// to publish fresh diagnostics and keeps pull-capable servers' document state
5505    /// current for the next diagnostic request.
5506    pub fn lsp_resync_changed_file_for_diagnostics(&self, file_path: &Path) -> bool {
5507        if !file_path.is_file() {
5508            return false;
5509        }
5510
5511        let content = match std::fs::read_to_string(file_path) {
5512            Ok(content) => content,
5513            Err(err) => {
5514                crate::slog_warn!(
5515                    "skipping LSP resync for {} after external edit: {}",
5516                    file_path.display(),
5517                    err
5518                );
5519                return false;
5520            }
5521        };
5522
5523        let config = self.config();
5524        if let Some(mut lsp) = self.lsp_manager.try_lock() {
5525            if let Err(err) = lsp.notify_file_changed(file_path, &content, &config) {
5526                crate::slog_warn!(
5527                    "LSP resync failed for {} after external edit: {}",
5528                    file_path.display(),
5529                    err
5530                );
5531                return false;
5532            }
5533            true
5534        } else {
5535            false
5536        }
5537    }
5538
5539    /// Notify LSP and optionally wait for diagnostics.
5540    ///
5541    /// Call this after `write_format_validate` when the request has `"diagnostics": true`.
5542    /// Sends didChange to the server, waits briefly for publishDiagnostics, and returns
5543    /// any diagnostics for the file. If no server is running, returns empty immediately.
5544    ///
5545    /// v0.17.3: this is the version-aware path. Pre-edit cached diagnostics
5546    /// are NEVER returned — only entries whose `version` matches the
5547    /// post-edit document version (or, for unversioned servers, whose
5548    /// `epoch` advanced past the pre-edit snapshot).
5549    pub fn lsp_notify_and_collect_diagnostics(
5550        &self,
5551        file_path: &Path,
5552        content: &str,
5553        timeout: std::time::Duration,
5554    ) -> crate::lsp::manager::PostEditWaitOutcome {
5555        let config = self.config();
5556        let Some(mut lsp) = self.lsp_manager.try_lock() else {
5557            return crate::lsp::manager::PostEditWaitOutcome::default();
5558        };
5559
5560        // Clear any queued notifications before this write so the wait loop only
5561        // observes diagnostics triggered by the current change.
5562        lsp.drain_events();
5563
5564        // Snapshot per-server epochs and document versions BEFORE sending
5565        // didChange so the wait loop can prove freshness without accepting
5566        // stale pre-edit publishes that arrived late.
5567        let pre_snapshot = lsp.snapshot_pre_edit_state(file_path);
5568
5569        // Send didChange/didOpen and capture per-server target version.
5570        let expected_versions = match lsp.notify_file_changed_versioned(file_path, content, &config)
5571        {
5572            Ok(v) => v,
5573            Err(e) => {
5574                crate::slog_warn!("sync error for {}: {}", file_path.display(), e);
5575                return crate::lsp::manager::PostEditWaitOutcome::default();
5576            }
5577        };
5578
5579        // No server matched this file — return an empty outcome that's
5580        // honestly `complete: true` (nothing to wait for).
5581        if expected_versions.is_empty() {
5582            return crate::lsp::manager::PostEditWaitOutcome::default();
5583        }
5584
5585        lsp.wait_for_post_edit_diagnostics(
5586            file_path,
5587            &config,
5588            &expected_versions,
5589            &pre_snapshot,
5590            timeout,
5591        )
5592    }
5593
5594    /// Collect custom server root_markers from user config for use in
5595    /// `is_config_file_path_with_custom` checks (#25).
5596    fn custom_lsp_root_markers(&self) -> Vec<String> {
5597        self.config()
5598            .lsp_servers
5599            .iter()
5600            .flat_map(|s| s.root_markers.iter().cloned())
5601            .collect()
5602    }
5603
5604    fn notify_watched_config_files(&self, file_paths: &[PathBuf]) {
5605        let custom_markers = self.custom_lsp_root_markers();
5606        let config_paths: Vec<(PathBuf, FileChangeType)> = file_paths
5607            .iter()
5608            .filter(|path| is_config_file_path_with_custom(path, &custom_markers))
5609            .cloned()
5610            .map(|path| {
5611                let change_type = if path.exists() {
5612                    FileChangeType::CHANGED
5613                } else {
5614                    FileChangeType::DELETED
5615                };
5616                (path, change_type)
5617            })
5618            .collect();
5619
5620        self.notify_watched_config_events(&config_paths);
5621    }
5622
5623    fn multi_file_write_paths(params: &serde_json::Value) -> Option<Vec<PathBuf>> {
5624        let paths = params
5625            .get("multi_file_write_paths")
5626            .and_then(|value| value.as_array())?
5627            .iter()
5628            .filter_map(|value| value.as_str())
5629            .map(PathBuf::from)
5630            .collect::<Vec<_>>();
5631
5632        (!paths.is_empty()).then_some(paths)
5633    }
5634
5635    /// Parse config-file watched events from `multi_file_write_paths` when the
5636    /// array contains object entries `{ "path": "...", "type": "created|changed|deleted" }`.
5637    ///
5638    /// This handles the OBJECT variant of `multi_file_write_paths`. The STRING
5639    /// variant (bare path strings) is handled by `multi_file_write_paths()` and
5640    /// `notify_watched_config_files()`. Both variants read the same JSON key but
5641    /// with different per-entry schemas — they are NOT redundant.
5642    ///
5643    /// #18 note: in older code this function also existed alongside `multi_file_write_paths()`
5644    /// and was reachable via the `else if` branch when all entries were objects.
5645    /// Restoring both is correct.
5646    fn watched_file_events_from_params(
5647        params: &serde_json::Value,
5648        extra_markers: &[String],
5649    ) -> Option<Vec<(PathBuf, FileChangeType)>> {
5650        let events = params
5651            .get("multi_file_write_paths")
5652            .and_then(|value| value.as_array())?
5653            .iter()
5654            .filter_map(|entry| {
5655                // Only handle object entries — string entries go through multi_file_write_paths()
5656                let path = entry
5657                    .get("path")
5658                    .and_then(|value| value.as_str())
5659                    .map(PathBuf::from)?;
5660
5661                if !is_config_file_path_with_custom(&path, extra_markers) {
5662                    return None;
5663                }
5664
5665                let change_type = entry
5666                    .get("type")
5667                    .and_then(|value| value.as_str())
5668                    .and_then(Self::parse_file_change_type)
5669                    .unwrap_or_else(|| Self::change_type_from_current_state(&path));
5670
5671                Some((path, change_type))
5672            })
5673            .collect::<Vec<_>>();
5674
5675        (!events.is_empty()).then_some(events)
5676    }
5677
5678    fn parse_file_change_type(value: &str) -> Option<FileChangeType> {
5679        match value {
5680            "created" | "CREATED" | "Created" => Some(FileChangeType::CREATED),
5681            "changed" | "CHANGED" | "Changed" => Some(FileChangeType::CHANGED),
5682            "deleted" | "DELETED" | "Deleted" => Some(FileChangeType::DELETED),
5683            _ => None,
5684        }
5685    }
5686
5687    fn change_type_from_current_state(path: &Path) -> FileChangeType {
5688        if path.exists() {
5689            FileChangeType::CHANGED
5690        } else {
5691            FileChangeType::DELETED
5692        }
5693    }
5694
5695    fn notify_watched_config_events(&self, config_paths: &[(PathBuf, FileChangeType)]) {
5696        if config_paths.is_empty() {
5697            return;
5698        }
5699
5700        let config = self.config();
5701        if let Some(mut lsp) = self.lsp_manager.try_lock() {
5702            if let Err(e) = lsp.notify_files_watched_changed(config_paths, &config) {
5703                crate::slog_warn!("watched-file sync error: {}", e);
5704            }
5705        }
5706    }
5707
5708    pub fn lsp_notify_watched_config_file(&self, file_path: &Path, change_type: FileChangeType) {
5709        let custom_markers = self.custom_lsp_root_markers();
5710        if !is_config_file_path_with_custom(file_path, &custom_markers) {
5711            return;
5712        }
5713
5714        self.notify_watched_config_events(&[(file_path.to_path_buf(), change_type)]);
5715    }
5716
5717    /// Post-write LSP hook for multi-file edits. When the patch includes
5718    /// config-file edits, notify active workspace servers via
5719    /// `workspace/didChangeWatchedFiles` before sending the per-document
5720    /// didOpen/didChange for the current file.
5721    pub fn lsp_post_multi_file_write(
5722        &self,
5723        file_path: &Path,
5724        content: &str,
5725        file_paths: &[PathBuf],
5726        params: &serde_json::Value,
5727    ) -> Option<crate::lsp::manager::PostEditWaitOutcome> {
5728        self.notify_watched_config_files(file_paths);
5729        self.add_pending_tier2_paths(file_paths.iter().cloned());
5730        let _ = self.mark_status_bar_tier2_stale();
5731
5732        let wants_diagnostics = params
5733            .get("diagnostics")
5734            .and_then(|v| v.as_bool())
5735            .unwrap_or(false);
5736
5737        if !wants_diagnostics {
5738            self.lsp_notify_file_changed(file_path, content);
5739            return None;
5740        }
5741
5742        let wait_ms = params
5743            .get("wait_ms")
5744            .and_then(|v| v.as_u64())
5745            .unwrap_or(3000)
5746            .min(10_000);
5747
5748        Some(self.lsp_notify_and_collect_diagnostics(
5749            file_path,
5750            content,
5751            std::time::Duration::from_millis(wait_ms),
5752        ))
5753    }
5754
5755    /// Post-write LSP hook: notify server and optionally collect diagnostics.
5756    ///
5757    /// This is the single call site for all command handlers after `write_format_validate`.
5758    /// Behavior:
5759    /// - When `diagnostics: true` is in `params`, notifies the server, waits
5760    ///   until matching diagnostics arrive or the timeout expires, and returns
5761    ///   `Some(outcome)` with the verified-fresh diagnostics + per-server
5762    ///   status.
5763    /// - When `diagnostics: false` (or absent), just notifies (fire-and-forget)
5764    ///   and returns `None`. Callers must NOT wrap this in `Some(...)`; the
5765    ///   `None` is what tells the response builder to omit the LSP fields
5766    ///   entirely (preserves the no-diagnostics-requested response shape).
5767    ///
5768    /// v0.17.3: default `wait_ms` raised from 1500 to 3000 because real-world
5769    /// tsserver re-analysis on monorepo files routinely takes 2-5s. Still
5770    /// capped at 10000ms.
5771    pub fn lsp_post_write(
5772        &self,
5773        file_path: &Path,
5774        content: &str,
5775        params: &serde_json::Value,
5776    ) -> Option<crate::lsp::manager::PostEditWaitOutcome> {
5777        let wants_diagnostics = params
5778            .get("diagnostics")
5779            .and_then(|v| v.as_bool())
5780            .unwrap_or(false);
5781
5782        let custom_markers = self.custom_lsp_root_markers();
5783        if let Some(file_paths) = Self::multi_file_write_paths(params) {
5784            self.add_pending_tier2_paths(file_paths);
5785        } else {
5786            self.add_pending_tier2_paths([file_path.to_path_buf()]);
5787        }
5788        let _ = self.mark_status_bar_tier2_stale();
5789
5790        if !wants_diagnostics {
5791            if let Some(file_paths) = Self::multi_file_write_paths(params) {
5792                self.notify_watched_config_files(&file_paths);
5793            } else if let Some(config_events) =
5794                Self::watched_file_events_from_params(params, &custom_markers)
5795            {
5796                self.notify_watched_config_events(&config_events);
5797            }
5798            self.lsp_notify_file_changed(file_path, content);
5799            return None;
5800        }
5801
5802        let wait_ms = params
5803            .get("wait_ms")
5804            .and_then(|v| v.as_u64())
5805            .unwrap_or(3000)
5806            .min(10_000); // Cap at 10 seconds to prevent hangs from adversarial input
5807
5808        if let Some(file_paths) = Self::multi_file_write_paths(params) {
5809            return self.lsp_post_multi_file_write(file_path, content, &file_paths, params);
5810        }
5811
5812        if let Some(config_events) = Self::watched_file_events_from_params(params, &custom_markers)
5813        {
5814            self.notify_watched_config_events(&config_events);
5815        }
5816
5817        Some(self.lsp_notify_and_collect_diagnostics(
5818            file_path,
5819            content,
5820            std::time::Duration::from_millis(wait_ms),
5821        ))
5822    }
5823
5824    fn path_restriction_context(
5825        &self,
5826        req_id: &str,
5827        path: &Path,
5828    ) -> Result<Option<PathRestrictionContext>, crate::protocol::Response> {
5829        let config = self.config();
5830        let force_restrict = self.request_force_restrict(req_id);
5831        if !config.restrict_to_project_root && !force_restrict {
5832            return Ok(None);
5833        }
5834        let root = match &config.project_root {
5835            Some(root) => root.clone(),
5836            None if force_restrict => {
5837                return Err(crate::protocol::Response::error(
5838                    req_id,
5839                    "path_outside_root",
5840                    "project root is required when path restriction is forced",
5841                ));
5842            }
5843            None => return Ok(None),
5844        };
5845        drop(config);
5846
5847        let raw_root = root.clone();
5848        let resolved_root = std::fs::canonicalize(&root).unwrap_or(root);
5849        let path_for_resolution = if path.is_relative() {
5850            raw_root.join(path)
5851        } else {
5852            path.to_path_buf()
5853        };
5854        Ok(Some(PathRestrictionContext {
5855            raw_root,
5856            resolved_root,
5857            path_for_resolution,
5858        }))
5859    }
5860
5861    /// Validate that a file path falls within the configured project root.
5862    ///
5863    /// When `project_root` is configured (normal plugin usage), this resolves the
5864    /// path and checks it starts with the root. Returns the canonicalized path on
5865    /// success, or an error response on violation.
5866    ///
5867    /// When no `project_root` is configured (direct CLI usage), all paths pass
5868    /// through unrestricted for backward compatibility.
5869    pub fn validate_path(
5870        &self,
5871        req_id: &str,
5872        path: &Path,
5873    ) -> Result<std::path::PathBuf, crate::protocol::Response> {
5874        self.validate_path_with_artifact_session(req_id, path, None)
5875    }
5876
5877    /// Validate a write location without following its final path component.
5878    ///
5879    /// Checkpoint creation and restore use this mode because the final component
5880    /// is the object being preserved or replaced. Following a symlink there would
5881    /// authorize its target and change the stored snapshot key. Every ancestor is
5882    /// still resolved so a symlinked parent cannot escape the project root.
5883    pub fn validate_write_location(
5884        &self,
5885        req_id: &str,
5886        path: &Path,
5887    ) -> Result<std::path::PathBuf, crate::protocol::Response> {
5888        let Some(PathRestrictionContext {
5889            raw_root,
5890            resolved_root,
5891            path_for_resolution,
5892        }) = self.path_restriction_context(req_id, path)?
5893        else {
5894            return Ok(path.to_path_buf());
5895        };
5896        let normalized = normalize_path(&path_for_resolution);
5897        let Some(file_name) = normalized.file_name() else {
5898            return self.validate_path(req_id, path);
5899        };
5900        let parent = normalized.parent().unwrap_or_else(|| Path::new(""));
5901        let resolved_parent = match std::fs::canonicalize(parent) {
5902            Ok(resolved) => resolved,
5903            Err(_) => {
5904                reject_escaping_symlink(req_id, path, parent, &resolved_root, &raw_root)?;
5905                resolve_with_existing_ancestors(parent)
5906            }
5907        };
5908        let resolved = normalize_path(&resolved_parent.join(file_name));
5909
5910        if !resolved.starts_with(&resolved_root) {
5911            return Err(path_error_response(req_id, path, &resolved_root));
5912        }
5913
5914        Ok(resolved)
5915    }
5916
5917    /// Validate a read path. A file produced by a background bash task may live
5918    /// outside the project root, so the session that owns the registered output
5919    /// may read that specific file. Mutating tools deliberately use
5920    /// [`AppContext::validate_path`] or [`AppContext::validate_write_location`]
5921    /// and never receive this exception.
5922    pub fn validate_read_path(
5923        &self,
5924        req_id: &str,
5925        session_id: &str,
5926        path: &Path,
5927    ) -> Result<std::path::PathBuf, crate::protocol::Response> {
5928        self.validate_path_with_artifact_session(req_id, path, Some(session_id))
5929    }
5930
5931    fn validate_path_with_artifact_session(
5932        &self,
5933        req_id: &str,
5934        path: &Path,
5935        artifact_session_id: Option<&str>,
5936    ) -> Result<std::path::PathBuf, crate::protocol::Response> {
5937        let Some(PathRestrictionContext {
5938            raw_root,
5939            resolved_root,
5940            path_for_resolution,
5941        }) = self.path_restriction_context(req_id, path)?
5942        else {
5943            // When path restriction is disabled, callers receive the input path
5944            // unchanged instead of an implicitly canonicalized filesystem path.
5945            return Ok(path.to_path_buf());
5946        };
5947
5948        // Resolve the path (follow symlinks, normalize ..). If canonicalization
5949        // fails (e.g. path does not exist or traverses a broken symlink), inspect
5950        // every existing component with lstat before falling back lexically so a
5951        // broken in-root symlink cannot be used to write outside project_root.
5952        let resolved = match std::fs::canonicalize(&path_for_resolution) {
5953            Ok(resolved) => resolved,
5954            Err(_) => {
5955                let normalized = normalize_path(&path_for_resolution);
5956                reject_escaping_symlink(
5957                    req_id,
5958                    &path_for_resolution,
5959                    &normalized,
5960                    &resolved_root,
5961                    &raw_root,
5962                )?;
5963                resolve_with_existing_ancestors(&normalized)
5964            }
5965        };
5966
5967        if !resolved.starts_with(&resolved_root) {
5968            let is_owned_bash_artifact = artifact_session_id.is_some_and(|session_id| {
5969                self.bash_background
5970                    .is_session_owned_artifact_path(session_id, &resolved)
5971            });
5972            if !is_owned_bash_artifact {
5973                return Err(path_error_response(req_id, path, &resolved_root));
5974            }
5975        }
5976
5977        Ok(resolved)
5978    }
5979
5980    /// Count active LSP server instances.
5981    pub fn lsp_server_count(&self) -> usize {
5982        self.lsp_manager
5983            .try_lock()
5984            .map(|lsp| lsp.server_count())
5985            .unwrap_or(0)
5986    }
5987
5988    /// Symbol cache statistics from the language provider.
5989    pub fn symbol_cache_stats(&self) -> serde_json::Value {
5990        let entries = self
5991            .symbol_cache
5992            .read()
5993            .map(|cache| cache.len())
5994            .unwrap_or(0);
5995        serde_json::json!({
5996            "local_entries": entries,
5997            "warm_entries": 0,
5998        })
5999    }
6000
6001    /// Build one root's memory estimate using only non-blocking lock attempts.
6002    /// A contended subsystem is represented as `busy` rather than delaying the
6003    /// status control path.
6004    pub fn memory_root_snapshot(&self) -> crate::memory::RootMemorySnapshot {
6005        let semantic = match self.semantic_index.try_read() {
6006            Ok(index) => index
6007                .as_ref()
6008                .map(SemanticIndex::estimated_memory)
6009                .unwrap_or_else(|| crate::memory::MemoryEstimate::estimated(0).count("entries", 0)),
6010            Err(TryLockError::Poisoned(error)) => error
6011                .into_inner()
6012                .as_ref()
6013                .map(SemanticIndex::estimated_memory)
6014                .unwrap_or_else(|| crate::memory::MemoryEstimate::estimated(0).count("entries", 0)),
6015            Err(TryLockError::WouldBlock) => crate::memory::MemoryEstimate::busy(),
6016        };
6017        let trigram = match self.search_index.try_read() {
6018            Ok(index) => index
6019                .as_ref()
6020                .map(SearchIndex::estimated_memory)
6021                .unwrap_or_else(|| crate::memory::MemoryEstimate::estimated(0).count("files", 0)),
6022            Err(TryLockError::Poisoned(error)) => error
6023                .into_inner()
6024                .as_ref()
6025                .map(SearchIndex::estimated_memory)
6026                .unwrap_or_else(|| crate::memory::MemoryEstimate::estimated(0).count("files", 0)),
6027            Err(TryLockError::WouldBlock) => crate::memory::MemoryEstimate::busy(),
6028        };
6029        let symbols = match self.symbol_cache.try_read() {
6030            Ok(cache) => cache.estimated_memory(),
6031            Err(TryLockError::Poisoned(error)) => error.into_inner().estimated_memory(),
6032            Err(TryLockError::WouldBlock) => crate::memory::MemoryEstimate::busy(),
6033        };
6034        let callgraph = match self.callgraph_store.try_read() {
6035            Ok(store) => store
6036                .as_ref()
6037                .map(|store| store.estimated_memory())
6038                .unwrap_or_else(|| {
6039                    crate::memory::MemoryEstimate::estimated(0).count("open_generation_handles", 0)
6040                }),
6041            Err(TryLockError::Poisoned(error)) => error
6042                .into_inner()
6043                .as_ref()
6044                .map(|store| store.estimated_memory())
6045                .unwrap_or_else(|| {
6046                    crate::memory::MemoryEstimate::estimated(0).count("open_generation_handles", 0)
6047                }),
6048            Err(TryLockError::WouldBlock) => crate::memory::MemoryEstimate::busy(),
6049        };
6050        let inspect = self.inspect_manager.estimated_memory();
6051        let bash = self.bash_background.estimated_memory();
6052        let lsp = self
6053            .lsp_manager
6054            .try_lock()
6055            .map(|lsp| lsp.estimated_memory())
6056            .unwrap_or_else(crate::memory::MemoryEstimate::busy);
6057        // AFT currently creates tree-sitter parsers per operation rather than
6058        // retaining a parser pool. Keep that fact explicit instead of assigning
6059        // a guessed byte size to tree-sitter internals.
6060        let parser_pool = crate::memory::MemoryEstimate::not_estimated()
6061            .count("pooled_parsers", 0)
6062            .gap("tree_sitter_parser_bytes");
6063        crate::memory::RootMemorySnapshot::new(
6064            semantic,
6065            trigram,
6066            symbols,
6067            callgraph,
6068            inspect,
6069            bash,
6070            lsp,
6071            parser_pool,
6072        )
6073    }
6074
6075    /// Attribute all actor roots registered in this process. Standalone mode
6076    /// has no actor registry, so the current context is inserted directly.
6077    pub fn memory_snapshot(&self, current_root: Option<&Path>) -> crate::memory::MemorySnapshot {
6078        let mut roots = BTreeMap::new();
6079        let (roots_status, contexts) = match self.app.try_memory_contexts() {
6080            Some(contexts) => ("ready", contexts),
6081            None => ("busy", Vec::new()),
6082        };
6083        for (root, context) in contexts {
6084            roots.insert(root.display().to_string(), context.memory_root_snapshot());
6085        }
6086        // Normalize through the same identity the registry keys on: on Windows
6087        // a verbatim `\\?\` current root would otherwise land as a SECOND
6088        // entry for an already-registered root and double-count its memory.
6089        let current_label = current_root
6090            .map(|root| {
6091                cortexkit_paths::ProjectRootId::from_path(root)
6092                    .map(|id| id.as_path().display().to_string())
6093                    .unwrap_or_else(|_| root.display().to_string())
6094            })
6095            .unwrap_or_else(|| "<unconfigured>".to_string());
6096        roots
6097            .entry(current_label)
6098            .or_insert_with(|| self.memory_root_snapshot());
6099        crate::memory::MemorySnapshot::new(roots_status, roots)
6100    }
6101}
6102
6103#[cfg(test)]
6104mod subc_lifecycle_admission_tests {
6105    use super::*;
6106
6107    #[test]
6108    fn route_teardown_does_not_supersede_disk_artifact_compatibility() {
6109        let ctx = AppContext::new(default_language_provider_factory(), Config::default());
6110        ctx.note_configure_warm_key("config-a".to_string());
6111        let content_generation = ctx.configure_content_generation();
6112        let lifecycle_generation = ctx.configure_generation();
6113        let search_epoch = ctx.next_search_persist_epoch();
6114        let semantic_epoch = ctx.next_semantic_persist_epoch();
6115        let search_persist_epoch = ctx.search_persist_epoch_flag();
6116        let semantic_persist_epoch = ctx.semantic_persist_epoch_flag();
6117
6118        ctx.mark_subc_unbound();
6119        assert!(ctx.configure_generation() > lifecycle_generation);
6120        assert_eq!(ctx.configure_content_generation(), content_generation);
6121        assert_eq!(search_persist_epoch.current(), search_epoch);
6122        assert_eq!(semantic_persist_epoch.current(), semantic_epoch);
6123
6124        ctx.mark_subc_bound();
6125        ctx.note_configure_warm_key("config-b".to_string());
6126        assert!(ctx.configure_content_generation() > content_generation);
6127        let replacement_search_epoch = ctx.next_search_persist_epoch();
6128        let replacement_semantic_epoch = ctx.next_semantic_persist_epoch();
6129        assert!(replacement_search_epoch > search_epoch);
6130        assert!(replacement_semantic_epoch > semantic_epoch);
6131        assert_eq!(search_persist_epoch.current(), replacement_search_epoch);
6132        assert_eq!(semantic_persist_epoch.current(), replacement_semantic_epoch);
6133    }
6134
6135    #[test]
6136    fn lifecycle_gate_serializes_unbind_with_worker_start_commit() {
6137        let admission = SubcLifecycleAdmission::default();
6138        let generation = Arc::new(AtomicU64::new(11));
6139        let expected = generation.load(Ordering::SeqCst);
6140        let starts = Arc::new(AtomicUsize::new(0));
6141        let (entered_tx, entered_rx) = std::sync::mpsc::channel();
6142        let (release_tx, release_rx) = std::sync::mpsc::channel();
6143
6144        let worker_admission = admission.clone();
6145        let worker_generation = Arc::clone(&generation);
6146        let worker_starts = Arc::clone(&starts);
6147        let worker = std::thread::spawn(move || {
6148            worker_admission.run_if_current(&worker_generation, expected, || {
6149                entered_tx.send(()).unwrap();
6150                release_rx.recv().unwrap();
6151                worker_starts.fetch_add(1, Ordering::SeqCst);
6152            })
6153        });
6154        entered_rx.recv().unwrap();
6155
6156        let unbind_admission = admission.clone();
6157        let unbind_generation = Arc::clone(&generation);
6158        let (unbound_tx, unbound_rx) = std::sync::mpsc::channel();
6159        let unbind = std::thread::spawn(move || {
6160            unbind_admission.mark_unbound(&unbind_generation);
6161            unbound_tx.send(()).unwrap();
6162        });
6163
6164        assert!(
6165            unbound_rx
6166                .recv_timeout(std::time::Duration::from_millis(50))
6167                .is_err(),
6168            "unbind must wait for an admitted worker-start commit"
6169        );
6170        release_tx.send(()).unwrap();
6171        assert!(worker.join().unwrap().is_some());
6172        unbound_rx
6173            .recv_timeout(std::time::Duration::from_secs(1))
6174            .unwrap();
6175        unbind.join().unwrap();
6176        assert_eq!(starts.load(Ordering::SeqCst), 1);
6177        assert!(
6178            admission
6179                .run_if_current(&generation, generation.load(Ordering::SeqCst), || {
6180                    starts.fetch_add(1, Ordering::SeqCst);
6181                })
6182                .is_none(),
6183            "worker starts after unbind must be denied"
6184        );
6185    }
6186
6187    #[test]
6188    fn health_snapshot_returns_busy_before_locking_artifact_receivers() {
6189        let ctx = Arc::new(AppContext::new(
6190            default_language_provider_factory(),
6191            Config::default(),
6192        ));
6193        let lifecycle_guard = ctx.subc_lifecycle.unbound.lock();
6194        let (started_tx, started_rx) = std::sync::mpsc::channel();
6195        let (snapshot_tx, snapshot_rx) = std::sync::mpsc::channel();
6196        let worker_ctx = Arc::clone(&ctx);
6197        let worker = std::thread::spawn(move || {
6198            started_tx.send(()).unwrap();
6199            snapshot_tx
6200                .send(worker_ctx.try_health_snapshot(Path::new("health-root")))
6201                .unwrap();
6202        });
6203        started_rx
6204            .recv_timeout(Duration::from_secs(1))
6205            .expect("health snapshot worker should start");
6206
6207        let snapshot = snapshot_rx.recv_timeout(Duration::from_secs(2));
6208        let callgraph_receiver_available = ctx.callgraph_store_rx.try_lock().is_some();
6209        drop(lifecycle_guard);
6210        worker.join().unwrap();
6211
6212        assert!(
6213            matches!(
6214                snapshot,
6215                Ok(RootHealthSnapshot {
6216                    state: RootHealthState::Busy,
6217                    ..
6218                })
6219            ),
6220            "health snapshots must report busy instead of waiting for lifecycle admission"
6221        );
6222        assert!(
6223            callgraph_receiver_available,
6224            "health snapshots must not hold the callgraph receiver while lifecycle admission is busy"
6225        );
6226    }
6227
6228    #[test]
6229    fn borrow_only_root_with_partial_tier2_aggregates_reports_disabled() {
6230        let ctx = AppContext::new(default_language_provider_factory(), Config::default());
6231        ctx.set_artifact_owner(
6232            Some(crate::artifact_owner::ArtifactOwnerStatus {
6233                mode: crate::artifact_owner::ArtifactOwnerMode::ReadOnly,
6234                project_key: "borrowed".to_string(),
6235                manifest_path: "manifest.json".to_string(),
6236                owner_project_scope_key: "owner".to_string(),
6237                owner_checkout_path: "/owner".to_string(),
6238                note: None,
6239            }),
6240            None,
6241        );
6242        ctx.update_status_bar_tier2(Some(4), None, None, None, true);
6243
6244        let snapshot = ctx.try_health_snapshot(Path::new("borrow-only-root"));
6245
6246        assert_eq!(snapshot.tier2.expect("tier2 health").status, "disabled");
6247    }
6248
6249    #[test]
6250    fn worktree_guard_prevents_partial_tier2_from_reporting_building() {
6251        let ctx = AppContext::new(default_language_provider_factory(), Config::default());
6252        ctx.set_cache_writer_capabilities(true, true);
6253        ctx.update_status_bar_tier2(Some(4), None, None, None, true);
6254        assert_eq!(
6255            ctx.try_health_snapshot(Path::new("writer-root"))
6256                .tier2
6257                .expect("tier2 health")
6258                .status,
6259            "building"
6260        );
6261
6262        ctx.set_cache_role(true, None);
6263
6264        assert_eq!(
6265            ctx.try_health_snapshot(Path::new("worktree-root"))
6266                .tier2
6267                .expect("tier2 health")
6268                .status,
6269            "disabled"
6270        );
6271    }
6272
6273    #[test]
6274    fn unbound_artifact_cancellation_clears_semantic_refresh_state() {
6275        let temp = tempfile::tempdir().unwrap();
6276        let ctx = AppContext::new(
6277            default_language_provider_factory(),
6278            Config {
6279                project_root: Some(temp.path().to_path_buf()),
6280                semantic_search: true,
6281                ..Config::default()
6282            },
6283        );
6284        *ctx.semantic_index()
6285            .write()
6286            .unwrap_or_else(std::sync::PoisonError::into_inner) =
6287            Some(SemanticIndex::new(temp.path().to_path_buf(), 3));
6288        let mut status = SemanticIndexStatus::ready();
6289        status.add_refreshing_file(temp.path().join("changed.rs"));
6290        *ctx.semantic_index_status()
6291            .write()
6292            .unwrap_or_else(std::sync::PoisonError::into_inner) = status;
6293        let (request_tx, _request_rx) = crossbeam_channel::unbounded();
6294        let (_event_tx, event_rx) = crossbeam_channel::unbounded();
6295        ctx.install_semantic_refresh_worker_for_build_epoch(
6296            request_tx,
6297            event_rx,
6298            Arc::new(Mutex::new(None)),
6299            ctx.semantic_index_rx_epoch(),
6300        );
6301
6302        ctx.cancel_unbound_artifact_work();
6303
6304        assert!(ctx.semantic_refresh_event_rx().lock().is_none());
6305        assert!(matches!(
6306            &*ctx
6307                .semantic_index_status()
6308                .read()
6309                .unwrap_or_else(std::sync::PoisonError::into_inner),
6310            SemanticIndexStatus::Ready { refreshing, .. } if refreshing.is_empty()
6311        ));
6312    }
6313
6314    #[test]
6315    fn terminal_empty_search_receiver_reports_completion_work() {
6316        let ctx = AppContext::new(default_language_provider_factory(), Config::default());
6317        let (sender, receiver) = crossbeam_channel::unbounded();
6318        let epoch = ctx.install_search_index_rx(receiver, ctx.configure_generation());
6319        let terminal_guard = ctx.search_index_rx_terminal_guard(epoch);
6320        drop(sender);
6321        drop(terminal_guard);
6322
6323        assert!(
6324            ctx.completion_drains_have_work(),
6325            "an empty disconnected one-shot receiver must wake the completion drain"
6326        );
6327    }
6328
6329    #[test]
6330    fn conditional_semantic_receiver_retire_preserves_replacement_epoch() {
6331        let ctx = AppContext::new(default_language_provider_factory(), Config::default());
6332        let (_old_sender, old_receiver) = crossbeam_channel::unbounded();
6333        let old_epoch = ctx.install_semantic_index_rx(old_receiver, ctx.configure_generation());
6334        let (_replacement_sender, replacement_receiver) = crossbeam_channel::unbounded();
6335        let replacement_epoch =
6336            ctx.install_semantic_index_rx(replacement_receiver, ctx.configure_generation());
6337
6338        assert!(replacement_epoch > old_epoch);
6339        assert_eq!(ctx.retire_semantic_index_rx_if_epoch(old_epoch), None);
6340        assert!(ctx.semantic_index_rx().lock().is_some());
6341        assert_eq!(ctx.semantic_index_rx_epoch(), replacement_epoch);
6342    }
6343
6344    #[test]
6345    fn stale_terminal_guard_cannot_hide_newer_finished_receiver() {
6346        let ctx = AppContext::new(default_language_provider_factory(), Config::default());
6347        let (old_sender, old_receiver) = crossbeam_channel::unbounded();
6348        let old_epoch = ctx.install_search_index_rx(old_receiver, ctx.configure_generation());
6349        let old_guard = ctx.search_index_rx_terminal_guard(old_epoch);
6350        let (current_sender, current_receiver) = crossbeam_channel::unbounded();
6351        let current_epoch =
6352            ctx.install_search_index_rx(current_receiver, ctx.configure_generation());
6353        let current_guard = ctx.search_index_rx_terminal_guard(current_epoch);
6354        drop(old_sender);
6355        drop(current_sender);
6356
6357        drop(current_guard);
6358        drop(old_guard);
6359
6360        assert!(current_epoch > old_epoch);
6361        assert_eq!(
6362            ctx.search_index_rx_terminal_epoch.load(Ordering::SeqCst),
6363            current_epoch,
6364            "a stale worker must not move the terminal watermark backward"
6365        );
6366        assert!(ctx.completion_drains_have_work());
6367    }
6368
6369    #[test]
6370    fn finished_semantic_refresh_worker_reports_completion_work() {
6371        let ctx = AppContext::new(default_language_provider_factory(), Config::default());
6372        let (request_tx, _request_rx) = crossbeam_channel::unbounded();
6373        let (event_tx, event_rx) = crossbeam_channel::unbounded();
6374        let worker_slot = Arc::new(Mutex::new(Some(std::thread::spawn(|| {}))));
6375        ctx.install_semantic_refresh_worker_for_build_epoch(
6376            request_tx,
6377            event_rx,
6378            Arc::clone(&worker_slot),
6379            ctx.semantic_index_rx_epoch(),
6380        );
6381        drop(event_tx);
6382        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(1);
6383        while !worker_slot
6384            .lock()
6385            .unwrap_or_else(std::sync::PoisonError::into_inner)
6386            .as_ref()
6387            .is_some_and(std::thread::JoinHandle::is_finished)
6388        {
6389            assert!(
6390                std::time::Instant::now() < deadline,
6391                "worker did not finish"
6392            );
6393            std::thread::yield_now();
6394        }
6395
6396        assert!(
6397            ctx.completion_drains_have_work(),
6398            "a finished refresh worker must wake the completion drain after its event queue empties"
6399        );
6400    }
6401
6402    #[test]
6403    fn unbound_lifecycle_rejects_all_deferred_worker_starts() {
6404        let admission = SubcLifecycleAdmission::default();
6405        let generation = Arc::new(AtomicU64::new(7));
6406        admission.mark_unbound(&generation);
6407        let expected = generation.load(Ordering::SeqCst);
6408        let starts = Arc::new(AtomicUsize::new(0));
6409
6410        let workers = (0..16)
6411            .map(|_| {
6412                let admission = admission.clone();
6413                let generation = Arc::clone(&generation);
6414                let starts = Arc::clone(&starts);
6415                std::thread::spawn(move || {
6416                    admission.run_if_current(&generation, expected, || {
6417                        starts.fetch_add(1, Ordering::SeqCst);
6418                    })
6419                })
6420            })
6421            .collect::<Vec<_>>();
6422
6423        for worker in workers {
6424            assert!(worker.join().unwrap().is_none());
6425        }
6426        assert_eq!(starts.load(Ordering::SeqCst), 0);
6427    }
6428}
6429
6430#[cfg(test)]
6431mod force_restrict_tests {
6432    use super::*;
6433    use crate::language::StubProvider;
6434    use tempfile::TempDir;
6435
6436    fn test_context(project_root: Option<PathBuf>, restrict_to_project_root: bool) -> AppContext {
6437        AppContext::new(
6438            Box::new(StubProvider),
6439            Config {
6440                project_root,
6441                restrict_to_project_root,
6442                ..Config::default()
6443            },
6444        )
6445    }
6446
6447    #[test]
6448    fn standalone_validate_path_parity_without_force_restrict() {
6449        let root = TempDir::new().expect("root tempdir");
6450        let outside = TempDir::new().expect("outside tempdir");
6451        let outside_path = outside.path().join("outside.txt");
6452
6453        let unrestricted = test_context(Some(root.path().to_path_buf()), false);
6454        assert_eq!(
6455            unrestricted
6456                .validate_path("standalone-unrestricted", &outside_path)
6457                .expect("unrestricted standalone validates"),
6458            outside_path
6459        );
6460
6461        let restricted = test_context(Some(root.path().to_path_buf()), true);
6462        let err = restricted
6463            .validate_path("standalone-restricted", &outside_path)
6464            .expect_err("restricted standalone rejects outside root");
6465        assert_eq!(
6466            serde_json::to_value(err).unwrap()["code"],
6467            "path_outside_root"
6468        );
6469    }
6470
6471    #[test]
6472    fn force_restrict_guard_refcounts_duplicate_request_ids() {
6473        let root = TempDir::new().expect("root tempdir");
6474        let outside = TempDir::new().expect("outside tempdir");
6475        let outside_path = outside.path().join("outside.txt");
6476        let ctx = test_context(Some(root.path().to_path_buf()), false);
6477
6478        assert!(ctx.validate_path("dup", &outside_path).is_ok());
6479        let guard1 = ctx.force_restrict_guard("dup");
6480        let guard2 = ctx.force_restrict_guard("dup");
6481        assert!(ctx.validate_path("dup", &outside_path).is_err());
6482        drop(guard1);
6483        assert!(
6484            ctx.validate_path("dup", &outside_path).is_err(),
6485            "duplicate guard must keep the request over-restricted"
6486        );
6487        drop(guard2);
6488        assert!(ctx.validate_path("dup", &outside_path).is_ok());
6489    }
6490
6491    #[test]
6492    fn with_force_restrict_cleans_up_after_normal_completion_and_panic() {
6493        let root = TempDir::new().expect("root tempdir");
6494        let outside = TempDir::new().expect("outside tempdir");
6495        let outside_path = outside.path().join("outside.txt");
6496        let ctx = test_context(Some(root.path().to_path_buf()), false);
6497
6498        ctx.with_force_restrict("normal", || {
6499            assert!(ctx.validate_path("normal", &outside_path).is_err());
6500        });
6501        assert!(!ctx.request_force_restrict("normal"));
6502        assert!(ctx.validate_path("normal", &outside_path).is_ok());
6503
6504        let panicked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
6505            ctx.with_force_restrict("panic", || {
6506                assert!(ctx.validate_path("panic", &outside_path).is_err());
6507                panic!("intentional force-restrict cleanup panic");
6508            });
6509        }));
6510        assert!(panicked.is_err());
6511        assert!(!ctx.request_force_restrict("panic"));
6512        assert!(ctx.validate_path("panic", &outside_path).is_ok());
6513    }
6514
6515    #[cfg(unix)]
6516    #[test]
6517    fn validate_write_location_keeps_final_symlink_as_the_authorized_location() {
6518        let root = TempDir::new().expect("root tempdir");
6519        let outside = tempfile::NamedTempFile::new().expect("outside file");
6520        let link = root.path().join("file.txt");
6521        std::os::unix::fs::symlink(outside.path(), &link).expect("create final symlink");
6522        let ctx = test_context(Some(root.path().to_path_buf()), false);
6523        let _guard = ctx.force_restrict_guard("write-location-final-link");
6524
6525        let validated = ctx
6526            .validate_write_location("write-location-final-link", &link)
6527            .expect("the in-root link location is writable");
6528
6529        assert_eq!(
6530            validated,
6531            std::fs::canonicalize(root.path()).unwrap().join("file.txt")
6532        );
6533    }
6534
6535    #[cfg(unix)]
6536    #[test]
6537    fn validate_write_location_rejects_symlinked_parent_escape() {
6538        let root = TempDir::new().expect("root tempdir");
6539        let outside = TempDir::new().expect("outside tempdir");
6540        let linked_parent = root.path().join("linked-parent");
6541        std::os::unix::fs::symlink(outside.path(), &linked_parent).expect("create parent symlink");
6542        let candidate = linked_parent.join("file.txt");
6543        let ctx = test_context(Some(root.path().to_path_buf()), false);
6544        let _guard = ctx.force_restrict_guard("write-location-parent-link");
6545
6546        let error = ctx
6547            .validate_write_location("write-location-parent-link", &candidate)
6548            .expect_err("a symlinked parent must not escape the project root");
6549
6550        assert_eq!(
6551            serde_json::to_value(error).unwrap()["code"],
6552            "path_outside_root"
6553        );
6554    }
6555
6556    #[cfg(unix)]
6557    #[test]
6558    fn validate_write_location_rejects_outside_link_to_inside_file() {
6559        let root = TempDir::new().expect("root tempdir");
6560        let outside = TempDir::new().expect("outside tempdir");
6561        let inside = root.path().join("inside.txt");
6562        std::fs::write(&inside, "inside").unwrap();
6563        let outside_link = outside.path().join("outside-link.txt");
6564        std::os::unix::fs::symlink(&inside, &outside_link).expect("create outside symlink");
6565        let ctx = test_context(Some(root.path().to_path_buf()), false);
6566        let _guard = ctx.force_restrict_guard("write-location-outside-link");
6567
6568        let error = ctx
6569            .validate_write_location("write-location-outside-link", &outside_link)
6570            .expect_err("an out-of-root lexical location must remain blocked");
6571
6572        assert_eq!(
6573            serde_json::to_value(error).unwrap()["code"],
6574            "path_outside_root"
6575        );
6576    }
6577
6578    #[test]
6579    fn forced_restrict_without_project_root_fails_closed() {
6580        let ctx = test_context(None, false);
6581        let _guard = ctx.force_restrict_guard("missing-root");
6582        let err = ctx
6583            .validate_path("missing-root", Path::new("relative.txt"))
6584            .expect_err("forced restriction without a root must fail closed");
6585        assert_eq!(
6586            serde_json::to_value(err).unwrap()["code"],
6587            "path_outside_root"
6588        );
6589
6590        let write_err = ctx
6591            .validate_write_location("missing-root", Path::new("relative.txt"))
6592            .expect_err("write-location validation must also fail closed");
6593        assert_eq!(
6594            serde_json::to_value(write_err).unwrap()["code"],
6595            "path_outside_root"
6596        );
6597    }
6598}
6599
6600#[cfg(test)]
6601mod callgraph_store_for_ops_tests {
6602    use super::*;
6603    use crate::inspect::{InspectCategory, InspectSnapshot, JobOutcome, JobScope};
6604    use crate::parser::TreeSitterProvider;
6605    use crate::protocol::RawRequest;
6606    use serde_json::json;
6607    use std::ffi::OsString;
6608    use std::path::Path;
6609    use std::sync::{Barrier, Mutex as StdMutex, MutexGuard, OnceLock};
6610    use tempfile::TempDir;
6611
6612    struct CallgraphWaitWindowEnvGuard {
6613        _guard: MutexGuard<'static, ()>,
6614        previous: Option<OsString>,
6615    }
6616
6617    impl Drop for CallgraphWaitWindowEnvGuard {
6618        fn drop(&mut self) {
6619            // SAFETY: serialized by the process-local guard held for this
6620            // helper's lifetime, and restored before the guard is released.
6621            unsafe {
6622                match &self.previous {
6623                    Some(value) => std::env::set_var("AFT_CALLGRAPH_BUILD_WAIT_MS", value),
6624                    None => std::env::remove_var("AFT_CALLGRAPH_BUILD_WAIT_MS"),
6625                }
6626            }
6627        }
6628    }
6629
6630    fn callgraph_build_wait_ms(ms: u64) -> CallgraphWaitWindowEnvGuard {
6631        static LOCK: OnceLock<StdMutex<()>> = OnceLock::new();
6632        let guard = LOCK
6633            .get_or_init(|| StdMutex::new(()))
6634            .lock()
6635            .unwrap_or_else(|error| error.into_inner());
6636        let previous = std::env::var_os("AFT_CALLGRAPH_BUILD_WAIT_MS");
6637        // SAFETY: serialized by LOCK above and restored by the returned guard.
6638        unsafe {
6639            std::env::set_var("AFT_CALLGRAPH_BUILD_WAIT_MS", ms.to_string());
6640        }
6641        CallgraphWaitWindowEnvGuard {
6642            _guard: guard,
6643            previous,
6644        }
6645    }
6646
6647    fn force_async_callgraph_builds() -> CallgraphWaitWindowEnvGuard {
6648        callgraph_build_wait_ms(0)
6649    }
6650
6651    fn cold_build_context() -> Arc<AppContext> {
6652        let project = TempDir::new().expect("project tempdir");
6653        let storage = TempDir::new().expect("storage tempdir");
6654        let source_dir = project.path().join("src");
6655        std::fs::create_dir_all(&source_dir).expect("source dir");
6656        std::fs::write(
6657            source_dir.join("lib.rs"),
6658            "pub fn caller() { callee(); }\npub fn callee() {}\n",
6659        )
6660        .expect("source file");
6661
6662        Arc::new(AppContext::new(
6663            Box::new(TreeSitterProvider::new()),
6664            Config {
6665                project_root: Some(project.keep()),
6666                storage_dir: Some(storage.keep()),
6667                callgraph_chunk_size: 1,
6668                ..Config::default()
6669            },
6670        ))
6671    }
6672
6673    fn with_fake_home_env<R>(home: &Path, f: impl FnOnce() -> R) -> R {
6674        let _guard = crate::test_env::process_env_lock();
6675        let prev_home = std::env::var_os("HOME");
6676        let prev_userprofile = std::env::var_os("USERPROFILE");
6677        unsafe {
6678            std::env::set_var("HOME", home);
6679            std::env::set_var("USERPROFILE", home);
6680        }
6681        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f));
6682        unsafe {
6683            match prev_home {
6684                Some(value) => std::env::set_var("HOME", value),
6685                None => std::env::remove_var("HOME"),
6686            }
6687            match prev_userprofile {
6688                Some(value) => std::env::set_var("USERPROFILE", value),
6689                None => std::env::remove_var("USERPROFILE"),
6690            }
6691        }
6692        match result {
6693            Ok(value) => value,
6694            Err(payload) => std::panic::resume_unwind(payload),
6695        }
6696    }
6697
6698    fn configure_request_with_params(params: serde_json::Value) -> RawRequest {
6699        RawRequest {
6700            id: "cfg".to_string(),
6701            command: "configure".to_string(),
6702            lsp_hints: None,
6703            session_id: None,
6704            params,
6705        }
6706    }
6707
6708    fn user_tier(doc: serde_json::Value) -> serde_json::Value {
6709        json!({
6710            "tier": "user",
6711            "source": "/u/aft.jsonc",
6712            "doc": doc.to_string(),
6713        })
6714    }
6715
6716    fn configure_context(project_root: &Path, storage_dir: &Path) -> AppContext {
6717        let ctx = AppContext::new(Box::new(TreeSitterProvider::new()), Config::default());
6718        let response = crate::commands::configure::handle_configure(
6719            &configure_request_with_params(json!({
6720                "project_root": project_root,
6721                "harness": "opencode",
6722                "storage_dir": storage_dir,
6723                "config": [user_tier(json!({
6724                    "callgraph_store": true,
6725                    "search_index": true,
6726                    "semantic_search": true,
6727                }))],
6728            })),
6729            &ctx,
6730        );
6731        assert!(response.success, "configure should succeed: {response:?}");
6732        ctx
6733    }
6734
6735    fn inspect_snapshot(ctx: &AppContext) -> InspectSnapshot {
6736        InspectSnapshot::new(
6737            ctx.canonical_cache_root(),
6738            ctx.inspect_dir(),
6739            ctx.config(),
6740            ctx.symbol_cache(),
6741        )
6742    }
6743
6744    fn empty_semantic_index_for_ctx(ctx: &AppContext) -> SemanticIndex {
6745        let project_root = ctx
6746            .config()
6747            .project_root
6748            .clone()
6749            .expect("test context has a project root");
6750        let files: Vec<PathBuf> = Vec::new();
6751        let mut embed = |_texts: Vec<String>| -> Result<Vec<Vec<f32>>, String> { Ok(Vec::new()) };
6752        SemanticIndex::build(&project_root, &files, &mut embed, 1)
6753            .expect("empty semantic index should build")
6754    }
6755
6756    #[test]
6757    fn home_root_gate_blocks_callgraph_store_entry_points() {
6758        let _wait_guard = force_async_callgraph_builds();
6759        let home = TempDir::new().expect("home tempdir");
6760        let storage = TempDir::new().expect("storage tempdir");
6761        let source_dir = home.path().join("src");
6762        std::fs::create_dir_all(&source_dir).expect("source dir");
6763        std::fs::write(
6764            source_dir.join("lib.rs"),
6765            "pub fn caller() { callee(); }\npub fn callee() {}\n",
6766        )
6767        .expect("source file");
6768
6769        with_fake_home_env(home.path(), || {
6770            let ctx = configure_context(home.path(), storage.path());
6771            assert!(
6772                !ctx.heavy_root_work_allowed(),
6773                "HOME root configure must close the heavy-root-work gate"
6774            );
6775            assert_eq!(
6776                ctx.try_health_snapshot(home.path())
6777                    .callgraph_store
6778                    .as_ref()
6779                    .map(|component| component.status),
6780                Some("disabled"),
6781                "HOME root health must not advertise callgraph building"
6782            );
6783
6784            reset_callgraph_cold_build_spawn_count_for_test();
6785            assert!(matches!(
6786                ctx.callgraph_store_for_ops(),
6787                CallgraphStoreAccess::Unavailable
6788            ));
6789            assert!(
6790                ctx.ensure_callgraph_store()
6791                    .expect("ensure_callgraph_store should not error")
6792                    .is_none(),
6793                "shared gate must also block synchronous standalone callgraph builds"
6794            );
6795            assert_eq!(
6796                callgraph_cold_build_spawn_count_for_test(),
6797                0,
6798                "HOME root gate must not spawn a cold callgraph build"
6799            );
6800        });
6801    }
6802
6803    #[test]
6804    fn home_root_gate_blocks_inspect_manager_submit_paths() {
6805        let home = TempDir::new().expect("home tempdir");
6806        let storage = TempDir::new().expect("storage tempdir");
6807        let source_dir = home.path().join("src");
6808        std::fs::create_dir_all(&source_dir).expect("source dir");
6809        std::fs::write(source_dir.join("lib.rs"), "pub fn one() {}\n").expect("source file");
6810
6811        with_fake_home_env(home.path(), || {
6812            let ctx = configure_context(home.path(), storage.path());
6813            let snapshot = inspect_snapshot(&ctx);
6814            let scope = JobScope::for_project(snapshot.project_root.clone());
6815            let manager = ctx.inspect_manager();
6816
6817            assert!(matches!(
6818                manager.submit_category(snapshot.clone(), InspectCategory::Metrics, scope.clone()),
6819                JobOutcome::Failed { .. }
6820            ));
6821
6822            let submission = manager.submit_tier2_run_with_reuse_serial_background(
6823                snapshot,
6824                vec![InspectCategory::DeadCode],
6825            );
6826            assert!(submission.queued_categories.is_empty());
6827            assert!(submission.newly_queued_categories.is_empty());
6828            assert!(submission.deferred_categories.is_empty());
6829            assert_eq!(submission.errors.len(), 1);
6830            assert!(
6831                !manager.tier2_any_in_flight(),
6832                "HOME root gate must reject Tier-2 submission before any job is queued"
6833            );
6834        });
6835    }
6836
6837    #[test]
6838    fn non_home_root_still_allows_callgraph_cold_builds() {
6839        let _env_guard = force_async_callgraph_builds();
6840        reset_callgraph_cold_build_spawn_count_for_test();
6841        let ctx = cold_build_context();
6842
6843        assert!(ctx.heavy_root_work_allowed());
6844        assert!(matches!(
6845            ctx.callgraph_store_for_ops(),
6846            CallgraphStoreAccess::Building | CallgraphStoreAccess::Ready(_)
6847        ));
6848        assert_eq!(
6849            callgraph_cold_build_spawn_count_for_test(),
6850            1,
6851            "non-home roots must still be able to cold-build the callgraph store"
6852        );
6853
6854        let rx = ctx
6855            .callgraph_store_rx
6856            .lock()
6857            .as_ref()
6858            .cloned()
6859            .expect("non-home cold build should install an in-flight receiver");
6860        rx.recv_timeout(Duration::from_secs(30))
6861            .expect("background cold build should complete");
6862        *ctx.callgraph_store_rx.lock() = None;
6863    }
6864
6865    #[test]
6866    fn semantic_ready_event_resumes_deferred_callgraph_and_tier2() {
6867        let _env_guard = force_async_callgraph_builds();
6868        CALLGRAPH_COLD_BUILD_SPAWN_COUNT.store(0, Ordering::SeqCst);
6869        let ctx = cold_build_context();
6870        let (tx, rx) = crossbeam_channel::unbounded();
6871        *ctx.semantic_index_rx().lock() = Some(rx);
6872        ctx.schedule_semantic_cold_seed_gate_for_configure();
6873
6874        assert!(matches!(
6875            ctx.callgraph_store_for_ops(),
6876            CallgraphStoreAccess::Building
6877        ));
6878        assert_eq!(CALLGRAPH_COLD_BUILD_SPAWN_COUNT.load(Ordering::SeqCst), 0);
6879        tx.send(SemanticIndexEvent::Ready(empty_semantic_index_for_ctx(
6880            &ctx,
6881        )))
6882        .expect("send ready event");
6883
6884        crate::runtime_drain::drain_semantic_index_events(&ctx);
6885
6886        assert!(
6887            !ctx.semantic_cold_seed_active(),
6888            "semantic Ready must clear the scheduled cold gate"
6889        );
6890        assert!(
6891            ctx.tier2_pull_demand_pending(),
6892            "semantic Ready must resume deferred Tier-2 work"
6893        );
6894        assert_eq!(
6895            CALLGRAPH_COLD_BUILD_SPAWN_COUNT.load(Ordering::SeqCst),
6896            1,
6897            "semantic Ready must resume the deferred callgraph warm"
6898        );
6899        let rx = ctx
6900            .callgraph_store_rx
6901            .lock()
6902            .as_ref()
6903            .cloned()
6904            .expect("ready resume should install an in-flight callgraph receiver");
6905        rx.recv_timeout(Duration::from_secs(30))
6906            .expect("background cold build should complete");
6907        *ctx.callgraph_store_rx.lock() = None;
6908    }
6909
6910    #[test]
6911    fn semantic_gate_cleared_event_resumes_deferred_callgraph_and_tier2() {
6912        let _env_guard = force_async_callgraph_builds();
6913        CALLGRAPH_COLD_BUILD_SPAWN_COUNT.store(0, Ordering::SeqCst);
6914        let ctx = cold_build_context();
6915        ctx.schedule_semantic_cold_seed_gate_for_configure();
6916
6917        assert!(matches!(
6918            ctx.callgraph_store_for_ops(),
6919            CallgraphStoreAccess::Building
6920        ));
6921        assert_eq!(CALLGRAPH_COLD_BUILD_SPAWN_COUNT.load(Ordering::SeqCst), 0);
6922        ctx.resume_deferred_work_after_semantic_cold_seed_gate_cleared();
6923
6924        assert!(
6925            !ctx.semantic_cold_seed_active(),
6926            "cached-load or retry-wait clear must reopen the semantic cold gate"
6927        );
6928        assert!(
6929            ctx.tier2_pull_demand_pending(),
6930            "cached-load or retry-wait clear must resume deferred Tier-2 work"
6931        );
6932        assert_eq!(
6933            CALLGRAPH_COLD_BUILD_SPAWN_COUNT.load(Ordering::SeqCst),
6934            1,
6935            "cached-load or retry-wait clear must resume deferred callgraph warm"
6936        );
6937        let rx = ctx
6938            .callgraph_store_rx
6939            .lock()
6940            .as_ref()
6941            .cloned()
6942            .expect("gate-clear resume should install an in-flight callgraph receiver");
6943        rx.recv_timeout(Duration::from_secs(30))
6944            .expect("background cold build should complete");
6945        *ctx.callgraph_store_rx.lock() = None;
6946    }
6947
6948    #[test]
6949    fn semantic_cold_seed_gate_defers_callgraph_cold_spawn_until_resume() {
6950        let _env_guard = force_async_callgraph_builds();
6951        CALLGRAPH_COLD_BUILD_SPAWN_COUNT.store(0, Ordering::SeqCst);
6952        let ctx = cold_build_context();
6953
6954        ctx.set_semantic_cold_seed_active_for_test(true);
6955        assert!(
6956            matches!(
6957                ctx.callgraph_store_for_ops(),
6958                CallgraphStoreAccess::Building
6959            ),
6960            "callgraph ops should degrade as building while the semantic cold gate is active"
6961        );
6962        assert_eq!(
6963            CALLGRAPH_COLD_BUILD_SPAWN_COUNT.load(Ordering::SeqCst),
6964            0,
6965            "semantic cold gate must not spawn a competing callgraph cold build"
6966        );
6967        assert!(ctx.semantic_callgraph_warm_deferred_for_test());
6968
6969        ctx.clear_semantic_cold_seed_gate_and_resume_deferred_work();
6970        assert_eq!(
6971            CALLGRAPH_COLD_BUILD_SPAWN_COUNT.load(Ordering::SeqCst),
6972            1,
6973            "clearing the semantic cold gate should resume the deferred callgraph warm"
6974        );
6975
6976        let rx = ctx
6977            .callgraph_store_rx
6978            .lock()
6979            .as_ref()
6980            .cloned()
6981            .expect("deferred warm should install an in-flight receiver");
6982        rx.recv_timeout(Duration::from_secs(30))
6983            .expect("background cold build should complete");
6984        *ctx.callgraph_store_rx.lock() = None;
6985    }
6986
6987    #[test]
6988    fn semantic_cold_seed_gate_clear_requests_tier2_pull() {
6989        let ctx = AppContext::new(Box::new(TreeSitterProvider::new()), Config::default());
6990        ctx.schedule_semantic_cold_seed_gate_for_configure();
6991
6992        ctx.resume_deferred_work_after_semantic_cold_seed_gate_cleared();
6993
6994        assert!(
6995            !ctx.semantic_cold_seed_active(),
6996            "retry-wait or cached-load events must reopen the semantic cold gate"
6997        );
6998        assert!(
6999            ctx.tier2_pull_demand_pending(),
7000            "clearing the semantic cold gate should kick a Tier-2 pull refresh"
7001        );
7002    }
7003
7004    #[test]
7005    fn semantic_failed_event_clears_scheduled_gate_and_requests_tier2_pull() {
7006        let ctx = AppContext::new(Box::new(TreeSitterProvider::new()), Config::default());
7007        let (tx, rx) = crossbeam_channel::unbounded();
7008        *ctx.semantic_index_rx().lock() = Some(rx);
7009        ctx.schedule_semantic_cold_seed_gate_for_configure();
7010        tx.send(SemanticIndexEvent::Failed(
7011            "embedding backend failed".to_string(),
7012        ))
7013        .expect("send failed event");
7014
7015        crate::runtime_drain::drain_semantic_index_events(&ctx);
7016
7017        assert!(
7018            !ctx.semantic_cold_seed_active(),
7019            "semantic Failed must clear the scheduled cold gate"
7020        );
7021        assert!(
7022            ctx.tier2_pull_demand_pending(),
7023            "semantic Failed must resume deferred Tier-2 work"
7024        );
7025    }
7026
7027    #[test]
7028    fn semantic_disconnect_clears_scheduled_gate_and_requests_tier2_pull() {
7029        let ctx = AppContext::new(Box::new(TreeSitterProvider::new()), Config::default());
7030        let (tx, rx) = crossbeam_channel::unbounded::<SemanticIndexEvent>();
7031        *ctx.semantic_index_rx().lock() = Some(rx);
7032        ctx.schedule_semantic_cold_seed_gate_for_configure();
7033        drop(tx);
7034
7035        crate::runtime_drain::drain_semantic_index_events(&ctx);
7036
7037        assert!(
7038            !ctx.semantic_cold_seed_active(),
7039            "semantic worker disconnect must clear the scheduled cold gate"
7040        );
7041        assert!(
7042            ctx.tier2_pull_demand_pending(),
7043            "semantic worker disconnect must resume deferred Tier-2 work"
7044        );
7045    }
7046
7047    #[test]
7048    fn semantic_cold_seed_gate_is_per_context_for_tier2_scheduler() {
7049        let ctx_a = AppContext::new(Box::new(TreeSitterProvider::new()), Config::default());
7050        let ctx_b = AppContext::new(Box::new(TreeSitterProvider::new()), Config::default());
7051        let base = Instant::now();
7052        ctx_a.reset_tier2_refresh_scheduler_at(base);
7053        ctx_b.reset_tier2_refresh_scheduler_at(base);
7054        ctx_a.set_semantic_cold_seed_active_for_test(true);
7055
7056        assert_eq!(
7057            ctx_a.tick_tier2_refresh_scheduler_at(
7058                base + crate::inspect::tier2_scheduler::TIER2_REFRESH_COLD_CACHE_DELAY,
7059                0,
7060            ),
7061            None,
7062            "root A should defer Tier-2 while its semantic cold seed is active"
7063        );
7064        assert_eq!(
7065            ctx_b.tick_tier2_refresh_scheduler_at(
7066                base + crate::inspect::tier2_scheduler::TIER2_REFRESH_COLD_CACHE_DELAY,
7067                0,
7068            ),
7069            Some(Tier2TriggerReason::ConfigureWarm),
7070            "root B must not inherit root A's semantic cold gate"
7071        );
7072    }
7073
7074    #[test]
7075    fn inline_wait_settled_event_clears_superseded_receiver() {
7076        let _env_guard = callgraph_build_wait_ms(2_000);
7077        let project = TempDir::new().expect("project tempdir");
7078        let storage = TempDir::new().expect("storage tempdir");
7079        std::fs::write(project.path().join("lib.rs"), "pub fn marker() {}\n").expect("source file");
7080        let project_root = std::fs::canonicalize(project.path()).expect("canonical project root");
7081        let ctx = Arc::new(AppContext::new(
7082            Box::new(TreeSitterProvider::new()),
7083            Config {
7084                project_root: Some(project.path().to_path_buf()),
7085                storage_dir: Some(storage.path().to_path_buf()),
7086                callgraph_chunk_size: 1,
7087                ..Config::default()
7088            },
7089        ));
7090        let (reached, release) = install_callgraph_build_start_gate(project_root);
7091        let request_ctx = Arc::clone(&ctx);
7092        let request = std::thread::spawn(move || request_ctx.callgraph_store_for_ops());
7093        reached
7094            .recv_timeout(Duration::from_secs(2))
7095            .expect("callgraph worker did not reach start barrier");
7096
7097        ctx.next_callgraph_persist_epoch();
7098        release.send(()).unwrap();
7099        assert!(matches!(
7100            request.join().expect("callgraph request thread"),
7101            CallgraphStoreAccess::Building
7102        ));
7103        assert!(
7104            ctx.callgraph_store_rx().lock().is_none(),
7105            "inline Settled handling must retire the matching receiver"
7106        );
7107        assert!(
7108            ctx.callgraph_store()
7109                .read()
7110                .unwrap_or_else(std::sync::PoisonError::into_inner)
7111                .is_none(),
7112            "Settled must not reopen and install an older persisted store"
7113        );
7114    }
7115
7116    #[test]
7117    fn inline_ready_without_published_pointer_settles_and_preserves_pending_paths() {
7118        let _env_guard = callgraph_build_wait_ms(2_000);
7119        let project = TempDir::new().expect("project tempdir");
7120        let storage = TempDir::new().expect("storage tempdir");
7121        std::fs::write(project.path().join("lib.rs"), "pub fn marker() {}\n").expect("source file");
7122        let ctx = AppContext::new(
7123            Box::new(TreeSitterProvider::new()),
7124            Config {
7125                project_root: Some(project.path().to_path_buf()),
7126                storage_dir: Some(storage.path().to_path_buf()),
7127                callgraph_chunk_size: 1,
7128                ..Config::default()
7129            },
7130        );
7131        let pending = project.path().join("pending.rs");
7132        ctx.add_pending_callgraph_store_paths([pending.clone()]);
7133        REMOVE_CALLGRAPH_POINTER_BEFORE_INLINE_REOPEN.store(true, Ordering::SeqCst);
7134        let _remove_pointer_guard = RemoveCallgraphPointerBeforeInlineReopenGuard;
7135
7136        assert!(matches!(
7137            ctx.callgraph_store_for_ops(),
7138            CallgraphStoreAccess::Building
7139        ));
7140        assert!(
7141            ctx.callgraph_store_rx().lock().is_none(),
7142            "inline Ready must settle after the published pointer disappears"
7143        );
7144        assert_eq!(
7145            ctx.take_pending_callgraph_store_paths(),
7146            vec![pending],
7147            "inline reopen failure must preserve pending watcher paths"
7148        );
7149    }
7150
7151    #[test]
7152    fn take_pending_callgraph_store_paths_drops_paths_outside_current_root() {
7153        let project = TempDir::new().expect("project tempdir");
7154        let foreign = TempDir::new().expect("foreign tempdir");
7155        let ctx = AppContext::new(
7156            Box::new(TreeSitterProvider::new()),
7157            Config {
7158                project_root: Some(project.path().to_path_buf()),
7159                ..Config::default()
7160            },
7161        );
7162        let inside = project.path().join("kept.rs");
7163        // A late-deferring batch from a superseded root writes into the shared
7164        // pending sink; replaying it into the NEW root's store would index a
7165        // foreign project's files.
7166        let outside = foreign.path().join("previous-root-file.rs");
7167        // Lexical escape: starts_with(project) is true on the raw spelling but
7168        // the path resolves outside the root.
7169        let dotdot_escape = project
7170            .path()
7171            .join("..")
7172            .join(
7173                foreign
7174                    .path()
7175                    .file_name()
7176                    .expect("foreign tempdir has a name"),
7177            )
7178            .join("escaped.rs");
7179        ctx.add_pending_callgraph_store_paths([inside.clone(), outside, dotdot_escape]);
7180
7181        assert_eq!(
7182            ctx.take_pending_callgraph_store_paths(),
7183            vec![inside],
7184            "pending replay must drop foreign and dot-dot-escaping paths"
7185        );
7186    }
7187
7188    #[test]
7189    fn watcher_gap_invalidation_keeps_semantic_reloadable_and_skips_readonly_force_token() {
7190        let project = TempDir::new().expect("project tempdir");
7191        let ctx = AppContext::new(
7192            Box::new(TreeSitterProvider::new()),
7193            Config {
7194                project_root: Some(project.path().to_path_buf()),
7195                semantic_search: true,
7196                ..Config::default()
7197            },
7198        );
7199        ctx.set_canonical_cache_root(project.path().to_path_buf());
7200        // Read-only root: a force token could only be fulfilled by a local
7201        // writer build, which this root will never run.
7202        ctx.set_cache_writer_capabilities(false, true);
7203        *ctx.semantic_index_status()
7204            .write()
7205            .unwrap_or_else(std::sync::PoisonError::into_inner) = SemanticIndexStatus::ready();
7206
7207        ctx.invalidate_artifacts_after_watcher_gap();
7208
7209        assert!(
7210            matches!(
7211                &*ctx
7212                    .semantic_index_status()
7213                    .read()
7214                    .unwrap_or_else(std::sync::PoisonError::into_inner),
7215                SemanticIndexStatus::Ready { .. }
7216            ),
7217            "semantic-enabled root must stay reloadable (Disabled has no self-healing path)"
7218        );
7219        assert_eq!(
7220            ctx.pending_callgraph_store_force_token(),
7221            None,
7222            "read-only root must not be stuck behind an unfulfillable force token"
7223        );
7224    }
7225
7226    #[test]
7227    fn watcher_gap_invalidation_marks_force_rebuild_for_writer_roots() {
7228        let project = TempDir::new().expect("project tempdir");
7229        let ctx = AppContext::new(
7230            Box::new(TreeSitterProvider::new()),
7231            Config {
7232                project_root: Some(project.path().to_path_buf()),
7233                ..Config::default()
7234            },
7235        );
7236        ctx.set_canonical_cache_root(project.path().to_path_buf());
7237        ctx.set_cache_writer_capabilities(true, true);
7238
7239        ctx.invalidate_artifacts_after_watcher_gap();
7240
7241        assert!(
7242            ctx.pending_callgraph_store_force_token().is_some(),
7243            "writer roots must still reconcile the store after the unobserved interval"
7244        );
7245        assert!(
7246            matches!(
7247                &*ctx
7248                    .semantic_index_status()
7249                    .read()
7250                    .unwrap_or_else(std::sync::PoisonError::into_inner),
7251                SemanticIndexStatus::Disabled
7252            ),
7253            "semantic-disabled config maps to Disabled status"
7254        );
7255    }
7256
7257    #[cfg(unix)]
7258    #[test]
7259    fn take_pending_callgraph_store_paths_drops_symlink_dotdot_escape() {
7260        let project = TempDir::new().expect("project tempdir");
7261        let foreign = TempDir::new().expect("foreign tempdir");
7262        std::fs::create_dir_all(foreign.path().join("dir")).expect("foreign dir");
7263        std::fs::write(foreign.path().join("secret.rs"), "pub fn s() {}\n").expect("secret");
7264        let ctx = AppContext::new(
7265            Box::new(TreeSitterProvider::new()),
7266            Config {
7267                project_root: Some(project.path().to_path_buf()),
7268                ..Config::default()
7269            },
7270        );
7271        // `root/link` targets a foreign directory; `root/link/../secret.rs`
7272        // therefore resolves to `foreign/secret.rs` under filesystem-first
7273        // semantics (matching the store's normalize_file_path). A lexical-first
7274        // filter would erase `link/..` and wrongly keep it as `root/secret.rs`.
7275        std::os::unix::fs::symlink(foreign.path().join("dir"), project.path().join("link"))
7276            .expect("plant symlink");
7277        let escape = project.path().join("link").join("..").join("secret.rs");
7278        // Dead component below the symlink: full canonicalization fails, so
7279        // the ancestor walk must reach and resolve `link` BEFORE any lexical
7280        // `..` resolution — a lexical-first pass would erase `dead/../..` and
7281        // wrongly keep this as `root/deep-secret.rs`.
7282        let dead_component_escape = project
7283            .path()
7284            .join("link")
7285            .join("dead")
7286            .join("..")
7287            .join("..")
7288            .join("deep-secret.rs");
7289        // Re-entry: `dead/..` drains back to the project root, then `link`
7290        // (an EXISTING symlink) must resolve through the filesystem — a
7291        // one-shot lexical pass over the dead tail would erase `link/..` too
7292        // and wrongly keep this as `root/reentry-secret.rs`.
7293        std::fs::write(foreign.path().join("reentry-secret.rs"), "pub fn r() {}\n")
7294            .expect("reentry secret");
7295        let reentry_escape = project
7296            .path()
7297            .join("dead")
7298            .join("..")
7299            .join("link")
7300            .join("..")
7301            .join("reentry-secret.rs");
7302        // Dangling symlink whose `..` re-enters the root: the store cannot
7303        // canonicalize it either and keeps the raw absolute spelling as an
7304        // out-of-root key, so containment must fail closed (a repaired-target
7305        // race could otherwise index outside the root).
7306        std::os::unix::fs::symlink(
7307            foreign.path().join("nonexistent-target"),
7308            project.path().join("dangling"),
7309        )
7310        .expect("plant dangling symlink");
7311        let dangling_reentry = project
7312            .path()
7313            .join("dangling")
7314            .join("..")
7315            .join("via-dangling.rs");
7316        // `..` traversal through a regular file: realpath rejects with
7317        // ENOTDIR; lexically popping the file would fabricate containment.
7318        std::fs::write(project.path().join("plain.rs"), "pub fn p() {}\n").expect("plain file");
7319        let through_file = project
7320            .path()
7321            .join("plain.rs")
7322            .join("..")
7323            .join("via-file.rs");
7324        let kept = project.path().join("kept.rs");
7325        ctx.add_pending_callgraph_store_paths([
7326            escape,
7327            dead_component_escape,
7328            reentry_escape,
7329            dangling_reentry,
7330            through_file,
7331            kept.clone(),
7332        ]);
7333
7334        assert_eq!(
7335            ctx.take_pending_callgraph_store_paths(),
7336            vec![kept],
7337            "symlink-plus-dotdot escapes must be dropped with filesystem-first semantics"
7338        );
7339    }
7340
7341    #[cfg(windows)]
7342    #[test]
7343    fn take_pending_callgraph_store_paths_drops_drive_relative_paths() {
7344        // Guard-sensitivity: exercise the classifier directly against a root
7345        // ON THE DRIVE CWD's drive, where join() replaces the root and the
7346        // joined path can genuinely resolve under the drive CWD — without the
7347        // early Prefix/RootDir rejection, a `C:file-under-cwd` spelling whose
7348        // drive CWD happens to sit inside the root would pass the post-join
7349        // prefix check.
7350        let cwd = std::env::current_dir().expect("drive cwd");
7351        let cwd_file = PathBuf::from(format!(
7352            "{}under-drive-cwd.rs",
7353            cwd.components()
7354                .next()
7355                .map(|prefix| prefix.as_os_str().to_string_lossy().into_owned())
7356                .expect("drive prefix")
7357        ));
7358        assert!(cwd_file.is_relative(), "C:foo must classify as relative");
7359        assert!(
7360            !pending_path_in_roots(&cwd_file, &[cwd.clone()]),
7361            "drive-relative spelling must be rejected even when the drive CWD is inside the root"
7362        );
7363        assert!(
7364            !pending_path_in_roots(Path::new(r"\root-relative.rs"), &[cwd]),
7365            "root-relative spelling must be rejected"
7366        );
7367
7368        let project = TempDir::new().expect("project tempdir");
7369        let ctx = AppContext::new(
7370            Box::new(TreeSitterProvider::new()),
7371            Config {
7372                project_root: Some(project.path().to_path_buf()),
7373                ..Config::default()
7374            },
7375        );
7376        let kept = project.path().join("kept.rs");
7377        ctx.add_pending_callgraph_store_paths([
7378            PathBuf::from("C:drive-relative.rs"),
7379            PathBuf::from(r"\root-relative.rs"),
7380            kept.clone(),
7381        ]);
7382
7383        assert_eq!(
7384            ctx.take_pending_callgraph_store_paths(),
7385            vec![kept],
7386            "drive-relative and root-relative spellings must be rejected"
7387        );
7388    }
7389
7390    #[test]
7391    fn take_pending_callgraph_store_paths_keeps_relative_and_deleted_paths() {
7392        let project = TempDir::new().expect("project tempdir");
7393        let ctx = AppContext::new(
7394            Box::new(TreeSitterProvider::new()),
7395            Config {
7396                project_root: Some(project.path().to_path_buf()),
7397                ..Config::default()
7398            },
7399        );
7400        // Relative paths are project-root-relative by the callgraph store's
7401        // contract, and pending paths legitimately reference deleted files.
7402        let relative = PathBuf::from("src/relative.rs");
7403        let deleted = project.path().join("never-created.rs");
7404        ctx.add_pending_callgraph_store_paths([relative.clone(), deleted.clone()]);
7405
7406        let mut taken = ctx.take_pending_callgraph_store_paths();
7407        taken.sort();
7408        let mut expected = vec![relative, deleted];
7409        expected.sort();
7410        assert_eq!(
7411            taken, expected,
7412            "root-relative and deleted in-root paths must survive the filter"
7413        );
7414    }
7415
7416    #[test]
7417    fn concurrent_cold_callgraph_store_for_ops_spawns_one_build() {
7418        let _env_guard = force_async_callgraph_builds();
7419        CALLGRAPH_COLD_BUILD_SPAWN_COUNT.store(0, Ordering::SeqCst);
7420
7421        let project = TempDir::new().expect("project tempdir");
7422        let storage = TempDir::new().expect("storage tempdir");
7423        let source_dir = project.path().join("src");
7424        std::fs::create_dir_all(&source_dir).expect("source dir");
7425        std::fs::write(
7426            source_dir.join("lib.rs"),
7427            "pub fn caller() { callee(); }\npub fn callee() {}\n",
7428        )
7429        .expect("source file");
7430
7431        let ctx = Arc::new(AppContext::new(
7432            Box::new(TreeSitterProvider::new()),
7433            Config {
7434                project_root: Some(project.path().to_path_buf()),
7435                storage_dir: Some(storage.path().to_path_buf()),
7436                callgraph_chunk_size: 1,
7437                ..Config::default()
7438            },
7439        ));
7440
7441        let barrier = Arc::new(Barrier::new(3));
7442        let handles = (0..2)
7443            .map(|_| {
7444                let ctx = Arc::clone(&ctx);
7445                let barrier = Arc::clone(&barrier);
7446                std::thread::spawn(move || {
7447                    barrier.wait();
7448                    matches!(
7449                        ctx.callgraph_store_for_ops(),
7450                        CallgraphStoreAccess::Building | CallgraphStoreAccess::Ready(_)
7451                    )
7452                })
7453            })
7454            .collect::<Vec<_>>();
7455
7456        barrier.wait();
7457        for handle in handles {
7458            assert!(
7459                handle.join().expect("callgraph caller thread"),
7460                "cold callgraph ops should report Building or observe the installed store"
7461            );
7462        }
7463
7464        assert_eq!(
7465            CALLGRAPH_COLD_BUILD_SPAWN_COUNT.load(Ordering::SeqCst),
7466            1,
7467            "concurrent cold callers must share one background build"
7468        );
7469
7470        let rx = ctx
7471            .callgraph_store_rx
7472            .lock()
7473            .as_ref()
7474            .cloned()
7475            .expect("in-flight receiver installed before spawn");
7476        rx.recv_timeout(Duration::from_secs(30))
7477            .expect("background cold build should complete");
7478        *ctx.callgraph_store_rx.lock() = None;
7479    }
7480
7481    #[test]
7482    fn watcher_gap_invalidation_gates_resident_artifacts_and_forces_strict_verify() {
7483        let root = TempDir::new().expect("project tempdir");
7484        let canonical_root = std::fs::canonicalize(root.path()).expect("canonical project root");
7485        let ctx = AppContext::new(
7486            Box::new(TreeSitterProvider::new()),
7487            Config {
7488                project_root: Some(canonical_root.clone()),
7489                ..Config::default()
7490            },
7491        );
7492        *ctx.search_index
7493            .write()
7494            .unwrap_or_else(std::sync::PoisonError::into_inner) =
7495            Some(SearchIndex::build(&canonical_root));
7496        *ctx.semantic_index
7497            .write()
7498            .unwrap_or_else(std::sync::PoisonError::into_inner) =
7499            Some(SemanticIndex::new(canonical_root.clone(), 3));
7500        *ctx.semantic_index_status
7501            .write()
7502            .unwrap_or_else(std::sync::PoisonError::into_inner) = SemanticIndexStatus::ready();
7503
7504        let artifact = canonical_root.join("verify-artifact.bin");
7505        std::fs::write(&artifact, b"same-size").expect("write verification artifact");
7506        let generation =
7507            crate::cache_freshness::artifact_generation(&artifact).expect("artifact generation");
7508        crate::cache_freshness::record_verify_completed(
7509            &canonical_root,
7510            crate::cache_freshness::VerifyArtifact::Search,
7511            Some(generation),
7512        );
7513        assert_eq!(
7514            crate::cache_freshness::warm_verify_plan(
7515                &canonical_root,
7516                crate::cache_freshness::VerifyArtifact::Search,
7517                Some(generation),
7518            ),
7519            crate::cache_freshness::WarmVerifyPlan::Skip
7520        );
7521
7522        ctx.invalidate_artifacts_after_watcher_gap();
7523
7524        assert!(ctx
7525            .search_index
7526            .read()
7527            .unwrap_or_else(std::sync::PoisonError::into_inner)
7528            .is_none());
7529        assert!(ctx
7530            .semantic_index
7531            .read()
7532            .unwrap_or_else(std::sync::PoisonError::into_inner)
7533            .is_none());
7534        assert!(ctx.pending_callgraph_store_force_token().is_some());
7535        assert_eq!(
7536            crate::cache_freshness::warm_verify_plan(
7537                &canonical_root,
7538                crate::cache_freshness::VerifyArtifact::Search,
7539                Some(generation),
7540            ),
7541            crate::cache_freshness::WarmVerifyPlan::Strict
7542        );
7543    }
7544
7545    #[test]
7546    fn cancelled_semantic_refresh_transfers_refreshing_files_to_pending() {
7547        let root = TempDir::new().expect("project tempdir");
7548        let ctx = AppContext::new(
7549            Box::new(TreeSitterProvider::new()),
7550            Config {
7551                project_root: Some(root.path().to_path_buf()),
7552                semantic_search: true,
7553                ..Config::default()
7554            },
7555        );
7556        *ctx.semantic_index
7557            .write()
7558            .unwrap_or_else(std::sync::PoisonError::into_inner) =
7559            Some(SemanticIndex::new(root.path().to_path_buf(), 3));
7560        let refreshing_path = root.path().join("src/lib.rs");
7561        {
7562            let mut status = ctx
7563                .semantic_index_status
7564                .write()
7565                .unwrap_or_else(std::sync::PoisonError::into_inner);
7566            *status = SemanticIndexStatus::ready();
7567            status.start_refreshing_file(refreshing_path.clone());
7568        }
7569        let (request_tx, _request_rx) = crossbeam_channel::unbounded();
7570        let (_event_tx, event_rx) = crossbeam_channel::unbounded();
7571        ctx.install_semantic_refresh_worker_for_build_epoch(
7572            request_tx,
7573            event_rx,
7574            Arc::new(Mutex::new(None)),
7575            ctx.semantic_index_rx_epoch(),
7576        );
7577
7578        ctx.cancel_unbound_artifact_work();
7579
7580        // The cancelled worker will never re-embed the in-flight file; the
7581        // retained pending set is the only record for the replacement worker.
7582        assert_eq!(
7583            ctx.pending_semantic_index_paths
7584                .lock()
7585                .iter()
7586                .cloned()
7587                .collect::<Vec<_>>(),
7588            vec![refreshing_path],
7589            "cancelled in-flight refresh files must transfer to the pending set"
7590        );
7591        assert!(matches!(
7592            &*ctx
7593                .semantic_index_status
7594                .read()
7595                .unwrap_or_else(std::sync::PoisonError::into_inner),
7596            SemanticIndexStatus::Ready { refreshing, .. } if refreshing.is_empty()
7597        ));
7598    }
7599
7600    #[test]
7601    fn unbind_before_corpus_started_preserves_corpus_intent() {
7602        // The probe stamps `refreshing_corpus` before sending, but the worker
7603        // emits CorpusStarted only after walking the project. An unbind in
7604        // that window must re-derive the corpus intent from the stamped
7605        // status, not lose it.
7606        let root = TempDir::new().expect("project tempdir");
7607        let ctx = AppContext::new(
7608            Box::new(TreeSitterProvider::new()),
7609            Config {
7610                project_root: Some(root.path().to_path_buf()),
7611                semantic_search: true,
7612                ..Config::default()
7613            },
7614        );
7615        *ctx.semantic_index
7616            .write()
7617            .unwrap_or_else(std::sync::PoisonError::into_inner) =
7618            Some(SemanticIndex::new(root.path().to_path_buf(), 3));
7619        *ctx.semantic_index_status
7620            .write()
7621            .unwrap_or_else(std::sync::PoisonError::into_inner) = SemanticIndexStatus::Building {
7622            stage: "refreshing_corpus".to_string(),
7623            files: None,
7624            entries_done: None,
7625            entries_total: None,
7626        };
7627        let (request_tx, _request_rx) = crossbeam_channel::unbounded();
7628        let (_event_tx, event_rx) = crossbeam_channel::unbounded();
7629        ctx.install_semantic_refresh_worker_for_build_epoch(
7630            request_tx,
7631            event_rx,
7632            Arc::new(Mutex::new(None)),
7633            ctx.semantic_index_rx_epoch(),
7634        );
7635
7636        ctx.cancel_unbound_artifact_work();
7637
7638        assert!(
7639            *ctx.pending_semantic_corpus_refresh.lock(),
7640            "corpus intent stamped before CorpusStarted must survive the cancellation"
7641        );
7642    }
7643
7644    #[test]
7645    fn cancelled_search_corpus_refresh_drops_nonready_resident_index() {
7646        let root = TempDir::new().expect("project tempdir");
7647        let ctx = AppContext::new(
7648            Box::new(TreeSitterProvider::new()),
7649            Config {
7650                project_root: Some(root.path().to_path_buf()),
7651                ..Config::default()
7652            },
7653        );
7654        // A corpus refresh in flight: resident index marked non-ready plus an
7655        // installed receiver. Cancelling only the receiver would strand the
7656        // non-ready resident (equivalent rebind reloads only a MISSING index).
7657        let mut refreshing = SearchIndex::new();
7658        refreshing.ready = false;
7659        *ctx.search_index
7660            .write()
7661            .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(refreshing);
7662        let (_tx, rx) = crossbeam_channel::unbounded();
7663        ctx.install_search_index_rx(rx, ctx.configure_generation());
7664
7665        ctx.cancel_unbound_artifact_work();
7666
7667        assert!(
7668            ctx.search_index
7669                .read()
7670                .unwrap_or_else(std::sync::PoisonError::into_inner)
7671                .is_none(),
7672            "a cancelled corpus refresh must drop the non-ready resident so rebind reloads it"
7673        );
7674        assert!(ctx
7675            .search_index_rx
7676            .read()
7677            .unwrap_or_else(std::sync::PoisonError::into_inner)
7678            .is_none());
7679    }
7680
7681    #[test]
7682    fn active_semantic_file_refresh_blocks_idle_eviction_until_completion() {
7683        let root = TempDir::new().expect("project tempdir");
7684        let ctx = AppContext::new(
7685            Box::new(TreeSitterProvider::new()),
7686            Config {
7687                project_root: Some(root.path().to_path_buf()),
7688                ..Config::default()
7689            },
7690        );
7691        *ctx.semantic_index
7692            .write()
7693            .unwrap_or_else(std::sync::PoisonError::into_inner) =
7694            Some(SemanticIndex::new(root.path().to_path_buf(), 3));
7695        let refreshing_path = root.path().join("src/lib.rs");
7696        {
7697            let mut status = ctx
7698                .semantic_index_status
7699                .write()
7700                .unwrap_or_else(std::sync::PoisonError::into_inner);
7701            *status = SemanticIndexStatus::ready();
7702            status.start_refreshing_file(refreshing_path.clone());
7703        }
7704
7705        assert!(ctx.artifact_eviction_blocked());
7706        assert!(!ctx.evict_idle_artifacts());
7707        assert!(ctx
7708            .semantic_index
7709            .read()
7710            .unwrap_or_else(std::sync::PoisonError::into_inner)
7711            .is_some());
7712
7713        ctx.semantic_index_status
7714            .write()
7715            .unwrap_or_else(std::sync::PoisonError::into_inner)
7716            .complete_refreshing_file(&refreshing_path);
7717        assert!(ctx.evict_idle_artifacts());
7718        assert!(ctx
7719            .semantic_index
7720            .read()
7721            .unwrap_or_else(std::sync::PoisonError::into_inner)
7722            .is_none());
7723    }
7724}
7725
7726#[cfg(test)]
7727mod status_emitter_tests {
7728    use super::*;
7729    use crate::parser::TreeSitterProvider;
7730
7731    fn ctx_with_frame_rx() -> (AppContext, mpsc::Receiver<PushFrame>) {
7732        let ctx = AppContext::new(Box::new(TreeSitterProvider::new()), Config::default());
7733        let (tx, rx) = mpsc::channel();
7734        ctx.set_progress_sender(Some(Arc::new(Box::new(move |frame| {
7735            let _ = tx.send(frame);
7736        }))));
7737        (ctx, rx)
7738    }
7739
7740    #[test]
7741    fn status_emitter_signal_triggers_push() {
7742        let (ctx, rx) = ctx_with_frame_rx();
7743        ctx.status_emitter().signal(ctx.build_status_snapshot());
7744        let frame = rx
7745            .recv_timeout(Duration::from_millis(STATUS_DEBOUNCE_MS + 500))
7746            .expect("status_changed push");
7747        assert!(matches!(frame, PushFrame::StatusChanged(_)));
7748    }
7749
7750    #[test]
7751    fn status_emitter_debounces_burst() {
7752        let (ctx, rx) = ctx_with_frame_rx();
7753        for _ in 0..10 {
7754            ctx.status_emitter().signal(ctx.build_status_snapshot());
7755        }
7756        let frame = rx
7757            .recv_timeout(Duration::from_millis(STATUS_DEBOUNCE_MS + 500))
7758            .expect("status_changed push");
7759        assert!(matches!(frame, PushFrame::StatusChanged(_)));
7760        assert!(rx.try_recv().is_err());
7761    }
7762
7763    #[test]
7764    fn status_emitter_separate_windows_separate_pushes() {
7765        let (ctx, rx) = ctx_with_frame_rx();
7766        ctx.status_emitter().signal(ctx.build_status_snapshot());
7767        rx.recv_timeout(Duration::from_millis(STATUS_DEBOUNCE_MS + 500))
7768            .expect("first push");
7769        ctx.status_emitter().signal(ctx.build_status_snapshot());
7770        rx.recv_timeout(Duration::from_millis(STATUS_DEBOUNCE_MS + 500))
7771            .expect("second push");
7772    }
7773
7774    #[test]
7775    fn status_emitter_no_signal_no_push() {
7776        let (_ctx, rx) = ctx_with_frame_rx();
7777        assert!(rx
7778            .recv_timeout(Duration::from_millis(STATUS_DEBOUNCE_MS + 100))
7779            .is_err());
7780    }
7781
7782    #[test]
7783    fn status_emitter_shutdown_cleanly_exits_debounce_thread() {
7784        let (ctx, rx) = ctx_with_frame_rx();
7785        drop(ctx);
7786        assert!(rx.recv_timeout(Duration::from_millis(50)).is_err());
7787    }
7788
7789    #[test]
7790    fn progress_sender_slot_is_per_context_for_shared_app() {
7791        let app = App::default_shared();
7792        let ctx_a = AppContext::from_app(Arc::clone(&app), Config::default());
7793        let ctx_b = AppContext::from_app(app, Config::default());
7794        let (tx_a, rx_a) = mpsc::channel();
7795        let (tx_b, rx_b) = mpsc::channel();
7796
7797        ctx_a.set_progress_sender(Some(Arc::new(Box::new(move |frame| {
7798            let _ = tx_a.send(frame);
7799        }))));
7800        ctx_b.set_progress_sender(Some(Arc::new(Box::new(move |frame| {
7801            let _ = tx_b.send(frame);
7802        }))));
7803
7804        ctx_a.emit_progress(ProgressFrame {
7805            frame_type: "progress",
7806            request_id: "ctx-a".to_string(),
7807            kind: crate::protocol::ProgressKind::Stdout,
7808            chunk: "a".to_string(),
7809        });
7810        ctx_b.emit_progress(ProgressFrame {
7811            frame_type: "progress",
7812            request_id: "ctx-b".to_string(),
7813            kind: crate::protocol::ProgressKind::Stdout,
7814            chunk: "b".to_string(),
7815        });
7816
7817        match rx_a
7818            .recv_timeout(Duration::from_millis(50))
7819            .expect("ctx A progress frame")
7820        {
7821            PushFrame::Progress(frame) => assert_eq!(frame.request_id, "ctx-a"),
7822            other => panic!("unexpected frame for ctx A: {other:?}"),
7823        }
7824        assert!(rx_a.try_recv().is_err());
7825
7826        match rx_b
7827            .recv_timeout(Duration::from_millis(50))
7828            .expect("ctx B progress frame")
7829        {
7830            PushFrame::Progress(frame) => assert_eq!(frame.request_id, "ctx-b"),
7831            other => panic!("unexpected frame for ctx B: {other:?}"),
7832        }
7833        assert!(rx_b.try_recv().is_err());
7834    }
7835}
7836
7837#[cfg(test)]
7838mod health_warming_honesty_tests {
7839    use super::*;
7840    use crate::parser::TreeSitterProvider;
7841
7842    fn ctx_with_config(config: Config) -> AppContext {
7843        AppContext::new(Box::new(TreeSitterProvider::new()), config)
7844    }
7845
7846    fn health_search_status(ctx: &AppContext) -> &'static str {
7847        let root = std::path::Path::new("/tmp/health-warming-honesty-test");
7848        ctx.try_health_snapshot(root)
7849            .search_index
7850            .expect("search_index component present")
7851            .status
7852    }
7853
7854    fn health_tier2_status(ctx: &AppContext) -> &'static str {
7855        let root = std::path::Path::new("/tmp/health-warming-honesty-test");
7856        ctx.try_health_snapshot(root)
7857            .tier2
7858            .expect("tier2 component present")
7859            .status
7860    }
7861
7862    #[test]
7863    fn write_denied_search_index_reports_ready_not_building() {
7864        // A write-denied cold build installs an empty index that is flagged
7865        // build-denied and stays not-ready (so grep keeps the fallback walk).
7866        // Health must treat it as settled, not "building" forever.
7867        let config = Config {
7868            search_index: true,
7869            ..Config::default()
7870        };
7871        let ctx = ctx_with_config(config);
7872        let mut index = SearchIndex::new();
7873        index.build_denied = true;
7874        *ctx.search_index()
7875            .write()
7876            .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(index);
7877
7878        assert_eq!(
7879            health_search_status(&ctx),
7880            "ready",
7881            "a build-denied index is a terminal settled state and must not report building forever"
7882        );
7883    }
7884
7885    #[test]
7886    fn in_progress_search_index_still_reports_building() {
7887        // Control: a genuinely not-ready, not-denied index (a real build in
7888        // flight) must still report building — the build-denied carve-out must
7889        // not leak into ordinary in-progress builds.
7890        let config = Config {
7891            search_index: true,
7892            ..Config::default()
7893        };
7894        let ctx = ctx_with_config(config);
7895        let index = SearchIndex::new(); // ready=false, build_denied=false
7896        *ctx.search_index()
7897            .write()
7898            .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(index);
7899
7900        assert_eq!(health_search_status(&ctx), "building");
7901    }
7902
7903    #[test]
7904    fn tier2_blocked_on_callgraph_reports_ready_not_building() {
7905        // dead_code is suppressed (None) while the callgraph store is not ready,
7906        // but unused_exports/duplicates are complete and fresh. Health must not
7907        // report tier2 as "building" forever for a cycle that is otherwise
7908        // complete — the callgraph component tells the callgraph story.
7909        let ctx = ctx_with_config(Config::default()); // inspect.enabled defaults true
7910        ctx.update_status_bar_tier2(None, Some(3), Some(2), None, false);
7911        ctx.set_status_bar_tier2_dead_code_blocked_on_callgraph(true);
7912
7913        assert_eq!(
7914            health_tier2_status(&ctx),
7915            "ready",
7916            "tier2 complete except dead_code-blocked-on-callgraph must not stay building"
7917        );
7918    }
7919
7920    #[test]
7921    fn tier2_missing_dead_code_without_callgraph_block_reports_building() {
7922        // Control: with no callgraph block recorded, a missing dead_code count is
7923        // a genuine in-progress scan and must still report building.
7924        let ctx = ctx_with_config(Config::default());
7925        ctx.update_status_bar_tier2(None, Some(3), Some(2), None, false);
7926        ctx.set_status_bar_tier2_dead_code_blocked_on_callgraph(false);
7927
7928        assert_eq!(health_tier2_status(&ctx), "building");
7929    }
7930}
7931
7932#[cfg(test)]
7933mod status_bar_tests {
7934    use super::*;
7935    use crate::parser::TreeSitterProvider;
7936
7937    fn ctx() -> AppContext {
7938        AppContext::new(Box::new(TreeSitterProvider::new()), Config::default())
7939    }
7940
7941    #[test]
7942    fn status_bar_counts_none_until_tier2_populated() {
7943        let ctx = ctx();
7944        // No scan has run yet — never surface a bar claiming "0 dead code".
7945        assert!(ctx.status_bar_counts().is_none());
7946
7947        ctx.update_status_bar_tier2(Some(5), Some(3), Some(7), Some(2), false);
7948        let counts = ctx.status_bar_counts().expect("populated");
7949        assert_eq!(counts.dead_code, 5);
7950        assert_eq!(counts.unused_exports, 3);
7951        assert_eq!(counts.duplicates, 7);
7952        assert_eq!(counts.todos, 2);
7953        assert!(!counts.tier2_stale);
7954        // Errors/warnings are read live from an empty LSP store → 0.
7955        assert_eq!(counts.errors, 0);
7956        assert_eq!(counts.warnings, 0);
7957    }
7958
7959    #[test]
7960    fn changing_root_clears_project_scoped_status_counts() {
7961        let temp = tempfile::tempdir().expect("tempdir");
7962        let first_root = temp.path().join("first");
7963        let second_root = temp.path().join("second");
7964        std::fs::create_dir_all(&first_root).expect("create first root");
7965        std::fs::create_dir_all(&second_root).expect("create second root");
7966        let ctx = ctx();
7967        ctx.set_canonical_cache_root(first_root);
7968        ctx.update_status_bar_tier2(Some(5), Some(3), Some(7), Some(2), false);
7969        assert!(ctx.status_bar_counts().is_some());
7970
7971        ctx.set_canonical_cache_root(second_root);
7972
7973        assert!(
7974            ctx.status_bar_counts().is_none(),
7975            "counts from the previous root must not appear in a newly bound root"
7976        );
7977    }
7978
7979    #[test]
7980    fn partial_tier2_does_not_fabricate_zeros() {
7981        let ctx = ctx();
7982        // Only dead_code has completed (the slow first serial category); the
7983        // other two are still in flight. The bar must stay suppressed rather
7984        // than render `D5 U0 C0` with fabricated zeros (#1).
7985        ctx.update_status_bar_tier2(Some(5), None, None, None, true);
7986        assert!(
7987            ctx.status_bar_counts().is_none(),
7988            "bar must not surface until all three Tier-2 categories are real"
7989        );
7990
7991        // Second category completes — still incomplete, still suppressed.
7992        ctx.update_status_bar_tier2(None, Some(3), None, None, true);
7993        assert!(ctx.status_bar_counts().is_none());
7994
7995        // Final category completes → bar surfaces with all real counts, and
7996        // none of them were ever fabricated.
7997        ctx.update_status_bar_tier2(None, None, Some(7), None, false);
7998        let counts = ctx.status_bar_counts().expect("all three real now");
7999        assert_eq!(counts.dead_code, 5);
8000        assert_eq!(counts.unused_exports, 3);
8001        assert_eq!(counts.duplicates, 7);
8002    }
8003
8004    #[test]
8005    fn update_with_none_todos_preserves_last_known_todos() {
8006        let ctx = ctx();
8007        ctx.update_status_bar_tier2(Some(1), Some(1), Some(1), Some(9), false);
8008        // A background-scan refresh passes todos=None → todo count preserved.
8009        ctx.update_status_bar_tier2(Some(2), Some(2), Some(2), None, false);
8010        let counts = ctx.status_bar_counts().expect("populated");
8011        assert_eq!(counts.todos, 9);
8012        assert_eq!(counts.dead_code, 2);
8013    }
8014
8015    #[test]
8016    fn update_with_none_count_preserves_last_known_count() {
8017        let ctx = ctx();
8018        ctx.update_status_bar_tier2(Some(10), Some(20), Some(30), None, false);
8019        // A refresh that only recomputed dead_code preserves the other two
8020        // real counts rather than overwriting them with a fabricated 0.
8021        ctx.update_status_bar_tier2(Some(11), None, None, None, false);
8022        let counts = ctx.status_bar_counts().expect("populated");
8023        assert_eq!(counts.dead_code, 11);
8024        assert_eq!(counts.unused_exports, 20);
8025        assert_eq!(counts.duplicates, 30);
8026    }
8027
8028    #[test]
8029    fn mark_stale_sets_flag_only_after_populate() {
8030        let ctx = ctx();
8031        // No-op before first populate.
8032        ctx.mark_status_bar_tier2_stale();
8033        assert!(ctx.status_bar_counts().is_none());
8034
8035        ctx.update_status_bar_tier2(Some(4), Some(0), Some(0), Some(0), false);
8036        ctx.mark_status_bar_tier2_stale();
8037        assert!(ctx.status_bar_counts().expect("populated").tier2_stale);
8038
8039        // A completed scan clears stale.
8040        ctx.update_status_bar_tier2(Some(4), Some(0), Some(0), None, false);
8041        assert!(!ctx.status_bar_counts().expect("populated").tier2_stale);
8042    }
8043
8044    // End-to-end wiring: a diagnostic for a file inflates the status-bar `E`
8045    // count (read live from the warm LSP set); clearing that file's diagnostics
8046    // (the deleted-file path) drops it back. This is the AppContext glue between
8047    // the watcher-drain clear and the agent-visible bar.
8048    #[test]
8049    fn clearing_diagnostics_for_deleted_file_drops_status_bar_errors() {
8050        use crate::lsp::diagnostics::{DiagnosticSeverity, StoredDiagnostic};
8051        use crate::lsp::registry::ServerKind;
8052        use crate::lsp::roots::ServerKey;
8053
8054        let ctx = ctx();
8055        ctx.update_status_bar_tier2(Some(0), Some(0), Some(0), Some(0), false); // populate so the bar surfaces
8056
8057        let file = std::path::PathBuf::from("/proj/gone.ts");
8058        {
8059            let mut lsp = ctx.lsp();
8060            lsp.diagnostics_store_mut_for_test().publish(
8061                ServerKey {
8062                    kind: ServerKind::TypeScript,
8063                    root: std::path::PathBuf::from("/proj"),
8064                },
8065                file.clone(),
8066                vec![StoredDiagnostic {
8067                    file: file.clone(),
8068                    line: 1,
8069                    column: 1,
8070                    end_line: 1,
8071                    end_column: 2,
8072                    severity: DiagnosticSeverity::Error,
8073                    message: "boom".into(),
8074                    code: None,
8075                    source: None,
8076                }],
8077            );
8078        }
8079
8080        // Bar reflects the live warm-set error.
8081        assert_eq!(ctx.status_bar_counts().expect("populated").errors, 1);
8082
8083        // Clearing the (now-deleted) file's diagnostics drops the count.
8084        let removed = ctx.lsp_clear_diagnostics_for_file(&file);
8085        assert!(removed);
8086        assert_eq!(ctx.status_bar_counts().expect("populated").errors, 0);
8087    }
8088
8089    #[test]
8090    fn status_bar_preserves_authoritative_counts_during_provisional_publish() {
8091        use crate::lsp::diagnostics::{DiagnosticSeverity, StoredDiagnostic};
8092        use crate::lsp::registry::ServerKind;
8093        use crate::lsp::roots::ServerKey;
8094
8095        let ctx = ctx();
8096        ctx.update_status_bar_tier2(Some(0), Some(0), Some(0), Some(0), false);
8097        let root = std::path::PathBuf::from("/proj");
8098        let file = root.join("src/main.rs");
8099        let key = ServerKey {
8100            kind: ServerKind::Rust,
8101            root,
8102        };
8103        let diagnostic = || StoredDiagnostic {
8104            file: file.clone(),
8105            line: 1,
8106            column: 1,
8107            end_line: 1,
8108            end_column: 2,
8109            severity: DiagnosticSeverity::Error,
8110            message: "analyzer result".into(),
8111            code: None,
8112            source: None,
8113        };
8114
8115        {
8116            let mut lsp = ctx.lsp();
8117            lsp.diagnostics_store_mut_for_test().publish(
8118                key.clone(),
8119                file.clone(),
8120                vec![diagnostic()],
8121            );
8122        }
8123        assert_eq!(ctx.status_bar_counts().expect("populated").errors, 1);
8124
8125        {
8126            let mut lsp = ctx.lsp();
8127            lsp.diagnostics_store_mut_for_test()
8128                .publish_full_with_provisional(
8129                    key.clone(),
8130                    file.clone(),
8131                    vec![diagnostic()],
8132                    None,
8133                    None,
8134                    true,
8135                );
8136        }
8137        assert_eq!(
8138            ctx.status_bar_counts().expect("populated").errors,
8139            1,
8140            "warming diagnostics must not replace the last authoritative E count"
8141        );
8142
8143        {
8144            let mut lsp = ctx.lsp();
8145            assert!(lsp
8146                .diagnostics_store_mut_for_test()
8147                .mark_provisional_for_server_stale(&key));
8148        }
8149        assert_eq!(
8150            ctx.status_bar_counts().expect("populated").errors,
8151            1,
8152            "invalidating warming entries must retain the last authoritative E count"
8153        );
8154
8155        {
8156            let mut lsp = ctx.lsp();
8157            lsp.diagnostics_store_mut_for_test()
8158                .publish(key, file.clone(), vec![diagnostic()]);
8159        }
8160        assert_eq!(ctx.status_bar_counts().expect("populated").errors, 1);
8161    }
8162
8163    #[test]
8164    fn status_bar_filtered_counts_ignore_environmental_flap() {
8165        use crate::lsp::diagnostics::{DiagnosticSeverity, StoredDiagnostic};
8166        use crate::lsp::registry::ServerKind;
8167        use crate::lsp::roots::ServerKey;
8168
8169        let ctx = ctx();
8170        let root = if cfg!(windows) {
8171            std::path::PathBuf::from(r"C:\proj")
8172        } else {
8173            std::path::PathBuf::from("/proj")
8174        };
8175        ctx.set_canonical_cache_root(root.clone());
8176        ctx.update_status_bar_tier2(Some(0), Some(0), Some(0), Some(0), false);
8177
8178        let file = root.join("aft.jsonc");
8179        let key = ServerKey {
8180            kind: ServerKind::TypeScript,
8181            root: root.clone(),
8182        };
8183        let env = StoredDiagnostic {
8184            file: file.clone(),
8185            line: 1,
8186            column: 1,
8187            end_line: 1,
8188            end_column: 2,
8189            severity: DiagnosticSeverity::Error,
8190            message: "Failed to load schema from https://example.com/schema.json".into(),
8191            code: None,
8192            source: Some("json".into()),
8193        };
8194
8195        assert_eq!(ctx.status_bar_counts().expect("populated").errors, 0);
8196
8197        {
8198            let mut lsp = ctx.lsp();
8199            lsp.diagnostics_store_mut_for_test()
8200                .publish(key.clone(), file.clone(), vec![env]);
8201        }
8202        assert_eq!(
8203            ctx.status_bar_counts().expect("populated").errors,
8204            0,
8205            "environmental publish must not change status-bar E"
8206        );
8207
8208        {
8209            let mut lsp = ctx.lsp();
8210            lsp.diagnostics_store_mut_for_test()
8211                .publish(key, file, vec![]);
8212        }
8213        assert_eq!(
8214            ctx.status_bar_counts().expect("populated").errors,
8215            0,
8216            "environmental clear must not change status-bar E"
8217        );
8218    }
8219}
8220
8221#[cfg(test)]
8222mod harness_path_tests {
8223    use super::*;
8224    use crate::harness::Harness;
8225    use crate::parser::TreeSitterProvider;
8226
8227    fn ctx_with_storage_and_harness(storage_dir: PathBuf, harness: Harness) -> AppContext {
8228        let ctx = AppContext::new(Box::new(TreeSitterProvider::new()), Config::default());
8229        ctx.update_config(|config| {
8230            config.storage_dir = Some(storage_dir);
8231        });
8232        ctx.set_harness(harness);
8233        ctx
8234    }
8235
8236    #[test]
8237    fn harness_dir_resolves_correctly() {
8238        let storage = PathBuf::from("/tmp/cortexkit/aft");
8239        let ctx = ctx_with_storage_and_harness(storage.clone(), Harness::Pi);
8240
8241        assert_eq!(ctx.harness_dir(), storage.join("pi"));
8242    }
8243
8244    #[test]
8245    fn bash_tasks_dir_uses_hash_session() {
8246        let storage = PathBuf::from("/tmp/cortexkit/aft");
8247        let ctx = ctx_with_storage_and_harness(storage.clone(), Harness::Opencode);
8248
8249        assert_eq!(
8250            ctx.bash_tasks_dir("ses_abc"),
8251            storage
8252                .join("opencode")
8253                .join("bash-tasks")
8254                .join(hash_session("ses_abc"))
8255        );
8256    }
8257
8258    #[test]
8259    fn backups_dir_includes_path_hash() {
8260        let storage = PathBuf::from("/tmp/cortexkit/aft");
8261        let ctx = ctx_with_storage_and_harness(storage.clone(), Harness::Pi);
8262
8263        assert_eq!(
8264            ctx.backups_dir("ses_abc", "pathhash"),
8265            storage
8266                .join("pi")
8267                .join("backups")
8268                .join(hash_session("ses_abc"))
8269                .join("pathhash")
8270        );
8271    }
8272
8273    #[test]
8274    fn filters_dir_under_harness() {
8275        let storage = PathBuf::from("/tmp/cortexkit/aft");
8276        let ctx = ctx_with_storage_and_harness(storage.clone(), Harness::Opencode);
8277
8278        assert_eq!(ctx.filters_dir(), storage.join("opencode").join("filters"));
8279    }
8280
8281    #[test]
8282    fn trust_file_is_host_global() {
8283        let storage = PathBuf::from("/tmp/cortexkit/aft");
8284        let ctx = ctx_with_storage_and_harness(storage.clone(), Harness::Pi);
8285
8286        assert_eq!(
8287            ctx.trust_file(),
8288            storage.join("trusted-filter-projects.json")
8289        );
8290    }
8291
8292    #[test]
8293    fn same_session_different_harness_resolve_different_paths() {
8294        let storage = PathBuf::from("/tmp/cortexkit/aft");
8295        let opencode = ctx_with_storage_and_harness(storage.clone(), Harness::Opencode);
8296        let pi = ctx_with_storage_and_harness(storage, Harness::Pi);
8297
8298        assert_ne!(
8299            opencode.bash_tasks_dir("ses_same"),
8300            pi.bash_tasks_dir("ses_same")
8301        );
8302    }
8303
8304    #[test]
8305    fn callgraph_and_inspect_dirs_are_root_keyed() {
8306        let temp = tempfile::tempdir().expect("tempdir");
8307        let storage = temp.path().join("storage");
8308        let root = temp.path().join("checkout");
8309        std::fs::create_dir_all(&root).expect("create root");
8310        let ctx = ctx_with_storage_and_harness(storage.clone(), Harness::Opencode);
8311        ctx.set_canonical_cache_root(root.clone());
8312
8313        assert_eq!(
8314            ctx.callgraph_store_dir(),
8315            storage
8316                .join("callgraph")
8317                .join(crate::search_index::artifact_cache_key(&root))
8318        );
8319        assert_eq!(
8320            ctx.inspect_dir(),
8321            storage
8322                .join("inspect")
8323                .join(crate::path_identity::project_scope_key(&root))
8324        );
8325        assert!(!ctx
8326            .callgraph_store_dir()
8327            .starts_with(storage.join("opencode")));
8328        assert!(!ctx.inspect_dir().starts_with(storage.join("opencode")));
8329    }
8330
8331    #[test]
8332    fn per_domain_capability_allows_inspect_writer_when_callgraph_read_only() {
8333        let storage = PathBuf::from("/tmp/cortexkit/aft");
8334        let ctx = ctx_with_storage_and_harness(storage, Harness::Opencode);
8335        ctx.set_cache_writer_capabilities(false, true);
8336
8337        assert!(ctx.shared_artifacts_read_only());
8338        assert!(!ctx.callgraph_writer());
8339        assert!(ctx.inspect_writer());
8340    }
8341}
8342
8343#[cfg(test)]
8344mod shared_db_tests {
8345    use super::*;
8346    use tempfile::tempdir;
8347
8348    #[test]
8349    fn app_contexts_share_one_database_connection() {
8350        let storage = tempdir().expect("storage tempdir");
8351        let root_one = tempdir().expect("first root tempdir");
8352        let root_two = tempdir().expect("second root tempdir");
8353        let app = App::default_shared();
8354        let ctx_one = AppContext::from_app(
8355            Arc::clone(&app),
8356            Config {
8357                project_root: Some(root_one.path().to_path_buf()),
8358                ..Config::default()
8359            },
8360        );
8361        let ctx_two = AppContext::from_app(
8362            Arc::clone(&app),
8363            Config {
8364                project_root: Some(root_two.path().to_path_buf()),
8365                ..Config::default()
8366            },
8367        );
8368        let path = storage.path().join("aft.db");
8369
8370        let first = app.open_db(&path).expect("open shared database");
8371        let second = app.open_db(&path).expect("reuse shared database");
8372
8373        assert!(Arc::ptr_eq(&first, &second));
8374        assert!(Arc::ptr_eq(
8375            &ctx_one.db().expect("first context database"),
8376            &ctx_two.db().expect("second context database")
8377        ));
8378    }
8379}
8380
8381#[cfg(test)]
8382mod gitignore_tests {
8383    use super::*;
8384    use std::fs;
8385    use std::path::Path;
8386    use tempfile::TempDir;
8387
8388    fn make_ctx_with_root(root: &Path) -> AppContext {
8389        let provider = Box::new(crate::parser::TreeSitterProvider::new());
8390        let config = Config {
8391            project_root: Some(root.to_path_buf()),
8392            ..Config::default()
8393        };
8394        AppContext::new(provider, config)
8395    }
8396
8397    /// Helper: returns true when the matcher would skip `path` (as if it
8398    /// arrived via a watcher event for this project root). Canonicalizes
8399    /// the query path so symlink prefixes (e.g. macOS `/var` → `/private/var`)
8400    /// don't trip the `ignore` crate's "path is expected to be under the
8401    /// root" panic — production code does the same guard via
8402    /// `path.starts_with(matcher.path())` in `drain_watcher_events`.
8403    fn is_ignored(ctx: &AppContext, path: &Path) -> bool {
8404        let Some(matcher) = ctx.gitignore() else {
8405            return false;
8406        };
8407        let canonical = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
8408        if !canonical.starts_with(matcher.path()) {
8409            return false;
8410        }
8411        let is_dir = canonical.is_dir();
8412        matcher
8413            .matched_path_or_any_parents(&canonical, is_dir)
8414            .is_ignore()
8415    }
8416
8417    /// Run `f` with global git-ignore discovery neutralized.
8418    ///
8419    /// `rebuild_gitignore` loads git's global excludes via the `ignore`
8420    /// crate, which discovers them from TWO places: `core.excludesfile` in
8421    /// `$HOME/.gitconfig` (or `$XDG_CONFIG_HOME/git/config`), and the default
8422    /// `$XDG_CONFIG_HOME/git/ignore` / `$HOME/.config/git/ignore` locations.
8423    /// A developer machine commonly has one of these, so a "no project ignore
8424    /// → None" assertion is only deterministic when BOTH discovery roots point
8425    /// at an empty directory — neutralizing only `XDG_CONFIG_HOME` still finds
8426    /// a `~/.gitconfig` `core.excludesfile`. Serialized on the process-wide
8427    /// env lock shared with every other HOME-mutating test; env is restored
8428    /// before the closure result is used.
8429    fn with_neutralized_global_gitignore<R>(f: impl FnOnce() -> R) -> R {
8430        let _guard = crate::test_env::process_env_lock();
8431        let tmp = TempDir::new().unwrap();
8432        let prev_xdg = std::env::var_os("XDG_CONFIG_HOME");
8433        let prev_home = std::env::var_os("HOME");
8434        let prev_userprofile = std::env::var_os("USERPROFILE");
8435        // SAFETY: serialized by the process env lock; restored immediately
8436        // after `f`.
8437        unsafe {
8438            std::env::set_var("XDG_CONFIG_HOME", tmp.path());
8439            std::env::set_var("HOME", tmp.path());
8440            std::env::set_var("USERPROFILE", tmp.path());
8441        }
8442        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f));
8443        unsafe {
8444            match prev_xdg {
8445                Some(v) => std::env::set_var("XDG_CONFIG_HOME", v),
8446                None => std::env::remove_var("XDG_CONFIG_HOME"),
8447            }
8448            match prev_home {
8449                Some(v) => std::env::set_var("HOME", v),
8450                None => std::env::remove_var("HOME"),
8451            }
8452            match prev_userprofile {
8453                Some(v) => std::env::set_var("USERPROFILE", v),
8454                None => std::env::remove_var("USERPROFILE"),
8455            }
8456        }
8457        match result {
8458            Ok(r) => r,
8459            Err(p) => std::panic::resume_unwind(p),
8460        }
8461    }
8462
8463    #[test]
8464    fn rebuild_gitignore_returns_none_without_project_root() {
8465        let provider = Box::new(crate::parser::TreeSitterProvider::new());
8466        let ctx = AppContext::new(provider, Config::default());
8467        with_neutralized_global_gitignore(|| ctx.rebuild_gitignore());
8468        assert!(ctx.gitignore().is_none());
8469    }
8470
8471    #[test]
8472    fn rebuild_gitignore_returns_none_for_project_with_no_gitignore() {
8473        let tmp = TempDir::new().unwrap();
8474        let ctx = make_ctx_with_root(tmp.path());
8475        with_neutralized_global_gitignore(|| ctx.rebuild_gitignore());
8476        assert!(ctx.gitignore().is_none());
8477    }
8478
8479    #[test]
8480    fn matcher_filters_files_in_ignored_dist_dir() {
8481        let tmp = TempDir::new().unwrap();
8482        fs::write(tmp.path().join(".gitignore"), "dist/\nbuild/\n").unwrap();
8483        fs::create_dir_all(tmp.path().join("dist")).unwrap();
8484        fs::create_dir_all(tmp.path().join("src")).unwrap();
8485        let dist_file = tmp.path().join("dist").join("bundle.js");
8486        let src_file = tmp.path().join("src").join("app.ts");
8487        fs::write(&dist_file, "x").unwrap();
8488        fs::write(&src_file, "y").unwrap();
8489
8490        let ctx = make_ctx_with_root(tmp.path());
8491        ctx.rebuild_gitignore();
8492
8493        assert!(ctx.gitignore().is_some());
8494        assert!(
8495            is_ignored(&ctx, &dist_file),
8496            "dist/bundle.js should be ignored"
8497        );
8498        assert!(
8499            !is_ignored(&ctx, &src_file),
8500            "src/app.ts should NOT be ignored"
8501        );
8502    }
8503
8504    #[test]
8505    fn matcher_handles_node_modules_and_target() {
8506        let tmp = TempDir::new().unwrap();
8507        fs::write(tmp.path().join(".gitignore"), "node_modules/\ntarget/\n").unwrap();
8508        fs::create_dir_all(tmp.path().join("node_modules/foo")).unwrap();
8509        fs::create_dir_all(tmp.path().join("target/debug")).unwrap();
8510        let nm_file = tmp.path().join("node_modules/foo/index.js");
8511        let target_file = tmp.path().join("target/debug/aft");
8512        fs::write(&nm_file, "x").unwrap();
8513        fs::write(&target_file, "x").unwrap();
8514
8515        let ctx = make_ctx_with_root(tmp.path());
8516        ctx.rebuild_gitignore();
8517
8518        assert!(is_ignored(&ctx, &nm_file));
8519        assert!(is_ignored(&ctx, &target_file));
8520    }
8521
8522    #[test]
8523    fn matcher_honors_negation_pattern() {
8524        // .gitignore: ignore all *.log files EXCEPT important.log
8525        let tmp = TempDir::new().unwrap();
8526        fs::write(tmp.path().join(".gitignore"), "*.log\n!important.log\n").unwrap();
8527        let random_log = tmp.path().join("random.log");
8528        let important_log = tmp.path().join("important.log");
8529        fs::write(&random_log, "x").unwrap();
8530        fs::write(&important_log, "y").unwrap();
8531
8532        let ctx = make_ctx_with_root(tmp.path());
8533        ctx.rebuild_gitignore();
8534
8535        assert!(is_ignored(&ctx, &random_log));
8536        assert!(
8537            !is_ignored(&ctx, &important_log),
8538            "negation pattern should un-ignore important.log"
8539        );
8540    }
8541
8542    #[test]
8543    fn rebuild_picks_up_gitignore_changes() {
8544        let tmp = TempDir::new().unwrap();
8545        let ignore_path = tmp.path().join(".gitignore");
8546        fs::write(&ignore_path, "foo.txt\n").unwrap();
8547        let foo = tmp.path().join("foo.txt");
8548        let bar = tmp.path().join("bar.txt");
8549        fs::write(&foo, "").unwrap();
8550        fs::write(&bar, "").unwrap();
8551
8552        let ctx = make_ctx_with_root(tmp.path());
8553        ctx.rebuild_gitignore();
8554        assert!(is_ignored(&ctx, &foo));
8555        assert!(!is_ignored(&ctx, &bar));
8556
8557        // Now flip the rules: ignore bar.txt instead of foo.txt
8558        fs::write(&ignore_path, "bar.txt\n").unwrap();
8559        ctx.rebuild_gitignore();
8560        assert!(!is_ignored(&ctx, &foo));
8561        assert!(is_ignored(&ctx, &bar));
8562    }
8563
8564    #[test]
8565    fn gitignore_loads_info_exclude_when_present() {
8566        let tmp = TempDir::new().unwrap();
8567        let info_dir = tmp.path().join(".git/info");
8568        fs::create_dir_all(&info_dir).unwrap();
8569        fs::write(info_dir.join("exclude"), "secrets.txt\n").unwrap();
8570        let secrets = tmp.path().join("secrets.txt");
8571        let public = tmp.path().join("public.txt");
8572        fs::write(&secrets, "token").unwrap();
8573        fs::write(&public, "ok").unwrap();
8574
8575        let ctx = make_ctx_with_root(tmp.path());
8576        ctx.rebuild_gitignore();
8577
8578        assert!(is_ignored(&ctx, &secrets));
8579        assert!(!is_ignored(&ctx, &public));
8580    }
8581
8582    #[test]
8583    fn matcher_picks_up_nested_gitignore() {
8584        let tmp = TempDir::new().unwrap();
8585        // Root .gitignore is intentionally empty — only the nested one ignores
8586        fs::write(tmp.path().join(".gitignore"), "").unwrap();
8587        let sub = tmp.path().join("packages/foo");
8588        fs::create_dir_all(&sub).unwrap();
8589        fs::write(sub.join(".gitignore"), "generated/\n").unwrap();
8590        let generated_file = sub.join("generated").join("out.js");
8591        fs::create_dir_all(generated_file.parent().unwrap()).unwrap();
8592        fs::write(&generated_file, "x").unwrap();
8593
8594        let ctx = make_ctx_with_root(tmp.path());
8595        ctx.rebuild_gitignore();
8596
8597        assert!(
8598            is_ignored(&ctx, &generated_file),
8599            "nested gitignore in packages/foo/.gitignore should ignore generated/"
8600        );
8601    }
8602}
8603
8604#[cfg(test)]
8605mod verify_memo_watcher_tests {
8606    use super::*;
8607
8608    #[test]
8609    fn pending_watcher_path_invalidates_root_verify_memo() {
8610        let root_dir = tempfile::tempdir().unwrap();
8611        let root = std::fs::canonicalize(root_dir.path()).unwrap();
8612        let artifact = root.join("cache.bin");
8613        std::fs::write(&artifact, b"generation").unwrap();
8614        let generation = crate::cache_freshness::artifact_generation(&artifact).unwrap();
8615        crate::cache_freshness::record_verify_completed(
8616            &root,
8617            crate::cache_freshness::VerifyArtifact::Search,
8618            Some(generation),
8619        );
8620        assert_eq!(
8621            crate::cache_freshness::warm_verify_plan(
8622                &root,
8623                crate::cache_freshness::VerifyArtifact::Search,
8624                Some(generation),
8625            ),
8626            crate::cache_freshness::WarmVerifyPlan::Skip
8627        );
8628
8629        let ctx = AppContext::from_app(
8630            App::default_shared(),
8631            Config {
8632                project_root: Some(root.clone()),
8633                ..Config::default()
8634            },
8635        );
8636        ctx.set_canonical_cache_root(root.clone());
8637        ctx.add_pending_search_index_paths([root.join("changed.rs")]);
8638        assert_eq!(
8639            crate::cache_freshness::warm_verify_plan(
8640                &root,
8641                crate::cache_freshness::VerifyArtifact::Search,
8642                Some(generation),
8643            ),
8644            crate::cache_freshness::WarmVerifyPlan::StatFirst
8645        );
8646    }
8647}
8648
8649#[cfg(test)]
8650mod watcher_runtime_state_tests {
8651    use super::*;
8652    use crate::language::StubProvider;
8653
8654    fn test_context() -> AppContext {
8655        AppContext::new(Box::new(StubProvider), Config::default())
8656    }
8657
8658    #[test]
8659    fn finished_watcher_thread_reports_inactive_and_is_reclaimed_with_invalidation() {
8660        let root = tempfile::tempdir().expect("project tempdir");
8661        let canonical_root = std::fs::canonicalize(root.path()).expect("canonical root");
8662        let ctx = AppContext::new(
8663            Box::new(StubProvider),
8664            Config {
8665                project_root: Some(canonical_root.clone()),
8666                ..Config::default()
8667            },
8668        );
8669        ctx.set_canonical_cache_root(canonical_root.clone());
8670        // Suppress the physical FSEvents reinstall (parallel in-process tests
8671        // must not install real OS watchers); the property under test is the
8672        // corpse reclaim + invalidation, not the reinstall.
8673        struct DisableWatcherGuard;
8674        impl Drop for DisableWatcherGuard {
8675            fn drop(&mut self) {
8676                unsafe { std::env::remove_var("AFT_TEST_DISABLE_FILE_WATCHER") };
8677            }
8678        }
8679        let _env_lock = crate::test_env::process_env_lock();
8680        unsafe { std::env::set_var("AFT_TEST_DISABLE_FILE_WATCHER", "1") };
8681        let _disable_watcher = DisableWatcherGuard;
8682        // Warm state the corpse reclaim must invalidate: resident index +
8683        // warm Skip memo.
8684        *ctx.search_index
8685            .write()
8686            .unwrap_or_else(std::sync::PoisonError::into_inner) =
8687            Some(crate::search_index::SearchIndex::new());
8688        let artifact = canonical_root.join("artifact.bin");
8689        std::fs::write(&artifact, b"artifact").expect("artifact");
8690        let generation = crate::cache_freshness::artifact_generation(&artifact);
8691        crate::cache_freshness::record_verify_completed(
8692            &canonical_root,
8693            crate::cache_freshness::VerifyArtifact::Search,
8694            generation,
8695        );
8696
8697        let (dispatch_tx, dispatch_rx) = crate::watcher_filter::watcher_dispatch_channel();
8698        let _dispatch_tx = dispatch_tx;
8699        // A thread that exits on its own models a backend failure while the
8700        // root was unbound (drains suppressed, queued error undrained).
8701        let join = std::thread::spawn(|| {});
8702        ctx.install_watcher_runtime(
8703            dispatch_rx,
8704            WatcherThreadHandle::new(Arc::new(AtomicBool::new(false)), join),
8705        );
8706        let deadline = std::time::Instant::now() + Duration::from_secs(2);
8707        while ctx.watcher_runtime_active() {
8708            assert!(
8709                std::time::Instant::now() < deadline,
8710                "a finished watcher thread must report the runtime inactive"
8711            );
8712            std::thread::yield_now();
8713        }
8714
8715        // The production entry point: rebind restoration must reclaim the
8716        // corpse, invalidate the unobserved-window state, and reinstall.
8717        crate::commands::configure::ensure_project_watcher(&ctx);
8718
8719        assert!(
8720            ctx.search_index
8721                .read()
8722                .unwrap_or_else(std::sync::PoisonError::into_inner)
8723                .is_none(),
8724            "corpse reclaim must drop resident artifacts (events since the failure are lost)"
8725        );
8726        assert_eq!(
8727            crate::cache_freshness::warm_verify_plan(
8728                &canonical_root,
8729                crate::cache_freshness::VerifyArtifact::Search,
8730                generation,
8731            ),
8732            crate::cache_freshness::WarmVerifyPlan::Strict,
8733            "corpse reclaim must force strict re-verification"
8734        );
8735        assert!(
8736            !ctx.take_finished_watcher_runtime(),
8737            "reclaim is one-shot; the corpse is gone after ensure_project_watcher"
8738        );
8739    }
8740
8741    #[test]
8742    fn watcher_runtime_requires_both_thread_and_dispatch_receiver() {
8743        let ctx = test_context();
8744        let (dispatch_tx, dispatch_rx) = crate::watcher_filter::watcher_dispatch_channel();
8745        let shutdown = Arc::new(AtomicBool::new(false));
8746        let thread_shutdown = Arc::clone(&shutdown);
8747        let join = std::thread::spawn(move || {
8748            while !thread_shutdown.load(Ordering::SeqCst) {
8749                std::thread::sleep(Duration::from_millis(1));
8750            }
8751            drop(dispatch_tx);
8752        });
8753        ctx.install_watcher_runtime(
8754            dispatch_rx,
8755            WatcherThreadHandle::new(Arc::clone(&shutdown), join),
8756        );
8757        assert!(ctx.watcher_runtime_active());
8758
8759        *ctx.watcher_rx.lock() = None;
8760        assert!(
8761            !ctx.watcher_runtime_active(),
8762            "a thread without its dispatch receiver is not a usable watcher runtime"
8763        );
8764        ctx.stop_watcher_runtime();
8765    }
8766}
8767
8768#[cfg(test)]
8769mod semantic_probe_tests {
8770    use super::*;
8771
8772    #[test]
8773    fn cleared_semantic_worker_invalidates_orphaned_probe_timer() {
8774        let root = tempfile::tempdir().unwrap();
8775        let ctx = AppContext::new(
8776            default_language_provider_factory(),
8777            Config {
8778                project_root: Some(root.path().to_path_buf()),
8779                ..Config::default()
8780            },
8781        );
8782        let (request_tx, _request_rx) = crossbeam_channel::unbounded();
8783        let (_event_tx, event_rx) = crossbeam_channel::unbounded();
8784        let worker_slot = Arc::new(Mutex::new(None));
8785        ctx.install_semantic_refresh_worker_for_build_epoch(
8786            request_tx,
8787            event_rx,
8788            worker_slot,
8789            ctx.semantic_index_rx_epoch(),
8790        );
8791
8792        ctx.ensure_semantic_refresh_probe_scheduled(Duration::from_millis(20));
8793        assert!(ctx.semantic_refresh_probe_is_scheduled());
8794        ctx.clear_semantic_refresh_worker();
8795        std::thread::sleep(Duration::from_millis(50));
8796
8797        assert!(!ctx.semantic_refresh_probe_ready());
8798        assert!(!ctx.semantic_refresh_probe_is_scheduled());
8799        assert!(!ctx.completion_drains_have_work());
8800    }
8801}