Skip to main content

fallow_api/runtime/
mod.rs

1//! Programmatic runtime entry points that avoid depending on `fallow-cli`.
2
3use std::path::{Path, PathBuf};
4
5use fallow_config::{FallowConfig, HealthConfig, PlannedAnalysis};
6use fallow_engine::{
7    dead_code::DeadCodeAnalysisArtifacts,
8    duplicates::DuplicationReport,
9    project_config::{self, ConfigFileOptions, ConfigLoadError},
10    session::AnalysisSession,
11};
12use fallow_output::{HealthGrouping, HealthReport};
13use fallow_types::output_format::OutputFormat;
14use fallow_types::workspace::WorkspaceDiagnostic;
15use rustc_hash::FxHashSet;
16
17mod audit;
18mod audit_base_ref;
19mod combined;
20mod dead_code;
21mod decision_surface;
22mod duplication;
23mod feature_flags;
24mod mutation;
25mod mutation_record;
26mod mutation_replay;
27mod mutation_runner_options;
28mod mutation_witness;
29mod similar_code;
30mod trace;
31mod type_aware_config;
32
33pub use crate::runtime_output::{
34    ArchitectureOutput, ArchitectureProgrammaticOutput, AuditProgrammaticKeySnapshot,
35    AuditProgrammaticOutput, BoundaryViolationsOutput, BoundaryViolationsProgrammaticOutput,
36    CircularDependenciesOutput, CircularDependenciesProgrammaticOutput, CombinedProgrammaticOutput,
37    DeadCodeOutput, DeadCodeProgrammaticOutput, DecisionSurfaceProgrammaticOutput,
38    DuplicationOutput, DuplicationProgrammaticOutput, FeatureFlagsOutput,
39    FeatureFlagsProgrammaticOutput, HealthJsonReportInput, HealthProgrammaticOutput,
40    TraceClassMemberOutput, TraceCloneOutput, TraceCloneProgrammaticOutput, TraceDependencyOutput,
41    TraceDependencyProgrammaticOutput, TraceErrorOutput, TraceErrorProgrammaticOutput,
42    TraceExportOutput, TraceExportProgrammaticOutput, TraceExportTargetOutput, TraceFileOutput,
43    TraceFileProgrammaticOutput, TraceImportPathOutput, TraceImportPathProgrammaticOutput,
44    serialize_health_report_json,
45};
46pub use audit::{AUDIT_CONFIG_BASELINE_UNSUPPORTED, run_audit};
47#[cfg(any(test, feature = "testing"))]
48pub(crate) use audit::{analysis_options_for_audit, resolve_audit_run};
49pub use combined::run_combined;
50pub use dead_code::{
51    run_architecture, run_boundary_violations, run_circular_dependencies, run_dead_code,
52    run_dead_code_with_baseline,
53};
54pub use decision_surface::run_decision_surface;
55pub use duplication::run_duplication;
56pub use feature_flags::run_feature_flags;
57pub use mutation::{plan_mutation, run_mutation, run_mutation_with_progress};
58pub use mutation_replay::replay_mutation;
59pub use similar_code::{
60    inspect_similar_code, parse_similar_code_candidate_snapshot, review_similar_code,
61    run_similar_code, select_similar_code_candidate_snapshot,
62};
63pub use trace::{
64    TraceCloneBenchmarkResult, benchmark_trace_clone_compact_json,
65    benchmark_trace_graph_family_compact_json, run_trace_clone, run_trace_dependency,
66    run_trace_error, run_trace_export, run_trace_file, run_trace_import_path,
67};
68pub use type_aware_config::TYPE_AWARE_CONFIG_UNSUPPORTED;
69
70use crate::{
71    ComplexityOptions, ProgrammaticError,
72    analysis_context::{
73        ProgrammaticAnalysisContext, resolve_programmatic_analysis_context,
74        workspace_roots_for_session,
75    },
76    derive_complexity_options,
77    next_steps::{audit_changed_applicable, setup_pointer_applicable, suggestions_enabled},
78    run::{ProgrammaticEntry, ResolvedRun, resolve_programmatic_run},
79};
80
81type ProgrammaticResult<T> = Result<T, ProgrammaticError>;
82
83/// Load the `health` section of the project config for adapters that layer
84/// config-sourced coverage inputs before building options (the MCP typed
85/// route; see [`crate::coverage`]). The root and config path resolve exactly
86/// as they do for the analysis itself. Returns `None` when the project has no
87/// config file. The function parses the config file and does not validate
88/// the rest of the config, so the health analysis reports such errors.
89///
90/// # Errors
91///
92/// Returns the analysis-context errors for an invalid root or config path,
93/// and `FALLOW_CONFIG_LOAD_FAILED` when the config cannot be loaded.
94pub fn load_health_config(
95    options: &crate::AnalysisOptions,
96) -> ProgrammaticResult<Option<HealthConfig>> {
97    let root = crate::analysis_context::resolve_analysis_root(options.root.as_deref())?;
98    crate::analysis_context::validate_analysis_config_path(options.config_path.as_deref())?;
99    let loaded = load_config_file(
100        &root,
101        options.config_path.as_deref(),
102        options.allow_remote_extends,
103    )?;
104    Ok(loaded.map(|config| config.health))
105}
106
107/// The config file of the project, or `None` when the project has no config
108/// file.
109fn load_config_file(
110    root: &Path,
111    config_path: Option<&Path>,
112    allow_remote_extends: bool,
113) -> ProgrammaticResult<Option<FallowConfig>> {
114    let file = project_config::load_config_file(
115        root,
116        config_path,
117        ConfigFileOptions {
118            allow_remote_extends,
119        },
120    )
121    .map_err(|err| config_load_error(&err))?;
122    Ok(file.path.map(|_| file.config))
123}
124
125fn config_load_error(err: &ConfigLoadError) -> ProgrammaticError {
126    ProgrammaticError::new(format!("failed to load config: {}", err.chain()), 2)
127        .with_code("FALLOW_CONFIG_LOAD_FAILED")
128        .with_context("analysis.configPath")
129}
130
131pub(super) fn health_may_consume_dead_code_artifacts(
132    options: &ComplexityOptions,
133    config: &fallow_config::ResolvedConfig,
134) -> bool {
135    let sections = derive_complexity_options(options);
136    let max_crap = options.max_crap.unwrap_or(config.health.max_crap);
137    sections.file_scores
138        || sections.coverage_gaps
139        || sections.hotspots
140        || sections.targets
141        || sections.force_full
142        || max_crap > 0.0
143}
144
145pub(super) fn health_may_consume_duplication_report(options: &ComplexityOptions) -> bool {
146    let sections = derive_complexity_options(options);
147    sections.score || sections.targets
148}
149
150/// Runtime probes used by programmatic health output assembly.
151///
152/// Concrete runners supply environment and project facts while the stable
153/// command strings and output ordering remain owned by `fallow-output`.
154pub struct ProgrammaticHealthNextStepFacts {
155    /// False when `FALLOW_SUGGESTIONS=off`; suppresses all steps.
156    pub suggestions_enabled: bool,
157    /// Offer the guided-setup pointer because no fallow config exists yet.
158    pub offer_setup: bool,
159    /// Local impact digest counters, when a digest is available.
160    pub impact_digest: Option<fallow_output::ImpactDigestCounts>,
161    /// Offer `fallow audit` because the working tree has changed files.
162    pub audit_changed: bool,
163}
164
165/// API-owned health analysis payload returned by programmatic runners.
166///
167/// The engine owns execution, but this type is the public runner contract so
168/// embedders do not have to construct or depend on engine result structs.
169pub struct ProgrammaticHealthAnalysis {
170    /// Typed health report produced by the engine.
171    pub report: HealthReport,
172    /// Grouped findings when a grouping mode was requested.
173    pub grouping: Option<HealthGrouping>,
174    /// Resolved analysis root the report paths are relative to.
175    pub root: PathBuf,
176    /// Analysis wall time.
177    pub elapsed: std::time::Duration,
178}
179
180impl ProgrammaticHealthAnalysis {
181    fn from_engine<GroupResolver>(
182        analysis: fallow_engine::health::HealthAnalysisResult<GroupResolver>,
183    ) -> Self {
184        Self {
185            root: analysis.config.root,
186            report: analysis.report,
187            grouping: analysis.grouping,
188            elapsed: analysis.elapsed,
189        }
190    }
191}
192
193/// Health runner output shared by API, NAPI, and alternate runners.
194///
195/// Runtime-only presentation probes stay explicit so the API boundary, not the
196/// concrete runner, owns the final programmatic report assembly.
197pub struct ProgrammaticHealthRun {
198    /// Engine analysis payload.
199    pub analysis: ProgrammaticHealthAnalysis,
200    /// Non-fatal per-file diagnostics collected during the workspace walk.
201    pub workspace_diagnostics: Vec<WorkspaceDiagnostic>,
202    /// Environment and project facts that drive next-step suggestions.
203    pub next_step_facts: ProgrammaticHealthNextStepFacts,
204    /// Analysis run id stamped into telemetry metadata when present.
205    pub telemetry_analysis_run_id: Option<String>,
206    /// What became of the narrowing requests the run received.
207    pub request_outcomes: Option<fallow_output::RequestOutcomes>,
208}
209
210/// Runner boundary for programmatic health.
211///
212/// This keeps embedders on the typed API contract while still allowing tests
213/// and host integrations to provide a custom health runner.
214pub trait ProgrammaticHealthRunner {
215    /// Run health analysis for public programmatic options.
216    ///
217    /// # Errors
218    ///
219    /// Returns a structured programmatic error when the concrete runner cannot
220    /// resolve options or complete health analysis.
221    fn run_programmatic_health(
222        &self,
223        options: &ComplexityOptions,
224    ) -> Result<ProgrammaticHealthRun, ProgrammaticError>;
225
226    /// Whether [`Self::run_programmatic_health`] refuses config-sourced
227    /// type-aware analysis itself, from the config that it loads. With the
228    /// default `false`, [`run_health_with_runner`] reads the config for the
229    /// check before the runner starts.
230    fn refuses_config_type_aware(&self) -> bool {
231        false
232    }
233}
234
235/// Default health runner backed directly by `fallow-engine`.
236///
237/// This runs the command-neutral health pipeline through the engine health
238/// runner without touching the CLI crate: the programmatic
239/// path never groups (`--group-by`), never drives the runtime coverage sidecar,
240/// and never records CLI telemetry, so the runner hooks are inert. This is
241/// the default runner for NAPI and Rust embedders.
242#[derive(Debug, Clone, Copy, Default)]
243pub struct EngineHealthRunner;
244
245impl ProgrammaticHealthRunner for EngineHealthRunner {
246    fn run_programmatic_health(
247        &self,
248        options: &ComplexityOptions,
249    ) -> Result<ProgrammaticHealthRun, ProgrammaticError> {
250        let resolved = resolve_programmatic_analysis_context(&options.analysis)?;
251        resolved.install(|| {
252            // The health runner reports a config that does not load with its
253            // own error, as `fallow health` does.
254            let resolve = || {
255                resolve_programmatic_run(&options.analysis, &ProgrammaticEntry::Health)
256                    .map_err(|_| health_config_load_error())
257            };
258            let run = if health_reads_config_type_aware(options) {
259                type_aware_config::resolve_run_refusing_type_aware(
260                    &options.analysis,
261                    type_aware_config::TypeAwareCommand::Analysis,
262                    type_aware_config::ConfigLocation::of(&resolved),
263                    resolve,
264                )?
265            } else {
266                resolve()?
267            };
268            run_programmatic_health_on_engine(&resolved, options, &run)
269        })
270    }
271
272    fn refuses_config_type_aware(&self) -> bool {
273        true
274    }
275}
276
277/// The error of a health analysis whose config does not load, as
278/// `fallow health` reports it.
279pub(super) fn health_config_load_error() -> ProgrammaticError {
280    programmatic_health_error(
281        "health",
282        fallow_engine::health::HealthError::Message {
283            message: "failed to load health project config".to_owned(),
284            exit_code: 2,
285        },
286    )
287}
288
289fn run_programmatic_health_on_engine(
290    resolved: &ProgrammaticAnalysisContext,
291    options: &ComplexityOptions,
292    run: &ResolvedRun,
293) -> ProgrammaticResult<ProgrammaticHealthRun> {
294    let health_options = derive_programmatic_health_execution_options(resolved, options);
295    let health = crate::run::runnable(run, PlannedAnalysis::Health)?;
296    let loaded = fallow_engine::health::UngroupedHealthSession::load(&health_options, &health)
297        .map_err(|error| programmatic_health_error("health", error))?;
298    let workspace_roots = workspace_roots_for_session(resolved, loaded.workspaces())?;
299    let result = loaded
300        .run(&health_options, workspace_roots)
301        .map_err(|error| programmatic_health_error("health", error))?;
302    resolved.record_changed_since_from_runner(result.changed_files_analyzed.as_deref());
303
304    Ok(programmatic_health_run_from_engine_result(
305        result,
306        resolved.request_outcomes(),
307    ))
308}
309
310fn programmatic_health_run_from_engine_result<GroupResolver>(
311    result: fallow_engine::health::HealthAnalysisResult<GroupResolver>,
312    request_outcomes: Option<fallow_output::RequestOutcomes>,
313) -> ProgrammaticHealthRun {
314    let root = result.config.root.clone();
315    let next_step_facts = ProgrammaticHealthNextStepFacts {
316        suggestions_enabled: suggestions_enabled(),
317        offer_setup: setup_pointer_applicable(&root),
318        impact_digest: None,
319        audit_changed: audit_changed_applicable(&root),
320    };
321    ProgrammaticHealthRun {
322        workspace_diagnostics: result.workspace_diagnostics.clone(),
323        analysis: ProgrammaticHealthAnalysis::from_engine(result.without_group_resolver()),
324        next_step_facts,
325        telemetry_analysis_run_id: None,
326        request_outcomes,
327    }
328}
329
330#[cfg(test)]
331pub(super) fn run_health_with_session(
332    options: &ComplexityOptions,
333    resolved: &ProgrammaticAnalysisContext,
334    session: &AnalysisSession,
335    changed_files: Option<&FxHashSet<PathBuf>>,
336) -> ProgrammaticResult<HealthProgrammaticOutput> {
337    run_health_with_session_artifacts(options, resolved, session, changed_files, None, None)
338}
339
340pub(super) fn run_health_with_session_artifacts(
341    options: &ComplexityOptions,
342    resolved: &ProgrammaticAnalysisContext,
343    session: &AnalysisSession,
344    changed_files: Option<&FxHashSet<PathBuf>>,
345    pre_computed_analysis: Option<DeadCodeAnalysisArtifacts>,
346    pre_computed_duplication: Option<DuplicationReport>,
347) -> ProgrammaticResult<HealthProgrammaticOutput> {
348    crate::validate_complexity_options(options)?;
349    let health_options = derive_programmatic_health_execution_options(resolved, options);
350    let workspace_roots = workspace_roots_for_session(resolved, session.workspaces())?;
351    let result = fallow_engine::health::run_ungrouped_health_with_session_artifacts(
352        &health_options,
353        workspace_roots,
354        session,
355        changed_files.map(|files| files.iter().cloned().collect()),
356        pre_computed_analysis,
357        pre_computed_duplication,
358    )
359    .map_err(|error| programmatic_health_error("health", error))?;
360    resolved.record_changed_since_from_runner(result.changed_files_analyzed.as_deref());
361
362    Ok(assemble_health_programmatic_output(
363        options,
364        programmatic_health_run_from_engine_result(result, resolved.request_outcomes()),
365    ))
366}
367
368fn programmatic_health_error(
369    command: &str,
370    error: fallow_engine::health::HealthError,
371) -> ProgrammaticError {
372    let (message, exit_code) = match error {
373        fallow_engine::health::HealthError::Message { message, exit_code } => (message, exit_code),
374        fallow_engine::health::HealthError::Printed(exit_code) => {
375            (format!("{command} failed"), exit_code)
376        }
377    };
378    let code = format!(
379        "FALLOW_{}_FAILED",
380        command.replace('-', "_").to_ascii_uppercase()
381    );
382    ProgrammaticError::new(message, exit_code)
383        .with_code(code)
384        .with_context(format!("fallow {command}"))
385        .with_help(format!(
386            "Re-run `fallow {command} --format json --quiet` in the target project for CLI diagnostics"
387        ))
388}
389
390/// Run programmatic health / complexity through the engine-backed runner.
391///
392/// # Errors
393///
394/// Returns a structured programmatic error for invalid options or analysis
395/// failures.
396pub fn run_health(options: &ComplexityOptions) -> ProgrammaticResult<HealthProgrammaticOutput> {
397    run_health_with_runner(options, &EngineHealthRunner)
398}
399
400#[must_use]
401fn derive_programmatic_health_execution_options<'a>(
402    resolved: &'a ProgrammaticAnalysisContext,
403    options: &'a ComplexityOptions,
404) -> fallow_engine::health::HealthExecutionOptions<'a> {
405    let run = crate::derive_complexity_run_options(options);
406
407    fallow_engine::health::HealthExecutionOptions {
408        root: resolved.root(),
409        config_path: resolved.config_path(),
410        output: OutputFormat::Human,
411        no_cache: resolved.no_cache(),
412        threads: resolved.threads(),
413        quiet: true,
414        complexity_breakdown: run.complexity_breakdown,
415        thresholds: crate::thresholds_to_engine(run.thresholds),
416        top: run.top,
417        sort: crate::complexity_sort_to_engine(run.sort),
418        production: resolved.production_override().unwrap_or(false),
419        production_override: resolved.production_override(),
420        allow_remote_extends: resolved.allow_remote_extends(),
421        changed_since: resolved.changed_since(),
422        diff_index: resolved.diff_index(),
423        use_shared_diff_index: false,
424        workspace: resolved.workspace(),
425        changed_workspaces: resolved.changed_workspaces(),
426        baseline: None,
427        save_baseline: None,
428        baseline_mode: fallow_engine::baseline::HealthBaselineMode::Count,
429        baseline_mode_explicit: false,
430        complexity: run.sections.complexity,
431        file_scores: run.sections.file_scores,
432        coverage_gaps: run.sections.coverage_gaps,
433        config_activates_coverage_gaps: options.config_activates_coverage_gaps
434            || !run.sections.any_section,
435        hotspots: run.sections.hotspots,
436        ownership: run.sections.ownership,
437        targets: run.sections.targets,
438        css: run.css,
439        css_deep: run.css_deep,
440        force_full: run.sections.force_full,
441        score_only_output: run.sections.score_only_output,
442        enforce_coverage_gap_gate: true,
443        effort: run.effort.map(crate::target_effort_to_output),
444        score: run.sections.score,
445        gates: fallow_engine::health::HealthGateOptions::default(),
446        since: run.since,
447        min_commits: run.min_commits,
448        explain: resolved.explain_enabled(),
449        summary: false,
450        save_snapshot: None,
451        trend: false,
452        coverage_inputs: crate::coverage_inputs_to_engine(run.coverage_inputs),
453        performance: false,
454        runtime_coverage: None,
455        churn_file: None,
456        analysis_identity: fallow_types::semantic::SemanticAnalysisIdentity::default(),
457        group_by: None,
458        group_filter: None,
459        trend_from: None,
460        scope: None,
461        ownership_emails: run
462            .ownership_emails
463            .map(crate::ownership_email_mode_to_config),
464    }
465}
466
467/// Run programmatic health / complexity and return typed API output.
468///
469/// The runner is a seam for tests and hosts. [`EngineHealthRunner`] is the
470/// default. The runner supplies typed analysis and runtime facts. This API
471/// crate owns the final programmatic report assembly.
472///
473/// # Errors
474///
475/// Returns a structured programmatic error for invalid options or runner
476/// failures. When no section is selected and the environment or
477/// `typeAware.enabled` turns on type-aware analysis that the options leave
478/// off, it returns [`TYPE_AWARE_CONFIG_UNSUPPORTED`].
479pub fn run_complexity_with_runner(
480    options: &ComplexityOptions,
481    runner: &impl ProgrammaticHealthRunner,
482) -> ProgrammaticResult<HealthProgrammaticOutput> {
483    crate::validate_complexity_options(options)?;
484    if !runner.refuses_config_type_aware() {
485        reject_health_config_type_aware(options)?;
486    }
487    run_validated_complexity(options, runner)
488}
489
490/// The health section of a combined or audit run that the caller resolved.
491/// The caller checks the type-aware layers with its own precedence, so the
492/// `fallow health` check does not apply.
493pub(super) fn run_health_in_run(
494    options: &ComplexityOptions,
495    resolved: &ProgrammaticAnalysisContext,
496    run: &ResolvedRun,
497) -> ProgrammaticResult<HealthProgrammaticOutput> {
498    crate::validate_complexity_options(options)?;
499    crate::analysis_context::ensure_options_not_cancelled(&options.analysis, "health analysis")?;
500    let health = resolved.install(|| run_programmatic_health_on_engine(resolved, options, run))?;
501    Ok(assemble_health_programmatic_output(options, health))
502}
503
504/// `fallow health` runs type coupling from config only when no section is
505/// selected (`health_type_coupling_is_default_section` in the CLI).
506fn health_reads_config_type_aware(options: &ComplexityOptions) -> bool {
507    !options.css && !crate::derive_complexity_options(options).any_section
508}
509
510/// The type-aware check of [`health_reads_config_type_aware`] for a runner
511/// that does not refuse config-sourced type-aware analysis itself.
512fn reject_health_config_type_aware(options: &ComplexityOptions) -> ProgrammaticResult<()> {
513    if !health_reads_config_type_aware(options) {
514        return Ok(());
515    }
516    let root = crate::analysis_context::resolve_analysis_root(options.analysis.root.as_deref())?;
517    crate::analysis_context::validate_analysis_config_path(
518        options.analysis.config_path.as_deref(),
519    )?;
520    type_aware_config::reject_config_type_aware_at(
521        &options.analysis,
522        type_aware_config::ConfigLocation {
523            root: &root,
524            config_path: options.analysis.config_path.as_deref(),
525            allow_remote_extends: options.analysis.allow_remote_extends,
526        },
527        type_aware_config::TypeAwareCommand::Analysis,
528    )
529}
530
531fn run_validated_complexity(
532    options: &ComplexityOptions,
533    runner: &impl ProgrammaticHealthRunner,
534) -> ProgrammaticResult<HealthProgrammaticOutput> {
535    crate::analysis_context::ensure_options_not_cancelled(&options.analysis, "health analysis")?;
536    Ok(assemble_health_programmatic_output(
537        options,
538        runner.run_programmatic_health(options)?,
539    ))
540}
541
542fn assemble_health_programmatic_output(
543    options: &ComplexityOptions,
544    run: ProgrammaticHealthRun,
545) -> HealthProgrammaticOutput {
546    let ProgrammaticHealthRun {
547        analysis,
548        workspace_diagnostics,
549        next_step_facts,
550        telemetry_analysis_run_id,
551        request_outcomes,
552    } = run;
553    let root = analysis.root.clone();
554    let next_steps =
555        fallow_output::build_health_next_steps(fallow_output::build_health_next_steps_input(
556            &analysis.report,
557            next_step_facts.suggestions_enabled,
558            next_step_facts.offer_setup,
559            next_step_facts.impact_digest,
560            next_step_facts.audit_changed,
561            None,
562        ));
563    HealthProgrammaticOutput {
564        report: analysis.report,
565        grouping: analysis.grouping,
566        root,
567        elapsed: analysis.elapsed,
568        explain: options.analysis.explain,
569        workspace_diagnostics,
570        next_steps,
571        telemetry_analysis_run_id,
572        request_outcomes,
573    }
574}
575
576/// Alias for [`run_complexity_with_runner`] with a product-oriented name.
577///
578/// # Errors
579///
580/// Returns the same structured errors as [`run_complexity_with_runner`].
581pub fn run_health_with_runner(
582    options: &ComplexityOptions,
583    runner: &impl ProgrammaticHealthRunner,
584) -> ProgrammaticResult<HealthProgrammaticOutput> {
585    run_complexity_with_runner(options, runner)
586}
587
588#[cfg(test)]
589mod cancellation_tests;
590#[cfg(test)]
591mod tests;