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