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