fallow-api 3.24.0

Programmatic API contract types for fallow
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
//! Programmatic runtime entry points that avoid depending on `fallow-cli`.

use std::path::{Path, PathBuf};

use fallow_config::{FallowConfig, HealthConfig, ProductionAnalysis, ProductionConfig};
use fallow_engine::{
    dead_code::DeadCodeAnalysisArtifacts, duplicates::DuplicationReport, session::AnalysisSession,
};
use fallow_output::{HealthGrouping, HealthReport, RootEnvelopeMode};
use fallow_types::output_format::OutputFormat;
use fallow_types::workspace::WorkspaceDiagnostic;
use rustc_hash::FxHashSet;

mod audit;
mod combined;
mod dead_code;
mod decision_surface;
mod duplication;
mod feature_flags;
mod similar_code;
mod trace;

pub use crate::runtime_output::{
    AuditProgrammaticKeySnapshot, AuditProgrammaticOutput, BoundaryViolationsOutput,
    BoundaryViolationsProgrammaticOutput, CircularDependenciesOutput,
    CircularDependenciesProgrammaticOutput, CombinedProgrammaticOutput, DeadCodeOutput,
    DeadCodeProgrammaticOutput, DecisionSurfaceProgrammaticOutput, DuplicationOutput,
    DuplicationProgrammaticOutput, FeatureFlagsOutput, FeatureFlagsProgrammaticOutput,
    HealthJsonReportInput, HealthProgrammaticOutput, TraceClassMemberOutput, TraceCloneOutput,
    TraceCloneProgrammaticOutput, TraceDependencyOutput, TraceDependencyProgrammaticOutput,
    TraceErrorOutput, TraceErrorProgrammaticOutput, TraceExportOutput,
    TraceExportProgrammaticOutput, TraceExportTargetOutput, TraceFileOutput,
    TraceFileProgrammaticOutput, TraceImportPathOutput, TraceImportPathProgrammaticOutput,
    serialize_health_report_json,
};
pub use audit::run_audit;
pub use combined::run_combined;
pub use dead_code::{run_boundary_violations, run_circular_dependencies, run_dead_code};
pub use decision_surface::run_decision_surface;
pub use duplication::run_duplication;
pub use feature_flags::run_feature_flags;
pub use similar_code::{
    inspect_similar_code, parse_similar_code_candidate_snapshot, review_similar_code,
    run_similar_code, select_similar_code_candidate_snapshot,
};
pub use trace::{
    TraceCloneBenchmarkResult, benchmark_trace_clone_compact_json,
    benchmark_trace_graph_family_compact_json, run_trace_clone, run_trace_dependency,
    run_trace_error, run_trace_export, run_trace_file, run_trace_import_path,
};

use crate::{
    ComplexityOptions, ProgrammaticError,
    analysis_context::{
        ProgrammaticAnalysisContext, resolve_programmatic_analysis_context,
        workspace_roots_for_session,
    },
    derive_complexity_options,
    next_steps::{setup_pointer_applicable, suggestions_enabled},
};

type ProgrammaticResult<T> = Result<T, ProgrammaticError>;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) struct EffectiveProductionModes {
    pub dead_code: bool,
    pub health: bool,
    pub dupes: bool,
}

pub(super) fn resolve_effective_production_modes(
    resolved: &ProgrammaticAnalysisContext,
    dead_code_override: Option<bool>,
    health_override: Option<bool>,
    dupes_override: Option<bool>,
) -> ProgrammaticResult<EffectiveProductionModes> {
    let config = load_context_production_config(resolved)?;
    Ok(EffectiveProductionModes {
        dead_code: effective_production_mode(
            config,
            ProductionAnalysis::DeadCode,
            resolved,
            dead_code_override,
        ),
        health: effective_production_mode(
            config,
            ProductionAnalysis::Health,
            resolved,
            health_override,
        ),
        dupes: effective_production_mode(
            config,
            ProductionAnalysis::Dupes,
            resolved,
            dupes_override,
        ),
    })
}

fn effective_production_mode(
    config: ProductionConfig,
    analysis: ProductionAnalysis,
    resolved: &ProgrammaticAnalysisContext,
    analysis_override: Option<bool>,
) -> bool {
    analysis_override
        .or_else(|| resolved.production_override())
        .unwrap_or_else(|| config.for_analysis(analysis))
}

fn load_context_production_config(
    resolved: &ProgrammaticAnalysisContext,
) -> ProgrammaticResult<ProductionConfig> {
    let loaded = load_config_file(
        resolved.root(),
        resolved.config_path().as_deref(),
        resolved.allow_remote_extends(),
    )?;
    Ok(loaded.map_or_else(ProductionConfig::default, |config| config.production))
}

/// Load the `health` section of the project config for adapters that layer
/// config-sourced coverage inputs before building options (the MCP typed
/// route; see [`crate::coverage`]). The root and config path resolve exactly
/// as they do for the analysis itself. Returns `None` when the project has no
/// config file.
///
/// # Errors
///
/// Returns the analysis-context errors for an invalid root or config path,
/// and `FALLOW_CONFIG_LOAD_FAILED` when the config cannot be loaded.
pub fn load_health_config(
    options: &crate::AnalysisOptions,
) -> ProgrammaticResult<Option<HealthConfig>> {
    let root = crate::analysis_context::resolve_analysis_root(options.root.as_deref())?;
    crate::analysis_context::validate_analysis_config_path(options.config_path.as_deref())?;
    let loaded = load_config_file(
        &root,
        options.config_path.as_deref(),
        options.allow_remote_extends,
    )?;
    Ok(loaded.map(|config| config.health))
}

fn load_config_file(
    root: &Path,
    config_path: Option<&Path>,
    allow_remote_extends: bool,
) -> ProgrammaticResult<Option<FallowConfig>> {
    let load_options = fallow_config::ConfigLoadOptions {
        allow_remote_extends,
    };
    if let Some(path) = config_path {
        return FallowConfig::load_with_options(path, load_options)
            .map(Some)
            .map_err(|err| config_load_error(format!("failed to load config: {err:#}")));
    }
    FallowConfig::find_and_load_with_options(root, load_options)
        .map(|found| found.map(|(config, _)| config))
        .map_err(|err| config_load_error(format!("failed to load config: {err}")))
}

fn config_load_error(message: String) -> ProgrammaticError {
    ProgrammaticError::new(message, 2)
        .with_code("FALLOW_CONFIG_LOAD_FAILED")
        .with_context("analysis.configPath")
}

pub(super) fn health_may_consume_dead_code_artifacts(
    options: &ComplexityOptions,
    config: &fallow_config::ResolvedConfig,
) -> bool {
    let sections = derive_complexity_options(options);
    let max_crap = options.max_crap.unwrap_or(config.health.max_crap);
    sections.file_scores
        || sections.coverage_gaps
        || sections.hotspots
        || sections.targets
        || sections.force_full
        || max_crap > 0.0
}

pub(super) fn health_may_consume_duplication_report(options: &ComplexityOptions) -> bool {
    let sections = derive_complexity_options(options);
    sections.score || sections.targets
}

/// Runtime probes used by programmatic health output assembly.
///
/// Concrete runners supply environment and project facts while the stable
/// command strings and output ordering remain owned by `fallow-output`.
pub struct ProgrammaticHealthNextStepFacts {
    /// False when `FALLOW_SUGGESTIONS=off`; suppresses all steps.
    pub suggestions_enabled: bool,
    /// Offer the guided-setup pointer because no fallow config exists yet.
    pub offer_setup: bool,
    /// Local impact digest counters, when a digest is available.
    pub impact_digest: Option<fallow_output::ImpactDigestCounts>,
    /// Offer `fallow audit` because the working tree has changed files.
    pub audit_changed: bool,
}

/// API-owned health analysis payload returned by programmatic runners.
///
/// The engine owns execution, but this type is the public runner contract so
/// embedders do not have to construct or depend on engine result structs.
pub struct ProgrammaticHealthAnalysis {
    /// Typed health report produced by the engine.
    pub report: HealthReport,
    /// Grouped findings when a grouping mode was requested.
    pub grouping: Option<HealthGrouping>,
    /// Resolved analysis root the report paths are relative to.
    pub root: PathBuf,
    /// Analysis wall time.
    pub elapsed: std::time::Duration,
}

impl ProgrammaticHealthAnalysis {
    fn from_engine<GroupResolver>(
        analysis: fallow_engine::health::HealthAnalysisResult<GroupResolver>,
    ) -> Self {
        Self {
            root: analysis.config.root,
            report: analysis.report,
            grouping: analysis.grouping,
            elapsed: analysis.elapsed,
        }
    }
}

/// Health runner output shared by API, NAPI, and alternate runners.
///
/// Runtime-only presentation probes stay explicit so the API boundary, not the
/// concrete runner, owns the final programmatic report assembly.
pub struct ProgrammaticHealthRun {
    /// Engine analysis payload.
    pub analysis: ProgrammaticHealthAnalysis,
    /// Non-fatal per-file diagnostics collected during the workspace walk.
    pub workspace_diagnostics: Vec<WorkspaceDiagnostic>,
    /// Environment and project facts that drive next-step suggestions.
    pub next_step_facts: ProgrammaticHealthNextStepFacts,
    /// Analysis run id stamped into telemetry metadata when present.
    pub telemetry_analysis_run_id: Option<String>,
}

/// Runner boundary for programmatic health.
///
/// This keeps embedders on the typed API contract while still allowing tests
/// and host integrations to provide a custom health runner.
pub trait ProgrammaticHealthRunner {
    /// Run health analysis for public programmatic options.
    ///
    /// # Errors
    ///
    /// Returns a structured programmatic error when the concrete runner cannot
    /// resolve options or complete health analysis.
    fn run_programmatic_health(
        &self,
        options: &ComplexityOptions,
    ) -> Result<ProgrammaticHealthRun, ProgrammaticError>;
}

/// Default health runner backed directly by `fallow-engine`.
///
/// This runs the command-neutral health pipeline through the engine health
/// runner without touching the CLI crate: the programmatic
/// path never groups (`--group-by`), never drives the runtime coverage sidecar,
/// and never records CLI telemetry, so the runner hooks are inert. NAPI and
/// future Rust embedders use this runner; the CLI keeps its own runner for the
/// `fallow health` command path.
#[derive(Debug, Clone, Copy, Default)]
pub struct EngineHealthRunner;

impl ProgrammaticHealthRunner for EngineHealthRunner {
    fn run_programmatic_health(
        &self,
        options: &ComplexityOptions,
    ) -> Result<ProgrammaticHealthRun, ProgrammaticError> {
        let resolved = resolve_programmatic_analysis_context(&options.analysis)?;
        resolved.install(|| run_programmatic_health_on_engine(&resolved, options))
    }
}

fn run_programmatic_health_on_engine(
    resolved: &ProgrammaticAnalysisContext,
    options: &ComplexityOptions,
) -> ProgrammaticResult<ProgrammaticHealthRun> {
    let health_options = derive_programmatic_health_execution_options(resolved, options);
    let result = fallow_engine::health::run_ungrouped_health(
        &health_options,
        resolved.workspace_roots.clone(),
    )
    .map_err(|error| programmatic_health_error("health", error))?;

    Ok(programmatic_health_run_from_engine_result(result))
}

fn programmatic_health_run_from_engine_result<GroupResolver>(
    result: fallow_engine::health::HealthAnalysisResult<GroupResolver>,
) -> ProgrammaticHealthRun {
    let root = result.config.root.clone();
    let next_step_facts = ProgrammaticHealthNextStepFacts {
        suggestions_enabled: suggestions_enabled(),
        offer_setup: setup_pointer_applicable(&root),
        impact_digest: None,
        audit_changed: fallow_engine::churn::is_git_repo(&root),
    };
    ProgrammaticHealthRun {
        workspace_diagnostics: result.workspace_diagnostics.clone(),
        analysis: ProgrammaticHealthAnalysis::from_engine(result.without_group_resolver()),
        next_step_facts,
        telemetry_analysis_run_id: None,
    }
}

#[cfg(test)]
pub(super) fn run_health_with_session(
    options: &ComplexityOptions,
    resolved: &ProgrammaticAnalysisContext,
    session: &AnalysisSession,
    changed_files: Option<&FxHashSet<PathBuf>>,
) -> ProgrammaticResult<HealthProgrammaticOutput> {
    run_health_with_session_artifacts(options, resolved, session, changed_files, None, None)
}

pub(super) fn run_health_with_session_artifacts(
    options: &ComplexityOptions,
    resolved: &ProgrammaticAnalysisContext,
    session: &AnalysisSession,
    changed_files: Option<&FxHashSet<PathBuf>>,
    pre_computed_analysis: Option<DeadCodeAnalysisArtifacts>,
    pre_computed_duplication: Option<DuplicationReport>,
) -> ProgrammaticResult<HealthProgrammaticOutput> {
    crate::validate_complexity_options(options)?;
    let health_options = derive_programmatic_health_execution_options(resolved, options);
    let workspace_roots = workspace_roots_for_session(resolved, session.workspaces())?;
    let result = fallow_engine::health::run_ungrouped_health_with_session_artifacts(
        &health_options,
        workspace_roots,
        session,
        changed_files.map(|files| files.iter().cloned().collect()),
        pre_computed_analysis,
        pre_computed_duplication,
    )
    .map_err(|error| programmatic_health_error("health", error))?;

    Ok(assemble_health_programmatic_output(
        options,
        programmatic_health_run_from_engine_result(result),
    ))
}

fn programmatic_health_error(
    command: &str,
    error: fallow_engine::health::HealthError,
) -> ProgrammaticError {
    let (message, exit_code) = match error {
        fallow_engine::health::HealthError::Message { message, exit_code } => (message, exit_code),
        fallow_engine::health::HealthError::Printed(exit_code) => {
            (format!("{command} failed"), exit_code)
        }
    };
    let code = format!(
        "FALLOW_{}_FAILED",
        command.replace('-', "_").to_ascii_uppercase()
    );
    ProgrammaticError::new(message, exit_code)
        .with_code(code)
        .with_context(format!("fallow {command}"))
        .with_help(format!(
            "Re-run `fallow {command} --format json --quiet` in the target project for CLI diagnostics"
        ))
}

/// Run programmatic health / complexity through the engine-backed runner.
///
/// # Errors
///
/// Returns a structured programmatic error for invalid options or analysis
/// failures.
pub fn run_health(options: &ComplexityOptions) -> ProgrammaticResult<HealthProgrammaticOutput> {
    run_health_with_runner(options, &EngineHealthRunner)
}

#[must_use]
fn derive_programmatic_health_execution_options<'a>(
    resolved: &'a ProgrammaticAnalysisContext,
    options: &'a ComplexityOptions,
) -> fallow_engine::health::HealthExecutionOptions<'a> {
    let run = crate::derive_complexity_run_options(options);

    fallow_engine::health::HealthExecutionOptions {
        root: resolved.root(),
        config_path: resolved.config_path(),
        output: OutputFormat::Human,
        no_cache: resolved.no_cache(),
        threads: resolved.threads(),
        quiet: true,
        complexity_breakdown: run.complexity_breakdown,
        thresholds: crate::thresholds_to_engine(run.thresholds),
        top: run.top,
        sort: crate::complexity_sort_to_engine(run.sort),
        production: resolved.production_override().unwrap_or(false),
        production_override: resolved.production_override(),
        allow_remote_extends: resolved.allow_remote_extends(),
        changed_since: resolved.changed_since(),
        diff_index: resolved.diff_index(),
        use_shared_diff_index: false,
        workspace: resolved.workspace(),
        changed_workspaces: resolved.changed_workspaces(),
        baseline: None,
        save_baseline: None,
        baseline_mode: fallow_engine::baseline::HealthBaselineMode::Count,
        baseline_mode_explicit: false,
        complexity: run.sections.complexity,
        file_scores: run.sections.file_scores,
        coverage_gaps: run.sections.coverage_gaps,
        config_activates_coverage_gaps: !run.sections.any_section,
        hotspots: run.sections.hotspots,
        ownership: run.sections.ownership,
        targets: run.sections.targets,
        css: run.css,
        css_deep: run.css_deep,
        force_full: run.sections.force_full,
        score_only_output: run.sections.score_only_output,
        enforce_coverage_gap_gate: true,
        effort: run.effort.map(crate::target_effort_to_output),
        score: run.sections.score,
        gates: fallow_engine::health::HealthGateOptions::default(),
        since: run.since,
        min_commits: run.min_commits,
        explain: resolved.explain_enabled(),
        summary: false,
        save_snapshot: None,
        trend: false,
        coverage_inputs: crate::coverage_inputs_to_engine(run.coverage_inputs),
        performance: false,
        runtime_coverage: None,
        churn_file: None,
        analysis_identity: fallow_types::semantic::SemanticAnalysisIdentity::default(),
        group_by: None,
        ownership_emails: run
            .ownership_emails
            .map(crate::ownership_email_mode_to_config),
    }
}

/// Run programmatic health / complexity and return typed API output.
///
/// The concrete runner is injected while the health implementation is still
/// being migrated out of the CLI crate. Runner-owned responsibilities are
/// limited to typed analysis plus runtime facts; this API crate owns the final
/// programmatic report assembly.
///
/// # Errors
///
/// Returns a structured programmatic error for invalid options or runner
/// failures.
pub fn run_complexity_with_runner(
    options: &ComplexityOptions,
    runner: &impl ProgrammaticHealthRunner,
) -> ProgrammaticResult<HealthProgrammaticOutput> {
    crate::validate_complexity_options(options)?;
    crate::analysis_context::ensure_options_not_cancelled(&options.analysis, "health analysis")?;
    Ok(assemble_health_programmatic_output(
        options,
        runner.run_programmatic_health(options)?,
    ))
}

fn assemble_health_programmatic_output(
    options: &ComplexityOptions,
    run: ProgrammaticHealthRun,
) -> HealthProgrammaticOutput {
    let ProgrammaticHealthRun {
        analysis,
        workspace_diagnostics,
        next_step_facts,
        telemetry_analysis_run_id,
    } = run;
    let root = analysis.root.clone();
    let next_steps =
        fallow_output::build_health_next_steps(fallow_output::build_health_next_steps_input(
            &analysis.report,
            next_step_facts.suggestions_enabled,
            next_step_facts.offer_setup,
            next_step_facts.impact_digest,
            next_step_facts.audit_changed,
        ));
    HealthProgrammaticOutput {
        report: analysis.report,
        grouping: analysis.grouping,
        root,
        elapsed: analysis.elapsed,
        explain: options.analysis.explain,
        workspace_diagnostics,
        next_steps,
        envelope_mode: root_envelope_mode(),
        telemetry_analysis_run_id,
    }
}

/// Alias for [`run_complexity_with_runner`] with a product-oriented name.
///
/// # Errors
///
/// Returns the same structured errors as [`run_complexity_with_runner`].
pub fn run_health_with_runner(
    options: &ComplexityOptions,
    runner: &impl ProgrammaticHealthRunner,
) -> ProgrammaticResult<HealthProgrammaticOutput> {
    run_complexity_with_runner(options, runner)
}

const fn root_envelope_mode() -> RootEnvelopeMode {
    RootEnvelopeMode::Tagged
}

#[cfg(test)]
mod cancellation_tests;
#[cfg(test)]
mod tests;