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