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
990    use fallow_config::{AuditGate, FallowConfig, HealthConfig};
991    use fallow_types::output_format::OutputFormat;
992
993    use super::*;
994
995    fn resolved_config_with_max_crap(max_crap: f64) -> fallow_config::ResolvedConfig {
996        FallowConfig {
997            health: HealthConfig {
998                max_crap,
999                ..HealthConfig::default()
1000            },
1001            ..FallowConfig::default()
1002        }
1003        .resolve(
1004            std::env::temp_dir().join("fallow-api-runtime-test"),
1005            OutputFormat::Json,
1006            1,
1007            true,
1008            true,
1009            None,
1010        )
1011    }
1012
1013    #[test]
1014    fn audit_complexity_only_health_does_not_retain_dead_code_artifacts() {
1015        let options = ComplexityOptions {
1016            complexity: true,
1017            ..ComplexityOptions::default()
1018        };
1019        let config = resolved_config_with_max_crap(0.0);
1020
1021        assert!(!health_may_consume_dead_code_artifacts(&options, &config));
1022    }
1023
1024    #[test]
1025    fn audit_health_artifact_reuse_tracks_config_max_crap() {
1026        let options = ComplexityOptions {
1027            complexity: true,
1028            ..ComplexityOptions::default()
1029        };
1030        let config = resolved_config_with_max_crap(30.0);
1031
1032        assert!(health_may_consume_dead_code_artifacts(&options, &config));
1033    }
1034
1035    #[test]
1036    fn audit_health_artifact_reuse_tracks_file_score_inputs() {
1037        let config = resolved_config_with_max_crap(0.0);
1038        for options in [
1039            ComplexityOptions {
1040                file_scores: true,
1041                ..ComplexityOptions::default()
1042            },
1043            ComplexityOptions {
1044                coverage_gaps: true,
1045                ..ComplexityOptions::default()
1046            },
1047            ComplexityOptions {
1048                targets: true,
1049                ..ComplexityOptions::default()
1050            },
1051            ComplexityOptions {
1052                score: true,
1053                ..ComplexityOptions::default()
1054            },
1055            ComplexityOptions {
1056                max_crap: Some(30.0),
1057                complexity: true,
1058                ..ComplexityOptions::default()
1059            },
1060        ] {
1061            assert!(health_may_consume_dead_code_artifacts(&options, &config));
1062        }
1063    }
1064
1065    #[test]
1066    fn audit_analysis_preserves_explicit_false_production_override() {
1067        let options = AuditOptions {
1068            production: false,
1069            analysis: AnalysisOptions {
1070                production: true,
1071                production_override: Some(false),
1072                ..AnalysisOptions::default()
1073            },
1074            ..AuditOptions::default()
1075        };
1076
1077        let analysis = analysis_options_for_audit(&options, "HEAD");
1078
1079        assert_eq!(analysis.production_override, Some(false));
1080        assert!(!analysis.production);
1081    }
1082
1083    #[test]
1084    fn audit_health_duplication_reuse_tracks_score_and_targets() {
1085        for options in [
1086            ComplexityOptions {
1087                score: true,
1088                ..ComplexityOptions::default()
1089            },
1090            ComplexityOptions {
1091                targets: true,
1092                ..ComplexityOptions::default()
1093            },
1094        ] {
1095            assert!(health_may_consume_duplication_report(&options));
1096        }
1097
1098        assert!(!health_may_consume_duplication_report(&ComplexityOptions {
1099            complexity: true,
1100            ..ComplexityOptions::default()
1101        }));
1102    }
1103
1104    #[test]
1105    fn run_audit_default_new_only_marks_untracked_added_file_introduced() {
1106        let project = audit_fixture();
1107        let output = run_audit(&AuditOptions {
1108            analysis: AnalysisOptions {
1109                root: Some(project.path().to_path_buf()),
1110                no_cache: true,
1111                explain: true,
1112                ..AnalysisOptions::default()
1113            },
1114            base: Some("HEAD".to_string()),
1115            gate: Some(AuditGate::NewOnly),
1116            ..AuditOptions::default()
1117        })
1118        .expect("audit output");
1119
1120        assert_eq!(output.verdict, AuditVerdict::Fail);
1121        assert_eq!(output.summary.dead_code_issues, 1);
1122        assert_eq!(output.attribution.dead_code_introduced, 1);
1123        assert!(output.base_snapshot.is_some());
1124
1125        let json = crate::serialize_audit_programmatic_json(output).expect("audit json");
1126        assert_eq!(json["schema_version"], fallow_output::AUDIT_SCHEMA_VERSION);
1127        assert_eq!(
1128            json["dead_code"]["unused_files"][0]["path"],
1129            "src/feature.ts"
1130        );
1131        assert_eq!(json["dead_code"]["unused_files"][0]["introduced"], true);
1132    }
1133
1134    #[test]
1135    fn run_audit_reports_diff_risk_findings_on_the_typed_route() {
1136        let project = audit_fixture();
1137        std::fs::write(
1138            project.path().join("src/index.ts"),
1139            "// eslint-disable-next-line no-console\nconsole.log('entry');\n",
1140        )
1141        .expect("write changed entry");
1142        let output = run_audit(&AuditOptions {
1143            analysis: AnalysisOptions {
1144                root: Some(project.path().to_path_buf()),
1145                no_cache: true,
1146                ..AnalysisOptions::default()
1147            },
1148            base: Some("HEAD".to_string()),
1149            gate: Some(AuditGate::NewOnly),
1150            ..AuditOptions::default()
1151        })
1152        .expect("audit output");
1153
1154        assert_eq!(output.diff_risk.findings.len(), 1);
1155        let json = crate::serialize_audit_programmatic_json(output).expect("audit json");
1156        assert_eq!(
1157            json["diff_risk"]["findings"][0]["rule"],
1158            "added-suppression"
1159        );
1160        assert_eq!(json["diff_risk"]["findings"][0]["path"], "src/index.ts");
1161        assert_eq!(json["diff_risk"]["findings"][0]["line"], 1);
1162        assert_eq!(json["attribution"]["diff_risk_introduced"], 1);
1163    }
1164
1165    #[test]
1166    fn run_audit_warn_only_dead_code_matches_cli_verdict_semantics() {
1167        let project = audit_fixture();
1168        std::fs::write(
1169            project.path().join(".fallowrc.json"),
1170            r#"{"rules":{"unused-files":"warn"}}"#,
1171        )
1172        .expect("write config");
1173
1174        let output = run_audit(&AuditOptions {
1175            analysis: AnalysisOptions {
1176                root: Some(project.path().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("audit output");
1185
1186        assert_eq!(output.verdict, AuditVerdict::Warn);
1187        assert!(!output.summary.dead_code_has_errors);
1188    }
1189
1190    #[test]
1191    fn run_audit_styling_error_matches_cli_for_new_only_and_all_gates() {
1192        let project = audit_styling_fixture();
1193        let root = project.path();
1194        std::fs::write(
1195            root.join("src/styles.css"),
1196            "#app .legacy .title { color: red; }\n.plain { color: blue; }\n",
1197        )
1198        .expect("write inherited-only change");
1199
1200        let all = run_audit(&AuditOptions {
1201            analysis: AnalysisOptions {
1202                root: Some(root.to_path_buf()),
1203                no_cache: true,
1204                ..AnalysisOptions::default()
1205            },
1206            base: Some("HEAD".to_string()),
1207            gate: Some(AuditGate::All),
1208            ..AuditOptions::default()
1209        })
1210        .expect("all-gate audit");
1211        assert_eq!(all.verdict, AuditVerdict::Fail);
1212
1213        let inherited_only = run_audit(&AuditOptions {
1214            analysis: AnalysisOptions {
1215                root: Some(root.to_path_buf()),
1216                no_cache: true,
1217                ..AnalysisOptions::default()
1218            },
1219            base: Some("HEAD".to_string()),
1220            gate: Some(AuditGate::NewOnly),
1221            ..AuditOptions::default()
1222        })
1223        .expect("new-only inherited audit");
1224        assert_eq!(inherited_only.verdict, AuditVerdict::Pass);
1225        assert!(inherited_only.base_snapshot.is_some());
1226        let inherited_json =
1227            crate::serialize_audit_programmatic_json(inherited_only).expect("inherited audit JSON");
1228        assert_eq!(
1229            inherited_json["complexity"]["styling_findings"][0]["introduced"],
1230            false
1231        );
1232
1233        std::fs::write(
1234            root.join("src/styles.css"),
1235            "#app .legacy .title { color: red; }\n.plain { color: blue; }\n#app .introduced .title { color: green; }\n",
1236        )
1237        .expect("write introduced styling change");
1238        let introduced = run_audit(&AuditOptions {
1239            analysis: AnalysisOptions {
1240                root: Some(root.to_path_buf()),
1241                no_cache: true,
1242                ..AnalysisOptions::default()
1243            },
1244            base: Some("HEAD".to_string()),
1245            gate: Some(AuditGate::NewOnly),
1246            ..AuditOptions::default()
1247        })
1248        .expect("new-only introduced audit");
1249        assert_eq!(introduced.verdict, AuditVerdict::Fail);
1250        let introduced_json =
1251            crate::serialize_audit_programmatic_json(introduced).expect("introduced audit JSON");
1252        let styling = introduced_json["complexity"]["styling_findings"]
1253            .as_array()
1254            .expect("styling findings");
1255        assert!(
1256            styling
1257                .iter()
1258                .any(|finding| finding["line"] == 1 && finding["introduced"] == false)
1259        );
1260        assert!(
1261            styling
1262                .iter()
1263                .any(|finding| finding["line"] == 3 && finding["introduced"] == true)
1264        );
1265    }
1266
1267    /// #2347: a pre-existing high-CRAP function must stay `introduced: false`
1268    /// when Istanbul coverage is supplied and an unrelated edit touches its
1269    /// file. The base snapshot analyzes a temporary worktree, so the coverage
1270    /// entries (recorded against the HEAD checkout) must be rebased onto that
1271    /// worktree; otherwise the base side falls back to the reachability
1272    /// estimate, scores below threshold, and the unchanged finding flips the
1273    /// new-only gate.
1274    #[test]
1275    fn run_audit_coverage_keeps_unchanged_function_inherited() {
1276        let project = tempfile::tempdir().expect("project");
1277        let root = project.path();
1278        std::fs::create_dir_all(root.join("src")).expect("create src");
1279        std::fs::write(
1280            root.join("package.json"),
1281            r#"{"name":"audit-api-coverage","type":"module","main":"src/index.ts","devDependencies":{"vitest":"^3.0.0"}}"#,
1282        )
1283        .expect("write package");
1284        std::fs::write(root.join("src/index.ts"), "console.log('entry');\n").expect("write entry");
1285        std::fs::write(
1286            root.join("src/branchy.ts"),
1287            "export function branchy(n: number): number {\n\
1288             \x20 if (n < 0) return -1;\n\
1289             \x20 if (n === 0) return 0;\n\
1290             \x20 if (n < 10) return 1;\n\
1291             \x20 if (n < 100) return 2;\n\
1292             \x20 if (n < 1000) return 3;\n\
1293             \x20 if (n < 10000) return 4;\n\
1294             \x20 return 5;\n\
1295             }\n",
1296        )
1297        .expect("write branchy");
1298        std::fs::write(
1299            root.join("src/branchy.test.ts"),
1300            "import { branchy } from './branchy';\nbranchy(1);\n",
1301        )
1302        .expect("write test reference");
1303        git(root, &["init"]);
1304        git(root, &["add", "."]);
1305        git(
1306            root,
1307            &[
1308                "-c",
1309                "user.email=test@example.com",
1310                "-c",
1311                "user.name=Test",
1312                "-c",
1313                "commit.gpgsign=false",
1314                "commit",
1315                "-m",
1316                "initial",
1317            ],
1318        );
1319        let mut source = std::fs::read_to_string(root.join("src/branchy.ts")).expect("branchy");
1320        source.push_str("branchy(-1);\n");
1321        std::fs::write(root.join("src/branchy.ts"), source).expect("append unrelated statement");
1322
1323        std::fs::create_dir_all(root.join("artifacts")).expect("create artifacts");
1324        let recorded = root.join("src/branchy.ts");
1325        let recorded = recorded.to_string_lossy().replace('\\', "\\\\");
1326        std::fs::write(
1327            root.join("artifacts/coverage-final.json"),
1328            format!(
1329                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":{{}}}}}}"#
1330            ),
1331        )
1332        .expect("write coverage");
1333
1334        let output = run_audit(&AuditOptions {
1335            analysis: AnalysisOptions {
1336                root: Some(root.to_path_buf()),
1337                no_cache: true,
1338                ..AnalysisOptions::default()
1339            },
1340            base: Some("HEAD".to_string()),
1341            gate: Some(AuditGate::NewOnly),
1342            max_crap: Some(10.0),
1343            coverage: Some(root.join("artifacts/coverage-final.json")),
1344            ..AuditOptions::default()
1345        })
1346        .expect("audit output");
1347
1348        assert_eq!(output.attribution.complexity_introduced, 0);
1349        assert_eq!(output.attribution.complexity_inherited, 1);
1350        assert_eq!(output.verdict, AuditVerdict::Pass);
1351        let json = crate::serialize_audit_programmatic_json(output).expect("audit json");
1352        let findings = json["complexity"]["findings"]
1353            .as_array()
1354            .expect("complexity findings");
1355        let branchy = findings
1356            .iter()
1357            .find(|finding| finding["name"] == "branchy")
1358            .expect("branchy reported above the CRAP threshold with 0% measured coverage");
1359        assert_eq!(branchy["introduced"], false);
1360        assert_eq!(branchy["coverage_source"], "istanbul");
1361    }
1362
1363    #[test]
1364    fn audit_production_mode_branches_preserve_per_section_workspace_scope() {
1365        let project = audit_workspace_modes_fixture("");
1366
1367        for mask in 0_u8..8 {
1368            let modes = ProductionModesMask::from(mask);
1369            let output = run_audit(&AuditOptions {
1370                production_dead_code: Some(modes.dead_code),
1371                production_health: Some(modes.health),
1372                production_dupes: Some(modes.dupes),
1373                ..workspace_modes_audit_options(project.path())
1374            })
1375            .unwrap_or_else(|error| panic!("audit mask {mask:03b} failed: {error}"));
1376            assert_audit_sections_follow_modes(output, modes, mask);
1377        }
1378    }
1379
1380    /// The per-section modes may also come only from the config file. Audit
1381    /// must compare the modes after config resolution: with no overrides the
1382    /// raw options are all `None` and look equal even when the sections
1383    /// differ.
1384    #[test]
1385    fn audit_config_production_modes_scope_each_section() {
1386        for mask in 0_u8..8 {
1387            let modes = ProductionModesMask::from(mask);
1388            let project = audit_workspace_modes_fixture(&format!(
1389                r#","production":{{"deadCode":{},"health":{},"dupes":{}}}"#,
1390                modes.dead_code, modes.health, modes.dupes
1391            ));
1392            let output = run_audit(&workspace_modes_audit_options(project.path()))
1393                .unwrap_or_else(|error| panic!("audit mask {mask:03b} failed: {error}"));
1394            assert_audit_sections_follow_modes(output, modes, mask);
1395        }
1396    }
1397
1398    #[derive(Clone, Copy)]
1399    struct ProductionModesMask {
1400        dead_code: bool,
1401        health: bool,
1402        dupes: bool,
1403    }
1404
1405    impl From<u8> for ProductionModesMask {
1406        fn from(mask: u8) -> Self {
1407            Self {
1408                dead_code: mask & 0b001 != 0,
1409                health: mask & 0b010 != 0,
1410                dupes: mask & 0b100 != 0,
1411            }
1412        }
1413    }
1414
1415    fn workspace_modes_audit_options(root: &Path) -> AuditOptions {
1416        AuditOptions {
1417            analysis: AnalysisOptions {
1418                root: Some(root.to_path_buf()),
1419                workspace: Some(vec!["@audit/a".to_string()]),
1420                no_cache: true,
1421                ..AnalysisOptions::default()
1422            },
1423            base: Some("HEAD".to_string()),
1424            gate: Some(AuditGate::All),
1425            include_entry_exports: true,
1426            ..AuditOptions::default()
1427        }
1428    }
1429
1430    fn assert_audit_sections_follow_modes(
1431        output: AuditProgrammaticOutput,
1432        modes: ProductionModesMask,
1433        mask: u8,
1434    ) {
1435        let json = crate::serialize_audit_programmatic_json(output)
1436            .unwrap_or_else(|error| panic!("serialize mask {mask:03b}: {error}"));
1437
1438        let dead_code = json["dead_code"].to_string();
1439        let complexity = json["complexity"].to_string();
1440        let duplication = json["duplication"].to_string();
1441        assert_eq!(
1442            dead_code.contains("mode-sentinel.test.ts"),
1443            !modes.dead_code,
1444            "dead-code scope mismatch for mask {mask:03b}: {dead_code}"
1445        );
1446        assert_eq!(
1447            complexity.contains("mode-sentinel.test.ts"),
1448            !modes.health,
1449            "health scope mismatch for mask {mask:03b}: {complexity}"
1450        );
1451        assert_eq!(
1452            duplication.contains("mode-sentinel.test.ts"),
1453            !modes.dupes,
1454            "duplication scope mismatch for mask {mask:03b}: {duplication}"
1455        );
1456
1457        for section in [&dead_code, &complexity] {
1458            assert!(
1459                !section.contains("packages/b"),
1460                "workspace B leaked into mask {mask:03b}: {section}"
1461            );
1462        }
1463        // A clone group is in scope when one of its instances is, and it
1464        // keeps every instance, so a copy in workspace B may show next to
1465        // the copy in workspace A. No group may be only in workspace B.
1466        for group in json["duplication"]["clone_groups"]
1467            .as_array()
1468            .into_iter()
1469            .flatten()
1470        {
1471            assert!(
1472                group["instances"]
1473                    .as_array()
1474                    .into_iter()
1475                    .flatten()
1476                    .any(|instance| instance["file"]
1477                        .as_str()
1478                        .is_some_and(|file| file.starts_with("packages/a/"))),
1479                "a clone group outside workspace A leaked into mask {mask:03b}: {group}"
1480            );
1481        }
1482    }
1483
1484    #[test]
1485    fn empty_audit_output_uses_resolved_root_for_head_sha() {
1486        let project = audit_fixture();
1487        let output = empty_audit_output(
1488            &AuditOptions {
1489                analysis: AnalysisOptions {
1490                    root: None,
1491                    ..AnalysisOptions::default()
1492                },
1493                base: Some("HEAD".to_string()),
1494                gate: Some(AuditGate::NewOnly),
1495                ..AuditOptions::default()
1496            },
1497            ResolvedAuditBase {
1498                git_ref: "HEAD".to_string(),
1499                description: None,
1500                inherited_refs: Vec::new(),
1501            },
1502            project.path(),
1503            0,
1504            std::time::Duration::ZERO,
1505        );
1506
1507        assert!(output.head_sha.is_some());
1508    }
1509
1510    fn audit_fixture() -> tempfile::TempDir {
1511        let project = tempfile::tempdir().expect("project");
1512        std::fs::create_dir_all(project.path().join("src")).expect("create src");
1513        std::fs::write(
1514            project.path().join("package.json"),
1515            r#"{"name":"audit-api","type":"module","main":"src/index.ts"}"#,
1516        )
1517        .expect("write package");
1518        std::fs::write(
1519            project.path().join("src/index.ts"),
1520            "console.log('entry');\n",
1521        )
1522        .expect("write entry");
1523        git(project.path(), &["init"]);
1524        git(project.path(), &["add", "."]);
1525        git(
1526            project.path(),
1527            &[
1528                "-c",
1529                "user.email=test@example.com",
1530                "-c",
1531                "user.name=Test",
1532                "-c",
1533                "commit.gpgsign=false",
1534                "commit",
1535                "-m",
1536                "initial",
1537            ],
1538        );
1539        std::fs::write(
1540            project.path().join("src/feature.ts"),
1541            "export const unused = 1;\n",
1542        )
1543        .expect("write changed source");
1544        project
1545    }
1546
1547    fn audit_styling_fixture() -> tempfile::TempDir {
1548        let project = tempfile::tempdir().expect("project");
1549        std::fs::create_dir_all(project.path().join("src")).expect("create src");
1550        std::fs::write(
1551            project.path().join("package.json"),
1552            r#"{"name":"audit-api-styling","type":"module","main":"src/index.ts"}"#,
1553        )
1554        .expect("write package");
1555        std::fs::write(
1556            project.path().join(".fallowrc.json"),
1557            r#"{"rules":{"css-selector-complexity":"error"}}"#,
1558        )
1559        .expect("write config");
1560        std::fs::write(
1561            project.path().join("src/index.ts"),
1562            "console.log('entry');\n",
1563        )
1564        .expect("write entry");
1565        std::fs::write(
1566            project.path().join("src/styles.css"),
1567            "#app .legacy .title { color: red; }\n",
1568        )
1569        .expect("write inherited styling");
1570        git(project.path(), &["init"]);
1571        git(project.path(), &["add", "."]);
1572        git(
1573            project.path(),
1574            &[
1575                "-c",
1576                "user.email=test@example.com",
1577                "-c",
1578                "user.name=Test",
1579                "-c",
1580                "commit.gpgsign=false",
1581                "commit",
1582                "-m",
1583                "initial",
1584            ],
1585        );
1586        project
1587    }
1588
1589    /// `extra_config` is appended to the top-level `.fallowrc.json` object.
1590    fn audit_workspace_modes_fixture(extra_config: &str) -> tempfile::TempDir {
1591        let project = tempfile::tempdir().expect("project");
1592        std::fs::write(
1593            project.path().join("package.json"),
1594            r#"{"name":"audit-root","private":true,"workspaces":["packages/*"]}"#,
1595        )
1596        .expect("write root package");
1597        std::fs::write(
1598            project.path().join(".fallowrc.json"),
1599            format!(
1600                r#"{{
1601  "duplicates": {{
1602    "minTokens": 10,
1603    "minLines": 2,
1604    "ignoreDefaults": false
1605  }},
1606  "health": {{
1607    "maxCyclomatic": 2,
1608    "maxCognitive": 2,
1609    "maxCrap": 2.0,
1610    "maxUnitSize": 3
1611  }}{extra_config}
1612}}"#
1613            ),
1614        )
1615        .expect("write config");
1616
1617        for name in ["a", "b"] {
1618            let package = project.path().join("packages").join(name);
1619            std::fs::create_dir_all(package.join("src")).expect("create package source");
1620            std::fs::write(
1621                package.join("package.json"),
1622                format!(r#"{{"name":"@audit/{name}","type":"module","main":"src/index.ts"}}"#),
1623            )
1624            .expect("write package manifest");
1625            std::fs::write(
1626                package.join("src/index.ts"),
1627                format!("export const {name}Entry = true;\n"),
1628            )
1629            .expect("write package entry");
1630        }
1631
1632        git(project.path(), &["init"]);
1633        git(project.path(), &["add", "."]);
1634        git(
1635            project.path(),
1636            &[
1637                "-c",
1638                "user.email=test@example.com",
1639                "-c",
1640                "user.name=Test",
1641                "-c",
1642                "commit.gpgsign=false",
1643                "commit",
1644                "-m",
1645                "initial",
1646            ],
1647        );
1648
1649        let sentinel = r"export function auditModeSentinel(value: number) {
1650  let result = value;
1651  if (value > 0) result += 1;
1652  if (value > 1) result += 2;
1653  if (value > 2) result += 3;
1654  if (value > 3) result += 4;
1655  return result;
1656}
1657";
1658        for name in ["a", "b"] {
1659            let source = project.path().join("packages").join(name).join("src");
1660            std::fs::write(source.join("mode-sentinel.test.ts"), sentinel)
1661                .expect("write test sentinel");
1662            std::fs::write(source.join("mode-sentinel-copy.test.ts"), sentinel)
1663                .expect("write duplicate test sentinel");
1664        }
1665
1666        project
1667    }
1668
1669    use fallow_engine::git_fixture::fixture_git as git;
1670
1671    /// #2699: the auto-detect fallthrough gets the same ref validation as the
1672    /// explicit and environment paths, so a malformed detection surfaces as a
1673    /// base-ref error instead of a changed-files failure deeper in the run.
1674    #[test]
1675    fn resolve_audit_base_ref_validates_the_auto_detected_ref() {
1676        let project = tempfile::tempdir().expect("temp dir");
1677        let root = project.path();
1678        std::fs::write(root.join("index.ts"), "export const used = 1;\n").expect("write entry");
1679        git(root, &["init", "-b", "main"]);
1680        git(root, &["add", "."]);
1681        git(
1682            root,
1683            &[
1684                "-c",
1685                "user.email=test@example.com",
1686                "-c",
1687                "user.name=Test",
1688                "-c",
1689                "commit.gpgsign=false",
1690                "commit",
1691                "-m",
1692                "initial",
1693            ],
1694        );
1695        git(root, &["update-ref", "refs/remotes/origin/main", "main"]);
1696        git(
1697            root,
1698            &[
1699                "symbolic-ref",
1700                "refs/remotes/origin/HEAD",
1701                "refs/remotes/origin/main",
1702            ],
1703        );
1704        let options = AuditOptions {
1705            analysis: AnalysisOptions {
1706                root: Some(root.to_path_buf()),
1707                ..AnalysisOptions::default()
1708            },
1709            ..AuditOptions::default()
1710        };
1711
1712        let resolved = resolve_audit_base_ref(&options).expect("base ref resolves");
1713
1714        assert!(
1715            fallow_engine::validate::validate_git_ref(&resolved.git_ref).is_ok(),
1716            "auto-detected ref must be usable as a git ref: {:?}",
1717            resolved.git_ref
1718        );
1719        assert_eq!(
1720            resolved.description.as_deref(),
1721            Some("merge-base with origin/main")
1722        );
1723    }
1724
1725    fn registered_worktree_count(root: &Path) -> usize {
1726        let output = fallow_engine::git_fixture::fixture_git_command(root)
1727            .args(["worktree", "list", "--porcelain"])
1728            .output()
1729            .expect("git worktree list");
1730        assert!(output.status.success(), "git worktree list failed");
1731        String::from_utf8_lossy(&output.stdout)
1732            .lines()
1733            .filter(|line| line.starts_with("worktree "))
1734            .count()
1735    }
1736
1737    /// #3885: the base snapshot of the programmatic audit, which MCP also
1738    /// uses, is not registered with Git while the base analysis reads it.
1739    #[test]
1740    fn programmatic_base_snapshot_is_unregistered_during_base_analysis() {
1741        use crate::audit_run::AuditBackend as _;
1742
1743        let project = tempfile::tempdir().expect("temp dir");
1744        let root = project.path();
1745        std::fs::write(
1746            root.join("package.json"),
1747            r#"{"name":"base-snapshot","main":"index.ts"}"#,
1748        )
1749        .expect("write manifest");
1750        std::fs::write(root.join("index.ts"), "export const used = 1;\n").expect("write entry");
1751        git(root, &["init", "-b", "main"]);
1752        git(root, &["add", "."]);
1753        git(
1754            root,
1755            &[
1756                "-c",
1757                "user.email=test@example.com",
1758                "-c",
1759                "user.name=Test",
1760                "-c",
1761                "commit.gpgsign=false",
1762                "commit",
1763                "-m",
1764                "initial",
1765            ],
1766        );
1767        let options = AuditOptions {
1768            analysis: AnalysisOptions {
1769                root: Some(root.to_path_buf()),
1770                ..AnalysisOptions::default()
1771            },
1772            ..AuditOptions::default()
1773        };
1774        let analysis = analysis_options_for_audit(&options, "HEAD");
1775        let resolved = audit_section_context(&analysis).expect("context resolves");
1776        let run = resolve_audit_run(&options, &analysis).expect("run resolves");
1777        let backend = ProgrammaticAuditBackend {
1778            options: &options,
1779            analysis: &analysis,
1780            resolved: &resolved,
1781            run: &run,
1782            config: head_config(&run).expect("head config"),
1783        };
1784
1785        let checkout = backend
1786            .create_base_checkout("HEAD", None)
1787            .unwrap_or_else(|_| panic!("base checkout is created"));
1788        assert_eq!(
1789            registered_worktree_count(root),
1790            1,
1791            "only the main worktree may be registered while the base analysis runs"
1792        );
1793        let base = backend
1794            .run_base(checkout.path(), None)
1795            .unwrap_or_else(|_| panic!("base analysis runs on the unregistered snapshot"));
1796        assert!(base.subanalyses.dead_code.is_some());
1797        assert_eq!(registered_worktree_count(root), 1);
1798
1799        let path = checkout.path().to_path_buf();
1800        drop(checkout);
1801        assert!(!path.exists(), "the base snapshot is removed on drop");
1802        assert_eq!(registered_worktree_count(root), 1);
1803    }
1804
1805    #[cfg(unix)]
1806    fn commit_all(root: &Path, message: &str) {
1807        git(root, &["add", "-f", "."]);
1808        git(
1809            root,
1810            &[
1811                "-c",
1812                "user.email=test@example.com",
1813                "-c",
1814                "user.name=Test",
1815                "-c",
1816                "commit.gpgsign=false",
1817                "commit",
1818                "-m",
1819                message,
1820            ],
1821        );
1822    }
1823
1824    /// The base commit is untrusted. A gitdir that it commits under the name
1825    /// of the snapshot stub, or as a nested bare repository, must not run its
1826    /// config during the audit.
1827    #[cfg(unix)]
1828    #[test]
1829    fn audit_never_runs_a_git_config_from_the_base_commit() {
1830        let project = tempfile::tempdir().expect("temp dir");
1831        let root = project.path().join("repo");
1832        let marker = project.path().join("fsmonitor-ran");
1833        std::fs::create_dir_all(&root).expect("create repo");
1834        std::fs::write(
1835            root.join("package.json"),
1836            r#"{"name":"crafted-base","main":"index.ts"}"#,
1837        )
1838        .expect("write manifest");
1839        std::fs::write(root.join("index.ts"), "export const used = 1;\n").expect("write entry");
1840        for dir in ["fallow-audit-unregistered", "pkg"] {
1841            let gitdir = root.join(dir);
1842            std::fs::create_dir_all(gitdir.join("objects")).expect("create objects");
1843            std::fs::create_dir_all(gitdir.join("refs")).expect("create refs");
1844            std::fs::write(gitdir.join("objects/.keep"), "").expect("write keep");
1845            std::fs::write(gitdir.join("refs/.keep"), "").expect("write keep");
1846            std::fs::write(gitdir.join("HEAD"), "ref: refs/heads/main\n").expect("write HEAD");
1847            std::fs::write(
1848                gitdir.join("config"),
1849                format!(
1850                    "[core]\n\trepositoryformatversion = 0\n\tfsmonitor = \"touch '{}'; false\"\n",
1851                    marker.display()
1852                ),
1853            )
1854            .expect("write config");
1855        }
1856        git(&root, &["init", "-b", "main"]);
1857        commit_all(&root, "base");
1858        std::fs::write(root.join("index.ts"), "export const used = 2;\n").expect("change entry");
1859        commit_all(&root, "head");
1860        let options = AuditOptions {
1861            analysis: AnalysisOptions {
1862                root: Some(root),
1863                ..AnalysisOptions::default()
1864            },
1865            base: Some("HEAD~1".to_owned()),
1866            ..AuditOptions::default()
1867        };
1868
1869        let output = run_audit(&options).unwrap_or_else(|_| panic!("audit runs"));
1870
1871        assert!(output.base_snapshot.is_some(), "the base pass must run");
1872        assert!(
1873            !marker.exists(),
1874            "a Git config from the base commit ran a command"
1875        );
1876    }
1877
1878    /// #3885: a programmatic audit removes the snapshots of a dead owner,
1879    /// registered or not, and keeps the snapshot of a live owner. The dead
1880    /// owner's snapshots are made older than the age floor of the cleanup.
1881    #[cfg(unix)]
1882    #[test]
1883    fn audit_removes_snapshots_of_dead_owners_only() {
1884        const DEAD_PID: u32 = 99_999_998;
1885        assert!(!fallow_engine::repo_refs::process_is_alive(DEAD_PID));
1886        let project = tempfile::tempdir().expect("temp dir");
1887        let root = project.path().join("repo");
1888        std::fs::create_dir_all(&root).expect("create repo");
1889        std::fs::write(
1890            root.join("package.json"),
1891            r#"{"name":"orphans","main":"index.ts"}"#,
1892        )
1893        .expect("write manifest");
1894        std::fs::write(root.join("index.ts"), "export const used = 1;\n").expect("write entry");
1895        git(&root, &["init", "-b", "main"]);
1896        commit_all(&root, "base");
1897        std::fs::write(root.join("index.ts"), "export const used = 2;\n").expect("change entry");
1898        commit_all(&root, "head");
1899
1900        let nanos = std::time::SystemTime::now()
1901            .duration_since(std::time::UNIX_EPOCH)
1902            .expect("clock after epoch")
1903            .as_nanos();
1904        let temp = std::env::temp_dir();
1905        let dead = temp.join(format!("fallow-audit-base-{DEAD_PID}-{nanos}-0"));
1906        let dead_registered = temp.join(format!("fallow-audit-base-{DEAD_PID}-{nanos}-1"));
1907        let alive = temp.join(format!(
1908            "fallow-audit-base-{}-{nanos}-900000",
1909            std::process::id()
1910        ));
1911        for dir in [&dead, &alive] {
1912            std::fs::create_dir_all(dir).expect("create leftover");
1913            std::fs::write(dir.join("index.ts"), "").expect("write leftover file");
1914        }
1915        git(
1916            &root,
1917            &[
1918                "worktree",
1919                "add",
1920                "--detach",
1921                "--quiet",
1922                dead_registered.to_str().expect("UTF-8 path"),
1923                "HEAD",
1924            ],
1925        );
1926        let old = std::time::SystemTime::now()
1927            - fallow_engine::repo_refs::ORPHAN_MIN_AGE
1928            - std::time::Duration::from_secs(60);
1929        for dir in [&dead, &dead_registered, &alive] {
1930            std::fs::File::open(dir)
1931                .and_then(|handle| handle.set_modified(old))
1932                .expect("age the leftover");
1933        }
1934        assert_eq!(registered_worktree_count(&root), 2);
1935        let options = AuditOptions {
1936            analysis: AnalysisOptions {
1937                root: Some(root.clone()),
1938                ..AnalysisOptions::default()
1939            },
1940            base: Some("HEAD~1".to_owned()),
1941            ..AuditOptions::default()
1942        };
1943
1944        let output = run_audit(&options).unwrap_or_else(|_| panic!("audit runs"));
1945
1946        let alive_kept = alive.is_dir();
1947        let _ = std::fs::remove_dir_all(&alive);
1948        assert!(output.base_snapshot.is_some(), "the base pass must run");
1949        assert!(!dead.exists(), "the leftover of a dead owner is removed");
1950        assert!(!dead_registered.exists());
1951        assert_eq!(
1952            registered_worktree_count(&root),
1953            1,
1954            "the registration of a dead owner is removed"
1955        );
1956        assert!(alive_kept, "the snapshot of a live owner stays");
1957    }
1958}