Skip to main content

fallow_api/runtime/
audit.rs

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