Skip to main content

fallow_api/
combined_output.rs

1//! Combined JSON output assembly shared by CLI and programmatic consumers.
2
3use std::path::Path;
4use std::time::Duration;
5
6use fallow_output::{
7    COMBINED_SCHEMA_VERSION, CombinedMeta, CombinedOutput, HealthReport, check_meta, dupes_meta,
8    harmonize_dead_code_health_suppress_line_actions, health_meta, retain_reported_rules,
9    serialize_combined_json_output, strip_root_prefix,
10};
11use fallow_types::envelope::{ElapsedMs, SchemaVersion, ToolVersion};
12use fallow_types::output::NextStep;
13use fallow_types::results::AnalysisResults;
14use fallow_types::workspace::WorkspaceDiagnostic;
15
16use crate::{
17    CheckJsonExtraOutputs, CheckJsonPayloadInput, DupesReportPayload, serialize_check_json_payload,
18};
19
20/// Dead-code section inputs for a bare combined JSON report.
21pub struct CombinedCheckJsonSection<'a> {
22    /// Typed dead-code results serialized into the `check` section.
23    pub results: &'a AnalysisResults,
24    /// Project root; its prefix is stripped from paths inside the section.
25    pub root: &'a Path,
26    /// Dead-code analysis wall time, emitted as the section's `elapsed_ms`.
27    pub elapsed: Duration,
28    /// Whether duplicate-export findings can be auto-fixed through config;
29    /// propagated onto their fix actions.
30    pub config_fixable: bool,
31    /// Caller-computed baseline and regression sections.
32    pub extras: CheckJsonExtraOutputs,
33}
34
35/// Inputs for bare `fallow --format json` output assembly.
36pub struct CombinedJsonOutputInput<'a> {
37    /// Applied refs for exact workspace package roots.
38    pub package_baselines: Vec<fallow_output::PackageBaselineStatus>,
39    /// Every gate this run evaluated, absent when it evaluated none. The
40    /// programmatic route runs no CLI-layer gate and leaves this `None`.
41    pub gate_outcomes: Option<fallow_output::GateOutcomes>,
42    /// Every narrowing or shaping request this run received, absent when it
43    /// was asked for nothing. The programmatic route resolves no CLI flag and
44    /// leaves this `None`; an entry whose `status` is not `applied` means the
45    /// report is wider than what was asked for.
46    pub request_outcomes: Option<fallow_output::RequestOutcomes>,
47
48    /// Dead-code section; `None` omits `check` from the envelope.
49    pub check: Option<CombinedCheckJsonSection<'a>>,
50    /// Duplication section; `None` omits `dupes` from the envelope.
51    pub dupes: Option<&'a DupesReportPayload>,
52    /// Health section; `None` omits `health` from the envelope.
53    pub health: Option<&'a HealthReport>,
54    /// Project root; its prefix is stripped from paths in every section.
55    pub root: &'a Path,
56    /// Total wall time across sections, emitted as the root `elapsed_ms`.
57    pub elapsed: Duration,
58    /// Emit per-section explain metadata under `meta`.
59    pub explain: bool,
60    /// Type-aware pass metadata, merged into the check section's meta even
61    /// when `explain` is off.
62    pub type_aware: Option<fallow_types::envelope::TypeAwareMeta>,
63    /// Workspace, source-discovery, and analysis-stage diagnostics for the
64    /// run: the same list the standalone envelopes carry, emitted on the
65    /// combined root and omitted when empty. The root is the only carrier, so
66    /// a run that skips a section still reports them (issue #2366).
67    pub workspace_diagnostics: Vec<WorkspaceDiagnostic>,
68    /// Suggested follow-up commands for the consumer.
69    pub next_steps: Vec<NextStep>,
70    /// Analysis run id stamped into telemetry metadata when present.
71    pub telemetry_analysis_run_id: Option<&'a str>,
72}
73
74/// Build and serialize bare combined JSON through the API output boundary.
75///
76/// # Errors
77///
78/// Returns a serde error when any typed section cannot be converted to JSON.
79pub fn serialize_combined_json(
80    input: CombinedJsonOutputInput<'_>,
81) -> Result<serde_json::Value, serde_json::Error> {
82    let mut check_results = input.check.as_ref().map(|section| section.results.clone());
83    let mut health_report = input.health.cloned();
84    harmonize_dead_code_health_suppress_line_actions(
85        check_results.as_mut(),
86        health_report.as_mut(),
87    );
88
89    let check = if let Some(section) = input.check {
90        if let Some(results) = check_results.as_ref() {
91            Some(serialize_combined_check_json(section, results)?)
92        } else {
93            None
94        }
95    } else {
96        None
97    };
98    let dupes = serialize_combined_dupes_json(input.dupes, input.root)?;
99    let health = serialize_combined_health_json(health_report.as_ref(), input.root)?;
100
101    let mut meta = input
102        .explain
103        .then(|| combined_meta_for_output(check.is_some(), dupes.is_some(), health.is_some()));
104    if let Some(type_aware) = input.type_aware {
105        let combined_meta = meta.get_or_insert(CombinedMeta {
106            check: None,
107            dupes: None,
108            health: None,
109            telemetry: None,
110        });
111        let check_meta = combined_meta
112            .check
113            .get_or_insert_with(fallow_types::envelope::Meta::default);
114        check_meta.type_aware = Some(type_aware);
115    }
116    if let (Some(results), Some(check_meta)) = (
117        check_results.as_ref(),
118        meta.as_mut().and_then(|meta| meta.check.as_mut()),
119    ) {
120        retain_reported_rules(check_meta, [results]);
121    }
122
123    let output = CombinedOutput {
124        package_baselines: input.package_baselines,
125        schema_version: SchemaVersion(COMBINED_SCHEMA_VERSION),
126        version: ToolVersion(env!("CARGO_PKG_VERSION").to_string()),
127        elapsed_ms: ElapsedMs(elapsed_ms_for_output(input.elapsed)),
128        gate_outcomes: input.gate_outcomes,
129        request_outcomes: input.request_outcomes,
130        meta,
131        check,
132        dupes,
133        health,
134        workspace_diagnostics: input.workspace_diagnostics,
135        next_steps: input.next_steps,
136    };
137
138    let mut value = serialize_combined_json_output(output, input.telemetry_analysis_run_id)?;
139    if let Some(diagnostics) = value.get_mut("workspace_diagnostics") {
140        strip_root_prefix(diagnostics, &format!("{}/", input.root.display()));
141    }
142    Ok(value)
143}
144
145fn serialize_combined_check_json(
146    section: CombinedCheckJsonSection<'_>,
147    results: &AnalysisResults,
148) -> Result<serde_json::Value, serde_json::Error> {
149    serialize_check_json_payload(CheckJsonPayloadInput {
150        results,
151        root: section.root,
152        elapsed: section.elapsed,
153        config_fixable: section.config_fixable,
154        extras: section.extras,
155        workspace_diagnostics: Vec::new(),
156    })
157}
158
159/// Build a combined duplication section without adding a nested root envelope.
160///
161/// # Errors
162///
163/// Returns a serde error when the typed duplication payload cannot be
164/// serialized.
165pub fn serialize_combined_dupes_json(
166    dupes: Option<&DupesReportPayload>,
167    root: &Path,
168) -> Result<Option<serde_json::Value>, serde_json::Error> {
169    let Some(payload) = dupes else {
170        return Ok(None);
171    };
172    let mut json = serde_json::to_value(payload)?;
173    let root_prefix = format!("{}/", root.display());
174    strip_root_prefix(&mut json, &root_prefix);
175    Ok(Some(json))
176}
177
178/// Build a combined health section without adding a nested root envelope.
179///
180/// # Errors
181///
182/// Returns a serde error when the typed health payload cannot be serialized.
183pub fn serialize_combined_health_json(
184    health: Option<&HealthReport>,
185    root: &Path,
186) -> Result<Option<serde_json::Value>, serde_json::Error> {
187    let Some(report) = health else {
188        return Ok(None);
189    };
190    let mut json = serde_json::to_value(report)?;
191    let root_prefix = format!("{}/", root.display());
192    strip_root_prefix(&mut json, &root_prefix);
193    Ok(Some(json))
194}
195
196fn elapsed_ms_for_output(elapsed: Duration) -> u64 {
197    u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX)
198}
199
200fn combined_meta_for_output(
201    include_check: bool,
202    include_dupes: bool,
203    include_health: bool,
204) -> CombinedMeta {
205    CombinedMeta {
206        check: include_check.then(check_meta),
207        dupes: include_dupes.then(dupes_meta),
208        health: include_health.then(health_meta),
209        telemetry: None,
210    }
211}
212
213#[cfg(test)]
214mod tests {
215    use std::time::Duration;
216
217    use fallow_output::{
218        ComplexityViolation, ExceededThreshold, FindingSeverity, HealthFinding, HealthReport,
219    };
220    use fallow_types::output_dead_code::UnusedExportFinding;
221    use fallow_types::output_health::{HealthFindingAction, HealthFindingActionType};
222    use fallow_types::results::{AnalysisResults, UnusedExport};
223    use fallow_types::workspace::{WorkspaceDiagnostic, WorkspaceDiagnosticKind};
224
225    use super::{CombinedCheckJsonSection, CombinedJsonOutputInput, serialize_combined_json};
226
227    #[test]
228    fn combined_json_root_contains_stable_envelope_fields() {
229        let root = serialize_combined_json(CombinedJsonOutputInput {
230            package_baselines: Vec::new(),
231            gate_outcomes: None,
232            request_outcomes: None,
233            check: None,
234            dupes: None,
235            health: None,
236            root: std::path::Path::new("."),
237            elapsed: Duration::from_millis(42),
238            explain: false,
239            type_aware: None,
240            workspace_diagnostics: Vec::new(),
241            next_steps: Vec::new(),
242            telemetry_analysis_run_id: None,
243        })
244        .expect("combined JSON root");
245
246        assert_eq!(
247            root.get("kind").and_then(serde_json::Value::as_str),
248            Some("combined")
249        );
250        assert_eq!(
251            root.get("elapsed_ms").and_then(serde_json::Value::as_u64),
252            Some(42)
253        );
254        assert!(root.get("schema_version").is_some());
255        assert!(root.get("version").is_some());
256    }
257
258    #[test]
259    fn combined_json_harmonizes_dead_code_and_health_suppress_actions_before_serialization() {
260        let root = std::path::Path::new("/project");
261        let path = root.join("src/shared.ts");
262        let mut results = AnalysisResults::default();
263        results
264            .unused_exports
265            .push(UnusedExportFinding::with_actions(UnusedExport {
266                path: path.clone(),
267                export_name: "value".to_string(),
268                is_type_only: false,
269                line: 7,
270                col: 0,
271                span_start: 0,
272                is_re_export: false,
273                deprecated: false,
274                deprecated_reason: None,
275            }));
276        let health = HealthReport {
277            findings: vec![HealthFinding::new(
278                ComplexityViolation {
279                    path,
280                    name: "expensive".to_string(),
281                    line: 7,
282                    col: 0,
283                    cyclomatic: 22,
284                    standard_cyclomatic: None,
285                    cognitive: 18,
286                    line_count: 40,
287                    param_count: 1,
288                    react_hook_count: 0,
289                    react_jsx_max_depth: 0,
290                    react_prop_count: 0,
291                    react_hook_profile: None,
292                    exceeded: ExceededThreshold::Both,
293                    effective_severity: None,
294                    severity: FindingSeverity::High,
295                    crap: None,
296                    mutation: None,
297                    coverage_pct: None,
298                    coverage_tier: None,
299                    coverage_source: None,
300                    inherited_from: None,
301                    component_rollup: None,
302                    contributions: Vec::new(),
303                    effective_thresholds: None,
304                    threshold_source: None,
305                    max_file_lines: None,
306                },
307                vec![HealthFindingAction {
308                    kind: HealthFindingActionType::SuppressLine,
309                    auto_fixable: false,
310                    description: "Suppress with an inline comment above the function declaration"
311                        .to_string(),
312                    note: None,
313                    comment: Some("// fallow-ignore-next-line complexity".to_string()),
314                    placement: Some("above-function-declaration".to_string()),
315                    target_path: None,
316                }],
317                None,
318            )],
319            ..HealthReport::default()
320        };
321
322        let output = serialize_combined_json(CombinedJsonOutputInput {
323            package_baselines: Vec::new(),
324            gate_outcomes: None,
325            request_outcomes: None,
326            check: Some(CombinedCheckJsonSection {
327                results: &results,
328                root,
329                elapsed: Duration::ZERO,
330                config_fixable: false,
331                extras: crate::CheckJsonExtraOutputs::default(),
332            }),
333            dupes: None,
334            health: Some(&health),
335            root,
336            elapsed: Duration::ZERO,
337            explain: false,
338            type_aware: None,
339            workspace_diagnostics: Vec::new(),
340            next_steps: Vec::new(),
341            telemetry_analysis_run_id: None,
342        })
343        .expect("combined JSON");
344
345        assert_eq!(
346            output["check"]["unused_exports"][0]["actions"][1]["comment"],
347            "// fallow-ignore-next-line unused-export, complexity"
348        );
349        assert_eq!(
350            output["health"]["findings"][0]["actions"][0]["comment"],
351            "// fallow-ignore-next-line unused-export, complexity"
352        );
353    }
354
355    fn combined_json_with_diagnostics(
356        root: &std::path::Path,
357        include_check: bool,
358        workspace_diagnostics: Vec<WorkspaceDiagnostic>,
359    ) -> serde_json::Value {
360        let results = AnalysisResults::default();
361        serialize_combined_json(CombinedJsonOutputInput {
362            package_baselines: Vec::new(),
363            gate_outcomes: None,
364            request_outcomes: None,
365            check: include_check.then(|| CombinedCheckJsonSection {
366                results: &results,
367                root,
368                elapsed: Duration::ZERO,
369                config_fixable: false,
370                extras: crate::CheckJsonExtraOutputs::default(),
371            }),
372            dupes: None,
373            health: None,
374            root,
375            elapsed: Duration::ZERO,
376            explain: false,
377            type_aware: None,
378            workspace_diagnostics,
379            next_steps: Vec::new(),
380            telemetry_analysis_run_id: None,
381        })
382        .expect("combined JSON")
383    }
384
385    fn malformed_yaml_diagnostic(root: &std::path::Path) -> WorkspaceDiagnostic {
386        WorkspaceDiagnostic::new(
387            root,
388            root.join("pnpm-workspace.yaml"),
389            WorkspaceDiagnosticKind::MalformedPnpmWorkspaceYaml {
390                error: "could not find expected ':'".to_owned(),
391            },
392        )
393    }
394
395    /// Issue #2366: the combined root carries the diagnostics it is given,
396    /// root-relative like the standalone envelopes, and omits the array when
397    /// there are none. The `check` section never grows its own copy, so the
398    /// document has exactly one carrier.
399    #[test]
400    fn combined_root_carries_workspace_diagnostics_root_relative_or_omits_them() {
401        let root = std::path::Path::new("/project");
402        let output =
403            combined_json_with_diagnostics(root, true, vec![malformed_yaml_diagnostic(root)]);
404        assert_eq!(
405            output["workspace_diagnostics"][0]["kind"],
406            "malformed-pnpm-workspace-yaml"
407        );
408        assert_eq!(
409            output["workspace_diagnostics"][0]["path"],
410            "pnpm-workspace.yaml"
411        );
412        assert!(
413            output["check"].is_object(),
414            "the check section is present, so the absence check below is not vacuous: {output}"
415        );
416        assert!(
417            output["check"].get("workspace_diagnostics").is_none(),
418            "the check section is not a second carrier: {output}"
419        );
420
421        let empty = combined_json_with_diagnostics(root, true, Vec::new());
422        assert!(
423            empty.get("workspace_diagnostics").is_none(),
424            "an empty list is omitted from the combined root: {empty}"
425        );
426    }
427
428    /// Issue #2366: the carrier does not depend on which sections ran, so a
429    /// combined run without a `check` section (`--skip check`, `--only health`,
430    /// `--only dupes`) still reports the diagnostics.
431    #[test]
432    fn combined_root_carries_workspace_diagnostics_without_a_check_section() {
433        let root = std::path::Path::new("/project");
434        let output =
435            combined_json_with_diagnostics(root, false, vec![malformed_yaml_diagnostic(root)]);
436        assert!(
437            output.get("check").is_none(),
438            "this run has no check section: {output}"
439        );
440        assert_eq!(
441            output["workspace_diagnostics"][0]["kind"],
442            "malformed-pnpm-workspace-yaml"
443        );
444        assert_eq!(
445            output["workspace_diagnostics"][0]["path"],
446            "pnpm-workspace.yaml"
447        );
448    }
449}