Skip to main content

fallow_engine/
lib.rs

1//! Typed analysis engine boundary for fallow consumers.
2//!
3//! `fallow-core` remains the internal orchestration backend. This crate owns
4//! the typed boundary that editor, API, and embedding surfaces can depend on
5//! without calling deprecated core entry points directly. Public modules should
6//! expose owned engine runners, typed result structs, or narrowly scoped aliases
7//! instead of broad core re-exports.
8//!
9//! User documentation for the analysis engine is on [fallow.tools](https://fallow.tools/docs/analysis/):
10//!
11//! - [Analysis overview](https://fallow.tools/docs/analysis/)
12//! - [Duplication analysis](https://fallow.tools/docs/analysis/duplication/)
13//! - [Similar code](https://fallow.tools/docs/analysis/similar-code/)
14
15#![warn(missing_docs)]
16#![cfg_attr(not(test), deny(clippy::disallowed_methods))]
17#![cfg_attr(
18    test,
19    allow(
20        clippy::unwrap_used,
21        clippy::expect_used,
22        reason = "tests use unwrap and expect to keep fixture setup concise"
23    )
24)]
25
26use std::fmt;
27#[cfg(test)]
28use std::path::Path;
29
30/// Finding-count and finding-identity baselines for suppressing known issues
31/// across runs.
32pub mod baseline;
33pub mod baseline_growth;
34pub mod baseline_location;
35/// Read-only inspection of the persisted extraction cache, for `fallow doctor`.
36pub mod cache_status;
37pub mod change_coupling;
38pub mod change_scope;
39pub mod changed_files;
40pub mod churn;
41mod churn_shallow;
42/// Continuous integration detection shared by the API runtime and the CLI.
43pub mod ci_env;
44pub mod clock;
45pub mod code_routes;
46pub mod codeowners;
47mod core_backend;
48pub mod cross_reference;
49mod css;
50pub mod dead_code;
51pub mod diff_scope;
52pub mod diff_source;
53pub mod discover;
54pub mod duplicates;
55mod effective_severity;
56pub mod entry_weight;
57pub mod error_severity;
58pub mod export_declarations;
59mod feature_flags;
60pub mod flag_age;
61mod flag_registry;
62pub mod flag_report;
63pub mod flag_retirement;
64pub mod flag_vendor;
65pub mod flags;
66pub mod import_bindings;
67pub(crate) mod graph {
68    pub use fallow_graph::graph::*;
69}
70mod base_worktree_orphans;
71mod base_worktree_registration;
72#[path = "git_env.rs"]
73mod git_env;
74pub mod guard;
75pub mod health;
76pub mod list_inventory;
77pub mod module_graph;
78/// The static half of mutation testing: mutant selection, test mapping,
79/// pruning and ranking.
80pub mod mutation;
81pub mod package_baselines;
82pub mod plugins;
83pub mod project_analysis;
84pub mod project_config;
85mod public_api;
86pub mod repo_refs;
87pub mod requested_rule_off;
88pub mod resolved_run;
89mod results;
90pub mod search_visibility;
91mod security;
92pub mod session;
93mod session_graph;
94mod session_reuse;
95pub mod shell_quote;
96pub mod similar_code;
97pub mod sink_substitution;
98pub mod source;
99mod suppress;
100pub mod test_paths;
101pub mod thread_pool;
102pub mod trace;
103pub mod trace_chain;
104pub mod trace_error;
105pub mod unprovable;
106/// Input validation shared by CLI-facing entry points: git refs, root paths,
107/// and control-character rejection.
108pub mod validate;
109pub mod vital_signs;
110pub mod viz;
111pub mod warm_parse;
112pub mod workspace_scope;
113pub mod write_guard;
114
115/// Result alias for typed engine operations.
116pub type EngineResult<T> = Result<T, EngineError>;
117
118/// Error type exposed by the typed engine boundary.
119#[derive(Debug, Clone, PartialEq, Eq)]
120pub struct EngineError {
121    message: String,
122    cancelled: bool,
123}
124
125impl EngineError {
126    /// Create an engine error from a user-facing message.
127    #[must_use]
128    fn new(message: impl Into<String>) -> Self {
129        Self {
130            message: message.into(),
131            cancelled: false,
132        }
133    }
134
135    /// Create the error an analysis returns when its caller cancelled it.
136    ///
137    /// `stage` names the pipeline boundary the run stopped at, so a caller can
138    /// tell how far the analysis got before it was stopped.
139    #[must_use]
140    pub fn cancelled(stage: &str) -> Self {
141        Self {
142            message: format!("analysis was cancelled before {stage}"),
143            cancelled: true,
144        }
145    }
146
147    /// Whether this error reports a caller-requested cancellation rather than
148    /// a failed analysis.
149    #[must_use]
150    pub const fn is_cancelled(&self) -> bool {
151        self.cancelled
152    }
153
154    /// User-facing error message from the backend.
155    #[must_use]
156    pub fn message(&self) -> &str {
157        &self.message
158    }
159}
160
161impl fmt::Display for EngineError {
162    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
163        f.write_str(&self.message)
164    }
165}
166
167impl std::error::Error for EngineError {}
168
169fn engine_error(err: impl fmt::Display) -> EngineError {
170    EngineError::new(err.to_string())
171}
172
173#[cfg(test)]
174mod tests {
175    use super::*;
176    use crate::{
177        project_analysis::ProjectAnalysisArtifactOptions,
178        project_config::{
179            ProjectConfigOptions, config_for_project, config_for_project_analysis,
180            resolve_cache_max_size_bytes,
181        },
182        session::AnalysisSession,
183    };
184    use fallow_config::ProductionAnalysis;
185    use fallow_types::output_format::OutputFormat;
186    use std::fs;
187    use std::path::PathBuf;
188
189    #[test]
190    fn engine_error_displays_message() {
191        let err = EngineError::new("config failed");
192
193        assert_eq!(err.message(), "config failed");
194        assert_eq!(err.to_string(), "config failed");
195    }
196
197    #[test]
198    fn engine_resolves_parse_cache_size_policy() {
199        let mut config = fallow_config::FallowConfig::default().resolve(
200            PathBuf::from("/repo"),
201            OutputFormat::Json,
202            1,
203            false,
204            true,
205            None,
206        );
207        assert_eq!(
208            resolve_cache_max_size_bytes(&config),
209            fallow_extract::cache::DEFAULT_CACHE_MAX_SIZE
210        );
211
212        config.cache_max_size_mb = Some(3);
213        assert_eq!(resolve_cache_max_size_bytes(&config), 3 * 1024 * 1024);
214
215        config.cache_max_size_mb = Some(u32::MAX);
216        assert_eq!(
217            resolve_cache_max_size_bytes(&config),
218            (u32::MAX as usize).saturating_mul(1024 * 1024)
219        );
220    }
221
222    #[test]
223    fn engine_root_does_not_reexport_broad_surface_modules() {
224        let source = fs::read_to_string(
225            std::path::PathBuf::from(
226                std::env::var_os("CARGO_MANIFEST_DIR").expect("cargo sets CARGO_MANIFEST_DIR"),
227            )
228            .join("src/lib.rs"),
229        )
230        .expect("read engine lib");
231        let public_surface = source
232            .split("#[cfg(test)]")
233            .next()
234            .expect("engine lib has public surface before tests");
235        let forbidden_exports = [
236            "pub use flags::",
237            "pub use git_env::",
238            "pub use public_api::",
239            "pub use results::",
240            "pub use security::",
241            "pub use suppress::",
242            "health_shared_parse_data_from_artifacts",
243        ];
244
245        for forbidden in forbidden_exports {
246            assert!(
247                !public_surface.contains(forbidden),
248                "engine root must expose typed modules, not `{forbidden}`"
249            );
250        }
251    }
252
253    #[test]
254    fn engine_session_owns_dead_code_pipeline_sequence() {
255        let session_source = fs::read_to_string(
256            std::path::PathBuf::from(
257                std::env::var_os("CARGO_MANIFEST_DIR").expect("cargo sets CARGO_MANIFEST_DIR"),
258            )
259            .join("src/session.rs"),
260        )
261        .expect("read engine session");
262        assert!(
263            !session_source.contains("analyze_with_owned_parse_result_from_discovery"),
264            "engine session must not delegate dead-code orchestration to the old core monolith"
265        );
266        for required_phase in [
267            "prepare_dead_code_backend_prelude",
268            "discover_dead_code_entry_points",
269            "try_load_dead_code_graph_cache",
270            "resolve_dead_code_imports",
271            "build_dead_code_graph",
272            "run_dead_code_detectors",
273        ] {
274            assert!(
275                session_source.contains(required_phase),
276                "engine session must explicitly sequence `{required_phase}`"
277            );
278        }
279    }
280
281    #[test]
282    fn engine_session_owns_analysis_discovery() {
283        let session_source = fs::read_to_string(
284            std::path::PathBuf::from(
285                std::env::var_os("CARGO_MANIFEST_DIR").expect("cargo sets CARGO_MANIFEST_DIR"),
286            )
287            .join("src/session.rs"),
288        )
289        .expect("read engine session");
290        assert!(
291            session_source.contains("crate::discover::prepare_analysis_discovery"),
292            "engine session must build discovery through the engine discovery boundary"
293        );
294        assert!(
295            session_source.contains("prepare_analysis_discovery_with_workspaces"),
296            "engine session must reuse workspace metadata captured during config load"
297        );
298        assert!(
299            session_source.contains("workspace_discovery_ms.is_some()"),
300            "AnalysisSession::from_config must only reuse workspace metadata when ProjectConfig preloaded it"
301        );
302        assert!(
303            !session_source.contains("core_backend::prepare_analysis_discovery"),
304            "engine session must not delegate discovery orchestration to core_backend"
305        );
306    }
307
308    #[test]
309    fn analysis_session_loads_config_and_discovered_files() {
310        let temp = tempfile::tempdir().expect("tempdir");
311        let src = temp.path().join("src");
312        std::fs::create_dir(&src).expect("src dir");
313        std::fs::write(src.join("index.ts"), "export const value = 1;\n").expect("source file");
314
315        let session = AnalysisSession::load(temp.path(), None).expect("session loads");
316
317        assert_eq!(session.root(), temp.path());
318        assert!(session.config_path().is_none());
319        assert!(session.files().iter().any(|file| {
320            file.path
321                .strip_prefix(temp.path())
322                .is_ok_and(|path| path == Path::new("src/index.ts"))
323        }));
324    }
325
326    #[test]
327    fn analysis_session_applies_config_adjustment_before_discovery() {
328        let temp = tempfile::tempdir().expect("tempdir");
329        let src = temp.path().join("src");
330        std::fs::create_dir(&src).expect("src dir");
331        std::fs::write(src.join("index.ts"), "export const value = 1;\n").expect("source file");
332        std::fs::write(src.join("index.test.ts"), "export const testValue = 1;\n")
333            .expect("test source file");
334
335        let session = AnalysisSession::load_with_config(temp.path(), None, |config| {
336            config.production = true;
337        })
338        .expect("session loads");
339
340        let relative_paths: Vec<_> = session
341            .files()
342            .iter()
343            .filter_map(|file| file.path.strip_prefix(temp.path()).ok())
344            .collect();
345        assert!(relative_paths.contains(&Path::new("src/index.ts")));
346        assert!(!relative_paths.contains(&Path::new("src/index.test.ts")));
347    }
348
349    #[test]
350    fn analysis_session_config_adjustment_invalidates_preloaded_workspaces() {
351        let temp = tempfile::tempdir().expect("tempdir");
352        std::fs::write(
353            temp.path().join("package.json"),
354            r#"{"name":"root","workspaces":["packages/*"]}"#,
355        )
356        .expect("root package");
357        std::fs::create_dir_all(temp.path().join("packages/a")).expect("workspace dir");
358        std::fs::create_dir_all(temp.path().join("packages/ignored")).expect("ignored dir");
359        std::fs::write(
360            temp.path().join("packages/a/package.json"),
361            r#"{"name":"a","main":"src/index.ts"}"#,
362        )
363        .expect("workspace package");
364
365        let session = AnalysisSession::load_with_config(temp.path(), None, |config| {
366            config.ignore_patterns = globset::GlobSetBuilder::new()
367                .add(globset::Glob::new("packages/ignored").expect("ignore glob"))
368                .build()
369                .expect("ignore set")
370                .into();
371        })
372        .expect("session loads");
373
374        assert!(
375            session
376                .workspaces()
377                .iter()
378                .all(|workspace| workspace.name != "ignored"),
379            "config mutations that affect workspace discovery must not reuse preloaded workspaces"
380        );
381        assert!(
382            !session
383                .workspace_diagnostics()
384                .iter()
385                .any(|diagnostic| diagnostic.path.ends_with("packages/ignored")),
386            "config mutations that affect workspace diagnostics must not reuse stale diagnostics"
387        );
388    }
389
390    #[test]
391    fn analysis_session_captures_workspace_diagnostics() {
392        let temp = tempfile::tempdir().expect("tempdir");
393        std::fs::write(
394            temp.path().join("package.json"),
395            r#"{"name":"diagnostic-root","workspaces":["packages/*"]}"#,
396        )
397        .expect("package json");
398        std::fs::create_dir_all(temp.path().join("packages/empty")).expect("workspace dir");
399        std::fs::create_dir(temp.path().join("src")).expect("src dir");
400        std::fs::write(
401            temp.path().join("src/index.ts"),
402            "export const value = 1;\n",
403        )
404        .expect("source file");
405
406        let session = AnalysisSession::load(temp.path(), None).expect("session loads");
407
408        assert!(session.workspace_diagnostics().iter().any(|diagnostic| {
409            diagnostic.kind.id() == "glob-matched-no-package-json"
410                && diagnostic.path.ends_with("packages/empty")
411        }));
412    }
413
414    #[test]
415    fn analysis_session_from_resolved_config_discovers_workspaces() {
416        let temp = tempfile::tempdir().expect("tempdir");
417        std::fs::write(
418            temp.path().join("package.json"),
419            r#"{"name":"root","workspaces":["packages/*"]}"#,
420        )
421        .expect("root package");
422        std::fs::create_dir_all(temp.path().join("packages/a/src")).expect("workspace dir");
423        std::fs::write(
424            temp.path().join("packages/a/package.json"),
425            r#"{"name":"pkg-a","main":"src/index.ts"}"#,
426        )
427        .expect("workspace package");
428        std::fs::write(
429            temp.path().join("packages/a/src/index.ts"),
430            "export const value = 1;\n",
431        )
432        .expect("workspace source");
433
434        let config = fallow_config::FallowConfig::default().resolve(
435            temp.path().to_path_buf(),
436            OutputFormat::Json,
437            1,
438            false,
439            true,
440            None,
441        );
442        let session = AnalysisSession::from_resolved_config(config).expect("session");
443
444        assert!(
445            session
446                .workspaces()
447                .iter()
448                .any(|workspace| workspace.name == "pkg-a"),
449            "resolved-config sessions must expose workspaces found during fallback discovery"
450        );
451    }
452
453    #[test]
454    fn analysis_session_can_be_consumed_into_pipeline_parts() {
455        let temp = tempfile::tempdir().expect("tempdir");
456        let src = temp.path().join("src");
457        std::fs::create_dir(&src).expect("src dir");
458        std::fs::write(src.join("index.ts"), "export const value = 1;\n").expect("source file");
459
460        let session = AnalysisSession::load(temp.path(), None).expect("session loads");
461        let parts = session.into_parts();
462
463        assert_eq!(parts.config.root, temp.path());
464        assert!(parts.config_path.is_none());
465        assert!(parts.files.iter().any(|file| {
466            file.path
467                .strip_prefix(temp.path())
468                .is_ok_and(|path| path == Path::new("src/index.ts"))
469        }));
470    }
471
472    #[test]
473    fn analysis_session_parses_only_its_discovered_files() {
474        let temp = tempfile::tempdir().expect("tempdir");
475        let src = temp.path().join("src");
476        std::fs::create_dir(&src).expect("src dir");
477        std::fs::write(src.join("index.ts"), "export const value = 1;\n").expect("source file");
478
479        let session = AnalysisSession::load(temp.path(), None).expect("session loads");
480        std::fs::write(src.join("late.ts"), "export const late = 1;\n").expect("late source file");
481        let parts = session.parsed_parts_uncached(false);
482
483        assert_eq!(parts.config.root, temp.path());
484        assert!(parts.config_path.is_none());
485        assert!(parts.modules.iter().any(|module| {
486            parts.files[module.file_id.0 as usize]
487                .path
488                .strip_prefix(temp.path())
489                .is_ok_and(|path| path == Path::new("src/index.ts"))
490        }));
491        assert!(parts.modules.iter().all(|module| {
492            !parts.files[module.file_id.0 as usize]
493                .path
494                .ends_with("late.ts")
495        }));
496    }
497
498    #[test]
499    fn analysis_session_reuses_complexity_parse_for_plain_parse() {
500        let temp = tempfile::tempdir().expect("tempdir");
501        let src = temp.path().join("src");
502        std::fs::create_dir(&src).expect("src dir");
503        std::fs::write(
504            src.join("index.ts"),
505            "export function value() { return 1; }\n",
506        )
507        .expect("source file");
508
509        let session = AnalysisSession::load(temp.path(), None).expect("session loads");
510        let first = session.parsed_parts(true);
511        assert!(!first.modules.is_empty());
512
513        let second = session.parsed_parts(false);
514
515        assert!(!second.modules.is_empty());
516        assert!(second.parse_ms.abs() < f64::EPSILON);
517        assert!(second.parse_cpu_ms.abs() < f64::EPSILON);
518    }
519
520    #[test]
521    fn dead_code_reused_parse_path_uses_engine_pipeline() {
522        let temp = tempfile::tempdir().expect("tempdir");
523        let src = temp.path().join("src");
524        std::fs::create_dir(&src).expect("src dir");
525        std::fs::write(src.join("index.ts"), "import './util';\n").expect("entry file");
526        std::fs::write(src.join("util.ts"), "export const value = 1;\n").expect("source file");
527
528        let session = AnalysisSession::load(temp.path(), None).expect("session loads");
529        let parts = session.parsed_parts_uncached(false);
530        let analysis = crate::dead_code::analyze_with_parse_result(&parts.config, &parts.modules)
531            .expect("reused parse analysis succeeds");
532
533        assert!(analysis.graph.is_some());
534        assert!(analysis.modules.is_none());
535        assert!(analysis.files.is_none());
536        assert!(
537            analysis
538                .file_hashes
539                .keys()
540                .any(|path| path.ends_with("util.ts"))
541        );
542    }
543
544    #[test]
545    fn analysis_session_reparses_when_cached_source_changes() {
546        let temp = tempfile::tempdir().expect("tempdir");
547        let src = temp.path().join("src");
548        std::fs::create_dir(&src).expect("src dir");
549        std::fs::write(
550            src.join("index.ts"),
551            "import { value } from './util';\nconsole.log(value);\n",
552        )
553        .expect("entry file");
554        let util_path = src.join("util.ts");
555        std::fs::write(&util_path, "export const value = 1;\n").expect("source file");
556
557        let session = AnalysisSession::load(temp.path(), None).expect("session loads");
558        let first = session
559            .analyze_project_with(&fallow_config::DuplicatesConfig::default(), true)
560            .expect("first analysis succeeds");
561        assert!(first.dead_code.results.unused_exports.is_empty());
562
563        std::fs::write(
564            &util_path,
565            "export const value = 1;\nexport const addedUnused = 2;\n",
566        )
567        .expect("updated source file");
568
569        let second = session
570            .analyze_project_with(&fallow_config::DuplicatesConfig::default(), true)
571            .expect("second analysis succeeds");
572        assert!(
573            second
574                .dead_code
575                .results
576                .unused_exports
577                .iter()
578                .any(|finding| finding.export.export_name == "addedUnused")
579        );
580    }
581
582    #[test]
583    fn analysis_session_returns_combined_project_analysis() {
584        let temp = tempfile::tempdir().expect("tempdir");
585        let src = temp.path().join("src");
586        std::fs::create_dir(&src).expect("src dir");
587        let repeated =
588            "export function repeated() {\n  return ['alpha', 'beta', 'gamma'].join(',');\n}\n";
589        std::fs::write(src.join("a.ts"), repeated).expect("source file");
590        std::fs::write(src.join("b.ts"), repeated).expect("source file");
591
592        let session = AnalysisSession::load(temp.path(), None).expect("session loads");
593        let mut config = session.config().duplicates.clone();
594        config.min_tokens = 1;
595        config.min_lines = 1;
596
597        let analysis = session
598            .analyze_project_with(&config, true)
599            .expect("project analysis succeeds");
600
601        assert!(analysis.dead_code.modules.is_some());
602        assert!(analysis.dead_code.files.is_some());
603        assert!(!analysis.duplication.clone_groups.is_empty());
604    }
605
606    #[test]
607    fn analysis_session_reuses_discovery_for_dead_code() {
608        let temp = tempfile::tempdir().expect("tempdir");
609        let src = temp.path().join("src");
610        std::fs::create_dir(&src).expect("src dir");
611        std::fs::write(src.join("index.ts"), "export const value = 1;\n").expect("source file");
612
613        let session = AnalysisSession::load(temp.path(), None).expect("session loads");
614        std::fs::write(src.join("late.ts"), "export const late = 1;\n").expect("late source file");
615
616        let analysis = session.analyze_dead_code().expect("analysis succeeds");
617
618        assert!(
619            analysis
620                .results
621                .unused_files
622                .iter()
623                .all(|finding| !finding.file.path.ends_with("late.ts")),
624            "session analysis must not rediscover files added after session load"
625        );
626    }
627
628    /// The editor session loads the config with `config_for_project`, so the
629    /// `production.ignore` globs must reach discovery there too (issue #4622).
630    #[test]
631    fn editor_session_applies_production_ignore() {
632        let temp = tempfile::tempdir().expect("tempdir");
633        let root = temp.path();
634        std::fs::create_dir_all(root.join("src")).expect("src dir");
635        std::fs::create_dir_all(root.join("scripts")).expect("scripts dir");
636        std::fs::write(root.join("src/index.ts"), "export const a = 1;\n").expect("index");
637        std::fs::write(root.join("scripts/seed.ts"), "export const s = 1;\n").expect("seed");
638        std::fs::write(
639            root.join(".fallowrc.json"),
640            r#"{ "production": { "deadCode": true, "ignore": ["scripts/**"] } }"#,
641        )
642        .expect("config");
643
644        let session = AnalysisSession::load_with_config_options(
645            root,
646            None,
647            fallow_config::ConfigLoadOptions::default(),
648            |_| {},
649        )
650        .expect("session");
651        let files: Vec<String> = session
652            .files()
653            .iter()
654            .map(|file| file.path.to_string_lossy().replace('\\', "/"))
655            .collect();
656
657        assert!(
658            files.iter().any(|file| file.ends_with("/src/index.ts")),
659            "{files:?}"
660        );
661        assert!(
662            !files.iter().any(|file| file.ends_with("/scripts/seed.ts")),
663            "production.ignore drops scripts/ in the editor session: {files:?}"
664        );
665    }
666
667    #[test]
668    fn analysis_session_returns_retained_artifacts() {
669        let temp = tempfile::tempdir().expect("tempdir");
670        let src = temp.path().join("src");
671        std::fs::create_dir(&src).expect("src dir");
672        std::fs::write(
673            src.join("index.ts"),
674            "export function used() { return 1; }\nused();\n",
675        )
676        .expect("source file");
677
678        let config = config_for_project(temp.path(), None)
679            .expect("config")
680            .config;
681        let session = AnalysisSession::from_resolved_config(config).expect("session");
682        let artifacts = session
683            .analyze_dead_code_with_artifacts(true, true)
684            .expect("analysis succeeds");
685
686        assert!(artifacts.graph.is_some());
687        assert!(artifacts.modules.is_some_and(|modules| !modules.is_empty()));
688        assert!(artifacts.files.is_some_and(|files| !files.is_empty()));
689    }
690
691    #[test]
692    fn analysis_session_returns_reuse_artifacts_with_fingerprints_and_scope() {
693        let temp = tempfile::tempdir().expect("tempdir");
694        let src = temp.path().join("src");
695        std::fs::create_dir(&src).expect("src dir");
696        let source = src.join("index.ts");
697        std::fs::write(&source, "export const value = 1;\n").expect("source file");
698
699        let session = AnalysisSession::load(temp.path(), None).expect("session loads");
700        let mut changed_files = rustc_hash::FxHashSet::default();
701        changed_files.insert(source.clone());
702        let artifacts = session
703            .analyze_dead_code_with_session_artifacts(false, true, Some(changed_files))
704            .expect("analysis succeeds");
705
706        assert!(artifacts.analysis.graph.is_some());
707        assert!(
708            artifacts
709                .changed_files
710                .as_ref()
711                .is_some_and(|changed| changed.contains(&source))
712        );
713        assert!(
714            artifacts
715                .source_fingerprints
716                .get(&source)
717                .is_some_and(|fingerprint| fingerprint.file_size > 0)
718        );
719    }
720
721    #[test]
722    fn analysis_session_keeps_the_graph_without_trace_work() {
723        let temp = tempfile::tempdir().expect("tempdir");
724        let src = temp.path().join("src");
725        std::fs::create_dir(&src).expect("src dir");
726        std::fs::write(
727            temp.path().join("package.json"),
728            r#"{"name": "graph-only", "main": "src/index.ts"}"#,
729        )
730        .expect("package.json");
731        std::fs::write(src.join("index.ts"), "export { a } from './mod';\n").expect("index");
732        std::fs::write(src.join("mod.ts"), "export const a = 1;\n").expect("mod");
733
734        let session = AnalysisSession::load(temp.path(), None).expect("session loads");
735        let artifacts = session
736            .analyze_dead_code_keeping_graph()
737            .expect("analysis succeeds");
738
739        let graph = artifacts.graph.as_ref().expect("the graph is kept");
740        assert!(
741            artifacts.timings.is_none(),
742            "the graph-only run collects no pipeline timings"
743        );
744        let re_exports = crate::module_graph::named_re_exports(graph);
745        assert_eq!(re_exports.len(), 1, "{re_exports:?}");
746        assert_eq!(re_exports[0].exported_name, "a");
747        assert_eq!(re_exports[0].imported_name, "a");
748        assert!(re_exports[0].path.ends_with("src/index.ts"));
749        assert!(re_exports[0].source_path.ends_with("src/mod.ts"));
750    }
751
752    #[test]
753    fn analysis_session_returns_project_artifacts_with_reuse_metadata() {
754        let temp = tempfile::tempdir().expect("tempdir");
755        let src = temp.path().join("src");
756        std::fs::create_dir(&src).expect("src dir");
757        let source = src.join("index.ts");
758        std::fs::write(&source, "export const value = 1;\n").expect("source file");
759
760        let session = AnalysisSession::load(temp.path(), None).expect("session loads");
761        let mut changed_files = rustc_hash::FxHashSet::default();
762        changed_files.insert(source.clone());
763        let artifacts = session
764            .analyze_project_with_artifacts(
765                &session.config().duplicates,
766                ProjectAnalysisArtifactOptions {
767                    retain_complexity_artifacts: true,
768                    retain_graph: true,
769                    changed_files: Some(changed_files),
770                    collect_source_fingerprints: true,
771                },
772            )
773            .expect("project analysis succeeds");
774
775        assert!(artifacts.dead_code.graph.is_some());
776        assert!(
777            artifacts
778                .changed_files
779                .as_ref()
780                .is_some_and(|changed| changed.contains(&source))
781        );
782        assert!(
783            artifacts
784                .source_fingerprints
785                .as_ref()
786                .and_then(|fingerprints| fingerprints.get(&source))
787                .is_some_and(|fingerprint| fingerprint.file_size > 0)
788        );
789
790        let lightweight = session
791            .analyze_project_with_artifacts(
792                &session.config().duplicates,
793                ProjectAnalysisArtifactOptions::default(),
794            )
795            .expect("project analysis succeeds");
796        assert!(
797            lightweight.source_fingerprints.is_none(),
798            "source fingerprints should be opt-in for lightweight editor analysis"
799        );
800
801        let output = artifacts.into_output();
802        assert!(output.dead_code.modules.is_some());
803        assert!(output.dead_code.files.is_some());
804    }
805
806    #[test]
807    fn project_artifacts_focus_duplication_to_changed_files() {
808        let temp = tempfile::tempdir().expect("tempdir");
809        let src = temp.path().join("src");
810        std::fs::create_dir(&src).expect("src dir");
811        let repeated =
812            "export function repeated() {\n  return ['alpha', 'beta', 'gamma'].join(',');\n}\n";
813        let a = src.join("a.ts");
814        std::fs::write(&a, repeated).expect("source file");
815        std::fs::write(src.join("b.ts"), repeated).expect("source file");
816
817        let session = AnalysisSession::load(temp.path(), None).expect("session loads");
818        let mut config = session.config().duplicates.clone();
819        config.min_tokens = 1;
820        config.min_lines = 1;
821
822        let full = session
823            .analyze_project_with_artifacts(&config, ProjectAnalysisArtifactOptions::default())
824            .expect("project analysis succeeds");
825        assert!(!full.duplication.clone_groups.is_empty());
826
827        let mut unrelated = rustc_hash::FxHashSet::default();
828        unrelated.insert(src.join("unrelated.ts"));
829        let focused_empty = session
830            .analyze_project_with_artifacts(
831                &config,
832                ProjectAnalysisArtifactOptions {
833                    changed_files: Some(unrelated),
834                    ..ProjectAnalysisArtifactOptions::default()
835                },
836            )
837            .expect("project analysis succeeds");
838        assert!(focused_empty.duplication.clone_groups.is_empty());
839
840        let mut changed = rustc_hash::FxHashSet::default();
841        changed.insert(a);
842        let focused = session
843            .analyze_project_with_artifacts(
844                &config,
845                ProjectAnalysisArtifactOptions {
846                    changed_files: Some(changed),
847                    ..ProjectAnalysisArtifactOptions::default()
848                },
849            )
850            .expect("project analysis succeeds");
851        assert!(!focused.duplication.clone_groups.is_empty());
852    }
853
854    #[test]
855    fn analysis_session_runs_duplication_with_default_skip_metadata() {
856        let temp = tempfile::tempdir().expect("tempdir");
857        let src = temp.path().join("src");
858        let generated = temp.path().join("storybook-static");
859        std::fs::create_dir(&src).expect("src dir");
860        std::fs::create_dir(&generated).expect("generated dir");
861        let repeated =
862            "export function repeated() {\n  return ['alpha', 'beta', 'gamma'].join(',');\n}\n";
863        std::fs::write(src.join("a.ts"), repeated).expect("source file");
864        std::fs::write(src.join("b.ts"), repeated).expect("source file");
865        std::fs::write(generated.join("generated.ts"), repeated).expect("generated file");
866
867        let session = AnalysisSession::load(temp.path(), None).expect("session loads");
868        let mut config = session.config().duplicates.clone();
869        config.min_tokens = 1;
870        config.min_lines = 1;
871
872        let analysis = session.find_duplicates_with_defaults(&config, None);
873
874        assert!(!analysis.report.clone_groups.is_empty());
875        assert!(analysis.default_ignore_skips.total > 0);
876    }
877
878    #[test]
879    fn trace_symbol_chain_uses_retained_engine_analysis() {
880        let temp = tempfile::tempdir().expect("tempdir");
881        let src = temp.path().join("src");
882        std::fs::create_dir(&src).expect("src dir");
883        std::fs::write(
884            src.join("util.ts"),
885            "export function helper() { return 1; }\n",
886        )
887        .expect("util source");
888        std::fs::write(
889            src.join("index.ts"),
890            "import { helper } from './util';\nexport const value = helper();\n",
891        )
892        .expect("index source");
893
894        let project_config = config_for_project_analysis(
895            temp.path(),
896            None,
897            ProjectConfigOptions {
898                output: OutputFormat::Json,
899                no_cache: true,
900                threads: 1,
901                production_override: None,
902                quiet: true,
903                analysis: ProductionAnalysis::DeadCode,
904                allow_remote_extends: false,
905            },
906        )
907        .expect("project config loads");
908        let session = AnalysisSession::from_config(project_config);
909        let trace = crate::trace_chain::trace_symbol_chain_with_session(
910            &session,
911            fallow_types::trace_chain::SymbolChainQuery {
912                file: "src/util.ts",
913                symbol: "helper",
914                depth: 1,
915                directions: fallow_types::trace_chain::TraceDirections {
916                    callers: true,
917                    callees: false,
918                },
919            },
920        )
921        .expect("trace succeeds")
922        .expect("trace target exists");
923
924        assert!(trace.symbol_found);
925        assert_eq!(trace.file, Path::new("src/util.ts"));
926        assert!(trace.callers.is_some_and(|callers| {
927            callers
928                .iter()
929                .any(|caller| caller.file == Path::new("src/index.ts"))
930        }));
931    }
932
933    fn workspace_fixture_path(name: &str) -> std::path::PathBuf {
934        std::path::PathBuf::from(
935            std::env::var_os("CARGO_MANIFEST_DIR").expect("cargo sets CARGO_MANIFEST_DIR"),
936        )
937        .join("../../tests/fixtures")
938        .join(name)
939    }
940
941    fn trace_symbol_chain_fixture(
942        fixture: &str,
943        file: &str,
944        symbol: &str,
945        directions: fallow_types::trace_chain::TraceDirections,
946        depth: u32,
947    ) -> fallow_types::trace_chain::SymbolChainTrace {
948        let root = workspace_fixture_path(fixture);
949        let session = AnalysisSession::load(&root, None).expect("session loads");
950        crate::trace_chain::trace_symbol_chain_with_session(
951            &session,
952            fallow_types::trace_chain::SymbolChainQuery {
953                file,
954                symbol,
955                depth,
956                directions,
957            },
958        )
959        .expect("trace succeeds")
960        .expect("trace target exists")
961    }
962
963    fn symbol_chain_hop_files(
964        hops: &[fallow_types::trace_chain::ChainHop],
965    ) -> std::collections::BTreeSet<String> {
966        hops.iter()
967            .map(|hop| hop.file.to_string_lossy().replace('\\', "/"))
968            .collect()
969    }
970
971    #[test]
972    fn trace_symbol_chain_caller_set_matches_import_symbol_callers() {
973        let trace = trace_symbol_chain_fixture(
974            "e8-symbol-chain",
975            "src/format.ts",
976            "formatDate",
977            fallow_types::trace_chain::TraceDirections {
978                callers: true,
979                callees: false,
980            },
981            1,
982        );
983
984        assert!(trace.symbol_found, "formatDate is an export of format.ts");
985        assert!(
986            trace.best_effort,
987            "symbol-level chains are labeled best-effort"
988        );
989
990        let callers = trace.callers.expect("callers were requested");
991        let actual = symbol_chain_hop_files(&callers);
992        let expected: std::collections::BTreeSet<String> =
993            ["src/report.ts".to_string(), "src/middle.ts".to_string()]
994                .into_iter()
995                .collect();
996        assert_eq!(actual, expected);
997
998        for hop in &callers {
999            assert_eq!(hop.imported_as, "formatDate");
1000            assert_eq!(hop.local_name, "formatDate");
1001            assert_eq!(hop.depth, 1);
1002            assert!(!hop.type_only);
1003        }
1004    }
1005
1006    #[test]
1007    fn trace_symbol_chain_reports_unresolved_callees() {
1008        let trace = trace_symbol_chain_fixture(
1009            "e8-symbol-chain",
1010            "src/report.ts",
1011            "buildReport",
1012            fallow_types::trace_chain::TraceDirections {
1013                callers: false,
1014                callees: true,
1015            },
1016            1,
1017        );
1018
1019        assert!(trace.symbol_found, "buildReport is an export of report.ts");
1020
1021        let unresolved = trace
1022            .unresolved_callees
1023            .expect("callees were requested, so unresolved_callees is present");
1024        let callees: Vec<&str> = unresolved
1025            .iter()
1026            .map(|callee| callee.callee.as_str())
1027            .collect();
1028
1029        assert!(
1030            callees.contains(&"localHelper"),
1031            "the local helper callee must be reported as unresolved, got {callees:?}"
1032        );
1033        assert!(
1034            callees.contains(&"parseInt"),
1035            "the global callee must be reported as unresolved, got {callees:?}"
1036        );
1037        assert!(
1038            !callees.contains(&"formatDate"),
1039            "an imported callee resolves to an edge and is not unresolved, got {callees:?}"
1040        );
1041
1042        let local_helper = unresolved
1043            .iter()
1044            .find(|callee| callee.callee == "localHelper")
1045            .expect("local helper is unresolved");
1046        assert_eq!(
1047            local_helper.reason,
1048            fallow_types::trace_chain::UnresolvedReason::LocalOrGlobal
1049        );
1050
1051        let callees_hops = trace.callees.expect("callees were requested");
1052        let resolved_files = symbol_chain_hop_files(&callees_hops);
1053        assert!(
1054            resolved_files.contains("src/format.ts"),
1055            "the resolved import-symbol callee edge to format.ts must be present, got {resolved_files:?}"
1056        );
1057    }
1058
1059    /// A star collision, a real export, and a name nobody declares must be
1060    /// three distinguishable outcomes: before this, the first two of those
1061    /// three collapsed into one byte-identical "not found" answer.
1062    #[test]
1063    fn trace_symbol_chain_separates_ambiguous_from_unique_and_absent() {
1064        let both_directions = fallow_types::trace_chain::TraceDirections {
1065            callers: true,
1066            callees: true,
1067        };
1068
1069        let ambiguous = trace_symbol_chain_fixture(
1070            "effective-export-ambiguous-star",
1071            "src/barrel.ts",
1072            "foo",
1073            both_directions,
1074            1,
1075        );
1076        assert!(
1077            !ambiguous.symbol_found,
1078            "an ambiguous name is genuinely not exported by the barrel"
1079        );
1080        let collision = ambiguous
1081            .star_export_ambiguity
1082            .expect("the barrel's star sources collide on foo");
1083        let sources: Vec<String> = collision
1084            .sources
1085            .iter()
1086            .map(|source| source.to_string_lossy().replace('\\', "/"))
1087            .collect();
1088        assert_eq!(sources, vec!["src/left.ts", "src/right.ts"]);
1089        assert_eq!(
1090            collision.namespaces,
1091            vec![fallow_types::semantic::SemanticNamespace::Value]
1092        );
1093        assert!(
1094            ambiguous.reason.contains("src/left.ts")
1095                && ambiguous.reason.contains("src/right.ts")
1096                && ambiguous.reason.contains("ambiguous"),
1097            "the reason must name the colliding origins, got {}",
1098            ambiguous.reason
1099        );
1100
1101        let unique = trace_symbol_chain_fixture(
1102            "effective-export-ambiguous-star",
1103            "src/left.ts",
1104            "foo",
1105            both_directions,
1106            1,
1107        );
1108        assert!(unique.symbol_found, "left.ts really exports foo");
1109        assert!(
1110            unique.star_export_ambiguity.is_none(),
1111            "a declaring module is not itself ambiguous"
1112        );
1113
1114        let absent = trace_symbol_chain_fixture(
1115            "effective-export-ambiguous-star",
1116            "src/barrel.ts",
1117            "nonExistent",
1118            both_directions,
1119            1,
1120        );
1121        assert!(!absent.symbol_found);
1122        assert!(
1123            absent.star_export_ambiguity.is_none(),
1124            "an unknown name has no collision to report"
1125        );
1126        assert!(
1127            absent.reason.starts_with("symbol not found as an export"),
1128            "the unknown-name reason is unchanged, got {}",
1129            absent.reason
1130        );
1131        assert_ne!(
1132            absent.reason, ambiguous.reason,
1133            "ambiguous and absent must not report the same reason"
1134        );
1135    }
1136
1137    /// `export type *` sources colliding over value declarations produce a
1138    /// collision that exists only in type space, and the trace must report it
1139    /// in that namespace rather than staying silent.
1140    #[test]
1141    fn trace_symbol_chain_reports_a_type_only_star_collision() {
1142        let ambiguous = trace_symbol_chain_fixture(
1143            "effective-export-ambiguous-type-only-star",
1144            "src/barrel.ts",
1145            "Foo",
1146            fallow_types::trace_chain::TraceDirections {
1147                callers: true,
1148                callees: true,
1149            },
1150            1,
1151        );
1152
1153        assert!(!ambiguous.symbol_found);
1154        let collision = ambiguous
1155            .star_export_ambiguity
1156            .expect("the barrel's type-only star sources collide on Foo");
1157        let sources: Vec<String> = collision
1158            .sources
1159            .iter()
1160            .map(|source| source.to_string_lossy().replace('\\', "/"))
1161            .collect();
1162        assert_eq!(sources, vec!["src/left.ts", "src/right.ts"]);
1163        assert_eq!(
1164            collision.namespaces,
1165            vec![fallow_types::semantic::SemanticNamespace::Type]
1166        );
1167        assert!(
1168            ambiguous.reason.contains("src/left.ts") && ambiguous.reason.contains("ambiguous"),
1169            "the reason must name the colliding origins, got {}",
1170            ambiguous.reason
1171        );
1172    }
1173
1174    #[test]
1175    fn trace_export_uses_retained_engine_analysis_for_star_reexport() {
1176        let temp = tempfile::tempdir().expect("tempdir");
1177        let src = temp.path().join("src");
1178        std::fs::create_dir(&src).expect("src dir");
1179        std::fs::write(
1180            src.join("merged.ts"),
1181            "export const Merged = 1;\nexport const unusedControl = 2;\n",
1182        )
1183        .expect("merged source");
1184        std::fs::write(src.join("barrel.ts"), "export * from './merged';\n")
1185            .expect("barrel source");
1186        std::fs::write(
1187            src.join("index.ts"),
1188            "import { Merged } from './barrel';\nconsole.log(Merged);\n",
1189        )
1190        .expect("index source");
1191
1192        let config = config_for_project(temp.path(), None)
1193            .expect("config")
1194            .config;
1195        let session = AnalysisSession::from_resolved_config(config).expect("session");
1196        let artifacts = session
1197            .analyze_dead_code_with_artifacts(false, true)
1198            .expect("analysis succeeds");
1199        let graph = artifacts.graph.as_ref().expect("graph is retained");
1200        let trace = crate::trace::trace_export(graph, session.root(), "src/merged.ts", "Merged")
1201            .expect("trace exists");
1202
1203        assert!(trace.is_used, "trace should agree the value export is used");
1204        assert_eq!(
1205            trace.direct_references.len(),
1206            1,
1207            "trace should include the consumer named import"
1208        );
1209    }
1210
1211    #[test]
1212    fn trace_export_credits_entry_type_reexport_through_star_barrel() {
1213        let temp = tempfile::tempdir().expect("tempdir");
1214        let root = temp.path();
1215        std::fs::create_dir_all(root.join("src/kit")).expect("src/kit dir");
1216        std::fs::write(
1217            root.join(".fallowrc.json"),
1218            r#"{ "entry": ["src/index.ts"] }"#,
1219        )
1220        .expect("fallowrc");
1221        std::fs::write(
1222            root.join("src/index.ts"),
1223            "export type { ViaStar } from './kit';\n",
1224        )
1225        .expect("src/index.ts");
1226        std::fs::write(root.join("src/kit/index.ts"), "export * from './types';\n")
1227            .expect("src/kit/index.ts");
1228        std::fs::write(
1229            root.join("src/kit/types.ts"),
1230            "export type ViaStar = { a: string };\n",
1231        )
1232        .expect("src/kit/types.ts");
1233
1234        let config = config_for_project(root, None).expect("config").config;
1235        let session = AnalysisSession::from_resolved_config(config).expect("session");
1236        let artifacts = session
1237            .analyze_dead_code_with_artifacts(false, true)
1238            .expect("analysis succeeds");
1239        let graph = artifacts.graph.as_ref().expect("graph is retained");
1240        let trace =
1241            crate::trace::trace_export(graph, session.root(), "src/kit/types.ts", "ViaStar")
1242                .expect("trace exists");
1243
1244        assert!(
1245            trace.is_used,
1246            "entry type re-export through a star barrel must mark declaration as used, got {trace:?}"
1247        );
1248        assert_eq!(trace.direct_references.len(), 1);
1249        assert_eq!(trace.direct_references[0].kind, "re-export");
1250        assert_eq!(
1251            trace.reason,
1252            "Used by 1 file(s), re-exported through 2 barrel(s)"
1253        );
1254        let star_hop = trace
1255            .re_export_chains
1256            .iter()
1257            .find(|hop| hop.barrel_file.to_string_lossy().replace('\\', "/") == "src/kit/index.ts")
1258            .expect("star barrel hop must appear in re_export_chains");
1259        assert_eq!(
1260            star_hop.reference_count, 1,
1261            "star barrel hop must reflect the entry re-export reference"
1262        );
1263    }
1264}
1265
1266mod shared_state;