fallow-api 3.25.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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
//! JSON protocol serializers for typed programmatic runtime output.
//!
//! Runtime entry points return typed output from [`crate::runtime`]. CLI, MCP,
//! NAPI, and other protocol surfaces call these serializers at their JSON
//! boundary.

use crate::{
    ProgrammaticError,
    runtime::{
        AuditProgrammaticOutput, BoundaryViolationsProgrammaticOutput,
        CircularDependenciesProgrammaticOutput, CombinedProgrammaticOutput,
        DeadCodeProgrammaticOutput, DecisionSurfaceProgrammaticOutput,
        DuplicationProgrammaticOutput, FeatureFlagsProgrammaticOutput, HealthJsonReportInput,
        HealthProgrammaticOutput, TraceCloneProgrammaticOutput, TraceDependencyProgrammaticOutput,
        TraceErrorProgrammaticOutput, TraceExportProgrammaticOutput, TraceFileProgrammaticOutput,
        TraceImportPathProgrammaticOutput, serialize_health_report_json,
    },
};
use fallow_output::{
    AUDIT_SCHEMA_VERSION, CheckOutput, GroupByMode, RootEnvelopeMode,
    build_decision_surface_output, serialize_check_json_output,
    serialize_decision_surface_json_output, serialize_dupes_json_output,
    serialize_feature_flags_json_output, strip_root_prefix,
};
use fallow_types::envelope::{ElapsedMs, SchemaVersion, ToolVersion};
use fallow_types::workspace::{WorkspaceDiagnostic, merge_workspace_diagnostics};
use serde::Serialize;
use std::path::Path;
use std::time::Duration;

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

/// Serialize typed combined output into the stable JSON compatibility contract.
///
/// # Errors
///
/// Returns a structured error if one of the combined sections cannot serialize.
pub fn serialize_combined_programmatic_json(
    output: CombinedProgrammaticOutput,
) -> ProgrammaticResult<serde_json::Value> {
    let CombinedProgrammaticOutput {
        dead_code,
        duplication,
        health,
        root,
        elapsed,
        explain,
        next_steps,
        envelope_mode,
        telemetry_analysis_run_id,
    } = output;
    let workspace_diagnostics =
        combined_workspace_diagnostics(dead_code.as_ref(), health.as_ref(), duplication.as_ref());
    crate::serialize_combined_json(crate::CombinedJsonOutputInput {
        check: dead_code
            .as_ref()
            .map(|dead_code| crate::CombinedCheckJsonSection {
                results: &dead_code.output.results,
                root: &dead_code.root,
                elapsed: Duration::from_millis(dead_code.output.elapsed_ms.0),
                config_fixable: dead_code.config_fixable,
                extras: crate::CheckJsonExtraOutputs::default(),
            }),
        dupes: duplication
            .as_ref()
            .map(|duplication| &duplication.output.report),
        health: health.as_ref().map(|health| &health.report),
        root: &root,
        elapsed,
        explain,
        type_aware: None,
        workspace_diagnostics,
        next_steps,
        envelope_mode,
        telemetry_analysis_run_id: telemetry_analysis_run_id.as_deref(),
    })
    .map_err(|err| {
        ProgrammaticError::new(format!("failed to serialize combined report: {err}"), 2)
            .with_code("FALLOW_SERIALIZE_COMBINED_REPORT")
            .with_context("combined")
    })
}

/// Union the combined run's workspace diagnostics across its typed sections.
///
/// Each section captured the list as of the moment its own analysis finished,
/// and those lists can differ: a combined run walks the project once per
/// analysis, per-analysis `production` modes can give those walks different
/// file sets, and each walk clears the previous walk's source-discovery
/// entries. No single section therefore holds everything the run recorded, so
/// the root carries the deduplicated union in section order (dead code, then
/// health, then duplication) and a run missing a section (`--skip check`,
/// `--only health`, `--only dupes`) still reports what its remaining analyses
/// recorded.
///
/// Each section carries the diagnostics owned by its run. The combined root
/// unions those values without importing process-global history.
fn combined_workspace_diagnostics(
    dead_code: Option<&DeadCodeProgrammaticOutput>,
    health: Option<&HealthProgrammaticOutput>,
    duplication: Option<&DuplicationProgrammaticOutput>,
) -> Vec<WorkspaceDiagnostic> {
    let merged = merge_workspace_diagnostics(
        dead_code.map_or_else(Vec::new, |dead_code| {
            dead_code.output.workspace_diagnostics.clone()
        }),
        health.map_or_else(Vec::new, |health| health.workspace_diagnostics.clone()),
    );
    merge_workspace_diagnostics(
        merged,
        duplication.map_or_else(Vec::new, |duplication| {
            duplication.output.workspace_diagnostics.clone()
        }),
    )
}

/// Serialize typed decision-surface output into the stable JSON contract.
///
/// # Errors
///
/// Returns a structured error if the decision-surface payload cannot serialize.
pub fn serialize_decision_surface_programmatic_json(
    output: DecisionSurfaceProgrammaticOutput,
) -> ProgrammaticResult<serde_json::Value> {
    let DecisionSurfaceProgrammaticOutput {
        surface,
        elapsed: _,
        envelope_mode,
        telemetry_analysis_run_id,
    } = output;
    let payload = build_decision_surface_output(&surface);
    serialize_decision_surface_json_output(
        payload,
        envelope_mode,
        telemetry_analysis_run_id.as_deref(),
    )
    .map_err(|err| {
        ProgrammaticError::new(format!("failed to serialize decision surface: {err}"), 2)
            .with_code("FALLOW_SERIALIZE_DECISION_SURFACE")
            .with_context("decision-surface")
    })
}

/// Serialize typed audit output into the stable JSON compatibility contract.
///
/// # Errors
///
/// Returns a structured error if one of the audit sections cannot serialize.
pub fn serialize_audit_programmatic_json(
    output: AuditProgrammaticOutput,
) -> ProgrammaticResult<serde_json::Value> {
    let base_snapshot = output.base_snapshot.as_ref();
    let dead_code = output
        .dead_code
        .as_ref()
        .map(|dead_code| serialize_audit_dead_code(dead_code, base_snapshot))
        .transpose()?;
    let duplication = output
        .duplication
        .as_ref()
        .map(|duplication| serialize_audit_duplication(duplication, base_snapshot))
        .transpose()?;
    let complexity = output
        .complexity
        .as_ref()
        .map(|complexity| serialize_audit_complexity(complexity, base_snapshot))
        .transpose()?;

    crate::serialize_audit_json(
        crate::AuditJsonOutputInput {
            header: crate::AuditJsonHeaderInput {
                schema_version: SchemaVersion(AUDIT_SCHEMA_VERSION),
                version: ToolVersion(env!("CARGO_PKG_VERSION").to_string()),
                verdict: output.verdict,
                changed_files_count: u32::try_from(output.changed_files_count).unwrap_or(u32::MAX),
                base_ref: output.base_ref,
                base_description: output.base_description,
                head_sha: output.head_sha,
                elapsed_ms: ElapsedMs(
                    u64::try_from(output.elapsed.as_millis()).unwrap_or(u64::MAX),
                ),
                base_snapshot_skipped: output.base_snapshot_skipped,
                summary: output.summary,
                attribution: output.attribution,
            },
            meta: None,
            dead_code,
            duplication,
            complexity,
            next_steps: output.next_steps,
        },
        output.envelope_mode,
        output.telemetry_analysis_run_id.as_deref(),
    )
    .map_err(|err| {
        ProgrammaticError::new(format!("failed to serialize audit report: {err}"), 2)
            .with_code("FALLOW_SERIALIZE_AUDIT_REPORT")
            .with_context("audit")
    })
}

/// Serialize the audit envelope's dead-code sub-result.
///
/// The sub-result is a `CheckOutput` body, so it carries the run's
/// `workspace_diagnostics[]` the way the standalone `dead-code` envelope and
/// the combined `check` section do. The two audit routes agree on everything
/// the dead-code analysis records. The programmatic route serializes the typed
/// output's by-value session snapshot, while the CLI route serializes the same
/// snapshot from `CheckResult`. Neither route rereads process-global diagnostic
/// history while building the envelope, so output is independent of call order
/// and of later analysis walks in the same process.
fn serialize_audit_dead_code(
    output: &DeadCodeProgrammaticOutput,
    base_snapshot: Option<&crate::AuditProgrammaticKeySnapshot>,
) -> ProgrammaticResult<serde_json::Value> {
    let mut json = crate::serialize_check_json_payload(crate::CheckJsonPayloadInput {
        results: &output.output.results,
        root: &output.root,
        elapsed: Duration::from_millis(output.output.elapsed_ms.0),
        config_fixable: output.config_fixable,
        extras: crate::CheckJsonExtraOutputs::default(),
        workspace_diagnostics: output.output.workspace_diagnostics.clone(),
    })
    .map_err(|err| {
        ProgrammaticError::new(format!("failed to serialize audit dead-code: {err}"), 2)
            .with_code("FALLOW_SERIALIZE_AUDIT_DEAD_CODE")
            .with_context("audit.deadCode")
    })?;
    if let Some(base) = base_snapshot {
        if has_persisted_introduced_flags(&json) {
            crate::audit_keys::annotate_stale_suppressions_json(
                &mut json,
                &output.output.results,
                &output.root,
                &base.dead_code,
            );
        } else {
            crate::audit_keys::annotate_dead_code_json(
                &mut json,
                &output.output.results,
                &output.root,
                &base.dead_code,
            );
        }
    }
    Ok(json)
}

fn serialize_audit_duplication(
    output: &DuplicationProgrammaticOutput,
    base_snapshot: Option<&crate::AuditProgrammaticKeySnapshot>,
) -> ProgrammaticResult<serde_json::Value> {
    let mut json = serde_json::to_value(&output.output.report).map_err(|err| {
        ProgrammaticError::new(format!("failed to serialize audit duplication: {err}"), 2)
            .with_code("FALLOW_SERIALIZE_AUDIT_DUPLICATION")
            .with_context("audit.duplication")
    })?;
    let root_prefix = format!("{}/", output.root.display());
    strip_root_prefix(&mut json, &root_prefix);
    if let Some(base) = base_snapshot
        && !has_persisted_introduced_flags(&json)
    {
        annotate_audit_duplication_json(&mut json, output, &base.dupes);
    }
    Ok(json)
}

fn serialize_audit_complexity(
    output: &HealthProgrammaticOutput,
    base_snapshot: Option<&crate::AuditProgrammaticKeySnapshot>,
) -> ProgrammaticResult<serde_json::Value> {
    let mut json = serde_json::to_value(&output.report).map_err(|err| {
        ProgrammaticError::new(format!("failed to serialize audit complexity: {err}"), 2)
            .with_code("FALLOW_SERIALIZE_AUDIT_COMPLEXITY")
            .with_context("audit.complexity")
    })?;
    let root_prefix = format!("{}/", output.root.display());
    strip_root_prefix(&mut json, &root_prefix);
    if let Some(base) = base_snapshot {
        crate::audit_keys::annotate_health_json(
            &mut json,
            &output.report,
            &output.root,
            &base.health,
        );
    }
    Ok(json)
}

fn has_persisted_introduced_flags(json: &serde_json::Value) -> bool {
    json.as_object().is_some_and(|object| {
        object.values().any(|value| {
            value
                .as_array()
                .is_some_and(|items| items.iter().any(|item| item.get("introduced").is_some()))
        })
    })
}

fn annotate_audit_duplication_json(
    json: &mut serde_json::Value,
    output: &DuplicationProgrammaticOutput,
    base: &rustc_hash::FxHashSet<String>,
) {
    let Some(items) = json
        .get_mut("clone_groups")
        .and_then(serde_json::Value::as_array_mut)
    else {
        return;
    };
    for (item, group) in items.iter_mut().zip(&output.output.report.clone_groups) {
        if let serde_json::Value::Object(map) = item {
            let key = crate::audit_keys::dupe_group_key(&group.group, &output.root);
            map.insert(
                "introduced".to_string(),
                serde_json::json!(!base.contains(&key)),
            );
        }
    }
}

/// Serialize typed dead-code output into the stable JSON compatibility contract.
///
/// # Errors
///
/// Returns a structured error if the output contract cannot be serialized.
pub fn serialize_dead_code_programmatic_json(
    output: DeadCodeProgrammaticOutput,
) -> ProgrammaticResult<serde_json::Value> {
    let DeadCodeProgrammaticOutput {
        output,
        root,
        config_fixable: _,
        envelope_mode,
        telemetry_analysis_run_id,
    } = output;
    serialize_check_programmatic_output(
        output,
        &root,
        envelope_mode,
        telemetry_analysis_run_id.as_deref(),
        "dead-code",
        "FALLOW_SERIALIZE_DEAD_CODE_REPORT",
    )
}

/// Serialize typed circular-dependency output into the JSON compatibility contract.
///
/// # Errors
///
/// Returns a structured error if the output contract cannot be serialized.
pub fn serialize_circular_dependencies_programmatic_json(
    output: CircularDependenciesProgrammaticOutput,
) -> ProgrammaticResult<serde_json::Value> {
    let CircularDependenciesProgrammaticOutput {
        output,
        root,
        envelope_mode,
        telemetry_analysis_run_id,
    } = output;
    serialize_check_programmatic_output(
        output,
        &root,
        envelope_mode,
        telemetry_analysis_run_id.as_deref(),
        "circular-dependencies",
        "FALLOW_SERIALIZE_CIRCULAR_DEPENDENCIES_REPORT",
    )
}

/// Serialize typed boundary-family output into the JSON compatibility contract.
///
/// # Errors
///
/// Returns a structured error if the output contract cannot be serialized.
pub fn serialize_boundary_violations_programmatic_json(
    output: BoundaryViolationsProgrammaticOutput,
) -> ProgrammaticResult<serde_json::Value> {
    let BoundaryViolationsProgrammaticOutput {
        output,
        root,
        envelope_mode,
        telemetry_analysis_run_id,
    } = output;
    serialize_check_programmatic_output(
        output,
        &root,
        envelope_mode,
        telemetry_analysis_run_id.as_deref(),
        "boundary-violations",
        "FALLOW_SERIALIZE_BOUNDARY_VIOLATIONS_REPORT",
    )
}

fn serialize_check_programmatic_output(
    output: CheckOutput,
    root: &Path,
    envelope_mode: RootEnvelopeMode,
    telemetry_analysis_run_id: Option<&str>,
    context: &'static str,
    code: &'static str,
) -> ProgrammaticResult<serde_json::Value> {
    let mut json = serialize_check_json_output(output, envelope_mode, telemetry_analysis_run_id)
        .map_err(|err| {
            ProgrammaticError::new(format!("failed to serialize {context} report: {err}"), 2)
                .with_code(code)
                .with_context(context)
        })?;
    let root_prefix = format!("{}/", root.display());
    strip_root_prefix(&mut json, &root_prefix);
    Ok(json)
}

/// Serialize typed duplication output into the JSON compatibility contract.
///
/// # Errors
///
/// Returns a structured error if the output contract cannot be serialized.
pub fn serialize_duplication_programmatic_json(
    output: DuplicationProgrammaticOutput,
) -> ProgrammaticResult<serde_json::Value> {
    let DuplicationProgrammaticOutput {
        output,
        root,
        threshold: _,
        envelope_mode,
        telemetry_analysis_run_id,
    } = output;
    let mut json =
        serialize_dupes_json_output(output, envelope_mode, telemetry_analysis_run_id.as_deref())
            .map_err(|err| {
                ProgrammaticError::new(format!("failed to serialize duplication report: {err}"), 2)
                    .with_code("FALLOW_SERIALIZE_DUPLICATION_REPORT")
                    .with_context("dupes")
            })?;
    let root_prefix = format!("{}/", root.display());
    strip_root_prefix(&mut json, &root_prefix);
    Ok(json)
}

/// Serialize typed feature-flag output into the JSON compatibility contract.
///
/// # Errors
///
/// Returns a structured error if the output contract cannot be serialized.
pub fn serialize_feature_flags_programmatic_json(
    output: FeatureFlagsProgrammaticOutput,
) -> ProgrammaticResult<serde_json::Value> {
    serialize_feature_flags_json_output(
        output.output,
        output.envelope_mode,
        output.telemetry_analysis_run_id.as_deref(),
    )
    .map_err(|err| {
        ProgrammaticError::new(
            format!("failed to serialize feature flags report: {err}"),
            2,
        )
        .with_code("FALLOW_SERIALIZE_FEATURE_FLAGS_REPORT")
        .with_context("feature-flags")
    })
}

/// Serialize typed export-trace output into the JSON compatibility contract.
///
/// # Errors
///
/// Returns a structured error if the trace output cannot be serialized.
pub fn serialize_trace_export_programmatic_json(
    output: TraceExportProgrammaticOutput,
) -> ProgrammaticResult<serde_json::Value> {
    serialize_trace_programmatic_output(
        output.output,
        "export trace",
        "FALLOW_SERIALIZE_TRACE_EXPORT",
        "trace_export",
    )
}

/// Serialize typed file-trace output into the JSON compatibility contract.
///
/// # Errors
///
/// Returns a structured error if the trace output cannot be serialized.
pub fn serialize_trace_file_programmatic_json(
    output: TraceFileProgrammaticOutput,
) -> ProgrammaticResult<serde_json::Value> {
    serialize_trace_programmatic_output(
        output.output,
        "file trace",
        "FALLOW_SERIALIZE_TRACE_FILE",
        "trace_file",
    )
}

/// Serialize typed import-path-trace output into the JSON compatibility contract.
///
/// # Errors
///
/// Returns a structured error if the trace output cannot be serialized.
pub fn serialize_trace_import_path_programmatic_json(
    output: TraceImportPathProgrammaticOutput,
) -> ProgrammaticResult<serde_json::Value> {
    serialize_trace_programmatic_output(
        output.output,
        "import path trace",
        "FALLOW_SERIALIZE_TRACE_IMPORT_PATH",
        "trace_import_path",
    )
}

/// Serialize typed dependency-trace output into the JSON compatibility contract.
///
/// # Errors
///
/// Returns a structured error if the trace output cannot be serialized.
pub fn serialize_trace_dependency_programmatic_json(
    output: TraceDependencyProgrammaticOutput,
) -> ProgrammaticResult<serde_json::Value> {
    serialize_trace_programmatic_output(
        output.output,
        "dependency trace",
        "FALLOW_SERIALIZE_TRACE_DEPENDENCY",
        "trace_dependency",
    )
}

/// Serialize typed stack-trace resolution into the JSON compatibility contract.
///
/// # Errors
///
/// Returns a structured error if the trace output cannot be serialized.
pub fn serialize_trace_error_programmatic_json(
    output: TraceErrorProgrammaticOutput,
) -> ProgrammaticResult<serde_json::Value> {
    serialize_trace_programmatic_output(
        output.output,
        "stack-trace resolution",
        "FALLOW_SERIALIZE_TRACE_ERROR",
        "trace_error",
    )
}

/// Serialize typed clone-trace output into the JSON compatibility contract.
///
/// # Errors
///
/// Returns a structured error if the trace output cannot be serialized.
pub fn serialize_trace_clone_programmatic_json(
    output: TraceCloneProgrammaticOutput,
) -> ProgrammaticResult<serde_json::Value> {
    serialize_trace_programmatic_output(
        output.output,
        "clone trace",
        "FALLOW_SERIALIZE_TRACE_CLONE",
        "trace_clone",
    )
}

fn serialize_trace_programmatic_output<T: Serialize>(
    output: T,
    context: &'static str,
    code: &'static str,
    error_context: &'static str,
) -> ProgrammaticResult<serde_json::Value> {
    serde_json::to_value(output).map_err(|err| {
        ProgrammaticError::new(format!("failed to serialize {context}: {err}"), 2)
            .with_code(code)
            .with_context(error_context)
    })
}

/// Serialize typed health / complexity output into the JSON compatibility contract.
///
/// # Errors
///
/// Returns a structured error if the health output contract cannot be serialized.
pub fn serialize_health_programmatic_json(
    output: HealthProgrammaticOutput,
) -> ProgrammaticResult<serde_json::Value> {
    let HealthProgrammaticOutput {
        report,
        grouping,
        root,
        elapsed,
        explain,
        workspace_diagnostics,
        next_steps,
        envelope_mode,
        telemetry_analysis_run_id,
    } = output;
    let (grouped_by, groups) = grouping.map_or((None, None), |grouping| {
        (
            group_by_mode_from_label(grouping.mode),
            Some(grouping.groups),
        )
    });
    serialize_health_report_json(HealthJsonReportInput {
        report,
        root: &root,
        elapsed,
        explain,
        type_aware: None,
        grouped_by,
        groups,
        workspace_diagnostics,
        next_steps,
        envelope_mode,
        telemetry_analysis_run_id: telemetry_analysis_run_id.as_deref(),
    })
    .map_err(|err| {
        ProgrammaticError::new(format!("failed to serialize health report: {err}"), 2)
            .with_code("FALLOW_SERIALIZE_HEALTH_REPORT")
            .with_context("health")
    })
}

fn group_by_mode_from_label(label: &str) -> Option<GroupByMode> {
    match label {
        "owner" => Some(GroupByMode::Owner),
        "directory" => Some(GroupByMode::Directory),
        "package" => Some(GroupByMode::Package),
        "section" => Some(GroupByMode::Section),
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use super::{
        RootEnvelopeMode, serialize_audit_dead_code, serialize_combined_programmatic_json,
    };
    use crate::DupesReportPayload;
    use crate::runtime::{
        CombinedProgrammaticOutput, DeadCodeProgrammaticOutput, DuplicationProgrammaticOutput,
        HealthProgrammaticOutput,
    };
    use fallow_output::{
        CHECK_SCHEMA_VERSION, CheckOutputInput, DUPES_SCHEMA_VERSION, DupesOutputInput,
        HealthReport, build_check_output, build_dupes_output,
    };
    use fallow_types::duplicates::DuplicationReport;
    use fallow_types::results::AnalysisResults;
    use fallow_types::workspace::{WorkspaceDiagnostic, WorkspaceDiagnosticKind};
    use std::path::Path;
    use std::time::Duration;

    fn dead_code_output(
        root: &Path,
        workspace_diagnostics: Vec<WorkspaceDiagnostic>,
    ) -> DeadCodeProgrammaticOutput {
        DeadCodeProgrammaticOutput {
            output: build_check_output(CheckOutputInput {
                schema_version: CHECK_SCHEMA_VERSION,
                version: "0.0.0-test".to_owned(),
                elapsed: Duration::ZERO,
                results: AnalysisResults::default(),
                config_fixable: false,
                meta: None,
                workspace_diagnostics,
                next_steps: Vec::new(),
            }),
            root: root.to_path_buf(),
            config_fixable: false,
            envelope_mode: RootEnvelopeMode::Tagged,
            telemetry_analysis_run_id: None,
        }
    }

    /// Issue #2366: the audit envelope's dead-code sub-result carries the run's
    /// workspace diagnostics root-relative, matching what the CLI audit path
    /// reads from the registry, and omits the array when there are none.
    #[test]
    fn audit_dead_code_section_carries_workspace_diagnostics_root_relative_or_omits_them() {
        let root = Path::new("/project");
        let carried = serialize_audit_dead_code(
            &dead_code_output(
                root,
                vec![WorkspaceDiagnostic::new(
                    root,
                    root.join("package.json"),
                    WorkspaceDiagnosticKind::BunLockbOverrideResolutionSkipped,
                )],
            ),
            None,
        )
        .expect("audit dead-code JSON");
        assert_eq!(
            carried["workspace_diagnostics"][0]["kind"],
            "bun-lockb-override-resolution-skipped"
        );
        assert_eq!(carried["workspace_diagnostics"][0]["path"], "package.json");

        let empty = serialize_audit_dead_code(&dead_code_output(root, Vec::new()), None)
            .expect("audit dead-code JSON");
        assert!(
            empty.get("workspace_diagnostics").is_none(),
            "an empty list is omitted from the audit dead-code section: {empty}"
        );
    }

    fn health_output(
        root: &Path,
        workspace_diagnostics: Vec<WorkspaceDiagnostic>,
    ) -> HealthProgrammaticOutput {
        HealthProgrammaticOutput {
            report: HealthReport::default(),
            grouping: None,
            root: root.to_path_buf(),
            elapsed: Duration::ZERO,
            explain: false,
            workspace_diagnostics,
            next_steps: Vec::new(),
            envelope_mode: RootEnvelopeMode::Tagged,
            telemetry_analysis_run_id: None,
        }
    }

    fn duplication_output(
        root: &Path,
        workspace_diagnostics: Vec<WorkspaceDiagnostic>,
    ) -> DuplicationProgrammaticOutput {
        DuplicationProgrammaticOutput {
            output: build_dupes_output(DupesOutputInput {
                schema_version: DUPES_SCHEMA_VERSION,
                version: "0.0.0-test".to_owned(),
                elapsed: Duration::ZERO,
                report: DupesReportPayload::from_report(&DuplicationReport::default()),
                clone_groups_shown: 0,
                clone_groups_omitted: 0,
                clone_families_shown: 0,
                clone_families_omitted: 0,
                grouped_by: None,
                total_issues: None,
                groups: None,
                meta: None,
                workspace_diagnostics,
                next_steps: Vec::new(),
            }),
            root: root.to_path_buf(),
            threshold: 0.0,
            envelope_mode: RootEnvelopeMode::Tagged,
            telemetry_analysis_run_id: None,
        }
    }

    fn combined_output(
        root: &Path,
        dead_code: Option<DeadCodeProgrammaticOutput>,
        health: Option<HealthProgrammaticOutput>,
    ) -> CombinedProgrammaticOutput {
        combined_output_with_duplication(root, dead_code, health, None)
    }

    fn combined_output_with_duplication(
        root: &Path,
        dead_code: Option<DeadCodeProgrammaticOutput>,
        health: Option<HealthProgrammaticOutput>,
        duplication: Option<DuplicationProgrammaticOutput>,
    ) -> CombinedProgrammaticOutput {
        CombinedProgrammaticOutput {
            dead_code,
            duplication,
            health,
            root: root.to_path_buf(),
            elapsed: Duration::ZERO,
            explain: false,
            next_steps: Vec::new(),
            envelope_mode: RootEnvelopeMode::Tagged,
            telemetry_analysis_run_id: None,
        }
    }

    fn bun_lockb_diagnostic(root: &Path) -> WorkspaceDiagnostic {
        WorkspaceDiagnostic::new(
            root,
            root.join("package.json"),
            WorkspaceDiagnosticKind::BunLockbOverrideResolutionSkipped,
        )
    }

    fn large_file_diagnostic(root: &Path, relative: &str) -> WorkspaceDiagnostic {
        WorkspaceDiagnostic::new(
            root,
            root.join(relative),
            WorkspaceDiagnosticKind::SkippedLargeFile {
                size_bytes: 6_000_000,
            },
        )
    }

    fn root_kinds(document: &serde_json::Value) -> Vec<String> {
        document["workspace_diagnostics"]
            .as_array()
            .cloned()
            .unwrap_or_default()
            .iter()
            .map(|diagnostic| diagnostic["kind"].as_str().unwrap_or_default().to_owned())
            .collect()
    }

    /// Issue #2366: the programmatic combined envelope (MCP `analyze` in code
    /// mode, NAPI, embedders) carries the run's workspace diagnostics on the
    /// combined root, root-relative, and omits the array when there are none.
    #[test]
    fn combined_programmatic_root_carries_workspace_diagnostics_or_omits_them() {
        let root = Path::new("/project");
        let carried = serialize_combined_programmatic_json(combined_output(
            root,
            Some(dead_code_output(root, vec![bun_lockb_diagnostic(root)])),
            None,
        ))
        .expect("combined JSON");
        assert_eq!(
            carried["workspace_diagnostics"][0]["kind"],
            "bun-lockb-override-resolution-skipped"
        );
        assert_eq!(carried["workspace_diagnostics"][0]["path"], "package.json");
        assert!(
            carried["check"].is_object(),
            "the check section is present, so the absence check below is not vacuous: {carried}"
        );
        assert!(
            carried["check"].get("workspace_diagnostics").is_none(),
            "the check section is not a second carrier: {carried}"
        );

        let empty = serialize_combined_programmatic_json(combined_output(
            root,
            Some(dead_code_output(root, Vec::new())),
            None,
        ))
        .expect("combined JSON");
        assert!(
            empty.get("workspace_diagnostics").is_none(),
            "an empty list is omitted from the combined root: {empty}"
        );
    }

    /// Issue #2366: a programmatic combined run without a dead-code section
    /// (the `--skip check` / `--only health` shape) still reports the
    /// diagnostics, taken from the section that did run.
    #[test]
    fn combined_programmatic_root_carries_workspace_diagnostics_without_a_dead_code_section() {
        let root = Path::new("/project");
        let carried = serialize_combined_programmatic_json(combined_output(
            root,
            None,
            Some(health_output(root, vec![bun_lockb_diagnostic(root)])),
        ))
        .expect("combined JSON");
        assert!(
            carried.get("check").is_none(),
            "this run has no check section: {carried}"
        );
        assert_eq!(
            carried["workspace_diagnostics"][0]["kind"],
            "bun-lockb-override-resolution-skipped"
        );
        assert_eq!(carried["workspace_diagnostics"][0]["path"], "package.json");
    }

    /// Issue #2366: a duplication-only combined run (an embedder driving
    /// `CombinedOptions` with just `duplication`) reports what that section
    /// recorded.
    #[test]
    fn combined_programmatic_root_carries_workspace_diagnostics_from_a_duplication_only_run() {
        let root = Path::new("/project");
        let carried = serialize_combined_programmatic_json(combined_output_with_duplication(
            root,
            None,
            None,
            Some(duplication_output(
                root,
                vec![large_file_diagnostic(root, "src/generated.ts")],
            )),
        ))
        .expect("combined JSON");
        assert!(
            carried.get("check").is_none() && carried.get("health").is_none(),
            "only the dupes section ran: {carried}"
        );
        assert_eq!(root_kinds(&carried), ["skipped-large-file"]);
        assert_eq!(
            carried["workspace_diagnostics"][0]["path"],
            "src/generated.ts"
        );
    }

    /// Issue #2366: sections of one combined run can record different lists,
    /// because each analysis walks the project itself and a per-analysis
    /// `production` mode changes which files that walk sees. The root carries
    /// the union so nothing the run recorded is dropped, deduplicated so a
    /// diagnostic two sections both saw is reported once, and in section order
    /// so a run whose analyses agree matches the standalone `dead-code`
    /// envelope exactly.
    #[test]
    fn combined_programmatic_root_unions_sections_that_recorded_different_diagnostics() {
        let root = Path::new("/project");
        let shared = bun_lockb_diagnostic(root);
        let carried = serialize_combined_programmatic_json(combined_output_with_duplication(
            root,
            Some(dead_code_output(
                root,
                vec![shared.clone(), large_file_diagnostic(root, "src/big.ts")],
            )),
            Some(health_output(root, vec![shared.clone()])),
            Some(duplication_output(
                root,
                vec![shared, large_file_diagnostic(root, "src/other.ts")],
            )),
        ))
        .expect("combined JSON");
        assert_eq!(
            root_kinds(&carried),
            [
                "bun-lockb-override-resolution-skipped",
                "skipped-large-file",
                "skipped-large-file",
            ],
            "the union keeps dead-code order first and drops the repeats: {}",
            carried["workspace_diagnostics"]
        );
        let paths: Vec<&str> = carried["workspace_diagnostics"]
            .as_array()
            .expect("array")
            .iter()
            .map(|diagnostic| diagnostic["path"].as_str().unwrap_or_default())
            .collect();
        assert_eq!(paths, ["package.json", "src/big.ts", "src/other.ts"]);
    }

    /// Issue #2366: a diagnostic only the health or duplication section
    /// recorded still reaches the root when the dead-code section recorded
    /// nothing, the direction that a `production: { deadCode: true }` split
    /// produces on a real project.
    #[test]
    fn combined_programmatic_root_keeps_diagnostics_an_empty_dead_code_section_missed() {
        let root = Path::new("/project");
        let carried = serialize_combined_programmatic_json(combined_output_with_duplication(
            root,
            Some(dead_code_output(root, Vec::new())),
            Some(health_output(
                root,
                vec![large_file_diagnostic(root, "src/big.test.ts")],
            )),
            None,
        ))
        .expect("combined JSON");
        assert_eq!(root_kinds(&carried), ["skipped-large-file"]);
        assert_eq!(
            carried["workspace_diagnostics"][0]["path"],
            "src/big.test.ts"
        );
    }
}