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