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