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