Skip to main content

fallow_api/runtime/
audit.rs

1use std::path::{Path, PathBuf};
2use std::time::Instant;
3
4use fallow_config::{ProductionAnalysis, ResolvedConfig};
5use fallow_engine::change_scope::{ChangeScope, ChangeScopeOwner};
6use fallow_engine::{
7    dead_code::DeadCodeAnalysisArtifacts,
8    project_analysis::ProjectAnalysisArtifactOptions,
9    project_config::ProjectConfigOptions,
10    repo_refs::{self, ResolvedAuditBase, TemporaryBaseWorktree},
11    session::AnalysisSession,
12};
13use fallow_output::build_audit_next_steps;
14use fallow_types::{
15    envelope::AuditIntroduced, output::NextStep, output_format::OutputFormat,
16    results::AnalysisResults,
17};
18use rustc_hash::FxHashSet;
19
20use crate::{
21    AnalysisOptions, AuditAttribution, AuditOptions, AuditProgrammaticOutput, AuditSummary,
22    AuditVerdict, ComplexityOptions, DeadCodeFilters, DeadCodeOptions, DuplicationOptions,
23    ProgrammaticError,
24    analysis_context::{
25        ProgrammaticAnalysisContext, changed_files_for_run, resolve_programmatic_analysis_context,
26    },
27    audit_run::{
28        AuditAnalyses, AuditAnalysesView, AuditBackend, AuditRun, AuditRunInput, DeadCodeView,
29        DuplicationView, HealthView,
30    },
31};
32
33use super::{
34    ProgrammaticResult, dead_code::run_dead_code_in_context,
35    duplication::run_duplication_in_context, health_may_consume_dead_code_artifacts,
36    health_may_consume_duplication_report, resolve_effective_production_modes,
37    run_health_for_audit, run_health_with_session_artifacts, type_aware_config,
38};
39
40/// Error code of [`run_audit`] when the project config sets an `audit`
41/// baseline key, which the typed audit cannot apply. Callers that can run
42/// `fallow audit` instead, such as the MCP `audit` tool, fall back on it.
43pub const AUDIT_CONFIG_BASELINE_UNSUPPORTED: &str = "FALLOW_AUDIT_BASELINE_UNSUPPORTED";
44
45/// Run changed-code audit through typed programmatic runners.
46///
47/// The audit itself is [`crate::audit_run::run`], the same implementation as
48/// `fallow audit`. This function supplies the typed runners and builds the
49/// programmatic output.
50///
51/// # Errors
52///
53/// Returns a structured error for invalid options, base-ref discovery failures,
54/// unsupported CLI-only audit surfaces (including the baseline keys of the
55/// `audit` config section, see [`AUDIT_CONFIG_BASELINE_UNSUPPORTED`]), or
56/// analysis failures. When the environment, `audit.typeAware` or
57/// `typeAware.enabled` turns on type-aware analysis that the options leave
58/// off, it returns [`super::TYPE_AWARE_CONFIG_UNSUPPORTED`].
59pub fn run_audit(options: &AuditOptions) -> ProgrammaticResult<AuditProgrammaticOutput> {
60    validate_audit_api_options(options)?;
61    let start = Instant::now();
62    let resolved_base = resolve_audit_base_ref(options)?;
63    let analysis = analysis_options_for_audit(options, &resolved_base.git_ref);
64    let resolved = audit_section_context(&analysis)?;
65    let config = load_programmatic_audit_config(&resolved)?;
66    let options = &options_with_audit_config(options, &config.audit);
67    let changed_files = changed_files_for_run(&resolved)?.unwrap_or_default();
68    let changed_files_count = changed_files.len();
69
70    reject_empty_selection(options)?;
71
72    if changed_files.is_empty() {
73        return Ok(empty_audit_output(
74            options,
75            resolved_base,
76            resolved.root(),
77            changed_files_count,
78            start.elapsed(),
79        ));
80    }
81
82    reject_config_baselines(&config.audit, options)?;
83    type_aware_config::reject_config_type_aware(
84        &options.analysis.type_aware,
85        &resolved,
86        type_aware_config::TypeAwareCommand::Audit,
87    )?;
88    let backend = ProgrammaticAuditBackend {
89        options,
90        analysis: &analysis,
91        resolved: &resolved,
92        config: &config,
93    };
94    let Some(AuditRun {
95        analyses,
96        outcome,
97        changed_files: _,
98    }) = crate::audit_run::run(
99        &backend,
100        AuditRunInput {
101            root: resolved.root(),
102            gate: options.gate.unwrap_or_default(),
103            worsened: options.worsened.unwrap_or_default(),
104            base_ref: &resolved_base.git_ref,
105            cache_dir: Some(&config.cache_dir),
106            changed_files,
107            inherited_base_refs: &resolved_base.inherited_refs,
108            compare_line_counts: config.health.file_lines_check_enabled(),
109        },
110    )?
111    else {
112        return Ok(empty_audit_output(
113            options,
114            resolved_base,
115            resolved.root(),
116            changed_files_count,
117            start.elapsed(),
118        ));
119    };
120
121    let mut head = analyses.subanalyses;
122    if outcome.base_snapshot.is_some()
123        && let Some(duplication) = head.duplication.as_mut()
124    {
125        for ((group, introduced), demoted) in duplication
126            .output
127            .report
128            .clone_groups
129            .iter_mut()
130            .zip(outcome.comparison.dupes.introduced())
131            .zip(outcome.comparison.dupes.demoted())
132        {
133            group.introduced = Some(AuditIntroduced(introduced));
134            group.demotion_reason = demoted.then_some(crate::CloneDemotionReason::NoAddedLines);
135        }
136    }
137    let next_steps = audit_next_steps(head.dead_code.as_ref(), head.complexity.as_ref());
138    let base_snapshot = crate::audit_run::programmatic_base_snapshot(&outcome);
139
140    Ok(AuditProgrammaticOutput {
141        verdict: outcome.verdict,
142        summary: outcome.summary,
143        attribution: outcome.attribution,
144        changed_files_count,
145        base_ref: resolved_base.git_ref,
146        base_description: resolved_base.description,
147        head_sha: repo_refs::short_head_sha(resolved.root()),
148        elapsed: start.elapsed(),
149        base_snapshot_skipped: None,
150        base_snapshot,
151        dead_code: head.dead_code,
152        duplication: head.duplication,
153        complexity: head.complexity,
154        diff_risk: outcome.diff_risk,
155        next_steps,
156        telemetry_analysis_run_id: None,
157    })
158}
159
160/// The typed runners of the programmatic audit.
161struct ProgrammaticAuditBackend<'a> {
162    options: &'a AuditOptions,
163    analysis: &'a AnalysisOptions,
164    resolved: &'a ProgrammaticAnalysisContext,
165    config: &'a ResolvedConfig,
166}
167
168impl<'a> AuditBackend for ProgrammaticAuditBackend<'a> {
169    type Analyses = ProgrammaticAuditAnalyses<'a>;
170    type Checkout = TemporaryBaseWorktree;
171    type CacheKey = ();
172    type Error = ProgrammaticError;
173
174    fn run_head(
175        &self,
176        changed_files: &FxHashSet<PathBuf>,
177    ) -> ProgrammaticResult<ProgrammaticAuditAnalyses<'a>> {
178        let subanalyses = run_audit_subanalyses_with_context(
179            self.options,
180            self.analysis,
181            self.resolved,
182            Some(changed_files),
183        )?;
184        Ok(ProgrammaticAuditAnalyses {
185            subanalyses,
186            config: self.config,
187            own_config_unused_code: None,
188        })
189    }
190
191    fn create_base_checkout(
192        &self,
193        base_ref: &str,
194        _base_sha: Option<&str>,
195    ) -> ProgrammaticResult<TemporaryBaseWorktree> {
196        TemporaryBaseWorktree::create(
197            self.resolved.root(),
198            base_ref,
199            &self.config.workspace_patterns,
200        )
201        .map_err(|err| {
202            ProgrammaticError::new(err.to_string(), 2)
203                .with_code("FALLOW_AUDIT_BASE_WORKTREE_FAILED")
204                .with_context("audit.base")
205        })
206    }
207
208    fn run_base(
209        &self,
210        base_root: &Path,
211        focus: Option<&FxHashSet<PathBuf>>,
212    ) -> ProgrammaticResult<ProgrammaticAuditAnalyses<'a>> {
213        let head_root = self.resolved.root();
214        let config_path = self
215            .options
216            .analysis
217            .config_path
218            .clone()
219            .or_else(|| fallow_config::FallowConfig::find_config_path(head_root));
220        let base_analysis = AnalysisOptions {
221            root: Some(base_root.to_path_buf()),
222            config_path,
223            changed_since: None,
224            explain: false,
225            ..self.options.analysis.clone()
226        };
227        let coverage = crate::audit_run::base_coverage_inputs(
228            head_root,
229            self.options.coverage.as_deref(),
230            self.options.coverage_root.as_deref(),
231        );
232        let base_options = AuditOptions {
233            coverage: coverage.coverage,
234            coverage_root: coverage.coverage_root,
235            ..self.options.clone()
236        };
237        let subanalyses = run_audit_subanalyses(&base_options, &base_analysis, focus, true)?;
238        let own_config_unused_code = subanalyses.dead_code.as_ref().and_then(|dead_code| {
239            own_config::base_own_config_unused_code(&own_config::BaseOwnConfigInput {
240                options: self.options,
241                base_analysis: &base_analysis,
242                head_root,
243                head_config_path: base_analysis.config_path.as_deref(),
244                base_root,
245                focus,
246                base_results: &dead_code.output.results,
247            })
248        });
249        Ok(ProgrammaticAuditAnalyses {
250            subanalyses,
251            config: self.config,
252            own_config_unused_code,
253        })
254    }
255}
256
257/// The typed analyses of one audit side. `config` is the head config, which
258/// decides severities and styling gates.
259struct ProgrammaticAuditAnalyses<'a> {
260    subanalyses: AuditSubanalyses,
261    config: &'a ResolvedConfig,
262    /// Unused-code keys of a base side under the config of the base commit.
263    own_config_unused_code: Option<FxHashSet<String>>,
264}
265
266impl AuditAnalyses for ProgrammaticAuditAnalyses<'_> {
267    fn view(&self) -> AuditAnalysesView<'_> {
268        let AuditSubanalyses {
269            dead_code,
270            duplication,
271            complexity,
272        } = &self.subanalyses;
273        AuditAnalysesView {
274            dead_code: dead_code.as_ref().map(|dead_code| DeadCodeView {
275                results: &dead_code.output.results,
276                config: self.config,
277                root: &dead_code.root,
278                type_aware: dead_code
279                    .output
280                    .meta
281                    .as_ref()
282                    .and_then(|meta| meta.type_aware.as_ref()),
283                syntactic_keys: None,
284                public_api: None,
285                own_config_unused_code: self.own_config_unused_code.as_ref(),
286            }),
287            duplication: duplication.as_ref().map(|duplication| DuplicationView {
288                clone_groups: duplication
289                    .output
290                    .report
291                    .clone_groups
292                    .iter()
293                    .map(|group| &group.group)
294                    .collect(),
295                root: &duplication.root,
296                duplication_percentage: duplication.output.report.stats.duplication_percentage,
297                threshold: duplication.threshold,
298            }),
299            health: complexity.as_ref().map(|complexity| HealthView {
300                report: &complexity.report,
301                root: &complexity.root,
302                rules: &self.config.rules,
303                branching: None,
304            }),
305        }
306    }
307
308    fn dead_code_results_mut(&mut self) -> Option<&mut AnalysisResults> {
309        self.subanalyses
310            .dead_code
311            .as_mut()
312            .map(|dead_code| &mut dead_code.output.results)
313    }
314
315    fn health_report_mut(&mut self) -> Option<&mut fallow_output::HealthReport> {
316        self.subanalyses
317            .complexity
318            .as_mut()
319            .map(|complexity| &mut complexity.report)
320    }
321
322    fn record_type_aware_warning(&mut self, warning: &str) {
323        if let Some(meta) = self
324            .subanalyses
325            .dead_code
326            .as_mut()
327            .and_then(|dead_code| dead_code.output.meta.as_mut())
328            .and_then(|meta| meta.type_aware.as_mut())
329        {
330            meta.warnings.push(warning.to_owned());
331            meta.warning_count = meta.warnings.len();
332        }
333    }
334}
335
336/// Resolve the options against the `audit` config section with the
337/// precedence of `fallow audit`. `gate` and `css_deep` win over the config,
338/// as `--gate` and `--css-deep` / `--no-css-deep` do. `css` can only turn
339/// styling off, as `--no-css` does: the CLI has no flag that overrides
340/// `audit.css: false`.
341///
342/// The destructure names every field, so a new `audit` key does not compile
343/// until the typed route applies it, rejects it, or states why it does not
344/// apply.
345fn options_with_audit_config(
346    options: &AuditOptions,
347    config: &fallow_config::AuditConfig,
348) -> AuditOptions {
349    let fallow_config::AuditConfig {
350        gate,
351        worsened,
352        dead_code,
353        health,
354        dupes,
355        css,
356        css_deep,
357        // `reject_config_baselines` refuses these keys.
358        dead_code_baseline: _,
359        health_baseline: _,
360        dupes_baseline: _,
361        // The typed audit uses a temporary base worktree, not the persistent
362        // snapshot cache that this key ages out.
363        cache_max_age_days: _,
364        // `type_aware_config::reject_config_type_aware` refuses this key when
365        // it turns on type-aware analysis.
366        type_aware: _,
367    } = config;
368    let css = options.css != Some(false) && css.unwrap_or(true);
369    let css_deep = css && options.css_deep.or(*css_deep).unwrap_or(true);
370    AuditOptions {
371        gate: Some(options.gate.unwrap_or(*gate)),
372        worsened: Some(options.worsened.unwrap_or(*worsened)),
373        dead_code: Some(
374            options
375                .dead_code
376                .unwrap_or_else(|| dead_code.unwrap_or(true)),
377        ),
378        health: Some(options.health.unwrap_or_else(|| health.unwrap_or(true))),
379        duplication: Some(options.duplication.unwrap_or_else(|| dupes.unwrap_or(true))),
380        css: Some(css),
381        css_deep: Some(css_deep),
382        ..options.clone()
383    }
384}
385
386/// A selection without any domain is an error, as in `fallow audit`.
387fn reject_empty_selection(options: &AuditOptions) -> ProgrammaticResult<()> {
388    if options.dead_code == Some(false)
389        && options.health == Some(false)
390        && options.duplication == Some(false)
391    {
392        return Err(ProgrammaticError::new(
393            "this audit selects no domain: the options and the audit.deadCode, audit.health and audit.dupes config keys leave nothing to run",
394            2,
395        )
396        .with_code("FALLOW_AUDIT_NO_ANALYSIS")
397        .with_context("audit"));
398    }
399    Ok(())
400}
401
402/// The typed audit cannot apply the health and duplication baselines of the
403/// `audit` config section. Fail instead of ignoring them: an ignored baseline
404/// reports suppressed findings again and can fail the gate. The MCP `audit`
405/// tool reads this code and runs the CLI, which applies the baselines. The
406/// baseline of a skipped domain has no effect, as in `fallow audit`.
407fn reject_config_baselines(
408    config: &fallow_config::AuditConfig,
409    options: &AuditOptions,
410) -> ProgrammaticResult<()> {
411    let keys = [
412        (
413            "audit.deadCodeBaseline",
414            &config.dead_code_baseline,
415            options.dead_code,
416        ),
417        (
418            "audit.healthBaseline",
419            &config.health_baseline,
420            options.health,
421        ),
422        (
423            "audit.dupesBaseline",
424            &config.dupes_baseline,
425            options.duplication,
426        ),
427    ];
428    let Some((key, _, _)) = keys
429        .iter()
430        .find(|(_, value, runs)| value.is_some() && *runs != Some(false))
431    else {
432        return Ok(());
433    };
434    Err(ProgrammaticError::new(
435        format!("programmatic audit does not yet support the `{key}` config key; use the CLI path"),
436        2,
437    )
438    .with_code(AUDIT_CONFIG_BASELINE_UNSUPPORTED)
439    .with_context(*key))
440}
441
442fn validate_audit_api_options(options: &AuditOptions) -> ProgrammaticResult<()> {
443    if let Err(err) =
444        fallow_engine::health::validate_coverage_root_absolute(options.coverage_root.as_deref())
445    {
446        return Err(ProgrammaticError::new(err, 2)
447            .with_code("FALLOW_INVALID_COVERAGE_ROOT")
448            .with_context("audit.coverageRoot"));
449    }
450    if options.runtime_coverage.is_some() {
451        return Err(ProgrammaticError::new(
452            "programmatic audit does not yet support runtime coverage; use the CLI path",
453            2,
454        )
455        .with_code("FALLOW_AUDIT_RUNTIME_COVERAGE_UNSUPPORTED")
456        .with_context("audit.runtimeCoverage"));
457    }
458    Ok(())
459}
460
461pub(super) fn resolve_audit_base_ref(
462    options: &AuditOptions,
463) -> ProgrammaticResult<ResolvedAuditBase> {
464    let explicit = options
465        .base
466        .as_deref()
467        .or(options.analysis.changed_since.as_deref());
468    let root = options
469        .analysis
470        .root
471        .clone()
472        .unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")));
473    crate::audit_run::resolve_audit_base(&root, explicit).map_err(|error| match error {
474        crate::audit_run::AuditBaseError::InvalidRef {
475            origin,
476            value,
477            reason,
478        } => ProgrammaticError::new(format!("invalid git ref `{value}`: {reason}"), 2)
479            .with_code("FALLOW_INVALID_GIT_REF")
480            .with_context(match origin {
481                crate::audit_run::AuditBaseOrigin::Environment => "FALLOW_AUDIT_BASE",
482                crate::audit_run::AuditBaseOrigin::Explicit
483                | crate::audit_run::AuditBaseOrigin::Detected => "audit.base",
484            }),
485        crate::audit_run::AuditBaseError::NotDetected => ProgrammaticError::new(
486            "could not detect base branch. Set audit.base to specify the comparison target",
487            2,
488        )
489        .with_code("FALLOW_AUDIT_BASE_NOT_FOUND")
490        .with_context("audit.base"),
491    })
492}
493
494fn analysis_options_for_audit(options: &AuditOptions, base_ref: &str) -> AnalysisOptions {
495    let production_override = options
496        .analysis
497        .production_override
498        .or_else(|| options.production.then_some(true));
499    AnalysisOptions {
500        changed_since: Some(base_ref.to_string()),
501        production: production_override.unwrap_or(options.production),
502        production_override,
503        ..options.analysis.clone()
504    }
505}
506
507fn analysis_with_production(
508    analysis: &AnalysisOptions,
509    production_override: Option<bool>,
510) -> AnalysisOptions {
511    AnalysisOptions {
512        production: production_override.unwrap_or(analysis.production),
513        production_override: production_override.or(analysis.production_override),
514        ..analysis.clone()
515    }
516}
517
518fn empty_audit_output(
519    options: &AuditOptions,
520    base: ResolvedAuditBase,
521    root: &Path,
522    changed_files_count: usize,
523    elapsed: std::time::Duration,
524) -> AuditProgrammaticOutput {
525    AuditProgrammaticOutput {
526        verdict: AuditVerdict::Pass,
527        summary: AuditSummary {
528            dead_code_issues: 0,
529            dead_code_has_errors: false,
530            dead_code_skipped: options.dead_code == Some(false),
531            complexity_skipped: options.health == Some(false),
532            duplication_skipped: options.duplication == Some(false),
533            complexity_findings: 0,
534            max_cyclomatic: None,
535            duplication_clone_groups: 0,
536        },
537        attribution: AuditAttribution {
538            gate: options.gate.unwrap_or_default(),
539            worsened: options.worsened.unwrap_or_default(),
540            ..AuditAttribution::default()
541        },
542        changed_files_count,
543        base_ref: base.git_ref,
544        base_description: base.description,
545        head_sha: repo_refs::short_head_sha(root),
546        elapsed,
547        base_snapshot_skipped: None,
548        base_snapshot: None,
549        dead_code: None,
550        duplication: None,
551        complexity: None,
552        diff_risk: fallow_output::DiffRiskReport::default(),
553        next_steps: Vec::new(),
554        telemetry_analysis_run_id: None,
555    }
556}
557
558struct AuditSubanalyses {
559    /// `None` when the audit skips the dead-code domain.
560    dead_code: Option<crate::DeadCodeProgrammaticOutput>,
561    /// `None` when the audit skips the duplication domain.
562    duplication: Option<crate::DuplicationProgrammaticOutput>,
563    /// `None` when the audit skips the health domain.
564    complexity: Option<crate::HealthProgrammaticOutput>,
565}
566
567struct AuditSubanalysisOptions {
568    dead_code: DeadCodeOptions,
569    duplication: DuplicationOptions,
570    complexity: ComplexityOptions,
571}
572
573fn audit_subanalysis_options(
574    options: &AuditOptions,
575    analysis: &AnalysisOptions,
576    coverage_relocated: bool,
577) -> AuditSubanalysisOptions {
578    AuditSubanalysisOptions {
579        dead_code: DeadCodeOptions {
580            finding_ids: Vec::new(),
581            analysis: analysis_with_production(analysis, options.production_dead_code),
582            filters: DeadCodeFilters::default(),
583            files: Vec::new(),
584            include_entry_exports: options.include_entry_exports,
585            show_cascade: options.show_cascade,
586        },
587        duplication: DuplicationOptions {
588            analysis: analysis_with_production(analysis, options.production_dupes),
589            ..DuplicationOptions::default()
590        },
591        complexity: ComplexityOptions {
592            analysis: analysis_with_production(analysis, options.production_health),
593            max_crap: options.max_crap,
594            complexity: true,
595            css: options.css.unwrap_or(true),
596            css_deep: options.css.unwrap_or(true) && options.css_deep.unwrap_or(true),
597            coverage: options.coverage.clone(),
598            coverage_root: options.coverage_root.clone(),
599            coverage_relocated,
600            ..ComplexityOptions::default()
601        },
602    }
603}
604
605/// Resolve the context of one audit side or section.
606///
607/// Audit compares head and base findings against its own changed files, so it
608/// owns the change scope. No section reads `workspaces.changedSince`: the base
609/// snapshot may not be a Git repository, and a package map that hid a base
610/// finding would report the head finding as introduced.
611fn audit_section_context(
612    analysis: &AnalysisOptions,
613) -> ProgrammaticResult<ProgrammaticAnalysisContext> {
614    Ok(resolve_programmatic_analysis_context(analysis)?
615        .with_change_scope_owner(ChangeScopeOwner::CallerKeepingUnusedCode))
616}
617
618fn run_audit_subanalyses(
619    options: &AuditOptions,
620    analysis: &AnalysisOptions,
621    changed_files: Option<&FxHashSet<PathBuf>>,
622    coverage_relocated: bool,
623) -> ProgrammaticResult<AuditSubanalyses> {
624    let resolved = audit_section_context(analysis)?;
625    run_audit_subanalyses_in_context(
626        options,
627        analysis,
628        &resolved,
629        changed_files,
630        coverage_relocated,
631    )
632}
633
634fn run_audit_subanalyses_with_context(
635    options: &AuditOptions,
636    analysis: &AnalysisOptions,
637    resolved: &ProgrammaticAnalysisContext,
638    changed_files: Option<&FxHashSet<PathBuf>>,
639) -> ProgrammaticResult<AuditSubanalyses> {
640    run_audit_subanalyses_in_context(options, analysis, resolved, changed_files, false)
641}
642
643fn run_audit_subanalyses_in_context(
644    options: &AuditOptions,
645    analysis: &AnalysisOptions,
646    resolved: &ProgrammaticAnalysisContext,
647    changed_files: Option<&FxHashSet<PathBuf>>,
648    coverage_relocated: bool,
649) -> ProgrammaticResult<AuditSubanalyses> {
650    let subanalysis_options = audit_subanalysis_options(options, analysis, coverage_relocated);
651    let production_modes = resolve_effective_production_modes(
652        resolved,
653        options.production_dead_code,
654        options.production_health,
655        options.production_dupes,
656    )?;
657
658    // A partial selection runs each chosen domain on its own; the shared
659    // sessions below assume all three domains.
660    let dead_code = options.dead_code != Some(false);
661    let health = options.health != Some(false);
662    let duplication = options.duplication != Some(false);
663    if !(dead_code && health && duplication) {
664        return Ok(AuditSubanalyses {
665            dead_code: dead_code
666                .then(|| {
667                    run_dead_code_in_context(
668                        &subanalysis_options.dead_code,
669                        None,
670                        &audit_section_context(&subanalysis_options.dead_code.analysis)?,
671                    )
672                })
673                .transpose()?,
674            duplication: duplication
675                .then(|| {
676                    run_duplication_in_context(
677                        &subanalysis_options.duplication,
678                        &audit_section_context(&subanalysis_options.duplication.analysis)?,
679                    )
680                })
681                .transpose()?,
682            complexity: health
683                .then(|| run_health_for_audit(&subanalysis_options.complexity))
684                .transpose()?,
685        });
686    }
687
688    if production_modes.all_match() {
689        return run_shared_project_audit_subanalyses(&subanalysis_options, changed_files);
690    }
691
692    if production_modes.dead_code_matches_health() {
693        return run_shared_dead_code_health_audit_subanalyses(&subanalysis_options, changed_files);
694    }
695
696    if production_modes.dead_code_matches_dupes() {
697        return run_shared_dead_code_dupes_audit_subanalyses(&subanalysis_options, changed_files);
698    }
699
700    Ok(AuditSubanalyses {
701        dead_code: Some(run_dead_code_in_context(
702            &subanalysis_options.dead_code,
703            None,
704            &audit_section_context(&subanalysis_options.dead_code.analysis)?,
705        )?),
706        duplication: Some(run_duplication_in_context(
707            &subanalysis_options.duplication,
708            &audit_section_context(&subanalysis_options.duplication.analysis)?,
709        )?),
710        complexity: Some(run_health_for_audit(&subanalysis_options.complexity)?),
711    })
712}
713
714fn run_shared_project_audit_subanalyses(
715    options: &AuditSubanalysisOptions,
716    changed_files: Option<&FxHashSet<PathBuf>>,
717) -> ProgrammaticResult<AuditSubanalyses> {
718    let resolved = audit_section_context(&options.dead_code.analysis)?;
719    resolved.install(|| {
720        let session = super::dead_code::load_dead_code_session(&options.dead_code, &resolved)?;
721        run_all_audit_subanalyses_with_project_artifacts(
722            &options.dead_code,
723            &options.duplication,
724            &options.complexity,
725            &resolved,
726            &session,
727            changed_files,
728        )
729    })
730}
731
732fn run_shared_dead_code_health_audit_subanalyses(
733    options: &AuditSubanalysisOptions,
734    changed_files: Option<&FxHashSet<PathBuf>>,
735) -> ProgrammaticResult<AuditSubanalyses> {
736    let resolved = audit_section_context(&options.dead_code.analysis)?;
737    resolved.install(|| {
738        let dead_code_options = &options.dead_code;
739        let duplication_options = &options.duplication;
740        let complexity_options = &options.complexity;
741        let session = super::dead_code::load_dead_code_session(dead_code_options, &resolved)?;
742        let (dead_code, complexity) = run_dead_code_and_health_with_session(
743            dead_code_options,
744            complexity_options,
745            &resolved,
746            &session,
747            changed_files,
748        )?;
749        Ok(AuditSubanalyses {
750            dead_code: Some(dead_code),
751            duplication: Some(run_duplication_in_context(
752                duplication_options,
753                &audit_section_context(&duplication_options.analysis)?,
754            )?),
755            complexity: Some(complexity),
756        })
757    })
758}
759
760fn run_shared_dead_code_dupes_audit_subanalyses(
761    options: &AuditSubanalysisOptions,
762    changed_files: Option<&FxHashSet<PathBuf>>,
763) -> ProgrammaticResult<AuditSubanalyses> {
764    let resolved = audit_section_context(&options.dead_code.analysis)?;
765    resolved.install(|| {
766        let session = super::dead_code::load_dead_code_session(&options.dead_code, &resolved)?;
767        let (dead_code, duplication, _, _) =
768            run_dead_code_and_duplication_with_project_artifacts(ProjectArtifactAuditInput {
769                dead_code_options: &options.dead_code,
770                duplication_options: &options.duplication,
771                resolved: &resolved,
772                session: &session,
773                changed_files,
774                retain_dead_code_artifacts: false,
775                retain_duplication_artifacts: false,
776            })?;
777        Ok(AuditSubanalyses {
778            dead_code: Some(dead_code),
779            duplication: Some(duplication),
780            complexity: Some(run_health_for_audit(&options.complexity)?),
781        })
782    })
783}
784
785fn run_dead_code_and_duplication_with_project_artifacts(
786    input: ProjectArtifactAuditInput<'_>,
787) -> ProgrammaticResult<(
788    crate::DeadCodeProgrammaticOutput,
789    crate::DuplicationProgrammaticOutput,
790    Option<DeadCodeAnalysisArtifacts>,
791    Option<fallow_engine::duplicates::DuplicationReport>,
792)> {
793    let dupes_config = super::duplication::build_dupes_config(
794        input.duplication_options,
795        &input.session.config().duplicates,
796    );
797    let section_start = Instant::now();
798    let project = input
799        .session
800        .analyze_project_with_artifacts(
801            &dupes_config,
802            ProjectAnalysisArtifactOptions {
803                retain_complexity_artifacts: input.retain_dead_code_artifacts,
804                retain_graph: input.retain_dead_code_artifacts,
805                changed_files: input.changed_files.cloned(),
806                collect_source_fingerprints: false,
807            },
808        )
809        .map_err(|err| {
810            ProgrammaticError::new(format!("audit analysis failed: {err}"), 2)
811                .with_code("FALLOW_AUDIT_FAILED")
812                .with_context("audit")
813        })?;
814    let duplication_artifacts = input
815        .retain_duplication_artifacts
816        .then(|| project.duplication.clone());
817    let dead_code = super::dead_code::run_dead_code_from_artifacts(
818        input.dead_code_options,
819        input.resolved,
820        input.session,
821        input.changed_files,
822        project.dead_code,
823        section_start,
824    )?;
825    let duplication = super::duplication::run_duplication_report_with_session(
826        input.duplication_options,
827        input.resolved,
828        input.session,
829        project.duplication,
830        // Audit attributes clone groups against its own changed files.
831        &ChangeScope::default(),
832        section_start,
833    )?;
834    let super::dead_code::DeadCodeProgrammaticRunWithArtifacts {
835        output: dead_code,
836        artifacts,
837    } = dead_code;
838    let dead_code_artifacts = input.retain_dead_code_artifacts.then_some(artifacts);
839    Ok((
840        dead_code,
841        duplication,
842        dead_code_artifacts,
843        duplication_artifacts,
844    ))
845}
846
847#[derive(Clone, Copy)]
848struct ProjectArtifactAuditInput<'a> {
849    dead_code_options: &'a DeadCodeOptions,
850    duplication_options: &'a DuplicationOptions,
851    resolved: &'a ProgrammaticAnalysisContext,
852    session: &'a AnalysisSession,
853    changed_files: Option<&'a FxHashSet<PathBuf>>,
854    retain_dead_code_artifacts: bool,
855    retain_duplication_artifacts: bool,
856}
857
858fn run_all_audit_subanalyses_with_project_artifacts(
859    dead_code_options: &DeadCodeOptions,
860    duplication_options: &DuplicationOptions,
861    complexity_options: &ComplexityOptions,
862    resolved: &ProgrammaticAnalysisContext,
863    session: &AnalysisSession,
864    changed_files: Option<&FxHashSet<PathBuf>>,
865) -> ProgrammaticResult<AuditSubanalyses> {
866    let retain_dead_code_artifacts =
867        health_may_consume_dead_code_artifacts(complexity_options, session.config());
868    let retain_duplication_artifacts = health_may_consume_duplication_report(complexity_options);
869    let (dead_code, duplication, dead_code_artifacts, duplication_artifacts) =
870        run_dead_code_and_duplication_with_project_artifacts(ProjectArtifactAuditInput {
871            dead_code_options,
872            duplication_options,
873            resolved,
874            session,
875            changed_files,
876            retain_dead_code_artifacts,
877            retain_duplication_artifacts,
878        })?;
879    let complexity = run_health_with_session_artifacts(
880        complexity_options,
881        resolved,
882        session,
883        changed_files,
884        dead_code_artifacts,
885        duplication_artifacts,
886    )?;
887    Ok(AuditSubanalyses {
888        dead_code: Some(dead_code),
889        duplication: Some(duplication),
890        complexity: Some(complexity),
891    })
892}
893
894fn run_dead_code_and_health_with_session(
895    dead_code_options: &DeadCodeOptions,
896    complexity_options: &ComplexityOptions,
897    resolved: &ProgrammaticAnalysisContext,
898    session: &AnalysisSession,
899    changed_files: Option<&FxHashSet<PathBuf>>,
900) -> ProgrammaticResult<(
901    crate::DeadCodeProgrammaticOutput,
902    crate::HealthProgrammaticOutput,
903)> {
904    let reuse_dead_code_artifacts =
905        health_may_consume_dead_code_artifacts(complexity_options, session.config());
906    let (dead_code, dead_code_artifacts) = if reuse_dead_code_artifacts {
907        let dead_code = super::dead_code::run_dead_code_with_session_artifacts(
908            dead_code_options,
909            resolved,
910            session,
911            changed_files,
912            |_| {},
913            Instant::now(),
914        )?;
915        (dead_code.output, Some(dead_code.artifacts))
916    } else {
917        (
918            super::dead_code::run_dead_code_with_session(
919                dead_code_options,
920                resolved,
921                session,
922                changed_files,
923                |_| {},
924                Instant::now(),
925            )?,
926            None,
927        )
928    };
929    let complexity = run_health_with_session_artifacts(
930        complexity_options,
931        resolved,
932        session,
933        changed_files,
934        dead_code_artifacts,
935        None,
936    )?;
937    Ok((dead_code, complexity))
938}
939
940fn load_programmatic_audit_config(
941    resolved: &ProgrammaticAnalysisContext,
942) -> ProgrammaticResult<fallow_config::ResolvedConfig> {
943    fallow_engine::project_config::config_for_project_analysis(
944        resolved.root(),
945        resolved.config_path().as_deref(),
946        ProjectConfigOptions {
947            output: OutputFormat::Json,
948            no_cache: resolved.no_cache(),
949            threads: resolved.threads(),
950            production_override: resolved.production_override(),
951            quiet: true,
952            analysis: ProductionAnalysis::DeadCode,
953            allow_remote_extends: resolved.allow_remote_extends(),
954        },
955    )
956    .map(|project| project.config)
957    .map_err(|err| {
958        ProgrammaticError::new(format!("failed to load config: {err}"), 2)
959            .with_code("FALLOW_CONFIG_LOAD_FAILED")
960            .with_context("analysis.configPath")
961    })
962}
963
964fn audit_next_steps(
965    dead_code: Option<&crate::DeadCodeProgrammaticOutput>,
966    complexity: Option<&crate::HealthProgrammaticOutput>,
967) -> Vec<NextStep> {
968    let input = fallow_output::build_audit_next_steps_input(
969        dead_code.map(|dead_code| (&dead_code.output.results, dead_code.root.as_path())),
970        complexity.map(|complexity| &complexity.report),
971        crate::next_steps::suggestions_enabled(),
972    );
973    build_audit_next_steps(&input)
974}
975
976#[path = "audit_own_config.rs"]
977mod own_config;
978
979#[cfg(test)]
980#[path = "audit_orphaned_tests.rs"]
981mod orphaned_tests;
982
983#[cfg(test)]
984mod tests {
985    use std::process::Command;
986
987    use fallow_config::{AuditGate, FallowConfig, HealthConfig};
988    use fallow_types::output_format::OutputFormat;
989
990    use super::*;
991
992    fn resolved_config_with_max_crap(max_crap: f64) -> fallow_config::ResolvedConfig {
993        FallowConfig {
994            health: HealthConfig {
995                max_crap,
996                ..HealthConfig::default()
997            },
998            ..FallowConfig::default()
999        }
1000        .resolve(
1001            std::env::temp_dir().join("fallow-api-runtime-test"),
1002            OutputFormat::Json,
1003            1,
1004            true,
1005            true,
1006            None,
1007        )
1008    }
1009
1010    #[test]
1011    fn audit_complexity_only_health_does_not_retain_dead_code_artifacts() {
1012        let options = ComplexityOptions {
1013            complexity: true,
1014            ..ComplexityOptions::default()
1015        };
1016        let config = resolved_config_with_max_crap(0.0);
1017
1018        assert!(!health_may_consume_dead_code_artifacts(&options, &config));
1019    }
1020
1021    #[test]
1022    fn audit_health_artifact_reuse_tracks_config_max_crap() {
1023        let options = ComplexityOptions {
1024            complexity: true,
1025            ..ComplexityOptions::default()
1026        };
1027        let config = resolved_config_with_max_crap(30.0);
1028
1029        assert!(health_may_consume_dead_code_artifacts(&options, &config));
1030    }
1031
1032    #[test]
1033    fn audit_health_artifact_reuse_tracks_file_score_inputs() {
1034        let config = resolved_config_with_max_crap(0.0);
1035        for options in [
1036            ComplexityOptions {
1037                file_scores: true,
1038                ..ComplexityOptions::default()
1039            },
1040            ComplexityOptions {
1041                coverage_gaps: true,
1042                ..ComplexityOptions::default()
1043            },
1044            ComplexityOptions {
1045                targets: true,
1046                ..ComplexityOptions::default()
1047            },
1048            ComplexityOptions {
1049                score: true,
1050                ..ComplexityOptions::default()
1051            },
1052            ComplexityOptions {
1053                max_crap: Some(30.0),
1054                complexity: true,
1055                ..ComplexityOptions::default()
1056            },
1057        ] {
1058            assert!(health_may_consume_dead_code_artifacts(&options, &config));
1059        }
1060    }
1061
1062    #[test]
1063    fn audit_analysis_preserves_explicit_false_production_override() {
1064        let options = AuditOptions {
1065            production: false,
1066            analysis: AnalysisOptions {
1067                production: true,
1068                production_override: Some(false),
1069                ..AnalysisOptions::default()
1070            },
1071            ..AuditOptions::default()
1072        };
1073
1074        let analysis = analysis_options_for_audit(&options, "HEAD");
1075
1076        assert_eq!(analysis.production_override, Some(false));
1077        assert!(!analysis.production);
1078    }
1079
1080    #[test]
1081    fn audit_health_duplication_reuse_tracks_score_and_targets() {
1082        for options in [
1083            ComplexityOptions {
1084                score: true,
1085                ..ComplexityOptions::default()
1086            },
1087            ComplexityOptions {
1088                targets: true,
1089                ..ComplexityOptions::default()
1090            },
1091        ] {
1092            assert!(health_may_consume_duplication_report(&options));
1093        }
1094
1095        assert!(!health_may_consume_duplication_report(&ComplexityOptions {
1096            complexity: true,
1097            ..ComplexityOptions::default()
1098        }));
1099    }
1100
1101    #[test]
1102    fn run_audit_default_new_only_marks_untracked_added_file_introduced() {
1103        let project = audit_fixture();
1104        let output = run_audit(&AuditOptions {
1105            analysis: AnalysisOptions {
1106                root: Some(project.path().to_path_buf()),
1107                no_cache: true,
1108                explain: true,
1109                ..AnalysisOptions::default()
1110            },
1111            base: Some("HEAD".to_string()),
1112            gate: Some(AuditGate::NewOnly),
1113            ..AuditOptions::default()
1114        })
1115        .expect("audit output");
1116
1117        assert_eq!(output.verdict, AuditVerdict::Fail);
1118        assert_eq!(output.summary.dead_code_issues, 1);
1119        assert_eq!(output.attribution.dead_code_introduced, 1);
1120        assert!(output.base_snapshot.is_some());
1121
1122        let json = crate::serialize_audit_programmatic_json(output).expect("audit json");
1123        assert_eq!(json["schema_version"], fallow_output::AUDIT_SCHEMA_VERSION);
1124        assert_eq!(
1125            json["dead_code"]["unused_files"][0]["path"],
1126            "src/feature.ts"
1127        );
1128        assert_eq!(json["dead_code"]["unused_files"][0]["introduced"], true);
1129    }
1130
1131    #[test]
1132    fn run_audit_reports_diff_risk_findings_on_the_typed_route() {
1133        let project = audit_fixture();
1134        std::fs::write(
1135            project.path().join("src/index.ts"),
1136            "// eslint-disable-next-line no-console\nconsole.log('entry');\n",
1137        )
1138        .expect("write changed entry");
1139        let output = run_audit(&AuditOptions {
1140            analysis: AnalysisOptions {
1141                root: Some(project.path().to_path_buf()),
1142                no_cache: true,
1143                ..AnalysisOptions::default()
1144            },
1145            base: Some("HEAD".to_string()),
1146            gate: Some(AuditGate::NewOnly),
1147            ..AuditOptions::default()
1148        })
1149        .expect("audit output");
1150
1151        assert_eq!(output.diff_risk.findings.len(), 1);
1152        let json = crate::serialize_audit_programmatic_json(output).expect("audit json");
1153        assert_eq!(
1154            json["diff_risk"]["findings"][0]["rule"],
1155            "added-suppression"
1156        );
1157        assert_eq!(json["diff_risk"]["findings"][0]["path"], "src/index.ts");
1158        assert_eq!(json["diff_risk"]["findings"][0]["line"], 1);
1159        assert_eq!(json["attribution"]["diff_risk_introduced"], 1);
1160    }
1161
1162    #[test]
1163    fn run_audit_warn_only_dead_code_matches_cli_verdict_semantics() {
1164        let project = audit_fixture();
1165        std::fs::write(
1166            project.path().join(".fallowrc.json"),
1167            r#"{"rules":{"unused-files":"warn"}}"#,
1168        )
1169        .expect("write config");
1170
1171        let output = run_audit(&AuditOptions {
1172            analysis: AnalysisOptions {
1173                root: Some(project.path().to_path_buf()),
1174                no_cache: true,
1175                ..AnalysisOptions::default()
1176            },
1177            base: Some("HEAD".to_string()),
1178            gate: Some(AuditGate::All),
1179            ..AuditOptions::default()
1180        })
1181        .expect("audit output");
1182
1183        assert_eq!(output.verdict, AuditVerdict::Warn);
1184        assert!(!output.summary.dead_code_has_errors);
1185    }
1186
1187    #[test]
1188    fn run_audit_styling_error_matches_cli_for_new_only_and_all_gates() {
1189        let project = audit_styling_fixture();
1190        let root = project.path();
1191        std::fs::write(
1192            root.join("src/styles.css"),
1193            "#app .legacy .title { color: red; }\n.plain { color: blue; }\n",
1194        )
1195        .expect("write inherited-only change");
1196
1197        let all = run_audit(&AuditOptions {
1198            analysis: AnalysisOptions {
1199                root: Some(root.to_path_buf()),
1200                no_cache: true,
1201                ..AnalysisOptions::default()
1202            },
1203            base: Some("HEAD".to_string()),
1204            gate: Some(AuditGate::All),
1205            ..AuditOptions::default()
1206        })
1207        .expect("all-gate audit");
1208        assert_eq!(all.verdict, AuditVerdict::Fail);
1209
1210        let inherited_only = run_audit(&AuditOptions {
1211            analysis: AnalysisOptions {
1212                root: Some(root.to_path_buf()),
1213                no_cache: true,
1214                ..AnalysisOptions::default()
1215            },
1216            base: Some("HEAD".to_string()),
1217            gate: Some(AuditGate::NewOnly),
1218            ..AuditOptions::default()
1219        })
1220        .expect("new-only inherited audit");
1221        assert_eq!(inherited_only.verdict, AuditVerdict::Pass);
1222        assert!(inherited_only.base_snapshot.is_some());
1223        let inherited_json =
1224            crate::serialize_audit_programmatic_json(inherited_only).expect("inherited audit JSON");
1225        assert_eq!(
1226            inherited_json["complexity"]["styling_findings"][0]["introduced"],
1227            false
1228        );
1229
1230        std::fs::write(
1231            root.join("src/styles.css"),
1232            "#app .legacy .title { color: red; }\n.plain { color: blue; }\n#app .introduced .title { color: green; }\n",
1233        )
1234        .expect("write introduced styling change");
1235        let introduced = run_audit(&AuditOptions {
1236            analysis: AnalysisOptions {
1237                root: Some(root.to_path_buf()),
1238                no_cache: true,
1239                ..AnalysisOptions::default()
1240            },
1241            base: Some("HEAD".to_string()),
1242            gate: Some(AuditGate::NewOnly),
1243            ..AuditOptions::default()
1244        })
1245        .expect("new-only introduced audit");
1246        assert_eq!(introduced.verdict, AuditVerdict::Fail);
1247        let introduced_json =
1248            crate::serialize_audit_programmatic_json(introduced).expect("introduced audit JSON");
1249        let styling = introduced_json["complexity"]["styling_findings"]
1250            .as_array()
1251            .expect("styling findings");
1252        assert!(
1253            styling
1254                .iter()
1255                .any(|finding| finding["line"] == 1 && finding["introduced"] == false)
1256        );
1257        assert!(
1258            styling
1259                .iter()
1260                .any(|finding| finding["line"] == 3 && finding["introduced"] == true)
1261        );
1262    }
1263
1264    /// #2347: a pre-existing high-CRAP function must stay `introduced: false`
1265    /// when Istanbul coverage is supplied and an unrelated edit touches its
1266    /// file. The base snapshot analyzes a temporary worktree, so the coverage
1267    /// entries (recorded against the HEAD checkout) must be rebased onto that
1268    /// worktree; otherwise the base side falls back to the reachability
1269    /// estimate, scores below threshold, and the unchanged finding flips the
1270    /// new-only gate.
1271    #[test]
1272    fn run_audit_coverage_keeps_unchanged_function_inherited() {
1273        let project = tempfile::tempdir().expect("project");
1274        let root = project.path();
1275        std::fs::create_dir_all(root.join("src")).expect("create src");
1276        std::fs::write(
1277            root.join("package.json"),
1278            r#"{"name":"audit-api-coverage","type":"module","main":"src/index.ts","devDependencies":{"vitest":"^3.0.0"}}"#,
1279        )
1280        .expect("write package");
1281        std::fs::write(root.join("src/index.ts"), "console.log('entry');\n").expect("write entry");
1282        std::fs::write(
1283            root.join("src/branchy.ts"),
1284            "export function branchy(n: number): number {\n\
1285             \x20 if (n < 0) return -1;\n\
1286             \x20 if (n === 0) return 0;\n\
1287             \x20 if (n < 10) return 1;\n\
1288             \x20 if (n < 100) return 2;\n\
1289             \x20 if (n < 1000) return 3;\n\
1290             \x20 if (n < 10000) return 4;\n\
1291             \x20 return 5;\n\
1292             }\n",
1293        )
1294        .expect("write branchy");
1295        std::fs::write(
1296            root.join("src/branchy.test.ts"),
1297            "import { branchy } from './branchy';\nbranchy(1);\n",
1298        )
1299        .expect("write test reference");
1300        git(root, &["init"]);
1301        git(root, &["add", "."]);
1302        git(
1303            root,
1304            &[
1305                "-c",
1306                "user.email=test@example.com",
1307                "-c",
1308                "user.name=Test",
1309                "-c",
1310                "commit.gpgsign=false",
1311                "commit",
1312                "-m",
1313                "initial",
1314            ],
1315        );
1316        let mut source = std::fs::read_to_string(root.join("src/branchy.ts")).expect("branchy");
1317        source.push_str("branchy(-1);\n");
1318        std::fs::write(root.join("src/branchy.ts"), source).expect("append unrelated statement");
1319
1320        std::fs::create_dir_all(root.join("artifacts")).expect("create artifacts");
1321        let recorded = root.join("src/branchy.ts");
1322        let recorded = recorded.to_string_lossy().replace('\\', "\\\\");
1323        std::fs::write(
1324            root.join("artifacts/coverage-final.json"),
1325            format!(
1326                r#"{{"{recorded}":{{"path":"{recorded}","statementMap":{{}},"fnMap":{{"0":{{"name":"branchy","line":1,"decl":{{"start":{{"line":1,"column":16}},"end":{{"line":1,"column":23}}}},"loc":{{"start":{{"line":1,"column":44}},"end":{{"line":9,"column":1}}}}}}}},"branchMap":{{}},"s":{{}},"f":{{"0":0}},"b":{{}}}}}}"#
1327            ),
1328        )
1329        .expect("write coverage");
1330
1331        let output = run_audit(&AuditOptions {
1332            analysis: AnalysisOptions {
1333                root: Some(root.to_path_buf()),
1334                no_cache: true,
1335                ..AnalysisOptions::default()
1336            },
1337            base: Some("HEAD".to_string()),
1338            gate: Some(AuditGate::NewOnly),
1339            max_crap: Some(10.0),
1340            coverage: Some(root.join("artifacts/coverage-final.json")),
1341            ..AuditOptions::default()
1342        })
1343        .expect("audit output");
1344
1345        assert_eq!(output.attribution.complexity_introduced, 0);
1346        assert_eq!(output.attribution.complexity_inherited, 1);
1347        assert_eq!(output.verdict, AuditVerdict::Pass);
1348        let json = crate::serialize_audit_programmatic_json(output).expect("audit json");
1349        let findings = json["complexity"]["findings"]
1350            .as_array()
1351            .expect("complexity findings");
1352        let branchy = findings
1353            .iter()
1354            .find(|finding| finding["name"] == "branchy")
1355            .expect("branchy reported above the CRAP threshold with 0% measured coverage");
1356        assert_eq!(branchy["introduced"], false);
1357        assert_eq!(branchy["coverage_source"], "istanbul");
1358    }
1359
1360    #[test]
1361    fn audit_production_mode_branches_preserve_per_section_workspace_scope() {
1362        let project = audit_workspace_modes_fixture("");
1363
1364        for mask in 0_u8..8 {
1365            let modes = ProductionModesMask::from(mask);
1366            let output = run_audit(&AuditOptions {
1367                production_dead_code: Some(modes.dead_code),
1368                production_health: Some(modes.health),
1369                production_dupes: Some(modes.dupes),
1370                ..workspace_modes_audit_options(project.path())
1371            })
1372            .unwrap_or_else(|error| panic!("audit mask {mask:03b} failed: {error}"));
1373            assert_audit_sections_follow_modes(output, modes, mask);
1374        }
1375    }
1376
1377    /// The per-section modes may also come only from the config file. Audit
1378    /// must compare the modes after config resolution: with no overrides the
1379    /// raw options are all `None` and look equal even when the sections
1380    /// differ.
1381    #[test]
1382    fn audit_config_production_modes_scope_each_section() {
1383        for mask in 0_u8..8 {
1384            let modes = ProductionModesMask::from(mask);
1385            let project = audit_workspace_modes_fixture(&format!(
1386                r#","production":{{"deadCode":{},"health":{},"dupes":{}}}"#,
1387                modes.dead_code, modes.health, modes.dupes
1388            ));
1389            let output = run_audit(&workspace_modes_audit_options(project.path()))
1390                .unwrap_or_else(|error| panic!("audit mask {mask:03b} failed: {error}"));
1391            assert_audit_sections_follow_modes(output, modes, mask);
1392        }
1393    }
1394
1395    #[derive(Clone, Copy)]
1396    struct ProductionModesMask {
1397        dead_code: bool,
1398        health: bool,
1399        dupes: bool,
1400    }
1401
1402    impl From<u8> for ProductionModesMask {
1403        fn from(mask: u8) -> Self {
1404            Self {
1405                dead_code: mask & 0b001 != 0,
1406                health: mask & 0b010 != 0,
1407                dupes: mask & 0b100 != 0,
1408            }
1409        }
1410    }
1411
1412    fn workspace_modes_audit_options(root: &Path) -> AuditOptions {
1413        AuditOptions {
1414            analysis: AnalysisOptions {
1415                root: Some(root.to_path_buf()),
1416                workspace: Some(vec!["@audit/a".to_string()]),
1417                no_cache: true,
1418                ..AnalysisOptions::default()
1419            },
1420            base: Some("HEAD".to_string()),
1421            gate: Some(AuditGate::All),
1422            include_entry_exports: true,
1423            ..AuditOptions::default()
1424        }
1425    }
1426
1427    fn assert_audit_sections_follow_modes(
1428        output: AuditProgrammaticOutput,
1429        modes: ProductionModesMask,
1430        mask: u8,
1431    ) {
1432        let json = crate::serialize_audit_programmatic_json(output)
1433            .unwrap_or_else(|error| panic!("serialize mask {mask:03b}: {error}"));
1434
1435        let dead_code = json["dead_code"].to_string();
1436        let complexity = json["complexity"].to_string();
1437        let duplication = json["duplication"].to_string();
1438        assert_eq!(
1439            dead_code.contains("mode-sentinel.test.ts"),
1440            !modes.dead_code,
1441            "dead-code scope mismatch for mask {mask:03b}: {dead_code}"
1442        );
1443        assert_eq!(
1444            complexity.contains("mode-sentinel.test.ts"),
1445            !modes.health,
1446            "health scope mismatch for mask {mask:03b}: {complexity}"
1447        );
1448        assert_eq!(
1449            duplication.contains("mode-sentinel.test.ts"),
1450            !modes.dupes,
1451            "duplication scope mismatch for mask {mask:03b}: {duplication}"
1452        );
1453
1454        for section in [&dead_code, &complexity] {
1455            assert!(
1456                !section.contains("packages/b"),
1457                "workspace B leaked into mask {mask:03b}: {section}"
1458            );
1459        }
1460        // A clone group is in scope when one of its instances is, and it
1461        // keeps every instance, so a copy in workspace B may show next to
1462        // the copy in workspace A. No group may be only in workspace B.
1463        for group in json["duplication"]["clone_groups"]
1464            .as_array()
1465            .into_iter()
1466            .flatten()
1467        {
1468            assert!(
1469                group["instances"]
1470                    .as_array()
1471                    .into_iter()
1472                    .flatten()
1473                    .any(|instance| instance["file"]
1474                        .as_str()
1475                        .is_some_and(|file| file.starts_with("packages/a/"))),
1476                "a clone group outside workspace A leaked into mask {mask:03b}: {group}"
1477            );
1478        }
1479    }
1480
1481    #[test]
1482    fn empty_audit_output_uses_resolved_root_for_head_sha() {
1483        let project = audit_fixture();
1484        let output = empty_audit_output(
1485            &AuditOptions {
1486                analysis: AnalysisOptions {
1487                    root: None,
1488                    ..AnalysisOptions::default()
1489                },
1490                base: Some("HEAD".to_string()),
1491                gate: Some(AuditGate::NewOnly),
1492                ..AuditOptions::default()
1493            },
1494            ResolvedAuditBase {
1495                git_ref: "HEAD".to_string(),
1496                description: None,
1497                inherited_refs: Vec::new(),
1498            },
1499            project.path(),
1500            0,
1501            std::time::Duration::ZERO,
1502        );
1503
1504        assert!(output.head_sha.is_some());
1505    }
1506
1507    fn audit_fixture() -> tempfile::TempDir {
1508        let project = tempfile::tempdir().expect("project");
1509        std::fs::create_dir_all(project.path().join("src")).expect("create src");
1510        std::fs::write(
1511            project.path().join("package.json"),
1512            r#"{"name":"audit-api","type":"module","main":"src/index.ts"}"#,
1513        )
1514        .expect("write package");
1515        std::fs::write(
1516            project.path().join("src/index.ts"),
1517            "console.log('entry');\n",
1518        )
1519        .expect("write entry");
1520        git(project.path(), &["init"]);
1521        git(project.path(), &["add", "."]);
1522        git(
1523            project.path(),
1524            &[
1525                "-c",
1526                "user.email=test@example.com",
1527                "-c",
1528                "user.name=Test",
1529                "-c",
1530                "commit.gpgsign=false",
1531                "commit",
1532                "-m",
1533                "initial",
1534            ],
1535        );
1536        std::fs::write(
1537            project.path().join("src/feature.ts"),
1538            "export const unused = 1;\n",
1539        )
1540        .expect("write changed source");
1541        project
1542    }
1543
1544    fn audit_styling_fixture() -> tempfile::TempDir {
1545        let project = tempfile::tempdir().expect("project");
1546        std::fs::create_dir_all(project.path().join("src")).expect("create src");
1547        std::fs::write(
1548            project.path().join("package.json"),
1549            r#"{"name":"audit-api-styling","type":"module","main":"src/index.ts"}"#,
1550        )
1551        .expect("write package");
1552        std::fs::write(
1553            project.path().join(".fallowrc.json"),
1554            r#"{"rules":{"css-selector-complexity":"error"}}"#,
1555        )
1556        .expect("write config");
1557        std::fs::write(
1558            project.path().join("src/index.ts"),
1559            "console.log('entry');\n",
1560        )
1561        .expect("write entry");
1562        std::fs::write(
1563            project.path().join("src/styles.css"),
1564            "#app .legacy .title { color: red; }\n",
1565        )
1566        .expect("write inherited styling");
1567        git(project.path(), &["init"]);
1568        git(project.path(), &["add", "."]);
1569        git(
1570            project.path(),
1571            &[
1572                "-c",
1573                "user.email=test@example.com",
1574                "-c",
1575                "user.name=Test",
1576                "-c",
1577                "commit.gpgsign=false",
1578                "commit",
1579                "-m",
1580                "initial",
1581            ],
1582        );
1583        project
1584    }
1585
1586    /// `extra_config` is appended to the top-level `.fallowrc.json` object.
1587    fn audit_workspace_modes_fixture(extra_config: &str) -> tempfile::TempDir {
1588        let project = tempfile::tempdir().expect("project");
1589        std::fs::write(
1590            project.path().join("package.json"),
1591            r#"{"name":"audit-root","private":true,"workspaces":["packages/*"]}"#,
1592        )
1593        .expect("write root package");
1594        std::fs::write(
1595            project.path().join(".fallowrc.json"),
1596            format!(
1597                r#"{{
1598  "duplicates": {{
1599    "minTokens": 10,
1600    "minLines": 2,
1601    "ignoreDefaults": false
1602  }},
1603  "health": {{
1604    "maxCyclomatic": 2,
1605    "maxCognitive": 2,
1606    "maxCrap": 2.0,
1607    "maxUnitSize": 3
1608  }}{extra_config}
1609}}"#
1610            ),
1611        )
1612        .expect("write config");
1613
1614        for name in ["a", "b"] {
1615            let package = project.path().join("packages").join(name);
1616            std::fs::create_dir_all(package.join("src")).expect("create package source");
1617            std::fs::write(
1618                package.join("package.json"),
1619                format!(r#"{{"name":"@audit/{name}","type":"module","main":"src/index.ts"}}"#),
1620            )
1621            .expect("write package manifest");
1622            std::fs::write(
1623                package.join("src/index.ts"),
1624                format!("export const {name}Entry = true;\n"),
1625            )
1626            .expect("write package entry");
1627        }
1628
1629        git(project.path(), &["init"]);
1630        git(project.path(), &["add", "."]);
1631        git(
1632            project.path(),
1633            &[
1634                "-c",
1635                "user.email=test@example.com",
1636                "-c",
1637                "user.name=Test",
1638                "-c",
1639                "commit.gpgsign=false",
1640                "commit",
1641                "-m",
1642                "initial",
1643            ],
1644        );
1645
1646        let sentinel = r"export function auditModeSentinel(value: number) {
1647  let result = value;
1648  if (value > 0) result += 1;
1649  if (value > 1) result += 2;
1650  if (value > 2) result += 3;
1651  if (value > 3) result += 4;
1652  return result;
1653}
1654";
1655        for name in ["a", "b"] {
1656            let source = project.path().join("packages").join(name).join("src");
1657            std::fs::write(source.join("mode-sentinel.test.ts"), sentinel)
1658                .expect("write test sentinel");
1659            std::fs::write(source.join("mode-sentinel-copy.test.ts"), sentinel)
1660                .expect("write duplicate test sentinel");
1661        }
1662
1663        project
1664    }
1665
1666    fn git(root: &Path, args: &[&str]) {
1667        let status = fallow_engine::changed_files::clear_ambient_git_env(&mut Command::new("git"))
1668            .args(args)
1669            .current_dir(root)
1670            .status()
1671            .expect("git command");
1672        assert!(status.success(), "git {args:?} failed");
1673    }
1674
1675    /// #2699: the auto-detect fallthrough gets the same ref validation as the
1676    /// explicit and environment paths, so a malformed detection surfaces as a
1677    /// base-ref error instead of a changed-files failure deeper in the run.
1678    #[test]
1679    fn resolve_audit_base_ref_validates_the_auto_detected_ref() {
1680        let project = tempfile::tempdir().expect("temp dir");
1681        let root = project.path();
1682        std::fs::write(root.join("index.ts"), "export const used = 1;\n").expect("write entry");
1683        git(root, &["init", "-b", "main"]);
1684        git(root, &["add", "."]);
1685        git(
1686            root,
1687            &[
1688                "-c",
1689                "user.email=test@example.com",
1690                "-c",
1691                "user.name=Test",
1692                "-c",
1693                "commit.gpgsign=false",
1694                "commit",
1695                "-m",
1696                "initial",
1697            ],
1698        );
1699        git(root, &["update-ref", "refs/remotes/origin/main", "main"]);
1700        git(
1701            root,
1702            &[
1703                "symbolic-ref",
1704                "refs/remotes/origin/HEAD",
1705                "refs/remotes/origin/main",
1706            ],
1707        );
1708        let options = AuditOptions {
1709            analysis: AnalysisOptions {
1710                root: Some(root.to_path_buf()),
1711                ..AnalysisOptions::default()
1712            },
1713            ..AuditOptions::default()
1714        };
1715
1716        let resolved = resolve_audit_base_ref(&options).expect("base ref resolves");
1717
1718        assert!(
1719            fallow_engine::validate::validate_git_ref(&resolved.git_ref).is_ok(),
1720            "auto-detected ref must be usable as a git ref: {:?}",
1721            resolved.git_ref
1722        );
1723        assert_eq!(
1724            resolved.description.as_deref(),
1725            Some("merge-base with origin/main")
1726        );
1727    }
1728
1729    fn registered_worktree_count(root: &Path) -> usize {
1730        let output = fallow_engine::changed_files::clear_ambient_git_env(&mut Command::new("git"))
1731            .args(["worktree", "list", "--porcelain"])
1732            .current_dir(root)
1733            .output()
1734            .expect("git worktree list");
1735        assert!(output.status.success(), "git worktree list failed");
1736        String::from_utf8_lossy(&output.stdout)
1737            .lines()
1738            .filter(|line| line.starts_with("worktree "))
1739            .count()
1740    }
1741
1742    /// #3885: the base snapshot of the programmatic audit, which MCP also
1743    /// uses, is not registered with Git while the base analysis reads it.
1744    #[test]
1745    fn programmatic_base_snapshot_is_unregistered_during_base_analysis() {
1746        use crate::audit_run::AuditBackend as _;
1747
1748        let project = tempfile::tempdir().expect("temp dir");
1749        let root = project.path();
1750        std::fs::write(
1751            root.join("package.json"),
1752            r#"{"name":"base-snapshot","main":"index.ts"}"#,
1753        )
1754        .expect("write manifest");
1755        std::fs::write(root.join("index.ts"), "export const used = 1;\n").expect("write entry");
1756        git(root, &["init", "-b", "main"]);
1757        git(root, &["add", "."]);
1758        git(
1759            root,
1760            &[
1761                "-c",
1762                "user.email=test@example.com",
1763                "-c",
1764                "user.name=Test",
1765                "-c",
1766                "commit.gpgsign=false",
1767                "commit",
1768                "-m",
1769                "initial",
1770            ],
1771        );
1772        let options = AuditOptions {
1773            analysis: AnalysisOptions {
1774                root: Some(root.to_path_buf()),
1775                ..AnalysisOptions::default()
1776            },
1777            ..AuditOptions::default()
1778        };
1779        let analysis = analysis_options_for_audit(&options, "HEAD");
1780        let resolved = audit_section_context(&analysis).expect("context resolves");
1781        let config = load_programmatic_audit_config(&resolved).expect("config loads");
1782        let backend = ProgrammaticAuditBackend {
1783            options: &options,
1784            analysis: &analysis,
1785            resolved: &resolved,
1786            config: &config,
1787        };
1788
1789        let checkout = backend
1790            .create_base_checkout("HEAD", None)
1791            .unwrap_or_else(|_| panic!("base checkout is created"));
1792        assert_eq!(
1793            registered_worktree_count(root),
1794            1,
1795            "only the main worktree may be registered while the base analysis runs"
1796        );
1797        let base = backend
1798            .run_base(checkout.path(), None)
1799            .unwrap_or_else(|_| panic!("base analysis runs on the unregistered snapshot"));
1800        assert!(base.subanalyses.dead_code.is_some());
1801        assert_eq!(registered_worktree_count(root), 1);
1802
1803        let path = checkout.path().to_path_buf();
1804        drop(checkout);
1805        assert!(!path.exists(), "the base snapshot is removed on drop");
1806        assert_eq!(registered_worktree_count(root), 1);
1807    }
1808
1809    #[cfg(unix)]
1810    fn commit_all(root: &Path, message: &str) {
1811        git(root, &["add", "-f", "."]);
1812        git(
1813            root,
1814            &[
1815                "-c",
1816                "user.email=test@example.com",
1817                "-c",
1818                "user.name=Test",
1819                "-c",
1820                "commit.gpgsign=false",
1821                "commit",
1822                "-m",
1823                message,
1824            ],
1825        );
1826    }
1827
1828    /// The base commit is untrusted. A gitdir that it commits under the name
1829    /// of the snapshot stub, or as a nested bare repository, must not run its
1830    /// config during the audit.
1831    #[cfg(unix)]
1832    #[test]
1833    fn audit_never_runs_a_git_config_from_the_base_commit() {
1834        let project = tempfile::tempdir().expect("temp dir");
1835        let root = project.path().join("repo");
1836        let marker = project.path().join("fsmonitor-ran");
1837        std::fs::create_dir_all(&root).expect("create repo");
1838        std::fs::write(
1839            root.join("package.json"),
1840            r#"{"name":"crafted-base","main":"index.ts"}"#,
1841        )
1842        .expect("write manifest");
1843        std::fs::write(root.join("index.ts"), "export const used = 1;\n").expect("write entry");
1844        for dir in ["fallow-audit-unregistered", "pkg"] {
1845            let gitdir = root.join(dir);
1846            std::fs::create_dir_all(gitdir.join("objects")).expect("create objects");
1847            std::fs::create_dir_all(gitdir.join("refs")).expect("create refs");
1848            std::fs::write(gitdir.join("objects/.keep"), "").expect("write keep");
1849            std::fs::write(gitdir.join("refs/.keep"), "").expect("write keep");
1850            std::fs::write(gitdir.join("HEAD"), "ref: refs/heads/main\n").expect("write HEAD");
1851            std::fs::write(
1852                gitdir.join("config"),
1853                format!(
1854                    "[core]\n\trepositoryformatversion = 0\n\tfsmonitor = \"touch '{}'; false\"\n",
1855                    marker.display()
1856                ),
1857            )
1858            .expect("write config");
1859        }
1860        git(&root, &["init", "-b", "main"]);
1861        commit_all(&root, "base");
1862        std::fs::write(root.join("index.ts"), "export const used = 2;\n").expect("change entry");
1863        commit_all(&root, "head");
1864        let options = AuditOptions {
1865            analysis: AnalysisOptions {
1866                root: Some(root),
1867                ..AnalysisOptions::default()
1868            },
1869            base: Some("HEAD~1".to_owned()),
1870            ..AuditOptions::default()
1871        };
1872
1873        let output = run_audit(&options).unwrap_or_else(|_| panic!("audit runs"));
1874
1875        assert!(output.base_snapshot.is_some(), "the base pass must run");
1876        assert!(
1877            !marker.exists(),
1878            "a Git config from the base commit ran a command"
1879        );
1880    }
1881
1882    /// #3885: a programmatic audit removes the snapshots of a dead owner,
1883    /// registered or not, and keeps the snapshot of a live owner. The dead
1884    /// owner's snapshots are made older than the age floor of the cleanup.
1885    #[cfg(unix)]
1886    #[test]
1887    fn audit_removes_snapshots_of_dead_owners_only() {
1888        const DEAD_PID: u32 = 99_999_998;
1889        assert!(!fallow_engine::repo_refs::process_is_alive(DEAD_PID));
1890        let project = tempfile::tempdir().expect("temp dir");
1891        let root = project.path().join("repo");
1892        std::fs::create_dir_all(&root).expect("create repo");
1893        std::fs::write(
1894            root.join("package.json"),
1895            r#"{"name":"orphans","main":"index.ts"}"#,
1896        )
1897        .expect("write manifest");
1898        std::fs::write(root.join("index.ts"), "export const used = 1;\n").expect("write entry");
1899        git(&root, &["init", "-b", "main"]);
1900        commit_all(&root, "base");
1901        std::fs::write(root.join("index.ts"), "export const used = 2;\n").expect("change entry");
1902        commit_all(&root, "head");
1903
1904        let nanos = std::time::SystemTime::now()
1905            .duration_since(std::time::UNIX_EPOCH)
1906            .expect("clock after epoch")
1907            .as_nanos();
1908        let temp = std::env::temp_dir();
1909        let dead = temp.join(format!("fallow-audit-base-{DEAD_PID}-{nanos}-0"));
1910        let dead_registered = temp.join(format!("fallow-audit-base-{DEAD_PID}-{nanos}-1"));
1911        let alive = temp.join(format!(
1912            "fallow-audit-base-{}-{nanos}-900000",
1913            std::process::id()
1914        ));
1915        for dir in [&dead, &alive] {
1916            std::fs::create_dir_all(dir).expect("create leftover");
1917            std::fs::write(dir.join("index.ts"), "").expect("write leftover file");
1918        }
1919        git(
1920            &root,
1921            &[
1922                "worktree",
1923                "add",
1924                "--detach",
1925                "--quiet",
1926                dead_registered.to_str().expect("UTF-8 path"),
1927                "HEAD",
1928            ],
1929        );
1930        let old = std::time::SystemTime::now()
1931            - fallow_engine::repo_refs::ORPHAN_MIN_AGE
1932            - std::time::Duration::from_secs(60);
1933        for dir in [&dead, &dead_registered, &alive] {
1934            std::fs::File::open(dir)
1935                .and_then(|handle| handle.set_modified(old))
1936                .expect("age the leftover");
1937        }
1938        assert_eq!(registered_worktree_count(&root), 2);
1939        let options = AuditOptions {
1940            analysis: AnalysisOptions {
1941                root: Some(root.clone()),
1942                ..AnalysisOptions::default()
1943            },
1944            base: Some("HEAD~1".to_owned()),
1945            ..AuditOptions::default()
1946        };
1947
1948        let output = run_audit(&options).unwrap_or_else(|_| panic!("audit runs"));
1949
1950        let alive_kept = alive.is_dir();
1951        let _ = std::fs::remove_dir_all(&alive);
1952        assert!(output.base_snapshot.is_some(), "the base pass must run");
1953        assert!(!dead.exists(), "the leftover of a dead owner is removed");
1954        assert!(!dead_registered.exists());
1955        assert_eq!(
1956            registered_worktree_count(&root),
1957            1,
1958            "the registration of a dead owner is removed"
1959        );
1960        assert!(alive_kept, "the snapshot of a live owner stays");
1961    }
1962}