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::{self, ConfigFileOptions, ConfigLoadError, 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_runner_options;
27mod mutation_witness;
28mod similar_code;
29mod trace;
30mod type_aware_config;
31
32pub use crate::runtime_output::{
33    ArchitectureOutput, ArchitectureProgrammaticOutput, AuditProgrammaticKeySnapshot,
34    AuditProgrammaticOutput, BoundaryViolationsOutput, BoundaryViolationsProgrammaticOutput,
35    CircularDependenciesOutput, CircularDependenciesProgrammaticOutput, CombinedProgrammaticOutput,
36    DeadCodeOutput, DeadCodeProgrammaticOutput, DecisionSurfaceProgrammaticOutput,
37    DuplicationOutput, DuplicationProgrammaticOutput, FeatureFlagsOutput,
38    FeatureFlagsProgrammaticOutput, HealthJsonReportInput, HealthProgrammaticOutput,
39    TraceClassMemberOutput, TraceCloneOutput, TraceCloneProgrammaticOutput, TraceDependencyOutput,
40    TraceDependencyProgrammaticOutput, TraceErrorOutput, TraceErrorProgrammaticOutput,
41    TraceExportOutput, TraceExportProgrammaticOutput, TraceExportTargetOutput, TraceFileOutput,
42    TraceFileProgrammaticOutput, TraceImportPathOutput, TraceImportPathProgrammaticOutput,
43    serialize_health_report_json,
44};
45pub use audit::{AUDIT_CONFIG_BASELINE_UNSUPPORTED, run_audit};
46pub use combined::run_combined;
47pub use dead_code::{
48    run_architecture, run_boundary_violations, run_circular_dependencies, run_dead_code,
49    run_dead_code_with_baseline,
50};
51pub use decision_surface::run_decision_surface;
52pub use duplication::run_duplication;
53pub use feature_flags::run_feature_flags;
54pub use mutation::{plan_mutation, run_mutation, run_mutation_with_progress};
55pub use mutation_replay::replay_mutation;
56pub use similar_code::{
57    inspect_similar_code, parse_similar_code_candidate_snapshot, review_similar_code,
58    run_similar_code, select_similar_code_candidate_snapshot,
59};
60pub use trace::{
61    TraceCloneBenchmarkResult, benchmark_trace_clone_compact_json,
62    benchmark_trace_graph_family_compact_json, run_trace_clone, run_trace_dependency,
63    run_trace_error, run_trace_export, run_trace_file, run_trace_import_path,
64};
65pub use type_aware_config::TYPE_AWARE_CONFIG_UNSUPPORTED;
66
67use crate::{
68    ComplexityOptions, ProgrammaticError,
69    analysis_context::{
70        ProgrammaticAnalysisContext, resolve_programmatic_analysis_context,
71        workspace_roots_for_session,
72    },
73    derive_complexity_options,
74    next_steps::{audit_changed_applicable, setup_pointer_applicable, suggestions_enabled},
75};
76
77type ProgrammaticResult<T> = Result<T, ProgrammaticError>;
78
79pub(super) fn resolve_effective_production_modes(
80    resolved: &ProgrammaticAnalysisContext,
81    dead_code_override: Option<bool>,
82    health_override: Option<bool>,
83    dupes_override: Option<bool>,
84) -> ProgrammaticResult<ProductionModes> {
85    let config = load_context_production_config(resolved)?;
86    Ok(ProductionFlags {
87        global: resolved.production_override(),
88        dead_code: dead_code_override,
89        health: health_override,
90        dupes: dupes_override,
91    }
92    .effective_modes(&config))
93}
94
95/// The run plan of the project config for `request`. A project without a
96/// config file has the default config. The config loads only when the plan
97/// depends on it.
98pub(super) fn plan_run(
99    resolved: &ProgrammaticAnalysisContext,
100    request: fallow_config::RunRequest,
101) -> ProgrammaticResult<fallow_config::RunPlan> {
102    let config = if request.reads_config() {
103        load_config_file(
104            resolved.root(),
105            resolved.config_path().as_deref(),
106            resolved.allow_remote_extends(),
107        )?
108    } else {
109        None
110    };
111    Ok(fallow_config::plan_run(
112        config.unwrap_or_default().plan_sections(),
113        request,
114    ))
115}
116
117fn load_context_production_config(
118    resolved: &ProgrammaticAnalysisContext,
119) -> ProgrammaticResult<ProductionConfig> {
120    let loaded = load_config_file(
121        resolved.root(),
122        resolved.config_path().as_deref(),
123        resolved.allow_remote_extends(),
124    )?;
125    Ok(loaded.map_or_else(ProductionConfig::default, |config| config.production))
126}
127
128/// Load the `health` section of the project config for adapters that layer
129/// config-sourced coverage inputs before building options (the MCP typed
130/// route; see [`crate::coverage`]). The root and config path resolve exactly
131/// as they do for the analysis itself. Returns `None` when the project has no
132/// config file.
133///
134/// # Errors
135///
136/// Returns the analysis-context errors for an invalid root or config path,
137/// and `FALLOW_CONFIG_LOAD_FAILED` when the config cannot be loaded.
138pub fn load_health_config(
139    options: &crate::AnalysisOptions,
140) -> ProgrammaticResult<Option<HealthConfig>> {
141    let root = crate::analysis_context::resolve_analysis_root(options.root.as_deref())?;
142    crate::analysis_context::validate_analysis_config_path(options.config_path.as_deref())?;
143    let loaded = load_config_file(
144        &root,
145        options.config_path.as_deref(),
146        options.allow_remote_extends,
147    )?;
148    Ok(loaded.map(|config| config.health))
149}
150
151/// The config file of the project, or `None` when the project has no config
152/// file.
153fn load_config_file(
154    root: &Path,
155    config_path: Option<&Path>,
156    allow_remote_extends: bool,
157) -> ProgrammaticResult<Option<FallowConfig>> {
158    let file = project_config::load_config_file(
159        root,
160        config_path,
161        ConfigFileOptions {
162            allow_remote_extends,
163        },
164    )
165    .map_err(|err| config_load_error(&err))?;
166    Ok(file.path.map(|_| file.config))
167}
168
169fn config_load_error(err: &ConfigLoadError) -> ProgrammaticError {
170    ProgrammaticError::new(format!("failed to load config: {}", err.chain()), 2)
171        .with_code("FALLOW_CONFIG_LOAD_FAILED")
172        .with_context("analysis.configPath")
173}
174
175pub(super) fn health_may_consume_dead_code_artifacts(
176    options: &ComplexityOptions,
177    config: &fallow_config::ResolvedConfig,
178) -> bool {
179    let sections = derive_complexity_options(options);
180    let max_crap = options.max_crap.unwrap_or(config.health.max_crap);
181    sections.file_scores
182        || sections.coverage_gaps
183        || sections.hotspots
184        || sections.targets
185        || sections.force_full
186        || max_crap > 0.0
187}
188
189pub(super) fn health_may_consume_duplication_report(options: &ComplexityOptions) -> bool {
190    let sections = derive_complexity_options(options);
191    sections.score || sections.targets
192}
193
194/// Runtime probes used by programmatic health output assembly.
195///
196/// Concrete runners supply environment and project facts while the stable
197/// command strings and output ordering remain owned by `fallow-output`.
198pub struct ProgrammaticHealthNextStepFacts {
199    /// False when `FALLOW_SUGGESTIONS=off`; suppresses all steps.
200    pub suggestions_enabled: bool,
201    /// Offer the guided-setup pointer because no fallow config exists yet.
202    pub offer_setup: bool,
203    /// Local impact digest counters, when a digest is available.
204    pub impact_digest: Option<fallow_output::ImpactDigestCounts>,
205    /// Offer `fallow audit` because the working tree has changed files.
206    pub audit_changed: bool,
207}
208
209/// API-owned health analysis payload returned by programmatic runners.
210///
211/// The engine owns execution, but this type is the public runner contract so
212/// embedders do not have to construct or depend on engine result structs.
213pub struct ProgrammaticHealthAnalysis {
214    /// Typed health report produced by the engine.
215    pub report: HealthReport,
216    /// Grouped findings when a grouping mode was requested.
217    pub grouping: Option<HealthGrouping>,
218    /// Resolved analysis root the report paths are relative to.
219    pub root: PathBuf,
220    /// Analysis wall time.
221    pub elapsed: std::time::Duration,
222}
223
224impl ProgrammaticHealthAnalysis {
225    fn from_engine<GroupResolver>(
226        analysis: fallow_engine::health::HealthAnalysisResult<GroupResolver>,
227    ) -> Self {
228        Self {
229            root: analysis.config.root,
230            report: analysis.report,
231            grouping: analysis.grouping,
232            elapsed: analysis.elapsed,
233        }
234    }
235}
236
237/// Health runner output shared by API, NAPI, and alternate runners.
238///
239/// Runtime-only presentation probes stay explicit so the API boundary, not the
240/// concrete runner, owns the final programmatic report assembly.
241pub struct ProgrammaticHealthRun {
242    /// Engine analysis payload.
243    pub analysis: ProgrammaticHealthAnalysis,
244    /// Non-fatal per-file diagnostics collected during the workspace walk.
245    pub workspace_diagnostics: Vec<WorkspaceDiagnostic>,
246    /// Environment and project facts that drive next-step suggestions.
247    pub next_step_facts: ProgrammaticHealthNextStepFacts,
248    /// Analysis run id stamped into telemetry metadata when present.
249    pub telemetry_analysis_run_id: Option<String>,
250    /// What became of the narrowing requests the run received.
251    pub request_outcomes: Option<fallow_output::RequestOutcomes>,
252}
253
254/// Runner boundary for programmatic health.
255///
256/// This keeps embedders on the typed API contract while still allowing tests
257/// and host integrations to provide a custom health runner.
258pub trait ProgrammaticHealthRunner {
259    /// Run health analysis for public programmatic options.
260    ///
261    /// # Errors
262    ///
263    /// Returns a structured programmatic error when the concrete runner cannot
264    /// resolve options or complete health analysis.
265    fn run_programmatic_health(
266        &self,
267        options: &ComplexityOptions,
268    ) -> Result<ProgrammaticHealthRun, ProgrammaticError>;
269}
270
271/// Default health runner backed directly by `fallow-engine`.
272///
273/// This runs the command-neutral health pipeline through the engine health
274/// runner without touching the CLI crate: the programmatic
275/// path never groups (`--group-by`), never drives the runtime coverage sidecar,
276/// and never records CLI telemetry, so the runner hooks are inert. This is
277/// the default runner for NAPI and Rust embedders.
278#[derive(Debug, Clone, Copy, Default)]
279pub struct EngineHealthRunner;
280
281impl ProgrammaticHealthRunner for EngineHealthRunner {
282    fn run_programmatic_health(
283        &self,
284        options: &ComplexityOptions,
285    ) -> Result<ProgrammaticHealthRun, ProgrammaticError> {
286        let resolved = resolve_programmatic_analysis_context(&options.analysis)?;
287        resolved.install(|| run_programmatic_health_on_engine(&resolved, options))
288    }
289}
290
291fn run_programmatic_health_on_engine(
292    resolved: &ProgrammaticAnalysisContext,
293    options: &ComplexityOptions,
294) -> ProgrammaticResult<ProgrammaticHealthRun> {
295    let health_options = derive_programmatic_health_execution_options(resolved, options);
296    let loaded = fallow_engine::health::UngroupedHealthSession::load(&health_options)
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    reject_health_config_type_aware(options)?;
485    run_validated_complexity(options, runner)
486}
487
488/// The health section of `fallow audit`. Audit resolves type-aware analysis
489/// with its own precedence, so the `fallow health` check does not apply.
490pub(super) fn run_health_for_audit(
491    options: &ComplexityOptions,
492) -> ProgrammaticResult<HealthProgrammaticOutput> {
493    crate::validate_complexity_options(options)?;
494    run_validated_complexity(options, &EngineHealthRunner)
495}
496
497/// `fallow health` runs type coupling from config only when no section is
498/// selected (`health_type_coupling_is_default_section` in the CLI).
499fn reject_health_config_type_aware(options: &ComplexityOptions) -> ProgrammaticResult<()> {
500    if options.css || crate::derive_complexity_options(options).any_section {
501        return Ok(());
502    }
503    let root = crate::analysis_context::resolve_analysis_root(options.analysis.root.as_deref())?;
504    crate::analysis_context::validate_analysis_config_path(
505        options.analysis.config_path.as_deref(),
506    )?;
507    type_aware_config::reject_config_type_aware_at(
508        &options.analysis.type_aware,
509        type_aware_config::ConfigLocation {
510            root: &root,
511            config_path: options.analysis.config_path.as_deref(),
512            allow_remote_extends: options.analysis.allow_remote_extends,
513        },
514        type_aware_config::TypeAwareCommand::Analysis,
515    )
516}
517
518fn run_validated_complexity(
519    options: &ComplexityOptions,
520    runner: &impl ProgrammaticHealthRunner,
521) -> ProgrammaticResult<HealthProgrammaticOutput> {
522    crate::analysis_context::ensure_options_not_cancelled(&options.analysis, "health analysis")?;
523    Ok(assemble_health_programmatic_output(
524        options,
525        runner.run_programmatic_health(options)?,
526    ))
527}
528
529fn assemble_health_programmatic_output(
530    options: &ComplexityOptions,
531    run: ProgrammaticHealthRun,
532) -> HealthProgrammaticOutput {
533    let ProgrammaticHealthRun {
534        analysis,
535        workspace_diagnostics,
536        next_step_facts,
537        telemetry_analysis_run_id,
538        request_outcomes,
539    } = run;
540    let root = analysis.root.clone();
541    let next_steps =
542        fallow_output::build_health_next_steps(fallow_output::build_health_next_steps_input(
543            &analysis.report,
544            next_step_facts.suggestions_enabled,
545            next_step_facts.offer_setup,
546            next_step_facts.impact_digest,
547            next_step_facts.audit_changed,
548            None,
549        ));
550    HealthProgrammaticOutput {
551        report: analysis.report,
552        grouping: analysis.grouping,
553        root,
554        elapsed: analysis.elapsed,
555        explain: options.analysis.explain,
556        workspace_diagnostics,
557        next_steps,
558        telemetry_analysis_run_id,
559        request_outcomes,
560    }
561}
562
563/// Alias for [`run_complexity_with_runner`] with a product-oriented name.
564///
565/// # Errors
566///
567/// Returns the same structured errors as [`run_complexity_with_runner`].
568pub fn run_health_with_runner(
569    options: &ComplexityOptions,
570    runner: &impl ProgrammaticHealthRunner,
571) -> ProgrammaticResult<HealthProgrammaticOutput> {
572    run_complexity_with_runner(options, runner)
573}
574
575#[cfg(test)]
576mod cancellation_tests;
577#[cfg(test)]
578mod tests;