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