Skip to main content

fallow_core/
lib.rs

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