fallow-cli 3.35.0

CLI for fallow, codebase intelligence for TypeScript and JavaScript
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
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
//! `fallow report --from <results.json>`: render an EXISTING fallow JSON
//! envelope in another format without re-running analysis (the analyze-once
//! flow: `fallow --format json -o results.json`, then one `report` call per
//! rendered surface).
//!
//! Supports GitHub-native text, CodeClimate, SARIF, markdown, and GitHub/GitLab
//! PR feedback formats. Dispatch is on the envelope's `kind` field, so any envelope
//! produced by `--format json`
//! (dead-code, architecture, dupes, health, audit, security, or the bare
//! combined run)
//! renders byte-identically to the direct `--format` run. The `fallow fix`
//! envelope carries no `kind`; it is detected by its top-level fields and
//! rendered via [`EnvelopeKind::Fix`].

use std::path::Path;
use std::process::ExitCode;

use fallow_config::{FallowConfig, OutputFormat};
use fallow_output::{GroupByMode, PrDecisionConclusion};

use crate::report::ci::pr_comment::Provider;
use crate::report::github_annotations::{self, EnvelopeKind};
use crate::report::github_summary;
use crate::telemetry;

/// Run `fallow report --from <file>` with the global `--format` and `--root`.
/// `quiet` removes the stderr notes, as on the live run of the same format.
pub fn run_report(
    from: &Path,
    output: OutputFormat,
    root: &Path,
    config_path: Option<&Path>,
    quiet: bool,
) -> ExitCode {
    if let Some(path) = config_path
        && let Err(error) = FallowConfig::load(path)
    {
        return crate::emit_known_failure(
            &format!("failed to load report config {}: {error}", path.display()),
            2,
            output,
            telemetry::FailureReason::Validation,
        );
    }
    let Some(target) = report_target(output) else {
        return crate::emit_known_failure(
            "fallow report supports --format github-annotations, github-summary, codeclimate, sarif, markdown, pr-comment-github, pr-comment-gitlab, review-github, or review-gitlab only",
            2,
            output,
            telemetry::FailureReason::UnsupportedFormat,
        );
    };
    let envelope = match load_envelope(from, output) {
        Ok(envelope) => envelope,
        Err(code) => return code,
    };
    let saved = match prepare_saved_envelope(envelope, output) {
        Ok(saved) => saved,
        Err(code) => return code,
    };
    let kind = match envelope_kind(&saved.envelope, from, output) {
        Ok(kind) => kind,
        Err(code) => return code,
    };
    if let Err(error) = validate_report_target(target, kind) {
        return crate::emit_known_failure(
            &error,
            2,
            output,
            telemetry::FailureReason::UnsupportedFormat,
        );
    }
    if let Err(error) = validate_saved_report_envelope(kind, &saved.envelope) {
        return crate::emit_known_failure(&error, 2, output, telemetry::FailureReason::Validation);
    }
    let resolver = match saved_group_resolver(saved.grouped_by, root, config_path, output) {
        Ok(resolver) => resolver,
        Err(code) => return code,
    };
    if !quiet && target.renders_severity() {
        crate::report::sarif::note_saved_severity_fallback(
            kind,
            &saved.envelope,
            root,
            config_path,
        );
    }
    crate::report::config_pattern_text::print_stderr_notes(
        &crate::report::config_pattern_text::envelope_diagnostics(&saved.envelope),
        output,
        quiet,
    );
    match target {
        ReportTarget::GithubAnnotations => {
            github_annotations::print_annotations(kind, &saved.envelope, root)
        }
        ReportTarget::GithubSummary => github_summary::print_summary(kind, &saved.envelope, root),
        ReportTarget::Markdown => {
            render_saved_markdown(kind, &saved.envelope, root, resolver.as_ref(), output)
        }
        ReportTarget::CodeClimate => {
            crate::report::codeclimate::print_envelope_codeclimate_with_config(
                kind,
                &saved.envelope,
                root,
                config_path,
                resolver.as_ref(),
            )
        }
        ReportTarget::Sarif => crate::report::sarif::print_envelope_sarif_with_config(
            kind,
            &saved.envelope,
            root,
            config_path,
            resolver.as_ref(),
            quiet,
        ),
        ReportTarget::PrComment(provider) | ReportTarget::Review(provider) => {
            render_saved_ci_target(
                target,
                provider,
                kind,
                &saved.envelope,
                root,
                config_path,
                resolver.as_ref(),
                output,
            )
        }
    }
}

/// Print the markdown document of a saved envelope, or exit 2 with the reason
/// when the envelope has no saved markdown document.
fn render_saved_markdown(
    kind: EnvelopeKind,
    envelope: &serde_json::Value,
    root: &Path,
    resolver: Option<&crate::report::OwnershipResolver>,
    output: OutputFormat,
) -> ExitCode {
    match crate::report::print_saved_markdown(kind, envelope, root, resolver) {
        Ok(()) => ExitCode::SUCCESS,
        Err(error) => {
            crate::emit_known_failure(&error, 2, output, telemetry::FailureReason::Validation)
        }
    }
}

/// The saved-render target of a `--format`, or `None` when `report` does not
/// support that format.
const fn report_target(output: OutputFormat) -> Option<ReportTarget> {
    match output {
        OutputFormat::GithubAnnotations => Some(ReportTarget::GithubAnnotations),
        OutputFormat::GithubSummary => Some(ReportTarget::GithubSummary),
        OutputFormat::CodeClimate => Some(ReportTarget::CodeClimate),
        OutputFormat::Sarif => Some(ReportTarget::Sarif),
        OutputFormat::Markdown => Some(ReportTarget::Markdown),
        OutputFormat::PrCommentGithub => Some(ReportTarget::PrComment(Provider::Github)),
        OutputFormat::PrCommentGitlab => Some(ReportTarget::PrComment(Provider::Gitlab)),
        OutputFormat::ReviewGithub => Some(ReportTarget::Review(Provider::Github)),
        OutputFormat::ReviewGitlab => Some(ReportTarget::Review(Provider::Gitlab)),
        _ => None,
    }
}

fn validate_report_target(target: ReportTarget, kind: EnvelopeKind) -> Result<(), String> {
    if matches!(target, ReportTarget::Markdown)
        && matches!(
            kind,
            EnvelopeKind::Audit | EnvelopeKind::Security | EnvelopeKind::Fix
        )
    {
        return Err(crate::report::saved_markdown_unsupported(kind));
    }
    if matches!(target, ReportTarget::CodeClimate) && kind == EnvelopeKind::Security {
        return Err(
            "fallow security supports --format human, json, sarif, github-annotations, or github-summary only."
                .to_owned(),
        );
    }
    if matches!(target, ReportTarget::PrComment(_) | ReportTarget::Review(_))
        && matches!(kind, EnvelopeKind::Security | EnvelopeKind::Fix)
    {
        return Err(format!(
            "saved {} envelopes do not support --format {}",
            command_label(kind),
            report_target_label(target)
        ));
    }
    Ok(())
}

fn validate_saved_report_envelope(
    kind: EnvelopeKind,
    envelope: &serde_json::Value,
) -> Result<(), String> {
    match kind {
        EnvelopeKind::Security => fallow_output::validate_saved_security_envelope(envelope),
        EnvelopeKind::Fix => Ok(()),
        EnvelopeKind::DeadCode
        | EnvelopeKind::Architecture
        | EnvelopeKind::Dupes
        | EnvelopeKind::Health
        | EnvelopeKind::Audit
        | EnvelopeKind::Combined => {
            crate::report::codeclimate::validate_saved_schema(kind, envelope)
        }
    }
}

#[expect(
    clippy::too_many_arguments,
    reason = "saved CI dispatch carries the parsed envelope context without rebuilding it"
)]
fn render_saved_ci_target(
    target: ReportTarget,
    provider: Provider,
    kind: EnvelopeKind,
    envelope: &serde_json::Value,
    root: &Path,
    config_path: Option<&Path>,
    resolver: Option<&crate::report::OwnershipResolver>,
    output: OutputFormat,
) -> ExitCode {
    let issues = match crate::report::codeclimate::envelope_codeclimate_issues_with_config(
        kind,
        envelope,
        root,
        config_path,
        resolver,
    ) {
        Ok(issues) => issues,
        Err(error) => {
            return crate::emit_known_failure(
                &error,
                2,
                output,
                telemetry::FailureReason::Validation,
            );
        }
    };
    let (conclusion, status_message) = match saved_ci_conclusion(kind, envelope) {
        Ok(value) => value,
        Err(error) => {
            return crate::emit_known_failure(
                &error,
                2,
                output,
                telemetry::FailureReason::Validation,
            );
        }
    };
    let command = command_label(kind);
    // The comment and the job summary render from one envelope, so a run whose
    // gate failed must not say "Quality gate passed" on the surface a reviewer
    // actually reads while the summary says it failed. The gate line is carried
    // as the status note, which leaves the check-run `conclusion` alone: that
    // is a documented non-blocker and moving it is a separate decision.
    let status_message = saved_status_message(
        envelope,
        status_message,
        // The resolver exists exactly when the saved envelope was grouped, and
        // carries the same mode label the live render prints. The flattened
        // grouped dead-code envelope no longer has `grouped_by` to read.
        resolver.map(crate::report::OwnershipResolver::mode_label),
    );
    let status_message = status_message.as_deref();
    let config_patterns = crate::report::config_pattern_text::envelope_diagnostics(envelope);
    let review_notes = crate::report::ci::review::ReviewSummaryNotes {
        message: status_message,
        config_patterns: &config_patterns,
    };
    match target {
        ReportTarget::PrComment(_) => {
            crate::report::ci::pr_comment::print_pr_comment_from_codeclimate_issues(
                command,
                provider,
                &issues,
                conclusion,
                crate::report::ci::pr_comment::PrCommentStatus {
                    message: status_message,
                    gates: &crate::report::gate_outcome_text::gate_rows(envelope),
                    config_patterns: &config_patterns,
                },
            )
        }
        ReportTarget::Review(_) => match conclusion {
            Some(conclusion) => {
                crate::report::ci::review::print_review_envelope_from_codeclimate_issues_with_conclusion(
                    command,
                    provider,
                    &issues,
                    conclusion,
                    review_notes,
                )
            }
            None => crate::report::ci::review::print_review_envelope_from_codeclimate_issues(
                command,
                provider,
                &issues,
                review_notes,
            ),
        },
        _ => unreachable!("saved CI target dispatch only accepts comment and review targets"),
    }
}

/// The status note a comment body rendered from `envelope` carries.
///
/// The saved render reaches it through [`saved_ci_conclusion`] and
/// [`saved_status_message`]. The live combined comment renders its own body and
/// calls this function on the envelope that `--format json` would print, so the
/// two bodies state the same clauses in the same order.
pub fn envelope_status_note(
    kind: EnvelopeKind,
    envelope: &serde_json::Value,
    grouping_dropped: Option<&str>,
) -> Result<Option<String>, String> {
    let (_, existing) = saved_ci_conclusion(kind, envelope)?;
    Ok(saved_status_message(envelope, existing, grouping_dropped))
}

/// The note a saved envelope's comment and review bodies carry: the existing
/// type-aware message, the baseline advisory, the gate verdict, whether the run
/// did what it was asked, a grouping this target cannot carry, or any
/// combination of them.
///
/// Additive to whatever `saved_ci_conclusion` already produced, so the
/// type-aware message keeps its place and the later clauses join it rather than
/// replacing it. Joined by the same function the live path uses, because the
/// two renders are one contract, and the clause order therefore matches
/// `report::ci_status_note`, which is what `the_live_and_saved_notes_agree`
/// pins.
///
/// The requests are read through `summary_line_for_saved_render`, because the
/// diff filter governing THIS body was resolved by this process rather than by
/// the run that saved the envelope.
fn saved_status_message(
    envelope: &serde_json::Value,
    existing: Option<&'static str>,
    grouping_dropped: Option<&str>,
) -> Option<String> {
    crate::report::join_status_clauses(&[
        existing,
        crate::report::baseline_advisory_text::advisory_line(envelope).as_deref(),
        crate::report::gate_outcome_text::summary_line(envelope).as_deref(),
        crate::report::request_outcome_text::summary_line_for_saved_render(envelope).as_deref(),
        grouping_dropped
            .map(crate::report::grouping_note::dropped_grouping_clause)
            .as_deref(),
    ])
}

#[cfg(test)]
mod status_note_tests {
    use fallow_output::{
        BaselineScopeReasons, BaselineStaleness, BaselineStalenessAdvisory, GateName, GateOutcome,
        GateOutcomes, GateStatus,
    };

    fn rotted_baseline() -> BaselineStaleness {
        BaselineStaleness {
            baseline_entries: 8,
            matched_entries: 0,
            stale_entries: 8,
            current_findings: 6,
            remaining_findings: None,
            change_scoped: false,
            stale: true,
            warning: BaselineStalenessAdvisory::ZeroOverlap,
            gate_trips: true,
            moved_entries: 0,
            unrecognised_format: false,
            saved_by: None,
            format: None,
            scope_reasons: BaselineScopeReasons::empty(),
        }
    }

    fn gates() -> GateOutcomes {
        let mut gates = GateOutcomes::new();
        gates.insert(
            GateName::Regression,
            GateOutcome::measured(GateStatus::Fail, true, 5.0, 0.0),
        );
        gates
    }

    fn requests() -> fallow_output::RequestOutcomes {
        let mut requests = fallow_output::RequestOutcomes::new();
        requests.insert(
            fallow_output::RequestName::ChangedSince,
            fallow_output::RequestOutcome::not_applied(
                fallow_output::RequestName::ChangedSince,
                "origin/main",
                "invalid-ref",
                "--changed-since 'origin/main' was ignored.",
            ),
        );
        requests.insert(
            fallow_output::RequestName::DiffFilter,
            fallow_output::RequestOutcome::applied(
                fallow_output::RequestName::DiffFilter,
                "--diff-file pr.diff",
            ),
        );
        requests
    }

    /// The live path builds the note from typed gates and the saved path from
    /// the parsed envelope. They must produce the same string, or
    /// `report --from` stops being byte-identical to a direct render.
    #[test]
    fn the_live_and_saved_notes_agree() {
        let gates = gates();
        let envelope = serde_json::json!({ "gate_outcomes": gates });
        assert_eq!(
            super::saved_status_message(&envelope, None, None),
            crate::report::ci_status_note(None, None, Some(&gates), None, None),
        );
        assert_eq!(
            super::saved_status_message(&envelope, Some("Note."), None),
            crate::report::ci_status_note(Some("Note."), None, Some(&gates), None, None),
        );
    }

    /// The type-aware message, the baseline advisory and the gate verdict at
    /// once, which is the note a type-aware-incomplete run with a rotted
    /// baseline and an armed gate produces.
    #[test]
    fn the_live_and_saved_notes_agree_on_every_clause() {
        let staleness = rotted_baseline();
        let mut gates = GateOutcomes::new();
        gates.insert(
            GateName::StaleBaseline,
            GateOutcome::new(GateStatus::Fail, true),
        );
        let envelope = serde_json::json!({
            "baseline_staleness": staleness,
            "gate_outcomes": gates
        });
        let advisory =
            crate::report::baseline_advisory_text::advisory_line_for_staleness(Some(&staleness));

        let saved = super::saved_status_message(&envelope, Some("Note."), None)
            .expect("three clauses are present");

        assert_eq!(
            Some(saved.clone()),
            crate::report::ci_status_note(
                Some("Note."),
                advisory.as_deref(),
                Some(&gates),
                None,
                None
            ),
        );
        assert!(
            saved.starts_with("Note. **Baseline matched nothing.**"),
            "{saved}"
        );
        assert!(
            saved.ends_with("Gate outcomes: failed stale-baseline."),
            "{saved}"
        );
    }

    /// A grouped envelope rendered into a body that cannot carry groups says
    /// so, and says it identically whether the body was rendered live or from
    /// the saved envelope (issue #2691).
    #[test]
    fn the_live_and_saved_grouping_notes_agree() {
        let envelope = serde_json::json!({ "kind": "health" });
        let saved = super::saved_status_message(&envelope, None, Some("owner"))
            .expect("a grouped render has something to say");
        assert_eq!(
            Some(saved.clone()),
            crate::report::ci_status_note(None, None, None, None, Some("owner")),
        );
        assert!(
            saved.contains("--group-by owner was requested"),
            "the requested mode reaches the rendered body: {saved}"
        );

        assert!(super::saved_status_message(&envelope, None, None).is_none());
    }

    /// The same parity for the run's requests, and for a body that carries
    /// every clause at once: the clause order is part of the contract, not an
    /// accident of which renderer ran.
    #[test]
    fn the_live_and_saved_request_notes_agree() {
        let requests = requests();
        let envelope = serde_json::json!({ "request_outcomes": requests });
        assert_eq!(
            super::saved_status_message(&envelope, None, None),
            crate::report::ci_status_note(None, None, None, Some(&requests), None),
        );

        let gates = gates();
        let both = serde_json::json!({
            "gate_outcomes": gates,
            "request_outcomes": requests,
        });
        let saved = super::saved_status_message(&both, Some("Note."), Some("package"))
            .expect("a note for a run with something to say");
        assert_eq!(
            Some(saved.clone()),
            crate::report::ci_status_note(
                Some("Note."),
                None,
                Some(&gates),
                Some(&requests),
                Some("package")
            ),
        );
        assert!(
            saved.starts_with("Note. Gate outcomes:"),
            "the type-aware message keeps its place ahead of the verdicts: {saved}"
        );
        assert!(
            saved.contains("Request outcomes: not applied changed-since (invalid-ref)"),
            "an unapplied request reaches the rendered body: {saved}"
        );
        assert!(
            saved.ends_with("run --format json for the grouped envelope."),
            "the grouping clause comes last: {saved}"
        );
    }

    /// The whole note at once, in the order the two renderers must agree on:
    /// the type-aware message, the baseline advisory, the gates, the requests
    /// and last the grouping this target could not carry.
    #[test]
    fn the_live_and_saved_notes_agree_on_all_five_clauses() {
        let staleness = rotted_baseline();
        let mut gates = GateOutcomes::new();
        gates.insert(
            GateName::StaleBaseline,
            GateOutcome::new(GateStatus::Fail, true),
        );
        let requests = requests();
        let envelope = serde_json::json!({
            "baseline_staleness": staleness,
            "gate_outcomes": gates,
            "request_outcomes": requests,
        });
        let advisory =
            crate::report::baseline_advisory_text::advisory_line_for_staleness(Some(&staleness));

        let saved = super::saved_status_message(&envelope, Some("Note."), Some("package"))
            .expect("every clause is present");

        assert_eq!(
            Some(saved.clone()),
            crate::report::ci_status_note(
                Some("Note."),
                advisory.as_deref(),
                Some(&gates),
                Some(&requests),
                Some("package")
            ),
        );
        let baseline = saved
            .find("**Baseline matched nothing.**")
            .expect("the baseline advisory");
        let gate = saved.find("Gate outcomes:").expect("the gate inventory");
        let request = saved
            .find("Request outcomes:")
            .expect("the request inventory");
        let grouping = saved.find("Grouping: --group-by").expect("the grouping");
        assert!(saved.starts_with("Note. "), "{saved}");
        assert!(
            baseline < gate && gate < request && request < grouping,
            "{saved}"
        );
    }

    /// A run with nothing to state must not gain an empty blockquote, so a body
    /// produced before any of these objects existed stays byte-identical.
    #[test]
    fn an_envelope_with_no_verdict_carries_no_note() {
        let envelope = serde_json::json!({ "kind": "dead-code" });
        assert!(super::saved_status_message(&envelope, None, None).is_none());
        assert!(crate::report::ci_status_note(None, None, None, None, None).is_none());
    }
}

fn saved_ci_conclusion(
    kind: EnvelopeKind,
    envelope: &serde_json::Value,
) -> Result<(Option<PrDecisionConclusion>, Option<&'static str>), String> {
    let type_aware = crate::report::ci::saved_type_aware_metadata(envelope)?;
    if type_aware
        .iter()
        .any(|meta| crate::report::ci::required_type_aware_incomplete(Some(meta)))
    {
        return Ok((
            Some(PrDecisionConclusion::Failure),
            Some(crate::report::ci::TYPE_AWARE_INCOMPLETE_MESSAGE),
        ));
    }
    if kind != EnvelopeKind::Audit {
        return Ok((None, None));
    }
    let verdict = envelope
        .get("verdict")
        .and_then(serde_json::Value::as_str)
        .ok_or_else(|| "saved audit envelope is missing its `verdict`".to_owned())?;
    let conclusion = match verdict {
        "pass" => PrDecisionConclusion::Success,
        "warn" => PrDecisionConclusion::Neutral,
        "fail" => PrDecisionConclusion::Failure,
        other => {
            return Err(format!(
                "saved audit envelope has unsupported verdict `{other}`"
            ));
        }
    };
    Ok((Some(conclusion), None))
}

const fn command_label(kind: EnvelopeKind) -> &'static str {
    match kind {
        EnvelopeKind::DeadCode => "dead-code",
        EnvelopeKind::Architecture => "architecture",
        EnvelopeKind::Dupes => "dupes",
        EnvelopeKind::Health => "health",
        EnvelopeKind::Audit => "audit",
        EnvelopeKind::Combined => "combined",
        EnvelopeKind::Security => "security",
        EnvelopeKind::Fix => "fix",
    }
}

const fn report_target_label(target: ReportTarget) -> &'static str {
    match target {
        ReportTarget::PrComment(Provider::Github) => "pr-comment-github",
        ReportTarget::PrComment(Provider::Gitlab) => "pr-comment-gitlab",
        ReportTarget::Review(Provider::Github) => "review-github",
        ReportTarget::Review(Provider::Gitlab) => "review-gitlab",
        ReportTarget::GithubAnnotations => "github-annotations",
        ReportTarget::GithubSummary => "github-summary",
        ReportTarget::CodeClimate => "codeclimate",
        ReportTarget::Sarif => "sarif",
        ReportTarget::Markdown => "markdown",
    }
}

#[derive(Debug)]
struct SavedEnvelope {
    envelope: serde_json::Value,
    grouped_by: Option<GroupByMode>,
}

pub const NORMALIZED_GROUPED_DEAD_CODE_MARKER: &str = "_fallow_report_normalized_grouped_dead_code";

/// The grouped kinds that `fallow report --from` flattens before it renders:
/// `(grouped kind, flat kind, current schema version)`.
///
/// Both members of the dead-code family write the same grouped body, so one
/// flatten step serves both and keeps the flat kind of the row.
const GROUPED_SAVED_KINDS: &[(&str, &str, u32)] = &[
    (
        "dead-code-grouped",
        "dead-code",
        fallow_output::CHECK_SCHEMA_VERSION,
    ),
    (
        "architecture-grouped",
        "architecture",
        fallow_output::ARCHITECTURE_SCHEMA_VERSION,
    ),
];

fn prepare_saved_envelope(
    envelope: serde_json::Value,
    output: OutputFormat,
) -> Result<SavedEnvelope, ExitCode> {
    normalize_saved_envelope(envelope).map_err(|error| {
        crate::emit_known_failure(&error, 2, output, telemetry::FailureReason::Validation)
    })
}

fn normalize_saved_envelope(mut envelope: serde_json::Value) -> Result<SavedEnvelope, String> {
    if let Some(root) = envelope.as_object_mut() {
        root.remove(NORMALIZED_GROUPED_DEAD_CODE_MARKER);
    }
    if matches!(
        envelope["kind"].as_str(),
        Some("dead-code" | "architecture")
    ) {
        normalize_historical_prop_count(&mut envelope)?;
    }
    for key in ["check", "dead_code"] {
        if let Some(section) = envelope.get_mut(key) {
            normalize_historical_prop_count(section)?;
        }
    }
    let grouped_by = envelope
        .get("grouped_by")
        .and_then(serde_json::Value::as_str)
        .and_then(parse_group_by_mode);
    let saved_kind = envelope.get("kind").and_then(serde_json::Value::as_str);
    let Some(&(_, flat_kind, current_version)) = GROUPED_SAVED_KINDS
        .iter()
        .find(|(grouped, _, _)| saved_kind == Some(*grouped))
    else {
        return Ok(SavedEnvelope {
            envelope,
            grouped_by,
        });
    };
    let Some(root) = envelope.as_object_mut() else {
        return Err("saved grouped dead-code envelope must be an object".to_owned());
    };
    let grouped_by = grouped_by.ok_or_else(|| {
        "saved grouped dead-code envelope has an unsupported or missing `grouped_by`".to_owned()
    })?;
    let mut groups_value = root.remove("groups").ok_or_else(|| {
        "saved grouped dead-code envelope is missing required field `groups`".to_owned()
    })?;
    let groups = groups_value.as_array_mut().ok_or_else(|| {
        "saved grouped dead-code envelope field `groups` must be an array".to_owned()
    })?;
    let current_schema = root
        .get("schema_version")
        .and_then(serde_json::Value::as_u64)
        == Some(u64::from(current_version));
    if current_schema {
        validate_current_grouped_dead_code(root, groups)?;
    }
    root.remove("grouped_by");
    root.insert(
        "kind".to_string(),
        serde_json::Value::String(flat_kind.to_string()),
    );
    root.insert(
        NORMALIZED_GROUPED_DEAD_CODE_MARKER.to_string(),
        serde_json::Value::Bool(true),
    );
    seed_required_categories(root);
    for group in groups {
        let Some(group) = group.as_object() else {
            continue;
        };
        for (key, value) in group {
            if matches!(key.as_str(), "key" | "owners" | "total_issues") {
                continue;
            }
            let Some(items) = value.as_array() else {
                continue;
            };
            let target = root
                .entry(key.clone())
                .or_insert_with(|| serde_json::Value::Array(Vec::new()));
            if let Some(target) = target.as_array_mut() {
                target.extend(items.iter().cloned());
            }
        }
    }
    if !current_schema {
        normalize_historical_prop_count(&mut envelope)?;
    }
    Ok(SavedEnvelope {
        envelope,
        grouped_by: Some(grouped_by),
    })
}

/// Give the flat envelope every category array that the typed results require.
///
/// The flatten step builds the category arrays from the groups. An envelope with
/// no groups (a clean `--group-by` run) has no arrays to build them from, so the
/// arrays come from the empty typed results instead.
fn seed_required_categories(root: &mut serde_json::Map<String, serde_json::Value>) {
    let Ok(serde_json::Value::Object(empty)) =
        serde_json::to_value(fallow_types::results::AnalysisResults::default())
    else {
        return;
    };
    for (key, value) in empty {
        if value.is_array() {
            root.entry(key).or_insert(value);
        }
    }
}

fn validate_current_grouped_dead_code(
    root: &mut serde_json::Map<String, serde_json::Value>,
    groups: &mut [serde_json::Value],
) -> Result<(), String> {
    let root_total = root
        .get("total_issues")
        .and_then(serde_json::Value::as_u64)
        .ok_or_else(|| {
            "saved grouped dead-code envelope is missing a non-negative integer `total_issues`"
                .to_owned()
        })?;
    let mut declared_grouped_total = 0_u64;
    let mut current_grouped_total = 0_u64;
    let mut historical_grouped_total = 0_u64;
    for (index, group) in groups.iter().enumerate() {
        let Some(group_object) = group.as_object() else {
            return Err(format!(
                "saved grouped dead-code envelope group {index} must be an object"
            ));
        };
        if !group_object
            .get("key")
            .is_some_and(serde_json::Value::is_string)
        {
            return Err(format!(
                "saved grouped dead-code envelope group {index} is missing a string `key`"
            ));
        }
        let declared_total = group_object
            .get("total_issues")
            .and_then(serde_json::Value::as_u64)
            .ok_or_else(|| {
                format!(
                    "saved grouped dead-code envelope group {index} is missing a non-negative integer `total_issues`"
                )
            })?;
        let results =
            serde_json::from_value::<fallow_types::results::AnalysisResults>(group.clone())
                .map_err(|error| {
                    format!(
                        "saved grouped dead-code envelope group {index} is incompatible with this Fallow version: {error}"
                    )
                })?;
        let (actual_total, historical_total) = saved_prop_totals(&results);
        if declared_total != actual_total && declared_total != historical_total {
            return Err(format!(
                "saved grouped dead-code envelope group {index} declares {declared_total} findings but contains {actual_total}"
            ));
        }
        declared_grouped_total = declared_grouped_total.saturating_add(declared_total);
        current_grouped_total = current_grouped_total.saturating_add(actual_total);
        historical_grouped_total = historical_grouped_total.saturating_add(historical_total);
    }
    if root_total != declared_grouped_total
        || (root_total != current_grouped_total && root_total != historical_grouped_total)
    {
        return Err(format!(
            "saved grouped dead-code envelope declares {root_total} findings but its groups contain {declared_grouped_total} under inconsistent count policies"
        ));
    }
    if root_total != current_grouped_total {
        reject_current_prop_counter(root.get("summary"))?;
        for group in groups {
            normalize_historical_prop_count(group)?;
        }
        root.insert("total_issues".to_owned(), current_grouped_total.into());
    }
    Ok(())
}

fn saved_prop_totals(results: &fallow_types::results::AnalysisResults) -> (u64, u64) {
    let current = u64::try_from(results.total_issues()).unwrap_or(u64::MAX);
    let errors = u64::try_from(results.enforced_prop_drilling_count()).unwrap_or(u64::MAX);
    (current, current.saturating_sub(errors))
}

fn reject_current_prop_counter(summary: Option<&serde_json::Value>) -> Result<(), String> {
    if summary.is_some_and(|summary| summary.get("prop_drilling_chains").is_some()) {
        return Err("saved dead-code envelope has a current prop-drilling counter but an inconsistent finding total".to_owned());
    }
    Ok(())
}

/// Earlier schema-10 producers saved error severity while excluding prop chains
/// from totals. The positive summary counter distinguishes current producers.
fn normalize_historical_prop_count(envelope: &mut serde_json::Value) -> Result<(), String> {
    if !envelope
        .get("prop_drilling_chains")
        .and_then(serde_json::Value::as_array)
        .is_some_and(|chains| {
            chains
                .iter()
                .any(|chain| chain["effective_severity"].as_str() == Some("error"))
        })
    {
        return Ok(());
    }
    let Some(declared) = envelope
        .get("total_issues")
        .and_then(serde_json::Value::as_u64)
    else {
        return Ok(());
    };
    let Ok(results) =
        serde_json::from_value::<fallow_types::results::AnalysisResults>(envelope.clone())
    else {
        return Ok(());
    };
    let (current, historical) = saved_prop_totals(&results);
    if declared == current || declared != historical {
        return Ok(());
    }
    reject_current_prop_counter(envelope.get("summary"))?;
    if let Some(summary) = envelope
        .get_mut("summary")
        .and_then(serde_json::Value::as_object_mut)
    {
        if summary
            .get("total_issues")
            .is_some_and(|total| total.as_u64() != Some(declared))
        {
            return Err("saved dead-code summary has an inconsistent finding total".to_owned());
        }
        summary.insert("total_issues".to_owned(), current.into());
        summary.insert(
            "prop_drilling_chains".to_owned(),
            (current - historical).into(),
        );
    }
    envelope["total_issues"] = current.into();
    Ok(())
}

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

fn saved_group_resolver(
    grouped_by: Option<GroupByMode>,
    root: &Path,
    config_path: Option<&Path>,
    output: OutputFormat,
) -> Result<Option<crate::report::OwnershipResolver>, ExitCode> {
    let explicit = config_path.and_then(|path| FallowConfig::load(path).ok());
    // The discovered config is loaded only when the explicit config gives no
    // CODEOWNERS path, as before. The explicit config, when it loads, is the
    // only source of `workspaces.patterns`.
    let discovered = explicit
        .as_ref()
        .is_none_or(|config| config.codeowners.is_none())
        .then(|| {
            FallowConfig::find_and_load(root)
                .ok()
                .flatten()
                .map(|(config, _)| config)
        })
        .flatten();
    let codeowners = explicit
        .as_ref()
        .and_then(|config| config.codeowners.as_deref())
        .or_else(|| {
            discovered
                .as_ref()
                .and_then(|config| config.codeowners.as_deref())
        });
    let workspace_patterns = explicit
        .as_ref()
        .or(discovered.as_ref())
        .and_then(|config| config.workspaces.as_ref())
        .map_or(&[][..], |workspaces| workspaces.patterns.as_slice());
    crate::runtime_support::build_ownership_resolver_for_mode(
        grouped_by,
        root,
        codeowners,
        workspace_patterns,
        output,
    )
}

#[derive(Clone, Copy)]
enum ReportTarget {
    GithubAnnotations,
    GithubSummary,
    CodeClimate,
    Sarif,
    Markdown,
    PrComment(Provider),
    Review(Provider),
}

impl ReportTarget {
    /// Whether the target prints a finding level that can come from the
    /// config, so a saved finding without its own level needs a stderr note.
    const fn renders_severity(self) -> bool {
        !matches!(
            self,
            Self::GithubAnnotations | Self::GithubSummary | Self::Markdown
        )
    }
}

fn load_envelope(from: &Path, output: OutputFormat) -> Result<serde_json::Value, ExitCode> {
    let source = std::fs::read_to_string(from).map_err(|err| {
        crate::emit_known_failure(
            &format!("failed to read {}: {err}", from.display()),
            2,
            output,
            telemetry::FailureReason::Validation,
        )
    })?;
    let envelope: serde_json::Value = serde_json::from_str(&source).map_err(|err| {
        crate::emit_known_failure(
            &format!(
                "{} is not valid JSON ({err}); generate it with `fallow ... --format json`",
                from.display()
            ),
            2,
            output,
            telemetry::FailureReason::Validation,
        )
    })?;
    if envelope.get("error").and_then(serde_json::Value::as_bool) == Some(true) {
        let message = envelope
            .get("message")
            .and_then(serde_json::Value::as_str)
            .unwrap_or("the original run did not include an error message");
        let code = envelope.get("code").and_then(serde_json::Value::as_str);
        // Exit codes 0 and 1 mean success, so a saved failure never maps to them.
        let exit_code = envelope
            .get("exit_code")
            .and_then(serde_json::Value::as_u64)
            .and_then(|code| u8::try_from(code).ok())
            .filter(|code| *code >= 2)
            .unwrap_or(2);
        let label = code.map_or_else(String::new, |code| format!(" [{code}]"));
        let mut error = fallow_api::ProgrammaticError::new(
            format!("saved Fallow run failed{label}: {message}"),
            exit_code,
        );
        if let Some(code) = code {
            error = error.with_code(code);
        }
        if let Some(help) = envelope.get("help").and_then(serde_json::Value::as_str) {
            error = error.with_help(help);
        }
        telemetry::note_failure_reason(telemetry::FailureReason::Validation);
        return Err(crate::error::emit_programmatic_error(
            &error,
            output,
            crate::error::requested_json_style(),
        ));
    }
    Ok(envelope)
}

fn envelope_kind(
    envelope: &serde_json::Value,
    from: &Path,
    output: OutputFormat,
) -> Result<EnvelopeKind, ExitCode> {
    let Some(kind) = envelope.get("kind").and_then(serde_json::Value::as_str) else {
        // The `fallow fix --format json` envelope is the only kind-less document
        // fallow emits (crates/output/src/fix.rs: no top-level `kind`). Resolve it
        // by field detection so `report --from <fix-results.json>` renders the fix
        // job summary natively; genuinely unrecognized documents keep erroring.
        if is_fix_envelope(envelope) {
            return Ok(EnvelopeKind::Fix);
        }
        return Err(crate::emit_known_failure(
            &format!(
                "{} is not a fallow results envelope (missing top-level `kind`); \
                 generate it with `fallow ... --format json`",
                from.display()
            ),
            2,
            output,
            telemetry::FailureReason::Validation,
        ));
    };
    parse_envelope_kind(kind).ok_or_else(|| {
        crate::emit_known_failure(
            &format!(
                "unsupported envelope kind `{kind}` in {}; fallow report renders dead-code, \
                 architecture, dupes, health, audit, security, and combined envelopes",
                from.display()
            ),
            2,
            output,
            telemetry::FailureReason::Validation,
        )
    })
}

/// Map the `--format json` root `kind` onto the renderer dispatch. The fix
/// envelope has no `kind` field; it is resolved separately via
/// [`is_fix_envelope`] field detection (see [`envelope_kind`]).
fn parse_envelope_kind(kind: &str) -> Option<EnvelopeKind> {
    match kind {
        "dead-code" => Some(EnvelopeKind::DeadCode),
        "architecture" => Some(EnvelopeKind::Architecture),
        "dupes" => Some(EnvelopeKind::Dupes),
        "health" => Some(EnvelopeKind::Health),
        "audit" => Some(EnvelopeKind::Audit),
        "security" => Some(EnvelopeKind::Security),
        "combined" => Some(EnvelopeKind::Combined),
        _ => None,
    }
}

/// Recognize a kind-less `fallow fix --format json` envelope by its stable
/// top-level keys. The fix root always carries both a `fixes` array and a
/// numeric `total_fixed` (see `crates/output/src/fix.rs::FixJsonOutput`); no
/// other fallow envelope is kind-less, so the two keys together are an
/// unambiguous signal.
fn is_fix_envelope(envelope: &serde_json::Value) -> bool {
    envelope
        .get("fixes")
        .is_some_and(serde_json::Value::is_array)
        && envelope
            .get("total_fixed")
            .is_some_and(serde_json::Value::is_number)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_envelope_kind_covers_supported_kinds() {
        assert_eq!(
            parse_envelope_kind("dead-code"),
            Some(EnvelopeKind::DeadCode)
        );
        assert_eq!(
            parse_envelope_kind("architecture"),
            Some(EnvelopeKind::Architecture)
        );
        assert_eq!(parse_envelope_kind("dupes"), Some(EnvelopeKind::Dupes));
        assert_eq!(parse_envelope_kind("health"), Some(EnvelopeKind::Health));
        assert_eq!(parse_envelope_kind("audit"), Some(EnvelopeKind::Audit));
        assert_eq!(
            parse_envelope_kind("security"),
            Some(EnvelopeKind::Security)
        );
        assert_eq!(
            parse_envelope_kind("combined"),
            Some(EnvelopeKind::Combined)
        );
    }

    /// Every command that `fallow report --from` renders parses, and its grouped
    /// kind flattens to the flat kind. Every refused command stays refused.
    #[test]
    fn report_from_follows_the_command_envelope_table() {
        use fallow_types::command_surfaces::{COMMAND_ENVELOPES, ReportFrom};

        for row in COMMAND_ENVELOPES {
            match row.report_from {
                ReportFrom::Renders => {
                    let kind = parse_envelope_kind(row.kind).unwrap_or_else(|| {
                        panic!("report --from does not parse kind `{}`", row.kind)
                    });
                    assert_eq!(command_label(kind), row.command);
                    if let Some(grouped) = row.grouped_kind {
                        let normalized = normalize_saved_envelope(serde_json::json!({
                            "kind": grouped,
                            "grouped_by": "directory",
                            "total_issues": 0,
                            "groups": [],
                        }))
                        .unwrap_or_else(|err| panic!("{grouped} does not normalize: {err}"));
                        assert_eq!(normalized.envelope["kind"], row.kind);
                    }
                }
                ReportFrom::Refused(reason) => {
                    assert!(!reason.is_empty(), "{}: empty reason", row.command);
                    assert_eq!(
                        parse_envelope_kind(row.kind),
                        None,
                        "report --from renders `{}`; mark the row Renders",
                        row.kind
                    );
                }
            }
        }
    }

    #[test]
    fn parse_envelope_kind_rejects_unknown_and_grouped_kinds() {
        assert_eq!(parse_envelope_kind("dead-code-grouped"), None);
        assert_eq!(parse_envelope_kind("architecture-grouped"), None);
        assert_eq!(parse_envelope_kind("feature-flags"), None);
        assert_eq!(parse_envelope_kind(""), None);
    }

    #[test]
    fn saved_audit_verdict_maps_to_ci_conclusion() {
        for (verdict, expected) in [
            ("pass", PrDecisionConclusion::Success),
            ("warn", PrDecisionConclusion::Neutral),
            ("fail", PrDecisionConclusion::Failure),
        ] {
            let envelope = serde_json::json!({ "verdict": verdict });
            let (conclusion, status) =
                saved_ci_conclusion(EnvelopeKind::Audit, &envelope).expect("audit verdict");
            assert_eq!(conclusion, Some(expected));
            assert_eq!(status, None);
        }
    }

    #[test]
    fn saved_required_incomplete_type_aware_result_fails_closed() {
        let identity = fallow_types::semantic::SemanticAnalysisIdentity {
            completeness: fallow_types::semantic::SemanticCompleteness::Partial,
            ..fallow_types::semantic::SemanticAnalysisIdentity::default()
        };
        let meta = fallow_types::envelope::TypeAwareMeta {
            identity: Some(identity),
            required_completeness: Some(
                fallow_types::semantic::SemanticCompletenessRequirement::Complete,
            ),
            ..fallow_types::envelope::TypeAwareMeta::default()
        };
        let envelope = serde_json::json!({
            "verdict": "pass",
            "_meta": { "type_aware": meta }
        });
        let (conclusion, status) =
            saved_ci_conclusion(EnvelopeKind::Audit, &envelope).expect("type-aware gate");
        assert_eq!(conclusion, Some(PrDecisionConclusion::Failure));
        assert_eq!(
            status,
            Some(crate::report::ci::TYPE_AWARE_INCOMPLETE_MESSAGE)
        );
    }

    #[test]
    fn saved_required_type_aware_result_without_identity_fails_closed() {
        let meta = fallow_types::envelope::TypeAwareMeta {
            required_completeness: Some(
                fallow_types::semantic::SemanticCompletenessRequirement::Complete,
            ),
            ..fallow_types::envelope::TypeAwareMeta::default()
        };
        let envelope = serde_json::json!({
            "_meta": { "type_aware": meta }
        });
        let (conclusion, status) =
            saved_ci_conclusion(EnvelopeKind::DeadCode, &envelope).expect("missing identity gate");
        assert_eq!(conclusion, Some(PrDecisionConclusion::Failure));
        assert_eq!(
            status,
            Some(crate::report::ci::TYPE_AWARE_INCOMPLETE_MESSAGE)
        );
    }

    #[test]
    fn malformed_saved_type_aware_metadata_is_rejected() {
        let mut meta = serde_json::to_value(fallow_types::envelope::TypeAwareMeta::default())
            .expect("serialize type-aware metadata");
        meta["queries"] = serde_json::json!("not-an-array");
        let envelope = serde_json::json!({
            "_meta": { "type_aware": meta }
        });

        let error = saved_ci_conclusion(EnvelopeKind::DeadCode, &envelope)
            .expect_err("malformed type-aware metadata must fail closed");
        assert!(error.contains("saved type-aware metadata at `/_meta/type_aware`"));
        assert!(error.contains("invalid type"));
    }

    #[test]
    fn historical_prop_counts_normalize_without_recomputing_audit_gates() {
        let section: serde_json::Value = serde_json::from_str(include_str!(
            "../tests/integration/fixtures/prop-drilling-advisory-error.json"
        ))
        .unwrap();
        let archive = serde_json::json!({
            "kind": "audit",
            "dead_code": section,
            "summary": {"dead_code_issues": 0, "dead_code_has_errors": false},
            "attribution": {"dead_code_introduced": 0, "dead_code_inherited": 0},
            "verdict": "pass"
        });
        let normalized = normalize_saved_envelope(archive.clone()).unwrap().envelope;
        assert_eq!(normalized["dead_code"]["total_issues"], 1);
        assert_eq!(normalized["dead_code"]["summary"]["total_issues"], 1);
        assert_eq!(
            normalized["dead_code"]["summary"]["prop_drilling_chains"],
            1
        );
        assert_eq!(
            normalized["dead_code"]["prop_drilling_chains"],
            archive["dead_code"]["prop_drilling_chains"]
        );
        for key in ["summary", "attribution", "verdict"] {
            assert_eq!(normalized[key], archive[key]);
        }
        assert_eq!(
            normalize_saved_envelope(normalized.clone())
                .unwrap()
                .envelope,
            normalized
        );
    }

    #[test]
    fn historical_grouped_prop_counts_normalize_with_or_without_schema_metadata() {
        let archive: serde_json::Value = serde_json::from_str(include_str!(
            "../tests/integration/fixtures/prop-drilling-advisory-grouped.json"
        ))
        .unwrap();
        for schema_present in [true, false] {
            let mut input = archive.clone();
            if !schema_present {
                input.as_object_mut().unwrap().remove("schema_version");
            }
            let normalized = normalize_saved_envelope(input).unwrap().envelope;
            assert_eq!(normalized["total_issues"], 1);
            assert_eq!(
                normalized["prop_drilling_chains"],
                archive["groups"][0]["prop_drilling_chains"]
            );
        }
    }

    #[test]
    fn grouped_dead_code_is_flattened_for_saved_renderers() {
        let normalized = normalize_saved_envelope(serde_json::json!({
            "kind": "dead-code-grouped",
            "grouped_by": "owner",
            "total_issues": 1,
            "groups": [{
                "key": "@team",
                "owners": ["@team"],
                "total_issues": 1,
                "unused_files": [{"path": "src/dead.ts", "actions": []}]
            }]
        }))
        .expect("valid grouped envelope");

        assert_eq!(normalized.grouped_by, Some(GroupByMode::Owner));
        assert_eq!(normalized.envelope["kind"], "dead-code");
        assert_eq!(
            normalized.envelope["unused_files"][0]["path"],
            "src/dead.ts"
        );
        assert!(normalized.envelope.get("groups").is_none());
        assert!(normalized.envelope.get("grouped_by").is_none());
        assert_eq!(
            normalized.envelope[NORMALIZED_GROUPED_DEAD_CODE_MARKER],
            true
        );
    }

    #[test]
    fn grouped_architecture_is_flattened_to_architecture() {
        let normalized = normalize_saved_envelope(serde_json::json!({
            "kind": "architecture-grouped",
            "grouped_by": "directory",
            "total_issues": 1,
            "groups": [{
                "key": "src",
                "total_issues": 1,
                "circular_dependencies": [{
                    "files": ["src/a.ts", "src/b.ts"],
                    "length": 2,
                    "line": 1,
                    "col": 0,
                    "actions": []
                }]
            }]
        }))
        .expect("valid grouped architecture envelope");

        assert_eq!(normalized.grouped_by, Some(GroupByMode::Directory));
        assert_eq!(normalized.envelope["kind"], "architecture");
        assert_eq!(
            normalized.envelope["circular_dependencies"][0]["files"][0],
            "src/a.ts"
        );
        assert!(normalized.envelope.get("groups").is_none());
    }

    #[test]
    fn malformed_current_grouped_architecture_fails_before_flattening() {
        let error = normalize_saved_envelope(serde_json::json!({
            "kind": "architecture-grouped",
            "schema_version": fallow_output::ARCHITECTURE_SCHEMA_VERSION,
            "version": env!("CARGO_PKG_VERSION"),
            "elapsed_ms": 0,
            "grouped_by": "owner",
            "total_issues": 1,
            "groups": [{
                "key": "@team",
                "total_issues": 1,
                "circular_dependencies": "invalid"
            }]
        }))
        .expect_err("malformed current group must fail closed");

        assert!(error.contains("group 0 is incompatible with this Fallow version"));
    }

    #[test]
    fn malformed_current_grouped_dead_code_fails_before_flattening() {
        let error = normalize_saved_envelope(serde_json::json!({
            "kind": "dead-code-grouped",
            "schema_version": fallow_output::CHECK_SCHEMA_VERSION,
            "version": env!("CARGO_PKG_VERSION"),
            "elapsed_ms": 0,
            "grouped_by": "owner",
            "total_issues": 1,
            "groups": [{
                "key": "@team",
                "total_issues": 1,
                "unused_files": [{"path": "src/dead.ts", "actions": []}],
                "unused_exports": "invalid"
            }]
        }))
        .expect_err("malformed current group must fail closed");

        assert!(error.contains("group 0 is incompatible with this Fallow version"));
    }

    #[test]
    fn is_fix_envelope_detects_kindless_fix_document() {
        let fix = serde_json::json!({
            "dry_run": false,
            "total_fixed": 3,
            "skipped": 0,
            "fixes": [{ "type": "remove_export", "applied": true }],
        });
        assert!(is_fix_envelope(&fix));
    }

    #[test]
    fn is_fix_envelope_rejects_other_kindless_documents() {
        // A dead-code envelope stripped of its `kind` must NOT masquerade as
        // fix: it has neither `fixes` nor `total_fixed`.
        assert!(!is_fix_envelope(&serde_json::json!({
            "total_issues": 4,
            "unused_files": [{ "path": "src/a.ts" }],
        })));
        // `fixes` alone (no `total_fixed`) is not enough.
        assert!(!is_fix_envelope(&serde_json::json!({ "fixes": [] })));
        // `total_fixed` alone (no `fixes` array) is not enough.
        assert!(!is_fix_envelope(&serde_json::json!({ "total_fixed": 0 })));
        // A `fixes` value that is not an array is rejected.
        assert!(!is_fix_envelope(&serde_json::json!({
            "fixes": "nope",
            "total_fixed": 0,
        })));
    }
}