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