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