Skip to main content

fallow_cli/
programmatic.rs

1use std::path::{Path, PathBuf};
2
3use fallow_config::{EmailMode, OutputFormat};
4use fallow_core::results::AnalysisResults;
5use serde::Serialize;
6
7use crate::check::{CheckOptions, IssueFilters, TraceOptions};
8use crate::dupes::{DupesMode, DupesOptions};
9use crate::health::{HealthOptions, SortBy};
10use crate::health_types::EffortEstimate;
11use crate::report::{build_duplication_json, build_health_json, build_json};
12
13/// Structured error surface for the programmatic API.
14#[derive(Debug, Clone, Serialize)]
15pub struct ProgrammaticError {
16    pub message: String,
17    pub exit_code: u8,
18    pub code: Option<String>,
19    pub help: Option<String>,
20    pub context: Option<String>,
21}
22
23impl ProgrammaticError {
24    #[must_use]
25    pub fn new(message: impl Into<String>, exit_code: u8) -> Self {
26        Self {
27            message: message.into(),
28            exit_code,
29            code: None,
30            help: None,
31            context: None,
32        }
33    }
34
35    #[must_use]
36    pub fn with_help(mut self, help: impl Into<String>) -> Self {
37        self.help = Some(help.into());
38        self
39    }
40
41    #[must_use]
42    pub fn with_code(mut self, code: impl Into<String>) -> Self {
43        self.code = Some(code.into());
44        self
45    }
46
47    #[must_use]
48    pub fn with_context(mut self, context: impl Into<String>) -> Self {
49        self.context = Some(context.into());
50        self
51    }
52}
53
54impl std::fmt::Display for ProgrammaticError {
55    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
56        write!(f, "{}", self.message)
57    }
58}
59
60impl std::error::Error for ProgrammaticError {}
61
62type ProgrammaticResult<T> = Result<T, ProgrammaticError>;
63
64/// Shared options for all one-shot analyses.
65#[derive(Debug, Clone, Default)]
66pub struct AnalysisOptions {
67    pub root: Option<PathBuf>,
68    pub config_path: Option<PathBuf>,
69    pub no_cache: bool,
70    pub threads: Option<usize>,
71    /// Legacy convenience override. `true` forces production mode; `false`
72    /// defers to config unless `production_override` is set.
73    pub production: bool,
74    /// Explicit production override from an embedder option. `None` means
75    /// use the project config for the current analysis.
76    pub production_override: Option<bool>,
77    pub changed_since: Option<String>,
78    pub workspace: Option<Vec<String>>,
79    pub changed_workspaces: Option<String>,
80    pub explain: bool,
81}
82
83/// Issue-type filters for the dead-code analysis.
84#[derive(Debug, Clone, Default)]
85pub struct DeadCodeFilters {
86    pub unused_files: bool,
87    pub unused_exports: bool,
88    pub unused_deps: bool,
89    pub unused_types: bool,
90    pub private_type_leaks: bool,
91    pub unused_enum_members: bool,
92    pub unused_class_members: bool,
93    pub unresolved_imports: bool,
94    pub unlisted_deps: bool,
95    pub duplicate_exports: bool,
96    pub circular_deps: bool,
97    pub boundary_violations: bool,
98    pub stale_suppressions: bool,
99}
100
101/// Options for dead-code-oriented analyses.
102#[derive(Debug, Clone, Default)]
103pub struct DeadCodeOptions {
104    pub analysis: AnalysisOptions,
105    pub filters: DeadCodeFilters,
106    pub files: Vec<PathBuf>,
107    pub include_entry_exports: bool,
108}
109
110/// Programmatic duplication mode selection.
111#[derive(Debug, Clone, Copy, Default)]
112pub enum DuplicationMode {
113    Strict,
114    #[default]
115    Mild,
116    Weak,
117    Semantic,
118}
119
120impl DuplicationMode {
121    const fn to_cli(self) -> DupesMode {
122        match self {
123            Self::Strict => DupesMode::Strict,
124            Self::Mild => DupesMode::Mild,
125            Self::Weak => DupesMode::Weak,
126            Self::Semantic => DupesMode::Semantic,
127        }
128    }
129}
130
131/// Options for duplication analysis.
132#[derive(Debug, Clone)]
133pub struct DuplicationOptions {
134    pub analysis: AnalysisOptions,
135    pub mode: DuplicationMode,
136    pub min_tokens: usize,
137    pub min_lines: usize,
138    pub threshold: f64,
139    pub skip_local: bool,
140    pub cross_language: bool,
141    pub ignore_imports: bool,
142    pub top: Option<usize>,
143}
144
145impl Default for DuplicationOptions {
146    fn default() -> Self {
147        Self {
148            analysis: AnalysisOptions::default(),
149            mode: DuplicationMode::Mild,
150            min_tokens: 50,
151            min_lines: 5,
152            threshold: 0.0,
153            skip_local: false,
154            cross_language: false,
155            ignore_imports: false,
156            top: None,
157        }
158    }
159}
160
161/// Sort criteria for complexity findings.
162#[derive(Debug, Clone, Copy, Default)]
163pub enum ComplexitySort {
164    #[default]
165    Cyclomatic,
166    Cognitive,
167    Lines,
168    Severity,
169}
170
171impl ComplexitySort {
172    const fn to_cli(self) -> SortBy {
173        match self {
174            Self::Severity => SortBy::Severity,
175            Self::Cyclomatic => SortBy::Cyclomatic,
176            Self::Cognitive => SortBy::Cognitive,
177            Self::Lines => SortBy::Lines,
178        }
179    }
180}
181
182/// Privacy mode for ownership-aware hotspot output.
183#[derive(Debug, Clone, Copy, Default)]
184pub enum OwnershipEmailMode {
185    Raw,
186    #[default]
187    Handle,
188    Hash,
189}
190
191impl OwnershipEmailMode {
192    const fn to_config(self) -> EmailMode {
193        match self {
194            Self::Raw => EmailMode::Raw,
195            Self::Handle => EmailMode::Handle,
196            Self::Hash => EmailMode::Hash,
197        }
198    }
199}
200
201/// Effort filter for refactoring targets.
202#[derive(Debug, Clone, Copy)]
203pub enum TargetEffort {
204    Low,
205    Medium,
206    High,
207}
208
209impl TargetEffort {
210    const fn to_cli(self) -> EffortEstimate {
211        match self {
212            Self::Low => EffortEstimate::Low,
213            Self::Medium => EffortEstimate::Medium,
214            Self::High => EffortEstimate::High,
215        }
216    }
217}
218
219/// Options for complexity / health analysis.
220#[derive(Debug, Clone, Default)]
221pub struct ComplexityOptions {
222    pub analysis: AnalysisOptions,
223    pub max_cyclomatic: Option<u16>,
224    pub max_cognitive: Option<u16>,
225    pub max_crap: Option<f64>,
226    pub top: Option<usize>,
227    pub sort: ComplexitySort,
228    pub complexity: bool,
229    pub file_scores: bool,
230    pub coverage_gaps: bool,
231    pub hotspots: bool,
232    pub ownership: bool,
233    pub ownership_emails: Option<OwnershipEmailMode>,
234    pub targets: bool,
235    pub effort: Option<TargetEffort>,
236    pub score: bool,
237    pub since: Option<String>,
238    pub min_commits: Option<u32>,
239    pub coverage: Option<PathBuf>,
240    pub coverage_root: Option<PathBuf>,
241}
242
243#[derive(Debug, Clone)]
244struct ResolvedAnalysisOptions {
245    root: PathBuf,
246    config_path: Option<PathBuf>,
247    no_cache: bool,
248    threads: usize,
249    production_override: Option<bool>,
250    changed_since: Option<String>,
251    workspace: Option<Vec<String>>,
252    changed_workspaces: Option<String>,
253    explain: bool,
254}
255
256impl AnalysisOptions {
257    fn resolve(&self) -> ProgrammaticResult<ResolvedAnalysisOptions> {
258        if self.threads == Some(0) {
259            return Err(
260                ProgrammaticError::new("`threads` must be greater than 0", 2)
261                    .with_code("FALLOW_INVALID_THREADS")
262                    .with_context("analysis.threads"),
263            );
264        }
265        if self.workspace.is_some() && self.changed_workspaces.is_some() {
266            return Err(ProgrammaticError::new(
267                "`workspace` and `changed_workspaces` are mutually exclusive",
268                2,
269            )
270            .with_code("FALLOW_MUTUALLY_EXCLUSIVE_OPTIONS")
271            .with_context("analysis.workspace"));
272        }
273
274        let root = if let Some(root) = &self.root {
275            root.clone()
276        } else {
277            std::env::current_dir().map_err(|err| {
278                ProgrammaticError::new(
279                    format!("failed to resolve current working directory: {err}"),
280                    2,
281                )
282                .with_code("FALLOW_CWD_UNAVAILABLE")
283                .with_context("analysis.root")
284            })?
285        };
286
287        if !root.exists() {
288            return Err(ProgrammaticError::new(
289                format!("analysis root does not exist: {}", root.display()),
290                2,
291            )
292            .with_code("FALLOW_INVALID_ROOT")
293            .with_context("analysis.root"));
294        }
295        if !root.is_dir() {
296            return Err(ProgrammaticError::new(
297                format!("analysis root is not a directory: {}", root.display()),
298                2,
299            )
300            .with_code("FALLOW_INVALID_ROOT")
301            .with_context("analysis.root"));
302        }
303
304        if let Some(config_path) = &self.config_path
305            && !config_path.exists()
306        {
307            return Err(ProgrammaticError::new(
308                format!("config file does not exist: {}", config_path.display()),
309                2,
310            )
311            .with_code("FALLOW_INVALID_CONFIG_PATH")
312            .with_context("analysis.configPath"));
313        }
314
315        let threads = self.threads.unwrap_or_else(default_threads);
316        crate::rayon_pool::configure_global_pool(threads);
317        let production_override = self
318            .production_override
319            .or_else(|| self.production.then_some(true));
320
321        Ok(ResolvedAnalysisOptions {
322            root,
323            config_path: self.config_path.clone(),
324            no_cache: self.no_cache,
325            threads,
326            production_override,
327            changed_since: self.changed_since.clone(),
328            workspace: self.workspace.clone(),
329            changed_workspaces: self.changed_workspaces.clone(),
330            explain: self.explain,
331        })
332    }
333}
334
335fn default_threads() -> usize {
336    std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get)
337}
338
339fn insert_meta(output: &mut serde_json::Value, meta: serde_json::Value) {
340    if let serde_json::Value::Object(map) = output {
341        map.insert("_meta".to_string(), meta);
342    }
343}
344
345fn build_dead_code_json(
346    results: &AnalysisResults,
347    root: &Path,
348    elapsed: std::time::Duration,
349    explain: bool,
350) -> ProgrammaticResult<serde_json::Value> {
351    let mut output = build_json(results, root, elapsed).map_err(|err| {
352        ProgrammaticError::new(format!("failed to serialize dead-code report: {err}"), 2)
353            .with_code("FALLOW_SERIALIZE_DEAD_CODE_REPORT")
354            .with_context("dead-code")
355    })?;
356    if explain {
357        insert_meta(&mut output, crate::explain::check_meta());
358    }
359    Ok(output)
360}
361
362fn to_issue_filters(filters: &DeadCodeFilters) -> IssueFilters {
363    IssueFilters {
364        unused_files: filters.unused_files,
365        unused_exports: filters.unused_exports,
366        unused_deps: filters.unused_deps,
367        unused_types: filters.unused_types,
368        private_type_leaks: filters.private_type_leaks,
369        unused_enum_members: filters.unused_enum_members,
370        unused_class_members: filters.unused_class_members,
371        unresolved_imports: filters.unresolved_imports,
372        unlisted_deps: filters.unlisted_deps,
373        duplicate_exports: filters.duplicate_exports,
374        circular_deps: filters.circular_deps,
375        boundary_violations: filters.boundary_violations,
376        stale_suppressions: filters.stale_suppressions,
377    }
378}
379
380fn generic_analysis_error(command: &str) -> ProgrammaticError {
381    let code = format!(
382        "FALLOW_{}_FAILED",
383        command.replace('-', "_").to_ascii_uppercase()
384    );
385    ProgrammaticError::new(format!("{command} failed"), 2)
386        .with_code(code)
387        .with_context(format!("fallow {command}"))
388        .with_help(format!(
389            "Re-run `fallow {command} --format json --quiet` in the target project for CLI diagnostics"
390        ))
391}
392
393fn build_check_options<'a>(
394    resolved: &'a ResolvedAnalysisOptions,
395    options: &'a DeadCodeOptions,
396    filters: &'a IssueFilters,
397    trace_opts: &'a TraceOptions,
398) -> CheckOptions<'a> {
399    CheckOptions {
400        root: &resolved.root,
401        config_path: &resolved.config_path,
402        output: OutputFormat::Human,
403        no_cache: resolved.no_cache,
404        threads: resolved.threads,
405        quiet: true,
406        fail_on_issues: false,
407        filters,
408        changed_since: resolved.changed_since.as_deref(),
409        baseline: None,
410        save_baseline: None,
411        sarif_file: None,
412        production: resolved.production_override.unwrap_or(false),
413        production_override: resolved.production_override,
414        workspace: resolved.workspace.as_deref(),
415        changed_workspaces: resolved.changed_workspaces.as_deref(),
416        group_by: None,
417        include_dupes: false,
418        trace_opts,
419        explain: resolved.explain,
420        top: None,
421        file: &options.files,
422        include_entry_exports: options.include_entry_exports,
423        summary: false,
424        regression_opts: crate::regression::RegressionOpts {
425            fail_on_regression: false,
426            tolerance: crate::regression::Tolerance::Absolute(0),
427            regression_baseline_file: None,
428            save_target: crate::regression::SaveRegressionTarget::None,
429            scoped: false,
430            quiet: true,
431        },
432        retain_modules_for_health: false,
433    }
434}
435
436fn filter_for_circular_dependencies(results: &AnalysisResults) -> AnalysisResults {
437    let mut filtered = results.clone();
438    filtered.unused_files.clear();
439    filtered.unused_exports.clear();
440    filtered.unused_types.clear();
441    filtered.private_type_leaks.clear();
442    filtered.unused_dependencies.clear();
443    filtered.unused_dev_dependencies.clear();
444    filtered.unused_optional_dependencies.clear();
445    filtered.unused_enum_members.clear();
446    filtered.unused_class_members.clear();
447    filtered.unresolved_imports.clear();
448    filtered.unlisted_dependencies.clear();
449    filtered.duplicate_exports.clear();
450    filtered.type_only_dependencies.clear();
451    filtered.test_only_dependencies.clear();
452    filtered.boundary_violations.clear();
453    filtered.stale_suppressions.clear();
454    filtered
455}
456
457fn filter_for_boundary_violations(results: &AnalysisResults) -> AnalysisResults {
458    let mut filtered = results.clone();
459    filtered.unused_files.clear();
460    filtered.unused_exports.clear();
461    filtered.unused_types.clear();
462    filtered.private_type_leaks.clear();
463    filtered.unused_dependencies.clear();
464    filtered.unused_dev_dependencies.clear();
465    filtered.unused_optional_dependencies.clear();
466    filtered.unused_enum_members.clear();
467    filtered.unused_class_members.clear();
468    filtered.unresolved_imports.clear();
469    filtered.unlisted_dependencies.clear();
470    filtered.duplicate_exports.clear();
471    filtered.type_only_dependencies.clear();
472    filtered.test_only_dependencies.clear();
473    filtered.circular_dependencies.clear();
474    filtered.stale_suppressions.clear();
475    filtered
476}
477
478/// Run the dead-code analysis and return the CLI JSON contract as a value.
479pub fn detect_dead_code(options: &DeadCodeOptions) -> ProgrammaticResult<serde_json::Value> {
480    let resolved = options.analysis.resolve()?;
481    let filters = to_issue_filters(&options.filters);
482    let trace_opts = TraceOptions {
483        trace_export: None,
484        trace_file: None,
485        trace_dependency: None,
486        performance: false,
487    };
488    let check_options = build_check_options(&resolved, options, &filters, &trace_opts);
489    let result = crate::check::execute_check(&check_options)
490        .map_err(|_| generic_analysis_error("dead-code"))?;
491    build_dead_code_json(
492        &result.results,
493        &result.config.root,
494        result.elapsed,
495        resolved.explain,
496    )
497}
498
499/// Run the circular-dependency analysis and return the standard dead-code JSON envelope
500/// filtered down to the `circular_dependencies` category.
501pub fn detect_circular_dependencies(
502    options: &DeadCodeOptions,
503) -> ProgrammaticResult<serde_json::Value> {
504    let resolved = options.analysis.resolve()?;
505    let filters = to_issue_filters(&options.filters);
506    let trace_opts = TraceOptions {
507        trace_export: None,
508        trace_file: None,
509        trace_dependency: None,
510        performance: false,
511    };
512    let check_options = build_check_options(&resolved, options, &filters, &trace_opts);
513    let result = crate::check::execute_check(&check_options)
514        .map_err(|_| generic_analysis_error("dead-code"))?;
515    let filtered = filter_for_circular_dependencies(&result.results);
516    build_dead_code_json(
517        &filtered,
518        &result.config.root,
519        result.elapsed,
520        resolved.explain,
521    )
522}
523
524/// Run the boundary-violation analysis and return the standard dead-code JSON envelope
525/// filtered down to the `boundary_violations` category.
526pub fn detect_boundary_violations(
527    options: &DeadCodeOptions,
528) -> ProgrammaticResult<serde_json::Value> {
529    let resolved = options.analysis.resolve()?;
530    let filters = to_issue_filters(&options.filters);
531    let trace_opts = TraceOptions {
532        trace_export: None,
533        trace_file: None,
534        trace_dependency: None,
535        performance: false,
536    };
537    let check_options = build_check_options(&resolved, options, &filters, &trace_opts);
538    let result = crate::check::execute_check(&check_options)
539        .map_err(|_| generic_analysis_error("dead-code"))?;
540    let filtered = filter_for_boundary_violations(&result.results);
541    build_dead_code_json(
542        &filtered,
543        &result.config.root,
544        result.elapsed,
545        resolved.explain,
546    )
547}
548
549/// Run the duplication analysis and return the CLI JSON contract as a value.
550pub fn detect_duplication(options: &DuplicationOptions) -> ProgrammaticResult<serde_json::Value> {
551    let resolved = options.analysis.resolve()?;
552    let dupes_options = DupesOptions {
553        root: &resolved.root,
554        config_path: &resolved.config_path,
555        output: OutputFormat::Human,
556        no_cache: resolved.no_cache,
557        threads: resolved.threads,
558        quiet: true,
559        mode: options.mode.to_cli(),
560        min_tokens: options.min_tokens,
561        min_lines: options.min_lines,
562        threshold: options.threshold,
563        skip_local: options.skip_local,
564        cross_language: options.cross_language,
565        ignore_imports: options.ignore_imports,
566        top: options.top,
567        baseline_path: None,
568        save_baseline_path: None,
569        production: resolved.production_override.unwrap_or(false),
570        production_override: resolved.production_override,
571        trace: None,
572        changed_since: resolved.changed_since.as_deref(),
573        changed_files: None,
574        workspace: resolved.workspace.as_deref(),
575        changed_workspaces: resolved.changed_workspaces.as_deref(),
576        explain: resolved.explain,
577        explain_skipped: false,
578        summary: false,
579        group_by: None,
580    };
581    let result =
582        crate::dupes::execute_dupes(&dupes_options).map_err(|_| generic_analysis_error("dupes"))?;
583    build_duplication_json(
584        &result.report,
585        &result.config.root,
586        result.elapsed,
587        resolved.explain,
588    )
589    .map_err(|err| {
590        ProgrammaticError::new(format!("failed to serialize duplication report: {err}"), 2)
591            .with_code("FALLOW_SERIALIZE_DUPLICATION_REPORT")
592            .with_context("dupes")
593    })
594}
595
596fn build_complexity_options<'a>(
597    resolved: &'a ResolvedAnalysisOptions,
598    options: &'a ComplexityOptions,
599) -> HealthOptions<'a> {
600    let ownership = options.ownership || options.ownership_emails.is_some();
601    let hotspots = options.hotspots || ownership;
602    let targets = options.targets || options.effort.is_some();
603    let any_section = options.complexity
604        || options.file_scores
605        || options.coverage_gaps
606        || hotspots
607        || targets
608        || options.score;
609    let eff_score = if any_section { options.score } else { true };
610    let force_full = eff_score;
611    let score_only_output = options.score
612        && !options.complexity
613        && !options.file_scores
614        && !options.coverage_gaps
615        && !hotspots
616        && !targets;
617    let eff_file_scores = if any_section {
618        options.file_scores
619    } else {
620        true
621    } || force_full;
622    let eff_hotspots = if any_section { hotspots } else { true };
623    let eff_complexity = if any_section {
624        options.complexity
625    } else {
626        true
627    };
628    let eff_targets = if any_section { targets } else { true };
629    let eff_coverage_gaps = if any_section {
630        options.coverage_gaps
631    } else {
632        false
633    };
634
635    HealthOptions {
636        root: &resolved.root,
637        config_path: &resolved.config_path,
638        output: OutputFormat::Human,
639        no_cache: resolved.no_cache,
640        threads: resolved.threads,
641        quiet: true,
642        max_cyclomatic: options.max_cyclomatic,
643        max_cognitive: options.max_cognitive,
644        max_crap: options.max_crap,
645        top: options.top,
646        sort: options.sort.to_cli(),
647        production: resolved.production_override.unwrap_or(false),
648        production_override: resolved.production_override,
649        changed_since: resolved.changed_since.as_deref(),
650        workspace: resolved.workspace.as_deref(),
651        changed_workspaces: resolved.changed_workspaces.as_deref(),
652        baseline: None,
653        save_baseline: None,
654        complexity: eff_complexity,
655        file_scores: eff_file_scores,
656        coverage_gaps: eff_coverage_gaps,
657        config_activates_coverage_gaps: !any_section,
658        hotspots: eff_hotspots,
659        ownership: ownership && eff_hotspots,
660        ownership_emails: options.ownership_emails.map(OwnershipEmailMode::to_config),
661        targets: eff_targets,
662        force_full,
663        score_only_output,
664        enforce_coverage_gap_gate: true,
665        effort: options.effort.map(TargetEffort::to_cli),
666        score: eff_score,
667        min_score: None,
668        since: options.since.as_deref(),
669        min_commits: options.min_commits,
670        explain: resolved.explain,
671        summary: false,
672        save_snapshot: None,
673        trend: false,
674        group_by: None,
675        coverage: options.coverage.as_deref(),
676        coverage_root: options.coverage_root.as_deref(),
677        performance: false,
678        min_severity: None,
679        runtime_coverage: None,
680    }
681}
682
683/// Run the health / complexity analysis and return the CLI JSON contract as a value.
684pub fn compute_complexity(options: &ComplexityOptions) -> ProgrammaticResult<serde_json::Value> {
685    let resolved = options.analysis.resolve()?;
686    if let Some(path) = &options.coverage
687        && !path.exists()
688    {
689        return Err(ProgrammaticError::new(
690            format!("coverage path does not exist: {}", path.display()),
691            2,
692        )
693        .with_code("FALLOW_INVALID_COVERAGE_PATH")
694        .with_context("health.coverage"));
695    }
696
697    let health_options = build_complexity_options(&resolved, options);
698    let result = crate::health::execute_health(&health_options)
699        .map_err(|_| generic_analysis_error("health"))?;
700    let action_opts = crate::health::health_action_opts(&result);
701    build_health_json(
702        &result.report,
703        &result.config.root,
704        result.elapsed,
705        resolved.explain,
706        action_opts,
707    )
708    .map_err(|err| {
709        ProgrammaticError::new(format!("failed to serialize health report: {err}"), 2)
710            .with_code("FALLOW_SERIALIZE_HEALTH_REPORT")
711            .with_context("health")
712    })
713}
714
715/// Alias for `compute_complexity` with a more product-oriented name.
716pub fn compute_health(options: &ComplexityOptions) -> ProgrammaticResult<serde_json::Value> {
717    compute_complexity(options)
718}
719
720#[cfg(test)]
721mod tests {
722    use super::*;
723    use crate::report::test_helpers::sample_results;
724
725    #[test]
726    fn circular_dependency_filter_clears_other_issue_types() {
727        let root = PathBuf::from("/project");
728        let results = sample_results(&root);
729        let filtered = filter_for_circular_dependencies(&results);
730        let json = build_dead_code_json(&filtered, &root, std::time::Duration::ZERO, false)
731            .expect("should serialize");
732
733        assert_eq!(json["circular_dependencies"].as_array().unwrap().len(), 1);
734        assert_eq!(json["boundary_violations"].as_array().unwrap().len(), 0);
735        assert_eq!(json["unused_files"].as_array().unwrap().len(), 0);
736        assert_eq!(json["summary"]["total_issues"], serde_json::Value::from(1));
737    }
738
739    #[test]
740    fn boundary_violation_filter_clears_other_issue_types() {
741        let root = PathBuf::from("/project");
742        let results = sample_results(&root);
743        let filtered = filter_for_boundary_violations(&results);
744        let json = build_dead_code_json(&filtered, &root, std::time::Duration::ZERO, false)
745            .expect("should serialize");
746
747        assert_eq!(json["boundary_violations"].as_array().unwrap().len(), 1);
748        assert_eq!(json["circular_dependencies"].as_array().unwrap().len(), 0);
749        assert_eq!(json["unused_exports"].as_array().unwrap().len(), 0);
750        assert_eq!(json["summary"]["total_issues"], serde_json::Value::from(1));
751    }
752
753    #[test]
754    fn dead_code_without_production_override_uses_per_analysis_config() {
755        let dir = tempfile::tempdir().expect("temp dir");
756        let root = dir.path();
757        std::fs::create_dir_all(root.join("src")).unwrap();
758        std::fs::write(
759            root.join("package.json"),
760            r#"{"name":"programmatic-production","main":"src/index.ts"}"#,
761        )
762        .unwrap();
763        std::fs::write(root.join("src/index.ts"), "export const ok = 1;\n").unwrap();
764        std::fs::write(root.join("src/utils.test.ts"), "export const dead = 1;\n").unwrap();
765        std::fs::write(
766            root.join(".fallowrc.json"),
767            r#"{"production":{"deadCode":true,"health":false,"dupes":false}}"#,
768        )
769        .unwrap();
770
771        let options = DeadCodeOptions {
772            analysis: AnalysisOptions {
773                root: Some(root.to_path_buf()),
774                ..AnalysisOptions::default()
775            },
776            ..DeadCodeOptions::default()
777        };
778        let json = detect_dead_code(&options).expect("analysis should succeed");
779        let paths = unused_file_paths(&json);
780
781        assert!(
782            !paths.iter().any(|path| path.ends_with("utils.test.ts")),
783            "omitted production option should defer to production.deadCode=true config: {paths:?}"
784        );
785    }
786
787    #[test]
788    fn dead_code_explicit_production_false_overrides_config() {
789        let dir = tempfile::tempdir().expect("temp dir");
790        let root = dir.path();
791        std::fs::create_dir_all(root.join("src")).unwrap();
792        std::fs::write(
793            root.join("package.json"),
794            r#"{"name":"programmatic-production","main":"src/index.ts"}"#,
795        )
796        .unwrap();
797        std::fs::write(root.join("src/index.ts"), "export const ok = 1;\n").unwrap();
798        std::fs::write(root.join("src/utils.test.ts"), "export const dead = 1;\n").unwrap();
799        std::fs::write(
800            root.join(".fallowrc.json"),
801            r#"{"production":{"deadCode":true,"health":false,"dupes":false}}"#,
802        )
803        .unwrap();
804
805        let options = DeadCodeOptions {
806            analysis: AnalysisOptions {
807                root: Some(root.to_path_buf()),
808                production_override: Some(false),
809                ..AnalysisOptions::default()
810            },
811            ..DeadCodeOptions::default()
812        };
813        let json = detect_dead_code(&options).expect("analysis should succeed");
814        let paths = unused_file_paths(&json);
815
816        assert!(
817            paths.iter().any(|path| path.ends_with("utils.test.ts")),
818            "explicit production=false should include test files despite config: {paths:?}"
819        );
820    }
821
822    fn unused_file_paths(json: &serde_json::Value) -> Vec<String> {
823        json["unused_files"]
824            .as_array()
825            .unwrap()
826            .iter()
827            .filter_map(|file| file["path"].as_str())
828            .map(str::to_owned)
829            .collect()
830    }
831}