Skip to main content

fallow_engine/
lib.rs

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