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