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