fallow-api 3.15.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
//! Typed programmatic runtime outputs and shared output-contract serializers.

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

pub use fallow_output::HEALTH_SCHEMA_VERSION;
use fallow_output::{
    CheckOutput, DupesOutput, FeatureFlagFinding, FeatureFlagsOutput as FeatureFlagsOutputContract,
    GroupByMode, HealthGroup, HealthGrouping, HealthJsonOutputInput, HealthOutputInput,
    HealthReport, RootEnvelopeMode, health_meta,
};
use fallow_types::output::NextStep;
use fallow_types::output_dead_code::{
    BoundaryCallViolationFinding, BoundaryCoverageViolationFinding, BoundaryViolationFinding,
    CircularDependencyFinding,
};
use fallow_types::results::AnalysisResults;
use fallow_types::workspace::WorkspaceDiagnostic;
use rustc_hash::FxHashSet;

use crate::{AuditAttribution, AuditSummary, AuditVerdict};
use crate::{CloneFamilyFinding, CloneGroupFinding, DupesReportPayload, DuplicationGroup};

/// Concrete dead-code output contract returned by typed programmatic runs.
pub type DeadCodeOutput = CheckOutput;

/// Concrete circular-dependency output contract returned by typed runs.
pub type CircularDependenciesOutput = CheckOutput;

/// Concrete boundary-family output contract returned by typed runs.
pub type BoundaryViolationsOutput = CheckOutput;

/// Concrete duplication output contract returned by typed programmatic runs.
pub type DuplicationOutput = DupesOutput<DupesReportPayload, DuplicationGroup>;

/// Concrete feature-flag output contract returned by typed programmatic runs.
pub type FeatureFlagsOutput = FeatureFlagsOutputContract;

/// Concrete export trace output returned by typed programmatic runs.
pub type TraceExportOutput = fallow_types::trace::ExportTrace;

/// Concrete class / enum / store member trace output (the `trace_export`
/// fallback when the name is a member rather than a top-level export). See
/// issue #1744.
pub type TraceClassMemberOutput = fallow_types::trace::ClassMemberTrace;

/// The `trace_export` target: either a top-level export or (fallback) a class /
/// enum / store member declared on one. Serialized untagged so the export shape
/// stays byte-identical to the historical contract and the member shape matches
/// the CLI's member trace; consumers distinguish by the presence of
/// `export_name` (export) vs `member_name` / `owner_export` (member).
#[derive(Debug, serde::Serialize)]
#[serde(untagged)]
pub enum TraceExportTargetOutput {
    /// A top-level export trace.
    Export(TraceExportOutput),
    /// A class / enum / store member trace.
    Member(TraceClassMemberOutput),
}

/// Concrete file trace output returned by typed programmatic runs.
pub type TraceFileOutput = fallow_types::trace::FileTrace;

/// Concrete dependency trace output returned by typed programmatic runs.
pub type TraceDependencyOutput = fallow_types::trace::DependencyTrace;

/// Concrete duplicate-code trace output returned by typed programmatic runs.
pub type TraceCloneOutput = fallow_types::trace::CloneTrace;

/// Inputs for serializing health JSON output through the API boundary.
pub struct HealthJsonReportInput<'a> {
    /// Typed health report to serialize.
    pub report: HealthReport,
    /// Project root; its prefix is stripped from every path in the output.
    pub root: &'a Path,
    /// Analysis wall time, emitted as `elapsed_ms`.
    pub elapsed: std::time::Duration,
    /// Emit explain metadata under `meta`.
    pub explain: bool,
    /// Type-aware pass metadata merged into `meta` even when `explain` is
    /// off.
    pub type_aware: Option<fallow_types::envelope::TypeAwareMeta>,
    /// Grouping axis recorded as `grouped_by`; `None` when ungrouped.
    pub grouped_by: Option<GroupByMode>,
    /// Precomputed group buckets matching `grouped_by`.
    pub groups: Option<Vec<HealthGroup>>,
    /// Non-fatal per-file diagnostics collected during the workspace walk.
    pub workspace_diagnostics: Vec<WorkspaceDiagnostic>,
    /// Suggested follow-up commands for the consumer.
    pub next_steps: Vec<NextStep>,
    /// Whether the root envelope carries a `kind` discriminant.
    pub envelope_mode: RootEnvelopeMode,
    /// Analysis run id stamped into telemetry metadata when present.
    pub telemetry_analysis_run_id: Option<&'a str>,
}

/// Typed programmatic combined output before JSON serialization.
#[derive(Debug, Clone)]
pub struct CombinedProgrammaticOutput {
    /// Dead-code section; `None` when the run skipped it.
    pub dead_code: Option<DeadCodeProgrammaticOutput>,
    /// Duplication section; `None` when the run skipped it.
    pub duplication: Option<DuplicationProgrammaticOutput>,
    /// Health section; `None` when the run skipped it.
    pub health: Option<HealthProgrammaticOutput>,
    /// Project root used when serializing stable JSON paths.
    pub root: PathBuf,
    /// Total wall time across sections, emitted as the root `elapsed_ms`.
    pub elapsed: std::time::Duration,
    /// Emit per-section explain metadata when serialized.
    pub explain: bool,
    /// Suggested follow-up commands for the consumer.
    pub next_steps: Vec<NextStep>,
    /// Whether the serialized root envelope carries a `kind` discriminant.
    pub envelope_mode: RootEnvelopeMode,
    /// Analysis run id stamped into telemetry metadata when present.
    pub telemetry_analysis_run_id: Option<String>,
}

/// Typed programmatic dead-code output before JSON serialization.
///
/// This is the API boundary embedders should use when they need access to the
/// typed engine/output result. Protocol surfaces serialize it explicitly at
/// their JSON boundary.
#[derive(Debug, Clone)]
pub struct DeadCodeProgrammaticOutput {
    /// Typed dead-code envelope produced by the run.
    pub output: DeadCodeOutput,
    /// Project root used when serializing stable JSON paths.
    pub root: PathBuf,
    /// Whether duplicate-export findings can be auto-fixed through config;
    /// propagated onto their fix actions when serialized.
    pub config_fixable: bool,
    /// Whether the serialized root envelope carries a `kind` discriminant.
    pub envelope_mode: RootEnvelopeMode,
    /// Analysis run id stamped into telemetry metadata when present.
    pub telemetry_analysis_run_id: Option<String>,
}

impl DeadCodeProgrammaticOutput {
    /// Full typed dead-code issue arrays retained by this run.
    #[must_use]
    pub fn results(&self) -> &AnalysisResults {
        &self.output.results
    }

    /// Project-relative root used when serializing stable JSON paths.
    #[must_use]
    pub fn root(&self) -> &Path {
        &self.root
    }
}

/// Typed programmatic circular-dependency output before JSON serialization.
///
/// The wire envelope stays the dead-code/check contract, but the Rust API
/// surface is family-specific so embedders do not have to treat this as a
/// generic dead-code run.
#[derive(Debug, Clone)]
pub struct CircularDependenciesProgrammaticOutput {
    /// Typed check envelope scoped to circular-dependency findings.
    pub output: CircularDependenciesOutput,
    /// Project root used when serializing stable JSON paths.
    pub root: PathBuf,
    /// Whether the serialized root envelope carries a `kind` discriminant.
    pub envelope_mode: RootEnvelopeMode,
    /// Analysis run id stamped into telemetry metadata when present.
    pub telemetry_analysis_run_id: Option<String>,
}

impl CircularDependenciesProgrammaticOutput {
    /// Full typed issue arrays retained by this family run.
    #[must_use]
    pub fn results(&self) -> &AnalysisResults {
        &self.output.results
    }

    /// The circular dependency findings retained by this family run.
    #[must_use]
    pub fn circular_dependencies(&self) -> &[CircularDependencyFinding] {
        &self.output.results.circular_dependencies
    }
}

impl From<DeadCodeProgrammaticOutput> for CircularDependenciesProgrammaticOutput {
    fn from(value: DeadCodeProgrammaticOutput) -> Self {
        Self {
            output: value.output,
            root: value.root,
            envelope_mode: value.envelope_mode,
            telemetry_analysis_run_id: value.telemetry_analysis_run_id,
        }
    }
}

/// Typed programmatic boundary-family output before JSON serialization.
///
/// This covers banned imports, boundary coverage, and forbidden call findings
/// while preserving the stable dead-code/check JSON envelope.
#[derive(Debug, Clone)]
pub struct BoundaryViolationsProgrammaticOutput {
    /// Typed check envelope scoped to boundary-family findings.
    pub output: BoundaryViolationsOutput,
    /// Project root used when serializing stable JSON paths.
    pub root: PathBuf,
    /// Whether the serialized root envelope carries a `kind` discriminant.
    pub envelope_mode: RootEnvelopeMode,
    /// Analysis run id stamped into telemetry metadata when present.
    pub telemetry_analysis_run_id: Option<String>,
}

impl BoundaryViolationsProgrammaticOutput {
    /// Full typed issue arrays retained by this family run.
    #[must_use]
    pub fn results(&self) -> &AnalysisResults {
        &self.output.results
    }

    /// Banned import boundary findings retained by this family run.
    #[must_use]
    pub fn boundary_violations(&self) -> &[BoundaryViolationFinding] {
        &self.output.results.boundary_violations
    }

    /// Boundary coverage findings retained by this family run.
    #[must_use]
    pub fn boundary_coverage_violations(&self) -> &[BoundaryCoverageViolationFinding] {
        &self.output.results.boundary_coverage_violations
    }

    /// Forbidden call findings retained by this family run.
    #[must_use]
    pub fn boundary_call_violations(&self) -> &[BoundaryCallViolationFinding] {
        &self.output.results.boundary_call_violations
    }
}

impl From<DeadCodeProgrammaticOutput> for BoundaryViolationsProgrammaticOutput {
    fn from(value: DeadCodeProgrammaticOutput) -> Self {
        Self {
            output: value.output,
            root: value.root,
            envelope_mode: value.envelope_mode,
            telemetry_analysis_run_id: value.telemetry_analysis_run_id,
        }
    }
}

/// Typed programmatic duplication output before JSON serialization.
#[derive(Debug, Clone)]
pub struct DuplicationProgrammaticOutput {
    /// Typed duplication envelope produced by the run.
    pub output: DuplicationOutput,
    /// Project root used when serializing stable JSON paths.
    pub root: PathBuf,
    /// Maximum allowed duplication percentage from the resolved config;
    /// 0 disables the percentage gate.
    pub threshold: f64,
    /// Whether the serialized root envelope carries a `kind` discriminant.
    pub envelope_mode: RootEnvelopeMode,
    /// Analysis run id stamped into telemetry metadata when present.
    pub telemetry_analysis_run_id: Option<String>,
}

impl DuplicationProgrammaticOutput {
    /// Typed duplication report payload retained by this run.
    #[must_use]
    pub const fn report(&self) -> &DupesReportPayload {
        &self.output.report
    }

    /// Clone groups retained by this run, with typed actions and fingerprints.
    #[must_use]
    pub fn clone_groups(&self) -> &[CloneGroupFinding] {
        &self.output.report.clone_groups
    }

    /// Clone families retained by this run, with nested typed clone groups.
    #[must_use]
    pub fn clone_families(&self) -> &[CloneFamilyFinding] {
        &self.output.report.clone_families
    }

    /// Grouped duplication buckets when a grouping mode was used.
    #[must_use]
    pub fn groups(&self) -> Option<&[DuplicationGroup]> {
        self.output.groups.as_deref()
    }
}

/// Typed programmatic feature-flag output before JSON serialization.
#[derive(Debug, Clone)]
pub struct FeatureFlagsProgrammaticOutput {
    /// Typed feature-flag envelope produced by the run.
    pub output: FeatureFlagsOutput,
    /// Whether the serialized root envelope carries a `kind` discriminant.
    pub envelope_mode: RootEnvelopeMode,
    /// Analysis run id stamped into telemetry metadata when present.
    pub telemetry_analysis_run_id: Option<String>,
}

impl FeatureFlagsProgrammaticOutput {
    /// Feature flag findings retained by this run.
    #[must_use]
    pub fn feature_flags(&self) -> &[FeatureFlagFinding] {
        &self.output.feature_flags
    }

    /// Number of feature flags retained by this run after scoping and limits.
    #[must_use]
    pub const fn total_flags(&self) -> usize {
        self.output.total_flags
    }
}

/// Typed programmatic export-trace output before JSON serialization. Carries
/// either an export trace or (fallback) a class / enum / store member trace.
#[derive(Debug)]
pub struct TraceExportProgrammaticOutput {
    /// Typed export-or-member trace produced by the run.
    pub output: TraceExportTargetOutput,
}

impl TraceExportProgrammaticOutput {
    /// Typed export-or-member trace retained by this run.
    #[must_use]
    pub const fn trace(&self) -> &TraceExportTargetOutput {
        &self.output
    }

    /// The export trace, when the target resolved to a top-level export.
    #[must_use]
    pub const fn as_export(&self) -> Option<&TraceExportOutput> {
        match &self.output {
            TraceExportTargetOutput::Export(export) => Some(export),
            TraceExportTargetOutput::Member(_) => None,
        }
    }

    /// The member trace, when the target resolved to a class / enum / store
    /// member (the `trace_export` fallback, issue #1744).
    #[must_use]
    pub const fn as_member(&self) -> Option<&TraceClassMemberOutput> {
        match &self.output {
            TraceExportTargetOutput::Member(member) => Some(member),
            TraceExportTargetOutput::Export(_) => None,
        }
    }
}

/// Typed programmatic file-trace output before JSON serialization.
#[derive(Debug)]
pub struct TraceFileProgrammaticOutput {
    /// Typed file trace produced by the run.
    pub output: TraceFileOutput,
}

impl TraceFileProgrammaticOutput {
    /// Typed file trace retained by this run.
    #[must_use]
    pub const fn trace(&self) -> &TraceFileOutput {
        &self.output
    }
}

/// Typed programmatic dependency-trace output before JSON serialization.
#[derive(Debug)]
pub struct TraceDependencyProgrammaticOutput {
    /// Typed dependency trace produced by the run.
    pub output: TraceDependencyOutput,
}

impl TraceDependencyProgrammaticOutput {
    /// Typed dependency trace retained by this run.
    #[must_use]
    pub const fn trace(&self) -> &TraceDependencyOutput {
        &self.output
    }
}

/// Typed programmatic duplicate-code trace output before JSON serialization.
#[derive(Debug)]
pub struct TraceCloneProgrammaticOutput {
    /// Typed clone trace produced by the run.
    pub output: TraceCloneOutput,
}

impl TraceCloneProgrammaticOutput {
    /// Typed clone trace retained by this run.
    #[must_use]
    pub const fn trace(&self) -> &TraceCloneOutput {
        &self.output
    }
}

/// Typed programmatic health / complexity output before JSON serialization.
#[derive(Debug, Clone)]
pub struct HealthProgrammaticOutput {
    /// Typed health report produced by the run.
    pub report: HealthReport,
    /// Grouped findings when a grouping mode was requested.
    pub grouping: Option<HealthGrouping>,
    /// Project root used when serializing stable JSON paths.
    pub root: PathBuf,
    /// Analysis wall time, emitted as `elapsed_ms` when serialized.
    pub elapsed: std::time::Duration,
    /// Emit explain metadata when serialized.
    pub explain: bool,
    /// Non-fatal per-file diagnostics collected during the workspace walk.
    pub workspace_diagnostics: Vec<WorkspaceDiagnostic>,
    /// Suggested follow-up commands for the consumer.
    pub next_steps: Vec<NextStep>,
    /// Whether the serialized root envelope carries a `kind` discriminant.
    pub envelope_mode: RootEnvelopeMode,
    /// Analysis run id stamped into telemetry metadata when present.
    pub telemetry_analysis_run_id: Option<String>,
}

/// Typed programmatic audit output before JSON serialization.
#[derive(Debug, Clone)]
pub struct AuditProgrammaticOutput {
    /// Overall audit verdict.
    pub verdict: AuditVerdict,
    /// Per-category issue counts.
    pub summary: AuditSummary,
    /// New-vs-inherited counts and the configured gate.
    pub attribution: AuditAttribution,
    /// Number of changed files the audit analyzed.
    pub changed_files_count: usize,
    /// Git revision the audit compared against.
    pub base_ref: String,
    /// Human-readable description of how the base was chosen.
    pub base_description: Option<String>,
    /// Commit SHA of the analyzed head, when known.
    pub head_sha: Option<String>,
    /// Audit wall time, emitted as `elapsed_ms` when serialized.
    pub elapsed: std::time::Duration,
    /// `Some(true)` when the base snapshot was skipped, so no attribution
    /// ran.
    pub base_snapshot_skipped: Option<bool>,
    /// Attribution key sets computed from the base run; present only when a
    /// base snapshot was analyzed.
    pub base_snapshot: Option<AuditProgrammaticKeySnapshot>,
    /// Dead-code section; `None` when the audit skipped it.
    pub dead_code: Option<DeadCodeProgrammaticOutput>,
    /// Duplication section; `None` when the audit skipped it.
    pub duplication: Option<DuplicationProgrammaticOutput>,
    /// Complexity (health) section; `None` when the audit skipped it.
    pub complexity: Option<HealthProgrammaticOutput>,
    /// Suggested follow-up commands for the consumer.
    pub next_steps: Vec<NextStep>,
    /// Whether the serialized root envelope carries a `kind` discriminant.
    pub envelope_mode: RootEnvelopeMode,
    /// Analysis run id stamped into telemetry metadata when present.
    pub telemetry_analysis_run_id: Option<String>,
}

/// Stable audit key snapshot used to classify introduced vs inherited findings.
#[derive(Debug, Clone, Default)]
pub struct AuditProgrammaticKeySnapshot {
    /// Base-run dead-code attribution keys.
    pub dead_code: FxHashSet<String>,
    /// Base-run complexity attribution keys.
    pub health: FxHashSet<String>,
    /// Base-run duplication group attribution keys.
    pub dupes: FxHashSet<String>,
}

/// Typed programmatic decision-surface output before JSON serialization.
#[derive(Debug, Clone)]
pub struct DecisionSurfaceProgrammaticOutput {
    /// Typed decision surface produced by the run.
    pub surface: fallow_output::DecisionSurface,
    /// Analysis wall time, emitted as `elapsed_ms` when serialized.
    pub elapsed: std::time::Duration,
    /// Whether the serialized root envelope carries a `kind` discriminant.
    pub envelope_mode: RootEnvelopeMode,
    /// Analysis run id stamped into telemetry metadata when present.
    pub telemetry_analysis_run_id: Option<String>,
}

/// Serialize a health / complexity report into the stable JSON output contract.
///
/// # Errors
///
/// Returns a serde error when the report cannot be converted to JSON.
pub fn serialize_health_report_json(
    input: HealthJsonReportInput<'_>,
) -> Result<serde_json::Value, serde_json::Error> {
    let root_prefix = format!("{}/", input.root.display());
    let meta = match (input.explain, input.type_aware) {
        (false, None) => None,
        (true, None) => Some(health_meta()),
        (false, Some(type_aware)) => Some(fallow_types::envelope::Meta {
            type_aware: Some(type_aware),
            ..fallow_types::envelope::Meta::default()
        }),
        (true, Some(type_aware)) => {
            let mut meta = health_meta();
            meta.type_aware = Some(type_aware);
            Some(meta)
        }
    };
    fallow_output::serialize_health_json_output(HealthJsonOutputInput {
        output: HealthOutputInput {
            schema_version: HEALTH_SCHEMA_VERSION,
            version: env!("CARGO_PKG_VERSION").to_string(),
            elapsed: input.elapsed,
            report: input.report,
            grouped_by: input.grouped_by,
            groups: input.groups,
            meta,
            workspace_diagnostics: input.workspace_diagnostics,
            next_steps: input.next_steps,
        },
        root_prefix: Some(&root_prefix),
        envelope_mode: input.envelope_mode,
        analysis_run_id: input.telemetry_analysis_run_id,
    })
}