Skip to main content

aft/inspect/
manager.rs

1use std::collections::{BTreeMap, BTreeSet, HashMap};
2use std::path::{Path, PathBuf};
3use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
4use std::sync::{Arc, Condvar, Mutex};
5use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
6
7use crossbeam_channel::{after, bounded, select, Receiver, Sender};
8use serde::Deserialize;
9use serde_json::{json, Value};
10
11use super::cache::{InspectCache, InspectCacheRead, InspectDbTimings, Tier2ContributionUpdates};
12use super::dispatch::{default_worker, start_dispatch_loop, InspectWorker};
13use super::freshness::{verify_contribution_file, ContributionFreshness};
14use super::job::{
15    is_test_file, CallgraphSnapshot, FileContribution, InspectCategory, InspectJob, InspectResult,
16    InspectScanSuccess, InspectSnapshot, JobKey, JobOutcome, JobScope,
17};
18use super::oxc_engine::LivenessVerdict;
19use super::oxc_engine::{
20    analyze_file_facts, analyze_files_with_cache, normalize_input_path, AnalyzeOptions,
21    DynamicImportFact, ExportFact, FileFacts, FileId, ImportFact, OxcEngineResult, OxcFactsCache,
22    ReExportFact, FACTS_FORMAT_VERSION, OXC_PROVENANCE,
23};
24use crate::cache_freshness::{self, FileFreshness, FreshnessVerdict};
25#[cfg(test)]
26use crate::callgraph_store::project_dead_code_snapshot;
27use crate::callgraph_store::{
28    project_dead_code_snapshot_with_revision, CallGraphStore, CallGraphStoreError,
29    ReadonlyCallGraphStore,
30};
31use crate::cold_build_limiter;
32
33const DEFAULT_SOFT_DEADLINE: Duration = Duration::from_secs(1);
34
35type WaiterTx = Sender<JobOutcome>;
36
37#[derive(Clone)]
38struct Waiter {
39    tx: WaiterTx,
40}
41
42struct CachedContributionFreshness {
43    file_path: PathBuf,
44    freshness: FileFreshness,
45}
46
47#[derive(Debug, Clone, PartialEq, Eq, Hash)]
48struct InspectCacheIdentity {
49    sqlite_path: PathBuf,
50    project_root: PathBuf,
51}
52
53/// A published generation names an immutable cold build; the durable revision
54/// distinguishes the cheap in-place refreshes of that generation.
55#[derive(Debug, Clone, PartialEq, Eq)]
56struct CallgraphProjectionIdentity {
57    project_root: PathBuf,
58    generation: Option<String>,
59    /// Only legacy stores lack a generation label, so their concrete database
60    /// path keeps fallback stores distinct without weakening generation checks.
61    legacy_sqlite_path: Option<PathBuf>,
62    write_revision: u64,
63}
64
65#[derive(Debug)]
66struct CachedCallgraphProjection {
67    identity: CallgraphProjectionIdentity,
68    snapshot: Arc<CallgraphSnapshot>,
69    estimated_bytes: u64,
70}
71
72#[derive(Debug, Clone)]
73pub struct Tier2RunSubmissionError {
74    pub category: InspectCategory,
75    pub message: String,
76}
77
78#[derive(Debug, Clone, Default)]
79pub struct Tier2RunSubmission {
80    pub queued_categories: Vec<InspectCategory>,
81    pub newly_queued_categories: Vec<InspectCategory>,
82    pub deferred_categories: Vec<InspectCategory>,
83    pub errors: Vec<Tier2RunSubmissionError>,
84}
85
86impl Tier2RunSubmission {
87    pub fn has_new_work(&self) -> bool {
88        !self.newly_queued_categories.is_empty()
89    }
90}
91
92#[derive(Debug, Clone)]
93struct Tier2ReuseOptions {
94    force_rescan_paths: BTreeSet<PathBuf>,
95    allow_callgraph_cold_build: bool,
96    require_callgraph_snapshot: bool,
97    interactive: bool,
98}
99
100impl Tier2ReuseOptions {
101    fn has_force_paths(&self) -> bool {
102        !self.force_rescan_paths.is_empty()
103    }
104}
105
106impl Default for Tier2ReuseOptions {
107    fn default() -> Self {
108        Self {
109            force_rescan_paths: BTreeSet::new(),
110            allow_callgraph_cold_build: true,
111            require_callgraph_snapshot: false,
112            interactive: false,
113        }
114    }
115}
116
117#[derive(Clone, Copy, Debug, Eq, PartialEq)]
118pub(crate) enum InspectBuilderState {
119    Building,
120    QueuedBehindColdBuilds,
121    GatedBySemanticSeed,
122    Suspended,
123    BuildDenied,
124    Absent,
125}
126
127impl InspectBuilderState {
128    pub(crate) const fn as_str(self) -> &'static str {
129        match self {
130            Self::Building => "building",
131            Self::QueuedBehindColdBuilds => "queued_behind_cold_builds",
132            Self::GatedBySemanticSeed => "gated_by_semantic_seed",
133            Self::Suspended => "suspended",
134            Self::BuildDenied => "build_denied (borrow-only)",
135            Self::Absent => "absent",
136        }
137    }
138}
139
140/// One admission into the inspect builder registry. Health's `tier2` field and
141/// inspect refusals both read this map so a published aggregate cannot report
142/// ready while a rebuild is still registered.
143///
144/// Failed attempts keep their history here after the in-flight state is
145/// cleared. A fast-failing rebuild that restarts on every probe would otherwise
146/// look like a brand-new warm-up (`building` at age 0) even though the same
147/// terminal keeps repeating.
148struct BuilderStateEntry {
149    state: Option<InspectBuilderState>,
150    started_at: Instant,
151    started_unix: u64,
152    first_attempt_unix: u64,
153    attempt_count: u64,
154    last_failure: Option<String>,
155    suspension: Option<crate::build_breaker::BuildSuspension>,
156}
157
158impl BuilderStateEntry {
159    fn new(state: InspectBuilderState) -> Self {
160        let now = unix_now_secs();
161        Self {
162            state: Some(state),
163            started_at: Instant::now(),
164            started_unix: now,
165            first_attempt_unix: now,
166            attempt_count: 0,
167            last_failure: None,
168            suspension: None,
169        }
170    }
171
172    fn is_in_flight(&self) -> bool {
173        self.state.is_some_and(|state| {
174            matches!(
175                state,
176                InspectBuilderState::Building
177                    | InspectBuilderState::QueuedBehindColdBuilds
178                    | InspectBuilderState::GatedBySemanticSeed
179            )
180        })
181    }
182
183    fn begin_attempt(&mut self, state: InspectBuilderState) {
184        self.state = Some(state);
185        self.suspension = None;
186        self.started_at = Instant::now();
187        self.started_unix = unix_now_secs();
188        if self.attempt_count == 0 && self.last_failure.is_none() {
189            self.first_attempt_unix = self.started_unix;
190        }
191    }
192
193    fn record_failure(&mut self, terminal: String) {
194        self.state = None;
195        self.suspension = None;
196        self.attempt_count = self.attempt_count.saturating_add(1);
197        self.last_failure = Some(terminal);
198    }
199
200    fn record_suspension(&mut self, suspension: crate::build_breaker::BuildSuspension) {
201        self.state = Some(InspectBuilderState::Suspended);
202        self.last_failure = None;
203        self.suspension = Some(suspension);
204    }
205
206    fn detail(&self) -> String {
207        if let Some(suspension) = self.suspension.as_ref() {
208            let now_ms = SystemTime::now()
209                .duration_since(UNIX_EPOCH)
210                .unwrap_or_default()
211                .as_millis()
212                .min(u128::from(u64::MAX)) as u64;
213            return format!(
214                "suspended domain={} deaths={} age_s={} reason={}",
215                suspension.domain.as_str(),
216                suspension.death_count,
217                suspension.age_seconds_at(now_ms),
218                suspension.reason,
219            );
220        }
221        if let Some(terminal) = self.last_failure.as_deref() {
222            return format!(
223                "last attempt failed: {terminal} (attempt {}, first at {})",
224                self.attempt_count, self.first_attempt_unix
225            );
226        }
227        match self.state {
228            Some(InspectBuilderState::Building) => format!(
229                "building since {} (age_s={})",
230                self.started_unix,
231                self.started_at.elapsed().as_secs()
232            ),
233            Some(other) => other.as_str().to_string(),
234            None => InspectBuilderState::Absent.as_str().to_string(),
235        }
236    }
237}
238
239fn unix_now_secs() -> u64 {
240    SystemTime::now()
241        .duration_since(UNIX_EPOCH)
242        .map(|duration| duration.as_secs())
243        .unwrap_or(0)
244}
245
246enum BuilderAttemptTerminal {
247    Succeeded,
248    Failed(String),
249    Inconclusive,
250}
251
252fn builder_attempt_terminal(outcome: &JobOutcome) -> BuilderAttemptTerminal {
253    match outcome {
254        JobOutcome::Fresh { payload } if callgraph_unavailable_payload(payload) => {
255            BuilderAttemptTerminal::Failed("callgraph_unavailable".to_string())
256        }
257        JobOutcome::Fresh { .. } => BuilderAttemptTerminal::Succeeded,
258        JobOutcome::Failed { message } => {
259            BuilderAttemptTerminal::Failed(builder_failure_terminal(message))
260        }
261        JobOutcome::Stale { .. } | JobOutcome::Pending { .. } => {
262            BuilderAttemptTerminal::Inconclusive
263        }
264    }
265}
266
267fn callgraph_unavailable_payload(payload: &Value) -> bool {
268    payload.get("callgraph_available").and_then(Value::as_bool) == Some(false)
269        || payload
270            .get("notes")
271            .and_then(Value::as_array)
272            .is_some_and(|notes| {
273                notes
274                    .iter()
275                    .any(|note| note.as_str() == Some("callgraph_unavailable"))
276            })
277}
278
279fn builder_failure_terminal(message: &str) -> String {
280    if message.contains("callgraph_unavailable") {
281        "callgraph_unavailable".to_string()
282    } else {
283        message
284            .lines()
285            .next()
286            .unwrap_or("failed")
287            .chars()
288            .take(64)
289            .collect()
290    }
291}
292
293fn callgraph_store_ready_for_dead_code(callgraph_dir: PathBuf, project_root: PathBuf) -> bool {
294    match CallGraphStore::open_readonly(callgraph_dir, project_root) {
295        Ok(Some(store)) => store
296            .stale_files()
297            .ok()
298            .is_some_and(|files| files.is_empty()),
299        _ => false,
300    }
301}
302
303/// Drops the builder-registry entry (and any leftover waiters) if a reuse
304/// worker returns, panics, or is cancelled without going through the
305/// completion router. Admission and exit must be paired; a leftover
306/// registration reads as `building` with no running job.
307struct Tier2FlightExitGuard<'a> {
308    manager: &'a InspectManager,
309    key: JobKey,
310}
311
312impl Drop for Tier2FlightExitGuard<'_> {
313    fn drop(&mut self) {
314        self.manager.finish_tier2_flight(
315            &self.key,
316            JobOutcome::Failed {
317                message: "tier2 reuse worker exited without publishing a result".to_string(),
318            },
319        );
320    }
321}
322
323fn cached_tier2_aggregate_usable(
324    category: InspectCategory,
325    options: &Tier2ReuseOptions,
326    aggregate: &Value,
327) -> bool {
328    if category == InspectCategory::DeadCode
329        && options.allow_callgraph_cold_build
330        && aggregate
331            .get("callgraph_available")
332            .and_then(Value::as_bool)
333            == Some(false)
334    {
335        return false;
336    }
337    true
338}
339
340pub struct InspectManager {
341    request_tx: Sender<InspectJob>,
342    result_rx: Receiver<InspectResult>,
343    #[allow(dead_code)]
344    pool: Arc<rayon::ThreadPool>,
345    in_flight: Mutex<HashMap<JobKey, Vec<Waiter>>>,
346    in_flight_changed: Condvar,
347    caches: Mutex<HashMap<InspectCacheIdentity, Arc<InspectCache>>>,
348    /// One root-scoped dead-code graph projection. It is cleared with the
349    /// manager's other idle artifacts rather than on a separate timer.
350    callgraph_projection: Mutex<Option<CachedCallgraphProjection>>,
351    oxc_facts_cache: Mutex<OxcFactsCache>,
352    soft_deadline: Duration,
353    next_job_id: AtomicU64,
354    heavy_root_work_allowed: Arc<AtomicBool>,
355    semantic_cold_seed_active: Arc<AtomicBool>,
356    cold_build_limiter: Mutex<Arc<cold_build_limiter::ColdBuildLimiter>>,
357    /// Inspect refusals (`builder_state=...`) and health's `tier2` field both
358    /// read this registry. The waiter map (`in_flight`) fans out completions;
359    /// both surfaces treat a category as busy when it has an entry here, and
360    /// fall back to the waiter map if the registry is empty.
361    builder_states: Mutex<HashMap<JobKey, BuilderStateEntry>>,
362    automatic_tier2_refresh_allowed: AtomicBool,
363    automatic_tier2_skip_logged: AtomicBool,
364    automatic_tier2_schedule_count: AtomicU64,
365    /// Monotonic count of Tier-2 completions delivered via the reuse path
366    /// (watcher-driven scheduler runs). These bypass `result_rx`/
367    /// `drain_completions`, so the `&AppContext`-side drain polls this counter
368    /// to know when to refresh the agent status bar after a background scan.
369    reuse_completions: AtomicU64,
370    /// Test observability for distinguishing queued reuse work from a worker that
371    /// has actually begun executing it.
372    reuse_starts: AtomicU64,
373}
374
375impl InspectManager {
376    pub fn new() -> Self {
377        Self::with_heavy_root_work_gate(Arc::new(AtomicBool::new(true)))
378    }
379
380    pub fn with_heavy_root_work_gate(heavy_root_work_allowed: Arc<AtomicBool>) -> Self {
381        Self::with_root_work_gates(heavy_root_work_allowed, Arc::new(AtomicBool::new(false)))
382    }
383
384    pub fn with_root_work_gates(
385        heavy_root_work_allowed: Arc<AtomicBool>,
386        semantic_cold_seed_active: Arc<AtomicBool>,
387    ) -> Self {
388        Self::with_worker_and_gates(
389            default_worker(),
390            DEFAULT_SOFT_DEADLINE,
391            heavy_root_work_allowed,
392            semantic_cold_seed_active,
393        )
394    }
395
396    #[doc(hidden)]
397    pub fn with_worker(worker: InspectWorker, soft_deadline: Duration) -> Self {
398        Self::with_worker_and_gate(worker, soft_deadline, Arc::new(AtomicBool::new(true)))
399    }
400
401    #[doc(hidden)]
402    pub fn with_worker_and_gate(
403        worker: InspectWorker,
404        soft_deadline: Duration,
405        heavy_root_work_allowed: Arc<AtomicBool>,
406    ) -> Self {
407        Self::with_worker_and_gates(
408            worker,
409            soft_deadline,
410            heavy_root_work_allowed,
411            Arc::new(AtomicBool::new(false)),
412        )
413    }
414
415    fn with_worker_and_gates(
416        worker: InspectWorker,
417        soft_deadline: Duration,
418        heavy_root_work_allowed: Arc<AtomicBool>,
419        semantic_cold_seed_active: Arc<AtomicBool>,
420    ) -> Self {
421        let handles = start_dispatch_loop(worker);
422        Self {
423            request_tx: handles.request_tx,
424            result_rx: handles.result_rx,
425            pool: handles.pool,
426            in_flight: Mutex::new(HashMap::new()),
427            in_flight_changed: Condvar::new(),
428            caches: Mutex::new(HashMap::new()),
429            callgraph_projection: Mutex::new(None),
430            oxc_facts_cache: Mutex::new(OxcFactsCache::new()),
431            soft_deadline,
432            next_job_id: AtomicU64::new(1),
433            heavy_root_work_allowed,
434            semantic_cold_seed_active,
435            cold_build_limiter: Mutex::new(cold_build_limiter::global_limiter()),
436            builder_states: Mutex::new(HashMap::new()),
437            automatic_tier2_refresh_allowed: AtomicBool::new(true),
438            automatic_tier2_skip_logged: AtomicBool::new(false),
439            automatic_tier2_schedule_count: AtomicU64::new(0),
440            reuse_completions: AtomicU64::new(0),
441            reuse_starts: AtomicU64::new(0),
442        }
443    }
444
445    fn heavy_root_work_allowed(&self) -> bool {
446        self.heavy_root_work_allowed.load(Ordering::SeqCst)
447    }
448
449    pub(crate) fn set_cold_build_limiter(
450        &self,
451        limiter: Arc<cold_build_limiter::ColdBuildLimiter>,
452    ) {
453        *self
454            .cold_build_limiter
455            .lock()
456            .unwrap_or_else(std::sync::PoisonError::into_inner) = limiter;
457    }
458
459    fn cold_build_limiter(&self) -> Arc<cold_build_limiter::ColdBuildLimiter> {
460        Arc::clone(
461            &self
462                .cold_build_limiter
463                .lock()
464                .unwrap_or_else(std::sync::PoisonError::into_inner),
465        )
466    }
467
468    fn set_builder_state(&self, key: &JobKey, state: InspectBuilderState) {
469        if let Ok(mut states) = self.builder_states.lock() {
470            if let Some(entry) = states.get_mut(key) {
471                entry.begin_attempt(state);
472            } else {
473                states.insert(key.clone(), BuilderStateEntry::new(state));
474            }
475        }
476    }
477
478    fn clear_builder_state(&self, key: &JobKey) {
479        if let Ok(mut states) = self.builder_states.lock() {
480            states.remove(key);
481        }
482    }
483
484    fn record_flight_start(&self, key: &JobKey) {
485        self.set_builder_state(key, InspectBuilderState::Building);
486    }
487
488    fn record_builder_attempt_outcome(&self, key: &JobKey, outcome: &JobOutcome) {
489        let Ok(mut states) = self.builder_states.lock() else {
490            return;
491        };
492        if states
493            .get(key)
494            .is_some_and(|entry| entry.suspension.is_some())
495        {
496            return;
497        }
498        match builder_attempt_terminal(outcome) {
499            BuilderAttemptTerminal::Succeeded => {
500                states.remove(key);
501            }
502            BuilderAttemptTerminal::Failed(terminal) => {
503                if let Some(entry) = states.get_mut(key) {
504                    entry.record_failure(terminal);
505                } else {
506                    let mut entry = BuilderStateEntry::new(InspectBuilderState::Building);
507                    entry.record_failure(terminal);
508                    states.insert(key.clone(), entry);
509                }
510            }
511            BuilderAttemptTerminal::Inconclusive => {
512                if let Some(entry) = states.get_mut(key) {
513                    entry.state = None;
514                    if entry.last_failure.is_none() && entry.attempt_count == 0 {
515                        states.remove(key);
516                    }
517                }
518            }
519        }
520    }
521
522    fn tier2_flight_exit_guard(&self, key: JobKey) -> Tier2FlightExitGuard<'_> {
523        Tier2FlightExitGuard { manager: self, key }
524    }
525
526    /// Record the attempt outcome and wake leftover waiters. Idempotent: a
527    /// second call after the completion router already ran is a no-op.
528    fn finish_tier2_flight(&self, key: &JobKey, outcome: JobOutcome) {
529        let Some(waiters) = self
530            .in_flight
531            .lock()
532            .ok()
533            .and_then(|mut in_flight| in_flight.remove(key))
534        else {
535            return;
536        };
537        self.record_builder_attempt_outcome(key, &outcome);
538        self.reuse_completions.fetch_add(1, Ordering::SeqCst);
539        for waiter in waiters {
540            let _ = waiter.tx.send(outcome.clone());
541        }
542    }
543
544    pub(crate) fn tier2_builder_state(&self, category: InspectCategory) -> InspectBuilderState {
545        let key = JobKey::for_project_category(category);
546        if let Ok(states) = self.builder_states.lock() {
547            if let Some(entry) = states.get(&key) {
548                if let Some(state) = entry.state {
549                    return state;
550                }
551            }
552        }
553        if self
554            .in_flight
555            .lock()
556            .map(|in_flight| in_flight.contains_key(&key))
557            .unwrap_or(false)
558        {
559            InspectBuilderState::Building
560        } else {
561            InspectBuilderState::Absent
562        }
563    }
564
565    pub(crate) fn tier2_builder_state_detail(&self, category: InspectCategory) -> String {
566        let key = JobKey::for_project_category(category);
567        if let Ok(states) = self.builder_states.lock() {
568            if let Some(entry) = states.get(&key) {
569                return entry.detail();
570            }
571        }
572        self.tier2_builder_state(category).as_str().to_string()
573    }
574
575    fn record_tier2_build_suspension(
576        &self,
577        key: &JobKey,
578        suspension: crate::build_breaker::BuildSuspension,
579    ) {
580        if let Ok(mut states) = self.builder_states.lock() {
581            if let Some(entry) = states.get_mut(key) {
582                entry.record_suspension(suspension);
583            } else {
584                let mut entry = BuilderStateEntry::new(InspectBuilderState::Suspended);
585                entry.record_suspension(suspension);
586                states.insert(key.clone(), entry);
587            }
588        }
589    }
590
591    #[cfg(test)]
592    pub(crate) fn record_tier2_build_suspension_for_test(
593        &self,
594        category: InspectCategory,
595        suspension: crate::build_breaker::BuildSuspension,
596    ) {
597        self.record_tier2_build_suspension(&JobKey::for_project_category(category), suspension);
598    }
599
600    fn builder_state_detail_for_job(&self, job: &InspectJob) -> String {
601        if !job.inspect_writer || !job.callgraph_writer {
602            InspectBuilderState::BuildDenied.as_str().to_string()
603        } else {
604            self.tier2_builder_state_detail(job.category)
605        }
606    }
607
608    /// Whether any Tier-2 category is registered in the builder registry.
609    /// Health uses this instead of published status-bar completeness so the
610    /// two surfaces cannot disagree about a live rebuild.
611    pub(crate) fn try_tier2_builder_busy(&self) -> Option<bool> {
612        let states = self.builder_states.try_lock().ok()?;
613        if states
614            .iter()
615            .any(|(key, entry)| key.category.is_tier2() && entry.is_in_flight())
616        {
617            return Some(true);
618        }
619        drop(states);
620        self.try_tier2_any_in_flight()
621    }
622
623    /// Whether a published callgraph store can back a dead_code snapshot.
624    ///
625    /// This is the same readiness predicate the builder uses before projection:
626    /// a store that opens but still has `backend_file_state='stale'` rows is
627    /// not ready, because `project_dead_code_snapshot` refuses those rows.
628    pub(crate) fn callgraph_ready_for_snapshot(&self, snapshot: &InspectSnapshot) -> bool {
629        if !snapshot.config.callgraph_store {
630            return false;
631        }
632        callgraph_store_dirs_from_inspect_dir(&snapshot.inspect_dir, &snapshot.project_root)
633            .into_iter()
634            .any(|dir| callgraph_store_ready_for_dead_code(dir, snapshot.project_root.clone()))
635    }
636
637    pub fn set_automatic_tier2_refresh_allowed(&self, allowed: bool) {
638        self.automatic_tier2_refresh_allowed
639            .store(allowed, Ordering::SeqCst);
640        self.automatic_tier2_skip_logged
641            .store(false, Ordering::SeqCst);
642    }
643
644    pub fn automatic_tier2_refresh_enabled(&self) -> bool {
645        self.automatic_tier2_refresh_allowed.load(Ordering::SeqCst)
646    }
647
648    pub fn automatic_tier2_refresh_allowed(&self) -> bool {
649        let allowed = self.automatic_tier2_refresh_enabled();
650        if !allowed
651            && !self
652                .automatic_tier2_skip_logged
653                .swap(true, Ordering::SeqCst)
654        {
655            crate::slog_debug!("automatic Tier-2 scan scheduling skipped for linked worktree root");
656        }
657        allowed
658    }
659
660    #[doc(hidden)]
661    pub fn inspect_pool_for_test(&self) -> Arc<rayon::ThreadPool> {
662        Arc::clone(&self.pool)
663    }
664
665    #[doc(hidden)]
666    pub fn automatic_tier2_schedule_count_for_test(&self) -> u64 {
667        self.automatic_tier2_schedule_count.load(Ordering::SeqCst)
668    }
669
670    fn category_needs_heavy_root_work(category: InspectCategory) -> bool {
671        category != InspectCategory::Diagnostics
672    }
673
674    fn heavy_root_work_block_message(category: InspectCategory) -> String {
675        format!(
676            "inspect category '{category}' is unavailable because heavy project-wide work is disabled for this root"
677        )
678    }
679
680    pub fn submit_category(
681        &self,
682        snapshot: InspectSnapshot,
683        category: InspectCategory,
684        caller_scope: JobScope,
685    ) -> JobOutcome {
686        self.submit_category_with_callgraph(snapshot, category, caller_scope, None)
687    }
688
689    pub fn submit_category_with_callgraph(
690        &self,
691        snapshot: InspectSnapshot,
692        category: InspectCategory,
693        caller_scope: JobScope,
694        callgraph_snapshot: Option<Arc<CallgraphSnapshot>>,
695    ) -> JobOutcome {
696        if !category.is_active() {
697            return JobOutcome::Failed {
698                message: format!("inspect category '{category}' is disabled in v0.33"),
699            };
700        }
701        if Self::category_needs_heavy_root_work(category) && !self.heavy_root_work_allowed() {
702            return JobOutcome::Failed {
703                message: Self::heavy_root_work_block_message(category),
704            };
705        }
706
707        let cache = match self.cache_for_snapshot(&snapshot) {
708            Ok(cache) => cache,
709            Err(message) => return JobOutcome::Failed { message },
710        };
711        let key = JobKey::for_category_scope(category, &caller_scope);
712        let (waiter_tx, waiter_rx) = bounded(1);
713
714        let wait_snapshot = snapshot.clone();
715        match self.enqueue_with_waiter(
716            snapshot,
717            category,
718            caller_scope.clone(),
719            key.clone(),
720            waiter_tx,
721            callgraph_snapshot,
722        ) {
723            Ok(()) => self.wait_for_outcome(key, caller_scope, cache, waiter_rx, wait_snapshot),
724            Err(message) => JobOutcome::Failed { message },
725        }
726    }
727
728    pub fn submit_background(
729        &self,
730        snapshot: InspectSnapshot,
731        category: InspectCategory,
732        caller_scope: JobScope,
733    ) -> Result<JobKey, String> {
734        self.submit_background_with_callgraph(snapshot, category, caller_scope, None)
735    }
736
737    pub fn submit_background_with_callgraph(
738        &self,
739        snapshot: InspectSnapshot,
740        category: InspectCategory,
741        caller_scope: JobScope,
742        callgraph_snapshot: Option<Arc<CallgraphSnapshot>>,
743    ) -> Result<JobKey, String> {
744        if !category.is_active() {
745            return Err(format!(
746                "inspect category '{category}' is disabled in v0.33"
747            ));
748        }
749        if Self::category_needs_heavy_root_work(category) && !self.heavy_root_work_allowed() {
750            return Err(Self::heavy_root_work_block_message(category));
751        }
752        let key = JobKey::for_category_scope(category, &caller_scope);
753        self.enqueue_without_waiter(
754            snapshot,
755            category,
756            caller_scope,
757            key.clone(),
758            callgraph_snapshot,
759        )?;
760        Ok(key)
761    }
762
763    pub fn submit_tier2_run_with_reuse_background(
764        self: &Arc<Self>,
765        snapshot: InspectSnapshot,
766        category: InspectCategory,
767    ) -> Result<Option<JobKey>, String> {
768        if !category.is_active() {
769            return Err(format!(
770                "inspect category '{category}' is disabled in v0.33"
771            ));
772        }
773        if !category.is_tier2() {
774            return Err(format!(
775                "inspect category '{category}' is not a Tier 2 category"
776            ));
777        }
778        if !self.heavy_root_work_allowed() {
779            return Err(Self::heavy_root_work_block_message(category));
780        }
781        if !self.automatic_tier2_refresh_allowed() {
782            return Ok(None);
783        }
784        self.automatic_tier2_schedule_count
785            .fetch_add(1, Ordering::SeqCst);
786
787        let job = self.tier2_reuse_job(snapshot, category, None);
788        let key = job.key.clone();
789        let mut in_flight = self
790            .in_flight
791            .lock()
792            .map_err(|_| "inspect in-flight map lock poisoned".to_string())?;
793        if in_flight.contains_key(&key) {
794            return Ok(Some(key));
795        }
796        let limiter = self.cold_build_limiter();
797        let request = cold_build_limiter::ColdBuildAdmissionRequest::new(
798            format!("tier2-background:{}", category.as_str()),
799            cold_build_limiter::ColdBuildAdmissionClass::Maintenance,
800        );
801        let Some(permit) =
802            cold_build_limiter::try_acquire_classified_with_limiter(&limiter, &request)
803        else {
804            return Err(format!(
805                "cold build concurrency limit ({}) reached; retrying later",
806                limiter.limit()
807            ));
808        };
809        in_flight.insert(key.clone(), Vec::new());
810        drop(in_flight);
811        self.record_flight_start(&key);
812
813        let manager = Arc::clone(self);
814        let pool = Arc::clone(&self.pool);
815        pool.spawn_fifo(move || {
816            let _permit = permit;
817            let _flight = manager.tier2_flight_exit_guard(job.key.clone());
818            let result =
819                manager.tier2_run_with_reuse_job_result_catching(job, Tier2ReuseOptions::default());
820            manager.route_tier2_reuse_completion(result);
821        });
822
823        Ok(Some(key))
824    }
825
826    pub fn submit_tier2_run_with_reuse_serial_background(
827        self: &Arc<Self>,
828        snapshot: InspectSnapshot,
829        categories: Vec<InspectCategory>,
830    ) -> Tier2RunSubmission {
831        let mut submission = Tier2RunSubmission::default();
832        let mut requested = Vec::new();
833
834        for category in categories {
835            if !category.is_active() {
836                submission.errors.push(Tier2RunSubmissionError {
837                    category,
838                    message: format!("inspect category '{category}' is disabled in v0.33"),
839                });
840                continue;
841            }
842            if !category.is_tier2() {
843                submission.errors.push(Tier2RunSubmissionError {
844                    category,
845                    message: format!("inspect category '{category}' is not a Tier 2 category"),
846                });
847                continue;
848            }
849            requested.push(category);
850        }
851
852        if requested.is_empty() {
853            return submission;
854        }
855        if !self.heavy_root_work_allowed() {
856            for category in requested {
857                submission.errors.push(Tier2RunSubmissionError {
858                    category,
859                    message: Self::heavy_root_work_block_message(category),
860                });
861            }
862            return submission;
863        }
864        if !self.automatic_tier2_refresh_allowed() {
865            return submission;
866        }
867        self.automatic_tier2_schedule_count
868            .fetch_add(requested.len() as u64, Ordering::SeqCst);
869
870        let mut in_flight = match self.in_flight.lock() {
871            Ok(in_flight) => in_flight,
872            Err(_) => {
873                for category in requested {
874                    submission.errors.push(Tier2RunSubmissionError {
875                        category,
876                        message: "inspect in-flight map lock poisoned".to_string(),
877                    });
878                }
879                return submission;
880            }
881        };
882
883        let mut started = Vec::new();
884        for category in requested {
885            let key = JobKey::for_project_category(category);
886            submission.queued_categories.push(category);
887            if in_flight.contains_key(&key) {
888                continue;
889            }
890            in_flight.insert(key.clone(), Vec::new());
891            started.push(key);
892            submission.newly_queued_categories.push(category);
893        }
894        drop(in_flight);
895        for key in &started {
896            self.record_flight_start(key);
897        }
898
899        if submission.newly_queued_categories.is_empty() {
900            return submission;
901        }
902
903        let limiter = self.cold_build_limiter();
904        let request = cold_build_limiter::ColdBuildAdmissionRequest::new(
905            "tier2-serial-background",
906            cold_build_limiter::ColdBuildAdmissionClass::Maintenance,
907        );
908        let Some(permit) =
909            cold_build_limiter::try_acquire_classified_with_limiter(&limiter, &request)
910        else {
911            let deferred = submission.newly_queued_categories.clone();
912            if let Ok(mut in_flight) = self.in_flight.lock() {
913                for category in &deferred {
914                    in_flight.remove(&JobKey::for_project_category(*category));
915                }
916            }
917            for category in &deferred {
918                self.clear_builder_state(&JobKey::for_project_category(*category));
919            }
920            submission
921                .queued_categories
922                .retain(|category| !deferred.contains(category));
923            submission.deferred_categories = deferred;
924            submission.newly_queued_categories.clear();
925            return submission;
926        };
927
928        let categories_for_worker = submission.newly_queued_categories.clone();
929        let manager = Arc::clone(self);
930        let pool = Arc::clone(&self.pool);
931        pool.spawn_fifo(move || {
932            let _permit = permit;
933            for category in categories_for_worker {
934                let job = manager.tier2_reuse_job(snapshot.clone(), category, None);
935                let _flight = manager.tier2_flight_exit_guard(job.key.clone());
936                let result = manager
937                    .tier2_run_with_reuse_job_result_catching(job, Tier2ReuseOptions::default());
938                manager.route_tier2_reuse_completion(result);
939            }
940        });
941
942        submission
943    }
944
945    pub fn tier2_any_in_flight(&self) -> bool {
946        self.in_flight
947            .lock()
948            .map(|in_flight| in_flight.keys().any(|key| key.category.is_tier2()))
949            .unwrap_or(false)
950    }
951
952    pub(crate) fn try_tier2_any_in_flight(&self) -> Option<bool> {
953        self.in_flight
954            .try_lock()
955            .ok()
956            .map(|in_flight| in_flight.keys().any(|key| key.category.is_tier2()))
957    }
958
959    #[cfg(test)]
960    pub(crate) fn set_tier2_in_flight_for_test(&self, category: InspectCategory, in_flight: bool) {
961        let key = JobKey::for_project_category(category);
962        let mut jobs = self
963            .in_flight
964            .lock()
965            .unwrap_or_else(std::sync::PoisonError::into_inner);
966        if in_flight {
967            jobs.entry(key.clone()).or_default();
968            drop(jobs);
969            self.record_flight_start(&key);
970        } else {
971            jobs.remove(&key);
972            drop(jobs);
973            self.clear_builder_state(&key);
974        }
975    }
976
977    #[cfg(test)]
978    pub(crate) fn record_tier2_attempt_outcome_for_test(
979        &self,
980        category: InspectCategory,
981        outcome: JobOutcome,
982    ) {
983        let key = JobKey::for_project_category(category);
984        {
985            let mut jobs = self
986                .in_flight
987                .lock()
988                .unwrap_or_else(std::sync::PoisonError::into_inner);
989            jobs.entry(key.clone()).or_default();
990        }
991        self.record_flight_start(&key);
992        self.finish_tier2_flight(&key, outcome);
993    }
994
995    /// Release per-project inspect caches so their SQLite readers and writer
996    /// leases do not remain open after a root has gone idle. Callers must check
997    /// [`Self::tier2_any_in_flight`] first so a running scan never loses its
998    /// cache while it is being used.
999    pub fn evict_idle_caches(&self) {
1000        if let Ok(mut caches) = self.caches.lock() {
1001            caches.clear();
1002        }
1003        self.clear_callgraph_projection();
1004        if let Ok(mut facts) = self.oxc_facts_cache.lock() {
1005            *facts = OxcFactsCache::new();
1006        }
1007        // A new corpus after idle eviction must not inherit the previous
1008        // root's failed-attempt history.
1009        if let Ok(mut states) = self.builder_states.lock() {
1010            states.retain(|_, entry| entry.is_in_flight());
1011        }
1012    }
1013
1014    /// Estimate inspect's resident aggregate maps without waiting on active
1015    /// scans. SQLite allocations are measured process-wide; OXC fact payload
1016    /// bytes remain an explicit gap.
1017    pub fn estimated_memory(&self) -> crate::memory::MemoryEstimate {
1018        let caches = match self.caches.try_lock() {
1019            Ok(caches) => caches.values().cloned().collect::<Vec<_>>(),
1020            Err(_) => return crate::memory::MemoryEstimate::busy(),
1021        };
1022        let facts_entries = match self.oxc_facts_cache.try_lock() {
1023            Ok(facts) => facts.len(),
1024            Err(_) => return crate::memory::MemoryEstimate::busy(),
1025        };
1026        let mut bytes = 0u64;
1027        let mut memory_aggregates = 0u64;
1028        for cache in &caches {
1029            let estimate = cache.estimated_memory();
1030            let Some(cache_bytes) = estimate.estimated_bytes else {
1031                return crate::memory::MemoryEstimate::busy();
1032            };
1033            bytes = bytes.saturating_add(cache_bytes);
1034            memory_aggregates = memory_aggregates.saturating_add(
1035                estimate
1036                    .counts
1037                    .get("memory_aggregates")
1038                    .copied()
1039                    .unwrap_or(0),
1040            );
1041        }
1042        crate::memory::MemoryEstimate::partial(bytes)
1043            .count("open_generation_handles", caches.len())
1044            .count("oxc_fact_entries", facts_entries)
1045            .count_u64("memory_aggregates", memory_aggregates)
1046            .gap("oxc_fact_bytes")
1047    }
1048
1049    /// Estimate the resident full-graph projection used by dead-code scans.
1050    /// The slot belongs to this root's manager and is dropped on idle eviction.
1051    pub fn callgraph_projection_estimated_memory(&self) -> crate::memory::MemoryEstimate {
1052        let projection = match self.callgraph_projection.try_lock() {
1053            Ok(projection) => projection,
1054            Err(_) => return crate::memory::MemoryEstimate::busy(),
1055        };
1056        let bytes = projection
1057            .as_ref()
1058            .map(|projection| projection.estimated_bytes)
1059            .unwrap_or(0);
1060        crate::memory::MemoryEstimate::estimated(bytes)
1061            .count(
1062                "callgraph_projection_snapshots",
1063                usize::from(projection.is_some()),
1064            )
1065            .count_u64("callgraph_projection_snapshot_bytes", bytes)
1066    }
1067
1068    fn cached_callgraph_projection(
1069        &self,
1070        identity: &CallgraphProjectionIdentity,
1071    ) -> Option<Arc<CallgraphSnapshot>> {
1072        let projection = self.callgraph_projection.lock().ok()?;
1073        projection
1074            .as_ref()
1075            .filter(|cached| cached.identity == *identity)
1076            .map(|cached| Arc::clone(&cached.snapshot))
1077    }
1078
1079    fn cache_callgraph_projection(
1080        &self,
1081        identity: CallgraphProjectionIdentity,
1082        snapshot: Arc<CallgraphSnapshot>,
1083    ) {
1084        let estimated_bytes = estimate_callgraph_snapshot_bytes(snapshot.as_ref());
1085        if let Ok(mut cached) = self.callgraph_projection.lock() {
1086            *cached = Some(CachedCallgraphProjection {
1087                identity,
1088                snapshot,
1089                estimated_bytes,
1090            });
1091        }
1092    }
1093
1094    fn clear_callgraph_projection(&self) {
1095        if let Ok(mut cached) = self.callgraph_projection.lock() {
1096            cached.take();
1097        }
1098    }
1099
1100    fn build_tier2_callgraph_snapshot_with_refresh(
1101        &self,
1102        job: &InspectJob,
1103        allow_cold_build: bool,
1104        build_if_missing: bool,
1105        refresh_paths: &[PathBuf],
1106    ) -> Option<Arc<CallgraphSnapshot>> {
1107        build_tier2_callgraph_snapshot_with_refresh_inner(
1108            job,
1109            allow_cold_build,
1110            build_if_missing,
1111            refresh_paths,
1112            Some(self),
1113        )
1114    }
1115
1116    /// Whether completed scan results are waiting in the channel. Used by the
1117    /// maintenance scheduler to skip enqueueing a completion drain with no work.
1118    pub fn has_pending_completions(&self) -> bool {
1119        !self.result_rx.is_empty()
1120    }
1121
1122    pub fn drain_completions(&self) -> usize {
1123        let mut drained = 0usize;
1124        while let Ok(result) = self.result_rx.try_recv() {
1125            self.route_completion(result);
1126            drained += 1;
1127        }
1128        drained
1129    }
1130
1131    pub fn discard_completions(&self) -> usize {
1132        let mut discarded = 0usize;
1133        while self.result_rx.try_recv().is_ok() {
1134            discarded += 1;
1135        }
1136        discarded
1137    }
1138
1139    pub fn cache_for_snapshot(
1140        &self,
1141        snapshot: &InspectSnapshot,
1142    ) -> Result<Arc<InspectCache>, String> {
1143        self.cache_for_paths(snapshot.inspect_dir.clone(), snapshot.project_root.clone())
1144    }
1145
1146    /// Latest persisted counts for the three Tier-2 categories, in
1147    /// `(dead_code, unused_exports, duplicates)` order. Reads the most recent
1148    /// aggregate regardless of contribution-hash freshness (last-known), so the
1149    /// agent status bar can refresh after a background scan completes without a
1150    /// freshness round-trip. A category with no readable aggregate reports
1151    /// `None` (never a fabricated `0`), so the status bar can preserve any
1152    /// last-known value and stay suppressed until every category is real (#1).
1153    pub fn latest_tier2_counts(
1154        &self,
1155        inspect_dir: PathBuf,
1156        project_root: PathBuf,
1157    ) -> (Option<usize>, Option<usize>, Option<usize>) {
1158        let Ok(cache) = self.cache_for_paths(inspect_dir, project_root) else {
1159            return (None, None, None);
1160        };
1161        let count_of = |category: InspectCategory| -> Option<usize> {
1162            cache
1163                .latest_aggregate_any_hash(category)
1164                .ok()
1165                .flatten()
1166                .and_then(|payload| {
1167                    if category == InspectCategory::DeadCode
1168                        && payload
1169                            .get("callgraph_available")
1170                            .and_then(serde_json::Value::as_bool)
1171                            == Some(false)
1172                    {
1173                        return None;
1174                    }
1175                    payload
1176                        .get("count")
1177                        .and_then(serde_json::Value::as_u64)
1178                        .map(|count| count as usize)
1179                })
1180        };
1181        (
1182            count_of(InspectCategory::DeadCode),
1183            count_of(InspectCategory::UnusedExports),
1184            count_of(InspectCategory::Duplicates),
1185        )
1186    }
1187
1188    /// Whether the latest persisted dead_code aggregate reported
1189    /// `callgraph_available:false` — i.e. dead_code was suppressed because the
1190    /// callgraph store was not ready when it scanned. Health uses this to avoid
1191    /// reporting tier2 as permanently "building" for a root whose only missing
1192    /// category is dead_code blocked on the callgraph store. Mirrors the
1193    /// suppression rule in [`Self::latest_tier2_counts`].
1194    pub fn dead_code_blocked_on_callgraph(
1195        &self,
1196        inspect_dir: PathBuf,
1197        project_root: PathBuf,
1198    ) -> bool {
1199        let Ok(cache) = self.cache_for_paths(inspect_dir, project_root) else {
1200            return false;
1201        };
1202        cache
1203            .latest_aggregate_any_hash(InspectCategory::DeadCode)
1204            .ok()
1205            .flatten()
1206            .and_then(|payload| {
1207                payload
1208                    .get("callgraph_available")
1209                    .and_then(serde_json::Value::as_bool)
1210            })
1211            == Some(false)
1212    }
1213
1214    pub fn cache_for_paths(
1215        &self,
1216        inspect_dir: PathBuf,
1217        project_root: PathBuf,
1218    ) -> Result<Arc<InspectCache>, String> {
1219        let project_key = crate::path_identity::project_scope_key(&project_root);
1220        let inspect_dir = if inspect_dir
1221            .file_name()
1222            .and_then(|name| name.to_str())
1223            .is_some_and(|name| name == project_key)
1224        {
1225            inspect_dir
1226        } else {
1227            inspect_dir.join(&project_key)
1228        };
1229        let identity = InspectCacheIdentity {
1230            sqlite_path: inspect_dir.join(format!("{project_key}.current")),
1231            project_root: project_root.clone(),
1232        };
1233        let mut caches = self
1234            .caches
1235            .lock()
1236            .map_err(|_| "inspect manager cache map lock poisoned".to_string())?;
1237        if let Some(cache) = caches.get(&identity) {
1238            return Ok(Arc::clone(cache));
1239        }
1240        let cache = Arc::new(
1241            InspectCache::open(inspect_dir, project_root)
1242                .map_err(|error| format!("failed to open inspect cache: {error}"))?,
1243        );
1244        caches.insert(identity, Arc::clone(&cache));
1245        Ok(cache)
1246    }
1247
1248    fn oxc_result_for_scan(
1249        &self,
1250        job: &InspectJob,
1251        files: &[PathBuf],
1252        force_reparse_files: &[PathBuf],
1253    ) -> Result<Option<OxcEngineResult>, String> {
1254        if !category_uses_oxc(job.category) {
1255            return Ok(None);
1256        }
1257        if job.category == InspectCategory::DeadCode && job.callgraph_snapshot.is_none() {
1258            return Ok(None);
1259        }
1260
1261        let public_api_entries =
1262            crate::inspect::entry_points::resolve_entry_points(&job.project_root);
1263        let entry_points = if job.category == InspectCategory::DeadCode {
1264            job.callgraph_snapshot
1265                .as_ref()
1266                .map(|snapshot| snapshot.entry_points.iter().cloned().collect::<Vec<_>>())
1267                .unwrap_or_default()
1268        } else {
1269            Vec::new()
1270        };
1271        let options = AnalyzeOptions {
1272            entry_points,
1273            public_api_files: public_api_entries.public_api_files(),
1274            executable_root_exports: public_api_entries.executable_root_exports(),
1275            force_reparse_files: force_reparse_files.to_vec(),
1276            entry_reachability: job.category == InspectCategory::DeadCode,
1277        };
1278
1279        let mut cache = self
1280            .oxc_facts_cache
1281            .lock()
1282            .map_err(|_| "inspect oxc facts cache lock poisoned".to_string())?;
1283        analyze_files_with_cache(&job.project_root, files, options, &mut cache)
1284            .map(Some)
1285            .map_err(|message| format!("oxc analyze failed: {message}"))
1286    }
1287
1288    pub fn tier2_run_with_reuse(
1289        &self,
1290        snapshot: InspectSnapshot,
1291        category: InspectCategory,
1292        caller_scope: JobScope,
1293        callgraph_snapshot: Option<Arc<CallgraphSnapshot>>,
1294    ) -> JobOutcome {
1295        if let Err(outcome) = validate_tier2_read_category(category) {
1296            return outcome;
1297        }
1298        if !self.heavy_root_work_allowed() {
1299            return JobOutcome::Failed {
1300                message: Self::heavy_root_work_block_message(category),
1301            };
1302        }
1303        let cache = match self.cache_for_snapshot(&snapshot) {
1304            Ok(cache) => cache,
1305            Err(message) => return JobOutcome::Failed { message },
1306        };
1307        let job = self.tier2_reuse_job(snapshot.clone(), category, callgraph_snapshot);
1308        let key = job.key.clone();
1309        let (waiter_tx, waiter_rx) = bounded(1);
1310        let claimed = match self.register_tier2_reuse_waiter(&key, waiter_tx) {
1311            Ok(claimed) => claimed,
1312            Err(message) => return JobOutcome::Failed { message },
1313        };
1314
1315        if claimed {
1316            let _flight = self.tier2_flight_exit_guard(key.clone());
1317            let result =
1318                self.tier2_run_with_reuse_job_result_catching(job, Tier2ReuseOptions::default());
1319            self.route_tier2_reuse_completion(result);
1320        }
1321
1322        match waiter_rx.recv() {
1323            Ok(outcome) => filter_outcome_for_scope_with_contributions(
1324                outcome,
1325                &snapshot,
1326                category,
1327                cache.as_ref(),
1328                &caller_scope,
1329            ),
1330            Err(_) => JobOutcome::Pending { in_flight: true },
1331        }
1332    }
1333
1334    /// Run a Tier-2 category to a terminal outcome for an explicit inspect.
1335    ///
1336    /// The blocking inspect path must not turn an unfinished reuse job into a
1337    /// partial response. A caller either receives the completed aggregate or a
1338    /// failure from the worker; it never receives a timeout-shaped `Pending`.
1339    pub fn tier2_run_with_reuse_blocking(
1340        self: &Arc<Self>,
1341        snapshot: InspectSnapshot,
1342        category: InspectCategory,
1343        caller_scope: JobScope,
1344    ) -> JobOutcome {
1345        self.tier2_run_with_reuse_blocking_once(snapshot, category, caller_scope, false)
1346    }
1347
1348    /// Run a Tier-2 category for a blocking request that requires fresh results.
1349    /// Unlike compatibility callers, this retries a temporarily unavailable
1350    /// callgraph instead of accepting that incomplete scan as the final result.
1351    pub fn tier2_run_with_reuse_blocking_fresh(
1352        self: &Arc<Self>,
1353        snapshot: InspectSnapshot,
1354        category: InspectCategory,
1355        caller_scope: JobScope,
1356    ) -> JobOutcome {
1357        let first = self.tier2_run_with_reuse_blocking_once(
1358            snapshot.clone(),
1359            category,
1360            caller_scope.clone(),
1361            category == InspectCategory::DeadCode,
1362        );
1363        if category == InspectCategory::DeadCode
1364            && first.payload().is_some_and(|payload| {
1365                payload.get("callgraph_available").and_then(Value::as_bool) == Some(false)
1366            })
1367        {
1368            // A blocking caller can attach to a background scan that started
1369            // before the callgraph was ready. Retry once under the blocking
1370            // policy so that transient result cannot become the terminal payload.
1371            return self.tier2_run_with_reuse_blocking_once(snapshot, category, caller_scope, true);
1372        }
1373        first
1374    }
1375
1376    fn tier2_run_with_reuse_blocking_once(
1377        self: &Arc<Self>,
1378        snapshot: InspectSnapshot,
1379        category: InspectCategory,
1380        caller_scope: JobScope,
1381        require_callgraph_snapshot: bool,
1382    ) -> JobOutcome {
1383        if let Err(outcome) = validate_tier2_read_category(category) {
1384            return outcome;
1385        }
1386        if !self.heavy_root_work_allowed() {
1387            return JobOutcome::Failed {
1388                message: Self::heavy_root_work_block_message(category),
1389            };
1390        }
1391        let cache = match self.cache_for_snapshot(&snapshot) {
1392            Ok(cache) => cache,
1393            Err(message) => return JobOutcome::Failed { message },
1394        };
1395
1396        let job = self.tier2_reuse_job(snapshot.clone(), category, None);
1397        let key = job.key.clone();
1398        let (waiter_tx, waiter_rx) = bounded(1);
1399        let claimed = match self.register_tier2_reuse_waiter(&key, waiter_tx) {
1400            Ok(claimed) => claimed,
1401            Err(message) => return JobOutcome::Failed { message },
1402        };
1403        if claimed {
1404            self.spawn_tier2_reuse_job(
1405                job,
1406                Tier2ReuseOptions {
1407                    require_callgraph_snapshot,
1408                    interactive: true,
1409                    ..Tier2ReuseOptions::default()
1410                },
1411            );
1412        }
1413
1414        self.wait_for_tier2_reuse(&key, &caller_scope, cache.as_ref(), waiter_rx, &snapshot)
1415    }
1416
1417    fn register_tier2_reuse_waiter(
1418        &self,
1419        key: &JobKey,
1420        waiter_tx: WaiterTx,
1421    ) -> Result<bool, String> {
1422        let mut in_flight = self
1423            .in_flight
1424            .lock()
1425            .map_err(|_| "inspect in-flight map lock poisoned".to_string())?;
1426        if let Some(waiters) = in_flight.get_mut(key) {
1427            waiters.push(Waiter { tx: waiter_tx });
1428            self.in_flight_changed.notify_all();
1429            return Ok(false);
1430        }
1431
1432        in_flight.insert(key.clone(), vec![Waiter { tx: waiter_tx }]);
1433        drop(in_flight);
1434        self.record_flight_start(key);
1435        Ok(true)
1436    }
1437
1438    fn wait_for_tier2_reuse_waiter_for_debug(&self, job: &InspectJob) {
1439        #[cfg(not(debug_assertions))]
1440        let _ = job;
1441        #[cfg(debug_assertions)]
1442        {
1443            const WAIT_ROOT_ENV: &str = "AFT_TEST_TIER2_REUSE_WAIT_FOR_WAITER_ROOT";
1444            if std::env::var_os(WAIT_ROOT_ENV).is_none()
1445                || !env_project_root_matches(WAIT_ROOT_ENV, &job.project_root)
1446            {
1447                return;
1448            }
1449
1450            // This test gate releases on the actual waiter registration, not elapsed
1451            // wall-clock time, so a queued background job cannot finish before the
1452            // direct-reuse request has attached on a contended runner.
1453            let deadline = Instant::now() + Duration::from_secs(30);
1454            let mut in_flight = self
1455                .in_flight
1456                .lock()
1457                .unwrap_or_else(std::sync::PoisonError::into_inner);
1458            loop {
1459                match in_flight.get(&job.key) {
1460                    Some(waiters) if waiters.is_empty() => {}
1461                    _ => return,
1462                }
1463                let now = Instant::now();
1464                if now >= deadline {
1465                    return;
1466                }
1467                let (next, wait_result) = self
1468                    .in_flight_changed
1469                    .wait_timeout(in_flight, deadline.saturating_duration_since(now))
1470                    .unwrap_or_else(std::sync::PoisonError::into_inner);
1471                in_flight = next;
1472                if wait_result.timed_out() {
1473                    return;
1474                }
1475            }
1476        }
1477    }
1478
1479    fn spawn_tier2_reuse_job(self: &Arc<Self>, job: InspectJob, options: Tier2ReuseOptions) {
1480        // Rebinds retain the persisted contribution cache. Let quick reuse prove
1481        // that cache before joining the cold-build queue, so an unchanged root can
1482        // answer immediately even while unrelated background builds own the slots.
1483        self.record_flight_start(&job.key);
1484        let manager = Arc::clone(self);
1485        let pool = Arc::clone(&self.pool);
1486        let cancellation = crate::executor::current_job_cancellation();
1487        pool.spawn_fifo(move || {
1488            let _cancellation = cancellation.map(crate::executor::install_job_cancellation);
1489            let _flight = manager.tier2_flight_exit_guard(job.key.clone());
1490            let result = manager.tier2_run_with_reuse_job_result_catching(job, options);
1491            manager.route_tier2_reuse_completion(result);
1492        });
1493    }
1494
1495    fn wait_for_tier2_reuse(
1496        &self,
1497        key: &JobKey,
1498        caller_scope: &JobScope,
1499        cache: &(impl InspectCacheRead + ?Sized),
1500        waiter_rx: Receiver<JobOutcome>,
1501        snapshot: &InspectSnapshot,
1502    ) -> JobOutcome {
1503        match waiter_rx.recv() {
1504            Ok(outcome) => filter_outcome_for_scope_with_contributions(
1505                outcome,
1506                snapshot,
1507                key.category,
1508                cache,
1509                caller_scope,
1510            ),
1511            Err(_) => JobOutcome::Failed {
1512                message: "inspect Tier-2 worker disconnected before completion".to_string(),
1513            },
1514        }
1515    }
1516
1517    /// Read-only Tier 2 aggregate lookup for `aft_inspect`. Does NOT run any
1518    /// scanner — returns the latest cached aggregate if present and verifies
1519    /// its contribution freshness so warm cache hits are reported as fresh.
1520    /// This is the non-blocking variant intended for the synchronous `inspect`
1521    /// command path; Tier 2 scans run via the watcher-driven scheduler or the
1522    /// compatibility `aft_inspect_tier2_run` command.
1523    pub fn tier2_read_cached(
1524        &self,
1525        snapshot: InspectSnapshot,
1526        category: InspectCategory,
1527        caller_scope: JobScope,
1528    ) -> JobOutcome {
1529        if let Err(outcome) = validate_tier2_read_category(category) {
1530            return outcome;
1531        }
1532        if !self.heavy_root_work_allowed() {
1533            return JobOutcome::Failed {
1534                message: Self::heavy_root_work_block_message(category),
1535            };
1536        }
1537        let cache = match self.cache_for_snapshot(&snapshot) {
1538            Ok(cache) => cache,
1539            Err(message) => return JobOutcome::Failed { message },
1540        };
1541        self.tier2_read_cached_from_cache(&snapshot, category, &caller_scope, cache.as_ref())
1542    }
1543
1544    pub fn tier2_read_cached_readonly(
1545        &self,
1546        snapshot: InspectSnapshot,
1547        category: InspectCategory,
1548        caller_scope: JobScope,
1549    ) -> JobOutcome {
1550        if let Err(outcome) = validate_tier2_read_category(category) {
1551            return outcome;
1552        }
1553        if !self.heavy_root_work_allowed() {
1554            return JobOutcome::Failed {
1555                message: Self::heavy_root_work_block_message(category),
1556            };
1557        }
1558        let key = JobKey::for_project_category(category);
1559        let in_flight = self
1560            .in_flight
1561            .lock()
1562            .map(|guard| guard.contains_key(&key))
1563            .unwrap_or(false);
1564        let cache = match InspectCache::open_readonly(
1565            snapshot.inspect_dir.clone(),
1566            snapshot.project_root.clone(),
1567        ) {
1568            Ok(Some(cache)) => cache,
1569            Ok(None) => return JobOutcome::Pending { in_flight },
1570            Err(error) => {
1571                return JobOutcome::Failed {
1572                    message: error.to_string(),
1573                }
1574            }
1575        };
1576        self.tier2_read_cached_from_cache(&snapshot, category, &caller_scope, &cache)
1577    }
1578
1579    fn tier2_read_cached_from_cache(
1580        &self,
1581        snapshot: &InspectSnapshot,
1582        category: InspectCategory,
1583        caller_scope: &JobScope,
1584        cache: &(impl InspectCacheRead + ?Sized),
1585    ) -> JobOutcome {
1586        let key = JobKey::for_project_category(category);
1587        let in_flight = self
1588            .in_flight
1589            .lock()
1590            .map(|guard| guard.contains_key(&key))
1591            .unwrap_or(false);
1592        match cache.get_aggregated_for_config(&key, snapshot.config.as_ref()) {
1593            Ok(Some(payload)) => {
1594                match self.tier2_cached_aggregate_is_fresh(snapshot, category, cache) {
1595                    Ok(true) => filter_outcome_for_scope_with_contributions(
1596                        JobOutcome::Fresh { payload },
1597                        snapshot,
1598                        category,
1599                        cache,
1600                        caller_scope,
1601                    ),
1602                    Ok(false) => filter_outcome_for_scope_with_contributions(
1603                        JobOutcome::Stale {
1604                            cached: Some(payload),
1605                            in_flight,
1606                        },
1607                        snapshot,
1608                        category,
1609                        cache,
1610                        caller_scope,
1611                    ),
1612                    Err(message) => JobOutcome::Failed { message },
1613                }
1614            }
1615            Ok(None) => match cache.latest_aggregate_any_hash(category) {
1616                Ok(Some(payload)) => filter_outcome_for_scope_with_contributions(
1617                    JobOutcome::Stale {
1618                        cached: Some(payload),
1619                        in_flight,
1620                    },
1621                    snapshot,
1622                    category,
1623                    cache,
1624                    caller_scope,
1625                ),
1626                Ok(None) => JobOutcome::Pending { in_flight },
1627                Err(error) => JobOutcome::Failed {
1628                    message: error.to_string(),
1629                },
1630            },
1631            Err(error) => JobOutcome::Failed {
1632                message: error.to_string(),
1633            },
1634        }
1635    }
1636
1637    fn tier2_cached_aggregate_is_fresh(
1638        &self,
1639        snapshot: &InspectSnapshot,
1640        category: InspectCategory,
1641        cache: &(impl InspectCacheRead + ?Sized),
1642    ) -> Result<bool, String> {
1643        let cached_records = load_contribution_freshness(cache, category)?;
1644        let cached_relative = cached_records
1645            .iter()
1646            .map(freshness_record_relative_key)
1647            .collect::<BTreeSet<_>>();
1648
1649        // The project walk is part of every identity check, including a negative
1650        // verdict. It detects additions and removals that per-record metadata
1651        // cannot observe, and gives all callers the same gitignore-aware file set.
1652        let project_scope = JobScope::for_project(snapshot.project_root.clone());
1653        let project_files = scope_files(&snapshot.project_root, &project_scope);
1654        let current_by_relative = current_project_files(&snapshot.project_root, &project_files);
1655
1656        let mut records_match = true;
1657        for record in &cached_records {
1658            let absolute = if record.file_path.is_absolute() {
1659                record.file_path.clone()
1660            } else {
1661                snapshot.project_root.join(&record.file_path)
1662            };
1663            match verify_contribution_file(&absolute, &record.freshness) {
1664                ContributionFreshness::Fresh { .. } => {}
1665                ContributionFreshness::Stale | ContributionFreshness::Deleted => {
1666                    records_match = false;
1667                }
1668            }
1669        }
1670
1671        Ok(records_match
1672            && current_by_relative.len() == cached_relative.len()
1673            && current_by_relative
1674                .keys()
1675                .all(|relative| cached_relative.contains(relative)))
1676    }
1677
1678    #[doc(hidden)]
1679    pub fn tier2_run_with_reuse_result(
1680        &self,
1681        snapshot: InspectSnapshot,
1682        category: InspectCategory,
1683        callgraph_snapshot: Option<Arc<CallgraphSnapshot>>,
1684    ) -> InspectResult {
1685        let job = self.tier2_reuse_job(snapshot, category, callgraph_snapshot);
1686        self.tier2_run_with_reuse_job_result(job)
1687    }
1688
1689    fn tier2_run_with_reuse_job_result(&self, job: InspectJob) -> InspectResult {
1690        self.tier2_run_with_reuse_job_result_with_options(job, Tier2ReuseOptions::default())
1691    }
1692
1693    fn tier2_run_with_reuse_job_result_catching(
1694        &self,
1695        job: InspectJob,
1696        options: Tier2ReuseOptions,
1697    ) -> InspectResult {
1698        let started = Instant::now();
1699        match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1700            self.tier2_run_with_reuse_job_result_with_options(job.clone(), options)
1701        })) {
1702            Ok(result) => result,
1703            Err(_) => InspectResult::failed(
1704                &job,
1705                "tier2 reuse worker panicked before completion",
1706                started.elapsed(),
1707            ),
1708        }
1709    }
1710
1711    fn tier2_run_with_reuse_job_result_with_options(
1712        &self,
1713        mut job: InspectJob,
1714        mut options: Tier2ReuseOptions,
1715    ) -> InspectResult {
1716        let started = Instant::now();
1717        self.reuse_starts.fetch_add(1, Ordering::SeqCst);
1718        self.wait_for_tier2_reuse_waiter_for_debug(&job);
1719        panic_tier2_reuse_for_debug(&job);
1720        if !job.category.is_active() {
1721            let result = InspectResult::failed(
1722                &job,
1723                format!("inspect category '{}' is disabled in v0.33", job.category),
1724                started.elapsed(),
1725            );
1726            log_tier2_benchmark_category_end(&result);
1727            return result;
1728        }
1729        if !job.category.is_tier2() {
1730            let result = InspectResult::failed(
1731                &job,
1732                format!(
1733                    "inspect category '{}' is not a Tier 2 category",
1734                    job.category
1735                ),
1736                started.elapsed(),
1737            );
1738            log_tier2_benchmark_category_end(&result);
1739            return result;
1740        }
1741
1742        if !job.inspect_writer {
1743            let result = InspectResult::failed(
1744                &job,
1745                "inspect writer capability is unavailable for this read-only cache path",
1746                started.elapsed(),
1747            );
1748            log_tier2_benchmark_category_end(&result);
1749            return result;
1750        }
1751
1752        let project_scope = JobScope::for_project(job.project_root.clone());
1753        job.scope_files = scope_files(&job.project_root, &project_scope);
1754        log_tier2_benchmark_category_start(&job);
1755        let cache = match self.cache_for_paths(job.inspect_dir.clone(), job.project_root.clone()) {
1756            Ok(cache) => cache,
1757            Err(message) => {
1758                let result = InspectResult::failed(&job, message, started.elapsed());
1759                log_tier2_benchmark_category_end(&result);
1760                return result;
1761            }
1762        };
1763        delay_tier2_reuse_for_debug(&job.project_root);
1764        if options.has_force_paths() {
1765            if let Ok(cached) = load_contribution_freshness(cache.as_ref(), job.category) {
1766                let (remaining, downgraded) = downgrade_unchanged_forced_paths_with_freshness(
1767                    &job.project_root,
1768                    &cached,
1769                    options.force_rescan_paths.iter().cloned().collect(),
1770                );
1771                options.force_rescan_paths = remaining.into_iter().collect();
1772                if downgraded > 0 {
1773                    crate::slog_info!(
1774                        "inspect: {} forced paths downgraded to cached (content unchanged)",
1775                        downgraded
1776                    );
1777                }
1778            }
1779        }
1780        if !options.has_force_paths() {
1781            if let Ok(Some(success)) =
1782                self.tier2_quick_reuse_success(&job, cache.as_ref(), &options)
1783            {
1784                let result = InspectResult::success(&job, success, started.elapsed());
1785                crate::slog_debug!(
1786                    "perf tier2 category={} reuse=hit ms={}",
1787                    job.category,
1788                    started.elapsed().as_millis()
1789                );
1790                log_tier2_benchmark_category_end(&result);
1791                return result;
1792            }
1793        }
1794
1795        // Automatic scans use the background seed gate to serialize their work.
1796        // A blocking inspect that proves it needs real work joins the interactive
1797        // class instead: it never preempts an in-flight build, but it takes a
1798        // released slot before another maintenance build can extend the wait.
1799        let _interactive_permit = if options.interactive {
1800            let queued_state = if self.semantic_cold_seed_active.load(Ordering::SeqCst) {
1801                InspectBuilderState::GatedBySemanticSeed
1802            } else {
1803                InspectBuilderState::QueuedBehindColdBuilds
1804            };
1805            self.set_builder_state(&job.key, queued_state);
1806            let request = cold_build_limiter::ColdBuildAdmissionRequest::new(
1807                format!("inspect:{}:{}", job.project_root.display(), job.job_id),
1808                cold_build_limiter::ColdBuildAdmissionClass::InspectTriggered,
1809            );
1810            let permit = cold_build_limiter::acquire_blocking_while_cancellable_with_limiter(
1811                &self.cold_build_limiter(),
1812                "explicit inspect Tier-2 run",
1813                request,
1814                || self.heavy_root_work_allowed(),
1815                || {
1816                    crate::executor::current_job_cancellation()
1817                        .is_some_and(|token| token.cancel_requested_before_commit())
1818                },
1819            );
1820            let Some(permit) = permit else {
1821                let result = InspectResult::failed(
1822                    &job,
1823                    "explicit inspect Tier-2 cold-build admission was cancelled",
1824                    started.elapsed(),
1825                );
1826                log_tier2_benchmark_category_end(&result);
1827                return result;
1828            };
1829            self.set_builder_state(&job.key, InspectBuilderState::Building);
1830            Some(permit)
1831        } else {
1832            None
1833        };
1834
1835        let result = match self.tier2_run_with_reuse_job(&job, &cache, &options) {
1836            Ok(success) => InspectResult::success(&job, success, started.elapsed()),
1837            Err(message) => InspectResult::failed(&job, message, started.elapsed()),
1838        };
1839        // Always-on perf line: a full (reuse=miss) scan is the expensive path —
1840        // for dead_code it includes store snapshot projection plus the scanner.
1841        // ms here lets us attribute background CPU bursts to a specific category from the log.
1842        crate::slog_info!(
1843            "perf tier2 category={} reuse=miss ms={}",
1844            job.category,
1845            started.elapsed().as_millis()
1846        );
1847        log_tier2_benchmark_category_end(&result);
1848        result
1849    }
1850
1851    fn tier2_reuse_job(
1852        &self,
1853        snapshot: InspectSnapshot,
1854        category: InspectCategory,
1855        callgraph_snapshot: Option<Arc<CallgraphSnapshot>>,
1856    ) -> InspectJob {
1857        InspectJob {
1858            job_id: self.next_job_id.fetch_add(1, Ordering::Relaxed),
1859            key: JobKey::for_project_category(category),
1860            category,
1861            scope_files: Vec::new(),
1862            project_root: snapshot.project_root,
1863            inspect_dir: snapshot.inspect_dir,
1864            config: snapshot.config,
1865            symbol_cache: snapshot.symbol_cache,
1866            inspect_writer: snapshot.inspect_writer,
1867            callgraph_writer: snapshot.callgraph_writer,
1868            callgraph_snapshot,
1869        }
1870    }
1871
1872    fn tier2_quick_reuse_success(
1873        &self,
1874        job: &InspectJob,
1875        cache: &InspectCache,
1876        options: &Tier2ReuseOptions,
1877    ) -> Result<Option<InspectScanSuccess>, String> {
1878        let cached_records = load_contribution_freshness(cache, job.category)?;
1879        let current_by_relative = current_project_files(&job.project_root, &job.scope_files);
1880        if cached_records.len() != current_by_relative.len() {
1881            return Ok(None);
1882        }
1883        for record in &cached_records {
1884            let relative = freshness_record_relative_key(record);
1885            let Some(current_file) = current_by_relative.get(&relative) else {
1886                return Ok(None);
1887            };
1888            match cache_freshness::metadata_matches(current_file, &record.freshness) {
1889                Ok(true) => {}
1890                Ok(false) => return Ok(None),
1891                Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
1892                Err(error) => {
1893                    return Err(format!(
1894                        "failed to stat {} for tier2 quick reuse: {error}",
1895                        current_file.display()
1896                    ));
1897                }
1898            }
1899        }
1900
1901        let contribution_set_hash = cache
1902            .contribution_set_hash_for_config(job.category, job.config.as_ref())
1903            .map_err(|error| error.to_string())?;
1904        let Some(aggregate) = cache
1905            .load_aggregate_if_hash_matches(job.category, &contribution_set_hash)
1906            .map_err(|error| error.to_string())?
1907        else {
1908            return Ok(None);
1909        };
1910        if !cached_tier2_aggregate_usable(job.category, options, &aggregate) {
1911            return Ok(None);
1912        }
1913
1914        cache
1915            .touch_tier2_last_full_run(job.category)
1916            .map_err(|error| error.to_string())?;
1917        Ok(Some(InspectScanSuccess {
1918            scanned_files: Vec::new(),
1919            contributions: Vec::new(),
1920            aggregate,
1921        }))
1922    }
1923
1924    #[allow(clippy::too_many_lines)]
1925    fn tier2_run_with_reuse_job(
1926        &self,
1927        job: &InspectJob,
1928        cache: &InspectCache,
1929        options: &Tier2ReuseOptions,
1930    ) -> Result<InspectScanSuccess, String> {
1931        let mut phases = Tier2PhaseTimings::default();
1932        let phase_started = Instant::now();
1933        let cached_records = load_contribution_freshness(cache, job.category)?;
1934        let current_by_relative = current_project_files(&job.project_root, &job.scope_files);
1935        let cached_relative = cached_records
1936            .iter()
1937            .map(freshness_record_relative_key)
1938            .collect::<BTreeSet<_>>();
1939        let force_relative = forced_relative_paths(job, &options.force_rescan_paths);
1940        let cold_cache = cached_relative.is_empty();
1941        #[cfg(debug_assertions)]
1942        let debug_cold_cache = cold_cache;
1943
1944        let mut updates = Tier2ContributionUpdates::default();
1945        let mut scan_by_relative = BTreeMap::<String, PathBuf>::new();
1946        let require_callgraph_refresh =
1947            if job.category == InspectCategory::DeadCode && options.require_callgraph_snapshot {
1948                !cache
1949                    .get_aggregated_for_config(&job.key, job.config.as_ref())
1950                    .map_err(|error| error.to_string())?
1951                    .is_some_and(|aggregate| {
1952                        aggregate
1953                            .get("callgraph_available")
1954                            .and_then(Value::as_bool)
1955                            == Some(true)
1956                    })
1957            } else {
1958                false
1959            };
1960        let mut callgraph_refresh_paths = options
1961            .force_rescan_paths
1962            .iter()
1963            .filter(|path| callgraph_store_indexes_path(path))
1964            .cloned()
1965            .collect::<BTreeSet<_>>();
1966        if require_callgraph_refresh {
1967            callgraph_refresh_paths.extend(
1968                current_by_relative
1969                    .values()
1970                    .filter(|path| callgraph_store_indexes_path(path))
1971                    .cloned(),
1972            );
1973        }
1974        let mut aggregate_job = job.clone();
1975
1976        for record in cached_records {
1977            let relative = freshness_record_relative_key(&record);
1978            let relative_path = PathBuf::from(&relative);
1979            let Some(current_file) = current_by_relative.get(&relative) else {
1980                updates.deletes.push(relative_path);
1981                insert_callgraph_refresh_path(
1982                    &mut callgraph_refresh_paths,
1983                    job.project_root.join(&relative),
1984                );
1985                continue;
1986            };
1987
1988            if force_relative.contains(&relative) {
1989                updates.deletes.push(relative_path);
1990                scan_by_relative.insert(relative, current_file.clone());
1991                insert_callgraph_refresh_path(&mut callgraph_refresh_paths, current_file.clone());
1992                continue;
1993            }
1994
1995            let absolute = job.project_root.join(&record.file_path);
1996            match verify_contribution_file(&absolute, &record.freshness) {
1997                ContributionFreshness::Fresh {
1998                    metadata_changed,
1999                    freshness,
2000                } => {
2001                    if metadata_changed {
2002                        updates.metadata_updates.push((relative_path, freshness));
2003                    }
2004                }
2005                ContributionFreshness::Stale => {
2006                    updates.deletes.push(relative_path);
2007                    scan_by_relative.insert(relative, current_file.clone());
2008                    insert_callgraph_refresh_path(
2009                        &mut callgraph_refresh_paths,
2010                        current_file.clone(),
2011                    );
2012                }
2013                ContributionFreshness::Deleted => {
2014                    updates.deletes.push(relative_path);
2015                    insert_callgraph_refresh_path(
2016                        &mut callgraph_refresh_paths,
2017                        job.project_root.join(&record.file_path),
2018                    );
2019                }
2020            }
2021        }
2022
2023        for (relative, file) in &current_by_relative {
2024            if !cached_relative.contains(relative) {
2025                scan_by_relative.insert(relative.clone(), file.clone());
2026                if !cold_cache {
2027                    insert_callgraph_refresh_path(&mut callgraph_refresh_paths, file.clone());
2028                }
2029            }
2030        }
2031        phases.freshness = phase_started.elapsed();
2032
2033        let mut scan_files = scan_by_relative.into_values().collect::<Vec<_>>();
2034        let force_reparse_files = scan_files.clone();
2035        let callgraph_refresh_files = callgraph_refresh_paths.into_iter().collect::<Vec<_>>();
2036        let dead_code_callgraph_refresh =
2037            job.category == InspectCategory::DeadCode && !callgraph_refresh_files.is_empty();
2038        if !scan_files.is_empty() {
2039            let mut scan_job = job.clone();
2040            scan_job.job_id = self.next_job_id.fetch_add(1, Ordering::Relaxed);
2041            scan_job.scope_files = scan_files.clone();
2042            if scan_job.category == InspectCategory::DeadCode
2043                && scan_job.callgraph_snapshot.is_none()
2044            {
2045                let snapshot_started = Instant::now();
2046                scan_job.callgraph_snapshot = self.build_tier2_callgraph_snapshot_with_refresh(
2047                    &scan_job,
2048                    options.allow_callgraph_cold_build,
2049                    options.require_callgraph_snapshot,
2050                    &callgraph_refresh_files,
2051                );
2052                phases.snapshot += snapshot_started.elapsed();
2053            }
2054            aggregate_job.callgraph_snapshot = scan_job.callgraph_snapshot.clone();
2055            #[cfg(debug_assertions)]
2056            if debug_cold_cache {
2057                std::thread::sleep(Duration::from_millis(10));
2058            }
2059            let scan_started = Instant::now();
2060            let oxc_result =
2061                self.oxc_result_for_scan(&scan_job, &scan_job.scope_files, &force_reparse_files)?;
2062            let scan_result = run_tier2_scan(&scan_job, oxc_result.as_ref());
2063            phases.scan += scan_started.elapsed();
2064            phases.scanned_files += scan_files.len();
2065            let scan_success = scan_result.outcome.map_err(|message| {
2066                format!("{} incremental scan failed: {message}", job.category)
2067            })?;
2068            updates.upserts.extend(scan_success.contributions);
2069        }
2070
2071        let has_updates = !updates.upserts.is_empty()
2072            || !updates.deletes.is_empty()
2073            || !updates.metadata_updates.is_empty();
2074        if !has_updates && !dead_code_callgraph_refresh {
2075            if let Some(aggregate) = cache
2076                .get_aggregated_for_config(&job.key, job.config.as_ref())
2077                .map_err(|error| error.to_string())?
2078            {
2079                if cached_tier2_aggregate_usable(job.category, options, &aggregate) {
2080                    cache
2081                        .touch_tier2_last_full_run(job.category)
2082                        .map_err(|error| error.to_string())?;
2083                    phases.log(job.category);
2084                    return Ok(InspectScanSuccess {
2085                        scanned_files: scan_files,
2086                        contributions: Vec::new(),
2087                        aggregate,
2088                    });
2089                }
2090            }
2091        }
2092
2093        let db_started = Instant::now();
2094        let mut contribution_set_hash = if has_updates {
2095            let (hash, db_timings) = cache
2096                .apply_contribution_updates_for_config(job.category, updates, job.config.as_ref())
2097                .map_err(|error| error.to_string())?;
2098            phases.add_db_timings(db_timings);
2099            hash
2100        } else {
2101            cache
2102                .contribution_set_hash_for_config(job.category, job.config.as_ref())
2103                .map_err(|error| error.to_string())?
2104        };
2105        phases.db = db_started.elapsed();
2106
2107        if !dead_code_callgraph_refresh {
2108            if let Some(aggregate) = cache
2109                .load_aggregate_if_hash_matches(job.category, &contribution_set_hash)
2110                .map_err(|error| error.to_string())?
2111            {
2112                if cached_tier2_aggregate_usable(job.category, options, &aggregate) {
2113                    cache
2114                        .touch_tier2_last_full_run(job.category)
2115                        .map_err(|error| error.to_string())?;
2116                    let contributions = load_contributions(cache, job)?;
2117                    phases.log(job.category);
2118                    return Ok(InspectScanSuccess {
2119                        scanned_files: scan_files,
2120                        contributions,
2121                        aggregate,
2122                    });
2123                }
2124            }
2125        }
2126
2127        let refresh_dead_code_facts = if job.category == InspectCategory::DeadCode {
2128            dead_code_contributions_need_fact_refresh(cache, job)?
2129        } else {
2130            false
2131        };
2132        let refresh_unused_exports_facts = if job.category == InspectCategory::UnusedExports {
2133            unused_exports_contributions_need_fact_refresh(cache, job)?
2134        } else {
2135            false
2136        };
2137        let refresh_duplicates_facts = if job.category == InspectCategory::Duplicates {
2138            duplicates_contributions_need_fact_refresh(cache, job)?
2139        } else {
2140            false
2141        };
2142        if refresh_dead_code_facts || refresh_unused_exports_facts || refresh_duplicates_facts {
2143            // Raw-facts contributions can be rolled up after manifest/resolver
2144            // edits without re-reading source. Only legacy verdict-bearing or
2145            // facts-version-mismatched caches need a one-time full refresh before
2146            // verdicts/roots can be recomputed globally.
2147            let full_scan_files = current_by_relative.into_values().collect::<Vec<_>>();
2148            if !full_scan_files.is_empty() {
2149                let mut rescan_job = job.clone();
2150                rescan_job.job_id = self.next_job_id.fetch_add(1, Ordering::Relaxed);
2151                rescan_job.scope_files = full_scan_files.clone();
2152                if rescan_job.category == InspectCategory::DeadCode
2153                    && rescan_job.callgraph_snapshot.is_none()
2154                {
2155                    let snapshot_started = Instant::now();
2156                    rescan_job.callgraph_snapshot = self
2157                        .build_tier2_callgraph_snapshot_with_refresh(
2158                            &rescan_job,
2159                            options.allow_callgraph_cold_build,
2160                            options.require_callgraph_snapshot,
2161                            &callgraph_refresh_files,
2162                        );
2163                    phases.snapshot += snapshot_started.elapsed();
2164                }
2165                let scan_started = Instant::now();
2166                let oxc_result = self.oxc_result_for_scan(
2167                    &rescan_job,
2168                    &rescan_job.scope_files,
2169                    &force_reparse_files,
2170                )?;
2171                let scan_result = run_tier2_scan(&rescan_job, oxc_result.as_ref());
2172                phases.scan += scan_started.elapsed();
2173                phases.scanned_files += full_scan_files.len();
2174                let scan_success = scan_result.outcome.map_err(|message| {
2175                    format!(
2176                        "{} full rescan after entry-point cache miss failed: {message}",
2177                        job.category
2178                    )
2179                })?;
2180                let rescan_updates = Tier2ContributionUpdates {
2181                    upserts: scan_success.contributions,
2182                    ..Tier2ContributionUpdates::default()
2183                };
2184                let db_started = Instant::now();
2185                let (hash, db_timings) = cache
2186                    .apply_contribution_updates_for_config(
2187                        job.category,
2188                        rescan_updates,
2189                        job.config.as_ref(),
2190                    )
2191                    .map_err(|error| error.to_string())?;
2192                contribution_set_hash = hash;
2193                phases.add_db_timings(db_timings);
2194                phases.db += db_started.elapsed();
2195                aggregate_job.callgraph_snapshot = rescan_job.callgraph_snapshot.clone();
2196                scan_files = full_scan_files;
2197
2198                if !dead_code_callgraph_refresh {
2199                    if let Some(aggregate) = cache
2200                        .load_aggregate_if_hash_matches(job.category, &contribution_set_hash)
2201                        .map_err(|error| error.to_string())?
2202                    {
2203                        if cached_tier2_aggregate_usable(job.category, options, &aggregate) {
2204                            cache
2205                                .touch_tier2_last_full_run(job.category)
2206                                .map_err(|error| error.to_string())?;
2207                            let contributions = load_contributions(cache, job)?;
2208                            phases.log(job.category);
2209                            return Ok(InspectScanSuccess {
2210                                scanned_files: scan_files,
2211                                contributions,
2212                                aggregate,
2213                            });
2214                        }
2215                    }
2216                }
2217            }
2218        }
2219
2220        if aggregate_job.category == InspectCategory::DeadCode
2221            && aggregate_job.callgraph_snapshot.is_none()
2222        {
2223            let snapshot_started = Instant::now();
2224            aggregate_job.callgraph_snapshot = self.build_tier2_callgraph_snapshot_with_refresh(
2225                &aggregate_job,
2226                options.allow_callgraph_cold_build,
2227                options.require_callgraph_snapshot,
2228                &callgraph_refresh_files,
2229            );
2230            phases.snapshot += snapshot_started.elapsed();
2231        }
2232        if options.require_callgraph_snapshot
2233            && aggregate_job.category == InspectCategory::DeadCode
2234            && aggregate_job.callgraph_snapshot.is_none()
2235        {
2236            return Err(format!(
2237                "tier2 dead_code aggregate did not complete; builder_state={}",
2238                self.builder_state_detail_for_job(job)
2239            ));
2240        }
2241        let rollup_started = Instant::now();
2242        let contributions = load_contributions(cache, &aggregate_job)?;
2243        let aggregate = roll_up_tier2_contributions(&aggregate_job, &contributions);
2244        cache
2245            .store_tier2_aggregate(job.key.clone(), &contribution_set_hash, aggregate.clone())
2246            .map_err(|error| error.to_string())?;
2247        phases.rollup = rollup_started.elapsed();
2248        phases.log(job.category);
2249
2250        Ok(InspectScanSuccess {
2251            scanned_files: scan_files,
2252            contributions,
2253            aggregate,
2254        })
2255    }
2256
2257    fn enqueue_with_waiter(
2258        &self,
2259        snapshot: InspectSnapshot,
2260        category: InspectCategory,
2261        caller_scope: JobScope,
2262        key: JobKey,
2263        waiter_tx: WaiterTx,
2264        callgraph_snapshot: Option<Arc<CallgraphSnapshot>>,
2265    ) -> Result<(), String> {
2266        let mut in_flight = self
2267            .in_flight
2268            .lock()
2269            .map_err(|_| "inspect in-flight map lock poisoned".to_string())?;
2270        if let Some(waiters) = in_flight.get_mut(&key) {
2271            waiters.push(Waiter { tx: waiter_tx });
2272            return Ok(());
2273        }
2274
2275        in_flight.insert(key.clone(), vec![Waiter { tx: waiter_tx }]);
2276        drop(in_flight);
2277        self.record_flight_start(&key);
2278
2279        if let Err(message) = self.enqueue_new_job(
2280            snapshot,
2281            category,
2282            caller_scope,
2283            key.clone(),
2284            callgraph_snapshot,
2285        ) {
2286            if let Ok(mut in_flight) = self.in_flight.lock() {
2287                in_flight.remove(&key);
2288            }
2289            self.clear_builder_state(&key);
2290            return Err(message);
2291        }
2292        Ok(())
2293    }
2294
2295    fn enqueue_without_waiter(
2296        &self,
2297        snapshot: InspectSnapshot,
2298        category: InspectCategory,
2299        caller_scope: JobScope,
2300        key: JobKey,
2301        callgraph_snapshot: Option<Arc<CallgraphSnapshot>>,
2302    ) -> Result<(), String> {
2303        let mut in_flight = self
2304            .in_flight
2305            .lock()
2306            .map_err(|_| "inspect in-flight map lock poisoned".to_string())?;
2307        if in_flight.contains_key(&key) {
2308            return Ok(());
2309        }
2310        in_flight.insert(key.clone(), Vec::new());
2311        drop(in_flight);
2312        self.record_flight_start(&key);
2313
2314        if let Err(message) = self.enqueue_new_job(
2315            snapshot,
2316            category,
2317            caller_scope,
2318            key.clone(),
2319            callgraph_snapshot,
2320        ) {
2321            if let Ok(mut in_flight) = self.in_flight.lock() {
2322                in_flight.remove(&key);
2323            }
2324            self.clear_builder_state(&key);
2325            return Err(message);
2326        }
2327        Ok(())
2328    }
2329
2330    fn enqueue_new_job(
2331        &self,
2332        snapshot: InspectSnapshot,
2333        category: InspectCategory,
2334        caller_scope: JobScope,
2335        key: JobKey,
2336        callgraph_snapshot: Option<Arc<CallgraphSnapshot>>,
2337    ) -> Result<(), String> {
2338        let scan_scope = if category.is_tier2() {
2339            JobScope::for_project(snapshot.project_root.clone())
2340        } else {
2341            caller_scope
2342        };
2343        let scope_files = scope_files(&snapshot.project_root, &scan_scope);
2344        let job = InspectJob {
2345            job_id: self.next_job_id.fetch_add(1, Ordering::Relaxed),
2346            key,
2347            category,
2348            scope_files,
2349            project_root: snapshot.project_root,
2350            inspect_dir: snapshot.inspect_dir,
2351            config: snapshot.config,
2352            symbol_cache: snapshot.symbol_cache,
2353            inspect_writer: snapshot.inspect_writer,
2354            callgraph_writer: snapshot.callgraph_writer,
2355            callgraph_snapshot,
2356        };
2357        self.request_tx
2358            .send(job)
2359            .map_err(|_| "inspect dispatch loop is unavailable".to_string())
2360    }
2361
2362    fn wait_for_outcome(
2363        &self,
2364        key: JobKey,
2365        caller_scope: JobScope,
2366        cache: Arc<InspectCache>,
2367        waiter_rx: Receiver<JobOutcome>,
2368        snapshot: InspectSnapshot,
2369    ) -> JobOutcome {
2370        let timeout = after(self.soft_deadline);
2371        let result_rx = self.result_rx.clone();
2372        loop {
2373            select! {
2374                recv(waiter_rx) -> outcome => {
2375                    return match outcome {
2376                        Ok(outcome) => filter_outcome_for_scope_with_contributions(
2377                            outcome,
2378                            &snapshot,
2379                            key.category,
2380                            cache.as_ref(),
2381                            &caller_scope,
2382                        ),
2383                        Err(_) => self.timeout_outcome(&key, &caller_scope, &cache, &snapshot),
2384                    };
2385                }
2386                recv(result_rx) -> result => {
2387                    match result {
2388                        Ok(result) => self.route_completion(result),
2389                        Err(_) => return self.timeout_outcome(&key, &caller_scope, &cache, &snapshot),
2390                    }
2391                }
2392                recv(timeout) -> _ => {
2393                    return self.timeout_outcome(&key, &caller_scope, &cache, &snapshot);
2394                }
2395            }
2396        }
2397    }
2398
2399    fn timeout_outcome(
2400        &self,
2401        key: &JobKey,
2402        caller_scope: &JobScope,
2403        cache: &(impl InspectCacheRead + ?Sized),
2404        snapshot: &InspectSnapshot,
2405    ) -> JobOutcome {
2406        match cache.get_aggregated_for_config(key, snapshot.config.as_ref()) {
2407            Ok(Some(cached)) => filter_outcome_for_scope_with_contributions(
2408                JobOutcome::Stale {
2409                    cached: Some(cached),
2410                    in_flight: true,
2411                },
2412                snapshot,
2413                key.category,
2414                cache,
2415                caller_scope,
2416            ),
2417            Ok(None) => JobOutcome::Pending { in_flight: true },
2418            Err(error) => JobOutcome::Failed {
2419                message: error.to_string(),
2420            },
2421        }
2422    }
2423
2424    fn route_completion(&self, result: InspectResult) {
2425        let outcome = self.completion_outcome(result.clone());
2426        self.record_builder_attempt_outcome(&result.key, &outcome);
2427        let waiters = self
2428            .in_flight
2429            .lock()
2430            .ok()
2431            .and_then(|mut in_flight| in_flight.remove(&result.key))
2432            .unwrap_or_default();
2433        for waiter in waiters {
2434            let _ = waiter.tx.send(outcome.clone());
2435        }
2436    }
2437
2438    fn route_tier2_reuse_completion(&self, result: InspectResult) {
2439        let outcome = match result.outcome.clone() {
2440            Ok(success) => JobOutcome::Fresh {
2441                payload: success.aggregate,
2442            },
2443            Err(message) => JobOutcome::Failed { message },
2444        };
2445        // Publish completion before waking waiters so a direct-reuse caller sees all
2446        // completion side effects when its result channel becomes ready. The same
2447        // finish path runs from the exit guard if this router is skipped.
2448        self.finish_tier2_flight(&result.key, outcome);
2449        // The counter also signals the main-thread drain that a background
2450        // (watcher-driven) Tier-2 scan finished. This path bypasses
2451        // `result_rx`/`drain_completions`, so without this signal the bar's
2452        // counts and `~` marker would only update on a manual `aft_inspect`.
2453    }
2454
2455    /// Snapshot the cumulative count of reuse-path (watcher-driven) Tier-2
2456    /// completions. The main-thread drain compares this against its last-seen
2457    /// value to detect background scans that finished since the previous tick.
2458    pub fn reuse_completion_count(&self) -> u64 {
2459        self.reuse_completions.load(Ordering::SeqCst)
2460    }
2461
2462    #[doc(hidden)]
2463    pub fn reuse_start_count_for_test(&self) -> u64 {
2464        self.reuse_starts.load(Ordering::SeqCst)
2465    }
2466
2467    fn completion_outcome(&self, result: InspectResult) -> JobOutcome {
2468        let cache =
2469            match self.cache_for_paths(result.inspect_dir.clone(), result.project_root.clone()) {
2470                Ok(cache) => cache,
2471                Err(message) => return JobOutcome::Failed { message },
2472            };
2473
2474        match result.outcome {
2475            Ok(success) => {
2476                let store_result = if result.category.is_tier2() {
2477                    cache.store_tier2_result_for_config(
2478                        result.key.clone(),
2479                        &success.scanned_files,
2480                        &success.contributions,
2481                        success.aggregate.clone(),
2482                        result.config.as_ref(),
2483                    )
2484                } else {
2485                    cache.store_aggregated(result.key, success.aggregate.clone())
2486                };
2487
2488                match store_result {
2489                    Ok(()) => JobOutcome::Fresh {
2490                        payload: success.aggregate,
2491                    },
2492                    Err(error) => JobOutcome::Failed {
2493                        message: error.to_string(),
2494                    },
2495                }
2496            }
2497            Err(message) => JobOutcome::Failed { message },
2498        }
2499    }
2500}
2501
2502impl Default for InspectManager {
2503    fn default() -> Self {
2504        Self::new()
2505    }
2506}
2507
2508fn validate_tier2_read_category(category: InspectCategory) -> Result<(), JobOutcome> {
2509    if !category.is_active() {
2510        return Err(JobOutcome::Failed {
2511            message: format!("inspect category '{category}' is disabled in v0.33"),
2512        });
2513    }
2514    if !category.is_tier2() {
2515        return Err(JobOutcome::Failed {
2516            message: format!("inspect category '{category}' is not a Tier 2 category"),
2517        });
2518    }
2519    Ok(())
2520}
2521
2522/// Phase-level wall-time attribution for one Tier-2 reuse=miss pass.
2523///
2524/// Exists to self-attribute pathological scans (e.g. a normally-100ms
2525/// unused_exports pass once took 677s under heavy machine load) without
2526/// needing a lucky live `sample`. Logged as ONE info line per pass, only when
2527/// real work happened (freshness/scan/snapshot/rollup/db), so quiet reuse passes stay silent.
2528#[derive(Default)]
2529struct Tier2PhaseTimings {
2530    /// Freshness verification of cached contributions (file stat + hash reads).
2531    freshness: Duration,
2532    /// Callgraph store snapshot projection (dead_code only).
2533    snapshot: Duration,
2534    /// Scanner compute over files needing (re)scan.
2535    scan: Duration,
2536    /// SQLite contribution upserts/deletes, including connection lock wait.
2537    db: Duration,
2538    /// Time waiting for the shared SQLite connection mutex.
2539    db_lock: Duration,
2540    /// Time spent in contribution update transactions after acquiring the mutex.
2541    db_txn: Duration,
2542    /// Aggregate roll-up + store.
2543    rollup: Duration,
2544    scanned_files: usize,
2545}
2546
2547impl Tier2PhaseTimings {
2548    fn add_db_timings(&mut self, timings: InspectDbTimings) {
2549        self.db_lock += timings.lock_wait;
2550        self.db_txn += timings.transaction;
2551    }
2552
2553    fn log(&self, category: InspectCategory) {
2554        let worked = self.freshness + self.scan + self.snapshot + self.rollup + self.db;
2555        if !worked.is_zero() {
2556            crate::logging::note_tier2_scan(
2557                category.to_string(),
2558                worked.as_millis().min(u128::from(u64::MAX)) as u64,
2559            );
2560        }
2561        if worked < Duration::from_millis(50) {
2562            return;
2563        }
2564        crate::slog_info!(
2565            "perf tier2 phases category={} freshness={}ms snapshot={}ms scan={}ms({} files) db={}ms(lock={},txn={}) rollup={}ms",
2566            category,
2567            self.freshness.as_millis(),
2568            self.snapshot.as_millis(),
2569            self.scan.as_millis(),
2570            self.scanned_files,
2571            self.db.as_millis(),
2572            self.db_lock.as_millis(),
2573            self.db_txn.as_millis(),
2574            self.rollup.as_millis()
2575        );
2576    }
2577}
2578
2579fn scope_files(project_root: &Path, scope: &JobScope) -> Vec<PathBuf> {
2580    let mut files = crate::callgraph::walk_project_files(project_root)
2581        .filter(|path| scope.contains(path))
2582        .collect::<Vec<_>>();
2583    files.sort();
2584    files
2585}
2586
2587fn forced_relative_paths(job: &InspectJob, paths: &BTreeSet<PathBuf>) -> BTreeSet<String> {
2588    let mut keys = BTreeSet::new();
2589    for path in paths {
2590        let absolute = if path.is_absolute() {
2591            path.clone()
2592        } else {
2593            job.project_root.join(path)
2594        };
2595        keys.insert(relative_cache_key(&job.project_root, &absolute));
2596        // Normalized, not bare-canonical: the project root is verbatim-stripped,
2597        // so a verbatim canonical path would fail strip_prefix and produce an
2598        // absolute key no cached contribution matches (the forced rescan then
2599        // silently misses).
2600        keys.insert(relative_cache_key(
2601            &job.project_root,
2602            &crate::inspect::job::canonicalize_normalized(&absolute),
2603        ));
2604    }
2605    keys
2606}
2607
2608fn downgrade_unchanged_forced_paths_with_freshness(
2609    project_root: &Path,
2610    cached: &[CachedContributionFreshness],
2611    paths: Vec<PathBuf>,
2612) -> (Vec<PathBuf>, usize) {
2613    let cached = cached
2614        .iter()
2615        .map(|record| (freshness_record_relative_key(record), record.freshness))
2616        .collect::<BTreeMap<_, _>>();
2617    let mut remaining = Vec::with_capacity(paths.len());
2618    let mut downgraded = 0;
2619
2620    for path in paths {
2621        let absolute = if path.is_absolute() {
2622            path.clone()
2623        } else {
2624            project_root.join(&path)
2625        };
2626        let direct_key = relative_cache_key(project_root, &absolute);
2627        // Same normalized form as forced_relative_paths; see the comment there.
2628        let canonical_key = Some(relative_cache_key(
2629            project_root,
2630            &crate::inspect::job::canonicalize_normalized(&absolute),
2631        ));
2632        let freshness = cached
2633            .get(&direct_key)
2634            .or_else(|| canonical_key.as_ref().and_then(|key| cached.get(key)));
2635        let content_unchanged = freshness.is_some_and(|freshness| {
2636            matches!(
2637                cache_freshness::verify_file_strict(&absolute, freshness),
2638                FreshnessVerdict::HotFresh | FreshnessVerdict::ContentFresh { .. }
2639            )
2640        });
2641        if content_unchanged {
2642            downgraded += 1;
2643        } else {
2644            remaining.push(path);
2645        }
2646    }
2647
2648    (remaining, downgraded)
2649}
2650
2651fn panic_tier2_reuse_for_debug(job: &InspectJob) {
2652    #[cfg(not(debug_assertions))]
2653    let _ = job;
2654    #[cfg(debug_assertions)]
2655    {
2656        if !env_project_root_matches("AFT_TEST_TIER2_REUSE_PANIC_ROOT", &job.project_root) {
2657            return;
2658        }
2659        let should_panic = std::env::var("AFT_TEST_TIER2_REUSE_PANIC_CATEGORY")
2660            .ok()
2661            .is_some_and(|category| category == job.category.as_str());
2662        if should_panic {
2663            panic!("forced tier2 reuse panic for {}", job.category);
2664        }
2665    }
2666}
2667
2668fn delay_tier2_reuse_for_debug(project_root: &Path) {
2669    #[cfg(not(debug_assertions))]
2670    let _ = project_root;
2671    #[cfg(debug_assertions)]
2672    {
2673        if !env_project_root_matches("AFT_TEST_TIER2_REUSE_DELAY_ROOT", project_root) {
2674            return;
2675        }
2676        if let Some(delay_ms) = std::env::var("AFT_TEST_TIER2_REUSE_DELAY_MS")
2677            .ok()
2678            .and_then(|raw| raw.parse::<u64>().ok())
2679        {
2680            std::thread::sleep(Duration::from_millis(delay_ms));
2681        }
2682    }
2683}
2684
2685#[cfg(debug_assertions)]
2686fn env_project_root_matches(var: &str, project_root: &Path) -> bool {
2687    let Some(raw) = std::env::var_os(var) else {
2688        return true;
2689    };
2690    let expected = PathBuf::from(raw);
2691    let expected = std::fs::canonicalize(&expected).unwrap_or(expected);
2692    let actual = std::fs::canonicalize(project_root).unwrap_or_else(|_| project_root.to_path_buf());
2693    expected == actual
2694}
2695
2696fn current_project_files(project_root: &Path, files: &[PathBuf]) -> BTreeMap<String, PathBuf> {
2697    files
2698        .iter()
2699        .map(|file| (relative_cache_key(project_root, file), file.clone()))
2700        .collect()
2701}
2702
2703fn insert_callgraph_refresh_path(paths: &mut BTreeSet<PathBuf>, path: PathBuf) {
2704    if callgraph_store_indexes_path(&path) {
2705        paths.insert(path);
2706    }
2707}
2708
2709fn callgraph_store_indexes_path(path: &Path) -> bool {
2710    crate::parser::detect_language(path).is_some()
2711}
2712
2713fn tier2_benchmark_logging_enabled() -> bool {
2714    std::env::var_os("AFT_SETTLE_BENCH_LOG").is_some()
2715}
2716
2717fn log_tier2_benchmark_category_start(job: &InspectJob) {
2718    if !tier2_benchmark_logging_enabled() {
2719        return;
2720    }
2721    crate::slog_info!(
2722        "settle bench: tier2_category_start category={} job_id={} files={}",
2723        job.category.as_str(),
2724        job.job_id,
2725        job.scope_files.len()
2726    );
2727}
2728
2729fn log_tier2_benchmark_category_end(result: &InspectResult) {
2730    if !tier2_benchmark_logging_enabled() {
2731        return;
2732    }
2733    match &result.outcome {
2734        Ok(success) => {
2735            let count = success
2736                .aggregate
2737                .get("count")
2738                .and_then(serde_json::Value::as_u64)
2739                .unwrap_or(0);
2740            crate::slog_info!(
2741                "settle bench: tier2_category_end category={} job_id={} status=success total_ms={} scanned_files={} contributions={} count={}",
2742                result.category.as_str(),
2743                result.job_id,
2744                result.duration.as_millis(),
2745                success.scanned_files.len(),
2746                success.contributions.len(),
2747                count
2748            );
2749        }
2750        Err(message) => {
2751            crate::slog_info!(
2752                "settle bench: tier2_category_end category={} job_id={} status=failed total_ms={} error={}",
2753                result.category.as_str(),
2754                result.job_id,
2755                result.duration.as_millis(),
2756                message.replace('\n', " ")
2757            );
2758        }
2759    }
2760}
2761
2762fn build_tier2_callgraph_snapshot(
2763    job: &InspectJob,
2764    allow_cold_build: bool,
2765) -> Option<Arc<CallgraphSnapshot>> {
2766    build_tier2_callgraph_snapshot_with_refresh_inner(job, allow_cold_build, false, &[], None)
2767}
2768
2769#[cfg(test)]
2770fn build_tier2_callgraph_snapshot_with_refresh(
2771    job: &InspectJob,
2772    allow_cold_build: bool,
2773    refresh_paths: &[PathBuf],
2774) -> Option<Arc<CallgraphSnapshot>> {
2775    build_tier2_callgraph_snapshot_with_refresh_inner(
2776        job,
2777        allow_cold_build,
2778        false,
2779        refresh_paths,
2780        None,
2781    )
2782}
2783
2784fn open_or_build_blocking_callgraph_store(
2785    callgraph_dir: PathBuf,
2786    project_root: PathBuf,
2787    allow_cold_build: bool,
2788    refresh_paths: &[PathBuf],
2789) -> Result<Option<CallGraphStore>, CallGraphStoreError> {
2790    if let Some(store) =
2791        CallGraphStore::open_ready_repairing(callgraph_dir.clone(), project_root.clone())?
2792    {
2793        return Ok(Some(store));
2794    }
2795    if !allow_cold_build || refresh_paths.is_empty() {
2796        return Ok(None);
2797    }
2798
2799    match CallGraphStore::cold_build_with_lease(
2800        callgraph_dir.clone(),
2801        project_root.clone(),
2802        refresh_paths,
2803    ) {
2804        Ok((store, _)) => Ok(Some(store)),
2805        Err(error @ CallGraphStoreError::Unavailable(_)) => {
2806            // Another actor may own the cold build. A blocking inspect waits for
2807            // its publication instead of turning that transient into a clean zero.
2808            let deadline = Instant::now() + Duration::from_secs(30);
2809            while Instant::now() < deadline {
2810                std::thread::sleep(Duration::from_millis(20));
2811                if let Some(store) = CallGraphStore::open_ready_repairing(
2812                    callgraph_dir.clone(),
2813                    project_root.clone(),
2814                )? {
2815                    return Ok(Some(store));
2816                }
2817            }
2818            Err(error)
2819        }
2820        Err(error) => Err(error),
2821    }
2822}
2823
2824fn merge_callgraph_refresh_paths(
2825    project_root: &Path,
2826    refresh_paths: &[PathBuf],
2827    stale: impl IntoIterator<Item = String>,
2828) -> Vec<PathBuf> {
2829    let mut paths = refresh_paths.to_vec();
2830    for rel in stale {
2831        let absolute = project_root.join(rel);
2832        if !paths.iter().any(|path| path == &absolute) {
2833            paths.push(absolute);
2834        }
2835    }
2836    paths
2837}
2838
2839fn refresh_writable_dead_code_store(
2840    store: &CallGraphStore,
2841    callgraph_dir: &Path,
2842    refresh_paths: &[PathBuf],
2843) {
2844    match store.refresh_files(refresh_paths) {
2845        Ok(stats) => {
2846            crate::slog_info!(
2847                "tier2 dead_code: refreshed callgraph store at {} for {} watcher path(s): changed={} deleted={} refreshed_own={}",
2848                callgraph_dir.display(),
2849                refresh_paths.len(),
2850                stats.changed_files.len(),
2851                stats.deleted_files.len(),
2852                stats.refreshed_own_files
2853            );
2854        }
2855        Err(error) => {
2856            crate::slog_warn!(
2857                "tier2 dead_code: failed to refresh callgraph store at {} before projection: {}",
2858                callgraph_dir.display(),
2859                error
2860            );
2861            if let Err(mark_error) = store.mark_files_stale(refresh_paths) {
2862                crate::slog_warn!(
2863                    "tier2 dead_code: failed to mark callgraph store files stale at {} after refresh failure: {}",
2864                    callgraph_dir.display(),
2865                    mark_error
2866                );
2867            }
2868        }
2869    }
2870}
2871
2872fn open_writable_dead_code_store(
2873    callgraph_dir: PathBuf,
2874    project_root: PathBuf,
2875    allow_cold_build: bool,
2876    build_if_missing: bool,
2877    refresh_paths: &[PathBuf],
2878) -> Result<Option<CallGraphStore>, CallGraphStoreError> {
2879    if build_if_missing {
2880        open_or_build_blocking_callgraph_store(
2881            callgraph_dir,
2882            project_root,
2883            allow_cold_build,
2884            refresh_paths,
2885        )
2886    } else if allow_cold_build {
2887        CallGraphStore::open_ready_repairing(callgraph_dir, project_root)
2888    } else {
2889        CallGraphStore::open_ready_no_rebuild(callgraph_dir, project_root)
2890    }
2891}
2892
2893fn build_tier2_callgraph_snapshot_with_refresh_inner(
2894    job: &InspectJob,
2895    allow_cold_build: bool,
2896    build_if_missing: bool,
2897    refresh_paths: &[PathBuf],
2898    projection_cache: Option<&InspectManager>,
2899) -> Option<Arc<CallgraphSnapshot>> {
2900    let started = Instant::now();
2901    if !job.config.callgraph_store {
2902        crate::slog_info!(
2903            "tier2 dead_code: callgraph store disabled; reporting callgraph_unavailable"
2904        );
2905        return None;
2906    }
2907
2908    let callgraph_dirs = callgraph_store_dirs_from_inspect_dir(&job.inspect_dir, &job.project_root);
2909    if callgraph_dirs.is_empty() {
2910        crate::slog_info!(
2911            "tier2 dead_code: inspect_dir has no root-keyed storage parent ({}); reporting callgraph_unavailable",
2912            job.inspect_dir.display()
2913        );
2914        return None;
2915    };
2916    for callgraph_dir in &callgraph_dirs {
2917        match CallGraphStore::cold_build_suspension(callgraph_dir, &job.project_root) {
2918            Ok(Some(suspension)) => {
2919                // This is a durable admission refusal, not a failed scan attempt.
2920                // Preserve it separately so blocking inspect reports the same
2921                // breaker tuple that navigation and health expose.
2922                if let Some(manager) = projection_cache {
2923                    manager.record_tier2_build_suspension(&job.key, suspension.clone());
2924                }
2925                crate::slog_info!(
2926                    "tier2 dead_code: callgraph build suspended for {} after {} deaths",
2927                    suspension.domain.as_str(),
2928                    suspension.death_count
2929                );
2930                return None;
2931            }
2932            Ok(None) => {}
2933            Err(error) => {
2934                crate::slog_warn!(
2935                    "tier2 dead_code: failed to read callgraph breaker at {}: {}",
2936                    callgraph_dir.display(),
2937                    error
2938                );
2939            }
2940        }
2941    }
2942
2943    enum ProjectionStore {
2944        ReadOnly(ReadonlyCallGraphStore),
2945        Writable(CallGraphStore),
2946    }
2947
2948    impl ProjectionStore {
2949        fn sqlite_path(&self) -> &Path {
2950            match self {
2951                Self::ReadOnly(store) => store.sqlite_path(),
2952                Self::Writable(store) => store.sqlite_path(),
2953            }
2954        }
2955
2956        fn projection_identity(
2957            &self,
2958            project_root: &Path,
2959            write_revision: u64,
2960        ) -> CallgraphProjectionIdentity {
2961            let generation = match self {
2962                Self::ReadOnly(store) => store.projection_generation(),
2963                Self::Writable(store) => store.projection_generation(),
2964            }
2965            .map(str::to_owned);
2966            let legacy_sqlite_path = generation
2967                .is_none()
2968                .then(|| self.sqlite_path().to_path_buf());
2969            CallgraphProjectionIdentity {
2970                project_root: project_root.to_path_buf(),
2971                generation,
2972                legacy_sqlite_path,
2973                write_revision,
2974            }
2975        }
2976
2977        fn current_projection_identity(
2978            &self,
2979            project_root: &Path,
2980        ) -> Result<Option<CallgraphProjectionIdentity>, CallGraphStoreError> {
2981            let write_revision = match self {
2982                Self::ReadOnly(store) => store.projection_write_revision()?,
2983                Self::Writable(store) => store.projection_write_revision()?,
2984            };
2985            Ok(write_revision.map(|revision| self.projection_identity(project_root, revision)))
2986        }
2987    }
2988
2989    for (index, callgraph_dir) in callgraph_dirs.iter().enumerate() {
2990        // Paths without an explicit refresh stay read-only unless the published
2991        // store still has stale backend rows. The background refresh worker is
2992        // the usual writer for those rows; when it never runs for this root,
2993        // dead_code refreshes them inline so projection is not stuck forever.
2994        let projection_store = if refresh_paths.is_empty() || !job.callgraph_writer {
2995            let store = match CallGraphStore::open_readonly(
2996                callgraph_dir.clone(),
2997                job.project_root.clone(),
2998            ) {
2999                Ok(Some(store)) => store,
3000                Ok(None) => {
3001                    crate::slog_info!(
3002                        "tier2 dead_code: callgraph store unavailable at {} (cold/building/not ready); trying fallback={}",
3003                        callgraph_dir.display(),
3004                        index + 1 < callgraph_dirs.len()
3005                    );
3006                    continue;
3007                }
3008                Err(error) => {
3009                    crate::slog_warn!(
3010                        "tier2 dead_code: failed to open callgraph store read-only at {}: {}; trying fallback={}",
3011                        callgraph_dir.display(),
3012                        error,
3013                        index + 1 < callgraph_dirs.len()
3014                    );
3015                    continue;
3016                }
3017            };
3018            let stale = job
3019                .callgraph_writer
3020                .then(|| store.stale_files().ok())
3021                .flatten()
3022                .unwrap_or_default();
3023            if stale.is_empty() {
3024                ProjectionStore::ReadOnly(store)
3025            } else {
3026                drop(store);
3027                let refresh =
3028                    merge_callgraph_refresh_paths(&job.project_root, refresh_paths, stale);
3029                let store = match open_writable_dead_code_store(
3030                    callgraph_dir.clone(),
3031                    job.project_root.clone(),
3032                    allow_cold_build,
3033                    build_if_missing,
3034                    &refresh,
3035                ) {
3036                    Ok(Some(store)) => store,
3037                    Ok(None) => {
3038                        crate::slog_info!(
3039                            "tier2 dead_code: callgraph store unavailable at {} (cold/building/not ready); trying fallback={}",
3040                            callgraph_dir.display(),
3041                            index + 1 < callgraph_dirs.len()
3042                        );
3043                        continue;
3044                    }
3045                    Err(error) => {
3046                        crate::slog_warn!(
3047                            "tier2 dead_code: failed to open callgraph writer at {}: {}; trying fallback={}",
3048                            callgraph_dir.display(),
3049                            error,
3050                            index + 1 < callgraph_dirs.len()
3051                        );
3052                        continue;
3053                    }
3054                };
3055                refresh_writable_dead_code_store(&store, callgraph_dir, &refresh);
3056                ProjectionStore::Writable(store)
3057            }
3058        } else {
3059            let store = match open_writable_dead_code_store(
3060                callgraph_dir.clone(),
3061                job.project_root.clone(),
3062                allow_cold_build,
3063                build_if_missing,
3064                refresh_paths,
3065            ) {
3066                Ok(Some(store)) => store,
3067                Ok(None) => {
3068                    crate::slog_info!(
3069                        "tier2 dead_code: callgraph store unavailable at {} (cold/building/not ready); trying fallback={}",
3070                        callgraph_dir.display(),
3071                        index + 1 < callgraph_dirs.len()
3072                    );
3073                    continue;
3074                }
3075                Err(error) => {
3076                    crate::slog_warn!(
3077                        "tier2 dead_code: failed to open callgraph writer at {}: {}; trying fallback={}",
3078                        callgraph_dir.display(),
3079                        error,
3080                        index + 1 < callgraph_dirs.len()
3081                    );
3082                    continue;
3083                }
3084            };
3085            let stale = store.stale_files().unwrap_or_default();
3086            let refresh = merge_callgraph_refresh_paths(&job.project_root, refresh_paths, stale);
3087            refresh_writable_dead_code_store(&store, callgraph_dir, &refresh);
3088            ProjectionStore::Writable(store)
3089        };
3090
3091        let cache_identity = match projection_store.current_projection_identity(&job.project_root) {
3092            Ok(identity) => identity,
3093            Err(error) => {
3094                crate::slog_warn!(
3095                    "tier2 dead_code: failed to read callgraph projection identity at {}: {}; trying fallback={}",
3096                    callgraph_dir.display(),
3097                    error,
3098                    index + 1 < callgraph_dirs.len()
3099                );
3100                continue;
3101            }
3102        };
3103        if let (Some(cache), Some(identity)) = (projection_cache, cache_identity.as_ref()) {
3104            // The pointer names immutable cold-build generations, while the durable
3105            // revision advances in the same SQLite transaction as every in-place
3106            // graph mutation. Equal identities therefore prove identical store
3107            // bytes for dead-code projection: this cache is exact, not heuristic.
3108            if let Some(snapshot) = cache.cached_callgraph_projection(identity) {
3109                return Some(snapshot);
3110            }
3111        } else if cache_identity.is_none() {
3112            // Stores from older binaries lack a durable revision, so keeping an
3113            // earlier snapshot would make an in-place refresh indistinguishable.
3114            if let Some(cache) = projection_cache {
3115                cache.clear_callgraph_projection();
3116            }
3117        }
3118
3119        let (write_revision, snapshot) = match project_dead_code_snapshot_with_revision(
3120            projection_store.sqlite_path(),
3121        ) {
3122            Ok(projected) => projected,
3123            Err(CallGraphStoreError::Unavailable(message)) => {
3124                crate::slog_info!(
3125                        "tier2 dead_code: callgraph store projection unavailable at {} ({}); trying fallback={}",
3126                        callgraph_dir.display(),
3127                        message,
3128                        index + 1 < callgraph_dirs.len()
3129                    );
3130                continue;
3131            }
3132            Err(error) => {
3133                crate::slog_warn!(
3134                        "tier2 dead_code: callgraph store projection failed at {}: {}; trying fallback={}",
3135                        callgraph_dir.display(),
3136                        error,
3137                        index + 1 < callgraph_dirs.len()
3138                    );
3139                continue;
3140            }
3141        };
3142        let snapshot = Arc::new(snapshot);
3143        if let (Some(cache), Some(write_revision)) = (projection_cache, write_revision) {
3144            cache.cache_callgraph_projection(
3145                projection_store.projection_identity(&job.project_root, write_revision),
3146                Arc::clone(&snapshot),
3147            );
3148        }
3149
3150        if index > 0 {
3151            crate::slog_info!(
3152                "tier2 dead_code: using ready callgraph store fallback {} for inspect_dir {}",
3153                callgraph_dir.display(),
3154                job.inspect_dir.display()
3155            );
3156        }
3157
3158        crate::slog_info!(
3159            "perf tier2_callgraph_snapshot: source=callgraph_store files={} exports={} edges={} entry_points={} ms={}",
3160            snapshot.files.len(),
3161            snapshot.exported_symbols.len(),
3162            snapshot.outbound_calls.len(),
3163            snapshot.entry_points.len(),
3164            started.elapsed().as_millis()
3165        );
3166
3167        return Some(snapshot);
3168    }
3169
3170    crate::slog_info!(
3171        "tier2 dead_code: no ready callgraph store found for inspect_dir {}; reporting callgraph_unavailable",
3172        job.inspect_dir.display()
3173    );
3174    None
3175}
3176
3177fn estimate_callgraph_snapshot_bytes(snapshot: &CallgraphSnapshot) -> u64 {
3178    let files = snapshot.files.iter().fold(0u64, |bytes, path| {
3179        bytes
3180            .saturating_add(std::mem::size_of::<PathBuf>() as u64)
3181            .saturating_add(crate::memory::path_bytes(path))
3182    });
3183    let exports = snapshot
3184        .exported_symbols
3185        .iter()
3186        .fold(0u64, |bytes, export| {
3187            bytes
3188                .saturating_add(std::mem::size_of::<super::job::CallgraphExport>() as u64)
3189                .saturating_add(crate::memory::path_bytes(&export.file))
3190                .saturating_add(crate::memory::usize_to_u64(export.symbol.len()))
3191                .saturating_add(crate::memory::usize_to_u64(export.kind.len()))
3192        });
3193    let calls = snapshot.outbound_calls.iter().fold(0u64, |bytes, call| {
3194        bytes
3195            .saturating_add(std::mem::size_of::<super::job::CallgraphOutboundCall>() as u64)
3196            .saturating_add(crate::memory::path_bytes(&call.caller_file))
3197            .saturating_add(crate::memory::usize_to_u64(call.caller_symbol.len()))
3198            .saturating_add(crate::memory::usize_to_u64(call.target.len()))
3199            .saturating_add(crate::memory::usize_to_u64(call.provenance.len()))
3200    });
3201    let entry_points = snapshot.entry_points.iter().fold(0u64, |bytes, path| {
3202        bytes
3203            .saturating_add(std::mem::size_of::<PathBuf>() as u64)
3204            .saturating_add(crate::memory::path_bytes(path))
3205    });
3206    let entry_point_symbols =
3207        snapshot
3208            .entry_point_symbols
3209            .iter()
3210            .fold(0u64, |bytes, (path, symbols)| {
3211                let symbols_bytes = symbols.iter().fold(0u64, |bytes, symbol| {
3212                    bytes
3213                        .saturating_add(std::mem::size_of::<String>() as u64)
3214                        .saturating_add(crate::memory::usize_to_u64(symbol.len()))
3215                });
3216                bytes
3217                    .saturating_add(std::mem::size_of::<(PathBuf, BTreeSet<String>)>() as u64)
3218                    .saturating_add(crate::memory::path_bytes(path))
3219                    .saturating_add(symbols_bytes)
3220            });
3221    (std::mem::size_of::<CallgraphSnapshot>() as u64)
3222        .saturating_add(files)
3223        .saturating_add(exports)
3224        .saturating_add(calls)
3225        .saturating_add(entry_points)
3226        .saturating_add(entry_point_symbols)
3227}
3228
3229fn callgraph_store_dir_from_inspect_dir(
3230    inspect_dir: &Path,
3231    project_root: &Path,
3232) -> Option<PathBuf> {
3233    let scope_key = crate::path_identity::project_scope_key(project_root);
3234    let storage_dir = if inspect_dir
3235        .file_name()
3236        .and_then(|name| name.to_str())
3237        .is_some_and(|name| name == scope_key)
3238    {
3239        inspect_dir.parent()?.parent()?
3240    } else {
3241        inspect_dir.parent()?
3242    };
3243    let project_key = crate::search_index::artifact_cache_key(project_root);
3244    Some(storage_dir.join("callgraph").join(project_key))
3245}
3246
3247fn callgraph_store_dirs_from_inspect_dir(inspect_dir: &Path, project_root: &Path) -> Vec<PathBuf> {
3248    callgraph_store_dir_from_inspect_dir(inspect_dir, project_root)
3249        .into_iter()
3250        .collect()
3251}
3252
3253#[cfg(test)]
3254fn canonicalize_for_snapshot(path: &Path) -> PathBuf {
3255    // Mirrors the projection's normalizer: snapshot paths are
3256    // verbatim-stripped, so test expectations must be too.
3257    crate::inspect::job::canonicalize_normalized(path)
3258}
3259
3260fn load_contribution_freshness(
3261    cache: &(impl InspectCacheRead + ?Sized),
3262    category: InspectCategory,
3263) -> Result<Vec<CachedContributionFreshness>, String> {
3264    cache
3265        .contribution_freshness(category)
3266        .map_err(|error| error.to_string())
3267        .map(|records| {
3268            records
3269                .into_iter()
3270                .map(|(file_path, freshness)| CachedContributionFreshness {
3271                    file_path,
3272                    freshness,
3273                })
3274                .collect()
3275        })
3276}
3277
3278fn freshness_record_relative_key(record: &CachedContributionFreshness) -> String {
3279    record.file_path.to_string_lossy().to_string()
3280}
3281
3282fn relative_cache_key(project_root: &Path, path: &Path) -> String {
3283    path.strip_prefix(project_root)
3284        .unwrap_or(path)
3285        .to_string_lossy()
3286        .to_string()
3287}
3288
3289fn load_contributions(
3290    cache: &(impl InspectCacheRead + ?Sized),
3291    job: &InspectJob,
3292) -> Result<Vec<FileContribution>, String> {
3293    cache
3294        .load_tier2_contributions(job.category)
3295        .map_err(|error| error.to_string())
3296        .map(|records| {
3297            records
3298                .into_iter()
3299                .map(|record| contribution_from_record(&job.project_root, record))
3300                .collect()
3301        })
3302}
3303
3304fn dead_code_contributions_need_fact_refresh(
3305    cache: &(impl InspectCacheRead + ?Sized),
3306    job: &InspectJob,
3307) -> Result<bool, String> {
3308    let contributions = load_contributions(cache, job)?;
3309    Ok(contributions
3310        .iter()
3311        .any(dead_code_contribution_needs_fact_refresh))
3312}
3313
3314fn dead_code_contribution_needs_fact_refresh(contribution: &FileContribution) -> bool {
3315    let Ok(parsed) =
3316        serde_json::from_value::<DeadCodeRefreshContribution>(contribution.contribution.clone())
3317    else {
3318        return true;
3319    };
3320
3321    if parsed.facts_format_version
3322        != Some(super::scanners::dead_code::DEAD_CODE_FACTS_FORMAT_VERSION)
3323    {
3324        return true;
3325    }
3326
3327    matches!(
3328        parsed.oxc_facts,
3329        Some(facts) if facts.format_version != FACTS_FORMAT_VERSION
3330    )
3331}
3332
3333fn unused_exports_contributions_need_fact_refresh(
3334    cache: &(impl InspectCacheRead + ?Sized),
3335    job: &InspectJob,
3336) -> Result<bool, String> {
3337    let contributions = load_contributions(cache, job)?;
3338    Ok(contributions
3339        .iter()
3340        .any(unused_exports_contribution_needs_fact_refresh))
3341}
3342
3343/// Duplicates contributions written before v0.44 lack the `line_count` field
3344/// (serde defaults it to 0), so a cached roll-up computes total_analyzed_lines
3345/// as 0 and the summary renders "0.0% of 0 analyzed lines". One full rescan
3346/// repopulates the counts; fresh contributions always carry line_count.
3347fn duplicates_contributions_need_fact_refresh(
3348    cache: &(impl InspectCacheRead + ?Sized),
3349    job: &InspectJob,
3350) -> Result<bool, String> {
3351    let contributions = load_contributions(cache, job)?;
3352    Ok(contributions
3353        .iter()
3354        .any(|contribution| contribution.contribution.get("line_count").is_none()))
3355}
3356
3357fn unused_exports_contribution_needs_fact_refresh(contribution: &FileContribution) -> bool {
3358    let top_level_oxc = contribution
3359        .contribution
3360        .get("provenance")
3361        .and_then(Value::as_str)
3362        == Some(OXC_PROVENANCE);
3363    let Ok(parsed) =
3364        serde_json::from_value::<UnusedExportsContribution>(contribution.contribution.clone())
3365    else {
3366        return false;
3367    };
3368    let uses_oxc =
3369        top_level_oxc || parsed.oxc_facts.is_some() || parsed.exports.iter().any(export_uses_oxc);
3370    if !uses_oxc {
3371        return false;
3372    }
3373
3374    !matches!(
3375        parsed.oxc_facts,
3376        Some(facts) if facts.format_version == FACTS_FORMAT_VERSION
3377    )
3378}
3379
3380fn contribution_from_record(
3381    project_root: &Path,
3382    record: super::cache::ContributionRecord,
3383) -> FileContribution {
3384    FileContribution::new(
3385        record.category,
3386        project_root.join(record.file_path),
3387        record.freshness,
3388        record.contribution,
3389    )
3390    .with_type_ref_names(record.type_ref_names)
3391}
3392
3393fn run_tier2_scan(job: &InspectJob, oxc_result: Option<&OxcEngineResult>) -> InspectResult {
3394    use super::scanners;
3395
3396    match job.category {
3397        InspectCategory::DeadCode => {
3398            scanners::dead_code::run_dead_code_scan_with_oxc(job, oxc_result)
3399        }
3400        InspectCategory::UnusedExports => {
3401            scanners::unused_exports::run_unused_exports_scan_with_oxc(job, oxc_result)
3402        }
3403        InspectCategory::Duplicates => scanners::duplicates::run_duplicates_scan(job),
3404        InspectCategory::Cycles => scanners::cycles::run_cycles_scan_with_oxc(job, oxc_result),
3405        other => InspectResult::failed(
3406            job,
3407            format!("inspect category '{other}' is not an active Tier 2 scanner"),
3408            Duration::from_secs(0),
3409        ),
3410    }
3411}
3412
3413fn roll_up_tier2_contributions(job: &InspectJob, contributions: &[FileContribution]) -> Value {
3414    roll_up_tier2_contributions_with_limit(job, contributions, Some(MAX_DRILL_DOWN_ITEMS))
3415}
3416
3417fn roll_up_tier2_contributions_with_limit(
3418    job: &InspectJob,
3419    contributions: &[FileContribution],
3420    drill_down_limit: Option<usize>,
3421) -> Value {
3422    match job.category {
3423        InspectCategory::DeadCode => {
3424            roll_up_dead_code_contributions(job, contributions, drill_down_limit)
3425        }
3426        InspectCategory::UnusedExports => {
3427            roll_up_unused_exports_contributions(job, contributions, drill_down_limit)
3428        }
3429        InspectCategory::Duplicates => {
3430            roll_up_duplicate_contributions(job, contributions, drill_down_limit)
3431        }
3432        InspectCategory::Cycles => {
3433            roll_up_cycle_contributions(job, contributions, drill_down_limit)
3434        }
3435        _ => json!({
3436            "count": 0,
3437            "items": [],
3438            "scanned_files": contributions.len(),
3439        }),
3440    }
3441}
3442
3443fn scoped_tier2_payload_from_contributions(
3444    snapshot: &InspectSnapshot,
3445    category: InspectCategory,
3446    cache: &(impl InspectCacheRead + ?Sized),
3447    project_payload: Value,
3448    scope: &JobScope,
3449) -> Result<Value, String> {
3450    if scope.is_project_wide() {
3451        return Ok(project_payload);
3452    }
3453
3454    let project_scope = JobScope::for_project(snapshot.project_root.clone());
3455    let rollup_job = scoped_tier2_rollup_job(snapshot, category, &project_scope);
3456    let contributions = load_contributions(cache, &rollup_job)?;
3457    let full_payload = roll_up_tier2_contributions_with_limit(&rollup_job, &contributions, None);
3458    let scoped_payload = filter_payload_for_scope(full_payload, scope);
3459    Ok(cap_payload_drill_down(scoped_payload, MAX_DRILL_DOWN_ITEMS))
3460}
3461
3462fn scoped_tier2_rollup_job(
3463    snapshot: &InspectSnapshot,
3464    category: InspectCategory,
3465    scope: &JobScope,
3466) -> InspectJob {
3467    let mut job = InspectJob {
3468        job_id: 0,
3469        key: JobKey::for_project_category(category),
3470        category,
3471        scope_files: scope_files(&snapshot.project_root, scope),
3472        project_root: snapshot.project_root.clone(),
3473        inspect_dir: snapshot.inspect_dir.clone(),
3474        config: Arc::clone(&snapshot.config),
3475        symbol_cache: Arc::clone(&snapshot.symbol_cache),
3476        inspect_writer: snapshot.inspect_writer,
3477        callgraph_writer: snapshot.callgraph_writer,
3478        callgraph_snapshot: None,
3479    };
3480
3481    if category == InspectCategory::DeadCode {
3482        // Scoped read-path rollups recompute dead-code liveness from cached
3483        // contributions. Use a real ready store snapshot when one exists; if no
3484        // snapshot is available, leave it absent so the rollup reports degraded
3485        // callgraph_unavailable instead of treating an empty graph as truth.
3486        job.callgraph_snapshot = build_tier2_callgraph_snapshot(&job, false);
3487    }
3488
3489    job
3490}
3491
3492fn roll_up_dead_code_contributions(
3493    job: &InspectJob,
3494    contributions: &[FileContribution],
3495    drill_down_limit: Option<usize>,
3496) -> Value {
3497    let Some(snapshot) = job.callgraph_snapshot.as_deref() else {
3498        return super::scanners::dead_code::callgraph_unavailable_aggregate(job.scope_files.len());
3499    };
3500
3501    let public_api_files = super::scanners::dead_code::collect_public_api_files(&job.project_root);
3502    let roles = super::entry_points::resolve_project_roles(&job.project_root);
3503    super::scanners::dead_code::aggregate_dead_code_contributions_with_snapshot(
3504        &job.project_root,
3505        snapshot,
3506        contributions,
3507        &public_api_files,
3508        &roles,
3509        drill_down_limit,
3510    )
3511}
3512
3513fn roll_up_unused_exports_contributions(
3514    job: &InspectJob,
3515    contributions: &[FileContribution],
3516    drill_down_limit: Option<usize>,
3517) -> Value {
3518    let parsed = contributions
3519        .iter()
3520        .filter_map(|contribution| {
3521            serde_json::from_value::<UnusedExportsContribution>(contribution.contribution.clone())
3522                .ok()
3523        })
3524        .collect::<Vec<_>>();
3525
3526    if parsed.iter().any(|scan| scan.oxc_facts.is_some()) {
3527        return roll_up_unused_exports_oxc_contributions(job, &parsed, drill_down_limit);
3528    }
3529
3530    let (public_api_files, package_warnings) = unused_public_api_entries(&job.project_root);
3531    let mut imported_by: BTreeMap<(String, String), BTreeSet<String>> = BTreeMap::new();
3532    let mut uncertain_by: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
3533    for scan in &parsed {
3534        for import in &scan.imports {
3535            let Some(resolved_file) = &import.resolved_file else {
3536                continue;
3537            };
3538            for name in &import.named {
3539                if name == "*" {
3540                    uncertain_by
3541                        .entry(resolved_file.clone())
3542                        .or_default()
3543                        .insert(scan.file.clone());
3544                } else {
3545                    imported_by
3546                        .entry((resolved_file.clone(), name.clone()))
3547                        .or_default()
3548                        .insert(scan.file.clone());
3549                }
3550            }
3551        }
3552    }
3553
3554    let mut count = 0usize;
3555    let mut items = Vec::new();
3556    let mut generated_count = 0usize;
3557    let mut generated_items = Vec::new();
3558    let test_only_count = 0usize;
3559    let test_only_items = Vec::new();
3560    let mut uncertain_count = 0usize;
3561    let mut uncertain_items = Vec::new();
3562    for scan in &parsed {
3563        if public_api_files.contains(&scan.file) {
3564            continue;
3565        }
3566        // Mirror the fresh-scan path: fixtures/corpora/mock data are consumed
3567        // by path, never imported, so their exports always look unused.
3568        if super::job::is_test_support_file(&scan.file) {
3569            continue;
3570        }
3571        let generated_file = super::generated::is_generated_file_with_cached_hint(
3572            &job.project_root,
3573            &scan.file,
3574            scan.generated,
3575        );
3576
3577        for export in &scan.exports {
3578            if export_uses_oxc(export) {
3579                match export.verdict.unwrap_or(LivenessVerdict::Unused) {
3580                    LivenessVerdict::Used => continue,
3581                    LivenessVerdict::Uncertain => {
3582                        uncertain_count += 1;
3583                        if drill_down_limit.is_none_or(|limit| uncertain_items.len() < limit) {
3584                            uncertain_items.push(json!({
3585                                "file": scan.file,
3586                                "symbol": export.symbol,
3587                                "kind": export.kind,
3588                                "line": export.line,
3589                                "reason": export.reason.as_deref().unwrap_or("oxc_uncertain"),
3590                                "provenance": export.provenance.as_deref().unwrap_or(OXC_PROVENANCE),
3591                            }));
3592                        }
3593                        continue;
3594                    }
3595                    LivenessVerdict::Unused => {}
3596                }
3597            } else {
3598                let imported = imported_by
3599                    .get(&(scan.file.clone(), export.symbol.clone()))
3600                    .map(|files| !files.is_empty())
3601                    .unwrap_or(false);
3602                let uncertain = uncertain_by
3603                    .get(&scan.file)
3604                    .map(|files| !files.is_empty())
3605                    .unwrap_or(false);
3606
3607                if imported {
3608                    continue;
3609                }
3610                if uncertain {
3611                    uncertain_count += 1;
3612                    if drill_down_limit.is_none_or(|limit| uncertain_items.len() < limit) {
3613                        uncertain_items.push(json!({
3614                            "file": scan.file,
3615                            "symbol": export.symbol,
3616                            "kind": export.kind,
3617                            "line": export.line,
3618                            "reason": "wildcard_import",
3619                        }));
3620                    }
3621                    continue;
3622                }
3623            }
3624
3625            let mut item = json!({
3626                "file": scan.file,
3627                "symbol": export.symbol,
3628                "kind": export.kind,
3629                "line": export.line,
3630            });
3631            if let Some(provenance) = &export.provenance {
3632                item["provenance"] = json!(provenance);
3633            }
3634            if generated_file {
3635                item["generated"] = json!(true);
3636                generated_count += 1;
3637                generated_items.push(item);
3638            } else {
3639                count += 1;
3640                items.push(item);
3641            }
3642        }
3643    }
3644
3645    let roles = super::entry_points::resolve_project_roles(&job.project_root);
3646    let items = super::entry_points::rank_and_truncate_items(items, &roles, drill_down_limit);
3647    let generated_items =
3648        super::entry_points::rank_and_truncate_items(generated_items, &roles, drill_down_limit);
3649    let top = super::entry_points::top_preview_symbols(&items);
3650    let generated_top = generated_items
3651        .iter()
3652        .take(super::entry_points::TOP_PREVIEW_ITEMS)
3653        .cloned()
3654        .collect::<Vec<_>>();
3655    let mut all_items = items;
3656    all_items.extend(generated_items.iter().cloned());
3657    if let Some(limit) = drill_down_limit {
3658        all_items.truncate(limit);
3659    }
3660    let test_only_items =
3661        super::entry_points::rank_and_truncate_items(test_only_items, &roles, drill_down_limit);
3662    let test_only_top = test_only_items
3663        .iter()
3664        .take(super::entry_points::TOP_PREVIEW_ITEMS)
3665        .cloned()
3666        .collect::<Vec<_>>();
3667
3668    let (parse_errors, skipped_files) = unused_exports_honesty_fields(&parsed);
3669    let mut aggregate = json!({
3670        "count": count,
3671        "generated_count": generated_count,
3672        "total_count": count + test_only_count + generated_count,
3673        "items": all_items,
3674        "top": top,
3675        "generated_items": generated_items,
3676        "generated_top": generated_top,
3677        "test_only_count": test_only_count,
3678        "test_only_items": test_only_items,
3679        "test_only_top": test_only_top,
3680        "drill_down_capped": drill_down_limit.is_some_and(|limit| count + generated_count > limit),
3681        "generated_drill_down_capped": drill_down_limit.is_some_and(|limit| generated_count > limit),
3682        "test_only_drill_down_capped": drill_down_limit.is_some_and(|limit| test_only_count > limit),
3683        "scanned_files": parsed.len(),
3684        "languages_skipped": skipped_languages(&job.scope_files, LanguageSkipMode::UnusedExports),
3685        "uncertain_count": uncertain_count,
3686        "uncertain_items": uncertain_items,
3687        "complete": parse_errors.is_empty() && skipped_files.is_empty(),
3688    });
3689    if !parse_errors.is_empty() {
3690        aggregate["parse_errors"] = Value::Array(parse_errors);
3691    }
3692    if !skipped_files.is_empty() {
3693        aggregate["skipped_files"] = Value::Array(skipped_files);
3694    }
3695    if !package_warnings.is_empty() {
3696        aggregate["note"] = Value::String(package_warnings.join("; "));
3697    }
3698    aggregate
3699}
3700
3701fn roll_up_unused_exports_oxc_contributions(
3702    job: &InspectJob,
3703    parsed: &[UnusedExportsContribution],
3704    drill_down_limit: Option<usize>,
3705) -> Value {
3706    let (public_api_files, package_warnings) = unused_public_api_entries(&job.project_root);
3707    let facts = parsed
3708        .iter()
3709        .filter_map(|scan| {
3710            let oxc_facts = scan.oxc_facts.as_ref()?;
3711            let path = job.project_root.join(&scan.file);
3712            Some(FileFacts {
3713                file_id: FileId(0),
3714                path: normalize_input_path(&job.project_root, &path),
3715                content_hash: oxc_facts.content_hash.clone(),
3716                exports: oxc_facts.exports.clone(),
3717                imports: oxc_facts.imports.clone(),
3718                re_exports: oxc_facts.re_exports.clone(),
3719                dynamic_imports: oxc_facts.dynamic_imports.clone(),
3720                same_file_value_references: oxc_facts.same_file_value_references.clone(),
3721                used_import_bindings: oxc_facts.used_import_bindings.clone(),
3722                type_referenced_import_bindings: oxc_facts.type_referenced_import_bindings.clone(),
3723                value_referenced_import_bindings: oxc_facts
3724                    .value_referenced_import_bindings
3725                    .clone(),
3726                parse_error: oxc_facts.parse_error.clone(),
3727            })
3728        })
3729        .collect::<Vec<_>>();
3730    let generated_by_file = parsed
3731        .iter()
3732        .map(|scan| {
3733            (
3734                scan.file.clone(),
3735                super::generated::is_generated_file_with_cached_hint(
3736                    &job.project_root,
3737                    &scan.file,
3738                    scan.generated,
3739                ),
3740            )
3741        })
3742        .collect::<BTreeMap<_, _>>();
3743    let entry_point_set = crate::inspect::entry_points::resolve_entry_points(&job.project_root);
3744    let oxc_result = analyze_file_facts(
3745        &job.project_root,
3746        facts,
3747        AnalyzeOptions {
3748            entry_points: Vec::new(),
3749            public_api_files: entry_point_set.public_api_files(),
3750            executable_root_exports: entry_point_set.executable_root_exports(),
3751            force_reparse_files: Vec::new(),
3752            entry_reachability: false,
3753        },
3754        Vec::new(),
3755    );
3756    let roles = super::entry_points::resolve_project_roles(&job.project_root);
3757
3758    let mut count = 0usize;
3759    let mut items = Vec::new();
3760    let mut generated_count = 0usize;
3761    let mut generated_items = Vec::new();
3762    let mut test_only_count = 0usize;
3763    let mut test_only_items = Vec::new();
3764    let mut uncertain_count = 0usize;
3765    let mut uncertain_items = Vec::new();
3766    for file in &oxc_result.files {
3767        if public_api_files.contains(&file.relative_file)
3768            || super::job::is_test_support_file(&file.relative_file)
3769        {
3770            continue;
3771        }
3772        let generated_file = generated_by_file
3773            .get(&file.relative_file)
3774            .copied()
3775            .unwrap_or_else(|| {
3776                super::generated::is_generated_file(
3777                    &job.project_root,
3778                    Path::new(&file.relative_file),
3779                )
3780            });
3781
3782        for export in &file.exports {
3783            match export.verdict {
3784                LivenessVerdict::Used => {
3785                    if !is_test_file(&file.relative_file)
3786                        && !export.test_only_reference_files.is_empty()
3787                    {
3788                        let mut item = json!({
3789                            "file": file.relative_file,
3790                            "symbol": export.symbol,
3791                            "kind": export.kind,
3792                            "line": export.line,
3793                            "provenance": export.provenance,
3794                            "used_by": export.test_only_reference_files,
3795                        });
3796                        add_oxc_reexport_contexts(&mut item, &export.also_reexported);
3797                        if generated_file {
3798                            item["generated"] = json!(true);
3799                            generated_count += 1;
3800                            generated_items.push(item);
3801                        } else {
3802                            test_only_count += 1;
3803                            test_only_items.push(item);
3804                        }
3805                    }
3806                }
3807                LivenessVerdict::Uncertain => {
3808                    uncertain_count += 1;
3809                    if drill_down_limit.is_none_or(|limit| uncertain_items.len() < limit) {
3810                        let mut item = json!({
3811                            "file": file.relative_file,
3812                            "symbol": export.symbol,
3813                            "kind": export.kind,
3814                            "line": export.line,
3815                            "reason": export.reason,
3816                            "provenance": export.provenance,
3817                        });
3818                        add_oxc_reexport_contexts(&mut item, &export.also_reexported);
3819                        uncertain_items.push(item);
3820                    }
3821                }
3822                LivenessVerdict::Unused => {
3823                    if !is_test_file(&file.relative_file)
3824                        && !export.test_only_reference_files.is_empty()
3825                    {
3826                        let mut item = json!({
3827                            "file": file.relative_file,
3828                            "symbol": export.symbol,
3829                            "kind": export.kind,
3830                            "line": export.line,
3831                            "provenance": export.provenance,
3832                            "used_by": export.test_only_reference_files,
3833                        });
3834                        add_oxc_reexport_contexts(&mut item, &export.also_reexported);
3835                        if generated_file {
3836                            item["generated"] = json!(true);
3837                            generated_count += 1;
3838                            generated_items.push(item);
3839                        } else {
3840                            test_only_count += 1;
3841                            test_only_items.push(item);
3842                        }
3843                        continue;
3844                    }
3845                    if export.has_references {
3846                        continue;
3847                    }
3848                    let mut item = json!({
3849                        "file": file.relative_file,
3850                        "symbol": export.symbol,
3851                        "kind": export.kind,
3852                        "line": export.line,
3853                        "provenance": export.provenance,
3854                    });
3855                    add_oxc_reexport_contexts(&mut item, &export.also_reexported);
3856                    if generated_file {
3857                        item["generated"] = json!(true);
3858                        generated_count += 1;
3859                        generated_items.push(item);
3860                    } else {
3861                        count += 1;
3862                        items.push(item);
3863                    }
3864                }
3865            }
3866        }
3867    }
3868
3869    let items = super::entry_points::rank_and_truncate_items(items, &roles, drill_down_limit);
3870    let generated_items =
3871        super::entry_points::rank_and_truncate_items(generated_items, &roles, drill_down_limit);
3872    let top = super::entry_points::top_preview_symbols(&items);
3873    let generated_top = generated_items
3874        .iter()
3875        .take(super::entry_points::TOP_PREVIEW_ITEMS)
3876        .cloned()
3877        .collect::<Vec<_>>();
3878    let mut all_items = items;
3879    all_items.extend(generated_items.iter().cloned());
3880    if let Some(limit) = drill_down_limit {
3881        all_items.truncate(limit);
3882    }
3883    let test_only_items =
3884        super::entry_points::rank_and_truncate_items(test_only_items, &roles, drill_down_limit);
3885    let test_only_top = test_only_items
3886        .iter()
3887        .take(super::entry_points::TOP_PREVIEW_ITEMS)
3888        .cloned()
3889        .collect::<Vec<_>>();
3890    let (mut parse_errors, skipped_files) = unused_exports_honesty_fields(parsed);
3891    for scan in parsed {
3892        if let Some(oxc_facts) = &scan.oxc_facts {
3893            if oxc_facts.format_version != FACTS_FORMAT_VERSION {
3894                parse_errors.push(json!({
3895                    "file": scan.file,
3896                    "message": format!(
3897                        "unsupported oxc facts format {}; expected {}",
3898                        oxc_facts.format_version, FACTS_FORMAT_VERSION
3899                    ),
3900                }));
3901            }
3902        }
3903    }
3904
3905    let mut aggregate = json!({
3906        "count": count,
3907        "generated_count": generated_count,
3908        "total_count": count + test_only_count + generated_count,
3909        "items": all_items,
3910        "top": top,
3911        "generated_items": generated_items,
3912        "generated_top": generated_top,
3913        "test_only_count": test_only_count,
3914        "test_only_items": test_only_items,
3915        "test_only_top": test_only_top,
3916        "drill_down_capped": drill_down_limit.is_some_and(|limit| count + generated_count > limit),
3917        "generated_drill_down_capped": drill_down_limit.is_some_and(|limit| generated_count > limit),
3918        "test_only_drill_down_capped": drill_down_limit.is_some_and(|limit| test_only_count > limit),
3919        "scanned_files": parsed.len(),
3920        "languages_skipped": skipped_languages(&job.scope_files, LanguageSkipMode::UnusedExports),
3921        "uncertain_count": uncertain_count,
3922        "uncertain_items": uncertain_items,
3923        "complete": parse_errors.is_empty() && skipped_files.is_empty(),
3924    });
3925    if !parse_errors.is_empty() {
3926        aggregate["parse_errors"] = Value::Array(parse_errors);
3927    }
3928    if !skipped_files.is_empty() {
3929        aggregate["skipped_files"] = Value::Array(skipped_files);
3930    }
3931    if !package_warnings.is_empty() {
3932        aggregate["note"] = Value::String(package_warnings.join("; "));
3933    }
3934    aggregate
3935}
3936
3937fn add_oxc_reexport_contexts(
3938    item: &mut Value,
3939    contexts: &[crate::inspect::oxc_engine::OxcReExportContext],
3940) {
3941    if !contexts.is_empty() {
3942        item["also_reexported"] = json!(contexts);
3943    }
3944}
3945
3946fn unused_exports_honesty_fields(parsed: &[UnusedExportsContribution]) -> (Vec<Value>, Vec<Value>) {
3947    let mut parse_error_keys = BTreeSet::new();
3948    let mut parse_errors = Vec::new();
3949    let mut skipped_file_keys = BTreeSet::new();
3950    let mut skipped_files = Vec::new();
3951    for contribution in parsed {
3952        for value in &contribution.parse_errors {
3953            let key = value.to_string();
3954            if parse_error_keys.insert(key) {
3955                parse_errors.push(value.clone());
3956            }
3957        }
3958        for value in &contribution.skipped_files {
3959            let key = value.to_string();
3960            if skipped_file_keys.insert(key) {
3961                skipped_files.push(value.clone());
3962            }
3963        }
3964    }
3965    (parse_errors, skipped_files)
3966}
3967
3968fn roll_up_duplicate_contributions(
3969    job: &InspectJob,
3970    contributions: &[FileContribution],
3971    drill_down_limit: Option<usize>,
3972) -> Value {
3973    super::scanners::duplicates::aggregate_duplicate_contributions_with_limit(
3974        contributions,
3975        skipped_languages(&job.scope_files, LanguageSkipMode::Duplicates),
3976        drill_down_limit,
3977        &job.config.inspect.duplicates.expected_mirrors,
3978    )
3979}
3980
3981fn roll_up_cycle_contributions(
3982    job: &InspectJob,
3983    contributions: &[FileContribution],
3984    drill_down_limit: Option<usize>,
3985) -> Value {
3986    super::scanners::cycles::aggregate_cycle_contributions_with_limit(
3987        &job.project_root,
3988        contributions,
3989        skipped_languages(&job.scope_files, LanguageSkipMode::Cycles),
3990        drill_down_limit,
3991    )
3992}
3993
3994fn cap_payload_drill_down(mut payload: Value, limit: usize) -> Value {
3995    let mut capped = false;
3996    if let Some(items) = payload.get_mut("items").and_then(Value::as_array_mut) {
3997        capped |= items.len() > limit;
3998        items.truncate(limit);
3999    }
4000    if let Some(groups) = payload.get_mut("groups").and_then(Value::as_array_mut) {
4001        capped |= groups.len() > limit;
4002        groups.truncate(limit);
4003    }
4004    if let Some(object) = payload.as_object_mut() {
4005        object.insert("drill_down_capped".to_string(), json!(capped));
4006    }
4007    payload
4008}
4009
4010const MAX_DRILL_DOWN_ITEMS: usize = 100;
4011
4012#[derive(Debug, Clone, Deserialize)]
4013struct ExportContribution {
4014    symbol: String,
4015    kind: String,
4016    line: u32,
4017    #[serde(default)]
4018    verdict: Option<LivenessVerdict>,
4019    #[serde(default)]
4020    reason: Option<String>,
4021    #[serde(default)]
4022    provenance: Option<String>,
4023}
4024
4025fn export_uses_oxc(export: &ExportContribution) -> bool {
4026    export.verdict.is_some() || export.provenance.as_deref() == Some(OXC_PROVENANCE)
4027}
4028
4029#[derive(Debug, Clone, Deserialize)]
4030struct DeadCodeRefreshContribution {
4031    #[serde(default)]
4032    facts_format_version: Option<u32>,
4033    #[serde(default)]
4034    oxc_facts: Option<OxcFactsContribution>,
4035}
4036
4037#[derive(Debug, Clone, Deserialize)]
4038struct UnusedExportsContribution {
4039    file: String,
4040    #[serde(default)]
4041    generated: Option<bool>,
4042    exports: Vec<ExportContribution>,
4043    #[serde(default)]
4044    imports: Vec<ImportContribution>,
4045    #[serde(default)]
4046    oxc_facts: Option<OxcFactsContribution>,
4047    #[serde(default)]
4048    parse_errors: Vec<Value>,
4049    #[serde(default)]
4050    skipped_files: Vec<Value>,
4051}
4052
4053#[derive(Debug, Clone, Deserialize)]
4054struct ImportContribution {
4055    resolved_file: Option<String>,
4056    named: Vec<String>,
4057}
4058
4059#[derive(Debug, Clone, Deserialize)]
4060struct OxcFactsContribution {
4061    format_version: u32,
4062    content_hash: String,
4063    exports: Vec<ExportFact>,
4064    imports: Vec<ImportFact>,
4065    re_exports: Vec<ReExportFact>,
4066    dynamic_imports: Vec<DynamicImportFact>,
4067    same_file_value_references: BTreeSet<String>,
4068    used_import_bindings: BTreeSet<String>,
4069    type_referenced_import_bindings: BTreeSet<String>,
4070    value_referenced_import_bindings: BTreeSet<String>,
4071    #[serde(default)]
4072    parse_error: Option<String>,
4073}
4074
4075#[derive(Debug, Clone, Copy)]
4076enum LanguageSkipMode {
4077    Duplicates,
4078    Cycles,
4079    UnusedExports,
4080}
4081
4082fn category_uses_oxc(category: InspectCategory) -> bool {
4083    matches!(
4084        category,
4085        InspectCategory::DeadCode | InspectCategory::UnusedExports | InspectCategory::Cycles
4086    )
4087}
4088
4089fn skipped_languages(files: &[PathBuf], mode: LanguageSkipMode) -> Vec<String> {
4090    files
4091        .iter()
4092        .filter_map(|file| skipped_language(file, mode))
4093        .collect::<BTreeSet<_>>()
4094        .into_iter()
4095        .collect()
4096}
4097
4098fn skipped_language(file: &Path, mode: LanguageSkipMode) -> Option<String> {
4099    let Some(language) = crate::parser::detect_language(file) else {
4100        return match mode {
4101            LanguageSkipMode::Duplicates => Some("unknown".to_string()),
4102            LanguageSkipMode::Cycles => Some("unknown".to_string()),
4103            LanguageSkipMode::UnusedExports => None,
4104        };
4105    };
4106
4107    let skipped = match mode {
4108        LanguageSkipMode::Duplicates => !duplicates_supports_language(language),
4109        LanguageSkipMode::Cycles => !is_js_ts_language(language),
4110        LanguageSkipMode::UnusedExports => !is_js_ts_language(language),
4111    };
4112    skipped.then(|| language_name(language).to_string())
4113}
4114
4115fn duplicates_supports_language(language: crate::parser::LangId) -> bool {
4116    !matches!(
4117        language,
4118        crate::parser::LangId::Bash
4119            | crate::parser::LangId::Html
4120            | crate::parser::LangId::Json
4121            | crate::parser::LangId::Scala
4122            | crate::parser::LangId::Solidity
4123            | crate::parser::LangId::Scss
4124            | crate::parser::LangId::Vue
4125            | crate::parser::LangId::Markdown
4126            | crate::parser::LangId::Java
4127            | crate::parser::LangId::Ruby
4128            | crate::parser::LangId::Kotlin
4129            | crate::parser::LangId::Swift
4130            | crate::parser::LangId::Php
4131            | crate::parser::LangId::Lua
4132            | crate::parser::LangId::Perl
4133            | crate::parser::LangId::Pascal
4134            | crate::parser::LangId::R
4135            | crate::parser::LangId::Groovy
4136            | crate::parser::LangId::ObjC
4137    )
4138}
4139
4140fn is_js_ts_language(language: crate::parser::LangId) -> bool {
4141    matches!(
4142        language,
4143        crate::parser::LangId::TypeScript
4144            | crate::parser::LangId::Tsx
4145            | crate::parser::LangId::JavaScript
4146    )
4147}
4148
4149fn language_name(language: crate::parser::LangId) -> &'static str {
4150    match language {
4151        crate::parser::LangId::TypeScript => "typescript",
4152        crate::parser::LangId::Tsx => "tsx",
4153        crate::parser::LangId::JavaScript => "javascript",
4154        crate::parser::LangId::Python => "python",
4155        crate::parser::LangId::Rust => "rust",
4156        crate::parser::LangId::Go => "go",
4157        crate::parser::LangId::C => "c",
4158        crate::parser::LangId::Cpp => "cpp",
4159        crate::parser::LangId::Zig => "zig",
4160        crate::parser::LangId::CSharp => "csharp",
4161        crate::parser::LangId::Bash => "bash",
4162        crate::parser::LangId::Html => "html",
4163        crate::parser::LangId::Markdown => "markdown",
4164        crate::parser::LangId::Yaml => "yaml",
4165        crate::parser::LangId::Solidity => "solidity",
4166        crate::parser::LangId::Scss => "scss",
4167        crate::parser::LangId::Vue => "vue",
4168        crate::parser::LangId::Json => "json",
4169        crate::parser::LangId::Scala => "scala",
4170        crate::parser::LangId::Java => "java",
4171        crate::parser::LangId::Ruby => "ruby",
4172        crate::parser::LangId::Kotlin => "kotlin",
4173        crate::parser::LangId::Swift => "swift",
4174        crate::parser::LangId::Php => "php",
4175        crate::parser::LangId::Lua => "lua",
4176        crate::parser::LangId::Perl => "perl",
4177        crate::parser::LangId::Pascal => "pascal",
4178        crate::parser::LangId::R => "r",
4179        crate::parser::LangId::Groovy => "groovy",
4180        crate::parser::LangId::ObjC => "objc",
4181    }
4182}
4183
4184fn unused_public_api_entries(project_root: &Path) -> (BTreeSet<String>, Vec<String>) {
4185    let entry_points = crate::inspect::entry_points::resolve_entry_points(project_root);
4186    (
4187        entry_points.public_api_files_relative(project_root),
4188        entry_points.warnings().to_vec(),
4189    )
4190}
4191
4192fn filter_outcome_for_scope_with_contributions(
4193    outcome: JobOutcome,
4194    snapshot: &InspectSnapshot,
4195    category: InspectCategory,
4196    cache: &(impl InspectCacheRead + ?Sized),
4197    scope: &JobScope,
4198) -> JobOutcome {
4199    if !category.is_tier2() || scope.is_project_wide() {
4200        return filter_outcome_for_scope(outcome, scope);
4201    }
4202
4203    match outcome {
4204        JobOutcome::Fresh { payload } => {
4205            match scoped_tier2_payload_from_contributions(snapshot, category, cache, payload, scope)
4206            {
4207                Ok(payload) => JobOutcome::Fresh { payload },
4208                Err(message) => JobOutcome::Failed { message },
4209            }
4210        }
4211        JobOutcome::Stale { cached, in_flight } => match cached {
4212            Some(payload) => {
4213                match scoped_tier2_payload_from_contributions(
4214                    snapshot, category, cache, payload, scope,
4215                ) {
4216                    Ok(payload) => JobOutcome::Stale {
4217                        cached: Some(payload),
4218                        in_flight,
4219                    },
4220                    Err(message) => JobOutcome::Failed { message },
4221                }
4222            }
4223            None => JobOutcome::Stale {
4224                cached: None,
4225                in_flight,
4226            },
4227        },
4228        JobOutcome::Pending { in_flight } => JobOutcome::Pending { in_flight },
4229        JobOutcome::Failed { message } => JobOutcome::Failed { message },
4230    }
4231}
4232
4233fn filter_outcome_for_scope(outcome: JobOutcome, scope: &JobScope) -> JobOutcome {
4234    match outcome {
4235        JobOutcome::Fresh { payload } => JobOutcome::Fresh {
4236            payload: filter_payload_for_scope(payload, scope),
4237        },
4238        JobOutcome::Stale { cached, in_flight } => JobOutcome::Stale {
4239            cached: cached.map(|payload| filter_payload_for_scope(payload, scope)),
4240            in_flight,
4241        },
4242        JobOutcome::Pending { in_flight } => JobOutcome::Pending { in_flight },
4243        JobOutcome::Failed { message } => JobOutcome::Failed { message },
4244    }
4245}
4246
4247fn filter_payload_for_scope(mut payload: serde_json::Value, scope: &JobScope) -> serde_json::Value {
4248    if scope.is_project_wide() {
4249        return payload;
4250    }
4251
4252    // Scoped Tier 2 callers pass an uncapped rollup into this filter and cap
4253    // drill-down only afterwards, so the recomputed count below remains the
4254    // true in-scope total rather than the size of a capped sample.
4255    if let Some(items) = payload
4256        .get_mut("items")
4257        .and_then(|value| value.as_array_mut())
4258    {
4259        let count = filter_values_for_scope(items, scope);
4260        let largest_cycle = items
4261            .iter()
4262            .filter_map(|item| item.get("files").and_then(Value::as_array).map(Vec::len))
4263            .max();
4264        if let Some(object) = payload.as_object_mut() {
4265            object.insert("count".to_string(), serde_json::json!(count));
4266            if object.contains_key("largest") {
4267                object.insert(
4268                    "largest".to_string(),
4269                    serde_json::json!(largest_cycle.unwrap_or(0)),
4270                );
4271            }
4272            if object.contains_key("total_groups") {
4273                object.insert("total_groups".to_string(), serde_json::json!(count));
4274            }
4275            if object.contains_key("groups_count") {
4276                object.insert("groups_count".to_string(), serde_json::json!(count));
4277            }
4278        }
4279    }
4280
4281    if let Some(groups) = payload
4282        .get_mut("groups")
4283        .and_then(|value| value.as_array_mut())
4284    {
4285        let count = filter_values_for_scope(groups, scope);
4286        if let Some(object) = payload.as_object_mut() {
4287            object.insert("count".to_string(), serde_json::json!(count));
4288            object.insert("total_groups".to_string(), serde_json::json!(count));
4289            if object.contains_key("groups_count") {
4290                object.insert("groups_count".to_string(), serde_json::json!(count));
4291            }
4292        }
4293    }
4294
4295    // `by_language` is a project-wide breakdown computed before scope filtering.
4296    // Leaving it in a scoped payload contradicts the recomputed in-scope `count`
4297    // (e.g. count: 3 alongside `(rust 214, ts 143)`). The filtered items don't
4298    // carry per-item language, so we can't faithfully recompute it — drop it so
4299    // the scoped summary doesn't render a misleading project-wide breakdown.
4300    if let Some(object) = payload.as_object_mut() {
4301        if object.contains_key("top") {
4302            if let Some(top) = recompute_scoped_top_preview(object) {
4303                object.insert("top".to_string(), top);
4304            } else if let Some(top) = object.get_mut("top").and_then(Value::as_array_mut) {
4305                filter_values_for_scope(top, scope);
4306            }
4307        }
4308        if object.contains_key("duplicated_lines") {
4309            recompute_duplicate_payload_stats(object);
4310        }
4311        object.remove("by_language");
4312    }
4313
4314    payload
4315}
4316
4317fn recompute_duplicate_payload_stats(object: &mut serde_json::Map<String, Value>) {
4318    let values = object
4319        .get("items")
4320        .or_else(|| object.get("groups"))
4321        .and_then(Value::as_array)
4322        .cloned()
4323        .unwrap_or_default();
4324    let (duplicated_lines, duplicated_file_count) = duplicate_line_stats_from_values(&values);
4325    let total_analyzed_lines = object
4326        .get("total_analyzed_lines")
4327        .and_then(Value::as_u64)
4328        .unwrap_or(0);
4329    let duplicated_percent = if total_analyzed_lines == 0 {
4330        0.0
4331    } else {
4332        (duplicated_lines as f64 * 100.0) / total_analyzed_lines as f64
4333    };
4334    object.insert("duplicated_lines".to_string(), json!(duplicated_lines));
4335    object.insert(
4336        "duplicated_file_count".to_string(),
4337        json!(duplicated_file_count),
4338    );
4339    object.insert("duplicated_percent".to_string(), json!(duplicated_percent));
4340}
4341
4342fn duplicate_line_stats_from_values(values: &[Value]) -> (u64, usize) {
4343    let mut by_file = BTreeMap::<String, Vec<(u64, u64)>>::new();
4344    for value in values {
4345        let Some(files) = value.get("files").and_then(Value::as_array) else {
4346            continue;
4347        };
4348        for occurrence in files.iter().filter_map(Value::as_str) {
4349            let Some((file, start, end)) = parse_duplicate_occurrence(occurrence) else {
4350                continue;
4351            };
4352            by_file
4353                .entry(file.to_string())
4354                .or_default()
4355                .push((start, end));
4356        }
4357    }
4358    let file_count = by_file.len();
4359    let duplicated_lines = by_file
4360        .values_mut()
4361        .map(|intervals| merged_duplicate_interval_lines(intervals))
4362        .sum();
4363    (duplicated_lines, file_count)
4364}
4365
4366fn merged_duplicate_interval_lines(intervals: &mut [(u64, u64)]) -> u64 {
4367    if intervals.is_empty() {
4368        return 0;
4369    }
4370    intervals.sort_by(|left, right| left.0.cmp(&right.0).then(left.1.cmp(&right.1)));
4371    let (mut current_start, mut current_end) = intervals[0];
4372    let mut total = 0;
4373    for &(start, end) in &intervals[1..] {
4374        if start <= current_end.saturating_add(1) {
4375            current_end = current_end.max(end);
4376        } else {
4377            total += current_end.saturating_sub(current_start).saturating_add(1);
4378            current_start = start;
4379            current_end = end;
4380        }
4381    }
4382    total + current_end.saturating_sub(current_start).saturating_add(1)
4383}
4384
4385fn recompute_scoped_top_preview(
4386    object: &serde_json::Map<String, Value>,
4387) -> Option<serde_json::Value> {
4388    let values = object
4389        .get("items")
4390        .or_else(|| object.get("groups"))
4391        .and_then(Value::as_array)?;
4392    Some(Value::Array(
4393        values
4394            .iter()
4395            .take(super::entry_points::TOP_PREVIEW_ITEMS)
4396            .map(top_preview_value)
4397            .collect(),
4398    ))
4399}
4400
4401fn top_preview_value(value: &Value) -> Value {
4402    if let Some(files) = value.get("files").and_then(Value::as_array) {
4403        let mut object = serde_json::Map::new();
4404        object.insert("files".to_string(), Value::Array(files.clone()));
4405        if let Some(cost) = value.get("cost").cloned() {
4406            object.insert("cost".to_string(), cost);
4407        }
4408        return Value::Object(object);
4409    }
4410
4411    json!({
4412        "file": value.get("file").and_then(Value::as_str).unwrap_or(""),
4413        "symbol": value.get("symbol").and_then(Value::as_str).unwrap_or(""),
4414    })
4415}
4416
4417fn filter_values_for_scope(values: &mut Vec<serde_json::Value>, scope: &JobScope) -> usize {
4418    values.retain_mut(|value| prune_value_for_scope(value, scope));
4419    values.len()
4420}
4421
4422fn prune_value_for_scope(value: &mut serde_json::Value, scope: &JobScope) -> bool {
4423    if let Some(file) = value.get("file").and_then(|file| file.as_str()) {
4424        return scope.contains_display_path(file);
4425    }
4426
4427    let first_scoped_occurrence = if let Some(files) = value
4428        .get_mut("files")
4429        .and_then(|files| files.as_array_mut())
4430    {
4431        files.retain(|file| {
4432            file.as_str()
4433                .is_some_and(|file| scope.contains_display_path(display_file_from_occurrence(file)))
4434        });
4435        if files.len() < 2 {
4436            return false;
4437        }
4438        files.first().and_then(Value::as_str).map(str::to_string)
4439    } else {
4440        None
4441    };
4442
4443    if let Some(occurrence) = first_scoped_occurrence {
4444        update_duplicate_group_sample(value, &occurrence);
4445    }
4446
4447    true
4448}
4449
4450fn update_duplicate_group_sample(value: &mut serde_json::Value, occurrence: &str) {
4451    let Some((file, start_line, end_line)) = parse_duplicate_occurrence(occurrence) else {
4452        return;
4453    };
4454    let Some(object) = value.as_object_mut() else {
4455        return;
4456    };
4457
4458    if object.contains_key("sample_file") {
4459        object.insert("sample_file".to_string(), json!(file));
4460    }
4461    if object.contains_key("sample_start_line") {
4462        object.insert("sample_start_line".to_string(), json!(start_line));
4463    }
4464    if object.contains_key("sample_end_line") {
4465        object.insert("sample_end_line".to_string(), json!(end_line));
4466    }
4467}
4468
4469fn parse_duplicate_occurrence(value: &str) -> Option<(&str, u64, u64)> {
4470    let (file, range) = value.rsplit_once(':')?;
4471    let (start, end) = range.split_once('-')?;
4472    if !start.chars().all(|char| char.is_ascii_digit())
4473        || !end.chars().all(|char| char.is_ascii_digit())
4474    {
4475        return None;
4476    }
4477
4478    Some((file, start.parse().ok()?, end.parse().ok()?))
4479}
4480
4481fn display_file_from_occurrence(value: &str) -> &str {
4482    let Some((file, range)) = value.rsplit_once(':') else {
4483        return value;
4484    };
4485    let Some((start, end)) = range.split_once('-') else {
4486        return value;
4487    };
4488    if start.chars().all(|char| char.is_ascii_digit())
4489        && end.chars().all(|char| char.is_ascii_digit())
4490    {
4491        file
4492    } else {
4493        value
4494    }
4495}
4496
4497#[cfg(test)]
4498mod guard_tests {
4499    use super::*;
4500
4501    fn write_ts_project(file_count: usize) -> tempfile::TempDir {
4502        let dir = tempfile::tempdir().expect("tempdir");
4503        let root = dir.path();
4504        for i in 0..file_count {
4505            std::fs::write(
4506                root.join(format!("mod{i}.ts")),
4507                format!("export function f{i}() {{ return {i}; }}\n"),
4508            )
4509            .expect("write fixture");
4510        }
4511        let canonical_root = std::fs::canonicalize(root).expect("canonical fixture root");
4512        let project_key = crate::search_index::artifact_cache_key(&canonical_root);
4513        crate::root_cache::configure_artifact_access(&canonical_root, &project_key, false);
4514        dir
4515    }
4516
4517    struct ProjectionObserverReset;
4518
4519    impl Drop for ProjectionObserverReset {
4520        fn drop(&mut self) {
4521            crate::callgraph_store::set_projection_before_open_observer(None);
4522        }
4523    }
4524
4525    fn count_projections() -> (Arc<std::sync::atomic::AtomicUsize>, ProjectionObserverReset) {
4526        let count = Arc::new(std::sync::atomic::AtomicUsize::new(0));
4527        let observed = Arc::clone(&count);
4528        crate::callgraph_store::set_projection_before_open_observer(Some(Arc::new(move |_| {
4529            observed.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
4530        })));
4531        (count, ProjectionObserverReset)
4532    }
4533
4534    fn write_projection_cache_file(path: &Path, contents: &str) {
4535        std::fs::create_dir_all(path.parent().expect("fixture file parent"))
4536            .expect("create fixture parent");
4537        std::fs::write(path, contents).expect("write fixture file");
4538    }
4539
4540    fn published_projection_fixture() -> (tempfile::TempDir, PathBuf, PathBuf, InspectJob) {
4541        let dir = tempfile::tempdir().expect("tempdir");
4542        let root = std::fs::canonicalize(dir.path()).expect("canonical fixture root");
4543        write_projection_cache_file(
4544            &root.join("src/main.ts"),
4545            "import { firstTarget } from './target';\nexport function main() { firstTarget(); }\n",
4546        );
4547        write_projection_cache_file(
4548            &root.join("src/target.ts"),
4549            "export function firstTarget() {}\n",
4550        );
4551        let inspect_dir = root.join(".aft-cache").join("inspect");
4552        let project_key = crate::search_index::artifact_cache_key(&root);
4553        crate::root_cache::configure_artifact_access(&root, &project_key, false);
4554        let callgraph_dir =
4555            callgraph_store_dir_from_inspect_dir(&inspect_dir, &root).expect("callgraph dir");
4556        let files = crate::callgraph::walk_project_files(&root).collect::<Vec<_>>();
4557        let (store, _) = CallGraphStore::cold_build_with_lease(callgraph_dir, root.clone(), &files)
4558            .expect("publish initial generation");
4559        drop(store);
4560        let mut job = snapshot_job(&root, &inspect_dir, true);
4561        job.callgraph_writer = false;
4562        (dir, root, inspect_dir, job)
4563    }
4564
4565    #[test]
4566    fn scoped_filter_recomputes_top_preview_from_scoped_items() {
4567        let project_root = PathBuf::from("/project");
4568        let scope = JobScope::from_roots(project_root.clone(), vec![project_root.join("src/in")]);
4569        let payload = json!({
4570            "count": 4,
4571            "items": [
4572                { "file": "src/out/a.ts", "symbol": "outside" },
4573                { "file": "src/in/b.ts", "symbol": "inside_b" },
4574                { "file": "src/in/c.ts", "symbol": "inside_c" }
4575            ],
4576            "top": [
4577                { "file": "src/out/a.ts", "symbol": "outside" },
4578                { "file": "src/out/z.ts", "symbol": "outside_z" }
4579            ],
4580            "by_language": { "typescript": 4 }
4581        });
4582
4583        let filtered = filter_payload_for_scope(payload, &scope);
4584
4585        assert_eq!(filtered["count"], json!(2));
4586        assert_eq!(
4587            filtered["top"],
4588            json!([
4589                { "file": "src/in/b.ts", "symbol": "inside_b" },
4590                { "file": "src/in/c.ts", "symbol": "inside_c" }
4591            ])
4592        );
4593        assert!(filtered["top"]
4594            .as_array()
4595            .unwrap()
4596            .iter()
4597            .all(|item| item["file"]
4598                .as_str()
4599                .is_some_and(|file| file.starts_with("src/in/"))));
4600    }
4601
4602    fn artifact_cache_key_for_test(project_root: &std::path::Path) -> String {
4603        let _git_env = crate::test_env::hermetic_git_env_guard();
4604        crate::search_index::artifact_cache_key(project_root)
4605    }
4606
4607    #[test]
4608    fn cache_for_paths_rebinds_same_project_key_to_current_root() {
4609        let _git_env = crate::test_env::hermetic_git_env_guard();
4610        let dir = tempfile::tempdir().expect("tempdir");
4611        let source = dir.path().join("source");
4612        std::fs::create_dir_all(&source).expect("create source repo");
4613        std::fs::write(
4614            source.join("package.json"),
4615            r#"{"name":"inspect-cache-fixture","version":"1.0.0"}"#,
4616        )
4617        .expect("write source manifest");
4618        std::fs::write(source.join("index.ts"), "export const source = 1;\n")
4619            .expect("write source file");
4620        let mut init = std::process::Command::new("git");
4621        assert!(
4622            crate::test_env::apply_hermetic_git_env(init.current_dir(&source))
4623                .arg("init")
4624                .status()
4625                .expect("git init source repo")
4626                .success()
4627        );
4628        let mut add = std::process::Command::new("git");
4629        assert!(
4630            crate::test_env::apply_hermetic_git_env(add.current_dir(&source))
4631                .args(["add", "."])
4632                .status()
4633                .expect("git add source repo")
4634                .success()
4635        );
4636        let mut commit = std::process::Command::new("git");
4637        assert!(
4638            crate::test_env::apply_hermetic_git_env(commit.current_dir(&source))
4639                .args([
4640                    "-c",
4641                    "user.name=AFT Tests",
4642                    "-c",
4643                    "user.email=aft-tests@example.com",
4644                    "commit",
4645                    "-m",
4646                    "initial",
4647                ])
4648                .status()
4649                .expect("git commit source repo")
4650                .success()
4651        );
4652
4653        let clone = dir.path().join("clone");
4654        let mut clone_command = std::process::Command::new("git");
4655        assert!(crate::test_env::apply_hermetic_git_env(&mut clone_command)
4656            .args(["clone", "--quiet"])
4657            .arg(&source)
4658            .arg(&clone)
4659            .status()
4660            .expect("git clone source repo")
4661            .success());
4662        std::fs::write(
4663            clone.join("package.json"),
4664            r#"{"name":"inspect-cache-fixture","version":"2.0.0"}"#,
4665        )
4666        .expect("write clone manifest edit");
4667        assert_eq!(
4668            artifact_cache_key_for_test(&source),
4669            artifact_cache_key_for_test(&clone),
4670            "clones with the same root commit should share the sqlite project key"
4671        );
4672
4673        let source = std::fs::canonicalize(source).expect("canonical source root");
4674        let clone = std::fs::canonicalize(clone).expect("canonical clone root");
4675        let manager = InspectManager::new();
4676        let inspect_dir = dir.path().join("inspect");
4677        let key = JobKey::for_project_category(InspectCategory::DeadCode);
4678        let source_cache = manager
4679            .cache_for_paths(inspect_dir.clone(), source.clone())
4680            .expect("open source cache");
4681        let source_hash = source_cache
4682            .contribution_set_hash(InspectCategory::DeadCode)
4683            .expect("source contribution hash");
4684        source_cache
4685            .store_tier2_aggregate(
4686                key.clone(),
4687                &source_hash,
4688                serde_json::json!({ "count": 7, "items": [] }),
4689            )
4690            .expect("store source aggregate");
4691        assert_eq!(
4692            source_cache
4693                .get_aggregated(&key)
4694                .expect("read source aggregate")
4695                .and_then(|payload| payload.get("count").and_then(Value::as_u64)),
4696            Some(7)
4697        );
4698
4699        let clone_cache = manager
4700            .cache_for_paths(inspect_dir, clone.clone())
4701            .expect("open clone cache");
4702        assert_eq!(clone_cache.project_root(), clone.as_path());
4703        assert!(
4704            clone_cache
4705                .get_aggregated(&key)
4706                .expect("read clone aggregate")
4707                .is_none(),
4708            "same-key clone with a different manifest must not reuse the source root's cached count"
4709        );
4710    }
4711
4712    #[test]
4713    fn dead_code_blocked_on_callgraph_reads_latest_aggregate_flag() {
4714        // Health asks the manager whether dead_code is only missing because the
4715        // callgraph store was not ready when it scanned. The answer must track
4716        // the latest persisted dead_code aggregate's `callgraph_available` flag
4717        // (mirroring the suppression rule in `latest_tier2_counts`).
4718        let dir = tempfile::tempdir().unwrap();
4719        let project_root = std::fs::canonicalize(dir.path()).unwrap();
4720        std::fs::write(project_root.join("lib.rs"), "pub fn marker() {}\n").unwrap();
4721        let manager = InspectManager::new();
4722        let inspect_dir = dir.path().join("inspect");
4723
4724        // No aggregate yet → not blocked.
4725        assert!(!manager.dead_code_blocked_on_callgraph(inspect_dir.clone(), project_root.clone()));
4726
4727        let cache = manager
4728            .cache_for_paths(inspect_dir.clone(), project_root.clone())
4729            .expect("open cache");
4730        let key = JobKey::for_project_category(InspectCategory::DeadCode);
4731        let hash = cache
4732            .contribution_set_hash(InspectCategory::DeadCode)
4733            .expect("contribution hash");
4734
4735        // A callgraph-backed dead_code aggregate → not blocked, count surfaced.
4736        cache
4737            .store_tier2_aggregate(
4738                key.clone(),
4739                &hash,
4740                serde_json::json!({ "count": 3, "callgraph_available": true }),
4741            )
4742            .expect("store callgraph-backed aggregate");
4743        assert!(!manager.dead_code_blocked_on_callgraph(inspect_dir.clone(), project_root.clone()));
4744        assert_eq!(
4745            manager
4746                .latest_tier2_counts(inspect_dir.clone(), project_root.clone())
4747                .0,
4748            Some(3)
4749        );
4750
4751        // A callgraph_unavailable aggregate (store not ready) → blocked, and the
4752        // count stays suppressed so the status bar never fabricates a zero.
4753        cache
4754            .store_tier2_aggregate(
4755                key,
4756                &hash,
4757                crate::inspect::scanners::dead_code::callgraph_unavailable_aggregate(1),
4758            )
4759            .expect("store callgraph_unavailable aggregate");
4760        assert!(manager.dead_code_blocked_on_callgraph(inspect_dir.clone(), project_root.clone()));
4761        assert_eq!(
4762            manager.latest_tier2_counts(inspect_dir, project_root).0,
4763            None,
4764            "callgraph_unavailable dead_code must stay suppressed"
4765        );
4766    }
4767
4768    fn snapshot_job(root: &Path, inspect_dir: &Path, callgraph_store: bool) -> InspectJob {
4769        use crate::config::Config;
4770        use crate::parser::SymbolCache;
4771        use std::sync::RwLock;
4772
4773        InspectJob {
4774            job_id: 1,
4775            key: JobKey::for_project_category(InspectCategory::DeadCode),
4776            category: InspectCategory::DeadCode,
4777            scope_files: Vec::new(),
4778            project_root: root.to_path_buf(),
4779            inspect_dir: inspect_dir.to_path_buf(),
4780            config: Arc::new(Config {
4781                project_root: Some(root.to_path_buf()),
4782                callgraph_store,
4783                ..Config::default()
4784            }),
4785            symbol_cache: Arc::new(RwLock::new(SymbolCache::new())),
4786            inspect_writer: true,
4787            callgraph_writer: true,
4788            callgraph_snapshot: None,
4789        }
4790    }
4791
4792    #[test]
4793    fn blocking_inspect_overtakes_queued_maintenance_after_active_seed_releases() {
4794        use crate::config::Config;
4795        use crate::parser::SymbolCache;
4796        use std::sync::RwLock;
4797
4798        let dir = tempfile::tempdir().expect("tempdir");
4799        let root = std::fs::canonicalize(dir.path()).expect("canonical fixture root");
4800        std::fs::create_dir_all(root.join("src")).expect("create source directory");
4801        std::fs::write(
4802            root.join("src/main.ts"),
4803            "export function plantedDead() { return 1; }\n",
4804        )
4805        .expect("write source fixture");
4806        let project_key = crate::search_index::artifact_cache_key(&root);
4807        crate::root_cache::configure_artifact_access(&root, &project_key, false);
4808        let inspect_dir = root.join(".aft-cache").join("inspect");
4809        let snapshot = InspectSnapshot::new_with_capabilities(
4810            root.clone(),
4811            inspect_dir,
4812            Arc::new(Config {
4813                project_root: Some(root.clone()),
4814                callgraph_store: true,
4815                ..Config::default()
4816            }),
4817            Arc::new(RwLock::new(SymbolCache::new())),
4818            true,
4819            true,
4820        );
4821
4822        let limiter = cold_build_limiter::test_limiter(1);
4823        let active_request = cold_build_limiter::ColdBuildAdmissionRequest::new(
4824            "active-semantic-seed",
4825            cold_build_limiter::ColdBuildAdmissionClass::Maintenance,
4826        );
4827        let active =
4828            cold_build_limiter::try_acquire_classified_with_limiter(&limiter, &active_request)
4829                .expect("active semantic seed holds the only slot");
4830        let semantic_seed_active = Arc::new(AtomicBool::new(true));
4831        let manager = Arc::new(InspectManager::with_root_work_gates(
4832            Arc::new(AtomicBool::new(true)),
4833            Arc::clone(&semantic_seed_active),
4834        ));
4835        manager.set_cold_build_limiter(Arc::clone(&limiter));
4836
4837        let inspect_manager = Arc::clone(&manager);
4838        let scope = JobScope::for_project(root);
4839        let (outcome_tx, outcome_rx) = std::sync::mpsc::channel();
4840        std::thread::spawn(move || {
4841            let outcome = inspect_manager.tier2_run_with_reuse_blocking_fresh(
4842                snapshot,
4843                InspectCategory::DeadCode,
4844                scope,
4845            );
4846            outcome_tx.send(outcome).expect("send inspect outcome");
4847        });
4848
4849        let deadline = Instant::now() + Duration::from_secs(3);
4850        while manager.tier2_builder_state(InspectCategory::DeadCode)
4851            != InspectBuilderState::GatedBySemanticSeed
4852        {
4853            assert!(
4854                Instant::now() < deadline,
4855                "inspect must queue while the active seed owns the slot"
4856            );
4857            std::thread::yield_now();
4858        }
4859        assert!(
4860            outcome_rx.try_recv().is_err(),
4861            "in-flight work is not preempted"
4862        );
4863
4864        let maintenance_limiter = Arc::clone(&limiter);
4865        let maintenance = std::thread::spawn(move || {
4866            cold_build_limiter::acquire_blocking_while_with_limiter(
4867                &maintenance_limiter,
4868                "queued background refresh",
4869                || true,
4870            )
4871            .expect("background refresh eventually resumes")
4872        });
4873        std::thread::sleep(Duration::from_millis(150));
4874        semantic_seed_active.store(false, Ordering::SeqCst);
4875        drop(active);
4876
4877        let outcome = outcome_rx
4878            .recv_timeout(Duration::from_secs(10))
4879            .expect("blocking inspect completes after the active seed releases");
4880        let payload = outcome.payload().expect("blocking inspect is fresh");
4881        assert_eq!(
4882            payload.get("callgraph_available").and_then(Value::as_bool),
4883            Some(true)
4884        );
4885        drop(maintenance.join().expect("background waiter joins"));
4886
4887        let events = limiter.admission_events();
4888        assert_eq!(
4889            events[0].class,
4890            cold_build_limiter::ColdBuildAdmissionClass::Maintenance
4891        );
4892        assert_eq!(
4893            events[1].class,
4894            cold_build_limiter::ColdBuildAdmissionClass::InspectTriggered,
4895            "explicit inspect takes the first released slot"
4896        );
4897        assert_eq!(
4898            events[2].class,
4899            cold_build_limiter::ColdBuildAdmissionClass::Maintenance
4900        );
4901    }
4902
4903    #[test]
4904    fn post_eviction_rebind_serves_unchanged_tier2_aggregate_without_cold_slot() {
4905        use crate::config::Config;
4906        use crate::parser::SymbolCache;
4907        use std::sync::RwLock;
4908
4909        let dir = tempfile::tempdir().expect("tempdir");
4910        let root = std::fs::canonicalize(dir.path()).expect("canonical fixture root");
4911        std::fs::create_dir_all(root.join("src")).expect("create source directory");
4912        std::fs::write(
4913            root.join("src/main.ts"),
4914            "export function plantedDead() { return 1; }\n",
4915        )
4916        .expect("write source fixture");
4917        let project_key = crate::search_index::artifact_cache_key(&root);
4918        crate::root_cache::configure_artifact_access(&root, &project_key, false);
4919        let inspect_dir = root.join(".aft-cache").join("inspect");
4920        let snapshot = InspectSnapshot::new_with_capabilities(
4921            root.clone(),
4922            inspect_dir,
4923            Arc::new(Config {
4924                project_root: Some(root.clone()),
4925                callgraph_store: true,
4926                ..Config::default()
4927            }),
4928            Arc::new(RwLock::new(SymbolCache::new())),
4929            true,
4930            true,
4931        );
4932        let limiter = cold_build_limiter::test_limiter(1);
4933        let manager = Arc::new(InspectManager::new());
4934        manager.set_cold_build_limiter(Arc::clone(&limiter));
4935        let first = manager.tier2_run_with_reuse_blocking_fresh(
4936            snapshot.clone(),
4937            InspectCategory::DeadCode,
4938            JobScope::for_project(root.clone()),
4939        );
4940        assert!(
4941            first.payload().is_some(),
4942            "initial scan persists a fresh aggregate"
4943        );
4944        assert!(!manager.tier2_any_in_flight());
4945        manager.evict_idle_caches();
4946
4947        let maintenance_request = cold_build_limiter::ColdBuildAdmissionRequest::new(
4948            "post-eviction-search-verify",
4949            cold_build_limiter::ColdBuildAdmissionClass::Maintenance,
4950        );
4951        let maintenance =
4952            cold_build_limiter::try_acquire_classified_with_limiter(&limiter, &maintenance_request)
4953                .expect("background verification owns the only cold slot");
4954        let events_before = limiter.admission_events().len();
4955        let rebound_manager = Arc::clone(&manager);
4956        let (outcome_tx, outcome_rx) = std::sync::mpsc::channel();
4957        std::thread::spawn(move || {
4958            let outcome = rebound_manager.tier2_run_with_reuse_blocking_fresh(
4959                snapshot,
4960                InspectCategory::DeadCode,
4961                JobScope::for_project(root),
4962            );
4963            outcome_tx.send(outcome).expect("send rebound outcome");
4964        });
4965
4966        let rebound = outcome_rx
4967            .recv_timeout(Duration::from_secs(3))
4968            .expect("unchanged persisted aggregate bypasses the occupied cold-build queue");
4969        assert!(rebound.payload().is_some());
4970        assert_eq!(
4971            limiter.admission_events().len(),
4972            events_before,
4973            "quick reuse must not request an interactive cold-build permit"
4974        );
4975        drop(maintenance);
4976        assert_eq!(
4977            manager.tier2_builder_state(InspectCategory::DeadCode),
4978            InspectBuilderState::Absent,
4979            "quick reuse must clear the builder registry on the way out"
4980        );
4981        assert!(!manager.tier2_any_in_flight());
4982    }
4983
4984    #[test]
4985    fn background_tier2_reuse_panic_clears_builder_registration() {
4986        use crate::config::Config;
4987        use crate::parser::SymbolCache;
4988        use std::sync::RwLock;
4989
4990        let dir = tempfile::tempdir().expect("tempdir");
4991        let root = std::fs::canonicalize(dir.path()).expect("canonical fixture root");
4992        std::fs::create_dir_all(root.join("src")).expect("create source directory");
4993        std::fs::write(
4994            root.join("src/dup.ts"),
4995            "export function planted() { return 1; }\n",
4996        )
4997        .expect("write source fixture");
4998        let project_key = crate::search_index::artifact_cache_key(&root);
4999        crate::root_cache::configure_artifact_access(&root, &project_key, false);
5000        let inspect_dir = root.join(".aft-cache").join("inspect");
5001        let snapshot = InspectSnapshot::new_with_capabilities(
5002            root.clone(),
5003            inspect_dir,
5004            Arc::new(Config {
5005                project_root: Some(root.clone()),
5006                ..Config::default()
5007            }),
5008            Arc::new(RwLock::new(SymbolCache::new())),
5009            true,
5010            true,
5011        );
5012
5013        let previous_root = std::env::var_os("AFT_TEST_TIER2_REUSE_PANIC_ROOT");
5014        let previous_category = std::env::var_os("AFT_TEST_TIER2_REUSE_PANIC_CATEGORY");
5015        unsafe {
5016            std::env::set_var("AFT_TEST_TIER2_REUSE_PANIC_ROOT", &root);
5017            std::env::set_var("AFT_TEST_TIER2_REUSE_PANIC_CATEGORY", "duplicates");
5018        }
5019        struct RestorePanicEnv {
5020            root: Option<std::ffi::OsString>,
5021            category: Option<std::ffi::OsString>,
5022        }
5023        impl Drop for RestorePanicEnv {
5024            fn drop(&mut self) {
5025                unsafe {
5026                    match self.root.take() {
5027                        Some(value) => std::env::set_var("AFT_TEST_TIER2_REUSE_PANIC_ROOT", value),
5028                        None => std::env::remove_var("AFT_TEST_TIER2_REUSE_PANIC_ROOT"),
5029                    }
5030                    match self.category.take() {
5031                        Some(value) => {
5032                            std::env::set_var("AFT_TEST_TIER2_REUSE_PANIC_CATEGORY", value)
5033                        }
5034                        None => std::env::remove_var("AFT_TEST_TIER2_REUSE_PANIC_CATEGORY"),
5035                    }
5036                }
5037            }
5038        }
5039        let _restore = RestorePanicEnv {
5040            root: previous_root,
5041            category: previous_category,
5042        };
5043
5044        let manager = Arc::new(InspectManager::new());
5045        manager
5046            .submit_tier2_run_with_reuse_background(snapshot, InspectCategory::Duplicates)
5047            .expect("queue background duplicates scan");
5048
5049        let deadline = Instant::now() + Duration::from_secs(20);
5050        loop {
5051            if !manager.tier2_any_in_flight()
5052                && manager.tier2_builder_state(InspectCategory::Duplicates)
5053                    == InspectBuilderState::Absent
5054            {
5055                break;
5056            }
5057            assert!(
5058                Instant::now() < deadline,
5059                "a reuse worker that panics before the completion router must still clear the builder registry"
5060            );
5061            std::thread::sleep(Duration::from_millis(10));
5062        }
5063    }
5064
5065    fn generated_unused_exports_fixture() -> (tempfile::TempDir, PathBuf, Vec<PathBuf>) {
5066        let dir = tempfile::tempdir().expect("tempdir");
5067        let root = dir.path().to_path_buf();
5068        let files = [
5069            (
5070                "src/hand.ts",
5071                "export function handUnused() {}
5072",
5073            ),
5074            (
5075                "gen/schema_pb.ts",
5076                "export function generatedPathUnused() {}
5077",
5078            ),
5079            (
5080                "src/banner.ts",
5081                "// Code generated by fixture. DO NOT EDIT.
5082export function bannerUnused() {}
5083",
5084            ),
5085        ];
5086        let paths = files
5087            .iter()
5088            .map(|(relative, contents)| {
5089                let path = root.join(relative);
5090                if let Some(parent) = path.parent() {
5091                    std::fs::create_dir_all(parent).expect("create parent");
5092                }
5093                std::fs::write(&path, contents).expect("write fixture file");
5094                std::fs::canonicalize(path).expect("canonical fixture path")
5095            })
5096            .collect::<Vec<_>>();
5097        (
5098            dir,
5099            std::fs::canonicalize(root).expect("canonical root"),
5100            paths,
5101        )
5102    }
5103
5104    fn unused_exports_job(root: &Path, scope_files: Vec<PathBuf>) -> InspectJob {
5105        use crate::config::Config;
5106        use crate::parser::SymbolCache;
5107        use std::sync::RwLock;
5108
5109        InspectJob {
5110            job_id: 1,
5111            key: JobKey::for_project_category(InspectCategory::UnusedExports),
5112            category: InspectCategory::UnusedExports,
5113            scope_files,
5114            project_root: root.to_path_buf(),
5115            inspect_dir: root.join(".aft-cache").join("inspect"),
5116            config: Arc::new(Config {
5117                project_root: Some(root.to_path_buf()),
5118                ..Config::default()
5119            }),
5120            symbol_cache: Arc::new(RwLock::new(SymbolCache::new())),
5121            inspect_writer: true,
5122            callgraph_writer: true,
5123            callgraph_snapshot: None,
5124        }
5125    }
5126
5127    #[test]
5128    fn unused_exports_oxc_cached_rollup_preserves_generated_split() {
5129        let (_dir, root, paths) = generated_unused_exports_fixture();
5130        let job = unused_exports_job(&root, paths.clone());
5131        let entry_points = crate::inspect::entry_points::resolve_entry_points(&root);
5132        let oxc_result = crate::inspect::oxc_engine::analyze_files(
5133            &root,
5134            &paths,
5135            AnalyzeOptions {
5136                entry_points: Vec::new(),
5137                public_api_files: entry_points.public_api_files(),
5138                executable_root_exports: entry_points.executable_root_exports(),
5139                force_reparse_files: Vec::new(),
5140                entry_reachability: false,
5141            },
5142        )
5143        .expect("oxc analyze succeeds");
5144        let fresh = crate::inspect::scanners::unused_exports::run_unused_exports_scan_with_oxc(
5145            &job,
5146            Some(&oxc_result),
5147        )
5148        .outcome
5149        .expect("fresh scan succeeds");
5150
5151        let rolled_up = roll_up_unused_exports_contributions(
5152            &job,
5153            &fresh.contributions,
5154            Some(MAX_DRILL_DOWN_ITEMS),
5155        );
5156
5157        assert_eq!(
5158            rolled_up, fresh.aggregate,
5159            "cached rollup must match fresh scan"
5160        );
5161        assert_eq!(rolled_up["count"], 1, "{rolled_up:#}");
5162        assert_eq!(rolled_up["generated_count"], 2, "{rolled_up:#}");
5163        assert_eq!(rolled_up["total_count"], 3, "{rolled_up:#}");
5164    }
5165
5166    #[test]
5167    fn unused_exports_cached_generated_state_avoids_reprobe_with_legacy_fallback() {
5168        let (_dir, root, paths) = generated_unused_exports_fixture();
5169        let job = unused_exports_job(&root, paths.clone());
5170        let entry_points = crate::inspect::entry_points::resolve_entry_points(&root);
5171        let oxc_result = crate::inspect::oxc_engine::analyze_files(
5172            &root,
5173            &paths,
5174            AnalyzeOptions {
5175                entry_points: Vec::new(),
5176                public_api_files: entry_points.public_api_files(),
5177                executable_root_exports: entry_points.executable_root_exports(),
5178                force_reparse_files: Vec::new(),
5179                entry_reachability: false,
5180            },
5181        )
5182        .expect("oxc analyze succeeds");
5183        let fresh = crate::inspect::scanners::unused_exports::run_unused_exports_scan_with_oxc(
5184            &job,
5185            Some(&oxc_result),
5186        )
5187        .outcome
5188        .expect("fresh scan succeeds");
5189        let mut contributions = fresh.contributions;
5190        let handwritten = contributions
5191            .iter_mut()
5192            .find(|contribution| contribution.file_path.ends_with("src/hand.ts"))
5193            .expect("handwritten contribution");
5194        handwritten.contribution["generated"] = json!(false);
5195
5196        crate::inspect::generated::reset_file_probe_count_for_debug(&root);
5197        let explicit_cached =
5198            roll_up_unused_exports_contributions(&job, &contributions, Some(MAX_DRILL_DOWN_ITEMS));
5199        assert_eq!(explicit_cached, fresh.aggregate);
5200        assert_eq!(
5201            crate::inspect::generated::file_probe_count_for_debug(&root),
5202            0,
5203            "an explicit cached generated=false must not probe the file again"
5204        );
5205
5206        let generated_banner = contributions
5207            .iter_mut()
5208            .find(|contribution| contribution.file_path.ends_with("src/banner.ts"))
5209            .expect("generated banner contribution");
5210        generated_banner
5211            .contribution
5212            .as_object_mut()
5213            .expect("contribution object")
5214            .remove("generated");
5215        crate::inspect::generated::reset_file_probe_count_for_debug(&root);
5216        let legacy_cached =
5217            roll_up_unused_exports_contributions(&job, &contributions, Some(MAX_DRILL_DOWN_ITEMS));
5218        assert_eq!(legacy_cached, fresh.aggregate);
5219        assert_eq!(
5220            crate::inspect::generated::file_probe_count_for_debug(&root),
5221            1,
5222            "a legacy contribution without generated must probe and recover its classification"
5223        );
5224    }
5225
5226    #[test]
5227    fn callgraph_snapshot_reports_unavailable_when_store_disabled() {
5228        let dir = write_ts_project(3);
5229        let root = std::fs::canonicalize(dir.path()).expect("canonical root");
5230        let inspect_dir = root.join(".aft-cache").join("inspect");
5231
5232        let snapshot =
5233            build_tier2_callgraph_snapshot(&snapshot_job(&root, &inspect_dir, false), false);
5234
5235        assert!(
5236            snapshot.is_none(),
5237            "dead_code must not rebuild the legacy graph when the store is disabled"
5238        );
5239    }
5240
5241    #[test]
5242    fn callgraph_snapshot_reports_unavailable_when_store_not_ready() {
5243        let dir = write_ts_project(3);
5244        let root = std::fs::canonicalize(dir.path()).expect("canonical root");
5245        let inspect_dir = root.join(".aft-cache").join("inspect");
5246        let callgraph_dir =
5247            callgraph_store_dir_from_inspect_dir(&inspect_dir, &root).expect("store dir");
5248        let _store = CallGraphStore::open(callgraph_dir, root.clone()).expect("open empty store");
5249
5250        let snapshot =
5251            build_tier2_callgraph_snapshot(&snapshot_job(&root, &inspect_dir, true), false);
5252
5253        assert!(
5254            snapshot.is_none(),
5255            "a cold/mid-build store must surface callgraph_unavailable instead of rebuilding inline"
5256        );
5257    }
5258
5259    #[test]
5260    fn suspended_callgraph_build_sets_distinct_builder_state() {
5261        let dir = write_ts_project(3);
5262        let root = std::fs::canonicalize(dir.path()).expect("canonical root");
5263        let inspect_dir = root.join(".aft-cache").join("inspect");
5264        let callgraph_dir =
5265            callgraph_store_dir_from_inspect_dir(&inspect_dir, &root).expect("store dir");
5266        let files = crate::callgraph::walk_project_files(&root).collect::<Vec<_>>();
5267        let key = crate::build_breaker::BreakerKey::new(
5268            root.display().to_string(),
5269            crate::build_breaker::BuildDomain::CallgraphCold,
5270            crate::callgraph_store::callgraph_corpus_fingerprint_for_test(&root, &files)
5271                .expect("corpus fingerprint"),
5272        );
5273        let breaker = crate::build_breaker::BuildDeathBreaker::open(
5274            callgraph_dir.join("build-breaker.sqlite"),
5275        )
5276        .expect("open breaker");
5277        let now = SystemTime::now()
5278            .duration_since(UNIX_EPOCH)
5279            .expect("system time")
5280            .as_millis() as u64;
5281        for _ in 0..3 {
5282            let crate::build_breaker::BreakerAdmission::Admitted(attempt) =
5283                breaker.admit_at(&key, 0, now).expect("admit build")
5284            else {
5285                panic!("early suspension before the threshold");
5286            };
5287            breaker
5288                .record_attributed_death_at(&key, &attempt.attempt_id, 0, 0, now)
5289                .expect("record death");
5290        }
5291
5292        let manager = InspectManager::new();
5293        let job = snapshot_job(&root, &inspect_dir, true);
5294        assert!(manager
5295            .build_tier2_callgraph_snapshot_with_refresh(&job, true, true, &files)
5296            .is_none());
5297        assert_eq!(
5298            manager.tier2_builder_state(InspectCategory::DeadCode),
5299            InspectBuilderState::Suspended
5300        );
5301        let detail = manager.tier2_builder_state_detail(InspectCategory::DeadCode);
5302        assert!(detail.starts_with("suspended domain=callgraph_cold deaths=3 age_s="));
5303        assert!(detail.ends_with("reason=zero_credit_death_limit"));
5304    }
5305
5306    #[test]
5307    fn readonly_tier2_projection_keeps_generation_pinned_through_concurrent_gc() {
5308        let dir = write_ts_project(3);
5309        let root = std::fs::canonicalize(dir.path()).expect("canonical root");
5310        let inspect_dir = root.join(".aft-cache").join("inspect");
5311        let callgraph_dir =
5312            callgraph_store_dir_from_inspect_dir(&inspect_dir, &root).expect("store dir");
5313        let files = crate::callgraph::walk_project_files(&root).collect::<Vec<_>>();
5314        let (store, _) =
5315            CallGraphStore::cold_build_with_lease(callgraph_dir.clone(), root.clone(), &files)
5316                .expect("initial generation");
5317        let initial_generation = store.sqlite_path().to_path_buf();
5318        drop(store);
5319        let project_key = crate::search_index::artifact_cache_key(&root);
5320        crate::root_cache::enable_writer_lease_acquisition_counts_for_test();
5321        // Delta-based counting: the enable flag is process-global and another
5322        // parallel test may have switched it on before this test's own setup
5323        // acquired its cold-build lease, so the absolute count is
5324        // enable-order-dependent. Only acquisitions inside the observed window
5325        // below are this assertion's business.
5326        let lease_count_before = crate::root_cache::writer_lease_acquisition_count_for_test(
5327            crate::root_cache::RootCacheDomain::Callgraph,
5328            &project_key,
5329            &root,
5330        );
5331
5332        let root_for_observer = root.clone();
5333        let dir_for_observer = callgraph_dir.clone();
5334        let files_for_observer = files.clone();
5335        crate::callgraph_store::set_projection_before_open_observer(Some(Arc::new(
5336            move |projected_path| {
5337                for _ in 0..3 {
5338                    let (published, _) = CallGraphStore::cold_build_with_lease(
5339                        dir_for_observer.clone(),
5340                        root_for_observer.clone(),
5341                        &files_for_observer,
5342                    )
5343                    .expect("concurrent generation publication");
5344                    drop(published);
5345                }
5346                assert!(
5347                    projected_path.is_file(),
5348                    "the tier2 reader marker must pin the selected generation through GC"
5349                );
5350            },
5351        )));
5352        let mut job = snapshot_job(&root, &inspect_dir, true);
5353        job.callgraph_writer = false;
5354
5355        let snapshot =
5356            build_tier2_callgraph_snapshot_with_refresh(&job, false, &[root.join("mod0.ts")]);
5357        crate::callgraph_store::set_projection_before_open_observer(None);
5358
5359        assert!(snapshot.is_some());
5360        assert!(initial_generation.is_file());
5361        assert_eq!(
5362            crate::root_cache::writer_lease_acquisition_count_for_test(
5363                crate::root_cache::RootCacheDomain::Callgraph,
5364                &project_key,
5365                &root,
5366            ) - lease_count_before,
5367            3,
5368            "only the three observer publications may acquire a writer lease; tier2 must stay read-only"
5369        );
5370    }
5371
5372    #[test]
5373    fn direct_callgraph_snapshot_does_not_cold_rebuild_when_store_needs_rebuild() {
5374        let dir = write_ts_project(3);
5375        let root = std::fs::canonicalize(dir.path()).expect("canonical root");
5376        let inspect_dir = root.join(".aft-cache").join("inspect");
5377        let callgraph_dir =
5378            callgraph_store_dir_from_inspect_dir(&inspect_dir, &root).expect("store dir");
5379        let store = CallGraphStore::open(callgraph_dir.clone(), root.clone()).expect("open store");
5380        let files = crate::callgraph::walk_project_files(&root).collect::<Vec<_>>();
5381        store.cold_build(&files).expect("cold build store");
5382        let sqlite_path = store.sqlite_path().to_path_buf();
5383        drop(store);
5384
5385        let still_existing_previous_root = root.with_file_name("previous-root-still-exists");
5386        std::fs::create_dir_all(&still_existing_previous_root).expect("create previous root");
5387        let conn = rusqlite::Connection::open(&sqlite_path).expect("open store sqlite");
5388        conn.execute(
5389            "UPDATE backend_file_state SET workspace_root = ?1",
5390            rusqlite::params![still_existing_previous_root.display().to_string()],
5391        )
5392        .expect("force root repair rebuild state");
5393        drop(conn);
5394
5395        let snapshot =
5396            build_tier2_callgraph_snapshot(&snapshot_job(&root, &inspect_dir, true), false)
5397                .expect("readonly snapshot should avoid cold-rebuilding the store");
5398
5399        assert_eq!(snapshot.files.len(), 3);
5400        let conn = rusqlite::Connection::open(&sqlite_path).expect("reopen store sqlite");
5401        let stored_root: String = conn
5402            .query_row(
5403                "SELECT workspace_root FROM backend_file_state LIMIT 1",
5404                [],
5405                |row| row.get(0),
5406            )
5407            .expect("read stored root");
5408        assert_eq!(
5409            stored_root,
5410            still_existing_previous_root.display().to_string(),
5411            "direct inspect must not cold-rebuild or re-root a read-only snapshot"
5412        );
5413    }
5414
5415    #[test]
5416    fn callgraph_snapshot_reads_ready_callgraph_store() {
5417        let dir = write_ts_project(3);
5418        let root = std::fs::canonicalize(dir.path()).expect("canonical root");
5419        let inspect_dir = root.join(".aft-cache").join("inspect");
5420        let callgraph_dir =
5421            callgraph_store_dir_from_inspect_dir(&inspect_dir, &root).expect("store dir");
5422        let store = CallGraphStore::open(callgraph_dir, root.clone()).expect("open store");
5423        let files = crate::callgraph::walk_project_files(&root).collect::<Vec<_>>();
5424        store.cold_build(&files).expect("cold build store");
5425
5426        let snapshot =
5427            build_tier2_callgraph_snapshot(&snapshot_job(&root, &inspect_dir, true), false)
5428                .expect("ready store snapshot");
5429
5430        assert_eq!(snapshot.files.len(), 3);
5431        assert_eq!(snapshot.exported_symbols.len(), 3);
5432    }
5433
5434    #[test]
5435    fn stale_callgraph_store_refreshes_inline_when_refresh_worker_does_not_run() {
5436        let dir = write_ts_project(2);
5437        let root = std::fs::canonicalize(dir.path()).expect("canonical root");
5438        let inspect_dir = root.join(".aft-cache").join("inspect");
5439        let callgraph_dir =
5440            callgraph_store_dir_from_inspect_dir(&inspect_dir, &root).expect("store dir");
5441        let project_key = crate::search_index::artifact_cache_key(&root);
5442        crate::root_cache::configure_artifact_access(&root, &project_key, false);
5443        let store = CallGraphStore::open(callgraph_dir.clone(), root.clone()).expect("open store");
5444        let files = crate::callgraph::walk_project_files(&root).collect::<Vec<_>>();
5445        store.cold_build(&files).expect("cold build store");
5446        store
5447            .mark_files_stale(&files)
5448            .expect("mark published store stale");
5449        drop(store);
5450
5451        let job = snapshot_job(&root, &inspect_dir, true);
5452        let manager = InspectManager::new();
5453        assert!(
5454            !manager.callgraph_ready_for_snapshot(&InspectSnapshot::new(
5455                root.clone(),
5456                inspect_dir.clone(),
5457                Arc::clone(&job.config),
5458                Arc::clone(&job.symbol_cache),
5459            )),
5460            "a store with leftover stale rows must not look callgraph-ready"
5461        );
5462
5463        let snapshot = manager
5464            .build_tier2_callgraph_snapshot_with_refresh(&job, false, false, &[])
5465            .expect("dead_code must refresh stale rows inline when the refresh worker never ran");
5466        assert_eq!(snapshot.files.len(), 2);
5467
5468        let ready = InspectSnapshot::new(
5469            root,
5470            inspect_dir,
5471            Arc::clone(&job.config),
5472            Arc::clone(&job.symbol_cache),
5473        );
5474        assert!(
5475            manager.callgraph_ready_for_snapshot(&ready),
5476            "after the inline refresh, callgraph_ready must agree with a successful projection"
5477        );
5478    }
5479
5480    #[test]
5481    fn callgraph_ready_and_builder_projection_agree_on_stale_rows() {
5482        let dir = write_ts_project(1);
5483        let root = std::fs::canonicalize(dir.path()).expect("canonical root");
5484        let inspect_dir = root.join(".aft-cache").join("inspect");
5485        let callgraph_dir =
5486            callgraph_store_dir_from_inspect_dir(&inspect_dir, &root).expect("store dir");
5487        let project_key = crate::search_index::artifact_cache_key(&root);
5488        crate::root_cache::configure_artifact_access(&root, &project_key, false);
5489        let store = CallGraphStore::open(callgraph_dir, root.clone()).expect("open store");
5490        let files = crate::callgraph::walk_project_files(&root).collect::<Vec<_>>();
5491        store.cold_build(&files).expect("cold build store");
5492        let sqlite_path = store.sqlite_path().to_path_buf();
5493        drop(store);
5494
5495        let job = snapshot_job(&root, &inspect_dir, true);
5496        let snapshot = InspectSnapshot::new(
5497            root.clone(),
5498            inspect_dir.clone(),
5499            Arc::clone(&job.config),
5500            Arc::clone(&job.symbol_cache),
5501        );
5502        let manager = InspectManager::new();
5503        assert!(
5504            manager.callgraph_ready_for_snapshot(&snapshot),
5505            "a fresh store must be ready for both the phase check and projection"
5506        );
5507        project_dead_code_snapshot(&sqlite_path).expect("fresh store should project");
5508
5509        let store = CallGraphStore::open_ready_no_rebuild(
5510            callgraph_store_dir_from_inspect_dir(&inspect_dir, &root).expect("store dir"),
5511            root.clone(),
5512        )
5513        .expect("reopen writer")
5514        .expect("ready writer");
5515        store.mark_files_stale(&files).expect("mark stale");
5516        drop(store);
5517
5518        assert!(
5519            !manager.callgraph_ready_for_snapshot(&snapshot),
5520            "callgraph_ready must use the same stale-row predicate as dead_code projection"
5521        );
5522        let error =
5523            project_dead_code_snapshot(&sqlite_path).expect_err("stale rows must block projection");
5524        match error {
5525            CallGraphStoreError::Unavailable(message) => {
5526                assert_eq!(message, "callgraph has stale files pending refresh")
5527            }
5528            other => panic!("expected Unavailable, got {other:?}"),
5529        }
5530    }
5531
5532    #[test]
5533    fn failed_builder_attempt_history_uses_locked_refusal_detail() {
5534        let manager = InspectManager::new();
5535        let unavailable = JobOutcome::Fresh {
5536            payload: crate::inspect::scanners::dead_code::callgraph_unavailable_aggregate(0),
5537        };
5538        manager
5539            .record_tier2_attempt_outcome_for_test(InspectCategory::DeadCode, unavailable.clone());
5540        let first = manager.tier2_builder_state_detail(InspectCategory::DeadCode);
5541        let first_at = first
5542            .rsplit("first at ")
5543            .next()
5544            .and_then(|tail| tail.strip_suffix(')'))
5545            .expect("first failure detail includes first-at unix time");
5546        for _ in 1..7 {
5547            manager.record_tier2_attempt_outcome_for_test(
5548                InspectCategory::DeadCode,
5549                unavailable.clone(),
5550            );
5551        }
5552        assert_eq!(
5553            manager.tier2_builder_state_detail(InspectCategory::DeadCode),
5554            format!("last attempt failed: callgraph_unavailable (attempt 7, first at {first_at})")
5555        );
5556        assert_eq!(
5557            manager.tier2_builder_state(InspectCategory::DeadCode),
5558            InspectBuilderState::Absent,
5559            "a finished failure must not keep the registry in an in-flight state"
5560        );
5561        assert_eq!(
5562            manager.try_tier2_builder_busy(),
5563            Some(false),
5564            "failed-attempt history must not look like a live rebuild"
5565        );
5566
5567        manager.record_tier2_attempt_outcome_for_test(
5568            InspectCategory::DeadCode,
5569            JobOutcome::Fresh {
5570                payload: serde_json::json!({ "callgraph_available": true, "count": 0 }),
5571            },
5572        );
5573        assert_eq!(
5574            manager.tier2_builder_state_detail(InspectCategory::DeadCode),
5575            InspectBuilderState::Absent.as_str()
5576        );
5577    }
5578
5579    #[test]
5580    fn generation_keyed_projection_cache_reuses_unchanged_snapshot() {
5581        let (_dir, _root, _inspect_dir, job) = published_projection_fixture();
5582        let manager = InspectManager::new();
5583        let (projections, _observer_reset) = count_projections();
5584
5585        let first = manager
5586            .build_tier2_callgraph_snapshot_with_refresh(&job, false, false, &[])
5587            .expect("first projection");
5588        let second = manager
5589            .build_tier2_callgraph_snapshot_with_refresh(&job, false, false, &[])
5590            .expect("cached projection");
5591
5592        assert!(
5593            Arc::ptr_eq(&first, &second),
5594            "an unchanged generation and write revision must reuse the projected Arc"
5595        );
5596        assert_eq!(
5597            projections.load(std::sync::atomic::Ordering::SeqCst),
5598            1,
5599            "two dead-code scans without a callgraph mutation must project once"
5600        );
5601        let memory = manager.callgraph_projection_estimated_memory();
5602        assert_eq!(
5603            memory.counts["callgraph_projection_snapshots"], 1,
5604            "the resident projection must be attributed to the root"
5605        );
5606        assert!(
5607            memory.estimated_bytes.unwrap_or_default() > 0,
5608            "a populated projection must report an estimated residency"
5609        );
5610    }
5611
5612    #[test]
5613    fn projection_cache_invalidates_on_in_place_refresh_for_readonly_scans() {
5614        let (_dir, root, inspect_dir, job) = published_projection_fixture();
5615        let manager = InspectManager::new();
5616        let (projections, _observer_reset) = count_projections();
5617        let target = root.join("src/target.ts");
5618        let callgraph_dir =
5619            callgraph_store_dir_from_inspect_dir(&inspect_dir, &root).expect("callgraph dir");
5620
5621        let first = manager
5622            .build_tier2_callgraph_snapshot_with_refresh(&job, false, false, &[])
5623            .expect("initial projection");
5624        let writer = CallGraphStore::open_ready_no_rebuild(callgraph_dir, root.clone())
5625            .expect("open writer")
5626            .expect("ready writer");
5627        let revision_before = writer
5628            .projection_write_revision()
5629            .expect("read initial revision")
5630            .expect("new stores write a projection revision");
5631        write_projection_cache_file(&target, "export function secondTarget() {}\n");
5632        writer
5633            .refresh_files(&[target])
5634            .expect("refresh changed target");
5635        let revision_after = writer
5636            .projection_write_revision()
5637            .expect("read refreshed revision")
5638            .expect("refreshed stores retain a projection revision");
5639        assert!(
5640            revision_after > revision_before,
5641            "the in-place refresh must advance the durable cache identity"
5642        );
5643        drop(writer);
5644
5645        let second = manager
5646            .build_tier2_callgraph_snapshot_with_refresh(&job, false, false, &[])
5647            .expect("refreshed readonly projection");
5648        assert!(
5649            !first
5650                .exported_symbols
5651                .iter()
5652                .any(|export| export.symbol == "secondTarget"),
5653            "the initial snapshot must not already contain the refreshed export"
5654        );
5655        assert!(
5656            second
5657                .exported_symbols
5658                .iter()
5659                .any(|export| export.symbol == "secondTarget"),
5660            "the readonly scan must expose graph data from the refreshed store"
5661        );
5662        assert_eq!(
5663            projections.load(std::sync::atomic::Ordering::SeqCst),
5664            2,
5665            "an in-place refresh must force the next scan to re-project"
5666        );
5667    }
5668
5669    #[test]
5670    fn projection_cache_invalidates_when_cold_build_publishes_new_generation() {
5671        let (_dir, root, inspect_dir, job) = published_projection_fixture();
5672        let manager = InspectManager::new();
5673        let (projections, _observer_reset) = count_projections();
5674        let target = root.join("src/target.ts");
5675        let callgraph_dir =
5676            callgraph_store_dir_from_inspect_dir(&inspect_dir, &root).expect("callgraph dir");
5677
5678        let first = manager
5679            .build_tier2_callgraph_snapshot_with_refresh(&job, false, false, &[])
5680            .expect("initial projection");
5681        let before = CallGraphStore::open_readonly(callgraph_dir.clone(), root.clone())
5682            .expect("open initial reader")
5683            .expect("initial reader");
5684        let revision_before = before
5685            .projection_write_revision()
5686            .expect("read initial revision")
5687            .expect("new stores write a projection revision");
5688        drop(before);
5689        write_projection_cache_file(&target, "export function coldBuildTarget() {}\n");
5690        let files = crate::callgraph::walk_project_files(&root).collect::<Vec<_>>();
5691        let (published, _) =
5692            CallGraphStore::cold_build_with_lease(callgraph_dir, root.clone(), &files)
5693                .expect("publish replacement generation");
5694        let revision_after = published
5695            .projection_write_revision()
5696            .expect("read replacement revision")
5697            .expect("replacement stores write a projection revision");
5698        assert_eq!(
5699            revision_after, revision_before,
5700            "cold builds begin with the same revision, so this assertion exercises the generation half of the cache identity"
5701        );
5702        drop(published);
5703
5704        let second = manager
5705            .build_tier2_callgraph_snapshot_with_refresh(&job, false, false, &[])
5706            .expect("replacement projection");
5707        assert!(
5708            !first
5709                .exported_symbols
5710                .iter()
5711                .any(|export| export.symbol == "coldBuildTarget"),
5712            "the initial snapshot must not already contain the replacement export"
5713        );
5714        assert!(
5715            second
5716                .exported_symbols
5717                .iter()
5718                .any(|export| export.symbol == "coldBuildTarget"),
5719            "the next scan must expose the generation published by the cold build"
5720        );
5721        assert_eq!(
5722            projections.load(std::sync::atomic::Ordering::SeqCst),
5723            2,
5724            "a new pointer generation must force the next scan to re-project"
5725        );
5726    }
5727
5728    #[test]
5729    fn idle_eviction_drops_generation_keyed_projection_cache() {
5730        let (_dir, _root, _inspect_dir, job) = published_projection_fixture();
5731        let manager = InspectManager::new();
5732        let (projections, _observer_reset) = count_projections();
5733
5734        let first = manager
5735            .build_tier2_callgraph_snapshot_with_refresh(&job, false, false, &[])
5736            .expect("initial projection");
5737        manager.evict_idle_caches();
5738        assert_eq!(
5739            manager.callgraph_projection_estimated_memory().counts
5740                ["callgraph_projection_snapshots"],
5741            0,
5742            "idle artifact eviction must release the root projection slot"
5743        );
5744        let second = manager
5745            .build_tier2_callgraph_snapshot_with_refresh(&job, false, false, &[])
5746            .expect("reloaded projection");
5747
5748        assert!(
5749            !Arc::ptr_eq(&first, &second),
5750            "eviction must drop the previous projection Arc"
5751        );
5752        assert_eq!(
5753            projections.load(std::sync::atomic::Ordering::SeqCst),
5754            2,
5755            "the next scan after idle eviction must reload the projection"
5756        );
5757    }
5758
5759    #[test]
5760    fn callgraph_snapshot_uses_ready_root_keyed_store() {
5761        let _git_env = crate::test_env::hermetic_git_env_guard();
5762        let dir = write_ts_project(3);
5763        let root = std::fs::canonicalize(dir.path()).expect("canonical root");
5764        let storage_dir = root.join(".aft-cache");
5765        let inspect_dir = storage_dir
5766            .join("inspect")
5767            .join(crate::path_identity::project_scope_key(&root));
5768        let warm_callgraph_dir = storage_dir
5769            .join("callgraph")
5770            .join(artifact_cache_key_for_test(&root));
5771        let store = CallGraphStore::open(warm_callgraph_dir, root.clone()).expect("open store");
5772        let files = crate::callgraph::walk_project_files(&root).collect::<Vec<_>>();
5773        store.cold_build(&files).expect("cold build store");
5774
5775        let snapshot =
5776            build_tier2_callgraph_snapshot(&snapshot_job(&root, &inspect_dir, true), false)
5777                .expect("ready sibling store snapshot");
5778
5779        assert_eq!(snapshot.files.len(), 3);
5780        assert_eq!(snapshot.exported_symbols.len(), 3);
5781    }
5782
5783    #[test]
5784    fn dead_code_forced_deletion_refreshes_callgraph_store_before_rollup() {
5785        let dir = tempfile::tempdir().expect("tempdir");
5786        let root = std::fs::canonicalize(dir.path()).expect("canonical root");
5787        write_fixture_file(
5788            &root,
5789            "package.json",
5790            r#"{"name":"dead-code-delete-refresh","type":"module","main":"src/main.ts"}"#,
5791            3_100_000_000,
5792        );
5793        write_fixture_file(
5794            &root,
5795            "src/main.ts",
5796            "export function main() {}\n",
5797            3_100_000_001,
5798        );
5799        write_fixture_file(
5800            &root,
5801            "src/dead.ts",
5802            "export function plantedDead() {}\n",
5803            3_100_000_002,
5804        );
5805
5806        let inspect_dir = root.join(".aft-cache").join("opencode").join("inspect");
5807        let callgraph_dir =
5808            callgraph_store_dir_from_inspect_dir(&inspect_dir, &root).expect("store dir");
5809        let project_key = crate::search_index::artifact_cache_key(&root);
5810        crate::root_cache::configure_artifact_access(&root, &project_key, false);
5811        let store = CallGraphStore::open(callgraph_dir.clone(), root.clone()).expect("open store");
5812        let project_files = crate::callgraph::walk_project_files(&root).collect::<Vec<_>>();
5813        store.cold_build(&project_files).expect("cold build store");
5814        drop(store);
5815
5816        let config = Arc::new(crate::config::Config {
5817            project_root: Some(root.clone()),
5818            callgraph_store: true,
5819            ..crate::config::Config::default()
5820        });
5821        let symbol_cache = Arc::new(std::sync::RwLock::new(crate::parser::SymbolCache::new()));
5822        let snapshot = InspectSnapshot::new(
5823            root.clone(),
5824            inspect_dir.clone(),
5825            Arc::clone(&config),
5826            Arc::clone(&symbol_cache),
5827        );
5828        let manager = InspectManager::new();
5829        let initial_job =
5830            manager.tier2_reuse_job(snapshot.clone(), InspectCategory::DeadCode, None);
5831        let initial = manager
5832            .tier2_run_with_reuse_job_result_with_options(initial_job, Tier2ReuseOptions::default())
5833            .outcome
5834            .expect("initial dead_code scan succeeds")
5835            .aggregate;
5836        assert!(
5837            aggregate_has_file_symbol(&initial, "src/dead.ts", "plantedDead"),
5838            "initial scan should report the planted dead export: {initial:#}"
5839        );
5840
5841        let deleted = root.join("src/dead.ts");
5842        std::fs::remove_file(&deleted).expect("delete dead fixture");
5843        let delete_job = manager.tier2_reuse_job(snapshot, InspectCategory::DeadCode, None);
5844        let refreshed = manager
5845            .tier2_run_with_reuse_job_result_with_options(
5846                delete_job,
5847                Tier2ReuseOptions {
5848                    force_rescan_paths: [deleted.clone()].into_iter().collect(),
5849                    allow_callgraph_cold_build: true,
5850                    require_callgraph_snapshot: false,
5851                    interactive: false,
5852                },
5853            )
5854            .outcome
5855            .expect("delete refresh dead_code scan succeeds")
5856            .aggregate;
5857
5858        assert_eq!(
5859            refreshed
5860                .get("callgraph_available")
5861                .and_then(Value::as_bool),
5862            Some(true),
5863            "forced watcher paths must keep the callgraph-backed aggregate available: {refreshed:#}"
5864        );
5865        assert!(
5866            !aggregate_has_file_symbol(&refreshed, "src/dead.ts", "plantedDead"),
5867            "delete refresh should remove the planted dead export: {refreshed:#}"
5868        );
5869
5870        let store = CallGraphStore::open_ready_no_rebuild(callgraph_dir, root)
5871            .expect("open refreshed store")
5872            .expect("refreshed store is ready");
5873        let projected = project_dead_code_snapshot(store.sqlite_path()).expect("project snapshot");
5874        assert!(
5875            projected
5876                .files
5877                .iter()
5878                .all(|file| !file.ends_with("src/dead.ts")),
5879            "watcher deletion should be applied to the persisted callgraph store: {:#?}",
5880            projected.files
5881        );
5882    }
5883
5884    fn aggregate_has_file_symbol(aggregate: &Value, file: &str, symbol: &str) -> bool {
5885        aggregate
5886            .get("items")
5887            .and_then(Value::as_array)
5888            .is_some_and(|items| {
5889                items.iter().any(|item| {
5890                    item.get("file").and_then(Value::as_str) == Some(file)
5891                        && item.get("symbol").and_then(Value::as_str) == Some(symbol)
5892                })
5893            })
5894    }
5895
5896    // A scoped payload must not carry the project-wide `by_language` breakdown
5897    // alongside the recomputed in-scope count — that contradiction renders as
5898    // e.g. "Dead code: 1 (rust 214, ts 143)".
5899    #[test]
5900    fn scoped_filter_drops_project_wide_by_language() {
5901        let scope = JobScope::from_roots("/proj", vec![PathBuf::from("/proj/src/a")]);
5902        assert!(
5903            !scope.is_project_wide(),
5904            "scope must be non-project for test"
5905        );
5906        let payload = serde_json::json!({
5907            "count": 99,
5908            "by_language": { "rust": 214, "typescript": 143 },
5909            "items": [
5910                { "file": "/proj/src/a/x.rs", "symbol": "live" },
5911                { "file": "/proj/src/other/y.rs", "symbol": "out" },
5912            ],
5913        });
5914        let filtered = filter_payload_for_scope(payload, &scope);
5915        assert!(
5916            filtered.get("by_language").is_none(),
5917            "scoped payload must drop project-wide by_language: {filtered}"
5918        );
5919        // Count is recomputed to the in-scope items (only x.rs under src/a).
5920        assert_eq!(filtered.get("count").and_then(|v| v.as_u64()), Some(1));
5921    }
5922    #[cfg(debug_assertions)]
5923    #[test]
5924    fn tier2_read_cached_freshness_does_not_hash_unchanged_contributions() {
5925        let (_dir, manager, snapshot, scope, _files) = duplicate_cache_fixture();
5926        let fixture_root = snapshot.project_root.clone();
5927
5928        crate::cache_freshness::reset_hash_file_if_small_count_for_debug();
5929        crate::cache_freshness::reset_verify_file_strict_count_for_debug();
5930        assert_fresh(manager.tier2_read_cached(snapshot, InspectCategory::Duplicates, scope));
5931
5932        assert_eq!(
5933            crate::cache_freshness::verify_file_strict_count_under_for_debug(&fixture_root),
5934            0,
5935            "dispatch-thread inspect freshness must not use strict verification"
5936        );
5937        assert_eq!(
5938            crate::cache_freshness::hash_file_if_small_count_for_debug(),
5939            0,
5940            "unchanged contribution files must stay on the stat-only fast path"
5941        );
5942    }
5943
5944    #[cfg(debug_assertions)]
5945    #[test]
5946    fn tier2_read_cached_freshness_returns_byte_identical_cold_scan_aggregate() {
5947        let (_dir, manager, snapshot, scope, _files) = duplicate_uncached_fixture();
5948        let cold_payload = fresh_payload(manager.tier2_run_with_reuse(
5949            snapshot.clone(),
5950            InspectCategory::Duplicates,
5951            scope.clone(),
5952            None,
5953        ));
5954
5955        crate::cache_freshness::reset_hash_file_if_small_count_for_debug();
5956        crate::cache_freshness::reset_verify_file_strict_count_for_debug();
5957        let fixture_root = snapshot.project_root.clone();
5958        let warm_payload =
5959            fresh_payload(manager.tier2_read_cached(snapshot, InspectCategory::Duplicates, scope));
5960
5961        let cold_bytes = serde_json::to_vec(&cold_payload).expect("serialize cold aggregate");
5962        let warm_bytes = serde_json::to_vec(&warm_payload).expect("serialize warm aggregate");
5963        assert_eq!(
5964            warm_bytes, cold_bytes,
5965            "warm unchanged read must return the byte-identical aggregate as the cold scan"
5966        );
5967        assert_eq!(
5968            crate::cache_freshness::verify_file_strict_count_under_for_debug(&fixture_root),
5969            0,
5970            "dispatch-thread warm read must not use strict verification"
5971        );
5972        assert_eq!(
5973            crate::cache_freshness::hash_file_if_small_count_for_debug(),
5974            0,
5975            "warm unchanged read must not content-hash cached contribution files"
5976        );
5977    }
5978
5979    #[test]
5980    fn tier2_read_cached_freshness_detects_changed_added_and_deleted_files() {
5981        let (_dir, manager, snapshot, scope, _files) = duplicate_cache_fixture();
5982        write_fixture_file(
5983            &snapshot.project_root,
5984            "src/foo.ts",
5985            "export const foo = 101;\nexport const changed = true;\n",
5986            3_000_000_001,
5987        );
5988        assert_stale(manager.tier2_read_cached(snapshot, InspectCategory::Duplicates, scope));
5989
5990        let (_dir, manager, snapshot, scope, _files) = duplicate_cache_fixture();
5991        write_fixture_file(
5992            &snapshot.project_root,
5993            "src/added.ts",
5994            "export const added = 3;\n",
5995            3_000_000_002,
5996        );
5997        assert_stale(manager.tier2_read_cached(snapshot, InspectCategory::Duplicates, scope));
5998
5999        let (_dir, manager, snapshot, scope, files) = duplicate_cache_fixture();
6000        std::fs::remove_file(&files[0]).expect("delete cached contribution file");
6001        assert_stale(manager.tier2_read_cached(snapshot, InspectCategory::Duplicates, scope));
6002    }
6003
6004    fn duplicate_cache_fixture() -> (
6005        tempfile::TempDir,
6006        InspectManager,
6007        InspectSnapshot,
6008        JobScope,
6009        Vec<PathBuf>,
6010    ) {
6011        let (dir, manager, snapshot, scope, files) = duplicate_uncached_fixture();
6012        store_duplicate_cache(&manager, &snapshot, &files);
6013        (dir, manager, snapshot, scope, files)
6014    }
6015
6016    fn duplicate_uncached_fixture() -> (
6017        tempfile::TempDir,
6018        InspectManager,
6019        InspectSnapshot,
6020        JobScope,
6021        Vec<PathBuf>,
6022    ) {
6023        use crate::config::Config;
6024        use crate::parser::SymbolCache;
6025        use std::sync::RwLock;
6026
6027        let dir = tempfile::tempdir().expect("tempdir");
6028        let root = std::fs::canonicalize(dir.path()).expect("canonical fixture root");
6029        let files = vec![
6030            write_fixture_file(
6031                &root,
6032                "src/foo.ts",
6033                "export const fixture = () => 1;
6034export const shared = 1;
6035",
6036                3_000_000_000,
6037            ),
6038            write_fixture_file(
6039                &root,
6040                "src/bar.ts",
6041                "export const fixture = () => 1;
6042export const shared = 1;
6043",
6044                3_000_000_000,
6045            ),
6046        ];
6047        let inspect_dir = root.join(".aft-cache").join("inspect");
6048        let snapshot = InspectSnapshot::new(
6049            root.clone(),
6050            inspect_dir,
6051            Arc::new(Config {
6052                project_root: Some(root.clone()),
6053                ..Config::default()
6054            }),
6055            Arc::new(RwLock::new(SymbolCache::new())),
6056        );
6057        let scope = JobScope::for_project(root);
6058        let manager = InspectManager::new();
6059        (dir, manager, snapshot, scope, files)
6060    }
6061
6062    fn write_fixture_file(root: &Path, relative: &str, content: &str, mtime_secs: i64) -> PathBuf {
6063        let path = root.join(relative);
6064        if let Some(parent) = path.parent() {
6065            std::fs::create_dir_all(parent).expect("create fixture parent");
6066        }
6067        std::fs::write(&path, content).expect("write fixture file");
6068        filetime::set_file_mtime(&path, filetime::FileTime::from_unix_time(mtime_secs, 0))
6069            .expect("set fixture mtime");
6070        path
6071    }
6072
6073    fn store_duplicate_cache(
6074        manager: &InspectManager,
6075        snapshot: &InspectSnapshot,
6076        files: &[PathBuf],
6077    ) {
6078        let cache = manager
6079            .cache_for_snapshot(snapshot)
6080            .expect("open inspect cache");
6081        let contributions = files
6082            .iter()
6083            .map(|file| {
6084                let freshness = crate::cache_freshness::collect(file).expect("collect freshness");
6085                FileContribution::new(
6086                    InspectCategory::Duplicates,
6087                    file.clone(),
6088                    freshness,
6089                    serde_json::json!({
6090                        "file": relative_cache_key(&snapshot.project_root, file),
6091                        "fragments": [],
6092                    }),
6093                )
6094            })
6095            .collect::<Vec<_>>();
6096        cache
6097            .store_tier2_result(
6098                JobKey::for_project_category(InspectCategory::Duplicates),
6099                files,
6100                &contributions,
6101                serde_json::json!({
6102                    "count": 0,
6103                    "groups": [],
6104                    "scanned_files": files.len(),
6105                    "total_groups": 0,
6106                }),
6107            )
6108            .expect("store tier2 cache fixture");
6109    }
6110
6111    fn assert_fresh(outcome: JobOutcome) {
6112        let _ = fresh_payload(outcome);
6113    }
6114
6115    fn fresh_payload(outcome: JobOutcome) -> Value {
6116        match outcome {
6117            JobOutcome::Fresh { payload } => payload,
6118            other => panic!("expected fresh cached Tier-2 outcome, got {other:?}"),
6119        }
6120    }
6121
6122    fn assert_stale(outcome: JobOutcome) {
6123        match outcome {
6124            JobOutcome::Stale { .. } => {}
6125            other => panic!("expected stale cached Tier-2 outcome, got {other:?}"),
6126        }
6127    }
6128}
6129
6130#[cfg(test)]
6131mod dead_code_projection_tests {
6132    use super::*;
6133    use crate::callgraph::walk_project_files;
6134    use crate::callgraph_store::{project_dead_code_snapshot, CallGraphStore};
6135    use crate::config::Config;
6136    use crate::inspect::job::DISPATCHED_CALLEE_SEPARATOR;
6137    use crate::inspect::scanners::DEFAULT_EXPORT_MARKER_KIND;
6138    use crate::parser::SymbolCache;
6139    use filetime::FileTime;
6140    use std::sync::atomic::{AtomicI64, Ordering as AtomicOrdering};
6141    use std::sync::RwLock;
6142
6143    static NEXT_MTIME: AtomicI64 = AtomicI64::new(1_900_000_000);
6144
6145    #[test]
6146    fn scoped_dead_code_rollup_uses_ready_callgraph_and_degrades_without_it() {
6147        let dir = tempfile::tempdir().expect("tempdir");
6148        write_projection_fixture(dir.path());
6149        let root = canonical_root(dir.path());
6150        let inspect_dir = root.join(".aft-cache").join("inspect");
6151        let callgraph_dir =
6152            callgraph_store_dir_from_inspect_dir(&inspect_dir, &root).expect("store dir");
6153        let project_key = crate::search_index::artifact_cache_key(&root);
6154        crate::root_cache::configure_artifact_access(&root, &project_key, false);
6155        let store = CallGraphStore::open(callgraph_dir.clone(), root.clone()).expect("open store");
6156        let files = project_files(&root);
6157        store.cold_build(&files).expect("cold build store");
6158        let projected = project_dead_code_snapshot(store.sqlite_path()).expect("project snapshot");
6159        drop(store);
6160
6161        let config = Arc::new(Config {
6162            project_root: Some(root.clone()),
6163            callgraph_store: true,
6164            ..Config::default()
6165        });
6166        let symbol_cache = Arc::new(RwLock::new(SymbolCache::new()));
6167        let scan_job = InspectJob {
6168            job_id: 87,
6169            key: JobKey::for_project_category(InspectCategory::DeadCode),
6170            category: InspectCategory::DeadCode,
6171            scope_files: files.clone(),
6172            project_root: root.clone(),
6173            inspect_dir: inspect_dir.clone(),
6174            config: Arc::clone(&config),
6175            symbol_cache: Arc::clone(&symbol_cache),
6176            inspect_writer: true,
6177            callgraph_writer: true,
6178            callgraph_snapshot: Some(Arc::new(projected)),
6179        };
6180        let success = crate::inspect::scanners::dead_code::run_dead_code_scan(&scan_job)
6181            .outcome
6182            .expect("dead_code scan succeeds");
6183        let cache = InspectCache::open(inspect_dir.clone(), root.clone()).expect("open cache");
6184        cache
6185            .store_tier2_result(
6186                scan_job.key.clone(),
6187                &success.scanned_files,
6188                &success.contributions,
6189                success.aggregate.clone(),
6190            )
6191            .expect("store tier2 result");
6192
6193        let snapshot = InspectSnapshot::new(root.clone(), inspect_dir, config, symbol_cache);
6194        let scope = JobScope::from_roots(root.clone(), vec![root.join("src/live.ts")]);
6195        assert!(
6196            !scope.is_project_wide(),
6197            "live.ts file scope must be scoped"
6198        );
6199
6200        let ready_payload = scoped_tier2_payload_from_contributions(
6201            &snapshot,
6202            InspectCategory::DeadCode,
6203            &cache,
6204            success.aggregate.clone(),
6205            &scope,
6206        )
6207        .expect("ready scoped payload");
6208        assert_eq!(
6209            ready_payload
6210                .get("callgraph_available")
6211                .and_then(Value::as_bool),
6212            Some(true),
6213            "ready store should produce a callgraph-backed scoped rollup: {ready_payload:#}"
6214        );
6215        assert_live_item(&ready_payload, "src/live.ts", "knownLive");
6216
6217        std::fs::remove_dir_all(&callgraph_dir).expect("remove ready callgraph store");
6218        let unavailable_payload = scoped_tier2_payload_from_contributions(
6219            &snapshot,
6220            InspectCategory::DeadCode,
6221            &cache,
6222            success.aggregate,
6223            &scope,
6224        )
6225        .expect("unavailable scoped payload");
6226        assert_eq!(
6227            unavailable_payload
6228                .get("callgraph_available")
6229                .and_then(Value::as_bool),
6230            Some(false),
6231            "missing store must report callgraph_unavailable instead of fabricating an empty graph: {unavailable_payload:#}"
6232        );
6233        assert_live_item(&unavailable_payload, "src/live.ts", "knownLive");
6234    }
6235    #[derive(Debug, PartialEq, Eq)]
6236    struct ComparableSnapshot {
6237        files: BTreeSet<PathBuf>,
6238        exported_symbols: BTreeSet<(PathBuf, String, String, u32)>,
6239        outbound_calls: BTreeSet<(PathBuf, String, String, u32)>,
6240        entry_points: BTreeSet<PathBuf>,
6241        entry_point_symbols: BTreeMap<PathBuf, BTreeSet<String>>,
6242    }
6243
6244    #[test]
6245    fn dead_code_projection_contains_expected_fixture_surface() {
6246        let dir = tempfile::tempdir().expect("tempdir");
6247        write_projection_fixture(dir.path());
6248        let root = canonical_root(dir.path());
6249        let projected = store_projected_snapshot(&root, ".store-dead-code-surface");
6250
6251        assert_projection_fixture_coverage(&root, &projected);
6252    }
6253
6254    #[test]
6255    fn dead_code_projection_incremental_scenario_matrix_matches_cold_rebuild() {
6256        run_projection_scenario("rename", setup_projection_rename, edit_projection_rename);
6257        run_projection_scenario("delete", setup_projection_delete, edit_projection_delete);
6258        run_projection_scenario(
6259            "barrel delete",
6260            setup_projection_barrel,
6261            edit_projection_barrel_delete,
6262        );
6263        run_projection_scenario(
6264            "dispatch edit",
6265            setup_projection_dispatch,
6266            edit_projection_dispatch,
6267        );
6268        run_projection_scenario(
6269            "body-only edit",
6270            setup_projection_body_only,
6271            edit_projection_body_only,
6272        );
6273    }
6274
6275    #[test]
6276    fn dead_code_projection_dead_code_scan_reports_expected_verdicts() {
6277        let dir = tempfile::tempdir().expect("tempdir");
6278        write_projection_fixture(dir.path());
6279        let root = canonical_root(dir.path());
6280        let files = project_files(&root);
6281        let projected = store_projected_snapshot(&root, ".store-dead-code-e2e");
6282
6283        let projected_aggregate = dead_code_aggregate(&root, files, projected);
6284        assert_dead_item(&projected_aggregate, "src/dead.ts", "knownDead");
6285        assert_live_item(&projected_aggregate, "src/live.ts", "knownLive");
6286        assert_live_item(&projected_aggregate, "src/render.ts", "render");
6287        assert_live_item(&projected_aggregate, "src/other_render.ts", "render");
6288    }
6289
6290    #[test]
6291    fn dead_code_projection_rust_attribute_entry_points_are_live() {
6292        let dir = tempfile::tempdir().expect("tempdir");
6293        write_rust_attribute_entry_fixture(dir.path());
6294        let root = canonical_root(dir.path());
6295        let files = project_files(&root);
6296        let store = CallGraphStore::open(root.join(".store-tauri-commands"), root.clone())
6297            .expect("open store");
6298        store.cold_build(&files).expect("cold build store");
6299        let command = store
6300            .node_for(Path::new("src/commands.rs"), "get_primers")
6301            .expect("command node");
6302        assert!(
6303            command.is_entry_point,
6304            "attribute-rooted commands must be labeled as callgraph entry points"
6305        );
6306        let private_command = store
6307            .node_for(Path::new("src/commands.rs"), "private_command")
6308            .expect("private command node");
6309        assert!(
6310            private_command.is_entry_point,
6311            "private attribute-rooted commands must also be callgraph entry points"
6312        );
6313
6314        let projected = project_dead_code_snapshot(store.sqlite_path()).expect("project snapshot");
6315        let aggregate = dead_code_aggregate(&root, files, projected);
6316        assert_live_item(&aggregate, "src/commands.rs", "get_primers");
6317        assert_live_item(&aggregate, "src/db.rs", "helper");
6318        assert_live_item(&aggregate, "src/db.rs", "private_helper");
6319        assert_live_item(&aggregate, "src/imported.rs", "imported_command");
6320        assert_live_item(&aggregate, "src/db.rs", "imported_helper");
6321        assert_dead_item(&aggregate, "src/commands.rs", "planted_dead");
6322        assert_dead_item(&aggregate, "src/unimported.rs", "false_command");
6323        assert_dead_item(&aggregate, "src/db.rs", "false_helper");
6324    }
6325
6326    #[test]
6327    fn dead_code_projection_rust_attribute_roots_are_cold_deterministic() {
6328        let dir = tempfile::tempdir().expect("tempdir");
6329        write_rust_attribute_entry_fixture(dir.path());
6330        let root = canonical_root(dir.path());
6331        let first = store_projected_snapshot(&root, ".store-tauri-cold-a");
6332        let second = store_projected_snapshot(&root, ".store-tauri-cold-b");
6333
6334        assert_snapshot_parts_eq("rust attribute roots cold", &first, &second);
6335    }
6336
6337    #[test]
6338    fn dead_code_projection_rust_attribute_roots_survive_unrelated_incremental_edit() {
6339        let dir = tempfile::tempdir().expect("tempdir");
6340        write_rust_attribute_entry_fixture(dir.path());
6341        let root = canonical_root(dir.path());
6342        let files_before = project_files(&root);
6343        let incremental_store =
6344            CallGraphStore::open(root.join(".store-tauri-incremental"), root.clone())
6345                .expect("open incremental store");
6346        incremental_store
6347            .cold_build(&files_before)
6348            .expect("initial cold build");
6349
6350        write_file(
6351            &root.join("src/unrelated.rs"),
6352            r#"// unrelated edit should not refresh command attribute facts
6353pub fn unrelated() -> u32 { 2 }
6354"#,
6355        );
6356        let stats = incremental_store
6357            .refresh_files(&[root.join("src/unrelated.rs")])
6358            .expect("refresh unrelated file");
6359        assert_eq!(stats.refreshed_own_files, 1);
6360        assert_eq!(stats.changed_files, vec!["src/unrelated.rs".to_string()]);
6361        assert!(
6362            !stats
6363                .surface_changed
6364                .iter()
6365                .any(|file| file == "src/commands.rs"),
6366            "unrelated edit must not refresh the command module: {stats:#?}"
6367        );
6368        let incremental = project_dead_code_snapshot(incremental_store.sqlite_path())
6369            .expect("project incremental snapshot");
6370
6371        let cold_store = CallGraphStore::open(root.join(".store-tauri-cold"), root.clone())
6372            .expect("open cold store");
6373        cold_store
6374            .cold_build(&project_files(&root))
6375            .expect("cold rebuild");
6376        let cold = project_dead_code_snapshot(cold_store.sqlite_path()).expect("project cold");
6377        assert_snapshot_parts_eq("rust attribute roots unrelated edit", &cold, &incremental);
6378
6379        let aggregate = dead_code_aggregate(&root, project_files(&root), incremental);
6380        assert_live_item(&aggregate, "src/commands.rs", "get_primers");
6381        assert_live_item(&aggregate, "src/db.rs", "helper");
6382        assert_live_item(&aggregate, "src/db.rs", "private_helper");
6383        assert_dead_item(&aggregate, "src/commands.rs", "planted_dead");
6384    }
6385
6386    fn assert_projection_fixture_coverage(root: &Path, snapshot: &CallgraphSnapshot) {
6387        let comparable = comparable_snapshot(snapshot);
6388        assert!(
6389            comparable
6390                .files
6391                .iter()
6392                .any(|file| file.extension().and_then(|ext| ext.to_str()) == Some("ts")),
6393            "fixture must include TypeScript files: {:#?}",
6394            comparable.files
6395        );
6396        assert!(
6397            comparable
6398                .files
6399                .iter()
6400                .any(|file| file.extension().and_then(|ext| ext.to_str()) == Some("js")),
6401            "fixture must include JavaScript files: {:#?}",
6402            comparable.files
6403        );
6404        assert!(
6405            comparable
6406                .files
6407                .iter()
6408                .any(|file| file.extension().and_then(|ext| ext.to_str()) == Some("rs")),
6409            "fixture must include Rust files: {:#?}",
6410            comparable.files
6411        );
6412
6413        let main_file = canonicalize_for_snapshot(&root.join("src/main.ts"));
6414        let private_dispatch_target = format!("{}::dispatch", main_file.display());
6415        assert!(
6416            comparable
6417                .outbound_calls
6418                .iter()
6419                .any(
6420                    |(caller_file, caller_symbol, target, _)| caller_file == &main_file
6421                        && caller_symbol == "main"
6422                        && target == &private_dispatch_target
6423                ),
6424            "fixture must cover same-file private fallback target {private_dispatch_target}: {:#?}",
6425            comparable.outbound_calls
6426        );
6427        assert!(
6428            comparable
6429                .outbound_calls
6430                .iter()
6431                .any(|(_, _, target, _)| target.contains(DISPATCHED_CALLEE_SEPARATOR)),
6432            "fixture must cover method-dispatch suffixes: {:#?}",
6433            comparable.outbound_calls
6434        );
6435        assert!(
6436            comparable
6437                .exported_symbols
6438                .iter()
6439                .any(|(_, symbol, kind, _)| symbol == "runDefault"
6440                    && kind == DEFAULT_EXPORT_MARKER_KIND),
6441            "fixture must cover default-export marker rows: {:#?}",
6442            comparable.exported_symbols
6443        );
6444    }
6445
6446    fn run_projection_scenario(name: &str, setup: fn(&Path), edit: fn(&Path) -> Vec<PathBuf>) {
6447        let dir = tempfile::tempdir().expect("tempdir");
6448        setup(dir.path());
6449        let root = canonical_root(dir.path());
6450        let files_before = project_files(&root);
6451        let incremental_store = CallGraphStore::open(
6452            root.join(format!(".store-dead-code-projection-{name}-incremental")),
6453            root.clone(),
6454        )
6455        .expect("open incremental store");
6456        incremental_store
6457            .cold_build(&files_before)
6458            .expect("initial cold build");
6459
6460        let changed = edit(&root);
6461        incremental_store
6462            .refresh_files(&changed)
6463            .expect("refresh changed files");
6464        let incremental = project_dead_code_snapshot(incremental_store.sqlite_path())
6465            .expect("project incremental snapshot");
6466
6467        let cold_store = CallGraphStore::open(
6468            root.join(format!(".store-dead-code-projection-{name}-cold")),
6469            root.clone(),
6470        )
6471        .expect("open cold store");
6472        cold_store
6473            .cold_build(&project_files(&root))
6474            .expect("cold rebuild");
6475        let cold =
6476            project_dead_code_snapshot(cold_store.sqlite_path()).expect("project cold snapshot");
6477
6478        assert_snapshot_parts_eq(name, &cold, &incremental);
6479    }
6480
6481    /// Store-backed dead_code benchmark. Measures, on a real checkout, the
6482    /// persisted-store cold build, the warm SQLite projection cost, and the
6483    /// remaining `run_dead_code_scan` cost (per-file reexport/type-ref reparse +
6484    /// BFS roll-up). Production Tier-2 reads a warm store; cold_build is included
6485    /// here only to make end-to-end store cost visible.
6486    /// Ignored by default; run with:
6487    ///   AFT_BENCH_REPO=/path/to/large/repo cargo test -p agent-file-tools --lib \
6488    ///     -- --ignored --nocapture --test-threads=1 dead_code_decision_b_benchmark
6489    #[test]
6490    #[ignore = "manual benchmark; needs AFT_BENCH_REPO pointing at a large checkout"]
6491    fn dead_code_decision_b_benchmark() {
6492        let Ok(repo) = std::env::var("AFT_BENCH_REPO") else {
6493            eprintln!("AFT_BENCH_REPO unset; skipping");
6494            return;
6495        };
6496        // Each phase flushes immediately so a file-redirected run shows live progress.
6497        macro_rules! mark {
6498            ($($a:tt)*) => {{ eprintln!($($a)*); let _ = std::io::Write::flush(&mut std::io::stderr()); }};
6499        }
6500        let root = canonical_root(Path::new(&repo));
6501        let files = project_files(&root);
6502        mark!(
6503            "\n=== Store-backed dead_code benchmark ===\nrepo: {}\nsource files (walk_project_files): {}\nstarted store cold_build...",
6504            root.display(),
6505            files.len()
6506        );
6507
6508        // Store cold_build + projection. Production warm runs skip cold_build and
6509        // pay only the projection below.
6510        let store_dir = root.join(".aft-bench-store");
6511        let _ = std::fs::remove_dir_all(&store_dir);
6512        let store = CallGraphStore::open(store_dir.clone(), root.clone()).expect("open store");
6513        let t = Instant::now();
6514        let cold_stats = store.cold_build(&files).expect("store cold build");
6515        let store_build_ms = t.elapsed().as_millis();
6516        let t = Instant::now();
6517        let projected = project_dead_code_snapshot(store.sqlite_path()).expect("projection");
6518        let proj_ms = t.elapsed().as_millis();
6519        mark!(
6520            "store cold_build: {} ms ({:?}) + projection: {} ms = {} ms  (exports={}, outbound={})\nstarted scan...",
6521            store_build_ms, cold_stats, proj_ms, store_build_ms + proj_ms,
6522            projected.exported_symbols.len(), projected.outbound_calls.len()
6523        );
6524
6525        // Remaining scanner cost: run_dead_code_scan given a ready snapshot.
6526        let t = Instant::now();
6527        let _result = dead_code_aggregate(&root, files.clone(), projected.clone());
6528        let scan_ms = t.elapsed().as_millis();
6529        mark!("run_dead_code_scan (cold contributions): {} ms", scan_ms);
6530
6531        mark!(
6532            "\nSUMMARY  files={}  store_cold_plus_projection={}ms  projection={}ms  scan_cold={}ms  total={}ms",
6533            files.len(),
6534            store_build_ms + proj_ms,
6535            proj_ms,
6536            scan_ms,
6537            store_build_ms + proj_ms + scan_ms
6538        );
6539        let _ = std::fs::remove_dir_all(&store_dir);
6540    }
6541
6542    fn store_projected_snapshot(root: &Path, store_name: &str) -> CallgraphSnapshot {
6543        let store =
6544            CallGraphStore::open(root.join(store_name), root.to_path_buf()).expect("open store");
6545        store
6546            .cold_build(&project_files(root))
6547            .expect("store cold build");
6548        project_dead_code_snapshot(store.sqlite_path()).expect("project snapshot")
6549    }
6550
6551    fn dead_code_aggregate(
6552        root: &Path,
6553        scope_files: Vec<PathBuf>,
6554        snapshot: CallgraphSnapshot,
6555    ) -> Value {
6556        let job = InspectJob {
6557            job_id: 86,
6558            key: JobKey::for_project_category(InspectCategory::DeadCode),
6559            category: InspectCategory::DeadCode,
6560            scope_files,
6561            project_root: root.to_path_buf(),
6562            inspect_dir: root.join(".aft-cache").join("inspect"),
6563            config: Arc::new(Config {
6564                project_root: Some(root.to_path_buf()),
6565                ..Config::default()
6566            }),
6567            symbol_cache: Arc::new(RwLock::new(SymbolCache::new())),
6568            inspect_writer: true,
6569            callgraph_writer: true,
6570            callgraph_snapshot: Some(Arc::new(snapshot)),
6571        };
6572        crate::inspect::scanners::dead_code::run_dead_code_scan(&job)
6573            .outcome
6574            .expect("dead_code scan succeeds")
6575            .aggregate
6576    }
6577
6578    fn assert_snapshot_parts_eq(
6579        label: &str,
6580        expected: &CallgraphSnapshot,
6581        actual: &CallgraphSnapshot,
6582    ) {
6583        let expected = comparable_snapshot(expected);
6584        let actual = comparable_snapshot(actual);
6585        assert_eq!(
6586            actual, expected,
6587            "{label} store-projected snapshot must match cold store snapshot"
6588        );
6589    }
6590
6591    fn comparable_snapshot(snapshot: &CallgraphSnapshot) -> ComparableSnapshot {
6592        ComparableSnapshot {
6593            files: snapshot.files.iter().cloned().collect(),
6594            exported_symbols: snapshot
6595                .exported_symbols
6596                .iter()
6597                .map(|export| {
6598                    (
6599                        export.file.clone(),
6600                        export.symbol.clone(),
6601                        export.kind.clone(),
6602                        export.line,
6603                    )
6604                })
6605                .collect(),
6606            outbound_calls: snapshot
6607                .outbound_calls
6608                .iter()
6609                .map(|call| {
6610                    (
6611                        call.caller_file.clone(),
6612                        call.caller_symbol.clone(),
6613                        call.target.clone(),
6614                        call.line,
6615                    )
6616                })
6617                .collect(),
6618            entry_points: snapshot.entry_points.clone(),
6619            entry_point_symbols: snapshot.entry_point_symbols.clone(),
6620        }
6621    }
6622
6623    fn assert_dead_item(aggregate: &Value, file: &str, symbol: &str) {
6624        assert!(
6625            aggregate_has_item(aggregate, file, symbol),
6626            "expected {file}::{symbol} to be reported dead: {aggregate:#}"
6627        );
6628    }
6629
6630    fn assert_live_item(aggregate: &Value, file: &str, symbol: &str) {
6631        assert!(
6632            !aggregate_has_item(aggregate, file, symbol),
6633            "expected {file}::{symbol} to be live/not reported dead: {aggregate:#}"
6634        );
6635    }
6636
6637    fn aggregate_has_item(aggregate: &Value, file: &str, symbol: &str) -> bool {
6638        let Some(items) = aggregate.get("items").and_then(Value::as_array) else {
6639            return false;
6640        };
6641        items.iter().any(|item| {
6642            item.get("file").and_then(Value::as_str) == Some(file)
6643                && item.get("symbol").and_then(Value::as_str) == Some(symbol)
6644        })
6645    }
6646
6647    fn project_files(root: &Path) -> Vec<PathBuf> {
6648        walk_project_files(root).collect()
6649    }
6650
6651    fn canonical_root(root: &Path) -> PathBuf {
6652        std::fs::canonicalize(root).unwrap_or_else(|_| root.to_path_buf())
6653    }
6654
6655    fn write_file(path: &Path, content: &str) {
6656        if let Some(parent) = path.parent() {
6657            std::fs::create_dir_all(parent).expect("create parent");
6658        }
6659        std::fs::write(path, content).expect("write fixture");
6660        bump_mtime(path);
6661    }
6662
6663    fn bump_mtime(path: &Path) {
6664        let secs = NEXT_MTIME.fetch_add(1, AtomicOrdering::SeqCst);
6665        filetime::set_file_mtime(path, FileTime::from_unix_time(secs, 0)).expect("bump mtime");
6666    }
6667
6668    fn remove_file(path: &Path) {
6669        std::fs::remove_file(path).expect("remove fixture");
6670    }
6671
6672    fn write_projection_fixture(root: &Path) {
6673        write_file(
6674            &root.join("package.json"),
6675            r#"{"name":"dead-code-projection-fixture","type":"module","main":"src/main.ts"}"#,
6676        );
6677        write_file(
6678            &root.join("Cargo.toml"),
6679            r#"[package]
6680name = "dead_code_projection_fixture"
6681version = "0.1.0"
6682edition = "2021"
6683"#,
6684        );
6685        write_file(
6686            &root.join("src/main.ts"),
6687            r#"import runDefault from "./default";
6688import { knownLive } from "./live";
6689import { jsEntry } from "./app.js";
6690
6691export function main() {
6692  dispatch();
6693  runDefault();
6694  jsEntry();
6695}
6696
6697function dispatch() {
6698  knownLive();
6699  const service = { render() {} };
6700  service.render();
6701}
6702"#,
6703        );
6704        write_file(
6705            &root.join("src/default.ts"),
6706            r#"export default function runDefault() {}
6707"#,
6708        );
6709        write_file(
6710            &root.join("src/live.ts"),
6711            r#"export function knownLive() {}
6712"#,
6713        );
6714        write_file(
6715            &root.join("src/dead.ts"),
6716            r#"export function knownDead() {}
6717"#,
6718        );
6719        write_file(
6720            &root.join("src/render.ts"),
6721            r#"export function render() {}
6722"#,
6723        );
6724        write_file(
6725            &root.join("src/other_render.ts"),
6726            r#"export function render() {}
6727"#,
6728        );
6729        write_file(
6730            &root.join("src/app.js"),
6731            r#"import { jsHelper } from "./js_helper.js";
6732
6733export function jsEntry() {
6734  jsHelper();
6735}
6736"#,
6737        );
6738        write_file(
6739            &root.join("src/js_helper.js"),
6740            r#"export function jsHelper() {}
6741"#,
6742        );
6743        write_file(
6744            &root.join("src/lib.rs"),
6745            r#"mod util;
6746use crate::util::rust_helper;
6747
6748pub fn rust_entry() {
6749    rust_helper();
6750}
6751"#,
6752        );
6753        write_file(
6754            &root.join("src/util.rs"),
6755            r#"pub fn rust_helper() {}
6756"#,
6757        );
6758    }
6759
6760    fn write_rust_attribute_entry_fixture(root: &Path) {
6761        write_file(
6762            &root.join("src/main.rs"),
6763            r#"mod commands;
6764mod db;
6765mod imported;
6766mod unimported;
6767mod unrelated;
6768
6769fn main() {
6770    tauri::generate_handler![commands::get_primers, imported::imported_command];
6771}
6772"#,
6773        );
6774        write_file(
6775            &root.join("src/commands.rs"),
6776            r#"use crate::db;
6777
6778#[tauri::command]
6779pub fn get_primers() -> String {
6780    db::helper()
6781}
6782
6783pub fn planted_dead() -> String {
6784    "dead".to_string()
6785}
6786
6787#[tauri::command]
6788fn private_command() -> String {
6789    db::private_helper()
6790}
6791"#,
6792        );
6793        write_file(
6794            &root.join("src/imported.rs"),
6795            r#"use crate::db;
6796use tauri::command;
6797
6798#[command]
6799pub fn imported_command() -> String {
6800    db::imported_helper()
6801}
6802"#,
6803        );
6804        write_file(
6805            &root.join("src/unimported.rs"),
6806            r#"use crate::db;
6807
6808#[command]
6809pub fn false_command() -> String {
6810    db::false_helper()
6811}
6812"#,
6813        );
6814        write_file(
6815            &root.join("src/db.rs"),
6816            r#"pub fn helper() -> String { "live".to_string() }
6817pub fn imported_helper() -> String { "live".to_string() }
6818pub fn private_helper() -> String { "live".to_string() }
6819pub fn false_helper() -> String { "dead".to_string() }
6820"#,
6821        );
6822        write_file(
6823            &root.join("src/unrelated.rs"),
6824            r#"pub fn unrelated() -> u32 { 1 }
6825"#,
6826        );
6827    }
6828
6829    fn setup_projection_rename(root: &Path) {
6830        write_file(
6831            &root.join("a.ts"),
6832            r#"export function outer() {
6833  inner();
6834}
6835
6836export function inner() {}
6837"#,
6838        );
6839    }
6840
6841    fn edit_projection_rename(root: &Path) -> Vec<PathBuf> {
6842        let path = root.join("a.ts");
6843        write_file(
6844            &path,
6845            r#"export function outer() {
6846  renamed();
6847}
6848
6849export function renamed() {}
6850"#,
6851        );
6852        vec![path]
6853    }
6854
6855    fn setup_projection_delete(root: &Path) {
6856        write_file(
6857            &root.join("main.ts"),
6858            r#"import { foo } from "./foo";
6859export function main() { foo(); }
6860"#,
6861        );
6862        write_file(&root.join("foo.ts"), "export function foo() {}\n");
6863    }
6864
6865    fn edit_projection_delete(root: &Path) -> Vec<PathBuf> {
6866        let path = root.join("foo.ts");
6867        remove_file(&path);
6868        vec![path]
6869    }
6870
6871    fn setup_projection_barrel(root: &Path) {
6872        write_file(
6873            &root.join("main.ts"),
6874            r#"import { foo } from "./barrel";
6875export function main() { foo(); }
6876"#,
6877        );
6878        write_file(&root.join("barrel.ts"), "export { foo } from \"./foo\";\n");
6879        write_file(&root.join("foo.ts"), "export function foo() {}\n");
6880    }
6881
6882    fn edit_projection_barrel_delete(root: &Path) -> Vec<PathBuf> {
6883        let path = root.join("barrel.ts");
6884        remove_file(&path);
6885        vec![path]
6886    }
6887
6888    fn setup_projection_dispatch(root: &Path) {
6889        write_file(
6890            &root.join("main.ts"),
6891            r#"export function main() {
6892  const service = { render() {}, paint() {} };
6893  service.render();
6894}
6895"#,
6896        );
6897        write_file(&root.join("render.ts"), "export function render() {}\n");
6898        write_file(&root.join("paint.ts"), "export function paint() {}\n");
6899    }
6900
6901    fn edit_projection_dispatch(root: &Path) -> Vec<PathBuf> {
6902        let path = root.join("main.ts");
6903        write_file(
6904            &path,
6905            r#"export function main() {
6906  const service = { render() {}, paint() {} };
6907  service.paint();
6908}
6909"#,
6910        );
6911        vec![path]
6912    }
6913
6914    fn setup_projection_body_only(root: &Path) {
6915        write_file(
6916            &root.join("main.ts"),
6917            r#"import { foo } from "./foo";
6918export function main() { foo(); }
6919"#,
6920        );
6921        write_file(
6922            &root.join("foo.ts"),
6923            r#"export function foo() {
6924  return 1;
6925}
6926"#,
6927        );
6928    }
6929
6930    fn edit_projection_body_only(root: &Path) -> Vec<PathBuf> {
6931        let path = root.join("foo.ts");
6932        write_file(
6933            &path,
6934            r#"export function foo() {
6935  return 2;
6936}
6937"#,
6938        );
6939        vec![path]
6940    }
6941
6942    #[test]
6943    fn forced_paths_downgrade_only_when_strict_hash_matches_cached_fact() {
6944        let dir = tempfile::tempdir().expect("tempdir");
6945        let root = std::fs::canonicalize(dir.path()).expect("canonical root");
6946        let unchanged = root.join("unchanged.ts");
6947        let changed = root.join("changed.ts");
6948        let oversized = root.join("oversized.ts");
6949        std::fs::write(&unchanged, "export const value = 1;\n").expect("write unchanged");
6950        std::fs::write(&changed, "export const before = 1;\n").expect("write changed baseline");
6951        let unchanged_freshness =
6952            cache_freshness::collect(&unchanged).expect("unchanged freshness");
6953        let changed_freshness = cache_freshness::collect(&changed).expect("changed freshness");
6954        std::fs::write(&changed, "export const after_ = 2;\n").expect("change same-size content");
6955        let oversized_file = std::fs::File::create(&oversized).expect("create oversized");
6956        oversized_file
6957            .set_len(cache_freshness::CONTENT_HASH_SIZE_CAP + 1)
6958            .expect("size oversized");
6959        let oversized_freshness =
6960            cache_freshness::collect(&oversized).expect("oversized freshness");
6961        let cached = vec![
6962            CachedContributionFreshness {
6963                file_path: PathBuf::from("unchanged.ts"),
6964                freshness: unchanged_freshness,
6965            },
6966            CachedContributionFreshness {
6967                file_path: PathBuf::from("changed.ts"),
6968                freshness: changed_freshness,
6969            },
6970            CachedContributionFreshness {
6971                file_path: PathBuf::from("oversized.ts"),
6972                freshness: oversized_freshness,
6973            },
6974        ];
6975
6976        let (remaining, downgraded) = downgrade_unchanged_forced_paths_with_freshness(
6977            &root,
6978            &cached,
6979            vec![
6980                PathBuf::from("unchanged.ts"),
6981                PathBuf::from("changed.ts"),
6982                PathBuf::from("oversized.ts"),
6983            ],
6984        );
6985
6986        assert_eq!(downgraded, 1);
6987        assert_eq!(
6988            remaining,
6989            vec![PathBuf::from("changed.ts"), PathBuf::from("oversized.ts")]
6990        );
6991    }
6992}