fallow-output 3.22.0

Output contract types for fallow reports
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
//! Shared CI comment output contracts for CLI and programmatic consumers.

use std::borrow::Cow;
use std::fmt::Write as _;

use crate::{
    CodeClimateIssue, CodeClimateSeverity, DiffIndex, GitHubReviewComment, GitHubReviewSide,
    GitLabReviewComment, GitLabReviewPosition, GitLabReviewPositionType, ReviewCheckConclusion,
    ReviewComment, ReviewEnvelopeEvent, ReviewEnvelopeMeta, ReviewEnvelopeOutput,
    ReviewEnvelopeSchema, ReviewEnvelopeSummary, ReviewId, ReviewProvider, default_marker_regex,
    default_marker_regex_flags, review_id_marker,
};
use serde_json::Value;

/// Supported CI review providers for generated comments.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CiProvider {
    /// GitHub pull requests and check runs.
    Github,
    /// GitLab merge requests and discussions.
    Gitlab,
}

impl CiProvider {
    /// Display name of the provider ("GitHub" / "GitLab").
    #[must_use]
    pub const fn name(self) -> &'static str {
        match self {
            Self::Github => "GitHub",
            Self::Gitlab => "GitLab",
        }
    }
}

/// Prefix prepended to a rendered path so CI platforms, which address files
/// from the repository root, can find it. Empty when the analysis root already
/// is the repository root.
///
/// This is presentation only. Nothing looks a path up in a diff after it has
/// been prefixed: matching happens on analysis-root-relative paths, which is
/// the namespace `DiffIndex::key_for_root_relative` translates from.
#[must_use]
pub fn apply_path_prefix(prefix: &str, path: &str) -> String {
    if prefix.is_empty() {
        return path.to_owned();
    }
    format!("{prefix}/{path}")
}

/// Normalized CodeClimate issue used by CI comment renderers.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CiIssue {
    /// Fallow rule identifier, taken from the CodeClimate `check_name`.
    pub rule_id: String,
    /// Human-readable finding description.
    pub description: String,
    /// CodeClimate severity string, e.g. `minor` or `major`.
    pub severity: String,
    /// File path relative to the analysed root.
    pub path: String,
    /// 1-based line of the finding.
    pub line: u64,
    /// Stable finding fingerprint used for comment identity.
    pub fingerprint: String,
}

/// Inputs for rendering a sticky PR/MR summary comment.
pub struct PrCommentRenderInput<'a> {
    /// Fallow command the comment reports on, e.g. `audit`.
    pub command: &'a str,
    /// CI provider whose comment conventions apply.
    pub provider: CiProvider,
    /// Findings to summarize, pre-sorted by severity and location.
    pub issues: &'a [CiIssue],
    /// Identity token embedded so reruns update the same sticky comment.
    pub marker_id: String,
    /// Maximum findings rendered in the comment body.
    pub max_comments: usize,
    /// Maps a rule id to its display category label.
    pub category_for_rule: &'a dyn Fn(&str) -> &'static str,
}

/// GitLab diff refs for a review-envelope position.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ReviewGitlabDiffRefs {
    /// Merge-base SHA of the MR diff.
    pub base_sha: String,
    /// First commit SHA of the MR diff.
    pub start_sha: String,
    /// Head commit SHA of the MR diff.
    pub head_sha: String,
}

/// Truncation signals produced while rendering a review envelope.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct ReviewEnvelopeTruncation {
    /// A comment body hit [`MAX_COMMENT_BODY_BYTES`] and was truncated.
    pub body: bool,
    /// More findings existed than `max_comments` allowed.
    pub comment_limit: bool,
}

/// Rendered review envelope plus side-channel signals for CLI telemetry.
#[derive(Debug)]
pub struct ReviewEnvelopeRenderResult {
    /// Provider-ready review envelope.
    pub envelope: ReviewEnvelopeOutput,
    /// Truncation signals observed while rendering.
    pub truncation: ReviewEnvelopeTruncation,
}

/// Inputs for rendering a GitHub/GitLab review envelope.
pub struct ReviewEnvelopeRenderInput<'a> {
    /// Fallow command the review reports on.
    pub command: &'a str,
    /// CI provider whose review API shapes the envelope.
    pub provider: CiProvider,
    /// Findings to turn into review comments.
    pub issues: &'a [CiIssue],
    /// Diff index used to keep comments on lines the diff actually added.
    pub diff_index: Option<&'a DiffIndex>,
    /// Prepended to every emitted path after diff lookups have run.
    pub path_prefix: &'a str,
    /// Maximum inline comments to emit.
    pub max_comments: usize,
    /// Required for GitLab positioned discussions; ignored for GitHub.
    pub gitlab_diff_refs: Option<&'a ReviewGitlabDiffRefs>,
    /// Whether to append per-finding guidance blocks to comment bodies.
    pub include_guidance: bool,
    /// Produces a provider-specific suggestion block for a finding, when one
    /// applies.
    pub suggestion_block: &'a dyn Fn(CiProvider, &CiIssue) -> Option<String>,
    /// Produces a guidance block for a finding, when one applies.
    pub guidance_block: &'a dyn Fn(&CiIssue) -> Option<String>,
}

/// Marker prefix appended to every v2 review-comment body.
pub const MARKER_PREFIX_V2: &str = "<!-- fallow-fingerprint:v2: ";

/// Closing of the v2 marker, after the fingerprint string.
pub const MARKER_SUFFIX_V2: &str = " -->";

/// Hard cap on a single review-comment body, matching GitHub's 65 536-char
/// comment limit; bodies at or over it are truncated with a marker suffix.
pub const MAX_COMMENT_BODY_BYTES: usize = 65_536;
const TRUNCATION_SUFFIX: &str = "\n\n<!-- fallow-truncated -->\n> Body truncated by fallow.";

/// Extract normalized CI issues from a raw CodeClimate JSON array, sorted by
/// severity then location.
#[must_use]
pub fn issues_from_codeclimate(value: &Value) -> Vec<CiIssue> {
    let mut issues = value
        .as_array()
        .into_iter()
        .flatten()
        .filter_map(issue_from_codeclimate)
        .collect::<Vec<_>>();
    sort_ci_issues(&mut issues);
    issues
}

/// Normalize typed CodeClimate issues into CI issues, sorted by severity then
/// location.
#[must_use]
pub fn issues_from_codeclimate_issues(issues: &[CodeClimateIssue]) -> Vec<CiIssue> {
    let mut issues = issues
        .iter()
        .map(issue_from_codeclimate_issue)
        .collect::<Vec<_>>();
    sort_ci_issues(&mut issues);
    issues
}

fn issue_from_codeclimate(value: &Value) -> Option<CiIssue> {
    let path = value.pointer("/location/path")?.as_str()?.to_string();
    let line = value
        .pointer("/location/lines/begin")
        .and_then(Value::as_u64)
        .unwrap_or(1);
    Some(CiIssue {
        rule_id: value
            .get("check_name")
            .and_then(Value::as_str)
            .unwrap_or("fallow/finding")
            .to_string(),
        description: value
            .get("description")
            .and_then(Value::as_str)
            .unwrap_or("Fallow finding")
            .to_string(),
        severity: value
            .get("severity")
            .and_then(Value::as_str)
            .unwrap_or("minor")
            .to_string(),
        fingerprint: value
            .get("fingerprint")
            .and_then(Value::as_str)
            .unwrap_or("")
            .to_string(),
        path,
        line,
    })
}

fn issue_from_codeclimate_issue(issue: &CodeClimateIssue) -> CiIssue {
    CiIssue {
        rule_id: issue.check_name.clone(),
        description: issue.description.clone(),
        severity: codeclimate_severity_label(issue.severity).to_owned(),
        path: issue.location.path.clone(),
        line: u64::from(issue.location.lines.begin),
        fingerprint: issue.fingerprint.clone(),
    }
}

const fn codeclimate_severity_label(severity: CodeClimateSeverity) -> &'static str {
    match severity {
        CodeClimateSeverity::Info => "info",
        CodeClimateSeverity::Minor => "minor",
        CodeClimateSeverity::Major => "major",
        CodeClimateSeverity::Critical => "critical",
        CodeClimateSeverity::Blocker => "blocker",
    }
}

fn sort_ci_issues(issues: &mut [CiIssue]) {
    issues
        .sort_by(|a, b| (&a.path, a.line, &a.fingerprint).cmp(&(&b.path, b.line, &b.fingerprint)));
}

fn fingerprint_hash(parts: &[&str]) -> String {
    crate::codeclimate_fingerprint_hash(parts)
}

/// Render the sticky PR/MR summary comment body: identity marker, headline
/// count, and per-category findings tables.
#[must_use]
#[expect(clippy::expect_used, reason = "formatting into String is infallible")]
pub fn render_pr_comment(input: &PrCommentRenderInput<'_>) -> String {
    let marker = format!("<!-- fallow-id: {} -->", input.marker_id);
    let title = command_title(input.command);
    let count = input.issues.len();
    let noun = if count == 1 { "finding" } else { "findings" };

    let mut out = String::new();
    out.push_str(&marker);
    out.push('\n');
    write!(&mut out, "### Fallow {title}\n\n").expect("write to string");
    if count == 0 {
        writeln!(
            &mut out,
            "No {provider} PR/MR findings.",
            provider = input.provider.name()
        )
        .expect("write to string");
    } else {
        write!(&mut out, "Found **{count}** {noun}.\n\n").expect("write to string");
        let groups = group_by_category(input.issues, input.category_for_rule);
        if let [(_, group_issues)] = groups.as_slice() {
            render_findings_table(&mut out, group_issues, input.max_comments, "Details");
        } else {
            for (category, group_issues) in &groups {
                let summary_label = summary_label(category, group_issues.len(), input.max_comments);
                render_findings_table(&mut out, group_issues, input.max_comments, &summary_label);
            }
        }
    }
    out.push_str("\nGenerated by fallow.");
    out
}

/// Rule ids whose findings describe project-wide config state rather than a
/// change touching a specific source line.
pub const PROJECT_LEVEL_RULE_IDS: &[&str] = &[
    "fallow/unused-catalog-entry",
    "fallow/empty-catalog-group",
    "fallow/unresolved-catalog-reference",
    "fallow/unused-dependency-override",
    "fallow/misconfigured-dependency-override",
    "fallow/unused-dependency",
    "fallow/unused-dev-dependency",
    "fallow/unused-optional-dependency",
    "fallow/type-only-dependency",
    "fallow/test-only-dependency",
    "fallow/dev-dependency-in-production",
];

/// Whether findings for `rule_id` describe the whole project (e.g. dependency
/// rules) rather than a specific file location.
#[must_use]
pub fn is_project_level_rule(rule_id: &str) -> bool {
    PROJECT_LEVEL_RULE_IDS.contains(&rule_id)
}

const CATEGORY_ORDER: [&str; 6] = [
    "Dead code",
    "Dependencies",
    "Duplication",
    "Health",
    "Architecture",
    "Suppressions",
];

fn group_by_category<'a>(
    issues: &'a [CiIssue],
    category_for_rule: &dyn Fn(&str) -> &'static str,
) -> Vec<(&'static str, Vec<&'a CiIssue>)> {
    let mut buckets: std::collections::BTreeMap<&'static str, Vec<&CiIssue>> =
        std::collections::BTreeMap::new();
    for issue in issues {
        let category = category_for_rule(&issue.rule_id);
        buckets.entry(category).or_default().push(issue);
    }
    let mut ordered: Vec<(&'static str, Vec<&CiIssue>)> = Vec::with_capacity(buckets.len());
    for category in CATEGORY_ORDER {
        if let Some(items) = buckets.remove(category) {
            ordered.push((category, items));
        }
    }
    for (category, items) in buckets {
        ordered.push((category, items));
    }
    ordered
}

/// Collapsible-section label for a findings category: appends "showing N"
/// when the table is capped below the category's total.
#[must_use]
pub fn summary_label(category: &str, total: usize, max: usize) -> String {
    if total > max {
        format!("{category} ({total}, showing {max})")
    } else {
        format!("{category} ({total})")
    }
}

#[expect(clippy::expect_used, reason = "formatting into String is infallible")]
fn render_findings_table(out: &mut String, issues: &[&CiIssue], max: usize, summary: &str) {
    writeln!(out, "<details>\n<summary>{summary}</summary>\n").expect("write to string");
    out.push_str("| Severity | Rule | Location | Description |\n");
    out.push_str("| --- | --- | --- | --- |\n");
    for issue in issues.iter().take(max) {
        writeln!(
            out,
            "| {} | `{}` | `{}`:{} | {} |",
            escape_md(&issue.severity),
            escape_md(&issue.rule_id),
            escape_md(&issue.path),
            issue.line,
            escape_md(&issue.description),
        )
        .expect("write to string");
    }
    if issues.len() > max {
        writeln!(
            out,
            "\nShowing {max} of {} findings. Run fallow locally or inspect the CI output for the full report.",
            issues.len(),
        )
        .expect("write to string");
    }
    out.push_str("\n</details>\n\n");
}

/// Human-readable report title for a fallow command name, e.g. `dupes` maps
/// to "duplication report".
#[must_use]
pub fn command_title(command: &str) -> &'static str {
    match command {
        "dead-code" | "check" => "dead-code report",
        "dupes" => "duplication report",
        "health" => "health report",
        "audit" => "audit report",
        "" | "combined" => "combined report",
        _ => "report",
    }
}

/// Escape a string for inclusion in a Markdown table cell.
#[must_use]
pub fn escape_md(value: &str) -> String {
    let value = value.trim();
    // Collapse CRLF to one space; a bare CR is a CommonMark line ending and
    // would otherwise split the table row.
    let mut chars = value.chars().peekable();
    let mut out = String::with_capacity(value.len());
    while let Some(ch) = chars.next() {
        let ch = match ch {
            '\r' => {
                if chars.peek() == Some(&'\n') {
                    chars.next();
                }
                ' '
            }
            '\n' => ' ',
            _ => ch,
        };
        if matches!(
            ch,
            '\\' | '`'
                | '*'
                | '_'
                | '['
                | ']'
                | '('
                | ')'
                | '!'
                | '<'
                | '>'
                | '#'
                | '|'
                | '~'
                | '&'
        ) {
            out.push('\\');
        }
        out.push(ch);
    }
    out
}

/// Render a complete CommonMark code span around an untrusted value. The
/// fence grows past the longest backtick run inside the value, so the span
/// cannot be closed early from within.
#[must_use]
pub fn markdown_code_span(value: &str) -> String {
    let longest_run = value
        .split(|c| c != '`')
        .map(str::len)
        .max()
        .unwrap_or_default();
    let fence = "`".repeat(longest_run + 1);
    let needs_padding = value.starts_with('`')
        || value.ends_with('`')
        || (value.starts_with(' ') && value.ends_with(' ') && !value.chars().all(|c| c == ' '));
    if needs_padding {
        format!("{fence} {value} {fence}")
    } else {
        format!("{fence}{value}{fence}")
    }
}

/// [`markdown_code_span`] for a Markdown table cell: pipes are additionally
/// escaped so the value cannot terminate the cell, and line endings collapse
/// to spaces because any CommonMark line ending would split the table row.
#[must_use]
pub fn markdown_table_code_span(value: &str) -> String {
    let collapsed = value.replace("\r\n", " ").replace(['\n', '\r'], " ");
    markdown_code_span(&collapsed.replace('|', "\\|"))
}

/// Escape prose for a Markdown table cell while leaving intentional inline
/// markup alone: pipes are escaped and line endings collapse to spaces.
#[must_use]
pub fn markdown_table_text(value: &str) -> String {
    value
        .replace("\r\n", " ")
        .replace(['\n', '\r'], " ")
        .replace('|', "\\|")
}

/// Render a provider-specific review envelope from typed CI issues.
#[must_use]
pub fn render_review_envelope(input: &ReviewEnvelopeRenderInput<'_>) -> ReviewEnvelopeRenderResult {
    render_review_envelope_with_id(input, None, None, None)
}

/// Render a review envelope with an explicit gate conclusion and status.
#[must_use]
pub fn render_review_envelope_with_conclusion(
    input: &ReviewEnvelopeRenderInput<'_>,
    conclusion: ReviewCheckConclusion,
    status_message: Option<&str>,
) -> ReviewEnvelopeRenderResult {
    render_review_envelope_with_id(input, None, Some(conclusion), status_message)
}

/// Render a review envelope whose bodies carry the supplied review scope.
#[must_use]
pub fn render_scoped_review_envelope(
    input: &ReviewEnvelopeRenderInput<'_>,
    review_id: &ReviewId,
) -> ReviewEnvelopeRenderResult {
    render_review_envelope_with_id(input, Some(review_id), None, None)
}

/// Render a scoped review envelope with an explicit gate conclusion and status.
#[must_use]
pub fn render_scoped_review_envelope_with_conclusion(
    input: &ReviewEnvelopeRenderInput<'_>,
    review_id: &ReviewId,
    conclusion: ReviewCheckConclusion,
    status_message: Option<&str>,
) -> ReviewEnvelopeRenderResult {
    render_review_envelope_with_id(input, Some(review_id), Some(conclusion), status_message)
}

fn render_review_envelope_with_id(
    input: &ReviewEnvelopeRenderInput<'_>,
    review_id: Option<&ReviewId>,
    conclusion: Option<ReviewCheckConclusion>,
    status_message: Option<&str>,
) -> ReviewEnvelopeRenderResult {
    let grouped = group_review_issues_by_path_line(input.issues, input.max_comments);

    let comments: Vec<ReviewComment> = grouped
        .groups
        .iter()
        .map(|group| {
            render_review_comment_for_group_with_id(
                &ReviewCommentRenderInput {
                    provider: input.provider,
                    group,
                    gitlab_diff_refs: input.gitlab_diff_refs,
                    diff_index: input.diff_index,
                    path_prefix: input.path_prefix,
                    include_guidance: input.include_guidance,
                    suggestion_block: input.suggestion_block,
                    guidance_block: input.guidance_block,
                },
                review_id,
            )
        })
        .collect();

    let conclusion = conclusion.unwrap_or_else(|| github_check_conclusion(input.issues));
    let summary_text = review_summary_text(
        input.command,
        input.provider,
        comments.len(),
        conclusion,
        status_message,
    );
    let summary_fp = summary_fingerprint(&summary_text);
    let summary_marker = review_markers(&summary_fp, review_id);
    let body = format!("{summary_text}{summary_marker}");
    let summary = ReviewEnvelopeSummary {
        body: body.clone(),
        fingerprint: summary_fp,
    };

    let truncation = ReviewEnvelopeTruncation {
        body: comments.iter().any(review_comment_truncated),
        comment_limit: grouped.truncated,
    };

    ReviewEnvelopeRenderResult {
        envelope: build_review_envelope_output(input.provider, body, summary, comments, conclusion),
        truncation,
    }
}

fn review_summary_text(
    command: &str,
    provider: CiProvider,
    comment_count: usize,
    conclusion: ReviewCheckConclusion,
    status_message: Option<&str>,
) -> String {
    let verdict = review_summary_verdict(conclusion);
    let status = status_message.map_or_else(String::new, |message| format!("\n\n> {message}"));
    format!(
        "### Fallow {}\n\n**{}**{}\n\n{} inline finding{} selected for {} review.\n\n<!-- fallow-review -->",
        command_title(command),
        verdict,
        status,
        comment_count,
        if comment_count == 1 { "" } else { "s" },
        provider.name(),
    )
}

fn review_summary_verdict(conclusion: ReviewCheckConclusion) -> &'static str {
    match conclusion {
        ReviewCheckConclusion::Failure => "Quality gate failed",
        ReviewCheckConclusion::Neutral => "Review needed",
        ReviewCheckConclusion::Success => "Quality gate passed",
    }
}

/// Review issues grouped per `(path, line)` for one-comment-per-location
/// rendering.
#[derive(Debug, PartialEq, Eq)]
pub struct GroupedReviewIssues<'a> {
    /// One group per distinct location, in input order.
    pub groups: Vec<Vec<&'a CiIssue>>,
    /// True when the group cap cut off remaining issues.
    pub truncated: bool,
}

/// Group consecutive same-(path, line) issues. Input is already sorted by
/// `(path, line, fingerprint)` so a single linear pass collects runs.
#[must_use]
pub fn group_review_issues_by_path_line(
    issues: &[CiIssue],
    max_groups: usize,
) -> GroupedReviewIssues<'_> {
    if max_groups == 0 {
        return GroupedReviewIssues {
            groups: Vec::new(),
            truncated: !issues.is_empty(),
        };
    }
    let mut groups: Vec<Vec<&CiIssue>> = Vec::with_capacity(max_groups.min(issues.len()));
    let mut current: Vec<&CiIssue> = Vec::new();
    let mut current_key: Option<(&str, u64)> = None;
    for issue in issues {
        let key = (issue.path.as_str(), issue.line);
        if Some(key) != current_key {
            if !current.is_empty() {
                groups.push(std::mem::take(&mut current));
                if groups.len() == max_groups {
                    return GroupedReviewIssues {
                        groups,
                        truncated: true,
                    };
                }
            }
            current_key = Some(key);
        }
        current.push(issue);
    }
    if !current.is_empty() && groups.len() < max_groups {
        groups.push(current);
    }
    GroupedReviewIssues {
        groups,
        truncated: false,
    }
}

fn review_comment_truncated(comment: &ReviewComment) -> bool {
    match comment {
        ReviewComment::GitHub(comment) => comment.truncated,
        ReviewComment::GitLab(comment) => comment.truncated,
    }
}

/// Inputs for rendering one inline review comment from a location group.
pub struct ReviewCommentRenderInput<'a, 'group> {
    /// CI provider whose comment shape to produce.
    pub provider: CiProvider,
    /// Issues sharing the same `(path, line)`; the first is the representative.
    pub group: &'a [&'group CiIssue],
    /// Required for GitLab positioned discussions; ignored for GitHub.
    pub gitlab_diff_refs: Option<&'a ReviewGitlabDiffRefs>,
    /// Diff index used to resolve renamed paths for GitLab positions.
    pub diff_index: Option<&'a DiffIndex>,
    /// Prepended to every emitted path after diff lookups have run.
    pub path_prefix: &'a str,
    /// Whether to append per-finding guidance blocks to the body.
    pub include_guidance: bool,
    /// Produces a provider-specific suggestion block for a finding, when one
    /// applies.
    pub suggestion_block: &'a dyn Fn(CiProvider, &CiIssue) -> Option<String>,
    /// Produces a guidance block for a finding, when one applies.
    pub guidance_block: &'a dyn Fn(&CiIssue) -> Option<String>,
}

/// Render one comment from a group of issues sharing the same `(path, line)`.
#[must_use]
pub fn render_review_comment_for_group(input: &ReviewCommentRenderInput<'_, '_>) -> ReviewComment {
    render_review_comment_for_group_with_id(input, None)
}

fn render_review_comment_for_group_with_id(
    input: &ReviewCommentRenderInput<'_, '_>,
    review_id: Option<&ReviewId>,
) -> ReviewComment {
    assert!(
        !input.group.is_empty(),
        "group_review_issues_by_path_line never yields empty"
    );
    let representative = input.group[0];
    let fingerprint = if input.group.len() == 1 {
        representative.fingerprint.clone()
    } else {
        let constituents: Vec<&str> = input.group.iter().map(|i| i.fingerprint.as_str()).collect();
        composite_fingerprint(&constituents)
    };

    let content = build_merged_comment_content(input);
    let marker_line = review_markers(&fingerprint, review_id);
    let (body, truncated) = cap_body_with_marker(&content, &marker_line);

    build_review_comment(ReviewCommentInput {
        provider: input.provider,
        representative,
        gitlab_diff_refs: input.gitlab_diff_refs,
        diff_index: input.diff_index,
        path_prefix: input.path_prefix,
        body,
        fingerprint,
        truncated,
    })
}

#[expect(clippy::expect_used, reason = "formatting into String is infallible")]
fn build_merged_comment_content(input: &ReviewCommentRenderInput<'_, '_>) -> String {
    let mut content = String::new();
    for (index, issue) in input.group.iter().enumerate() {
        let label = review_label_from_codeclimate(&issue.severity);
        if index > 0 {
            content.push_str("\n\n");
        }
        write!(
            content,
            "**{}** `{}`: {}",
            label,
            escape_md(&issue.rule_id),
            escape_md(&issue.description)
        )
        .expect("write to String is infallible");
        if let Some(suggestion) = (input.suggestion_block)(input.provider, issue) {
            content.push_str(&suggestion);
        }
        if input.include_guidance
            && let Some(guidance) = (input.guidance_block)(issue)
        {
            content.push_str(&guidance);
        }
    }
    content
}

struct ReviewCommentInput<'a> {
    provider: CiProvider,
    representative: &'a CiIssue,
    gitlab_diff_refs: Option<&'a ReviewGitlabDiffRefs>,
    diff_index: Option<&'a DiffIndex>,
    path_prefix: &'a str,
    body: String,
    fingerprint: String,
    truncated: bool,
}

fn build_review_comment(input: ReviewCommentInput<'_>) -> ReviewComment {
    let ReviewCommentInput {
        provider,
        representative,
        gitlab_diff_refs,
        diff_index,
        path_prefix,
        body,
        fingerprint,
        truncated,
    } = input;
    match provider {
        CiProvider::Github => ReviewComment::GitHub(GitHubReviewComment {
            path: apply_path_prefix(path_prefix, &representative.path),
            line: u32::try_from(representative.line).unwrap_or(u32::MAX),
            side: GitHubReviewSide::Right,
            body,
            fingerprint,
            truncated,
        }),
        CiProvider::Gitlab => {
            // Renames resolve on the analysis-root-relative path, before the
            // presentation prefix goes on: the diff's keys never carry it.
            let old_rel = diff_index
                .and_then(|di| di.old_path_for_root_relative(&representative.path))
                .map_or_else(|| representative.path.clone(), Cow::into_owned);
            let new_path = apply_path_prefix(path_prefix, &representative.path);
            let old_path = apply_path_prefix(path_prefix, &old_rel);
            let position = GitLabReviewPosition {
                base_sha: gitlab_diff_refs.map(|r| r.base_sha.clone()),
                start_sha: gitlab_diff_refs.map(|r| r.start_sha.clone()),
                head_sha: gitlab_diff_refs.map(|r| r.head_sha.clone()),
                position_type: GitLabReviewPositionType::Text,
                old_path,
                new_path,
                new_line: u32::try_from(representative.line).unwrap_or(u32::MAX),
            };
            ReviewComment::GitLab(GitLabReviewComment {
                body,
                position,
                fingerprint,
                truncated,
            })
        }
    }
}

/// Append `marker_line` to `content`, truncating `content` on a char boundary
/// so the whole body stays within [`MAX_COMMENT_BODY_BYTES`]. The marker is
/// never sacrificed. Returns the body and whether truncation happened.
#[must_use]
pub fn cap_body_with_marker(content: &str, marker_line: &str) -> (String, bool) {
    let intact_len = content.len() + marker_line.len();
    if intact_len <= MAX_COMMENT_BODY_BYTES {
        let mut out = String::with_capacity(intact_len);
        out.push_str(content);
        out.push_str(marker_line);
        return (out, false);
    }
    let reserved = marker_line.len() + TRUNCATION_SUFFIX.len();
    let budget = MAX_COMMENT_BODY_BYTES.saturating_sub(reserved);
    let mut cut = budget.min(content.len());
    while cut > 0 && !content.is_char_boundary(cut) {
        cut -= 1;
    }
    let mut out = String::with_capacity(MAX_COMMENT_BODY_BYTES);
    out.push_str(&content[..cut]);
    out.push_str(TRUNCATION_SUFFIX);
    out.push_str(marker_line);
    (out, true)
}

/// Map a CodeClimate severity name to the review badge label: `error` for
/// major and above, `warn` otherwise.
#[must_use]
pub const fn review_label_from_codeclimate(severity_name: &str) -> &'static str {
    match severity_name.as_bytes() {
        b"major" | b"critical" | b"blocker" => "error",
        _ => "warn",
    }
}

/// GitHub check conclusion for a set of findings: `Failure` when any is major
/// or above, `Success` when empty, `Neutral` otherwise.
#[must_use]
pub fn github_check_conclusion(issues: &[CiIssue]) -> ReviewCheckConclusion {
    if issues
        .iter()
        .any(|issue| matches!(issue.severity.as_str(), "major" | "critical" | "blocker"))
    {
        ReviewCheckConclusion::Failure
    } else if issues.is_empty() {
        ReviewCheckConclusion::Success
    } else {
        ReviewCheckConclusion::Neutral
    }
}

fn build_review_envelope_output(
    provider: CiProvider,
    body: String,
    summary: ReviewEnvelopeSummary,
    comments: Vec<ReviewComment>,
    conclusion: ReviewCheckConclusion,
) -> ReviewEnvelopeOutput {
    match provider {
        CiProvider::Github => ReviewEnvelopeOutput {
            event: Some(ReviewEnvelopeEvent::Comment),
            body,
            summary,
            comments,
            marker_regex: default_marker_regex(),
            marker_regex_flags: default_marker_regex_flags(),
            meta: ReviewEnvelopeMeta {
                schema: ReviewEnvelopeSchema::V3,
                provider: ReviewProvider::Github,
                check_conclusion: Some(conclusion),
            },
        },
        CiProvider::Gitlab => ReviewEnvelopeOutput {
            event: None,
            body,
            summary,
            comments,
            marker_regex: default_marker_regex(),
            marker_regex_flags: default_marker_regex_flags(),
            meta: ReviewEnvelopeMeta {
                schema: ReviewEnvelopeSchema::V3,
                provider: ReviewProvider::Gitlab,
                check_conclusion: None,
            },
        },
    }
}

fn review_markers(fingerprint: &str, review_id: Option<&ReviewId>) -> String {
    let fingerprint = format!("\n\n{MARKER_PREFIX_V2}{fingerprint}{MARKER_SUFFIX_V2}");
    match review_id {
        Some(review_id) => format!("{fingerprint}\n{}", review_id_marker(review_id)),
        None => fingerprint,
    }
}

/// Stable fingerprint for a summary comment body.
#[must_use]
pub fn summary_fingerprint(body: &str) -> String {
    fingerprint_hash(&[body])
}

/// Order-independent fingerprint for a comment merged from several findings:
/// constituents are sorted before hashing and the result carries a `merged:`
/// prefix.
#[must_use]
pub fn composite_fingerprint(constituents: &[&str]) -> String {
    let mut sorted: Vec<&str> = constituents.to_vec();
    sorted.sort_unstable();
    let joined = sorted.join(":");
    format!("merged:{}", fingerprint_hash(&[joined.as_str()]))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{CodeClimateIssueKind, CodeClimateLines, CodeClimateLocation};

    fn escape_md_legacy(value: &str) -> String {
        let collapsed = value.replace("\r\n", " ").replace(['\n', '\r'], " ");
        let mut out = String::with_capacity(collapsed.len());
        for ch in collapsed.chars() {
            if matches!(
                ch,
                '\\' | '`'
                    | '*'
                    | '_'
                    | '['
                    | ']'
                    | '('
                    | ')'
                    | '!'
                    | '<'
                    | '>'
                    | '#'
                    | '|'
                    | '~'
                    | '&'
            ) {
                out.push('\\');
            }
            out.push(ch);
        }
        out.trim().to_owned()
    }

    fn category_for_rule(rule_id: &str) -> &'static str {
        match rule_id {
            "fallow/code-duplication" => "Duplication",
            "fallow/high-complexity" => "Health",
            "fallow/unused-dependency" => "Dependencies",
            _ => "Dead code",
        }
    }

    #[test]
    fn extracts_issues_from_codeclimate() {
        let value = serde_json::json!([{
            "check_name": "fallow/unused-export",
            "description": "Export x is never imported",
            "severity": "minor",
            "fingerprint": "abc",
            "location": { "path": "src/a.ts", "lines": { "begin": 7 } }
        }]);
        let issues = issues_from_codeclimate(&value);
        assert_eq!(issues.len(), 1);
        assert_eq!(issues[0].path, "src/a.ts");
        assert_eq!(issues[0].line, 7);
    }

    #[test]
    fn typed_codeclimate_issues_extract_like_json_codeclimate() {
        let severities = [
            (CodeClimateSeverity::Info, "info"),
            (CodeClimateSeverity::Minor, "minor"),
            (CodeClimateSeverity::Major, "major"),
            (CodeClimateSeverity::Critical, "critical"),
            (CodeClimateSeverity::Blocker, "blocker"),
        ];
        let typed = severities
            .iter()
            .enumerate()
            .map(|(index, (severity, _))| CodeClimateIssue {
                kind: CodeClimateIssueKind::Issue,
                check_name: format!("fallow/rule-{index}"),
                description: format!("Finding {index}"),
                categories: vec!["Complexity".to_owned()],
                severity: *severity,
                fingerprint: format!("fp-{index}"),
                location: CodeClimateLocation {
                    path: format!("src/{index}.ts"),
                    lines: CodeClimateLines {
                        begin: u32::try_from(index + 1).expect("small fixture index"),
                    },
                },
                owner: None,
                group: None,
            })
            .collect::<Vec<_>>();
        let value = serde_json::to_value(&typed).expect("typed fixture serializes");

        assert_eq!(
            issues_from_codeclimate_issues(&typed),
            issues_from_codeclimate(&value)
        );
        let typed_labels = issues_from_codeclimate_issues(&typed)
            .into_iter()
            .map(|issue| issue.severity)
            .collect::<Vec<_>>();
        let expected_labels = severities
            .iter()
            .map(|(_, label)| (*label).to_owned())
            .collect::<Vec<_>>();
        assert_eq!(typed_labels, expected_labels);
    }

    #[test]
    fn renders_default_empty_comment() {
        let body = render_pr_comment(&PrCommentRenderInput {
            command: "check",
            provider: CiProvider::Github,
            issues: &[],
            marker_id: "fallow-results".to_owned(),
            max_comments: 50,
            category_for_rule: &category_for_rule,
        });
        assert!(body.contains("<!-- fallow-id: fallow-results"));
        assert!(body.contains("No GitHub PR/MR findings."));
    }

    #[test]
    fn escape_md_escapes_inline_commonmark_specials() {
        let raw = "foo*bar_baz [a](u) `c` <h> #x !i ~s | p";
        let escaped = escape_md(raw);
        for ch in [
            '*', '_', '[', ']', '(', ')', '`', '<', '>', '#', '!', '~', '|',
        ] {
            let raw_count = raw.chars().filter(|c| c == &ch).count();
            let escaped_count = escaped.matches(&format!("\\{ch}")).count();
            assert_eq!(
                raw_count, escaped_count,
                "char {ch:?}: raw {raw_count} occurrences, escaped {escaped_count} in {escaped:?}"
            );
        }
    }

    #[test]
    fn escape_md_escapes_ampersand_to_block_numeric_entity_bypass() {
        let raw = "value &#42;suspicious&#42; here";
        let escaped = escape_md(raw);
        assert!(escaped.contains(r"\&"), "got: {escaped}");
        assert!(escaped.contains(r"\#"), "got: {escaped}");
        assert!(!escaped.contains(" *suspicious"), "got: {escaped}");
    }

    #[test]
    fn summary_label_foreshadows_truncation() {
        assert_eq!(
            summary_label("Duplication", 160, 50),
            "Duplication (160, showing 50)"
        );
        assert_eq!(summary_label("Health", 12, 50), "Health (12)");
        assert_eq!(summary_label("Dependencies", 50, 50), "Dependencies (50)");
    }

    #[test]
    fn escape_md_does_not_escape_block_only_markers() {
        let raw = "fallow/test-only-dependency package.json:12";
        let escaped = escape_md(raw);
        assert!(!escaped.contains("\\-"), "should not escape `-`");
        assert!(!escaped.contains("\\."), "should not escape `.`");
        assert_eq!(escaped, raw);
    }

    #[test]
    fn escape_md_collapses_newlines_to_spaces() {
        let raw = "first\nsecond\nthird";
        assert_eq!(escape_md(raw), "first second third");
    }

    #[test]
    fn escape_md_collapses_carriage_returns_to_spaces() {
        assert_eq!(escape_md("first\r\nsecond\rthird"), "first second third");
    }

    #[test]
    fn escape_md_matches_legacy_contract_corpus() {
        const ALPHABET: [char; 12] = [
            'a', ' ', '\t', '\r', '\n', '\\', '|', '`', '&', '\u{2003}', 'é', '🦀',
        ];

        for length in 0..=4 {
            let case_count = ALPHABET.len().pow(length);
            for mut encoded in 0..case_count {
                let mut value = String::new();
                for _ in 0..length {
                    value.push(ALPHABET[encoded % ALPHABET.len()]);
                    encoded /= ALPHABET.len();
                }
                assert_eq!(
                    escape_md(&value),
                    escape_md_legacy(&value),
                    "contract mismatch for {value:?}"
                );
            }
        }
    }

    #[test]
    fn markdown_code_span_grows_fence_past_inner_backticks() {
        assert_eq!(markdown_code_span("plain"), "`plain`");
        assert_eq!(markdown_code_span("has`tick"), "``has`tick``");
        assert_eq!(markdown_code_span("`leading"), "`` `leading ``");
    }

    #[test]
    fn markdown_table_code_span_escapes_pipes() {
        assert_eq!(markdown_table_code_span("a|b"), "`a\\|b`");
        assert_eq!(markdown_table_code_span("x`|y"), "``x`\\|y``");
    }

    #[test]
    fn markdown_table_code_span_collapses_line_endings() {
        assert_eq!(markdown_table_code_span("a\r\nb\rc\nd"), "`a b c d`");
    }

    #[test]
    fn markdown_table_text_neutralizes_pipes_and_line_endings() {
        assert_eq!(markdown_table_text("a|b"), "a\\|b");
        assert_eq!(markdown_table_text("a\r\nb\rc\nd"), "a b c d");
    }

    #[test]
    fn escape_md_leaves_safe_chars_unchanged() {
        let raw = "Export 'helperFn' is never imported by other modules";
        assert_eq!(
            escape_md(raw),
            r"Export 'helperFn' is never imported by other modules"
        );
    }

    #[test]
    fn is_project_level_rule_covers_config_anchored_dependency_findings() {
        for rule_id in PROJECT_LEVEL_RULE_IDS {
            assert!(
                is_project_level_rule(rule_id),
                "{rule_id} must be project-level"
            );
        }
        for rule_id in [
            "fallow/unused-file",
            "fallow/unused-export",
            "fallow/unused-type",
            "fallow/unused-enum-member",
            "fallow/unused-class-member",
            "fallow/unused-store-member",
            "fallow/unresolved-import",
            "fallow/unlisted-dependency",
            "fallow/duplicate-export",
            "fallow/circular-dependency",
            "fallow/re-export-cycle",
            "fallow/boundary-violation",
            "fallow/stale-suppression",
            "fallow/private-type-leak",
            "fallow/high-complexity",
            "fallow/high-crap-score",
        ] {
            assert!(
                !is_project_level_rule(rule_id),
                "{rule_id} must NOT be project-level"
            );
        }
    }

    #[test]
    fn escape_md_double_apply_is_safe() {
        let raw = "code with `backticks` and *stars*";
        let once = escape_md(raw);
        let twice = escape_md(&once);
        assert!(twice.contains(r"\\"));
    }
}