Skip to main content

fallow_core/
lib.rs

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