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