Skip to main content

fallow_api/
runtime_output.rs

1//! Typed programmatic runtime outputs and shared output-contract serializers.
2
3use std::path::{Path, PathBuf};
4
5pub use fallow_output::HEALTH_SCHEMA_VERSION;
6use fallow_output::{
7    CheckOutput, DupesOutput, FeatureFlagFinding, FeatureFlagsOutput as FeatureFlagsOutputContract,
8    GroupByMode, HealthGroup, HealthGrouping, HealthJsonOutputInput, HealthOutputInput,
9    HealthReport, health_meta,
10};
11use fallow_types::output::NextStep;
12use fallow_types::output_dead_code::{
13    BoundaryCallViolationFinding, BoundaryCoverageViolationFinding, BoundaryViolationFinding,
14    CircularDependencyFinding,
15};
16use fallow_types::results::AnalysisResults;
17use fallow_types::workspace::WorkspaceDiagnostic;
18use rustc_hash::FxHashSet;
19
20use crate::{AuditAttribution, AuditSummary, AuditVerdict};
21use crate::{CloneFamilyFinding, CloneGroupFinding, DupesReportPayload, DuplicationGroup};
22
23/// Concrete dead-code output contract returned by typed programmatic runs.
24pub type DeadCodeOutput = CheckOutput;
25
26/// Concrete circular-dependency output contract returned by typed runs.
27pub type CircularDependenciesOutput = CheckOutput;
28
29/// Concrete boundary-family output contract returned by typed runs.
30pub type BoundaryViolationsOutput = CheckOutput;
31
32/// Concrete `fallow architecture` output contract returned by typed runs.
33pub type ArchitectureOutput = CheckOutput;
34
35/// Concrete duplication output contract returned by typed programmatic runs.
36pub type DuplicationOutput = DupesOutput<DupesReportPayload, DuplicationGroup>;
37
38/// Concrete feature-flag output contract returned by typed programmatic runs.
39pub type FeatureFlagsOutput = FeatureFlagsOutputContract;
40
41/// Concrete export trace output returned by typed programmatic runs.
42pub type TraceExportOutput = fallow_types::trace::ExportTrace;
43
44/// Concrete class / enum / store member trace output (the `trace_export`
45/// fallback when the name is a member rather than a top-level export). See
46/// issue #1744.
47pub type TraceClassMemberOutput = fallow_types::trace::ClassMemberTrace;
48
49/// The `trace_export` target: either a top-level export or (fallback) a class /
50/// enum / store member declared on one. Serialized untagged so the export shape
51/// stays byte-identical to the historical contract and the member shape matches
52/// the CLI's member trace; consumers distinguish by the presence of
53/// `export_name` (export) vs `member_name` / `owner_export` (member).
54#[derive(Debug, serde::Serialize)]
55#[serde(untagged)]
56pub enum TraceExportTargetOutput {
57    /// A top-level export trace.
58    Export(TraceExportOutput),
59    /// A class / enum / store member trace.
60    Member(TraceClassMemberOutput),
61}
62
63/// Concrete file trace output returned by typed programmatic runs.
64pub type TraceFileOutput = fallow_types::trace::FileTrace;
65
66/// Concrete dependency trace output returned by typed programmatic runs.
67pub type TraceDependencyOutput = fallow_types::trace::DependencyTrace;
68
69/// Concrete import-path trace output returned by typed programmatic runs.
70pub type TraceImportPathOutput = fallow_types::trace::ImportPathTrace;
71
72/// Concrete duplicate-code trace output returned by typed programmatic runs.
73pub type TraceCloneOutput = fallow_types::trace::CloneTrace;
74
75/// Concrete stack-trace resolution returned by typed programmatic runs.
76pub type TraceErrorOutput = fallow_types::trace_error::ErrorTrace;
77
78/// Inputs for serializing health JSON output through the API boundary.
79pub struct HealthJsonReportInput<'a> {
80    /// Every gate this run evaluated, absent when it evaluated none. The
81    /// programmatic route runs no CLI-layer gate and leaves this `None`.
82    pub gate_outcomes: Option<fallow_output::GateOutcomes>,
83    /// Every narrowing or shaping request this run received, absent when it
84    /// was asked for nothing. The programmatic route resolves no CLI flag and
85    /// leaves this `None`; an entry whose `status` is not `applied` means the
86    /// report is wider than what was asked for.
87    pub request_outcomes: Option<fallow_output::RequestOutcomes>,
88    /// Typed health report to serialize.
89    pub report: HealthReport,
90    /// Project root; its prefix is stripped from every path in the output.
91    pub root: &'a Path,
92    /// Analysis wall time, emitted as `elapsed_ms`.
93    pub elapsed: std::time::Duration,
94    /// Emit explain metadata under `meta`.
95    pub explain: bool,
96    /// Type-aware pass metadata merged into `meta` even when `explain` is
97    /// off.
98    pub type_aware: Option<fallow_types::envelope::TypeAwareMeta>,
99    /// Grouping axis recorded as `grouped_by`; `None` when ungrouped.
100    pub grouped_by: Option<GroupByMode>,
101    /// Precomputed group buckets matching `grouped_by`.
102    pub groups: Option<Vec<HealthGroup>>,
103    /// The `--group` selector patterns, when the run kept only some groups.
104    pub group_filter: Option<Vec<String>>,
105    /// Non-fatal per-file diagnostics collected during the workspace walk.
106    pub workspace_diagnostics: Vec<WorkspaceDiagnostic>,
107    /// Suggested follow-up commands for the consumer.
108    pub next_steps: Vec<NextStep>,
109    /// Analysis run id stamped into telemetry metadata when present.
110    pub telemetry_analysis_run_id: Option<&'a str>,
111}
112
113/// Typed programmatic combined output before JSON serialization.
114#[derive(Debug, Clone)]
115pub struct CombinedProgrammaticOutput {
116    /// Dead-code section; `None` when the run skipped it.
117    pub dead_code: Option<DeadCodeProgrammaticOutput>,
118    /// Duplication section; `None` when the run skipped it.
119    pub duplication: Option<DuplicationProgrammaticOutput>,
120    /// Health section; `None` when the run skipped it.
121    pub health: Option<HealthProgrammaticOutput>,
122    /// Project root used when serializing stable JSON paths.
123    pub root: PathBuf,
124    /// Total wall time across sections, emitted as the root `elapsed_ms`.
125    pub elapsed: std::time::Duration,
126    /// Emit per-section explain metadata when serialized.
127    pub explain: bool,
128    /// Suggested follow-up commands for the consumer.
129    pub next_steps: Vec<NextStep>,
130    /// Analysis run id stamped into telemetry metadata when present.
131    pub telemetry_analysis_run_id: Option<String>,
132    /// What became of the narrowing requests the run received, emitted at the
133    /// envelope root as `request_outcomes`, the only carrier on the combined
134    /// envelope.
135    pub request_outcomes: Option<fallow_output::RequestOutcomes>,
136    /// Each analysis that the run skips, with the reason, emitted at the
137    /// envelope root as `skipped` and omitted when empty. A skipped analysis
138    /// has no section.
139    pub skipped: Vec<fallow_output::SkippedAnalysis>,
140}
141
142/// Typed programmatic dead-code output before JSON serialization.
143///
144/// This is the API boundary embedders should use when they need access to the
145/// typed engine/output result. Protocol surfaces serialize it explicitly at
146/// their JSON boundary.
147#[derive(Debug, Clone)]
148pub struct DeadCodeProgrammaticOutput {
149    /// Typed dead-code envelope produced by the run.
150    pub output: DeadCodeOutput,
151    /// Project root used when serializing stable JSON paths.
152    pub root: PathBuf,
153    /// Whether duplicate-export findings can be auto-fixed through config;
154    /// propagated onto their fix actions when serialized.
155    pub config_fixable: bool,
156    /// Analysis run id stamped into telemetry metadata when present.
157    pub telemetry_analysis_run_id: Option<String>,
158}
159
160impl DeadCodeProgrammaticOutput {
161    /// Full typed dead-code issue arrays retained by this run.
162    #[must_use]
163    pub fn results(&self) -> &AnalysisResults {
164        &self.output.results
165    }
166
167    /// Project-relative root used when serializing stable JSON paths.
168    #[must_use]
169    pub fn root(&self) -> &Path {
170        &self.root
171    }
172}
173
174/// Typed programmatic circular-dependency output before JSON serialization.
175///
176/// The wire envelope stays the dead-code/check contract, but the Rust API
177/// surface is family-specific so embedders do not have to treat this as a
178/// generic dead-code run.
179#[derive(Debug, Clone)]
180pub struct CircularDependenciesProgrammaticOutput {
181    /// Typed check envelope scoped to circular-dependency findings.
182    pub output: CircularDependenciesOutput,
183    /// Project root used when serializing stable JSON paths.
184    pub root: PathBuf,
185    /// Analysis run id stamped into telemetry metadata when present.
186    pub telemetry_analysis_run_id: Option<String>,
187}
188
189impl CircularDependenciesProgrammaticOutput {
190    /// Full typed issue arrays retained by this family run.
191    #[must_use]
192    pub fn results(&self) -> &AnalysisResults {
193        &self.output.results
194    }
195
196    /// The circular dependency findings retained by this family run.
197    #[must_use]
198    pub fn circular_dependencies(&self) -> &[CircularDependencyFinding] {
199        &self.output.results.circular_dependencies
200    }
201}
202
203impl From<DeadCodeProgrammaticOutput> for CircularDependenciesProgrammaticOutput {
204    fn from(value: DeadCodeProgrammaticOutput) -> Self {
205        Self {
206            output: value.output,
207            root: value.root,
208            telemetry_analysis_run_id: value.telemetry_analysis_run_id,
209        }
210    }
211}
212
213/// Typed programmatic `fallow architecture` output before JSON serialization.
214///
215/// The body is the dead-code body. The JSON envelope has
216/// `kind: "architecture"` and its own `schema_version`.
217#[derive(Debug, Clone)]
218pub struct ArchitectureProgrammaticOutput {
219    /// Typed check envelope scoped to the architecture findings.
220    pub output: ArchitectureOutput,
221    /// Project root used when serializing stable JSON paths.
222    pub root: PathBuf,
223    /// Analysis run id stamped into telemetry metadata when present.
224    pub telemetry_analysis_run_id: Option<String>,
225}
226
227impl ArchitectureProgrammaticOutput {
228    /// Full typed issue arrays retained by this run.
229    #[must_use]
230    pub fn results(&self) -> &AnalysisResults {
231        &self.output.results
232    }
233}
234
235impl From<DeadCodeProgrammaticOutput> for ArchitectureProgrammaticOutput {
236    fn from(value: DeadCodeProgrammaticOutput) -> Self {
237        Self {
238            output: value.output,
239            root: value.root,
240            telemetry_analysis_run_id: value.telemetry_analysis_run_id,
241        }
242    }
243}
244
245/// Typed programmatic boundary-family output before JSON serialization.
246///
247/// This covers banned imports, boundary coverage, and forbidden call findings
248/// while preserving the stable dead-code/check JSON envelope.
249#[derive(Debug, Clone)]
250pub struct BoundaryViolationsProgrammaticOutput {
251    /// Typed check envelope scoped to boundary-family findings.
252    pub output: BoundaryViolationsOutput,
253    /// Project root used when serializing stable JSON paths.
254    pub root: PathBuf,
255    /// Analysis run id stamped into telemetry metadata when present.
256    pub telemetry_analysis_run_id: Option<String>,
257}
258
259impl BoundaryViolationsProgrammaticOutput {
260    /// Full typed issue arrays retained by this family run.
261    #[must_use]
262    pub fn results(&self) -> &AnalysisResults {
263        &self.output.results
264    }
265
266    /// Banned import boundary findings retained by this family run.
267    #[must_use]
268    pub fn boundary_violations(&self) -> &[BoundaryViolationFinding] {
269        &self.output.results.boundary_violations
270    }
271
272    /// Boundary coverage findings retained by this family run.
273    #[must_use]
274    pub fn boundary_coverage_violations(&self) -> &[BoundaryCoverageViolationFinding] {
275        &self.output.results.boundary_coverage_violations
276    }
277
278    /// Forbidden call findings retained by this family run.
279    #[must_use]
280    pub fn boundary_call_violations(&self) -> &[BoundaryCallViolationFinding] {
281        &self.output.results.boundary_call_violations
282    }
283}
284
285impl From<DeadCodeProgrammaticOutput> for BoundaryViolationsProgrammaticOutput {
286    fn from(value: DeadCodeProgrammaticOutput) -> Self {
287        Self {
288            output: value.output,
289            root: value.root,
290            telemetry_analysis_run_id: value.telemetry_analysis_run_id,
291        }
292    }
293}
294
295/// Typed programmatic duplication output before JSON serialization.
296#[derive(Debug, Clone)]
297pub struct DuplicationProgrammaticOutput {
298    /// Typed duplication envelope produced by the run.
299    pub output: DuplicationOutput,
300    /// Project root used when serializing stable JSON paths.
301    pub root: PathBuf,
302    /// Maximum allowed duplication percentage from the resolved config;
303    /// 0 disables the percentage gate.
304    pub threshold: f64,
305    /// The clone groups that `duplicates.ignoredClones` hid from the report.
306    /// The audit reads them, so an accepted clone stays accepted.
307    pub ignored_clone_groups: Vec<fallow_engine::duplicates::IgnoredCloneGroup>,
308    /// Analysis run id stamped into telemetry metadata when present.
309    pub telemetry_analysis_run_id: Option<String>,
310}
311
312impl DuplicationProgrammaticOutput {
313    /// Typed duplication report payload retained by this run.
314    #[must_use]
315    pub const fn report(&self) -> &DupesReportPayload {
316        &self.output.report
317    }
318
319    /// Clone groups retained by this run, with typed actions and fingerprints.
320    #[must_use]
321    pub fn clone_groups(&self) -> &[CloneGroupFinding] {
322        &self.output.report.clone_groups
323    }
324
325    /// Clone families retained by this run, with nested typed clone groups.
326    #[must_use]
327    pub fn clone_families(&self) -> &[CloneFamilyFinding] {
328        &self.output.report.clone_families
329    }
330
331    /// Grouped duplication buckets when a grouping mode was used.
332    #[must_use]
333    pub fn groups(&self) -> Option<&[DuplicationGroup]> {
334        self.output.groups.as_deref()
335    }
336}
337
338/// Typed programmatic feature-flag output before JSON serialization.
339#[derive(Debug, Clone)]
340pub struct FeatureFlagsProgrammaticOutput {
341    /// Typed feature-flag envelope produced by the run.
342    pub output: FeatureFlagsOutput,
343    /// Analysis run id stamped into telemetry metadata when present.
344    pub telemetry_analysis_run_id: Option<String>,
345}
346
347impl FeatureFlagsProgrammaticOutput {
348    /// Feature flag findings retained by this run.
349    #[must_use]
350    pub fn feature_flags(&self) -> &[FeatureFlagFinding] {
351        &self.output.feature_flags
352    }
353
354    /// Number of feature flags retained by this run after scoping and limits.
355    #[must_use]
356    pub const fn total_flags(&self) -> usize {
357        self.output.total_flags
358    }
359}
360
361/// Typed programmatic export-trace output before JSON serialization. Carries
362/// either an export trace or (fallback) a class / enum / store member trace.
363#[derive(Debug)]
364pub struct TraceExportProgrammaticOutput {
365    /// Typed export-or-member trace produced by the run.
366    pub output: TraceExportTargetOutput,
367}
368
369impl TraceExportProgrammaticOutput {
370    /// Typed export-or-member trace retained by this run.
371    #[must_use]
372    pub const fn trace(&self) -> &TraceExportTargetOutput {
373        &self.output
374    }
375
376    /// The export trace, when the target resolved to a top-level export.
377    #[must_use]
378    pub const fn as_export(&self) -> Option<&TraceExportOutput> {
379        match &self.output {
380            TraceExportTargetOutput::Export(export) => Some(export),
381            TraceExportTargetOutput::Member(_) => None,
382        }
383    }
384
385    /// The member trace, when the target resolved to a class / enum / store
386    /// member (the `trace_export` fallback, issue #1744).
387    #[must_use]
388    pub const fn as_member(&self) -> Option<&TraceClassMemberOutput> {
389        match &self.output {
390            TraceExportTargetOutput::Member(member) => Some(member),
391            TraceExportTargetOutput::Export(_) => None,
392        }
393    }
394}
395
396/// Typed programmatic file-trace output before JSON serialization.
397#[derive(Debug)]
398pub struct TraceFileProgrammaticOutput {
399    /// Typed file trace produced by the run.
400    pub output: TraceFileOutput,
401}
402
403impl TraceFileProgrammaticOutput {
404    /// Typed file trace retained by this run.
405    #[must_use]
406    pub const fn trace(&self) -> &TraceFileOutput {
407        &self.output
408    }
409}
410
411/// Typed programmatic import-path-trace output before JSON serialization.
412#[derive(Debug)]
413pub struct TraceImportPathProgrammaticOutput {
414    /// Typed import-path trace produced by the run.
415    pub output: TraceImportPathOutput,
416}
417
418impl TraceImportPathProgrammaticOutput {
419    /// Typed import-path trace retained by this run.
420    #[must_use]
421    pub const fn trace(&self) -> &TraceImportPathOutput {
422        &self.output
423    }
424}
425
426/// Typed programmatic dependency-trace output before JSON serialization.
427#[derive(Debug)]
428pub struct TraceDependencyProgrammaticOutput {
429    /// Typed dependency trace produced by the run.
430    pub output: TraceDependencyOutput,
431}
432
433impl TraceDependencyProgrammaticOutput {
434    /// Typed dependency trace retained by this run.
435    #[must_use]
436    pub const fn trace(&self) -> &TraceDependencyOutput {
437        &self.output
438    }
439}
440
441/// Typed programmatic stack-trace resolution before JSON serialization.
442#[derive(Debug)]
443pub struct TraceErrorProgrammaticOutput {
444    /// Typed stack-trace resolution produced by the run.
445    pub output: TraceErrorOutput,
446}
447
448impl TraceErrorProgrammaticOutput {
449    /// Typed stack-trace resolution retained by this run.
450    #[must_use]
451    pub const fn trace(&self) -> &TraceErrorOutput {
452        &self.output
453    }
454}
455
456/// Typed programmatic duplicate-code trace output before JSON serialization.
457#[derive(Debug)]
458pub struct TraceCloneProgrammaticOutput {
459    /// Typed clone trace produced by the run.
460    pub output: TraceCloneOutput,
461}
462
463impl TraceCloneProgrammaticOutput {
464    /// Typed clone trace retained by this run.
465    #[must_use]
466    pub const fn trace(&self) -> &TraceCloneOutput {
467        &self.output
468    }
469}
470
471/// Typed programmatic health / complexity output before JSON serialization.
472#[derive(Debug, Clone)]
473pub struct HealthProgrammaticOutput {
474    /// Typed health report produced by the run.
475    pub report: HealthReport,
476    /// Grouped findings when a grouping mode was requested.
477    pub grouping: Option<HealthGrouping>,
478    /// Project root used when serializing stable JSON paths.
479    pub root: PathBuf,
480    /// Analysis wall time, emitted as `elapsed_ms` when serialized.
481    pub elapsed: std::time::Duration,
482    /// Emit explain metadata when serialized.
483    pub explain: bool,
484    /// Non-fatal per-file diagnostics collected during the workspace walk.
485    pub workspace_diagnostics: Vec<WorkspaceDiagnostic>,
486    /// Suggested follow-up commands for the consumer.
487    pub next_steps: Vec<NextStep>,
488    /// Analysis run id stamped into telemetry metadata when present.
489    pub telemetry_analysis_run_id: Option<String>,
490    /// What became of the narrowing requests the run received, emitted as the
491    /// envelope's `request_outcomes`.
492    pub request_outcomes: Option<fallow_output::RequestOutcomes>,
493}
494
495/// Typed programmatic audit output before JSON serialization.
496#[derive(Debug, Clone)]
497pub struct AuditProgrammaticOutput {
498    /// Overall audit verdict.
499    pub verdict: AuditVerdict,
500    /// Per-category issue counts.
501    pub summary: AuditSummary,
502    /// New-vs-inherited counts and the configured gate.
503    pub attribution: AuditAttribution,
504    /// Number of changed files the audit analyzed.
505    pub changed_files_count: usize,
506    /// Git revision the audit compared against.
507    pub base_ref: String,
508    /// Human-readable description of how the base was chosen.
509    pub base_description: Option<String>,
510    /// Commit SHA of the analyzed head, when known.
511    pub head_sha: Option<String>,
512    /// Audit wall time, emitted as `elapsed_ms` when serialized.
513    pub elapsed: std::time::Duration,
514    /// Always `None` on the typed route. A skipped base means that the head
515    /// keys stand in for the base, so every finding is inherited. It does not
516    /// mean that no attribution ran.
517    pub base_snapshot_skipped: Option<bool>,
518    /// Attribution key sets of the base run, scoped to the changed files and
519    /// the pre-rename paths, with the rename remap and the dependency scope
520    /// applied. When the head run stands in for the base, it holds the head
521    /// keys. `None` when the gate needs no base or when the changeset is
522    /// empty.
523    pub base_snapshot: Option<AuditProgrammaticKeySnapshot>,
524    /// Dead-code section; `None` when the audit skipped it.
525    pub dead_code: Option<DeadCodeProgrammaticOutput>,
526    /// Duplication section; `None` when the audit skipped it.
527    pub duplication: Option<DuplicationProgrammaticOutput>,
528    /// Complexity (health) section; `None` when the audit skipped it.
529    pub complexity: Option<HealthProgrammaticOutput>,
530    /// Diff-risk findings. Every one is introduced by the change.
531    pub diff_risk: fallow_output::DiffRiskReport,
532    /// Suggested follow-up commands for the consumer.
533    pub next_steps: Vec<NextStep>,
534    /// Analysis run id stamped into telemetry metadata when present.
535    pub telemetry_analysis_run_id: Option<String>,
536}
537
538/// Stable audit key snapshot used to classify introduced vs inherited findings.
539#[derive(Debug, Clone, Default)]
540pub struct AuditProgrammaticKeySnapshot {
541    /// Base-run dead-code attribution keys.
542    pub dead_code: FxHashSet<String>,
543    /// Base-run complexity attribution keys.
544    pub health: FxHashSet<String>,
545    /// Base-run duplication group attribution keys.
546    pub dupes: FxHashSet<String>,
547}
548
549/// Typed programmatic decision-surface output before JSON serialization.
550#[derive(Debug, Clone)]
551pub struct DecisionSurfaceProgrammaticOutput {
552    /// Typed decision surface produced by the run.
553    pub surface: fallow_output::DecisionSurface,
554    /// Analysis wall time, emitted as `elapsed_ms` when serialized.
555    pub elapsed: std::time::Duration,
556    /// Analysis run id stamped into telemetry metadata when present.
557    pub telemetry_analysis_run_id: Option<String>,
558}
559
560/// Serialize a health / complexity report into the stable JSON output contract.
561///
562/// # Errors
563///
564/// Returns a serde error when the report cannot be converted to JSON.
565pub fn serialize_health_report_json(
566    input: HealthJsonReportInput<'_>,
567) -> Result<serde_json::Value, serde_json::Error> {
568    let root_prefix = format!("{}/", input.root.display());
569    let meta = match (input.explain, input.type_aware) {
570        (false, None) => None,
571        (true, None) => Some(health_meta()),
572        (false, Some(type_aware)) => Some(fallow_types::envelope::Meta {
573            type_aware: Some(type_aware),
574            ..fallow_types::envelope::Meta::default()
575        }),
576        (true, Some(type_aware)) => {
577            let mut meta = health_meta();
578            meta.type_aware = Some(type_aware);
579            Some(meta)
580        }
581    };
582    fallow_output::serialize_health_json_output(HealthJsonOutputInput {
583        output: HealthOutputInput {
584            gate_outcomes: input.gate_outcomes,
585            request_outcomes: input.request_outcomes,
586            schema_version: HEALTH_SCHEMA_VERSION,
587            version: env!("CARGO_PKG_VERSION").to_string(),
588            elapsed: input.elapsed,
589            report: input.report,
590            grouped_by: input.grouped_by,
591            groups: input.groups,
592            group_filter: input.group_filter,
593            meta,
594            workspace_diagnostics: input.workspace_diagnostics,
595            next_steps: input.next_steps,
596        },
597        root_prefix: Some(&root_prefix),
598        analysis_run_id: input.telemetry_analysis_run_id,
599    })
600}