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, true)
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
287/// With `standalone`, the output also states each `health.ignore` glob that
288/// matches no project file. In an audit or combined run, the dead-code
289/// section states them.
290fn run_programmatic_health_on_engine(
291    resolved: &ProgrammaticAnalysisContext,
292    options: &ComplexityOptions,
293    run: &ResolvedRun,
294    standalone: bool,
295) -> ProgrammaticResult<ProgrammaticHealthRun> {
296    let health_options = derive_programmatic_health_execution_options(resolved, options);
297    let health = crate::run::runnable(run, PlannedAnalysis::Health)?;
298    let loaded = fallow_engine::health::UngroupedHealthSession::load(&health_options, &health)
299        .map_err(|error| programmatic_health_error("health", error))?;
300    let workspace_roots = workspace_roots_for_session(resolved, loaded.workspaces())?;
301    let mut result = loaded
302        .run(&health_options, workspace_roots)
303        .map_err(|error| programmatic_health_error("health", error))?;
304    if standalone {
305        // The result holds no file list, so the project walk checks each glob.
306        let stale =
307            fallow_engine::ignore_list_notes::health_ignore_diagnostics(&result.config, &[]);
308        result.workspace_diagnostics.extend(stale);
309    }
310    resolved.record_changed_since_from_runner(result.changed_files_analyzed.as_deref());
311
312    Ok(programmatic_health_run_from_engine_result(
313        result,
314        resolved.request_outcomes(),
315    ))
316}
317
318fn programmatic_health_run_from_engine_result<GroupResolver>(
319    result: fallow_engine::health::HealthAnalysisResult<GroupResolver>,
320    request_outcomes: Option<fallow_output::RequestOutcomes>,
321) -> ProgrammaticHealthRun {
322    let root = result.config.root.clone();
323    let next_step_facts = ProgrammaticHealthNextStepFacts {
324        suggestions_enabled: suggestions_enabled(),
325        offer_setup: setup_pointer_applicable(&root),
326        impact_digest: None,
327        audit_changed: audit_changed_applicable(&root),
328    };
329    ProgrammaticHealthRun {
330        workspace_diagnostics: result.workspace_diagnostics.clone(),
331        analysis: ProgrammaticHealthAnalysis::from_engine(result.without_group_resolver()),
332        next_step_facts,
333        telemetry_analysis_run_id: None,
334        request_outcomes,
335    }
336}
337
338#[cfg(test)]
339pub(super) fn run_health_with_session(
340    options: &ComplexityOptions,
341    resolved: &ProgrammaticAnalysisContext,
342    session: &AnalysisSession,
343    changed_files: Option<&FxHashSet<PathBuf>>,
344) -> ProgrammaticResult<HealthProgrammaticOutput> {
345    run_health_with_session_artifacts(options, resolved, session, changed_files, None, None)
346}
347
348pub(super) fn run_health_with_session_artifacts(
349    options: &ComplexityOptions,
350    resolved: &ProgrammaticAnalysisContext,
351    session: &AnalysisSession,
352    changed_files: Option<&FxHashSet<PathBuf>>,
353    pre_computed_analysis: Option<DeadCodeAnalysisArtifacts>,
354    pre_computed_duplication: Option<DuplicationReport>,
355) -> ProgrammaticResult<HealthProgrammaticOutput> {
356    crate::validate_complexity_options(options)?;
357    let health_options = derive_programmatic_health_execution_options(resolved, options);
358    let workspace_roots = workspace_roots_for_session(resolved, session.workspaces())?;
359    let result = fallow_engine::health::run_ungrouped_health_with_session_artifacts(
360        &health_options,
361        workspace_roots,
362        session,
363        changed_files.map(|files| files.iter().cloned().collect()),
364        pre_computed_analysis,
365        pre_computed_duplication,
366    )
367    .map_err(|error| programmatic_health_error("health", error))?;
368    resolved.record_changed_since_from_runner(result.changed_files_analyzed.as_deref());
369
370    Ok(assemble_health_programmatic_output(
371        options,
372        programmatic_health_run_from_engine_result(result, resolved.request_outcomes()),
373    ))
374}
375
376fn programmatic_health_error(
377    command: &str,
378    error: fallow_engine::health::HealthError,
379) -> ProgrammaticError {
380    let (message, exit_code) = match error {
381        fallow_engine::health::HealthError::Message { message, exit_code } => (message, exit_code),
382        fallow_engine::health::HealthError::Printed(exit_code) => {
383            (format!("{command} failed"), exit_code)
384        }
385    };
386    let code = format!(
387        "FALLOW_{}_FAILED",
388        command.replace('-', "_").to_ascii_uppercase()
389    );
390    ProgrammaticError::new(message, exit_code)
391        .with_code(code)
392        .with_context(format!("fallow {command}"))
393        .with_help(format!(
394            "Re-run `fallow {command} --format json --quiet` in the target project for CLI diagnostics"
395        ))
396}
397
398/// Run programmatic health / complexity through the engine-backed runner.
399///
400/// # Errors
401///
402/// Returns a structured programmatic error for invalid options or analysis
403/// failures.
404pub fn run_health(options: &ComplexityOptions) -> ProgrammaticResult<HealthProgrammaticOutput> {
405    run_health_with_runner(options, &EngineHealthRunner)
406}
407
408#[must_use]
409fn derive_programmatic_health_execution_options<'a>(
410    resolved: &'a ProgrammaticAnalysisContext,
411    options: &'a ComplexityOptions,
412) -> fallow_engine::health::HealthExecutionOptions<'a> {
413    let run = crate::derive_complexity_run_options(options);
414
415    fallow_engine::health::HealthExecutionOptions {
416        root: resolved.root(),
417        config_path: resolved.config_path(),
418        output: OutputFormat::Human,
419        no_cache: resolved.no_cache(),
420        threads: resolved.threads(),
421        quiet: true,
422        complexity_breakdown: run.complexity_breakdown,
423        thresholds: crate::thresholds_to_engine(run.thresholds),
424        top: run.top,
425        sort: crate::complexity_sort_to_engine(run.sort),
426        production: resolved.production_override().unwrap_or(false),
427        production_override: resolved.production_override(),
428        allow_remote_extends: resolved.allow_remote_extends(),
429        changed_since: resolved.changed_since(),
430        diff_index: resolved.diff_index(),
431        use_shared_diff_index: false,
432        workspace: resolved.workspace(),
433        changed_workspaces: resolved.changed_workspaces(),
434        baseline: None,
435        save_baseline: None,
436        baseline_mode: fallow_engine::baseline::HealthBaselineMode::Count,
437        baseline_mode_explicit: false,
438        complexity: run.sections.complexity,
439        file_scores: run.sections.file_scores,
440        coverage_gaps: run.sections.coverage_gaps,
441        // The programmatic API has no shallow directories option yet.
442        shallow_directories: false,
443        config_activates_coverage_gaps: options.config_activates_coverage_gaps
444            || !run.sections.any_section,
445        hotspots: run.sections.hotspots,
446        ownership: run.sections.ownership,
447        targets: run.sections.targets,
448        css: run.css,
449        css_deep: run.css_deep,
450        force_full: run.sections.force_full,
451        score_only_output: run.sections.score_only_output,
452        enforce_coverage_gap_gate: true,
453        effort: run.effort.map(crate::target_effort_to_output),
454        score: run.sections.score,
455        gates: fallow_engine::health::HealthGateOptions::default(),
456        since: run.since,
457        min_commits: run.min_commits,
458        explain: resolved.explain_enabled(),
459        summary: false,
460        save_snapshot: None,
461        trend: false,
462        coverage_inputs: crate::coverage_inputs_to_engine(run.coverage_inputs),
463        performance: false,
464        runtime_coverage: None,
465        churn_file: None,
466        analysis_identity: fallow_types::semantic::SemanticAnalysisIdentity::default(),
467        group_by: None,
468        group_filter: None,
469        trend_from: None,
470        scope: None,
471        ownership_emails: run
472            .ownership_emails
473            .map(crate::ownership_email_mode_to_config),
474    }
475}
476
477/// Run programmatic health / complexity and return typed API output.
478///
479/// The runner is a seam for tests and hosts. [`EngineHealthRunner`] is the
480/// default. The runner supplies typed analysis and runtime facts. This API
481/// crate owns the final programmatic report assembly.
482///
483/// # Errors
484///
485/// Returns a structured programmatic error for invalid options or runner
486/// failures. When no section is selected and the environment or
487/// `typeAware.enabled` turns on type-aware analysis that the options leave
488/// off, it returns [`TYPE_AWARE_CONFIG_UNSUPPORTED`].
489pub fn run_complexity_with_runner(
490    options: &ComplexityOptions,
491    runner: &impl ProgrammaticHealthRunner,
492) -> ProgrammaticResult<HealthProgrammaticOutput> {
493    crate::validate_complexity_options(options)?;
494    if !runner.refuses_config_type_aware() {
495        reject_health_config_type_aware(options)?;
496    }
497    run_validated_complexity(options, runner)
498}
499
500/// The health section of a combined or audit run that the caller resolved.
501/// The caller checks the type-aware layers with its own precedence, so the
502/// `fallow health` check does not apply.
503pub(super) fn run_health_in_run(
504    options: &ComplexityOptions,
505    resolved: &ProgrammaticAnalysisContext,
506    run: &ResolvedRun,
507) -> ProgrammaticResult<HealthProgrammaticOutput> {
508    crate::validate_complexity_options(options)?;
509    crate::analysis_context::ensure_options_not_cancelled(&options.analysis, "health analysis")?;
510    let health =
511        resolved.install(|| run_programmatic_health_on_engine(resolved, options, run, false))?;
512    Ok(assemble_health_programmatic_output(options, health))
513}
514
515/// `fallow health` runs type coupling from config only when no section is
516/// selected (`health_type_coupling_is_default_section` in the CLI).
517fn health_reads_config_type_aware(options: &ComplexityOptions) -> bool {
518    !options.css && !crate::derive_complexity_options(options).any_section
519}
520
521/// The type-aware check of [`health_reads_config_type_aware`] for a runner
522/// that does not refuse config-sourced type-aware analysis itself.
523fn reject_health_config_type_aware(options: &ComplexityOptions) -> ProgrammaticResult<()> {
524    if !health_reads_config_type_aware(options) {
525        return Ok(());
526    }
527    let root = crate::analysis_context::resolve_analysis_root(options.analysis.root.as_deref())?;
528    crate::analysis_context::validate_analysis_config_path(
529        options.analysis.config_path.as_deref(),
530    )?;
531    type_aware_config::reject_config_type_aware_at(
532        &options.analysis,
533        type_aware_config::ConfigLocation {
534            root: &root,
535            config_path: options.analysis.config_path.as_deref(),
536            allow_remote_extends: options.analysis.allow_remote_extends,
537        },
538        type_aware_config::TypeAwareCommand::Analysis,
539    )
540}
541
542fn run_validated_complexity(
543    options: &ComplexityOptions,
544    runner: &impl ProgrammaticHealthRunner,
545) -> ProgrammaticResult<HealthProgrammaticOutput> {
546    crate::analysis_context::ensure_options_not_cancelled(&options.analysis, "health analysis")?;
547    Ok(assemble_health_programmatic_output(
548        options,
549        runner.run_programmatic_health(options)?,
550    ))
551}
552
553fn assemble_health_programmatic_output(
554    options: &ComplexityOptions,
555    run: ProgrammaticHealthRun,
556) -> HealthProgrammaticOutput {
557    let ProgrammaticHealthRun {
558        analysis,
559        workspace_diagnostics,
560        next_step_facts,
561        telemetry_analysis_run_id,
562        request_outcomes,
563    } = run;
564    let root = analysis.root.clone();
565    let next_steps =
566        fallow_output::build_health_next_steps(fallow_output::build_health_next_steps_input(
567            &analysis.report,
568            next_step_facts.suggestions_enabled,
569            next_step_facts.offer_setup,
570            next_step_facts.impact_digest,
571            next_step_facts.audit_changed,
572            None,
573        ));
574    HealthProgrammaticOutput {
575        report: analysis.report,
576        grouping: analysis.grouping,
577        root,
578        elapsed: analysis.elapsed,
579        explain: options.analysis.explain,
580        workspace_diagnostics,
581        next_steps,
582        telemetry_analysis_run_id,
583        request_outcomes,
584    }
585}
586
587/// Alias for [`run_complexity_with_runner`] with a product-oriented name.
588///
589/// # Errors
590///
591/// Returns the same structured errors as [`run_complexity_with_runner`].
592pub fn run_health_with_runner(
593    options: &ComplexityOptions,
594    runner: &impl ProgrammaticHealthRunner,
595) -> ProgrammaticResult<HealthProgrammaticOutput> {
596    run_complexity_with_runner(options, runner)
597}
598
599#[cfg(test)]
600mod cancellation_tests;
601#[cfg(test)]
602mod tests;