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