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