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