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 /// Analysis run id stamped into telemetry metadata when present.
306 pub telemetry_analysis_run_id: Option<String>,
307}
308
309impl DuplicationProgrammaticOutput {
310 /// Typed duplication report payload retained by this run.
311 #[must_use]
312 pub const fn report(&self) -> &DupesReportPayload {
313 &self.output.report
314 }
315
316 /// Clone groups retained by this run, with typed actions and fingerprints.
317 #[must_use]
318 pub fn clone_groups(&self) -> &[CloneGroupFinding] {
319 &self.output.report.clone_groups
320 }
321
322 /// Clone families retained by this run, with nested typed clone groups.
323 #[must_use]
324 pub fn clone_families(&self) -> &[CloneFamilyFinding] {
325 &self.output.report.clone_families
326 }
327
328 /// Grouped duplication buckets when a grouping mode was used.
329 #[must_use]
330 pub fn groups(&self) -> Option<&[DuplicationGroup]> {
331 self.output.groups.as_deref()
332 }
333}
334
335/// Typed programmatic feature-flag output before JSON serialization.
336#[derive(Debug, Clone)]
337pub struct FeatureFlagsProgrammaticOutput {
338 /// Typed feature-flag envelope produced by the run.
339 pub output: FeatureFlagsOutput,
340 /// Analysis run id stamped into telemetry metadata when present.
341 pub telemetry_analysis_run_id: Option<String>,
342}
343
344impl FeatureFlagsProgrammaticOutput {
345 /// Feature flag findings retained by this run.
346 #[must_use]
347 pub fn feature_flags(&self) -> &[FeatureFlagFinding] {
348 &self.output.feature_flags
349 }
350
351 /// Number of feature flags retained by this run after scoping and limits.
352 #[must_use]
353 pub const fn total_flags(&self) -> usize {
354 self.output.total_flags
355 }
356}
357
358/// Typed programmatic export-trace output before JSON serialization. Carries
359/// either an export trace or (fallback) a class / enum / store member trace.
360#[derive(Debug)]
361pub struct TraceExportProgrammaticOutput {
362 /// Typed export-or-member trace produced by the run.
363 pub output: TraceExportTargetOutput,
364}
365
366impl TraceExportProgrammaticOutput {
367 /// Typed export-or-member trace retained by this run.
368 #[must_use]
369 pub const fn trace(&self) -> &TraceExportTargetOutput {
370 &self.output
371 }
372
373 /// The export trace, when the target resolved to a top-level export.
374 #[must_use]
375 pub const fn as_export(&self) -> Option<&TraceExportOutput> {
376 match &self.output {
377 TraceExportTargetOutput::Export(export) => Some(export),
378 TraceExportTargetOutput::Member(_) => None,
379 }
380 }
381
382 /// The member trace, when the target resolved to a class / enum / store
383 /// member (the `trace_export` fallback, issue #1744).
384 #[must_use]
385 pub const fn as_member(&self) -> Option<&TraceClassMemberOutput> {
386 match &self.output {
387 TraceExportTargetOutput::Member(member) => Some(member),
388 TraceExportTargetOutput::Export(_) => None,
389 }
390 }
391}
392
393/// Typed programmatic file-trace output before JSON serialization.
394#[derive(Debug)]
395pub struct TraceFileProgrammaticOutput {
396 /// Typed file trace produced by the run.
397 pub output: TraceFileOutput,
398}
399
400impl TraceFileProgrammaticOutput {
401 /// Typed file trace retained by this run.
402 #[must_use]
403 pub const fn trace(&self) -> &TraceFileOutput {
404 &self.output
405 }
406}
407
408/// Typed programmatic import-path-trace output before JSON serialization.
409#[derive(Debug)]
410pub struct TraceImportPathProgrammaticOutput {
411 /// Typed import-path trace produced by the run.
412 pub output: TraceImportPathOutput,
413}
414
415impl TraceImportPathProgrammaticOutput {
416 /// Typed import-path trace retained by this run.
417 #[must_use]
418 pub const fn trace(&self) -> &TraceImportPathOutput {
419 &self.output
420 }
421}
422
423/// Typed programmatic dependency-trace output before JSON serialization.
424#[derive(Debug)]
425pub struct TraceDependencyProgrammaticOutput {
426 /// Typed dependency trace produced by the run.
427 pub output: TraceDependencyOutput,
428}
429
430impl TraceDependencyProgrammaticOutput {
431 /// Typed dependency trace retained by this run.
432 #[must_use]
433 pub const fn trace(&self) -> &TraceDependencyOutput {
434 &self.output
435 }
436}
437
438/// Typed programmatic stack-trace resolution before JSON serialization.
439#[derive(Debug)]
440pub struct TraceErrorProgrammaticOutput {
441 /// Typed stack-trace resolution produced by the run.
442 pub output: TraceErrorOutput,
443}
444
445impl TraceErrorProgrammaticOutput {
446 /// Typed stack-trace resolution retained by this run.
447 #[must_use]
448 pub const fn trace(&self) -> &TraceErrorOutput {
449 &self.output
450 }
451}
452
453/// Typed programmatic duplicate-code trace output before JSON serialization.
454#[derive(Debug)]
455pub struct TraceCloneProgrammaticOutput {
456 /// Typed clone trace produced by the run.
457 pub output: TraceCloneOutput,
458}
459
460impl TraceCloneProgrammaticOutput {
461 /// Typed clone trace retained by this run.
462 #[must_use]
463 pub const fn trace(&self) -> &TraceCloneOutput {
464 &self.output
465 }
466}
467
468/// Typed programmatic health / complexity output before JSON serialization.
469#[derive(Debug, Clone)]
470pub struct HealthProgrammaticOutput {
471 /// Typed health report produced by the run.
472 pub report: HealthReport,
473 /// Grouped findings when a grouping mode was requested.
474 pub grouping: Option<HealthGrouping>,
475 /// Project root used when serializing stable JSON paths.
476 pub root: PathBuf,
477 /// Analysis wall time, emitted as `elapsed_ms` when serialized.
478 pub elapsed: std::time::Duration,
479 /// Emit explain metadata when serialized.
480 pub explain: bool,
481 /// Non-fatal per-file diagnostics collected during the workspace walk.
482 pub workspace_diagnostics: Vec<WorkspaceDiagnostic>,
483 /// Suggested follow-up commands for the consumer.
484 pub next_steps: Vec<NextStep>,
485 /// Analysis run id stamped into telemetry metadata when present.
486 pub telemetry_analysis_run_id: Option<String>,
487 /// What became of the narrowing requests the run received, emitted as the
488 /// envelope's `request_outcomes`.
489 pub request_outcomes: Option<fallow_output::RequestOutcomes>,
490}
491
492/// Typed programmatic audit output before JSON serialization.
493#[derive(Debug, Clone)]
494pub struct AuditProgrammaticOutput {
495 /// Overall audit verdict.
496 pub verdict: AuditVerdict,
497 /// Per-category issue counts.
498 pub summary: AuditSummary,
499 /// New-vs-inherited counts and the configured gate.
500 pub attribution: AuditAttribution,
501 /// Number of changed files the audit analyzed.
502 pub changed_files_count: usize,
503 /// Git revision the audit compared against.
504 pub base_ref: String,
505 /// Human-readable description of how the base was chosen.
506 pub base_description: Option<String>,
507 /// Commit SHA of the analyzed head, when known.
508 pub head_sha: Option<String>,
509 /// Audit wall time, emitted as `elapsed_ms` when serialized.
510 pub elapsed: std::time::Duration,
511 /// Always `None` on the typed route. A skipped base means that the head
512 /// keys stand in for the base, so every finding is inherited. It does not
513 /// mean that no attribution ran.
514 pub base_snapshot_skipped: Option<bool>,
515 /// Attribution key sets of the base run, scoped to the changed files and
516 /// the pre-rename paths, with the rename remap and the dependency scope
517 /// applied. When the head run stands in for the base, it holds the head
518 /// keys. `None` when the gate needs no base or when the changeset is
519 /// empty.
520 pub base_snapshot: Option<AuditProgrammaticKeySnapshot>,
521 /// Dead-code section; `None` when the audit skipped it.
522 pub dead_code: Option<DeadCodeProgrammaticOutput>,
523 /// Duplication section; `None` when the audit skipped it.
524 pub duplication: Option<DuplicationProgrammaticOutput>,
525 /// Complexity (health) section; `None` when the audit skipped it.
526 pub complexity: Option<HealthProgrammaticOutput>,
527 /// Diff-risk findings. Every one is introduced by the change.
528 pub diff_risk: fallow_output::DiffRiskReport,
529 /// Suggested follow-up commands for the consumer.
530 pub next_steps: Vec<NextStep>,
531 /// Analysis run id stamped into telemetry metadata when present.
532 pub telemetry_analysis_run_id: Option<String>,
533}
534
535/// Stable audit key snapshot used to classify introduced vs inherited findings.
536#[derive(Debug, Clone, Default)]
537pub struct AuditProgrammaticKeySnapshot {
538 /// Base-run dead-code attribution keys.
539 pub dead_code: FxHashSet<String>,
540 /// Base-run complexity attribution keys.
541 pub health: FxHashSet<String>,
542 /// Base-run duplication group attribution keys.
543 pub dupes: FxHashSet<String>,
544}
545
546/// Typed programmatic decision-surface output before JSON serialization.
547#[derive(Debug, Clone)]
548pub struct DecisionSurfaceProgrammaticOutput {
549 /// Typed decision surface produced by the run.
550 pub surface: fallow_output::DecisionSurface,
551 /// Analysis wall time, emitted as `elapsed_ms` when serialized.
552 pub elapsed: std::time::Duration,
553 /// Analysis run id stamped into telemetry metadata when present.
554 pub telemetry_analysis_run_id: Option<String>,
555}
556
557/// Serialize a health / complexity report into the stable JSON output contract.
558///
559/// # Errors
560///
561/// Returns a serde error when the report cannot be converted to JSON.
562pub fn serialize_health_report_json(
563 input: HealthJsonReportInput<'_>,
564) -> Result<serde_json::Value, serde_json::Error> {
565 let root_prefix = format!("{}/", input.root.display());
566 let meta = match (input.explain, input.type_aware) {
567 (false, None) => None,
568 (true, None) => Some(health_meta()),
569 (false, Some(type_aware)) => Some(fallow_types::envelope::Meta {
570 type_aware: Some(type_aware),
571 ..fallow_types::envelope::Meta::default()
572 }),
573 (true, Some(type_aware)) => {
574 let mut meta = health_meta();
575 meta.type_aware = Some(type_aware);
576 Some(meta)
577 }
578 };
579 fallow_output::serialize_health_json_output(HealthJsonOutputInput {
580 output: HealthOutputInput {
581 gate_outcomes: input.gate_outcomes,
582 request_outcomes: input.request_outcomes,
583 schema_version: HEALTH_SCHEMA_VERSION,
584 version: env!("CARGO_PKG_VERSION").to_string(),
585 elapsed: input.elapsed,
586 report: input.report,
587 grouped_by: input.grouped_by,
588 groups: input.groups,
589 group_filter: input.group_filter,
590 meta,
591 workspace_diagnostics: input.workspace_diagnostics,
592 next_steps: input.next_steps,
593 },
594 root_prefix: Some(&root_prefix),
595 analysis_run_id: input.telemetry_analysis_run_id,
596 })
597}