Skip to main content

fallow_core/
lib.rs

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