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