Skip to main content

fallow_core/
lib.rs

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