Skip to main content

fallow_core/
lib.rs

1//! fallow-core is the internal implementation crate behind the `fallow`
2//! analyzer. External embedders should consume the curated programmatic
3//! surface at `fallow_api` (e.g. `run_dead_code`,
4//! `run_boundary_violations`, `run_duplication`, `run_health`). The typed
5//! `run_*` functions are the primary embedder contract; serialize typed output
6//! with the matching `serialize_*_programmatic_json` helper only at a protocol
7//! boundary. See `docs/fallow-core-migration.md`
8//! for the function-by-function migration map. Items in this crate may change
9//! in any release, including patch releases. Publishing remains transitional
10//! while `fallow-engine` still depends on core internals.
11
12#![cfg_attr(not(test), deny(clippy::disallowed_methods))]
13#![cfg_attr(
14    test,
15    allow(
16        clippy::unwrap_used,
17        clippy::expect_used,
18        reason = "tests use unwrap and expect to keep fixture setup concise"
19    )
20)]
21
22pub mod analyze;
23pub mod cache;
24pub mod discover;
25pub(crate) mod errors;
26mod external_style_usage;
27pub mod extract;
28pub mod git_env;
29mod package_assets;
30pub mod plugins;
31pub(crate) mod progress;
32pub mod results;
33pub(crate) mod scripts;
34/// Public hook for the fuzz harness (fuzz/fuzz_targets/fuzz_scripts.rs) only;
35/// not a supported API. The module itself stays crate-private.
36#[doc(hidden)]
37pub use scripts::parse_script;
38pub mod suppress;
39
40pub use fallow_graph::cache as graph_cache;
41pub use fallow_graph::graph;
42pub use fallow_graph::project;
43pub use fallow_graph::resolve;
44
45use std::path::{Path, PathBuf};
46use std::time::Instant;
47
48use errors::FallowError;
49use fallow_config::{
50    EntryPointRole, PackageJson, ResolvedConfig, find_undeclared_workspaces_with_ignores,
51};
52use fallow_types::cache_rejection::CacheRejection;
53use fallow_types::trace::{EntryPointSpans, PipelineCounters, PipelineTimings};
54use rayon::prelude::*;
55use results::AnalysisResults;
56use rustc_hash::FxHashSet;
57
58const UNDECLARED_WORKSPACE_WARNING_PREVIEW: usize = 5;
59type LoadedWorkspacePackage = (fallow_config::WorkspaceInfo, PackageJson);
60
61fn record_graph_package_usage(
62    graph: &mut graph::ModuleGraph,
63    package_name: &str,
64    file_id: discover::FileId,
65    is_type_only: bool,
66) {
67    graph
68        .package_usage
69        .entry(package_name.to_owned())
70        .or_default()
71        .push(file_id);
72    if is_type_only {
73        graph
74            .type_only_package_usage
75            .entry(package_name.to_owned())
76            .or_default()
77            .push(file_id);
78    }
79}
80
81fn workspace_package_name<'a>(
82    source: &str,
83    workspace_names: &FxHashSet<&'a str>,
84) -> Option<&'a str> {
85    if !resolve::is_bare_specifier(source) {
86        return None;
87    }
88    let package_name = resolve::extract_package_name(source);
89    workspace_names.get(package_name.as_str()).copied()
90}
91
92fn credit_workspace_package_usage(
93    graph: &mut graph::ModuleGraph,
94    resolved: &[resolve::ResolvedModule],
95    workspaces: &[fallow_config::WorkspaceInfo],
96) {
97    if workspaces.is_empty() {
98        return;
99    }
100
101    let workspace_names: FxHashSet<&str> = workspaces.iter().map(|ws| ws.name.as_str()).collect();
102    for module in resolved {
103        for import in module.all_resolved_imports() {
104            if matches!(
105                import.target,
106                resolve::ResolveResult::InternalModule(_)
107                    | resolve::ResolveResult::CommonJsInternalModule(_)
108            ) && let Some(package_name) =
109                workspace_package_name(&import.info.source, &workspace_names)
110            {
111                record_graph_package_usage(
112                    graph,
113                    package_name,
114                    module.file_id,
115                    import.info.is_type_only,
116                );
117            }
118        }
119
120        for re_export in &module.re_exports {
121            if matches!(re_export.target, resolve::ResolveResult::InternalModule(_))
122                && let Some(package_name) =
123                    workspace_package_name(&re_export.info.source, &workspace_names)
124            {
125                record_graph_package_usage(
126                    graph,
127                    package_name,
128                    module.file_id,
129                    re_export.info.is_type_only,
130                );
131            }
132        }
133    }
134}
135
136fn credit_package_path_references(graph: &mut graph::ModuleGraph, modules: &[extract::ModuleInfo]) {
137    for module in modules {
138        for package_name in &module.package_path_references {
139            record_graph_package_usage(graph, package_name, module.file_id, false);
140        }
141        // A module augmentation credits the package as a type-only use. The
142        // unlisted-dependency check reports a package only at a resolved
143        // import site, so an undeclared augmented package stays unreported.
144        for package_name in &module.type_package_references {
145            record_graph_package_usage(graph, package_name, module.file_id, true);
146        }
147    }
148}
149
150/// Credit the package behind each `node_modules/.bin/<name>` path in source.
151///
152/// The persisted graph cache does not hold these credits: the bin map comes
153/// from `node_modules`, which the cache manifest does not track. Each run
154/// applies them to a built or a loaded graph.
155fn credit_bin_path_references(
156    graph: &mut graph::ModuleGraph,
157    modules: &[extract::ModuleInfo],
158    binaries: &scripts::DependencyBinaries,
159) {
160    for module in modules {
161        for binary in &module.bin_path_references {
162            if let Some(package_name) = binaries.package_for(binary) {
163                record_graph_package_usage(graph, &package_name, module.file_id, false);
164            }
165        }
166    }
167}
168
169/// Result of the full analysis pipeline, including optional performance timings.
170#[doc(hidden)]
171pub struct AnalysisOutput {
172    pub results: AnalysisResults,
173    pub timings: Option<PipelineTimings>,
174    pub graph: Option<graph::ModuleGraph>,
175    /// Parsed modules from the pipeline, available when `retain_modules` is true.
176    /// Used by combined and LSP flows to share downstream module data.
177    /// Graph-only extraction payloads are released after graph construction.
178    pub modules: Option<Vec<extract::ModuleInfo>>,
179    /// Discovered files from the pipeline, available when `retain_modules` is true.
180    pub files: Option<Vec<discover::DiscoveredFile>>,
181    /// Package names invoked from package.json scripts and CI configs, mirroring
182    /// what the unused-deps detector consults. Populated for every pipeline run;
183    /// trace tooling reads it so `trace_dependency` agrees with `unused-deps` on
184    /// "used vs unused" instead of returning false-negatives for script-only deps.
185    pub script_used_packages: rustc_hash::FxHashSet<String>,
186    /// Which configs name which files and dependency names, so a trace can
187    /// say why a file is an entry point or why a name is provided.
188    pub trace_provenance: fallow_types::trace::TraceProvenance,
189    /// xxh3 content hash of every parsed source file, keyed by absolute path.
190    /// Used by `fallow fix` to detect on-disk drift between the in-process
191    /// analysis read and the per-file write; if the file's current hash
192    /// differs from the captured value, the fix for that file is skipped
193    /// with a clear diagnostic and exit 2. The hash is the same value
194    /// extract/cache uses for cache invalidation, so a cached parse contributes
195    /// the same hash as a fresh parse. Roughly 8 bytes per file (negligible
196    /// memory cost even on 100k-file projects).
197    pub file_hashes: rustc_hash::FxHashMap<std::path::PathBuf, u64>,
198}
199
200/// Parse/cache phase metrics supplied by callers that own parsing before
201/// handing modules back to the core detector backend.
202#[derive(Debug, Clone, Copy)]
203#[doc(hidden)]
204pub struct AnalysisParseMetrics {
205    parse_ms: f64,
206    cache_ms: f64,
207    cache_hits: usize,
208    cache_misses: usize,
209    parse_cpu_ms: f64,
210    cache_rejection: Option<CacheRejection>,
211}
212
213/// Update cache: write freshly parsed modules, refresh stale metadata entries,
214/// and upgrade entries a complexity-blind run wrote earlier.
215///
216/// An entry whose content hash still matches is rewritten only when its
217/// metadata fingerprint moved or when this run can add complexity the entry
218/// lacks. A run with `need_complexity == false` never rewrites the complexity
219/// an earlier `health` run stored: `module.complexity` is empty on such a run
220/// by design, so copying it over would silently strip the entry and make every
221/// later `health` run reparse the file.
222///
223/// `read_started_ns` is the time before the parse read the sources. A
224/// fingerprint that is not older than that time by the settle window is stored
225/// without its ctime, so the next run compares content for that file. The
226/// metadata is read here, after the parse. A save between the parse read and
227/// this read gives a ctime newer than `read_started_ns`, so that fingerprint
228/// never settles and is stored without its ctime.
229fn update_cache(
230    store: &mut cache::CacheStore,
231    modules: &[extract::ModuleInfo],
232    files: &[discover::DiscoveredFile],
233    need_complexity: bool,
234    read_started_ns: u64,
235) -> bool {
236    let mut dirty = false;
237    for module in modules {
238        if let Some(file) = files.get(module.file_id.0 as usize) {
239            let fingerprint = file_fingerprint(&file.path).for_content_read_at(read_started_ns);
240            if let Some(cached) = store.get_by_path_only(&file.path)
241                && cached.content_hash == module.content_hash
242            {
243                let stale_metadata = cached.source_fingerprint() != fingerprint;
244                let adds_complexity = need_complexity && !cached.complexity_extracted;
245                if stale_metadata || adds_complexity {
246                    let preserved_last_access = cached.last_access_secs;
247                    let preserved_complexity = (!need_complexity && cached.complexity_extracted)
248                        .then(|| cached.complexity.clone());
249                    let mut refreshed =
250                        cache::module_to_cached(module, fingerprint, need_complexity);
251                    refreshed.last_access_secs = preserved_last_access;
252                    if let Some(complexity) = preserved_complexity {
253                        refreshed.complexity = complexity;
254                        refreshed.complexity_extracted = true;
255                    }
256                    store.insert(&file.path, refreshed);
257                    dirty = true;
258                }
259                continue;
260            }
261            store.insert(
262                &file.path,
263                cache::module_to_cached(module, fingerprint, need_complexity),
264            );
265            dirty = true;
266        }
267    }
268    let removed_stale_paths = store.retain_paths(files);
269    dirty || removed_stale_paths
270}
271
272/// Resolve `config.cache_max_size_mb` into bytes, falling back to the
273/// extract crate's `DEFAULT_CACHE_MAX_SIZE`. Lives at this layer (not on
274/// `ResolvedConfig`) because `fallow-config` does not depend on
275/// `fallow-extract`; the bytes conversion is owned by the cache callsite.
276/// Public so CLI subcommands that load the cache directly (`flags`,
277/// `health`, `coverage analyze`) can call it without re-deriving the
278/// same fallback policy.
279#[must_use]
280fn resolve_cache_max_size_bytes(config: &ResolvedConfig) -> usize {
281    config
282        .cache_max_size_mb
283        .map_or(cache::DEFAULT_CACHE_MAX_SIZE, |mb| {
284            (mb as usize).saturating_mul(1024 * 1024)
285        })
286}
287
288/// Extract source fingerprint metadata from a path.
289fn file_fingerprint(path: &std::path::Path) -> fallow_types::source_fingerprint::SourceFingerprint {
290    std::fs::metadata(path).map_or(
291        fallow_types::source_fingerprint::SourceFingerprint::new(0, 0),
292        |metadata| fallow_types::source_fingerprint::SourceFingerprint::from_metadata(&metadata),
293    )
294}
295
296fn format_undeclared_workspace_warning(
297    root: &Path,
298    undeclared: &[fallow_config::WorkspaceDiagnostic],
299) -> Option<String> {
300    if undeclared.is_empty() {
301        return None;
302    }
303
304    let preview = undeclared
305        .iter()
306        .take(UNDECLARED_WORKSPACE_WARNING_PREVIEW)
307        .map(|diag| {
308            diag.path
309                .strip_prefix(root)
310                .unwrap_or(&diag.path)
311                .display()
312                .to_string()
313                .replace('\\', "/")
314        })
315        .collect::<Vec<_>>();
316    let remaining = undeclared
317        .len()
318        .saturating_sub(UNDECLARED_WORKSPACE_WARNING_PREVIEW);
319    let tail = if remaining > 0 {
320        format!(" (and {remaining} more)")
321    } else {
322        String::new()
323    };
324    let noun = if undeclared.len() == 1 {
325        "directory with package.json is"
326    } else {
327        "directories with package.json are"
328    };
329    let guidance = if undeclared.len() == 1 {
330        "Add that path to package.json workspaces or pnpm-workspace.yaml if it should be analyzed as a workspace."
331    } else {
332        "Add those paths to package.json workspaces or pnpm-workspace.yaml if they should be analyzed as workspaces."
333    };
334
335    Some(format!(
336        "{} {} not declared as {}: {}{}. {}",
337        undeclared.len(),
338        noun,
339        if undeclared.len() == 1 {
340            "a workspace"
341        } else {
342            "workspaces"
343        },
344        preview.join(", "),
345        tail,
346        guidance
347    ))
348}
349
350fn warn_undeclared_workspaces(
351    root: &Path,
352    workspaces_vec: &[fallow_config::WorkspaceInfo],
353    ignore_patterns: &fallow_config::IgnorePatternSet,
354    quiet: bool,
355) {
356    let undeclared = find_undeclared_workspaces_with_ignores(root, workspaces_vec, ignore_patterns);
357    if undeclared.is_empty() {
358        return;
359    }
360
361    let existing = fallow_config::workspace_diagnostics_for(root);
362    let already_flagged: rustc_hash::FxHashSet<PathBuf> = existing
363        .iter()
364        .map(|d| dunce::canonicalize(&d.path).unwrap_or_else(|_| d.path.clone()))
365        .collect();
366    let undeclared: Vec<_> = undeclared
367        .into_iter()
368        .filter(|diag| {
369            let canonical = dunce::canonicalize(&diag.path).unwrap_or_else(|_| diag.path.clone());
370            !already_flagged.contains(&canonical)
371        })
372        .collect();
373    if undeclared.is_empty() {
374        return;
375    }
376
377    fallow_config::append_workspace_diagnostics(root, undeclared.clone());
378
379    if !quiet && let Some(message) = format_undeclared_workspace_warning(root, &undeclared) {
380        tracing::warn!("{message}");
381    }
382}
383
384/// Run the full analysis pipeline.
385///
386/// # Errors
387///
388/// Returns an error if file discovery, parsing, or analysis fails.
389#[doc(hidden)]
390#[deprecated(
391    since = "2.76.0",
392    note = "fallow_core is internal; use fallow_api::run_dead_code for typed output; serialize with fallow_api::serialize_dead_code_programmatic_json for JSON output. See docs/fallow-core-migration.md."
393)]
394pub fn analyze(config: &ResolvedConfig) -> Result<AnalysisResults, FallowError> {
395    let output = analyze_full(config, false, false, false, false)?;
396    Ok(output.results)
397}
398
399/// Run the full analysis pipeline with export usage collection (for LSP Code Lens).
400///
401/// # Errors
402///
403/// Returns an error if file discovery, parsing, or analysis fails.
404#[doc(hidden)]
405#[deprecated(
406    since = "2.76.0",
407    note = "fallow_core is internal; use fallow_api::run_dead_code for public typed output. NOTE: export-usage collection is not exposed in the programmatic surface today. See docs/fallow-core-migration.md."
408)]
409pub fn analyze_with_usages(config: &ResolvedConfig) -> Result<AnalysisResults, FallowError> {
410    let output = analyze_full(config, false, true, false, false)?;
411    Ok(output.results)
412}
413
414/// Run the full analysis pipeline with optional performance timings and graph retention.
415///
416/// # Errors
417///
418/// Returns an error if file discovery, parsing, or analysis fails.
419#[doc(hidden)]
420#[deprecated(
421    since = "2.76.0",
422    note = "fallow_core is internal; use fallow_api::run_dead_code for public typed output. NOTE: trace timings are not exposed in the programmatic surface today; use `fallow dead-code --performance` for CLI-side timings. See docs/fallow-core-migration.md."
423)]
424pub fn analyze_with_trace(config: &ResolvedConfig) -> Result<AnalysisOutput, FallowError> {
425    analyze_full(config, true, false, false, false)
426}
427
428/// Run the full analysis pipeline, retaining parsed modules and discovered files.
429///
430/// Used by the combined command to share a single parse across dead-code and health.
431/// When `need_complexity` is true, the `ComplexityVisitor` runs during parsing so
432/// the returned modules contain per-function complexity data.
433///
434/// # Errors
435///
436/// Returns an error if file discovery, parsing, or analysis fails.
437#[doc(hidden)]
438#[deprecated(
439    since = "2.76.0",
440    note = "fallow_core is internal; use fallow_api::run_dead_code for public typed output. NOTE: combined-mode module retention is not exposed in the programmatic surface today. See docs/fallow-core-migration.md."
441)]
442pub fn analyze_retaining_modules(
443    config: &ResolvedConfig,
444    need_complexity: bool,
445    retain_graph: bool,
446) -> Result<AnalysisOutput, FallowError> {
447    analyze_full(config, retain_graph, false, need_complexity, true)
448}
449
450fn new_analysis_progress(config: &ResolvedConfig) -> progress::AnalysisProgress {
451    let show_progress = !config.quiet
452        && std::io::IsTerminal::is_terminal(&std::io::stderr())
453        && matches!(
454            config.output,
455            fallow_config::OutputFormat::Human
456                | fallow_config::OutputFormat::Compact
457                | fallow_config::OutputFormat::Markdown
458        );
459    progress::AnalysisProgress::new(show_progress)
460}
461
462fn discover_analysis_workspaces(
463    config: &ResolvedConfig,
464) -> Result<(Vec<fallow_config::WorkspaceInfo>, f64), FallowError> {
465    let t = Instant::now();
466    let (workspaces, diagnostics) =
467        fallow_config::discover_workspaces_with_diagnostics_and_patterns(
468            &config.root,
469            &config.ignore_patterns,
470            &config.workspace_patterns,
471        )
472        .map_err(|error| FallowError::config(error.to_string()))?;
473    fallow_config::stash_workspace_diagnostics(&config.root, diagnostics);
474    let workspaces_ms = t.elapsed().as_secs_f64() * 1000.0;
475    if !workspaces.is_empty() {
476        tracing::info!(count = workspaces.len(), "workspaces discovered");
477    }
478
479    warn_undeclared_workspaces(
480        &config.root,
481        &workspaces,
482        &config.ignore_patterns,
483        config.quiet,
484    );
485
486    Ok((workspaces, workspaces_ms))
487}
488
489/// Owned products of the shared pipeline prelude: progress reporter, project
490/// state (owns discovered files and workspaces), root package.json, and the
491/// discovery/workspace timings.
492struct AnalysisSetup {
493    progress: progress::AnalysisProgress,
494    project: project::ProjectState,
495    root_pkg: Option<PackageJson>,
496    /// Non-source config-candidate files captured by the same discovery walk,
497    /// used to resolve plugin config patterns in-memory (empty in production
498    /// mode, where the filesystem path is kept). Carried alongside `project`
499    /// rather than inside it to avoid churning `ProjectState`'s many callers.
500    config_candidates: Vec<std::path::PathBuf>,
501    discover_ms: f64,
502    workspaces_ms: f64,
503}
504
505/// Reusable discovery prelude for a resolved project.
506///
507/// This carries the file registry plus the workspace and config-candidate state
508/// that plugin detection needs, so engine sessions can run several analyses
509/// over one stable discovery boundary without re-walking the project.
510#[derive(Debug, Clone)]
511#[doc(hidden)]
512pub struct AnalysisDiscovery {
513    files: Vec<discover::DiscoveredFile>,
514    workspaces: Vec<fallow_config::WorkspaceInfo>,
515    root_pkg: Option<PackageJson>,
516    config_candidates: Vec<std::path::PathBuf>,
517    discover_ms: f64,
518    workspaces_ms: f64,
519}
520
521impl AnalysisDiscovery {
522    /// Build a discovery prelude from an engine-owned discovery run.
523    #[must_use]
524    pub fn from_parts(
525        files: Vec<discover::DiscoveredFile>,
526        workspaces: Vec<fallow_config::WorkspaceInfo>,
527        root_pkg: Option<PackageJson>,
528        config_candidates: Vec<std::path::PathBuf>,
529        discover_ms: f64,
530        workspaces_ms: f64,
531    ) -> Self {
532        Self {
533            files,
534            workspaces,
535            root_pkg,
536            config_candidates,
537            discover_ms,
538            workspaces_ms,
539        }
540    }
541
542    /// Discovered source files, indexed by stable `FileId` for this session.
543    #[must_use]
544    fn files(&self) -> &[discover::DiscoveredFile] {
545        &self.files
546    }
547
548    /// Discovered workspace packages for this session.
549    #[must_use]
550    pub fn workspaces(&self) -> &[fallow_config::WorkspaceInfo] {
551        &self.workspaces
552    }
553
554    /// Consume this discovery prelude and return its source file registry.
555    #[must_use]
556    pub fn into_files(self) -> Vec<discover::DiscoveredFile> {
557        self.files
558    }
559}
560
561/// Owned state shared across one legacy core analysis run.
562///
563/// Engine-owned sessions use `fallow-engine`; this remains only for deprecated
564/// core entrypoints while core is being narrowed to detector/backend helpers.
565pub(crate) struct AnalysisSession<'a> {
566    config: &'a ResolvedConfig,
567    pipeline_start: Instant,
568    progress: progress::AnalysisProgress,
569    project: project::ProjectState,
570    root_pkg: Option<PackageJson>,
571    config_candidates: Vec<std::path::PathBuf>,
572    discover_ms: f64,
573    workspaces_ms: f64,
574}
575
576impl<'a> AnalysisSession<'a> {
577    fn new(config: &'a ResolvedConfig) -> Result<Self, FallowError> {
578        let pipeline_start = Instant::now();
579        let AnalysisSetup {
580            progress,
581            project,
582            root_pkg,
583            config_candidates,
584            discover_ms,
585            workspaces_ms,
586        } = run_analysis_setup(config)?;
587
588        Ok(Self {
589            config,
590            pipeline_start,
591            progress,
592            project,
593            root_pkg,
594            config_candidates,
595            discover_ms,
596            workspaces_ms,
597        })
598    }
599
600    fn files(&self) -> &[discover::DiscoveredFile] {
601        self.project.files()
602    }
603
604    fn workspaces(&self) -> &[fallow_config::WorkspaceInfo] {
605        self.project.workspaces()
606    }
607
608    fn load_workspace_packages(&self) -> Vec<LoadedWorkspacePackage> {
609        load_workspace_packages(self.workspaces())
610    }
611
612    fn run_plugins_and_scripts(
613        &self,
614        workspace_pkgs: &[LoadedWorkspacePackage],
615    ) -> Result<(plugins::AggregatedPluginResult, f64, f64), FallowError> {
616        run_plugins_and_scripts(&PluginScriptInput {
617            config: self.config,
618            progress: &self.progress,
619            files: self.files(),
620            workspaces: self.workspaces(),
621            root_pkg: self.root_pkg.as_ref(),
622            workspace_pkgs,
623            config_candidates: &self.config_candidates,
624        })
625    }
626
627    fn prelude_timings(&self, plugins_ms: f64, scripts_ms: f64) -> PreludeTimings {
628        PreludeTimings {
629            discover_ms: self.discover_ms,
630            workspaces_ms: self.workspaces_ms,
631            plugins_ms,
632            scripts_ms,
633        }
634    }
635
636    fn parse_modules(&self, need_complexity: bool) -> AnalysisParseOutput {
637        let t = Instant::now();
638        self.progress
639            .set_stage(&format!("parsing {} files...", self.files().len()));
640        parse_analysis_modules(self.config, self.files(), need_complexity, t)
641    }
642
643    fn run_owned_core(
644        &self,
645        workspace_pkgs: &[LoadedWorkspacePackage],
646        plugin_result: &plugins::AggregatedPluginResult,
647        mut modules: Vec<extract::ModuleInfo>,
648        collect_usages: bool,
649    ) -> OwnedAnalysisCore {
650        let shared = AnalysisCoreSharedInput {
651            config: self.config,
652            progress: &self.progress,
653            files: self.files(),
654            workspaces: self.workspaces(),
655            root_pkg: self.root_pkg.as_ref(),
656            workspace_pkgs,
657            plugin_result,
658        };
659
660        let entry_points = discover_analysis_entry_points(&shared);
661        let mut graph_cache_rejection = None;
662        let (resolved, graph) =
663            match try_load_analysis_graph_cache(&shared, &entry_points, &modules) {
664                Ok(hit) => (
665                    TimedResolvedModules {
666                        project: hit.project,
667                        elapsed_ms: 0.0,
668                    },
669                    TimedGraph {
670                        graph: hit.graph,
671                        elapsed_ms: hit.elapsed_ms,
672                    },
673                ),
674                Err(rejection) => {
675                    graph_cache_rejection = rejection;
676                    let resolved = resolve_analysis_imports_timed(&shared, &modules);
677                    let graph = build_analysis_graph_timed(
678                        &shared,
679                        &resolved.project,
680                        &entry_points,
681                        &modules,
682                    );
683                    (resolved, graph)
684                }
685            };
686        release_resolution_payloads(&mut modules);
687        let analysis = analyze_dead_code_timed(
688            &shared,
689            &graph.graph,
690            &resolved.project.modules,
691            &modules,
692            collect_usages,
693            entry_points.summary,
694        );
695
696        OwnedAnalysisCore {
697            result: analysis.result,
698            graph: graph.graph,
699            modules,
700            entry_point_count: entry_points.count,
701            entry_points_ms: entry_points.elapsed_ms,
702            entry_point_spans: entry_points.spans,
703            resolve_ms: resolved.elapsed_ms,
704            graph_ms: graph.elapsed_ms,
705            analyze_ms: analysis.elapsed_ms,
706            graph_cache_rejection,
707            resolve_work: resolved.project.work,
708        }
709    }
710
711    fn run_full(
712        self,
713        retain: bool,
714        collect_usages: bool,
715        need_complexity: bool,
716        retain_modules: bool,
717    ) -> Result<AnalysisOutput, FallowError> {
718        let workspace_pkgs = self.load_workspace_packages();
719        let (plugin_result, plugins_ms, scripts_ms) =
720            self.run_plugins_and_scripts(&workspace_pkgs)?;
721
722        let AnalysisParseOutput { modules, metrics } = self.parse_modules(need_complexity);
723        let core = self.run_owned_core(&workspace_pkgs, &plugin_result, modules, collect_usages);
724        self.progress.finish();
725
726        let profile = full_analysis_pipeline_profile(
727            &self.prelude_timings(plugins_ms, scripts_ms),
728            self.pipeline_start,
729            self.files(),
730            self.workspaces(),
731            &core,
732            &metrics,
733        );
734        trace_pipeline_profile(&profile);
735
736        let mut trace_provenance = plugins::federation_trace_provenance(
737            &self.config.root,
738            self.files(),
739            &plugin_result.federation_sources,
740            &core.modules,
741        );
742        plugins::push_tooling_trace_credits(
743            &mut trace_provenance,
744            &self.config.root,
745            self.workspaces(),
746            &plugin_result,
747        );
748        let mut output = assemble_full_output(
749            core,
750            plugin_result,
751            &profile,
752            self.files(),
753            retain,
754            retain_modules,
755        );
756        output.trace_provenance = trace_provenance;
757        Ok(output)
758    }
759}
760
761/// Run the shared prelude: progress setup, node_modules check, workspace and
762/// root-package discovery, hidden-dir scoping, and file discovery.
763fn run_analysis_setup(config: &ResolvedConfig) -> Result<AnalysisSetup, FallowError> {
764    let progress = new_analysis_progress(config);
765
766    let (workspaces_vec, workspaces_ms) = discover_analysis_workspaces(config)?;
767    let root_pkg = fallow_config::load_dir_package_json(&config.root);
768    let discovery_hidden_dir_scopes =
769        discover::collect_hidden_dir_scopes(config, root_pkg.as_ref(), &workspaces_vec);
770
771    let t = Instant::now();
772    progress.set_stage("discovering files...");
773    let (discovered_files, config_candidates) =
774        discover::discover_files_and_config_candidates(config, &discovery_hidden_dir_scopes);
775    let discover_ms = t.elapsed().as_secs_f64() * 1000.0;
776
777    let project = project::ProjectState::new(discovered_files, workspaces_vec);
778
779    Ok(AnalysisSetup {
780        progress,
781        project,
782        root_pkg,
783        config_candidates,
784        discover_ms,
785        workspaces_ms,
786    })
787}
788
789/// Borrowed inputs for plugin detection and script analysis.
790struct PluginScriptInput<'a> {
791    config: &'a ResolvedConfig,
792    progress: &'a progress::AnalysisProgress,
793    files: &'a [discover::DiscoveredFile],
794    workspaces: &'a [fallow_config::WorkspaceInfo],
795    root_pkg: Option<&'a PackageJson>,
796    workspace_pkgs: &'a [LoadedWorkspacePackage],
797    config_candidates: &'a [std::path::PathBuf],
798}
799
800/// Run plugin detection and package.json/CI script analysis, returning the
801/// aggregated plugin result plus the two phase timings.
802fn run_plugins_and_scripts(
803    input: &PluginScriptInput<'_>,
804) -> Result<(plugins::AggregatedPluginResult, f64, f64), FallowError> {
805    let t = Instant::now();
806    input.progress.set_stage("detecting plugins...");
807    let mut plugin_result = run_plugins(
808        input.config,
809        input.files,
810        input.workspaces,
811        input.root_pkg,
812        input.workspace_pkgs,
813        input.config_candidates,
814    )?;
815    let plugins_ms = t.elapsed().as_secs_f64() * 1000.0;
816
817    let t = Instant::now();
818    analyze_all_scripts(
819        input.config,
820        input.workspaces,
821        input.root_pkg,
822        input.workspace_pkgs,
823        &mut plugin_result,
824    );
825    let scripts_ms = t.elapsed().as_secs_f64() * 1000.0;
826
827    Ok((plugin_result, plugins_ms, scripts_ms))
828}
829
830/// Timings captured by the dead-code backend prelude.
831#[derive(Debug, Clone, Copy)]
832#[doc(hidden)]
833pub struct DeadCodePreludeTimings {
834    pub discover_ms: f64,
835    pub workspaces_ms: f64,
836    pub plugins_ms: f64,
837    pub scripts_ms: f64,
838}
839
840/// Opaque backend prelude for engine-owned dead-code orchestration.
841///
842/// The engine owns the phase ordering. Core keeps the detector/backend state
843/// needed by those phases private.
844#[doc(hidden)]
845pub struct DeadCodeBackendPrelude<'a> {
846    config: &'a ResolvedConfig,
847    pipeline_start: Instant,
848    progress: progress::AnalysisProgress,
849    discovery: AnalysisDiscovery,
850    workspace_pkgs: Vec<LoadedWorkspacePackage>,
851    plugin_result: plugins::AggregatedPluginResult,
852    plugins_ms: f64,
853    scripts_ms: f64,
854}
855
856impl DeadCodeBackendPrelude<'_> {
857    #[must_use]
858    pub fn timings(&self) -> DeadCodePreludeTimings {
859        DeadCodePreludeTimings {
860            discover_ms: self.discovery.discover_ms,
861            workspaces_ms: self.discovery.workspaces_ms,
862            plugins_ms: self.plugins_ms,
863            scripts_ms: self.scripts_ms,
864        }
865    }
866
867    #[must_use]
868    pub fn elapsed_ms(&self) -> f64 {
869        self.pipeline_start.elapsed().as_secs_f64() * 1000.0
870    }
871
872    #[must_use]
873    pub fn script_used_packages(&self) -> FxHashSet<String> {
874        self.plugin_result.script_used_packages.clone()
875    }
876
877    /// Which configs name which files and dependency names, for the trace
878    /// output (issue #2796).
879    #[must_use]
880    pub fn trace_provenance(
881        &self,
882        modules: &[extract::ModuleInfo],
883    ) -> fallow_types::trace::TraceProvenance {
884        let mut provenance = plugins::federation_trace_provenance(
885            &self.config.root,
886            self.discovery.files(),
887            &self.plugin_result.federation_sources,
888            modules,
889        );
890        plugins::push_tooling_trace_credits(
891            &mut provenance,
892            &self.config.root,
893            self.discovery.workspaces(),
894            &self.plugin_result,
895        );
896        provenance
897    }
898
899    /// The plugin stage's result, after the workspace merge and the
900    /// auto-import gate, for listings that must agree with the analysis.
901    #[must_use]
902    pub const fn plugin_result(&self) -> &plugins::AggregatedPluginResult {
903        &self.plugin_result
904    }
905
906    pub fn finish(&self) {
907        self.progress.finish();
908    }
909}
910
911/// Entry-point discovery result for an engine-owned dead-code pipeline.
912#[doc(hidden)]
913pub struct DeadCodeEntryPoints {
914    inner: TimedEntryPoints,
915}
916
917impl DeadCodeEntryPoints {
918    #[must_use]
919    pub fn count(&self) -> usize {
920        self.inner.count
921    }
922
923    #[must_use]
924    pub fn elapsed_ms(&self) -> f64 {
925        self.inner.elapsed_ms
926    }
927
928    /// Sub-phase attribution for the discovery stage this result timed.
929    #[must_use]
930    pub fn spans(&self) -> EntryPointSpans {
931        self.inner.spans
932    }
933
934    /// Every entry point the analysis uses, deduplicated.
935    #[must_use]
936    pub fn all(&self) -> &[discover::EntryPoint] {
937        &self.inner.entry_points.all
938    }
939}
940
941/// Import-resolution result for an engine-owned dead-code pipeline.
942#[doc(hidden)]
943pub struct DeadCodeResolvedModules {
944    pub project: resolve::ResolvedProject,
945    pub elapsed_ms: f64,
946}
947
948/// Graph build or graph-cache result for an engine-owned dead-code pipeline.
949#[doc(hidden)]
950pub struct DeadCodeGraphRun {
951    pub graph: graph::ModuleGraph,
952    pub elapsed_ms: f64,
953}
954
955/// Detector result for an engine-owned dead-code pipeline.
956#[doc(hidden)]
957pub struct DeadCodeDetectorRun {
958    pub results: AnalysisResults,
959    pub elapsed_ms: f64,
960}
961
962/// Prepare plugin and script context for engine-owned dead-code orchestration.
963///
964/// # Errors
965///
966/// Returns an error if plugin detection fails.
967pub fn prepare_dead_code_backend_prelude(
968    config: &ResolvedConfig,
969    discovery: AnalysisDiscovery,
970) -> Result<DeadCodeBackendPrelude<'_>, FallowError> {
971    let progress = new_analysis_progress(config);
972    let pipeline_start = Instant::now();
973    let workspace_pkgs = load_workspace_packages(&discovery.workspaces);
974    let (plugin_result, plugins_ms, scripts_ms) = run_plugins_and_scripts(&PluginScriptInput {
975        config,
976        progress: &progress,
977        files: discovery.files(),
978        workspaces: &discovery.workspaces,
979        root_pkg: discovery.root_pkg.as_ref(),
980        workspace_pkgs: &workspace_pkgs,
981        config_candidates: &discovery.config_candidates,
982    })?;
983
984    Ok(DeadCodeBackendPrelude {
985        config,
986        pipeline_start,
987        progress,
988        discovery,
989        workspace_pkgs,
990        plugin_result,
991        plugins_ms,
992        scripts_ms,
993    })
994}
995
996/// Discover entry points for an engine-owned dead-code pipeline.
997#[must_use]
998pub fn discover_dead_code_entry_points(
999    prelude: &DeadCodeBackendPrelude<'_>,
1000) -> DeadCodeEntryPoints {
1001    let shared = prelude.shared_input();
1002    DeadCodeEntryPoints {
1003        inner: discover_analysis_entry_points(&shared),
1004    }
1005}
1006
1007/// Try loading the graph cache for an engine-owned dead-code pipeline.
1008///
1009/// # Errors
1010///
1011/// Returns the reason the persisted graph was refused, the same way the
1012/// owned-core path does. The engine pipeline reports it in the perf table, so
1013/// collapsing a refusal into a bare miss here would make the only feature that
1014/// explains a slow warm run unreachable from every engine-backed command.
1015/// `Err(None)` means there was nothing to refuse: the run disabled caching.
1016pub fn try_load_dead_code_graph_cache(
1017    prelude: &DeadCodeBackendPrelude<'_>,
1018    entry_points: &DeadCodeEntryPoints,
1019    modules: &[extract::ModuleInfo],
1020) -> Result<(DeadCodeResolvedModules, DeadCodeGraphRun), Option<CacheRejection>> {
1021    let shared = prelude.shared_input();
1022    try_load_analysis_graph_cache(&shared, &entry_points.inner, modules).map(|hit| {
1023        (
1024            DeadCodeResolvedModules {
1025                project: hit.project,
1026                elapsed_ms: 0.0,
1027            },
1028            DeadCodeGraphRun {
1029                graph: hit.graph,
1030                elapsed_ms: hit.elapsed_ms,
1031            },
1032        )
1033    })
1034}
1035
1036/// Resolve imports for an engine-owned dead-code pipeline.
1037#[must_use]
1038pub fn resolve_dead_code_imports(
1039    prelude: &DeadCodeBackendPrelude<'_>,
1040    modules: &[extract::ModuleInfo],
1041) -> DeadCodeResolvedModules {
1042    let shared = prelude.shared_input();
1043    let resolved = resolve_analysis_imports_timed(&shared, modules);
1044    DeadCodeResolvedModules {
1045        project: resolved.project,
1046        elapsed_ms: resolved.elapsed_ms,
1047    }
1048}
1049
1050/// Build the module graph for an engine-owned dead-code pipeline.
1051#[must_use]
1052pub fn build_dead_code_graph(
1053    prelude: &DeadCodeBackendPrelude<'_>,
1054    project: &resolve::ResolvedProject,
1055    entry_points: &DeadCodeEntryPoints,
1056    modules: &[extract::ModuleInfo],
1057) -> DeadCodeGraphRun {
1058    let shared = prelude.shared_input();
1059    let graph = build_analysis_graph_timed(&shared, project, &entry_points.inner, modules);
1060    DeadCodeGraphRun {
1061        graph: graph.graph,
1062        elapsed_ms: graph.elapsed_ms,
1063    }
1064}
1065
1066/// Run the dead-code detectors for an engine-owned pipeline.
1067#[must_use]
1068pub fn run_dead_code_detectors(
1069    prelude: &DeadCodeBackendPrelude<'_>,
1070    graph: &graph::ModuleGraph,
1071    resolved: &[resolve::ResolvedModule],
1072    modules: &[extract::ModuleInfo],
1073    collect_usages: bool,
1074    entry_points: &DeadCodeEntryPoints,
1075) -> DeadCodeDetectorRun {
1076    let shared = prelude.shared_input();
1077    let analysis = analyze_dead_code_timed(
1078        &shared,
1079        graph,
1080        resolved,
1081        modules,
1082        collect_usages,
1083        entry_points.inner.summary.clone(),
1084    );
1085    DeadCodeDetectorRun {
1086        results: analysis.result,
1087        elapsed_ms: analysis.elapsed_ms,
1088    }
1089}
1090
1091impl<'a> DeadCodeBackendPrelude<'a> {
1092    fn shared_input(&'a self) -> AnalysisCoreSharedInput<'a> {
1093        AnalysisCoreSharedInput {
1094            config: self.config,
1095            progress: &self.progress,
1096            files: self.discovery.files(),
1097            workspaces: &self.discovery.workspaces,
1098            root_pkg: self.discovery.root_pkg.as_ref(),
1099            workspace_pkgs: &self.workspace_pkgs,
1100            plugin_result: &self.plugin_result,
1101        }
1102    }
1103}
1104
1105/// Prelude/aggregate metrics shared between the parse and reuse pipeline paths
1106/// when assembling the `PipelineProfile`.
1107struct PreludeMetrics {
1108    discover_ms: f64,
1109    workspaces_ms: f64,
1110    plugins_ms: f64,
1111    scripts_ms: f64,
1112    total_ms: f64,
1113    file_count: usize,
1114    workspace_count: usize,
1115    module_count: usize,
1116}
1117
1118/// The four prelude phase timings (discovery through script analysis).
1119#[expect(
1120    clippy::struct_field_names,
1121    reason = "timings are all milliseconds; the _ms suffix is the unit"
1122)]
1123struct PreludeTimings {
1124    discover_ms: f64,
1125    workspaces_ms: f64,
1126    plugins_ms: f64,
1127    scripts_ms: f64,
1128}
1129
1130/// Build `PreludeMetrics` from the prelude timings, pipeline start instant, and
1131/// the discovered file/workspace/module counts.
1132fn prelude_metrics(
1133    timings: &PreludeTimings,
1134    pipeline_start: Instant,
1135    files: &[discover::DiscoveredFile],
1136    workspaces: &[fallow_config::WorkspaceInfo],
1137    module_count: usize,
1138) -> PreludeMetrics {
1139    PreludeMetrics {
1140        discover_ms: timings.discover_ms,
1141        workspaces_ms: timings.workspaces_ms,
1142        plugins_ms: timings.plugins_ms,
1143        scripts_ms: timings.scripts_ms,
1144        total_ms: pipeline_start.elapsed().as_secs_f64() * 1000.0,
1145        file_count: files.len(),
1146        workspace_count: workspaces.len(),
1147        module_count,
1148    }
1149}
1150
1151struct AnalysisCoreSharedInput<'a> {
1152    config: &'a ResolvedConfig,
1153    progress: &'a progress::AnalysisProgress,
1154    files: &'a [discover::DiscoveredFile],
1155    workspaces: &'a [fallow_config::WorkspaceInfo],
1156    root_pkg: Option<&'a PackageJson>,
1157    workspace_pkgs: &'a [LoadedWorkspacePackage],
1158    plugin_result: &'a plugins::AggregatedPluginResult,
1159}
1160
1161struct TimedEntryPoints {
1162    entry_points: discover::CategorizedEntryPoints,
1163    summary: results::EntryPointSummary,
1164    count: usize,
1165    elapsed_ms: f64,
1166    spans: EntryPointSpans,
1167}
1168
1169struct TimedResolvedModules {
1170    project: resolve::ResolvedProject,
1171    elapsed_ms: f64,
1172}
1173
1174struct TimedGraph {
1175    graph: graph::ModuleGraph,
1176    elapsed_ms: f64,
1177}
1178
1179struct GraphCacheHit {
1180    graph: graph::ModuleGraph,
1181    project: resolve::ResolvedProject,
1182    elapsed_ms: f64,
1183}
1184
1185#[derive(Clone, Copy)]
1186struct DiscoverAllEntryPointsInput<'a> {
1187    config: &'a ResolvedConfig,
1188    files: &'a [discover::DiscoveredFile],
1189    workspaces: &'a [fallow_config::WorkspaceInfo],
1190    root_pkg: Option<&'a PackageJson>,
1191    workspace_pkgs: &'a [LoadedWorkspacePackage],
1192    plugin_result: &'a plugins::AggregatedPluginResult,
1193}
1194
1195struct TimedAnalysis {
1196    result: AnalysisResults,
1197    elapsed_ms: f64,
1198}
1199
1200fn discover_analysis_entry_points(input: &AnalysisCoreSharedInput<'_>) -> TimedEntryPoints {
1201    let t = Instant::now();
1202    let (entry_points, spans) = discover_all_entry_points(DiscoverAllEntryPointsInput {
1203        config: input.config,
1204        files: input.files,
1205        workspaces: input.workspaces,
1206        root_pkg: input.root_pkg,
1207        workspace_pkgs: input.workspace_pkgs,
1208        plugin_result: input.plugin_result,
1209    });
1210    let elapsed_ms = t.elapsed().as_secs_f64() * 1000.0;
1211    let summary = summarize_entry_points(&entry_points.all);
1212    let count = entry_points.all.len();
1213
1214    TimedEntryPoints {
1215        entry_points,
1216        summary,
1217        count,
1218        elapsed_ms,
1219        spans,
1220    }
1221}
1222
1223/// Try to reuse the persisted module graph.
1224///
1225/// # Errors
1226///
1227/// `Err(Some(reason))` names why persisted work was refused. Two of these
1228/// branches are decided AFTER a full decode of a multi-megabyte blob, so they
1229/// are the most expensive refusals in the pipeline; leaving them silent made a
1230/// fully paid, fully wasted load indistinguishable from a first run.
1231/// `Err(None)` means there was nothing to refuse: the run disabled caching.
1232fn try_load_analysis_graph_cache(
1233    input: &AnalysisCoreSharedInput<'_>,
1234    entry_points: &TimedEntryPoints,
1235    modules: &[extract::ModuleInfo],
1236) -> Result<GraphCacheHit, Option<CacheRejection>> {
1237    if input.config.no_cache {
1238        return Err(None);
1239    }
1240
1241    let t = Instant::now();
1242    input.progress.set_stage("loading module graph cache...");
1243    let unseeded_declaration_files = orphan_module_declaration_files(input, modules);
1244    let current = build_graph_cache_manifest(
1245        input.config,
1246        input.plugin_result,
1247        &entry_points.entry_points,
1248        input.files,
1249        modules,
1250        &unseeded_declaration_files,
1251    );
1252    let store = graph_cache::GraphCacheStore::load(&input.config.cache_dir).map_err(Some)?;
1253    if store.manifest.matches_inputs(&current) {
1254        let project = restore_cached_resolved_project(input, modules, &store.resolved_project)?;
1255        tracing::debug!("Graph cache hit: skipping import resolution and graph build");
1256        let mut graph = store.graph;
1257        credit_bin_path_references(
1258            &mut graph,
1259            modules,
1260            &input.plugin_result.dependency_binaries,
1261        );
1262
1263        return Ok(GraphCacheHit {
1264            graph,
1265            project,
1266            elapsed_ms: t.elapsed().as_secs_f64() * 1000.0,
1267        });
1268    }
1269
1270    if let Some(rejection) = store.manifest.classify_resolution_mismatch(&current) {
1271        // The level is the rejection's own judgement of whether the reader can
1272        // do anything about it. Content drift is what a cache is for, so it
1273        // stays off stderr and is read from doctor or the performance table
1274        // instead; `describe()` already names the reason, so no field repeats it.
1275        if rejection.discarded_existing_work() {
1276            tracing::warn!(
1277                "Graph cache decoded but not reused: {}",
1278                rejection.describe()
1279            );
1280        } else {
1281            tracing::debug!(
1282                "Graph cache decoded but not reused: {}",
1283                rejection.describe()
1284            );
1285        }
1286        return Err(Some(rejection));
1287    }
1288
1289    let project = restore_cached_resolved_project(input, modules, &store.resolved_project)?;
1290    tracing::debug!("Graph resolver cache hit: skipping import resolution and rebuilding graph");
1291    let graph = build_analysis_graph_timed(input, &project, entry_points, modules);
1292
1293    Ok(GraphCacheHit {
1294        graph: graph.graph,
1295        project,
1296        elapsed_ms: t.elapsed().as_secs_f64() * 1000.0,
1297    })
1298}
1299
1300/// Remap a decoded resolver payload onto the current `FileId`s.
1301///
1302/// A failure here means the persisted stable keys no longer describe the
1303/// discovered files, which is a file-set change reported the same way as a
1304/// manifest-level one rather than a silent miss.
1305fn restore_cached_resolved_project(
1306    input: &AnalysisCoreSharedInput<'_>,
1307    modules: &[extract::ModuleInfo],
1308    resolved_project: &graph_cache::CachedResolvedProject,
1309) -> Result<resolve::ResolvedProject, Option<CacheRejection>> {
1310    graph_cache::restore_resolved_project(
1311        &input.config.root,
1312        modules,
1313        input.files,
1314        resolved_project,
1315    )
1316    .inspect(|project| {
1317        record_unreadable_auto_import_reads(
1318            project,
1319            input.files,
1320            input.plugin_result,
1321            input.config,
1322        );
1323    })
1324    .ok_or_else(|| {
1325        // Same file-set drift the manifest reports, and equally routine: at
1326        // debug for the reason `CacheRejection::discarded_existing_work`
1327        // documents.
1328        tracing::debug!(
1329            "Graph cache decoded but its resolver payload no longer maps to the discovered files"
1330        );
1331        Some(CacheRejection::FileSetChanged)
1332    })
1333}
1334
1335fn resolve_analysis_imports_timed(
1336    input: &AnalysisCoreSharedInput<'_>,
1337    modules: &[extract::ModuleInfo],
1338) -> TimedResolvedModules {
1339    let t = Instant::now();
1340    input.progress.set_stage("resolving imports...");
1341    let project = resolve_analysis_imports(
1342        modules,
1343        input.files,
1344        input.workspaces,
1345        input.plugin_result,
1346        input.config,
1347    );
1348    TimedResolvedModules {
1349        project,
1350        elapsed_ms: t.elapsed().as_secs_f64() * 1000.0,
1351    }
1352}
1353
1354fn build_analysis_graph_timed(
1355    input: &AnalysisCoreSharedInput<'_>,
1356    project: &resolve::ResolvedProject,
1357    entry_points: &TimedEntryPoints,
1358    modules: &[extract::ModuleInfo],
1359) -> TimedGraph {
1360    let t = Instant::now();
1361    input.progress.set_stage("building module graph...");
1362    let unseeded_declaration_files = orphan_module_declaration_files(input, modules);
1363    let mut graph = build_analysis_graph(&BuildAnalysisGraphInput {
1364        config: input.config,
1365        plugin_result: input.plugin_result,
1366        project,
1367        entry_points: &entry_points.entry_points,
1368        files: input.files,
1369        modules,
1370        workspaces: input.workspaces,
1371        unseeded_declaration_files: &unseeded_declaration_files,
1372    });
1373    credit_bin_path_references(
1374        &mut graph,
1375        modules,
1376        &input.plugin_result.dependency_binaries,
1377    );
1378    TimedGraph {
1379        graph,
1380        elapsed_ms: t.elapsed().as_secs_f64() * 1000.0,
1381    }
1382}
1383
1384/// The orphan module declaration files of this run, which the graph does not
1385/// seed as entry points. See [`discover::find_orphan_module_declaration_files`].
1386fn orphan_module_declaration_files(
1387    input: &AnalysisCoreSharedInput<'_>,
1388    modules: &[extract::ModuleInfo],
1389) -> FxHashSet<discover::FileId> {
1390    discover::find_orphan_module_declaration_files(&input.config.root, input.files, modules)
1391}
1392
1393fn release_resolution_payloads(modules: &mut [extract::ModuleInfo]) {
1394    for module in modules {
1395        module.release_resolution_payload();
1396    }
1397}
1398
1399fn analyze_dead_code_timed(
1400    input: &AnalysisCoreSharedInput<'_>,
1401    graph: &graph::ModuleGraph,
1402    resolved: &[resolve::ResolvedModule],
1403    modules: &[extract::ModuleInfo],
1404    collect_usages: bool,
1405    entry_point_summary: results::EntryPointSummary,
1406) -> TimedAnalysis {
1407    let t = Instant::now();
1408    input.progress.set_stage("analyzing...");
1409    let mut result = analyze::find_dead_code_full(
1410        graph,
1411        input.config,
1412        resolved,
1413        Some(input.plugin_result),
1414        input.workspaces,
1415        modules,
1416        collect_usages,
1417    );
1418    result.entry_point_summary = Some(entry_point_summary);
1419    TimedAnalysis {
1420        result,
1421        elapsed_ms: t.elapsed().as_secs_f64() * 1000.0,
1422    }
1423}
1424
1425fn analyze_full(
1426    config: &ResolvedConfig,
1427    retain: bool,
1428    collect_usages: bool,
1429    need_complexity: bool,
1430    retain_modules: bool,
1431) -> Result<AnalysisOutput, FallowError> {
1432    let _span = tracing::info_span!("fallow_analyze").entered();
1433    AnalysisSession::new(config)?.run_full(retain, collect_usages, need_complexity, retain_modules)
1434}
1435
1436fn full_analysis_pipeline_profile(
1437    timings: &PreludeTimings,
1438    pipeline_start: Instant,
1439    files: &[discover::DiscoveredFile],
1440    workspaces: &[fallow_config::WorkspaceInfo],
1441    core: &OwnedAnalysisCore,
1442    metrics: &ParseMetrics,
1443) -> PipelineProfile {
1444    let prelude = prelude_metrics(
1445        timings,
1446        pipeline_start,
1447        files,
1448        workspaces,
1449        core.modules.len(),
1450    );
1451    full_pipeline_profile(&prelude, core, metrics)
1452}
1453
1454/// Assemble the `AnalysisOutput` for the full pipeline, honoring the graph/module
1455/// retention flags and computing per-file content hashes.
1456fn assemble_full_output(
1457    core: OwnedAnalysisCore,
1458    plugin_result: plugins::AggregatedPluginResult,
1459    profile: &PipelineProfile,
1460    files: &[discover::DiscoveredFile],
1461    retain: bool,
1462    retain_modules: bool,
1463) -> AnalysisOutput {
1464    let file_hashes = collect_file_hashes(&core.modules, files);
1465    AnalysisOutput {
1466        results: core.result,
1467        timings: retained_pipeline_timings(retain, profile),
1468        graph: if retain { Some(core.graph) } else { None },
1469        modules: if retain_modules {
1470            Some(core.modules)
1471        } else {
1472            None
1473        },
1474        files: if retain_modules {
1475            Some(files.to_vec())
1476        } else {
1477            None
1478        },
1479        script_used_packages: plugin_result.script_used_packages,
1480        trace_provenance: fallow_types::trace::TraceProvenance::default(),
1481        file_hashes,
1482    }
1483}
1484
1485/// Result of the freshly-parsed analysis core; returns the owned `modules` (so the
1486/// caller can retain them) plus the per-phase timings.
1487struct OwnedAnalysisCore {
1488    result: AnalysisResults,
1489    graph: graph::ModuleGraph,
1490    modules: Vec<extract::ModuleInfo>,
1491    entry_point_count: usize,
1492    entry_points_ms: f64,
1493    entry_point_spans: EntryPointSpans,
1494    resolve_ms: f64,
1495    graph_ms: f64,
1496    analyze_ms: f64,
1497    graph_cache_rejection: Option<CacheRejection>,
1498    resolve_work: resolve::ResolveWork,
1499}
1500
1501/// Assemble the `PipelineProfile` for the full (freshly parsed) pipeline path.
1502fn full_pipeline_profile(
1503    prelude: &PreludeMetrics,
1504    core: &OwnedAnalysisCore,
1505    parse: &ParseMetrics,
1506) -> PipelineProfile {
1507    PipelineProfile {
1508        discover_ms: prelude.discover_ms,
1509        workspaces_ms: prelude.workspaces_ms,
1510        plugins_ms: prelude.plugins_ms,
1511        scripts_ms: prelude.scripts_ms,
1512        parse_ms: parse.parse_ms,
1513        cache_ms: parse.cache_ms,
1514        entry_points_ms: core.entry_points_ms,
1515        entry_point_spans: core.entry_point_spans,
1516        resolve_ms: core.resolve_ms,
1517        graph_ms: core.graph_ms,
1518        analyze_ms: core.analyze_ms,
1519        total_ms: prelude.total_ms,
1520        file_count: prelude.file_count,
1521        workspace_count: prelude.workspace_count,
1522        module_count: prelude.module_count,
1523        entry_point_count: core.entry_point_count,
1524        cache_hits: parse.cache_hits,
1525        cache_misses: parse.cache_misses,
1526        parse_cpu_ms: parse.parse_cpu_ms,
1527        parse_cache_load_ms: parse.parse_cache_load_ms,
1528        cache_rejection: parse.cache_rejection,
1529        graph_cache_rejection: core.graph_cache_rejection,
1530        counters: PipelineCounters {
1531            files_read: parse.files_read,
1532            source_bytes_read: parse.source_bytes_read,
1533            parse_cache_bytes_read: parse.parse_cache_bytes_read,
1534            css_masked_bytes: parse.css_masked_bytes,
1535            resolve_specifier_calls: core.resolve_work.specifier_calls,
1536            unique_specifiers: core.resolve_work.unique_specifiers,
1537            oxc_resolve_calls: core.resolve_work.oxc_resolve_calls,
1538            canonicalize_calls: core.resolve_work.canonicalize_calls,
1539        },
1540    }
1541}
1542
1543#[derive(Clone, Copy)]
1544struct PipelineProfile {
1545    discover_ms: f64,
1546    workspaces_ms: f64,
1547    plugins_ms: f64,
1548    scripts_ms: f64,
1549    parse_ms: f64,
1550    cache_ms: f64,
1551    entry_points_ms: f64,
1552    entry_point_spans: EntryPointSpans,
1553    resolve_ms: f64,
1554    graph_ms: f64,
1555    analyze_ms: f64,
1556    total_ms: f64,
1557    file_count: usize,
1558    workspace_count: usize,
1559    module_count: usize,
1560    entry_point_count: usize,
1561    cache_hits: usize,
1562    cache_misses: usize,
1563    parse_cpu_ms: f64,
1564    parse_cache_load_ms: f64,
1565    cache_rejection: Option<CacheRejection>,
1566    graph_cache_rejection: Option<CacheRejection>,
1567    counters: PipelineCounters,
1568}
1569
1570struct AnalysisParseOutput {
1571    modules: Vec<extract::ModuleInfo>,
1572    metrics: ParseMetrics,
1573}
1574
1575/// Parse/cache phase metrics carried into the full-pipeline `PipelineProfile`.
1576struct ParseMetrics {
1577    parse_ms: f64,
1578    cache_ms: f64,
1579    cache_hits: usize,
1580    cache_misses: usize,
1581    parse_cpu_ms: f64,
1582    /// Why the persisted parse cache was not reused, when it was not.
1583    cache_rejection: Option<CacheRejection>,
1584    files_read: u64,
1585    source_bytes_read: u64,
1586    parse_cache_bytes_read: u64,
1587    css_masked_bytes: u64,
1588    parse_cache_load_ms: f64,
1589}
1590
1591impl From<AnalysisParseMetrics> for ParseMetrics {
1592    fn from(metrics: AnalysisParseMetrics) -> Self {
1593        Self {
1594            parse_ms: metrics.parse_ms,
1595            cache_ms: metrics.cache_ms,
1596            cache_hits: metrics.cache_hits,
1597            cache_misses: metrics.cache_misses,
1598            parse_cpu_ms: metrics.parse_cpu_ms,
1599            cache_rejection: metrics.cache_rejection,
1600            files_read: 0,
1601            source_bytes_read: 0,
1602            parse_cache_bytes_read: 0,
1603            css_masked_bytes: 0,
1604            parse_cache_load_ms: 0.0,
1605        }
1606    }
1607}
1608
1609fn parse_analysis_modules(
1610    config: &ResolvedConfig,
1611    files: &[discover::DiscoveredFile],
1612    need_complexity: bool,
1613    start: Instant,
1614) -> AnalysisParseOutput {
1615    let cache_max_size_bytes = resolve_cache_max_size_bytes(config);
1616    let mut cache_rejection = None;
1617    let mut parse_cache_bytes_read = 0;
1618    let mut parse_cache_load_ms = 0.0;
1619    let mut cache_store = if config.no_cache {
1620        None
1621    } else {
1622        let load_start = Instant::now();
1623        let (loaded, bytes_read) = cache::CacheStore::load_counting_bytes(
1624            &config.cache_dir,
1625            &config.root,
1626            config.cache_config_hash,
1627            cache_max_size_bytes,
1628        );
1629        parse_cache_bytes_read = bytes_read;
1630        parse_cache_load_ms = load_start.elapsed().as_secs_f64() * 1000.0;
1631        match loaded {
1632            Ok(store) => Some(store),
1633            Err(rejection) => {
1634                cache_rejection = Some(rejection);
1635                None
1636            }
1637        }
1638    };
1639
1640    let read_started_ns = fallow_types::source_fingerprint::now_ns();
1641    let parse_result = extract::parse_all_files_cancellable(
1642        files,
1643        cache_store.as_ref(),
1644        need_complexity,
1645        None,
1646        &config.flags.patterns(),
1647    );
1648    let _ = fallow_config::record_source_read_failures(&config.root, &parse_result.read_failures);
1649    let _ = fallow_config::record_source_parse_degradations(
1650        &config.root,
1651        &parse_result.parse_degradations,
1652    );
1653    let modules = parse_result.modules;
1654    let parse_ms = start.elapsed().as_secs_f64() * 1000.0;
1655    let cache_ms = update_parse_cache_if_enabled(
1656        config,
1657        &mut cache_store,
1658        &modules,
1659        files,
1660        need_complexity,
1661        read_started_ns,
1662    );
1663
1664    AnalysisParseOutput {
1665        modules,
1666        metrics: ParseMetrics {
1667            parse_ms,
1668            cache_ms,
1669            cache_hits: parse_result.cache_hits,
1670            cache_misses: parse_result.cache_misses,
1671            parse_cpu_ms: parse_result.parse_cpu_ms,
1672            cache_rejection,
1673            files_read: parse_result.files_read,
1674            source_bytes_read: parse_result.source_bytes_read,
1675            parse_cache_bytes_read,
1676            css_masked_bytes: parse_result.css_masked_bytes,
1677            parse_cache_load_ms,
1678        },
1679    }
1680}
1681
1682fn retained_pipeline_timings(retain: bool, profile: &PipelineProfile) -> Option<PipelineTimings> {
1683    retain.then_some(PipelineTimings {
1684        discover_files_ms: profile.discover_ms,
1685        file_count: profile.file_count,
1686        workspaces_ms: profile.workspaces_ms,
1687        workspace_count: profile.workspace_count,
1688        plugins_ms: profile.plugins_ms,
1689        script_analysis_ms: profile.scripts_ms,
1690        parse_extract_ms: profile.parse_ms,
1691        parse_cpu_ms: profile.parse_cpu_ms,
1692        parse_cache_load_ms: profile.parse_cache_load_ms,
1693        module_count: profile.module_count,
1694        cache_hits: profile.cache_hits,
1695        cache_misses: profile.cache_misses,
1696        cache_rejection: profile.cache_rejection,
1697        graph_cache_rejection: profile.graph_cache_rejection,
1698        cache_update_ms: profile.cache_ms,
1699        entry_points_ms: profile.entry_points_ms,
1700        entry_point_spans: profile.entry_point_spans,
1701        entry_point_count: profile.entry_point_count,
1702        resolve_imports_ms: profile.resolve_ms,
1703        build_graph_ms: profile.graph_ms,
1704        analyze_ms: profile.analyze_ms,
1705        duplication_ms: None,
1706        total_ms: profile.total_ms,
1707        counters: profile.counters,
1708    })
1709}
1710
1711fn update_parse_cache_if_enabled(
1712    config: &ResolvedConfig,
1713    cache_store: &mut Option<cache::CacheStore>,
1714    modules: &[extract::ModuleInfo],
1715    files: &[discover::DiscoveredFile],
1716    need_complexity: bool,
1717    read_started_ns: u64,
1718) -> f64 {
1719    let t = Instant::now();
1720    if !config.no_cache {
1721        let cache_max_size_bytes = resolve_cache_max_size_bytes(config);
1722        let store = cache_store.get_or_insert_with(|| cache::CacheStore::new(&config.root));
1723        if update_cache(store, modules, files, need_complexity, read_started_ns)
1724            && let Err(error) = store.save(
1725                &config.cache_dir,
1726                config.cache_config_hash,
1727                cache_max_size_bytes,
1728            )
1729        {
1730            tracing::warn!("Failed to save cache: {error}");
1731        }
1732    }
1733    t.elapsed().as_secs_f64() * 1000.0
1734}
1735
1736fn resolve_analysis_imports(
1737    modules: &[extract::ModuleInfo],
1738    files: &[discover::DiscoveredFile],
1739    workspaces: &[fallow_config::WorkspaceInfo],
1740    plugin_result: &plugins::AggregatedPluginResult,
1741    config: &ResolvedConfig,
1742) -> resolve::ResolvedProject {
1743    let mut project = resolve::resolve_all_imports(&resolve::ResolveAllImportsInput {
1744        modules,
1745        files,
1746        workspaces,
1747        active_plugins: &plugin_result.active_plugins,
1748        path_aliases: &plugin_result.path_aliases,
1749        auto_imports: &plugin_result.auto_imports,
1750        jsx_import_sources: &plugin_result.jsx_import_sources,
1751        scss_include_paths: &plugin_result.scss_include_paths,
1752        static_dir_mappings: &plugin_result.static_dir_mappings,
1753        framework_static_dir_mappings: &plugin_result.framework_static_dir_mappings,
1754        root: &config.root,
1755        extra_conditions: &config.resolve.conditions,
1756    });
1757    external_style_usage::augment_external_style_package_usage(
1758        &mut project.modules,
1759        config,
1760        workspaces,
1761        plugin_result,
1762    );
1763    record_unreadable_auto_import_reads(&project, files, plugin_result, config);
1764    project
1765}
1766
1767/// Record one `plugin-effect-not-modeled` diagnostic for each file that reads
1768/// `#components` or `#imports` in a way the graph cannot narrow to names, such
1769/// as a spread of a namespace import. The read credits every name of that
1770/// module, so the run can miss unused convention files, and nothing else says
1771/// so. Only a run with `autoImports` on drops the convention entry patterns, so
1772/// only that run records it. See issue #2752.
1773///
1774/// The plugin stage replaces every plugin-stage diagnostic at the start of the
1775/// run, so an append here cannot leave a stale entry. The input is the resolved
1776/// project, which a warm graph cache restores, so a warm run records the same
1777/// entries as a cold one.
1778fn record_unreadable_auto_import_reads(
1779    project: &resolve::ResolvedProject,
1780    files: &[discover::DiscoveredFile],
1781    plugin_result: &plugins::AggregatedPluginResult,
1782    config: &ResolvedConfig,
1783) {
1784    if !config.auto_imports
1785        || plugin_result.auto_imports.is_empty()
1786        || !plugin_result
1787            .active_plugins
1788            .iter()
1789            .any(|name| name == "nuxt")
1790    {
1791        return;
1792    }
1793    let diagnostics: Vec<fallow_config::WorkspaceDiagnostic> =
1794        resolve::unreadable_auto_import_reads(&project.modules)
1795            .into_iter()
1796            .filter_map(|read| {
1797                let file = files.get(read.file_id.0 as usize)?;
1798                let diagnostic = plugins::PluginConfigDiagnostic::not_modeled(
1799                    &file.path,
1800                    "nuxt",
1801                    read.module,
1802                    AUTO_IMPORT_KEY_NOT_MODELED,
1803                );
1804                Some(diagnostic.into_workspace_diagnostic(&config.root))
1805            })
1806            .collect();
1807    fallow_config::append_workspace_diagnostics(&config.root, diagnostics);
1808}
1809
1810struct BuildAnalysisGraphInput<'a> {
1811    config: &'a ResolvedConfig,
1812    plugin_result: &'a plugins::AggregatedPluginResult,
1813    project: &'a resolve::ResolvedProject,
1814    entry_points: &'a discover::CategorizedEntryPoints,
1815    files: &'a [discover::DiscoveredFile],
1816    modules: &'a [extract::ModuleInfo],
1817    workspaces: &'a [fallow_config::WorkspaceInfo],
1818    unseeded_declaration_files: &'a FxHashSet<discover::FileId>,
1819}
1820
1821/// Build the analysis graph and persist it for the next identical run.
1822///
1823/// The warm hit path happens before import resolution in
1824/// `try_load_analysis_graph_cache`. This miss path always builds fresh, runs
1825/// both credit steps, and persists the graph plus resolver outputs for next
1826/// time. The cache is gated on `config.no_cache` and is a strict performance
1827/// optimization: a cache hit produces identical analysis results.
1828fn build_analysis_graph(input: &BuildAnalysisGraphInput<'_>) -> graph::ModuleGraph {
1829    let caching_enabled = !input.config.no_cache;
1830    let current_manifest = caching_enabled.then(|| {
1831        build_graph_cache_manifest(
1832            input.config,
1833            input.plugin_result,
1834            input.entry_points,
1835            input.files,
1836            input.modules,
1837            input.unseeded_declaration_files,
1838        )
1839    });
1840
1841    let mut graph = graph::ModuleGraph::build_with_declaration_seeding(
1842        &input.project.modules,
1843        &input.project.replaced_module_targets,
1844        &graph::ReachabilityRoots {
1845            all: &input.entry_points.all,
1846            runtime: &input.entry_points.runtime,
1847            test: &input.entry_points.test,
1848        },
1849        input.files,
1850        input.unseeded_declaration_files,
1851    );
1852    credit_package_path_references(&mut graph, input.modules);
1853    credit_workspace_package_usage(&mut graph, &input.project.modules, input.workspaces);
1854
1855    if let Some(manifest) = current_manifest {
1856        let Some(resolved_project) =
1857            graph_cache::cache_resolved_project(&input.config.root, input.files, input.project)
1858        else {
1859            return graph;
1860        };
1861        let store = graph_cache::GraphCacheStore {
1862            version: graph_cache::GRAPH_CACHE_VERSION,
1863            manifest,
1864            graph,
1865            resolved_project,
1866        };
1867        store.save(&input.config.cache_dir);
1868        // `save` borrows the store, so the freshly built graph is moved back out
1869        // and returned in-memory. The warm path loads-and-reconstructs an
1870        // identical graph from this same persisted blob (proven by the
1871        // cold-vs-warm correctness gate).
1872        return store.graph;
1873    }
1874
1875    graph
1876}
1877
1878/// Build the current `GraphCacheManifest` from the run's discovered files and
1879/// graph-affecting option hashes.
1880fn build_graph_cache_manifest(
1881    config: &ResolvedConfig,
1882    plugin_result: &plugins::AggregatedPluginResult,
1883    entry_points: &discover::CategorizedEntryPoints,
1884    files: &[discover::DiscoveredFile],
1885    modules: &[extract::ModuleInfo],
1886    unseeded_declaration_files: &FxHashSet<discover::FileId>,
1887) -> graph_cache::GraphCacheManifest {
1888    let mode = graph_cache::GraphCacheMode::new(
1889        resolver_options_hash(config),
1890        entry_points_hash(
1891            entry_points,
1892            files,
1893            unseeded_declaration_files,
1894            &config.root,
1895        ),
1896        plugin_config_hash(plugin_result, &config.root),
1897    );
1898    // The parse stage already hashed every file it read, so keying the manifest
1899    // on content costs nothing and does not inherit mtime's blind spot for a
1900    // same-size rewrite. A file with no module (unreadable) hashes to 0, which
1901    // compares equal only against another run that also failed to read it.
1902    let mut content_hashes = vec![0u64; files.len()];
1903    for module in modules {
1904        if let Some(slot) = content_hashes.get_mut(module.file_id.0 as usize) {
1905            *slot = module.content_hash;
1906        }
1907    }
1908    graph_cache::GraphCacheManifest::from_discovered_files(&config.root, files, mode, |file| {
1909        content_hashes
1910            .get(file.id.0 as usize)
1911            .copied()
1912            .unwrap_or_default()
1913    })
1914}
1915
1916/// Hash the resolver-affecting options: the extraction config hash and the
1917/// user-supplied resolve `conditions`.
1918///
1919/// The project root is deliberately NOT hashed. It is not a resolver option:
1920/// it is where the project happens to sit, and hashing it meant a container
1921/// job, a matrix over roots, or a copied worktree could never reuse a cache it
1922/// had fully decoded. Every path this mode covers is hashed root-relative
1923/// instead.
1924///
1925/// `cache_config_hash` does NOT fold tsconfig `paths`, despite what this
1926/// comment used to claim: it hashes extraction-affecting config plus external
1927/// plugin names. tsconfig-derived aliases reach the mode through
1928/// [`hash_path_aliases`].
1929///
1930/// `production` and `ignore_patterns` intentionally stay out of this hash:
1931/// they shape discovery, so changed file sets already miss through stable file
1932/// keys and source fingerprints in the manifest.
1933fn resolver_options_hash(config: &ResolvedConfig) -> u64 {
1934    use std::hash::{Hash, Hasher};
1935    let mut hasher = rustc_hash::FxHasher::default();
1936    config.cache_config_hash.hash(&mut hasher);
1937    config.resolve.conditions.hash(&mut hasher);
1938    hasher.finish()
1939}
1940
1941/// Render `path` the way every graph-cache mode hash spells a path: relative to
1942/// the project root where possible, with forward slashes, so an identical
1943/// project under a different absolute path hashes identically.
1944fn root_relative_key(root: &std::path::Path, path: &std::path::Path) -> String {
1945    path.strip_prefix(root)
1946        .unwrap_or(path)
1947        .to_string_lossy()
1948        .replace('\\', "/")
1949}
1950
1951/// Hash the entry-point set (sorted root-relative paths per role) so any change
1952/// in reachability roots misses the cache. The declaration files the graph
1953/// does not seed are reachability roots too: they depend on package.json,
1954/// tsconfig and sibling files the manifest does not track.
1955fn entry_points_hash(
1956    entry_points: &discover::CategorizedEntryPoints,
1957    files: &[discover::DiscoveredFile],
1958    unseeded_declaration_files: &FxHashSet<discover::FileId>,
1959    root: &std::path::Path,
1960) -> u64 {
1961    use std::hash::{Hash, Hasher};
1962    let mut hasher = rustc_hash::FxHasher::default();
1963    for role in [&entry_points.all, &entry_points.runtime, &entry_points.test] {
1964        let mut keys: Vec<String> = role
1965            .iter()
1966            .map(|ep| root_relative_key(root, &ep.path))
1967            .collect();
1968        keys.sort_unstable();
1969        keys.len().hash(&mut hasher);
1970        for key in keys {
1971            key.hash(&mut hasher);
1972        }
1973    }
1974    let mut unseeded: Vec<String> = files
1975        .iter()
1976        .filter(|file| unseeded_declaration_files.contains(&file.id))
1977        .map(|file| root_relative_key(root, &file.path))
1978        .collect();
1979    unseeded.sort_unstable();
1980    unseeded.len().hash(&mut hasher);
1981    for key in unseeded {
1982        key.hash(&mut hasher);
1983    }
1984    hasher.finish()
1985}
1986
1987/// Hash the plugin-derived graph-affecting configuration, with every path
1988/// spelled root-relative.
1989fn plugin_config_hash(
1990    plugin_result: &plugins::AggregatedPluginResult,
1991    root: &std::path::Path,
1992) -> u64 {
1993    use std::hash::{Hash, Hasher};
1994    let mut hasher = rustc_hash::FxHasher::default();
1995
1996    hash_active_plugins(plugin_result, &mut hasher);
1997    hash_path_aliases(plugin_result, root, &mut hasher);
1998
1999    let mut auto_imports: Vec<AutoImportHashKey<'_>> = plugin_result
2000        .auto_imports
2001        .iter()
2002        .map(|rule| {
2003            let mut scope: Vec<String> = rule
2004                .scope
2005                .iter()
2006                .map(|scope_root| root_relative_key(root, scope_root))
2007                .collect();
2008            scope.sort_unstable();
2009            (
2010                rule.name.as_str(),
2011                root_relative_key(root, &rule.source),
2012                auto_import_kind_rank(rule.kind),
2013                scope,
2014            )
2015        })
2016        .collect();
2017    auto_imports.sort_unstable();
2018    auto_imports.len().hash(&mut hasher);
2019    for key in &auto_imports {
2020        key.hash(&mut hasher);
2021    }
2022
2023    let mut jsx_import_sources: Vec<(&str, String, Vec<&str>)> = plugin_result
2024        .jsx_import_sources
2025        .iter()
2026        .map(|rule| {
2027            let mut include: Vec<&str> = rule.include.iter().map(String::as_str).collect();
2028            include.sort_unstable();
2029            (
2030                rule.source.as_str(),
2031                root_relative_key(root, &rule.config_dir),
2032                include,
2033            )
2034        })
2035        .collect();
2036    jsx_import_sources.sort_unstable();
2037    jsx_import_sources.dedup();
2038    jsx_import_sources.len().hash(&mut hasher);
2039    for key in &jsx_import_sources {
2040        key.hash(&mut hasher);
2041    }
2042
2043    let mut scss_include_paths: Vec<String> = plugin_result
2044        .scss_include_paths
2045        .iter()
2046        .map(|path| root_relative_key(root, path))
2047        .collect();
2048    scss_include_paths.sort_unstable();
2049    scss_include_paths.len().hash(&mut hasher);
2050    for path in scss_include_paths {
2051        path.hash(&mut hasher);
2052    }
2053
2054    let mut static_dir_mappings: Vec<(String, &str)> = plugin_result
2055        .static_dir_mappings
2056        .iter()
2057        .map(|(from_dir, mount)| (root_relative_key(root, from_dir), mount.as_str()))
2058        .collect();
2059    static_dir_mappings.sort_unstable();
2060    static_dir_mappings.len().hash(&mut hasher);
2061    for (from_dir, mount) in static_dir_mappings {
2062        from_dir.hash(&mut hasher);
2063        mount.hash(&mut hasher);
2064    }
2065
2066    hasher.finish()
2067}
2068
2069fn hash_active_plugins(
2070    plugin_result: &plugins::AggregatedPluginResult,
2071    hasher: &mut rustc_hash::FxHasher,
2072) {
2073    use std::hash::Hash;
2074    let mut active: Vec<&str> = plugin_result
2075        .active_plugins
2076        .iter()
2077        .map(String::as_str)
2078        .collect();
2079    active.sort_unstable();
2080    active.len().hash(hasher);
2081    for name in active {
2082        name.hash(hasher);
2083    }
2084}
2085
2086/// Hash tsconfig- and plugin-derived path aliases. Replacements are absolute
2087/// filesystem paths, so they are spelled root-relative like every other path in
2088/// the mode hash.
2089fn hash_path_aliases(
2090    plugin_result: &plugins::AggregatedPluginResult,
2091    root: &std::path::Path,
2092    hasher: &mut rustc_hash::FxHasher,
2093) {
2094    use std::hash::Hash;
2095    let mut aliases: Vec<(&str, String)> = plugin_result
2096        .path_aliases
2097        .iter()
2098        .map(|(prefix, replacement)| {
2099            (
2100                prefix.as_str(),
2101                root_relative_key(root, std::path::Path::new(replacement)),
2102            )
2103        })
2104        .collect();
2105    aliases.sort_unstable();
2106    aliases.len().hash(hasher);
2107    for (prefix, replacement) in aliases {
2108        prefix.hash(hasher);
2109        replacement.hash(hasher);
2110    }
2111}
2112
2113/// The fields of one auto-import rule that decide its graph edges: name,
2114/// root-relative source, kind rank, and sorted root-relative scope.
2115type AutoImportHashKey<'a> = (&'a str, String, u8, Vec<String>);
2116
2117fn auto_import_kind_rank(kind: fallow_config::AutoImportKind) -> u8 {
2118    match kind {
2119        fallow_config::AutoImportKind::Named => 0,
2120        fallow_config::AutoImportKind::Default => 1,
2121        fallow_config::AutoImportKind::DefaultComponent => 2,
2122    }
2123}
2124
2125fn collect_file_hashes(
2126    modules: &[extract::ModuleInfo],
2127    files: &[discover::DiscoveredFile],
2128) -> rustc_hash::FxHashMap<std::path::PathBuf, u64> {
2129    modules
2130        .iter()
2131        .filter_map(|module| {
2132            files
2133                .get(module.file_id.0 as usize)
2134                .map(|file| (file.path.clone(), module.content_hash))
2135        })
2136        .collect()
2137}
2138
2139fn trace_pipeline_profile(profile: &PipelineProfile) {
2140    let PipelineProfile {
2141        discover_ms,
2142        workspaces_ms,
2143        plugins_ms,
2144        scripts_ms,
2145        parse_ms,
2146        cache_ms,
2147        entry_points_ms,
2148        resolve_ms,
2149        graph_ms,
2150        analyze_ms,
2151        total_ms,
2152        file_count,
2153        module_count,
2154        entry_point_count,
2155        cache_hits,
2156        cache_misses,
2157        cache_rejection,
2158        ..
2159    } = *profile;
2160    let cache_summary = cache_rejection.map_or_else(
2161        || format!(" ({cache_hits} cached, {cache_misses} parsed)"),
2162        |rejection| {
2163            format!(
2164                " ({cache_hits} cached, {cache_misses} parsed, cache refused: {})",
2165                rejection.describe()
2166            )
2167        },
2168    );
2169
2170    tracing::debug!(
2171        "\n┌─ Pipeline Profile ─────────────────────────────\n\
2172         │  discover files:   {:>8.1}ms  ({} files)\n\
2173         │  workspaces:       {:>8.1}ms\n\
2174         │  plugin detection: {:>8.1}ms\n\
2175         │  script analysis:  {:>8.1}ms\n\
2176         │  parse/extract:    {:>8.1}ms  ({} modules{})\n\
2177         │  cache update:     {:>8.1}ms\n\
2178         │  entry points:     {:>8.1}ms  ({} entries)\n\
2179         │  resolve imports:  {:>8.1}ms\n\
2180         │  build graph:      {:>8.1}ms\n\
2181         │  analyze:          {:>8.1}ms\n\
2182         │  ────────────────────────────────────────────\n\
2183         │  TOTAL:            {:>8.1}ms\n\
2184         └─────────────────────────────────────────────────",
2185        discover_ms,
2186        file_count,
2187        workspaces_ms,
2188        plugins_ms,
2189        scripts_ms,
2190        parse_ms,
2191        module_count,
2192        cache_summary,
2193        cache_ms,
2194        entry_points_ms,
2195        entry_point_count,
2196        resolve_ms,
2197        graph_ms,
2198        analyze_ms,
2199        total_ms,
2200    );
2201}
2202
2203fn load_workspace_packages(
2204    workspaces: &[fallow_config::WorkspaceInfo],
2205) -> Vec<LoadedWorkspacePackage> {
2206    workspaces
2207        .iter()
2208        .filter_map(|ws| {
2209            fallow_config::load_dir_package_json(&ws.root).map(|pkg| (ws.clone(), pkg))
2210        })
2211        .collect()
2212}
2213
2214/// Analyze package.json scripts from root and all workspace packages.
2215///
2216/// Populates the plugin result with script-used packages and config file
2217/// entry patterns. Also scans CI config files for binary invocations.
2218fn analyze_all_scripts(
2219    config: &ResolvedConfig,
2220    workspaces: &[fallow_config::WorkspaceInfo],
2221    root_pkg: Option<&PackageJson>,
2222    workspace_pkgs: &[LoadedWorkspacePackage],
2223    plugin_result: &mut plugins::AggregatedPluginResult,
2224) {
2225    let all_dep_names = collect_all_dependency_names(root_pkg, workspace_pkgs);
2226    let all_dep_set: FxHashSet<String> = all_dep_names.iter().cloned().collect();
2227    let workspace_packages =
2228        discover::collect_workspace_packages(&config.root, root_pkg, workspace_pkgs);
2229    let all_scripts = collect_all_scripts(root_pkg, workspace_pkgs, &workspace_packages);
2230
2231    let nm_roots = collect_node_modules_roots(config, workspaces);
2232    let bin_map = scripts::build_bin_to_package_map(&nm_roots, &all_dep_names);
2233    let registry = plugins::PluginRegistry::new(config.external_plugins.clone());
2234    let deps = ScriptDependencyContext {
2235        bin_map: &bin_map,
2236        all_dep_set: &all_dep_set,
2237        workspace_packages: &workspace_packages,
2238        registry: &registry,
2239    };
2240
2241    analyze_root_scripts(config, root_pkg, &deps, plugin_result);
2242    analyze_workspace_scripts(config, workspace_pkgs, &deps, plugin_result);
2243    analyze_ci_scripts(config, &bin_map, &all_dep_set, &all_scripts, plugin_result);
2244    analyze_hook_scripts(
2245        config,
2246        workspaces,
2247        &scripts::hooks::HookContext {
2248            bin_map: &bin_map,
2249            declared_packages: &all_dep_set,
2250            scripts: &all_scripts,
2251            ignored: scripts::IgnoredCommandEntries::new(&config.ignore_command_entries),
2252        },
2253        plugin_result,
2254    );
2255    plugin_result.dependency_binaries =
2256        scripts::DependencyBinaries::new(config.root.clone(), bin_map, all_dep_set);
2257    plugin_result.dev_dependency_names = root_pkg
2258        .into_iter()
2259        .chain(workspace_pkgs.iter().map(|(_, ws_pkg)| ws_pkg))
2260        .flat_map(PackageJson::dev_dependency_names)
2261        .collect();
2262
2263    plugin_result
2264        .entry_point_roles
2265        .entry("scripts".to_string())
2266        .or_insert(EntryPointRole::Support);
2267}
2268
2269/// Gather sorted, deduped dependency names across the root and workspace packages.
2270fn collect_all_dependency_names(
2271    root_pkg: Option<&PackageJson>,
2272    workspace_pkgs: &[LoadedWorkspacePackage],
2273) -> Vec<String> {
2274    let mut all_dep_names: Vec<String> = Vec::new();
2275    if let Some(pkg) = root_pkg {
2276        all_dep_names.extend(pkg.all_dependency_names());
2277    }
2278    for (_, ws_pkg) in workspace_pkgs {
2279        all_dep_names.extend(ws_pkg.all_dependency_names());
2280    }
2281    all_dep_names.sort_unstable();
2282    all_dep_names.dedup();
2283    all_dep_names
2284}
2285
2286/// The binaries, dependencies, and workspace packages that script analysis
2287/// resolves commands against.
2288struct ScriptDependencyContext<'a> {
2289    bin_map: &'a rustc_hash::FxHashMap<String, String>,
2290    all_dep_set: &'a FxHashSet<String>,
2291    workspace_packages: &'a std::sync::Arc<scripts::WorkspacePackages>,
2292    registry: &'a plugins::PluginRegistry,
2293}
2294
2295/// The directory of a workspace package relative to the project root, with
2296/// `/` separators.
2297fn workspace_dir(root: &std::path::Path, ws: &fallow_config::WorkspaceInfo) -> String {
2298    ws.root
2299        .strip_prefix(root)
2300        .unwrap_or(&ws.root)
2301        .to_string_lossy()
2302        .replace('\\', "/")
2303}
2304
2305/// Gather the scripts declared by the root and workspace packages.
2306fn collect_all_scripts(
2307    root_pkg: Option<&PackageJson>,
2308    workspace_pkgs: &[LoadedWorkspacePackage],
2309    workspace_packages: &std::sync::Arc<scripts::WorkspacePackages>,
2310) -> scripts::ScriptCatalog {
2311    let mut catalog = scripts::ScriptCatalog::default();
2312    if let Some(pkg) = root_pkg
2313        && let Some(ref pkg_scripts) = pkg.scripts
2314    {
2315        catalog.merge_scripts(pkg_scripts);
2316    }
2317    for (_, ws_pkg) in workspace_pkgs {
2318        if let Some(ref ws_scripts) = ws_pkg.scripts {
2319            catalog.merge_workspace_scripts(ws_scripts);
2320        }
2321    }
2322    catalog.with_workspaces(std::sync::Arc::clone(workspace_packages), "")
2323}
2324
2325/// Collect every directory (root and workspaces) that has a local `node_modules`.
2326fn collect_node_modules_roots<'a>(
2327    config: &'a ResolvedConfig,
2328    workspaces: &'a [fallow_config::WorkspaceInfo],
2329) -> Vec<&'a std::path::Path> {
2330    let mut nm_roots: Vec<&std::path::Path> = Vec::new();
2331    if config.root.join("node_modules").is_dir() {
2332        nm_roots.push(&config.root);
2333    }
2334    for ws in workspaces {
2335        if ws.root.join("node_modules").is_dir() {
2336            nm_roots.push(&ws.root);
2337        }
2338    }
2339    nm_roots
2340}
2341
2342/// Scripts that the Nx `run-commands` targets of `<dir>/project.json` run, keyed
2343/// `nx:<target>` so they never collide with a `package.json` script.
2344#[expect(
2345    clippy::disallowed_types,
2346    reason = "joins the std HashMap of package.json scripts"
2347)]
2348fn nx_target_scripts(
2349    dir: &std::path::Path,
2350    project_root: &str,
2351    production: bool,
2352) -> std::collections::HashMap<String, String> {
2353    let Ok(source) = std::fs::read_to_string(dir.join("project.json")) else {
2354        return std::collections::HashMap::new();
2355    };
2356    let commands: std::collections::HashMap<String, String> =
2357        scripts::nx_targets::run_commands_scripts(&source, project_root)
2358            .into_iter()
2359            .collect();
2360    let commands = if production {
2361        scripts::filter_production_scripts(&commands)
2362    } else {
2363        commands
2364    };
2365    commands
2366        .into_iter()
2367        .map(|(target, command)| (format!("nx:{target}"), command))
2368        .collect()
2369}
2370
2371/// Analyze the root package.json scripts and fold the results into the plugin result.
2372fn analyze_root_scripts(
2373    config: &ResolvedConfig,
2374    root_pkg: Option<&PackageJson>,
2375    deps: &ScriptDependencyContext<'_>,
2376    plugin_result: &mut plugins::AggregatedPluginResult,
2377) {
2378    let pkg_scripts = root_pkg
2379        .and_then(|pkg| pkg.scripts.clone())
2380        .unwrap_or_default();
2381    let mut scripts_to_analyze = if config.production {
2382        scripts::filter_production_scripts(&pkg_scripts)
2383    } else {
2384        pkg_scripts.clone()
2385    };
2386    scripts_to_analyze.extend(nx_target_scripts(&config.root, "", config.production));
2387    if scripts_to_analyze.is_empty() {
2388        return;
2389    }
2390    let pkg_scripts = &pkg_scripts;
2391    let catalog =
2392        scripts::ScriptCatalog::from_scripts_with_bodies(pkg_scripts, &scripts_to_analyze)
2393            .with_workspaces(std::sync::Arc::clone(deps.workspace_packages), "");
2394    let script_analysis = scripts::analyze_scripts_with_dependency_context(
2395        &scripts_to_analyze,
2396        &config.root,
2397        deps.bin_map,
2398        deps.all_dep_set,
2399        &catalog,
2400        scripts::IgnoredCommandEntries::new(&config.ignore_command_entries),
2401    );
2402    plugin_result.script_used_packages = script_analysis.used_packages;
2403    plugin_result.merge_into(deps.registry.resolve_script_config_files(
2404        &script_analysis.binary_config_files,
2405        &config.root,
2406        "",
2407    ));
2408
2409    for config_file in &script_analysis.config_files {
2410        if let Some(path) = scripts::normalize_script_entry_pattern("", config_file) {
2411            plugin_result
2412                .discovered_always_used
2413                .push((path, "scripts".to_string()));
2414        }
2415    }
2416    for entry in &script_analysis.entry_files {
2417        if let Some(pat) = scripts::normalize_script_entry_pattern("", entry) {
2418            plugin_result
2419                .entry_patterns
2420                .push((plugins::PathRule::new(pat), "scripts".to_string()));
2421        }
2422    }
2423}
2424
2425/// Analyze each workspace package's scripts in parallel and merge the results.
2426type WsScriptOut = (
2427    Vec<String>,
2428    Vec<(String, String)>,
2429    Vec<(plugins::PathRule, String)>,
2430    plugins::AggregatedPluginResult,
2431);
2432
2433fn analyze_workspace_scripts(
2434    config: &ResolvedConfig,
2435    workspace_pkgs: &[LoadedWorkspacePackage],
2436    deps: &ScriptDependencyContext<'_>,
2437    plugin_result: &mut plugins::AggregatedPluginResult,
2438) {
2439    let ws_results: Vec<WsScriptOut> = workspace_pkgs
2440        .par_iter()
2441        .map(|(ws, ws_pkg)| analyze_one_workspace_scripts(config, ws, ws_pkg, deps))
2442        .collect();
2443    for (used_packages, discovered_always_used, entry_patterns, config_result) in ws_results {
2444        plugin_result.script_used_packages.extend(used_packages);
2445        plugin_result.merge_into(config_result);
2446        plugin_result
2447            .discovered_always_used
2448            .extend(discovered_always_used);
2449        plugin_result.entry_patterns.extend(entry_patterns);
2450    }
2451}
2452
2453/// Analyze a single workspace package's scripts, returning its used packages,
2454/// always-used config files, entry patterns, and the plugin result of the
2455/// config files that scripts pass to a plugin binary (all workspace-prefixed).
2456fn analyze_one_workspace_scripts(
2457    config: &ResolvedConfig,
2458    ws: &fallow_config::WorkspaceInfo,
2459    ws_pkg: &PackageJson,
2460    deps: &ScriptDependencyContext<'_>,
2461) -> WsScriptOut {
2462    let mut used_packages = Vec::new();
2463    let mut discovered_always_used: Vec<(String, String)> = Vec::new();
2464    let mut entry_patterns: Vec<(plugins::PathRule, String)> = Vec::new();
2465    let ws_prefix = workspace_dir(&config.root, ws);
2466    let ws_scripts = ws_pkg.scripts.clone().unwrap_or_default();
2467    let mut scripts_to_analyze = if config.production {
2468        scripts::filter_production_scripts(&ws_scripts)
2469    } else {
2470        ws_scripts.clone()
2471    };
2472    scripts_to_analyze.extend(nx_target_scripts(&ws.root, &ws_prefix, config.production));
2473    if scripts_to_analyze.is_empty() {
2474        return (
2475            used_packages,
2476            discovered_always_used,
2477            entry_patterns,
2478            plugins::AggregatedPluginResult::default(),
2479        );
2480    }
2481    let catalog =
2482        scripts::ScriptCatalog::from_scripts_with_bodies(&ws_scripts, &scripts_to_analyze)
2483            .with_workspaces(std::sync::Arc::clone(deps.workspace_packages), &ws_prefix);
2484    let ws_analysis = scripts::analyze_scripts_with_dependency_context(
2485        &scripts_to_analyze,
2486        &ws.root,
2487        deps.bin_map,
2488        deps.all_dep_set,
2489        &catalog,
2490        scripts::IgnoredCommandEntries::new(&config.ignore_command_entries),
2491    );
2492    used_packages.extend(ws_analysis.used_packages);
2493    let config_result = deps.registry.resolve_script_config_files(
2494        &ws_analysis.binary_config_files,
2495        &ws.root,
2496        &ws_prefix,
2497    );
2498
2499    for config_file in &ws_analysis.config_files {
2500        if let Some(path) = scripts::normalize_script_entry_pattern(&ws_prefix, config_file) {
2501            discovered_always_used.push((path, "scripts".to_string()));
2502        }
2503    }
2504    for entry in &ws_analysis.entry_files {
2505        if let Some(pat) = scripts::normalize_script_entry_pattern(&ws_prefix, entry) {
2506            entry_patterns.push((plugins::PathRule::new(pat), "scripts".to_string()));
2507        }
2508    }
2509    (
2510        used_packages,
2511        discovered_always_used,
2512        entry_patterns,
2513        config_result,
2514    )
2515}
2516
2517/// Analyze CI config files for binary invocations and merge the results.
2518fn analyze_ci_scripts(
2519    config: &ResolvedConfig,
2520    bin_map: &rustc_hash::FxHashMap<String, String>,
2521    all_dep_set: &FxHashSet<String>,
2522    all_scripts: &scripts::ScriptCatalog,
2523    plugin_result: &mut plugins::AggregatedPluginResult,
2524) {
2525    let ci_analysis = scripts::ci::analyze_ci_files(
2526        &config.root,
2527        bin_map,
2528        all_dep_set,
2529        all_scripts,
2530        scripts::IgnoredCommandEntries::new(&config.ignore_command_entries),
2531    );
2532    plugin_result
2533        .script_used_packages
2534        .extend(ci_analysis.used_packages);
2535    for entry in &ci_analysis.entry_files {
2536        if let Some(pat) = scripts::normalize_script_entry_pattern("", entry) {
2537            plugin_result
2538                .entry_patterns
2539                .push((plugins::PathRule::new(pat), "scripts".to_string()));
2540        }
2541    }
2542}
2543
2544/// Analyze git hook and staged-file commands for binary invocations and merge
2545/// the invoked packages into the script-used set.
2546///
2547/// Hooks run on a developer machine, never in production, so production mode
2548/// skips them, like the non-production package.json scripts.
2549fn analyze_hook_scripts(
2550    config: &ResolvedConfig,
2551    workspaces: &[fallow_config::WorkspaceInfo],
2552    context: &scripts::hooks::HookContext<'_>,
2553    plugin_result: &mut plugins::AggregatedPluginResult,
2554) {
2555    if config.production {
2556        return;
2557    }
2558    let roots = std::iter::once(config.root.as_path()).chain(
2559        workspaces
2560            .iter()
2561            .map(|ws| ws.root.as_path())
2562            .filter(|root| *root != config.root.as_path()),
2563    );
2564    for root in roots {
2565        plugin_result
2566            .script_used_packages
2567            .extend(scripts::hooks::analyze_hook_files(root, context));
2568    }
2569}
2570
2571/// Discover all entry points from static patterns, workspaces, plugins, and infrastructure.
2572fn discover_all_entry_points(
2573    input: DiscoverAllEntryPointsInput<'_>,
2574) -> (discover::CategorizedEntryPoints, EntryPointSpans) {
2575    let mut spans = EntryPointSpans::default();
2576    let mut mark = Instant::now();
2577    let mut entry_points = discover::CategorizedEntryPoints::default();
2578    // Every script pass resolves a command that selects workspace packages
2579    // (`yarn workspace web node scripts/a.ts`) against the same packages.
2580    let workspace_packages = discover::collect_workspace_packages(
2581        &input.config.root,
2582        input.root_pkg,
2583        input.workspace_pkgs,
2584    );
2585    let runtime_seeds = discover::workspace_runtime_script_seeds(&workspace_packages);
2586    let discovered = discover::DiscoveredPaths::new(input.files);
2587    let is_discovered = |path: &std::path::Path| discovered.contains(path);
2588    let script_workspaces = discover::ScriptWorkspaces {
2589        packages: &workspace_packages,
2590        project_root: &input.config.root,
2591        runtime_seeds: &runtime_seeds,
2592        discovered: Some(&is_discovered),
2593    };
2594    let root_discovery = discover::discover_root_entry_points(
2595        input.config,
2596        input.files,
2597        input.root_pkg,
2598        input.workspaces.is_empty(),
2599        script_workspaces,
2600    );
2601    spans.root_ms = split_ms(&mut mark);
2602
2603    let workspace_pkg_by_root: rustc_hash::FxHashMap<std::path::PathBuf, &PackageJson> = input
2604        .workspace_pkgs
2605        .iter()
2606        .map(|(ws, pkg)| (ws.root.clone(), pkg))
2607        .collect();
2608    let workspace_discovery: Vec<discover::EntryPointDiscovery> = input
2609        .workspaces
2610        .par_iter()
2611        .map(|ws| {
2612            let pkg = workspace_pkg_by_root.get(&ws.root).copied();
2613            discover::discover_workspace_package_entry_points(
2614                &ws.root,
2615                input.files,
2616                pkg,
2617                scripts::IgnoredCommandEntries::new(&input.config.ignore_command_entries),
2618                script_workspaces,
2619            )
2620        })
2621        .collect();
2622    let mut skipped_entries = rustc_hash::FxHashMap::default();
2623    entry_points.extend_runtime(root_discovery.entries);
2624    entry_points.extend_support(root_discovery.support_entries);
2625    for (path, count) in root_discovery.skipped_entries {
2626        *skipped_entries.entry(path).or_insert(0) += count;
2627    }
2628    let mut ws_entries = Vec::new();
2629    let mut ws_support_entries = Vec::new();
2630    for workspace in workspace_discovery {
2631        ws_entries.extend(workspace.entries);
2632        ws_support_entries.extend(workspace.support_entries);
2633        for (path, count) in workspace.skipped_entries {
2634            *skipped_entries.entry(path).or_insert(0) += count;
2635        }
2636    }
2637    discover::warn_skipped_entry_summary(&skipped_entries);
2638    entry_points.extend_runtime(ws_entries);
2639    entry_points.extend_support(ws_support_entries);
2640    spans.workspaces_ms = split_ms(&mut mark);
2641
2642    let plugin_entries = discover::discover_plugin_entry_point_sets_timed(
2643        input.plugin_result,
2644        input.config,
2645        input.files,
2646    );
2647    spans.plugin_glob_build_ms = plugin_entries.build_ms;
2648    spans.plugin_glob_match_ms = plugin_entries.match_ms;
2649    entry_points.extend(plugin_entries.entries);
2650    spans.plugins_ms = split_ms(&mut mark);
2651
2652    // Dockerfile, Procfile, and fly.toml commands resolve script calls such as
2653    // `npm run lint -- src/a.ts` against the same catalog as CI commands.
2654    let all_scripts =
2655        collect_all_scripts(input.root_pkg, input.workspace_pkgs, &workspace_packages);
2656    let infra_entries = discover::discover_infrastructure_entry_points(
2657        &input.config.root,
2658        discover::CommandRefContext {
2659            ignored: scripts::IgnoredCommandEntries::new(&input.config.ignore_command_entries),
2660            scripts: &all_scripts,
2661        },
2662    );
2663    entry_points.extend_runtime(infra_entries);
2664    spans.infrastructure_ms = split_ms(&mut mark);
2665
2666    if !input.config.dynamically_loaded.is_empty() {
2667        let dynamic_entries =
2668            discover::discover_dynamically_loaded_entry_points(input.config, input.files);
2669        entry_points.extend_runtime(dynamic_entries);
2670    }
2671    spans.dynamic_ms = split_ms(&mut mark);
2672
2673    let deduped = entry_points.dedup();
2674    spans.dedup_ms = split_ms(&mut mark);
2675    (deduped, spans)
2676}
2677
2678/// Elapsed milliseconds since `mark`, resetting `mark` to now.
2679///
2680/// Consecutive calls carve one stage into adjacent spans with no gap between
2681/// them, so the spans sum to the stage they subdivide.
2682fn split_ms(mark: &mut Instant) -> f64 {
2683    let now = Instant::now();
2684    let elapsed = now.duration_since(*mark).as_secs_f64() * 1000.0;
2685    *mark = now;
2686    elapsed
2687}
2688
2689/// Summarize entry points by source category for user-facing output.
2690fn summarize_entry_points(entry_points: &[discover::EntryPoint]) -> results::EntryPointSummary {
2691    let mut counts: rustc_hash::FxHashMap<String, usize> = rustc_hash::FxHashMap::default();
2692    for ep in entry_points {
2693        let category = match &ep.source {
2694            discover::EntryPointSource::PackageJsonMain
2695            | discover::EntryPointSource::PackageJsonModule
2696            | discover::EntryPointSource::PackageJsonExports
2697            | discover::EntryPointSource::PackageJsonBin
2698            | discover::EntryPointSource::PackageJsonScript => "package.json",
2699            discover::EntryPointSource::Plugin { .. } => "plugin",
2700            discover::EntryPointSource::TestFile => "test file",
2701            discover::EntryPointSource::DefaultIndex => "default index",
2702            discover::EntryPointSource::ManualEntry => "manual entry",
2703            discover::EntryPointSource::InfrastructureConfig => "config",
2704            discover::EntryPointSource::DynamicallyLoaded => "dynamically loaded",
2705        };
2706        *counts.entry(category.to_string()).or_insert(0) += 1;
2707    }
2708    let mut by_source: Vec<(String, usize)> = counts.into_iter().collect();
2709    by_source.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
2710    results::EntryPointSummary {
2711        total: entry_points.len(),
2712        by_source,
2713    }
2714}
2715
2716fn append_package_file_asset_patterns(
2717    result: &mut plugins::AggregatedPluginResult,
2718    prefix: &str,
2719    pkg: &PackageJson,
2720) {
2721    let prefix = prefix.trim_matches('/');
2722    for pattern in package_assets::scaffold_template_asset_patterns(pkg) {
2723        let pattern = if prefix.is_empty() {
2724            pattern
2725        } else {
2726            format!("{prefix}/{pattern}")
2727        };
2728        result
2729            .discovered_always_used
2730            .push((pattern, package_assets::PACKAGE_FILES_SOURCE.to_string()));
2731    }
2732}
2733
2734fn append_workspace_package_file_asset_patterns(
2735    result: &mut plugins::AggregatedPluginResult,
2736    config: &ResolvedConfig,
2737    workspace_pkgs: &[LoadedWorkspacePackage],
2738) {
2739    for (ws, ws_pkg) in workspace_pkgs {
2740        let ws_prefix = ws
2741            .root
2742            .strip_prefix(&config.root)
2743            .unwrap_or(&ws.root)
2744            .to_string_lossy()
2745            .replace('\\', "/");
2746        append_package_file_asset_patterns(result, &ws_prefix, ws_pkg);
2747    }
2748}
2749
2750/// Run plugins for root project and all workspace packages.
2751fn run_plugins(
2752    config: &ResolvedConfig,
2753    files: &[discover::DiscoveredFile],
2754    workspaces: &[fallow_config::WorkspaceInfo],
2755    root_pkg: Option<&PackageJson>,
2756    workspace_pkgs: &[LoadedWorkspacePackage],
2757    config_candidates: &[std::path::PathBuf],
2758) -> Result<plugins::AggregatedPluginResult, FallowError> {
2759    let registry = plugins::PluginRegistry::new(config.external_plugins.clone());
2760    let file_paths: Vec<std::path::PathBuf> = files.iter().map(|f| f.path.clone()).collect();
2761
2762    // The non-production config-discovery fast path: resolve plugin config
2763    // patterns against the files the discovery walk already collected (source
2764    // files unioned with non-source config candidates) instead of re-walking the
2765    // filesystem. Production keeps the filesystem path (no candidates captured).
2766    let candidate_index = (!config.production).then(|| {
2767        plugins::registry::ConfigCandidateIndex::build(
2768            file_paths
2769                .iter()
2770                .map(std::path::PathBuf::as_path)
2771                .chain(config_candidates.iter().map(std::path::PathBuf::as_path)),
2772        )
2773    });
2774
2775    let mut result = run_root_plugins(
2776        &registry,
2777        config,
2778        root_pkg,
2779        &file_paths,
2780        candidate_index.as_ref(),
2781    )?;
2782
2783    if workspaces.is_empty() {
2784        share_auto_imports_across_layers(&mut result, config, workspaces);
2785        gate_auto_import_entry_patterns(&mut result, config, workspaces);
2786        record_plugin_config_diagnostics(&result, &config.root);
2787        return Ok(result);
2788    }
2789
2790    append_workspace_package_file_asset_patterns(&mut result, config, workspace_pkgs);
2791
2792    let ws_results = run_workspace_plugins(
2793        &registry,
2794        config,
2795        workspace_pkgs,
2796        &file_paths,
2797        &result.active_plugins,
2798        candidate_index.as_ref(),
2799    );
2800    merge_workspace_plugin_results(&mut result, ws_results)?;
2801
2802    share_auto_imports_across_layers(&mut result, config, workspaces);
2803    gate_auto_import_entry_patterns(&mut result, config, workspaces);
2804    record_plugin_config_diagnostics(&result, &config.root);
2805
2806    Ok(result)
2807}
2808
2809/// Publish the plugin stage's advisories: one registry write per analysis, after
2810/// the workspace merge and the auto-import gate, which is the single point where
2811/// every plugin result has converged on the project root.
2812///
2813/// Always called, including with nothing to publish, because the write REPLACES
2814/// the previous run's set: a config the user fixed drops out on the next run
2815/// rather than persisting through a watch-mode rerun or a long-lived session.
2816///
2817/// Plugin config parsing is not cached (each analysis re-reads every config file
2818/// from disk and feeds only the plugin config hash), so a warm graph cache
2819/// carries these entries exactly like a cold one.
2820fn record_plugin_config_diagnostics(result: &plugins::AggregatedPluginResult, root: &Path) {
2821    let diagnostics = result
2822        .config_diagnostics
2823        .iter()
2824        .cloned()
2825        .map(|diagnostic| diagnostic.into_workspace_diagnostic(root))
2826        .collect();
2827    let _ = fallow_config::record_plugin_config_diagnostics(root, diagnostics);
2828}
2829
2830type WorkspacePluginResult = Result<
2831    (plugins::AggregatedPluginResult, String),
2832    Vec<plugins::registry::PluginRegexValidationError>,
2833>;
2834
2835/// Run plugins for the root project and apply its package-file asset patterns.
2836fn run_root_plugins(
2837    registry: &plugins::PluginRegistry,
2838    config: &ResolvedConfig,
2839    root_pkg: Option<&PackageJson>,
2840    file_paths: &[std::path::PathBuf],
2841    candidate_index: Option<&plugins::registry::ConfigCandidateIndex>,
2842) -> Result<plugins::AggregatedPluginResult, FallowError> {
2843    let root_config_search_roots = collect_config_search_roots(&config.root, file_paths);
2844    let root_config_search_root_refs: Vec<&Path> = root_config_search_roots
2845        .iter()
2846        .map(std::path::PathBuf::as_path)
2847        .collect();
2848
2849    let mut result = if let Some(pkg) = root_pkg {
2850        registry
2851            .try_run_with_search_roots(
2852                pkg,
2853                &config.root,
2854                file_paths,
2855                &root_config_search_root_refs,
2856                config.production,
2857                candidate_index,
2858            )
2859            .map_err(|errors| {
2860                FallowError::config(plugins::registry::format_plugin_regex_errors(&errors))
2861            })?
2862    } else {
2863        plugins::AggregatedPluginResult::default()
2864    };
2865    if let Some(pkg) = root_pkg {
2866        append_package_file_asset_patterns(&mut result, "", pkg);
2867    }
2868    Ok(result)
2869}
2870
2871/// Run plugins for every workspace package in parallel, returning per-workspace
2872/// results (or regex errors) for the caller to merge.
2873fn run_workspace_plugins(
2874    registry: &plugins::PluginRegistry,
2875    config: &ResolvedConfig,
2876    workspace_pkgs: &[LoadedWorkspacePackage],
2877    file_paths: &[std::path::PathBuf],
2878    root_active_plugins: &[String],
2879    candidate_index: Option<&plugins::registry::ConfigCandidateIndex>,
2880) -> Vec<WorkspacePluginResult> {
2881    let root_active_plugins: rustc_hash::FxHashSet<&str> =
2882        root_active_plugins.iter().map(String::as_str).collect();
2883
2884    let precompiled_matchers = registry.precompile_config_matchers();
2885    let workspace_relative_files = bucket_files_by_workspace(workspace_pkgs, file_paths);
2886
2887    workspace_pkgs
2888        .par_iter()
2889        .zip(workspace_relative_files.par_iter())
2890        .filter_map(|((ws, ws_pkg), relative_files)| {
2891            let ws_result =
2892                match registry.try_run_workspace_fast(&plugins::registry::WorkspacePluginRunInput {
2893                    pkg: ws_pkg,
2894                    root: &ws.root,
2895                    project_root: &config.root,
2896                    precompiled_config_matchers: &precompiled_matchers,
2897                    relative_files,
2898                    skip_config_plugins: &root_active_plugins,
2899                    production_mode: config.production,
2900                    candidate_index,
2901                }) {
2902                    Ok(result) => result,
2903                    Err(errors) => return Some(Err(errors)),
2904                };
2905            if ws_result.active_plugins.is_empty() {
2906                return None;
2907            }
2908            Some(Ok((ws_result, workspace_prefix(&config.root, &ws.root))))
2909        })
2910        .collect::<Vec<_>>()
2911}
2912
2913/// Merge per-workspace plugin results into the root result, surfacing any
2914/// accumulated regex errors as a single config error.
2915fn merge_workspace_plugin_results(
2916    result: &mut plugins::AggregatedPluginResult,
2917    ws_results: Vec<WorkspacePluginResult>,
2918) -> Result<(), FallowError> {
2919    let mut regex_errors = Vec::new();
2920    for ws_result in ws_results {
2921        match ws_result {
2922            Ok((mut ws_result, ws_prefix)) => {
2923                ws_result.apply_workspace_prefix(&ws_prefix);
2924                ws_result.config_patterns.clear();
2925                ws_result.script_used_packages.clear();
2926                result.merge_into(ws_result);
2927            }
2928            Err(mut errors) => regex_errors.append(&mut errors),
2929        }
2930    }
2931    if !regex_errors.is_empty() {
2932        return Err(FallowError::config(
2933            plugins::registry::format_plugin_regex_errors(&regex_errors),
2934        ));
2935    }
2936    Ok(())
2937}
2938
2939/// The project-relative prefix of a workspace root, empty for the project root
2940/// itself. A root outside the project tree keeps its own path, which is also the
2941/// prefix its patterns carry.
2942fn workspace_prefix(root: &Path, workspace_root: &Path) -> String {
2943    workspace_root
2944        .strip_prefix(root)
2945        .unwrap_or(workspace_root)
2946        .to_string_lossy()
2947        .into_owned()
2948}
2949
2950/// Make the auto-imports of a Nuxt app and of each layer it extends visible to
2951/// each other, for the rules of every plugin.
2952///
2953/// Each plugin run scopes its rules to its own root, and a local layer inside
2954/// that root is covered by it. A layer outside the root is a root of its own:
2955/// one that the app names by a relative path (`extends: ['../ui']`), or a
2956/// workspace that it names by its package name (`extends: ['@acme/ui']`).
2957///
2958/// Nuxt merges an app and its layers into one namespace. A rule of a root is
2959/// therefore visible to the layers the root reaches down through `extends`
2960/// (a layer layout renders a component that the app overrides) and to the
2961/// apps that reach the root (the app uses the components and stores of the
2962/// layer). The scope follows one direction per path: it never goes up from a
2963/// layer to a second app that extends the same layer, because the two apps
2964/// do not share names. See issue #2752.
2965fn share_auto_imports_across_layers(
2966    result: &mut plugins::AggregatedPluginResult,
2967    config: &ResolvedConfig,
2968    workspaces: &[fallow_config::WorkspaceInfo],
2969) {
2970    if result.auto_imports.is_empty() || !result.active_plugins.iter().any(|name| name == "nuxt") {
2971        return;
2972    }
2973    let links = layer_links(config, workspaces);
2974    if links.is_empty() {
2975        return;
2976    }
2977    let mut related: rustc_hash::FxHashMap<PathBuf, Vec<PathBuf>> =
2978        rustc_hash::FxHashMap::default();
2979    for rule in &mut result.auto_imports {
2980        let declared = rule.scope.clone();
2981        for root in &declared {
2982            let roots = related.entry(root.clone()).or_insert_with(|| {
2983                let mut roots = reachable_roots(root, &links, |(app, layer)| (app, layer));
2984                roots.extend(reachable_roots(root, &links, |(app, layer)| (layer, app)));
2985                roots
2986            });
2987            for extra in roots.iter() {
2988                if !rule.scope.contains(extra) {
2989                    rule.scope.push(extra.clone());
2990                }
2991            }
2992        }
2993    }
2994}
2995
2996/// The roots that `start` reaches through `links`, following each link from
2997/// the first root that `direction` returns to the second. `start` itself is
2998/// not part of the result.
2999fn reachable_roots<'a>(
3000    start: &Path,
3001    links: &'a [(PathBuf, PathBuf)],
3002    direction: impl Fn(&'a (PathBuf, PathBuf)) -> (&'a PathBuf, &'a PathBuf),
3003) -> Vec<PathBuf> {
3004    let mut found: Vec<PathBuf> = Vec::new();
3005    let mut pending: Vec<&Path> = vec![start];
3006    while let Some(current) = pending.pop() {
3007        for link in links {
3008            let (from, to) = direction(link);
3009            if from.as_path() == current && to.as_path() != start && !found.contains(to) {
3010                found.push(to.clone());
3011                pending.push(to.as_path());
3012            }
3013        }
3014    }
3015    found
3016}
3017
3018/// The `(app root, layer root)` pairs of every Nuxt layer outside the app
3019/// root: a relative `extends` path outside the root, and a workspace named by
3020/// its package name.
3021fn layer_links(
3022    config: &ResolvedConfig,
3023    workspaces: &[fallow_config::WorkspaceInfo],
3024) -> Vec<(PathBuf, PathBuf)> {
3025    let roots_by_name: rustc_hash::FxHashMap<&str, &Path> = workspaces
3026        .iter()
3027        .map(|ws| (ws.name.as_str(), ws.root.as_path()))
3028        .collect();
3029    let app_roots =
3030        std::iter::once(config.root.as_path()).chain(workspaces.iter().map(|ws| ws.root.as_path()));
3031    let mut links: Vec<(PathBuf, PathBuf)> = Vec::new();
3032    for app in app_roots {
3033        let package_layers = plugins::nuxt::package_layer_names(app)
3034            .into_iter()
3035            .filter_map(|name| {
3036                roots_by_name
3037                    .get(name.as_str())
3038                    .map(|root| root.to_path_buf())
3039            });
3040        for layer in plugins::nuxt::outside_layer_roots(app)
3041            .into_iter()
3042            .chain(package_layers)
3043        {
3044            let link = (app.to_path_buf(), layer);
3045            if link.0 != link.1 && !links.contains(&link) {
3046                links.push(link);
3047            }
3048        }
3049    }
3050    links
3051}
3052
3053/// When `autoImports` is enabled, drop the modeled Nuxt convention entry
3054/// patterns so genuinely-unreferenced convention files are reported as
3055/// `unused-file`. Component and script fallbacks are classified separately
3056/// because `components:` and `imports:` settings affect different convention
3057/// surfaces. A surface whose settings are not modeled keeps its patterns; a
3058/// config that statically proves the surface scans no more than the modeled
3059/// defaults is treated like the default and loses them.
3060///
3061/// Each root is classified on its own: the project root plus every workspace
3062/// root, and a pattern is judged by the config of the root whose prefix it
3063/// carries. One custom `nuxt.config` in a monorepo therefore no longer keeps
3064/// every other app's patterns. See issue #2737.
3065///
3066/// A surface that KEPT its patterns records one advisory per root and surface,
3067/// because the user enabled `autoImports` and did not get the findings it
3068/// promises on that surface, and nothing else said so. Only a surface whose
3069/// patterns were actually retained is recorded: a root whose `nuxt.config` fallow
3070/// models has nothing to report. See issue #2736.
3071fn gate_auto_import_entry_patterns(
3072    result: &mut plugins::AggregatedPluginResult,
3073    config: &ResolvedConfig,
3074    workspaces: &[fallow_config::WorkspaceInfo],
3075) {
3076    if !config.auto_imports {
3077        return;
3078    }
3079    if !result.active_plugins.iter().any(|name| name == "nuxt") {
3080        return;
3081    }
3082    let root_settings = plugins::nuxt::auto_import_settings(&config.root);
3083    let workspace_settings: Vec<_> = workspaces
3084        .iter()
3085        .map(|ws| {
3086            (
3087                workspace_prefix(&config.root, &ws.root),
3088                plugins::nuxt::auto_import_settings(&ws.root),
3089            )
3090        })
3091        .collect();
3092    let mut retained: Vec<plugins::PluginConfigDiagnostic> = Vec::new();
3093    result.entry_patterns.retain(|(rule, plugin)| {
3094        if plugin != "nuxt" {
3095            return true;
3096        }
3097        let setting =
3098            settings_for_entry_pattern(&root_settings, &workspace_settings, &rule.pattern);
3099        if plugins::nuxt::is_component_entry_pattern(&rule.pattern) {
3100            if !setting.components.is_custom() {
3101                return false;
3102            }
3103            record_retained_auto_import_surface(
3104                &mut retained,
3105                &setting.components_origin,
3106                "components",
3107            );
3108            return true;
3109        }
3110        if plugins::nuxt::is_script_auto_import_entry_pattern(&rule.pattern) {
3111            if !setting.scripts.is_custom() {
3112                return false;
3113            }
3114            record_retained_auto_import_surface(&mut retained, &setting.scripts_origin, "imports");
3115            return true;
3116        }
3117        true
3118    });
3119    result.config_diagnostics.extend(retained);
3120}
3121
3122/// The reason token for a surface that kept its patterns: a config file with a
3123/// property this reader cannot resolve statically needs the property fixed
3124/// before any surface in it can be classified, so it is named separately from a
3125/// surface whose own value is the thing fallow does not model.
3126const AUTO_IMPORT_PROPERTY_UNREADABLE: &str = "config-property-unreadable";
3127const AUTO_IMPORT_KEY_NOT_MODELED: &str = "key-effect-not-modeled";
3128
3129/// Record one advisory per `nuxt.config` and surface, however many patterns that
3130/// surface kept.
3131fn record_retained_auto_import_surface(
3132    retained: &mut Vec<plugins::PluginConfigDiagnostic>,
3133    origin: &plugins::nuxt::SurfaceOrigin,
3134    key: &str,
3135) {
3136    let Some(config_path) = origin.config_path.as_deref() else {
3137        return;
3138    };
3139    let reason = if origin.unreadable_property {
3140        AUTO_IMPORT_PROPERTY_UNREADABLE
3141    } else {
3142        AUTO_IMPORT_KEY_NOT_MODELED
3143    };
3144    let diagnostic = plugins::PluginConfigDiagnostic::not_modeled(config_path, "nuxt", key, reason);
3145    if !retained.contains(&diagnostic) {
3146        retained.push(diagnostic);
3147    }
3148}
3149
3150/// Pick the settings of the root that owns an entry pattern: the workspace with
3151/// the longest matching prefix, on a `{prefix}/` boundary so `packages/web` does
3152/// not capture `packages/web-admin`. A pattern under no workspace prefix, such as
3153/// the project root's own `app/components/**`, is the project root's own.
3154fn settings_for_entry_pattern<'a>(
3155    root: &'a plugins::nuxt::AutoImportSettings,
3156    workspaces: &'a [(String, plugins::nuxt::AutoImportSettings)],
3157    pattern: &str,
3158) -> &'a plugins::nuxt::AutoImportSettings {
3159    workspaces
3160        .iter()
3161        .filter(|(prefix, _)| {
3162            !prefix.is_empty()
3163                && pattern
3164                    .strip_prefix(prefix.as_str())
3165                    .is_some_and(|rest| rest.starts_with('/'))
3166        })
3167        .max_by_key(|(prefix, _)| prefix.len())
3168        .map_or(root, |(_, setting)| setting)
3169}
3170
3171fn bucket_files_by_workspace(
3172    workspace_pkgs: &[LoadedWorkspacePackage],
3173    file_paths: &[std::path::PathBuf],
3174) -> Vec<Vec<(std::path::PathBuf, String)>> {
3175    let workspace_roots: Vec<_> = workspace_pkgs
3176        .iter()
3177        .map(|(workspace, _)| workspace.root.as_path())
3178        .collect();
3179    bucket_files_by_workspace_roots(&workspace_roots, file_paths)
3180}
3181
3182fn bucket_files_by_workspace_roots(
3183    workspace_roots: &[&Path],
3184    file_paths: &[std::path::PathBuf],
3185) -> Vec<Vec<(std::path::PathBuf, String)>> {
3186    use rayon::prelude::*;
3187
3188    // A file may match nested or duplicate workspace roots. Keep the original
3189    // first-declaration-wins contract by storing the first index for each root
3190    // and selecting the lowest index among the file's matching ancestors.
3191    let mut workspace_by_root: rustc_hash::FxHashMap<&Path, usize> =
3192        rustc_hash::FxHashMap::default();
3193    for (idx, root) in workspace_roots.iter().enumerate() {
3194        workspace_by_root.entry(root).or_insert(idx);
3195    }
3196
3197    let assignments: Vec<Option<(usize, std::path::PathBuf, String)>> = file_paths
3198        .par_iter()
3199        .map(|file_path| {
3200            let idx = file_path
3201                .ancestors()
3202                .filter_map(|ancestor| workspace_by_root.get(ancestor).copied())
3203                .min()?;
3204            let relative = file_path.strip_prefix(workspace_roots[idx]).ok()?;
3205            Some((
3206                idx,
3207                file_path.clone(),
3208                relative.to_string_lossy().into_owned(),
3209            ))
3210        })
3211        .collect();
3212
3213    let mut buckets = vec![Vec::new(); workspace_roots.len()];
3214    for (idx, file_path, relative) in assignments.into_iter().flatten() {
3215        buckets[idx].push((file_path, relative));
3216    }
3217
3218    buckets
3219}
3220
3221/// Benchmark hook for workspace file assignment. This is not a supported API.
3222#[doc(hidden)]
3223pub fn benchmark_bucket_files_by_workspace(
3224    workspace_roots: &[std::path::PathBuf],
3225    file_paths: &[std::path::PathBuf],
3226) -> Vec<Vec<(std::path::PathBuf, String)>> {
3227    let workspace_roots: Vec<_> = workspace_roots
3228        .iter()
3229        .map(std::path::PathBuf::as_path)
3230        .collect();
3231    bucket_files_by_workspace_roots(&workspace_roots, file_paths)
3232}
3233
3234fn collect_config_search_roots(
3235    root: &Path,
3236    file_paths: &[std::path::PathBuf],
3237) -> Vec<std::path::PathBuf> {
3238    let mut roots: rustc_hash::FxHashSet<std::path::PathBuf> = rustc_hash::FxHashSet::default();
3239    roots.insert(root.to_path_buf());
3240
3241    for file_path in file_paths {
3242        let mut current = file_path.parent();
3243        while let Some(dir) = current {
3244            if !dir.starts_with(root) {
3245                break;
3246            }
3247            roots.insert(dir.to_path_buf());
3248            if dir == root {
3249                break;
3250            }
3251            current = dir.parent();
3252        }
3253    }
3254
3255    let mut roots_vec: Vec<_> = roots.into_iter().collect();
3256    roots_vec.sort();
3257    roots_vec
3258}
3259
3260/// Resolve the analysis config for a project, mirroring the CLI's `--config`
3261/// behavior when `config_path` is provided.
3262///
3263/// # Errors
3264///
3265/// Returns an error when an explicit config cannot be loaded or automatic
3266/// config discovery finds an invalid config.
3267fn config_for_project(
3268    root: &Path,
3269    config_path: Option<&Path>,
3270) -> Result<(ResolvedConfig, Option<std::path::PathBuf>), FallowError> {
3271    let user_config = if let Some(path) = config_path {
3272        Some((
3273            fallow_config::FallowConfig::load(path)
3274                .map_err(|e| FallowError::config(format!("{e:#}")))?,
3275            path.to_path_buf(),
3276        ))
3277    } else {
3278        fallow_config::FallowConfig::find_and_load(root).map_err(FallowError::config)?
3279    };
3280
3281    let config = match user_config {
3282        Some((config, path)) => resolve_user_config(config, path, root)?,
3283        None => (
3284            fallow_config::FallowConfig::default().resolve(
3285                root.to_path_buf(),
3286                fallow_config::OutputFormat::Human,
3287                num_cpus(),
3288                false,
3289                true,
3290                None,
3291            ),
3292            None,
3293        ),
3294    };
3295
3296    Ok(config)
3297}
3298
3299/// Flatten the dead-code production flag, validate boundaries and rule packs,
3300/// then resolve a user-supplied config for LSP/programmatic callers.
3301fn resolve_user_config(
3302    mut config: fallow_config::FallowConfig,
3303    path: std::path::PathBuf,
3304    root: &Path,
3305) -> Result<(ResolvedConfig, Option<std::path::PathBuf>), FallowError> {
3306    let dead_code_production = config
3307        .production
3308        .for_analysis(fallow_config::ProductionAnalysis::DeadCode);
3309    config.production = dead_code_production.into();
3310    config
3311        .validate_resolved_boundaries(root)
3312        .map_err(|errors| {
3313            let joined = errors
3314                .iter()
3315                .map(ToString::to_string)
3316                .collect::<Vec<_>>()
3317                .join("\n  - ");
3318            FallowError::config(format!("invalid boundary configuration:\n  - {joined}"))
3319        })?;
3320    let packs = fallow_config::load_rule_packs(root, &config.rule_packs).map_err(|errors| {
3321        let joined = errors
3322            .iter()
3323            .map(ToString::to_string)
3324            .collect::<Vec<_>>()
3325            .join("\n  - ");
3326        FallowError::config(format!("invalid rule pack:\n  - {joined}"))
3327    })?;
3328    let zone_errors = fallow_config::validate_rule_pack_zones(
3329        root,
3330        &config.boundaries,
3331        &config.rule_packs,
3332        &packs,
3333    );
3334    if !zone_errors.is_empty() {
3335        let joined = zone_errors
3336            .iter()
3337            .map(ToString::to_string)
3338            .collect::<Vec<_>>()
3339            .join("\n  - ");
3340        return Err(FallowError::config(format!(
3341            "invalid rule pack:\n  - {joined}"
3342        )));
3343    }
3344    Ok((
3345        config.resolve(
3346            root.to_path_buf(),
3347            fallow_config::OutputFormat::Human,
3348            num_cpus(),
3349            false,
3350            true, // quiet: LSP/programmatic callers don't need progress bars
3351            None, // LSP/programmatic embedders use the default cache cap
3352        ),
3353        Some(path),
3354    ))
3355}
3356
3357/// Create a default config for a project root.
3358///
3359/// `analyze_project` is the dead-code entry point used by the LSP and other
3360/// programmatic embedders. When the loaded config uses the per-analysis
3361/// production form (`production: { deadCode: true, ... }`), the production
3362/// flag must be flattened to the dead-code analysis here. Otherwise
3363/// `ResolvedConfig::resolve` calls `.global()` which returns false for the
3364/// per-analysis variant and the production-mode rule overrides
3365/// (`unused_dev_dependencies: off`, etc.) plus `resolved.production = true`
3366/// are silently dropped.
3367#[cfg_attr(
3368    not(test),
3369    allow(
3370        dead_code,
3371        reason = "config resolution fallback is exercised by session tests"
3372    )
3373)]
3374pub(crate) fn default_config(root: &Path) -> ResolvedConfig {
3375    config_for_project(root, None).map_or_else(
3376        |_| {
3377            fallow_config::FallowConfig::default().resolve(
3378                root.to_path_buf(),
3379                fallow_config::OutputFormat::Human,
3380                num_cpus(),
3381                false,
3382                true,
3383                None,
3384            )
3385        },
3386        |(config, _)| config,
3387    )
3388}
3389
3390fn num_cpus() -> usize {
3391    std::thread::available_parallelism().map_or(4, std::num::NonZeroUsize::get)
3392}
3393
3394#[cfg(test)]
3395mod tests {
3396    use super::{
3397        AnalysisSession, bucket_files_by_workspace, bucket_files_by_workspace_roots,
3398        collect_config_search_roots, credit_workspace_package_usage, default_config,
3399        format_undeclared_workspace_warning, gate_auto_import_entry_patterns,
3400        parse_analysis_modules, plugin_config_hash, resolver_options_hash,
3401        settings_for_entry_pattern, warn_undeclared_workspaces, workspace_prefix,
3402    };
3403    use std::path::{Path, PathBuf};
3404    use std::time::Instant;
3405
3406    use fallow_config::{
3407        AutoImportKind, AutoImportRule, WorkspaceDiagnostic, WorkspaceDiagnosticKind,
3408    };
3409    use fallow_types::discover::{DiscoveredFile, FileId};
3410    use fallow_types::extract::{ImportInfo, ImportedName};
3411
3412    fn plugin_result() -> crate::plugins::AggregatedPluginResult {
3413        let mut result = crate::plugins::AggregatedPluginResult::default();
3414        result.active_plugins.push("nuxt".to_string());
3415        result
3416            .path_aliases
3417            .push(("@/".to_string(), "src/".to_string()));
3418        result
3419    }
3420
3421    fn auto_import_settings(
3422        components: crate::plugins::nuxt::AutoImportSetting,
3423    ) -> crate::plugins::nuxt::AutoImportSettings {
3424        crate::plugins::nuxt::AutoImportSettings {
3425            components,
3426            scripts: crate::plugins::nuxt::AutoImportSetting::Default,
3427            components_origin: crate::plugins::nuxt::SurfaceOrigin {
3428                config_path: Some(std::path::PathBuf::from("nuxt.config.ts")),
3429                unreadable_property: false,
3430            },
3431            scripts_origin: crate::plugins::nuxt::SurfaceOrigin::default(),
3432        }
3433    }
3434
3435    #[test]
3436    fn entry_pattern_settings_prefer_the_longest_workspace_prefix() {
3437        let root = auto_import_settings(crate::plugins::nuxt::AutoImportSetting::Default);
3438        let workspaces = vec![
3439            (
3440                "packages/web".to_string(),
3441                auto_import_settings(crate::plugins::nuxt::AutoImportSetting::Custom),
3442            ),
3443            (
3444                "packages/web-admin".to_string(),
3445                auto_import_settings(crate::plugins::nuxt::AutoImportSetting::Disabled),
3446            ),
3447        ];
3448
3449        let admin = settings_for_entry_pattern(
3450            &root,
3451            &workspaces,
3452            "packages/web-admin/components/**/*.{vue,ts,tsx,js,jsx}",
3453        );
3454        assert_eq!(
3455            admin.components,
3456            crate::plugins::nuxt::AutoImportSetting::Disabled,
3457            "a sibling whose name starts with another workspace name is its own"
3458        );
3459
3460        let web = settings_for_entry_pattern(
3461            &root,
3462            &workspaces,
3463            "packages/web/components/**/*.{vue,ts,tsx,js,jsx}",
3464        );
3465        assert_eq!(
3466            web.components,
3467            crate::plugins::nuxt::AutoImportSetting::Custom
3468        );
3469    }
3470
3471    #[test]
3472    fn entry_pattern_without_a_workspace_prefix_belongs_to_the_project_root() {
3473        let root = auto_import_settings(crate::plugins::nuxt::AutoImportSetting::Custom);
3474        let workspaces = vec![(
3475            "packages/web".to_string(),
3476            auto_import_settings(crate::plugins::nuxt::AutoImportSetting::Default),
3477        )];
3478
3479        let setting = settings_for_entry_pattern(
3480            &root,
3481            &workspaces,
3482            "app/components/**/*.{vue,ts,tsx,js,jsx}",
3483        );
3484        assert_eq!(
3485            setting.components,
3486            crate::plugins::nuxt::AutoImportSetting::Custom
3487        );
3488    }
3489
3490    /// Build a project root holding one `nuxt.config.ts` and a plugin result
3491    /// carrying the two gated convention entry patterns.
3492    fn nuxt_gate_fixture(
3493        config_source: &str,
3494    ) -> (tempfile::TempDir, crate::plugins::AggregatedPluginResult) {
3495        let dir = tempfile::tempdir().expect("temp project");
3496        std::fs::write(dir.path().join("nuxt.config.ts"), config_source).expect("nuxt config");
3497        let mut result = crate::plugins::AggregatedPluginResult::default();
3498        result.active_plugins.push("nuxt".to_string());
3499        for pattern in [
3500            "app/components/**/*.{vue,ts,tsx,js,jsx}",
3501            "app/composables/*.{ts,tsx,js,jsx,mts,cts,mjs,cjs}",
3502        ] {
3503            result.entry_patterns.push((
3504                crate::plugins::PathRule::new(pattern.to_string()),
3505                "nuxt".to_string(),
3506            ));
3507        }
3508        (dir, result)
3509    }
3510
3511    fn gate(root: &Path, result: &mut crate::plugins::AggregatedPluginResult) {
3512        let config = fallow_config::FallowConfig {
3513            auto_imports: true,
3514            ..fallow_config::FallowConfig::default()
3515        };
3516        let resolved = config.resolve(
3517            root.to_path_buf(),
3518            fallow_config::OutputFormat::Json,
3519            1,
3520            false,
3521            true,
3522            None,
3523        );
3524        assert!(resolved.auto_imports, "the gate only runs when opted in");
3525        gate_auto_import_entry_patterns(result, &resolved, &[]);
3526    }
3527
3528    /// A surface that kept its patterns records one advisory naming the config
3529    /// file, the surface and why, because the user asked for the findings that
3530    /// surface no longer produces (issue #2736).
3531    #[test]
3532    fn a_retained_auto_import_surface_records_one_advisory_per_surface() {
3533        let (project, mut result) =
3534            nuxt_gate_fixture("export default { components: { dirs: ['~/ui'] } };\n");
3535        gate(project.path(), &mut result);
3536
3537        let recorded: Vec<(&str, &str, &str)> = result
3538            .config_diagnostics
3539            .iter()
3540            .map(|diagnostic| {
3541                (
3542                    diagnostic.plugin.as_str(),
3543                    diagnostic.key.as_str(),
3544                    diagnostic.reason.as_str(),
3545                )
3546            })
3547            .collect();
3548        assert_eq!(
3549            recorded,
3550            vec![("nuxt", "components", "key-effect-not-modeled")],
3551            "only the surface that kept its patterns is reported: {:?}",
3552            result.config_diagnostics
3553        );
3554        assert_eq!(
3555            result.config_diagnostics[0].config_path,
3556            project.path().join("nuxt.config.ts")
3557        );
3558        assert_eq!(
3559            result.entry_patterns.len(),
3560            1,
3561            "the modeled surface still loses its patterns: {:?}",
3562            result.entry_patterns
3563        );
3564    }
3565
3566    /// A top-level property this reader cannot resolve stands both surfaces
3567    /// down, and the remedy is the property rather than either surface, so it
3568    /// carries its own reason token.
3569    #[test]
3570    fn an_unreadable_top_level_property_reports_both_surfaces_with_its_own_reason() {
3571        let (project, mut result) =
3572            nuxt_gate_fixture("export default { ...baseConfig, modules: [] };\n");
3573        gate(project.path(), &mut result);
3574
3575        let recorded: Vec<(&str, &str)> = result
3576            .config_diagnostics
3577            .iter()
3578            .map(|diagnostic| (diagnostic.key.as_str(), diagnostic.reason.as_str()))
3579            .collect();
3580        assert_eq!(
3581            recorded,
3582            vec![
3583                ("components", "config-property-unreadable"),
3584                ("imports", "config-property-unreadable"),
3585            ],
3586            "{:?}",
3587            result.config_diagnostics
3588        );
3589        assert_eq!(
3590            result.entry_patterns.len(),
3591            2,
3592            "a spread keeps every gated pattern"
3593        );
3594    }
3595
3596    /// A config fallow models fully loses its patterns and reports nothing, so
3597    /// the advisory fires only where a finding was actually suppressed.
3598    #[test]
3599    fn a_modeled_nuxt_config_records_no_advisory() {
3600        let (project, mut result) = nuxt_gate_fixture("export default { modules: [] };\n");
3601        gate(project.path(), &mut result);
3602        assert!(
3603            result.config_diagnostics.is_empty(),
3604            "{:?}",
3605            result.config_diagnostics
3606        );
3607        assert!(
3608            result.entry_patterns.is_empty(),
3609            "both modeled surfaces lose their patterns: {:?}",
3610            result.entry_patterns
3611        );
3612    }
3613
3614    #[test]
3615    fn a_workspace_outside_the_project_keeps_its_own_prefix() {
3616        let project_root = Path::new("/repo");
3617        let outside = Path::new("/elsewhere/app");
3618        let prefix = workspace_prefix(project_root, outside);
3619        assert_eq!(prefix, "/elsewhere/app");
3620
3621        let root = auto_import_settings(crate::plugins::nuxt::AutoImportSetting::Default);
3622        let workspaces = vec![(
3623            prefix,
3624            auto_import_settings(crate::plugins::nuxt::AutoImportSetting::Custom),
3625        )];
3626        let setting = settings_for_entry_pattern(
3627            &root,
3628            &workspaces,
3629            "/elsewhere/app/components/**/*.{vue,ts,tsx,js,jsx}",
3630        );
3631        assert_eq!(
3632            setting.components,
3633            crate::plugins::nuxt::AutoImportSetting::Custom,
3634            "an out-of-tree workspace is classified on its own config"
3635        );
3636    }
3637
3638    #[test]
3639    fn commonjs_internal_import_credits_workspace_package_usage() {
3640        let workspace = fallow_config::WorkspaceInfo {
3641            root: PathBuf::from("/repo/packages/shared"),
3642            name: "@repo/shared".to_string(),
3643            is_internal_dependency: true,
3644        };
3645        let resolved = vec![crate::resolve::ResolvedModule {
3646            file_id: FileId(0),
3647            resolved_imports: vec![crate::resolve::ResolvedImport {
3648                info: ImportInfo {
3649                    source: "@repo/shared".to_string(),
3650                    imported_name: ImportedName::Namespace,
3651                    local_name: "shared".to_string(),
3652                    is_type_only: false,
3653                    is_type_only_star: false,
3654                    from_style: false,
3655                    span: oxc_span::Span::new(0, 20),
3656                    source_span: oxc_span::Span::new(8, 20),
3657                },
3658                target: crate::resolve::ResolveResult::CommonJsInternalModule(FileId(1)),
3659            }],
3660            ..crate::resolve::ResolvedModule::default()
3661        }];
3662        let mut graph = crate::graph::ModuleGraph::build(&[], &[], &[]);
3663
3664        credit_workspace_package_usage(&mut graph, &resolved, &[workspace]);
3665
3666        assert_eq!(
3667            graph.package_usage.get("@repo/shared"),
3668            Some(&vec![FileId(0)])
3669        );
3670    }
3671
3672    /// Root identity is checked by the manifest. The resolver options hash
3673    /// describes configuration independently of where the project resides.
3674    #[test]
3675    fn graph_cache_resolver_hash_is_independent_of_the_project_root() {
3676        let dir_a = tempfile::tempdir().expect("create temp dir a");
3677        let dir_b = tempfile::tempdir().expect("create temp dir b");
3678        let config_a = session_config(dir_a.path());
3679        let config_b = session_config(dir_b.path());
3680
3681        assert_eq!(
3682            resolver_options_hash(&config_a),
3683            resolver_options_hash(&config_b),
3684            "root identity is handled separately from resolver options"
3685        );
3686    }
3687
3688    /// A changed file set invalidates a graph even when its root and resolver
3689    /// options are unchanged.
3690    #[test]
3691    fn graph_cache_manifest_still_rejects_a_different_file_set() {
3692        let dir_a = tempfile::tempdir().expect("create temp dir a");
3693        let mode = crate::graph_cache::GraphCacheMode::new(1, 2, 3);
3694        let files_a = [crate::discover::DiscoveredFile {
3695            id: crate::discover::FileId(0),
3696            path: dir_a.path().join("src/a.ts"),
3697            size_bytes: 1,
3698        }];
3699        let files_b = [crate::discover::DiscoveredFile {
3700            id: crate::discover::FileId(0),
3701            path: dir_a.path().join("src/b.ts"),
3702            size_bytes: 1,
3703        }];
3704
3705        let manifest_a = crate::graph_cache::GraphCacheManifest::from_discovered_files(
3706            dir_a.path(),
3707            &files_a,
3708            mode,
3709            |_| 7,
3710        );
3711        let manifest_b = crate::graph_cache::GraphCacheManifest::from_discovered_files(
3712            dir_a.path(),
3713            &files_b,
3714            mode,
3715            |_| 7,
3716        );
3717
3718        assert_eq!(
3719            manifest_a.classify_resolution_mismatch(&manifest_b),
3720            Some(fallow_types::cache_rejection::CacheRejection::FileSetChanged)
3721        );
3722    }
3723
3724    #[test]
3725    fn graph_cache_resolver_hash_includes_resolve_conditions() {
3726        let dir = tempfile::tempdir().expect("create temp dir");
3727        let config_a = session_config(dir.path());
3728        let mut config_b = session_config(dir.path());
3729        config_b.resolve.conditions.push("react-server".to_string());
3730
3731        assert_ne!(
3732            resolver_options_hash(&config_a),
3733            resolver_options_hash(&config_b),
3734            "resolve condition changes must invalidate the graph cache"
3735        );
3736    }
3737
3738    #[test]
3739    fn graph_cache_plugin_hash_includes_auto_imports() {
3740        let mut without_auto_import = plugin_result();
3741        let mut with_auto_import = plugin_result();
3742        with_auto_import.auto_imports.push(AutoImportRule::new(
3743            "useCounter".to_string(),
3744            PathBuf::from("/project/composables/useCounter.ts"),
3745            AutoImportKind::Named,
3746        ));
3747
3748        assert_ne!(
3749            plugin_config_hash(&without_auto_import, std::path::Path::new("")),
3750            plugin_config_hash(&with_auto_import, std::path::Path::new("")),
3751            "auto-import edge changes must invalidate the graph cache"
3752        );
3753
3754        without_auto_import.auto_imports.push(AutoImportRule::new(
3755            "useCounter".to_string(),
3756            PathBuf::from("/project/composables/useCounter.ts"),
3757            AutoImportKind::Default,
3758        ));
3759        assert_ne!(
3760            plugin_config_hash(&without_auto_import, std::path::Path::new("")),
3761            plugin_config_hash(&with_auto_import, std::path::Path::new("")),
3762            "auto-import kind changes must invalidate the graph cache"
3763        );
3764
3765        let mut scoped = with_auto_import.auto_imports.clone();
3766        scoped[0].scope = vec![PathBuf::from("/project/packages/a")];
3767        let mut with_scoped_auto_import = plugin_result();
3768        with_scoped_auto_import.auto_imports = scoped;
3769        assert_ne!(
3770            plugin_config_hash(&with_scoped_auto_import, std::path::Path::new("")),
3771            plugin_config_hash(&with_auto_import, std::path::Path::new("")),
3772            "auto-import scope changes must invalidate the graph cache"
3773        );
3774    }
3775
3776    #[test]
3777    fn graph_cache_plugin_hash_includes_jsx_import_sources() {
3778        let rule = fallow_config::JsxImportSourceRule {
3779            source: "./src/jsx".to_string(),
3780            config_dir: PathBuf::from("/project"),
3781            include: vec!["src/**/*.test.tsx".to_string()],
3782        };
3783        let base = plugin_result();
3784        let mut with_rule = plugin_result();
3785        with_rule.jsx_import_sources.push(rule.clone());
3786        assert_ne!(
3787            plugin_config_hash(&base, std::path::Path::new("")),
3788            plugin_config_hash(&with_rule, std::path::Path::new("")),
3789            "JSX import source changes must invalidate the graph cache"
3790        );
3791
3792        let mut other_source = plugin_result();
3793        other_source
3794            .jsx_import_sources
3795            .push(fallow_config::JsxImportSourceRule {
3796                source: "./src/jsx/dom".to_string(),
3797                ..rule
3798            });
3799        assert_ne!(
3800            plugin_config_hash(&with_rule, std::path::Path::new("")),
3801            plugin_config_hash(&other_source, std::path::Path::new("")),
3802            "a changed JSX import source must invalidate the graph cache"
3803        );
3804    }
3805
3806    #[test]
3807    fn graph_cache_plugin_hash_includes_style_and_static_mappings() {
3808        let base = plugin_result();
3809        let mut with_scss = base.clone();
3810        with_scss
3811            .scss_include_paths
3812            .push(PathBuf::from("/project/styles"));
3813        assert_ne!(
3814            plugin_config_hash(&base, std::path::Path::new("")),
3815            plugin_config_hash(&with_scss, std::path::Path::new("")),
3816            "SCSS include path changes must invalidate the graph cache"
3817        );
3818
3819        let mut with_static_dir = base.clone();
3820        with_static_dir
3821            .static_dir_mappings
3822            .push((PathBuf::from("/project/public"), "/".to_string()));
3823        assert_ne!(
3824            plugin_config_hash(&base, std::path::Path::new("")),
3825            plugin_config_hash(&with_static_dir, std::path::Path::new("")),
3826            "static directory mapping changes must invalidate the graph cache"
3827        );
3828    }
3829
3830    fn diag(root: &Path, relative: &str) -> WorkspaceDiagnostic {
3831        WorkspaceDiagnostic::new(
3832            root,
3833            root.join(relative),
3834            WorkspaceDiagnosticKind::UndeclaredWorkspace,
3835        )
3836    }
3837
3838    fn session_config(root: &Path) -> fallow_config::ResolvedConfig {
3839        let mut config = default_config(root);
3840        config.no_cache = true;
3841        config.quiet = true;
3842        config
3843    }
3844
3845    fn write_session_fixture(root: &Path) {
3846        let src = root.join("src");
3847        std::fs::create_dir_all(&src).expect("create src");
3848        std::fs::write(
3849            root.join("package.json"),
3850            r#"{"name":"session-fixture","type":"module"}"#,
3851        )
3852        .expect("write package json");
3853        std::fs::write(
3854            src.join("index.ts"),
3855            "import { used } from './used';\nconsole.log(used);\n",
3856        )
3857        .expect("write index");
3858        std::fs::write(src.join("used.ts"), "export const used = 1;\n").expect("write used");
3859    }
3860
3861    #[test]
3862    fn analysis_session_discovers_project_files() {
3863        let dir = tempfile::tempdir().expect("create temp dir");
3864        write_session_fixture(dir.path());
3865        let config = session_config(dir.path());
3866
3867        let session = AnalysisSession::new(&config).expect("session setup should succeed");
3868
3869        assert!(
3870            session
3871                .files()
3872                .iter()
3873                .any(|file| file.path.ends_with("src/index.ts")),
3874            "session should own discovered project files"
3875        );
3876        assert_eq!(session.workspaces().len(), 0);
3877    }
3878
3879    #[test]
3880    fn direct_core_parse_surfaces_source_read_failure_diagnostic() {
3881        let project = tempfile::tempdir().expect("create project");
3882        let root = project.path();
3883        let paths = ["a.ts", "b.ts", "c.ts"].map(|name| root.join(name));
3884        for (index, path) in paths.iter().enumerate() {
3885            std::fs::write(path, format!("export const value{index} = {index};\n"))
3886                .expect("write source");
3887        }
3888        let files: Vec<DiscoveredFile> = paths
3889            .iter()
3890            .enumerate()
3891            .map(|(index, path)| DiscoveredFile {
3892                id: FileId(u32::try_from(index).expect("test index fits u32")),
3893                path: path.clone(),
3894                size_bytes: std::fs::metadata(path).expect("source metadata").len(),
3895            })
3896            .collect();
3897        std::fs::remove_file(&paths[1]).expect("remove source after discovery");
3898        let config = session_config(root);
3899
3900        let parsed = parse_analysis_modules(&config, &files, false, Instant::now());
3901
3902        assert_eq!(
3903            parsed
3904                .modules
3905                .iter()
3906                .map(|module| module.file_id)
3907                .collect::<Vec<_>>(),
3908            vec![FileId(0), FileId(2)]
3909        );
3910        let diagnostics = fallow_config::workspace_diagnostics_for(root);
3911        let diagnostic = diagnostics
3912            .iter()
3913            .find(|diagnostic| diagnostic.kind.id() == "source-read-failure")
3914            .expect("source read failure diagnostic");
3915        assert_eq!(diagnostic.path, paths[1]);
3916        assert!(matches!(
3917            diagnostic.kind,
3918            WorkspaceDiagnosticKind::SourceReadFailure { .. }
3919        ));
3920    }
3921
3922    #[test]
3923    fn analysis_session_parses_owned_modules() {
3924        let dir = tempfile::tempdir().expect("create temp dir");
3925        write_session_fixture(dir.path());
3926        let config = session_config(dir.path());
3927
3928        let session = AnalysisSession::new(&config).expect("session setup should succeed");
3929        let parsed = session.parse_modules(false);
3930
3931        assert!(
3932            parsed
3933                .modules
3934                .iter()
3935                .any(|module| session.files()[module.file_id.0 as usize]
3936                    .path
3937                    .ends_with("src/index.ts")),
3938            "session parsing should return modules keyed to session files"
3939        );
3940    }
3941
3942    #[test]
3943    fn undeclared_workspace_warning_is_singular_for_one_path() {
3944        let root = Path::new("/repo");
3945        let warning = format_undeclared_workspace_warning(root, &[diag(root, "packages/api")])
3946            .expect("warning should be rendered");
3947
3948        assert_eq!(
3949            warning,
3950            "1 directory with package.json is not declared as a workspace: packages/api. Add that path to package.json workspaces or pnpm-workspace.yaml if it should be analyzed as a workspace."
3951        );
3952    }
3953
3954    #[test]
3955    fn undeclared_workspace_warning_summarizes_many_paths() {
3956        let root = PathBuf::from("/repo");
3957        let diagnostics = [
3958            "examples/a",
3959            "examples/b",
3960            "examples/c",
3961            "examples/d",
3962            "examples/e",
3963            "examples/f",
3964        ]
3965        .into_iter()
3966        .map(|path| diag(&root, path))
3967        .collect::<Vec<_>>();
3968
3969        let warning = format_undeclared_workspace_warning(&root, &diagnostics)
3970            .expect("warning should be rendered");
3971
3972        assert_eq!(
3973            warning,
3974            "6 directories with package.json are not declared as workspaces: examples/a, examples/b, examples/c, examples/d, examples/e (and 1 more). Add those paths to package.json workspaces or pnpm-workspace.yaml if they should be analyzed as workspaces."
3975        );
3976    }
3977
3978    #[test]
3979    fn collect_config_search_roots_includes_file_ancestors_once() {
3980        let root = PathBuf::from("/repo");
3981        let search_roots = collect_config_search_roots(
3982            &root,
3983            &[
3984                root.join("apps/query/src/main.ts"),
3985                root.join("packages/shared/lib/index.ts"),
3986            ],
3987        );
3988
3989        assert_eq!(
3990            search_roots,
3991            vec![
3992                root.clone(),
3993                root.join("apps"),
3994                root.join("apps/query"),
3995                root.join("apps/query/src"),
3996                root.join("packages"),
3997                root.join("packages/shared"),
3998                root.join("packages/shared/lib"),
3999            ]
4000        );
4001    }
4002
4003    #[test]
4004    fn bucket_files_by_workspace_uses_workspace_relative_paths() {
4005        let root = PathBuf::from("/repo");
4006        let ui = fallow_config::WorkspaceInfo {
4007            root: root.join("apps/ui"),
4008            name: "ui".to_string(),
4009            is_internal_dependency: false,
4010        };
4011        let api = fallow_config::WorkspaceInfo {
4012            root: root.join("apps/api"),
4013            name: "api".to_string(),
4014            is_internal_dependency: false,
4015        };
4016        let workspace_pkgs = vec![
4017            (
4018                ui,
4019                fallow_config::PackageJson {
4020                    name: Some("ui".to_string()),
4021                    ..Default::default()
4022                },
4023            ),
4024            (
4025                api,
4026                fallow_config::PackageJson {
4027                    name: Some("api".to_string()),
4028                    ..Default::default()
4029                },
4030            ),
4031        ];
4032        let files = vec![
4033            root.join("apps/ui/vite.config.ts"),
4034            root.join("apps/ui/src/main.ts"),
4035            root.join("apps/api/src/server.ts"),
4036            root.join("tools/build.ts"),
4037        ];
4038
4039        let buckets = bucket_files_by_workspace(&workspace_pkgs, &files);
4040
4041        assert_eq!(
4042            buckets[0],
4043            vec![
4044                (
4045                    root.join("apps/ui/vite.config.ts"),
4046                    "vite.config.ts".to_string()
4047                ),
4048                (root.join("apps/ui/src/main.ts"), "src/main.ts".to_string()),
4049            ]
4050        );
4051        assert_eq!(
4052            buckets[1],
4053            vec![(
4054                root.join("apps/api/src/server.ts"),
4055                "src/server.ts".to_string()
4056            )]
4057        );
4058    }
4059
4060    #[test]
4061    fn workspace_bucketing_preserves_first_declared_match_and_file_order() {
4062        let root = PathBuf::from("/repo");
4063        let parent = root.join("apps");
4064        let child = parent.join("web");
4065        let nested_first = child.join("src/first.ts");
4066        let nested_second = child.join("src/second.ts");
4067        let unmatched = root.join("tools/build.ts");
4068        let files = vec![nested_first.clone(), unmatched, nested_second.clone()];
4069
4070        // The relative path preserves the input path's original separators, which
4071        // are mixed on Windows when the fixture is built via multiple `join` calls
4072        // (`web\src/first.ts`). Normalize separators before comparing so the
4073        // assertion checks bucketing + ordering, not host path formatting.
4074        let normalize = |bucket: &[(PathBuf, String)]| -> Vec<(PathBuf, String)> {
4075            bucket
4076                .iter()
4077                .map(|(path, rel)| (path.clone(), rel.replace('\\', "/")))
4078                .collect()
4079        };
4080
4081        let parent_first = bucket_files_by_workspace_roots(&[&parent, &child, &child], &files);
4082        assert_eq!(
4083            normalize(&parent_first[0]),
4084            vec![
4085                (nested_first.clone(), "web/src/first.ts".to_string()),
4086                (nested_second.clone(), "web/src/second.ts".to_string()),
4087            ]
4088        );
4089        assert!(parent_first[1].is_empty());
4090        assert!(parent_first[2].is_empty());
4091
4092        let child_first = bucket_files_by_workspace_roots(&[&child, &parent], &files);
4093        assert_eq!(
4094            normalize(&child_first[0]),
4095            vec![
4096                (nested_first, "src/first.ts".to_string()),
4097                (nested_second, "src/second.ts".to_string()),
4098            ]
4099        );
4100        assert!(child_first[1].is_empty());
4101    }
4102
4103    #[test]
4104    fn warn_undeclared_workspaces_suppresses_paths_already_flagged_as_malformed() {
4105        let dir = tempfile::tempdir().expect("create temp dir");
4106        let pkg_good = dir.path().join("packages").join("good");
4107        let pkg_bad = dir.path().join("packages").join("bad");
4108        std::fs::create_dir_all(&pkg_good).unwrap();
4109        std::fs::create_dir_all(&pkg_bad).unwrap();
4110        std::fs::write(
4111            dir.path().join("package.json"),
4112            r#"{"workspaces": ["packages/*"]}"#,
4113        )
4114        .unwrap();
4115        std::fs::write(pkg_good.join("package.json"), r#"{"name": "good"}"#).unwrap();
4116        std::fs::write(pkg_bad.join("package.json"), r"{,").unwrap();
4117
4118        let (workspaces, diagnostics) = fallow_config::discover_workspaces_with_diagnostics(
4119            dir.path(),
4120            &fallow_config::IgnorePatternSet::empty(),
4121        )
4122        .expect("root package.json is valid");
4123        assert_eq!(workspaces.len(), 1, "only the valid workspace discovers");
4124        fallow_config::stash_workspace_diagnostics(dir.path(), diagnostics);
4125
4126        warn_undeclared_workspaces(
4127            dir.path(),
4128            &workspaces,
4129            &fallow_config::IgnorePatternSet::empty(),
4130            false,
4131        );
4132
4133        let diagnostics = fallow_config::workspace_diagnostics_for(dir.path());
4134        let mut malformed = 0;
4135        let mut undeclared_for_bad = 0;
4136        for diag in &diagnostics {
4137            if matches!(
4138                diag.kind,
4139                WorkspaceDiagnosticKind::MalformedPackageJson { .. }
4140            ) && diag.path.ends_with("bad")
4141            {
4142                malformed += 1;
4143            }
4144            if matches!(diag.kind, WorkspaceDiagnosticKind::UndeclaredWorkspace)
4145                && diag.path.ends_with("bad")
4146            {
4147                undeclared_for_bad += 1;
4148            }
4149        }
4150        assert_eq!(
4151            malformed, 1,
4152            "expected one MalformedPackageJson for packages/bad: {diagnostics:?}"
4153        );
4154        assert_eq!(
4155            undeclared_for_bad, 0,
4156            "warn_undeclared_workspaces must NOT re-flag a path that already \
4157             carries MalformedPackageJson; got duplicates: {diagnostics:?}"
4158        );
4159    }
4160
4161    /// A same-length save that lands after the parse read the file, and before
4162    /// the run stored the cache, gives the stored module the fingerprint of the
4163    /// new content. A write in the same timestamp tick as the first write gives
4164    /// the same result. The next run must still parse the new content.
4165    #[test]
4166    fn a_rewrite_after_the_parse_read_misses_the_next_run() {
4167        use fallow_types::discover::{DiscoveredFile, FileId};
4168
4169        let project = tempfile::tempdir().expect("create project");
4170        let path = project.path().join("api.ts");
4171        let before = "export const alpha = 1;\n";
4172        let after = "export const bravo = 1;\n";
4173        assert_eq!(before.len(), after.len());
4174        std::fs::write(&path, before).expect("write source");
4175        let discovered = [DiscoveredFile {
4176            id: FileId(0),
4177            path: path.clone(),
4178            size_bytes: u64::try_from(before.len()).expect("source length fits u64"),
4179        }];
4180
4181        let read_started_ns = fallow_types::source_fingerprint::now_ns();
4182        let first = super::extract::parse_all_files(&discovered, None, false);
4183        std::fs::write(&path, after).expect("rewrite source with equal-length content");
4184        let mut store = super::cache::CacheStore::new(project.path());
4185        super::update_cache(
4186            &mut store,
4187            &first.modules,
4188            &discovered,
4189            false,
4190            read_started_ns,
4191        );
4192
4193        let second = super::extract::parse_all_files(&discovered, Some(&store), false);
4194        let exports: Vec<String> = second
4195            .modules
4196            .first()
4197            .expect("second parse produces module")
4198            .exports
4199            .iter()
4200            .map(|export| export.name.to_string())
4201            .collect();
4202        assert_eq!(exports, vec!["bravo".to_string()]);
4203    }
4204}