aptu-core 0.2.20

Core library for Aptu - OSS issue triage with AI assistance
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
// SPDX-License-Identifier: Apache-2.0

//! Triage status detection for GitHub issues.
//!
//! This module provides utilities to check whether an issue has already been triaged,
//! either through labels or Aptu-generated comments.

use crate::ai::types::{IssueDetails, PrReviewComment, PrReviewResponse, TriageResponse};
use crate::utils::is_priority_label;
use std::fmt::Write;
use tracing::debug;

/// Signature string used to identify Aptu-generated triage comments
pub const APTU_SIGNATURE: &str = "Generated by Aptu";

/// Status of whether an issue has already been triaged
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TriageStatus {
    /// Whether the issue has a type label (bug, enhancement, etc.)
    pub has_type_label: bool,
    /// Whether the issue has a priority label (p0-p4, priority: high/medium/low)
    pub has_priority_label: bool,
    /// Whether the issue has an Aptu-generated comment
    pub has_aptu_comment: bool,
    /// List of labels that indicate triage status
    pub label_names: Vec<String>,
}

impl TriageStatus {
    /// Create a new `TriageStatus`.
    #[must_use]
    pub fn new(
        has_type_label: bool,
        has_priority_label: bool,
        has_aptu_comment: bool,
        label_names: Vec<String>,
    ) -> Self {
        Self {
            has_type_label,
            has_priority_label,
            has_aptu_comment,
            label_names,
        }
    }

    /// Check if the issue has been triaged (has both type and priority labels, or Aptu comment).
    #[must_use]
    pub fn is_triaged(&self) -> bool {
        (self.has_type_label && self.has_priority_label) || self.has_aptu_comment
    }
}

/// Check if a label is a type label (bug, enhancement, documentation, etc.).
fn is_type_label(label: &str) -> bool {
    const TYPE_LABELS: &[&str] = &[
        "bug",
        "enhancement",
        "documentation",
        "question",
        "good first issue",
        "help wanted",
        "duplicate",
        "invalid",
        "wontfix",
        "triaged",
        "needs-triage",
        "status: triaged",
    ];
    TYPE_LABELS.contains(&label)
}

/// Renders a labeled list section in markdown format.
fn render_list_section_markdown(
    title: &str,
    items: &[String],
    empty_msg: &str,
    numbered: bool,
) -> String {
    let mut output = String::new();
    let _ = writeln!(output, "### {title}\n");
    if items.is_empty() {
        let _ = writeln!(output, "{empty_msg}");
    } else if numbered {
        for (i, item) in items.iter().enumerate() {
            let _ = writeln!(output, "{}. {}", i + 1, item);
        }
    } else {
        for item in items {
            let _ = writeln!(output, "- {item}");
        }
    }
    output.push('\n');
    output
}

/// Render the complexity section into markdown, if present.
fn render_complexity_markdown(output: &mut String, triage: &TriageResponse) {
    use crate::ai::types::ComplexityLevel;
    let Some(c) = &triage.complexity else {
        return;
    };
    output.push_str("### Complexity\n\n");
    let level_str = match c.level {
        ComplexityLevel::Low => "Low",
        ComplexityLevel::Medium => "Medium",
        ComplexityLevel::High => "High",
    };
    let loc_str = c
        .estimated_loc
        .map(|l| format!(" (~{l} LOC)"))
        .unwrap_or_default();
    let _ = writeln!(output, "**Level:** {level_str}{loc_str}");
    if c.affected_areas.is_empty() {
        output.push('\n');
    } else {
        let areas: Vec<String> = c.affected_areas.iter().map(|a| format!("`{a}`")).collect();
        let _ = writeln!(output, "Affected: {}\n", areas.join(", "));
    }
    if let Some(rec) = &c.recommendation
        && !rec.is_empty()
    {
        let _ = writeln!(output, "**Recommendation:** {rec}\n");
    }
}

/// Renders triage response as markdown for posting to GitHub.
///
/// Generates pure markdown without terminal colors. This is the core rendering
/// function used by both CLI and FFI layers.
///
/// # Arguments
///
/// * `triage` - The triage response to render
///
/// # Returns
///
/// A markdown string suitable for posting as a GitHub comment.
#[must_use]
pub fn render_triage_markdown(triage: &TriageResponse) -> String {
    let mut output = String::new();

    // Header
    output.push_str("## Triage Summary\n\n");
    output.push_str(&triage.summary);
    output.push_str("\n\n");

    // Labels (always show in markdown for maintainers)
    let labels: Vec<String> = triage
        .suggested_labels
        .iter()
        .map(|l| format!("`{l}`"))
        .collect();
    output.push_str(&render_list_section_markdown(
        "Suggested Labels",
        &labels,
        "None",
        false,
    ));

    // Suggested Milestone
    if let Some(milestone) = &triage.suggested_milestone
        && !milestone.is_empty()
    {
        output.push_str("### Suggested Milestone\n\n");
        output.push_str(milestone);
        output.push_str("\n\n");
    }

    // Suggested Milestone
    if let Some(milestone) = &triage.suggested_milestone
        && !milestone.is_empty()
    {
        output.push_str("### Suggested Milestone\n\n");
        output.push_str(milestone);
        output.push_str("\n\n");
    }

    // Complexity assessment
    render_complexity_markdown(&mut output, triage);

    // Questions
    output.push_str(&render_list_section_markdown(
        "Clarifying Questions",
        &triage.clarifying_questions,
        "None needed",
        true,
    ));

    // Duplicates
    output.push_str(&render_list_section_markdown(
        "Potential Duplicates",
        &triage.potential_duplicates,
        "None found",
        false,
    ));

    // Related issues with reason blockquote
    if !triage.related_issues.is_empty() {
        output.push_str("### Related Issues\n\n");
        for issue in &triage.related_issues {
            let _ = writeln!(output, "- **#{}** - {}", issue.number, issue.title);
            let _ = writeln!(output, "  > {}\n", issue.reason);
        }
    }

    // Status note (if present)
    if let Some(status_note) = &triage.status_note
        && !status_note.is_empty()
    {
        output.push_str("### Status\n\n");
        output.push_str(status_note);
        output.push_str("\n\n");
    }

    // Contributor guidance (if present)
    if let Some(guidance) = &triage.contributor_guidance {
        output.push_str("### Contributor Guidance\n\n");
        let beginner_label = if guidance.beginner_friendly {
            "**Beginner-friendly**"
        } else {
            "**Advanced**"
        };
        let _ = writeln!(output, "{beginner_label}\n");
        let _ = writeln!(output, "{}\n", guidance.reasoning);
    }

    // Implementation approach
    if let Some(approach) = &triage.implementation_approach
        && !approach.is_empty()
    {
        output.push_str("### Implementation Approach\n\n");
        for line in approach.lines() {
            let _ = writeln!(output, "  {line}");
        }
        output.push('\n');
    }

    // Signature
    output.push_str("---\n");
    output.push('*');
    output.push_str(APTU_SIGNATURE);
    output.push('*');
    output.push('\n');

    output
}

/// Render a `ReleaseNotesResponse` to markdown format.
///
/// Formats release notes with theme, narrative, and categorized sections
/// (highlights, features, fixes, improvements, documentation, maintenance, contributors).
///
/// # Arguments
///
/// * `response` - The release notes response to render
///
/// # Returns
///
/// A markdown string suitable for release notes or GitHub release descriptions.
#[must_use]
pub fn render_release_notes_markdown(response: &crate::ai::types::ReleaseNotesResponse) -> String {
    use std::fmt::Write;

    let mut body = String::new();

    // Add theme as header
    let _ = writeln!(body, "## {}\n", response.theme);

    // Add narrative
    if !response.narrative.is_empty() {
        let _ = writeln!(body, "{}\n", response.narrative);
    }

    // Add highlights
    if !response.highlights.is_empty() {
        body.push_str("### Highlights\n\n");
        for highlight in &response.highlights {
            let _ = writeln!(body, "- {highlight}");
        }
        body.push('\n');
    }

    // Add features
    if !response.features.is_empty() {
        body.push_str("### Features\n\n");
        for feature in &response.features {
            let _ = writeln!(body, "- {feature}");
        }
        body.push('\n');
    }

    // Add fixes
    if !response.fixes.is_empty() {
        body.push_str("### Fixes\n\n");
        for fix in &response.fixes {
            let _ = writeln!(body, "- {fix}");
        }
        body.push('\n');
    }

    // Add improvements
    if !response.improvements.is_empty() {
        body.push_str("### Improvements\n\n");
        for improvement in &response.improvements {
            let _ = writeln!(body, "- {improvement}");
        }
        body.push('\n');
    }

    // Add documentation
    if !response.documentation.is_empty() {
        body.push_str("### Documentation\n\n");
        for doc in &response.documentation {
            let _ = writeln!(body, "- {doc}");
        }
        body.push('\n');
    }

    // Add maintenance
    if !response.maintenance.is_empty() {
        body.push_str("### Maintenance\n\n");
        for maint in &response.maintenance {
            let _ = writeln!(body, "- {maint}");
        }
        body.push('\n');
    }

    // Add contributors
    if !response.contributors.is_empty() {
        body.push_str("### Contributors\n\n");
        for contributor in &response.contributors {
            let _ = writeln!(body, "- {contributor}");
        }
    }

    body
}

/// Check if an issue has already been triaged.
///
/// Returns `TriageStatus` indicating whether the issue has both type and priority labels,
/// or has an Aptu-generated comment.
pub fn check_already_triaged(issue: &IssueDetails) -> TriageStatus {
    let has_type_label = issue.labels.iter().any(|label| is_type_label(label));
    let has_priority_label = issue.labels.iter().any(|label| is_priority_label(label));

    let label_names: Vec<String> = issue
        .labels
        .iter()
        .filter(|label| is_type_label(label) || is_priority_label(label))
        .cloned()
        .collect();

    // Check for Aptu signature in comments
    let has_aptu_comment = issue
        .comments
        .iter()
        .any(|comment| comment.body.contains(APTU_SIGNATURE));

    if has_type_label || has_priority_label || has_aptu_comment {
        debug!(
            has_type_label = has_type_label,
            has_priority_label = has_priority_label,
            has_aptu_comment = has_aptu_comment,
            labels = ?label_names,
            "Issue triage status detected"
        );
    }

    TriageStatus::new(
        has_type_label,
        has_priority_label,
        has_aptu_comment,
        label_names,
    )
}

/// Formats an inline PR review comment body.
///
/// When the comment includes `suggested_code`, appends a GitHub suggestion block
/// that renders as a one-click "Apply suggestion" button in the PR diff view.
#[must_use]
pub fn render_pr_review_comment_body(comment: &PrReviewComment) -> String {
    let mut body = comment.comment.clone();
    if let Some(code) = &comment.suggested_code
        && !code.is_empty()
    {
        body.push_str("\n\n```suggestion\n");
        body.push_str(code);
        body.push_str("\n```");
    }
    body
}

/// Renders a concise PR review body for posting to GitHub.
///
/// Produces a short verdict + summary line, optionally followed by notable-change
/// bullets when the PR touches more than five files. All inline detail lives in the
/// anchored review comments; the body stays intentionally brief.
///
/// An `<!-- APTU_REVIEW -->` HTML comment is embedded so duplicate reviews can be
/// detected programmatically.
#[must_use]
pub fn render_pr_review_markdown(review: &PrReviewResponse, files_count: usize) -> String {
    let verdict_badge = match review.verdict.as_str() {
        "approve" => "✅ Approve",
        "request_changes" | "request-changes" => "❌ Request Changes",
        _ => "💬 Comment",
    };

    let mut body = format!(
        "<!-- APTU_REVIEW -->\n## Aptu Review\n\n**{}** — {}\n",
        verdict_badge, review.summary
    );

    // Notable changes bullets: only for larger PRs to give reviewers orientation.
    if files_count > 5 && !review.concerns.is_empty() {
        body.push('\n');
        for c in &review.concerns {
            let _ = writeln!(body, "- {c}");
        }
    }

    body.push_str("\n---\n\n<sub>Posted by [aptu](https://github.com/clouatre-labs/aptu)</sub>\n");

    body
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ai::types::{CommentSeverity, IssueComment};

    fn create_test_issue(labels: Vec<String>, comments: Vec<IssueComment>) -> IssueDetails {
        IssueDetails::builder()
            .owner("test".to_string())
            .repo("repo".to_string())
            .number(1)
            .title("Test issue".to_string())
            .body("Test body".to_string())
            .labels(labels)
            .comments(comments)
            .url("https://github.com/test/repo/issues/1".to_string())
            .build()
    }

    #[test]
    fn test_no_triage() {
        let issue = create_test_issue(vec![], vec![]);
        let status = check_already_triaged(&issue);
        assert!(!status.is_triaged());
        assert!(!status.has_type_label);
        assert!(!status.has_priority_label);
        assert!(!status.has_aptu_comment);
        assert!(status.label_names.is_empty());
    }

    #[test]
    fn test_type_label_only() {
        let labels = vec!["bug".to_string()];
        let issue = create_test_issue(labels, vec![]);
        let status = check_already_triaged(&issue);
        assert!(!status.is_triaged());
        assert!(status.has_type_label);
        assert!(!status.has_priority_label);
        assert!(!status.has_aptu_comment);
        assert_eq!(status.label_names.len(), 1);
    }

    #[test]
    fn test_priority_label_only() {
        let labels = vec!["p1".to_string()];
        let issue = create_test_issue(labels, vec![]);
        let status = check_already_triaged(&issue);
        assert!(!status.is_triaged());
        assert!(!status.has_type_label);
        assert!(status.has_priority_label);
        assert!(!status.has_aptu_comment);
        assert_eq!(status.label_names.len(), 1);
    }

    #[test]
    fn test_type_and_priority_labels() {
        let labels = vec!["bug".to_string(), "p1".to_string()];
        let issue = create_test_issue(labels, vec![]);
        let status = check_already_triaged(&issue);
        assert!(status.is_triaged());
        assert!(status.has_type_label);
        assert!(status.has_priority_label);
        assert!(!status.has_aptu_comment);
        assert_eq!(status.label_names.len(), 2);
    }

    #[test]
    fn test_priority_prefix_labels() {
        // Test all priority: prefix variants (high, medium, low)
        for priority in ["priority: high", "priority: medium", "priority: low"] {
            let labels = vec!["bug".to_string(), priority.to_string()];
            let issue = create_test_issue(labels, vec![]);
            let status = check_already_triaged(&issue);
            assert!(status.is_triaged(), "Failed for {priority}");
            assert!(status.has_type_label, "Failed for {priority}");
            assert!(status.has_priority_label, "Failed for {priority}");
        }
    }

    #[test]
    fn test_aptu_comment_only() {
        let comments = vec![IssueComment {
            author: "aptu-bot".to_string(),
            body: "This looks good. Generated by Aptu".to_string(),
        }];
        let issue = create_test_issue(vec![], comments);
        let status = check_already_triaged(&issue);
        assert!(status.is_triaged());
        assert!(!status.has_type_label);
        assert!(!status.has_priority_label);
        assert!(status.has_aptu_comment);
        assert!(status.label_names.is_empty());
    }

    #[test]
    fn test_type_label_with_aptu_comment() {
        let labels = vec!["bug".to_string()];
        let comments = vec![IssueComment {
            author: "aptu-bot".to_string(),
            body: "Generated by Aptu".to_string(),
        }];
        let issue = create_test_issue(labels, comments);
        let status = check_already_triaged(&issue);
        assert!(status.is_triaged());
        assert!(status.has_type_label);
        assert!(!status.has_priority_label);
        assert!(status.has_aptu_comment);
    }

    #[test]
    fn test_partial_signature_no_match() {
        let comments = vec![IssueComment {
            author: "other-bot".to_string(),
            body: "Generated by AnotherTool".to_string(),
        }];
        let issue = create_test_issue(vec![], comments);
        let status = check_already_triaged(&issue);
        assert!(!status.is_triaged());
        assert!(!status.has_aptu_comment);
    }

    #[test]
    fn test_irrelevant_labels() {
        let labels = vec!["component: ui".to_string(), "needs-review".to_string()];
        let issue = create_test_issue(labels, vec![]);
        let status = check_already_triaged(&issue);
        assert!(!status.is_triaged());
        assert!(!status.has_type_label);
        assert!(!status.has_priority_label);
        assert!(status.label_names.is_empty());
    }

    #[test]
    fn test_priority_label_case_insensitive() {
        let labels = vec!["bug".to_string(), "P2".to_string()];
        let issue = create_test_issue(labels, vec![]);
        let status = check_already_triaged(&issue);
        assert!(status.is_triaged());
        assert!(status.has_priority_label);
    }

    #[test]
    fn test_priority_prefix_case_insensitive() {
        let labels = vec!["enhancement".to_string(), "Priority: HIGH".to_string()];
        let issue = create_test_issue(labels, vec![]);
        let status = check_already_triaged(&issue);
        assert!(status.is_triaged());
        assert!(status.has_priority_label);
    }

    #[test]
    fn test_render_triage_markdown_basic() {
        let triage = TriageResponse {
            summary: "This is a test summary".to_string(),
            implementation_approach: None,
            clarifying_questions: vec!["Question 1?".to_string()],
            potential_duplicates: vec![],
            related_issues: vec![],
            suggested_labels: vec!["bug".to_string()],
            suggested_milestone: None,
            status_note: None,
            contributor_guidance: None,
            complexity: None,
        };

        let markdown = render_triage_markdown(&triage);
        assert!(markdown.contains("## Triage Summary"));
        assert!(markdown.contains("This is a test summary"));
        assert!(markdown.contains("### Clarifying Questions"));
        assert!(markdown.contains("1. Question 1?"));
        assert!(markdown.contains(APTU_SIGNATURE));
    }

    #[test]
    fn test_render_triage_markdown_with_labels() {
        let triage = TriageResponse {
            summary: "Summary".to_string(),
            implementation_approach: None,
            clarifying_questions: vec![],
            potential_duplicates: vec![],
            related_issues: vec![],
            suggested_labels: vec!["bug".to_string(), "p1".to_string()],
            suggested_milestone: None,
            status_note: None,
            contributor_guidance: None,
            complexity: None,
        };

        let markdown = render_triage_markdown(&triage);
        assert!(markdown.contains("### Suggested Labels"));
        assert!(markdown.contains("`bug`"));
        assert!(markdown.contains("`p1`"));
    }

    #[test]
    fn test_render_triage_markdown_multiline_approach() {
        let triage = TriageResponse {
            summary: "Summary".to_string(),
            implementation_approach: Some("Line 1\nLine 2\nLine 3".to_string()),
            clarifying_questions: vec![],
            potential_duplicates: vec![],
            related_issues: vec![],
            suggested_labels: vec![],
            suggested_milestone: None,
            status_note: None,
            contributor_guidance: None,
            complexity: None,
        };

        let markdown = render_triage_markdown(&triage);
        assert!(markdown.contains("### Implementation Approach"));
        assert!(markdown.contains("Line 1"));
        assert!(markdown.contains("Line 2"));
        assert!(markdown.contains("Line 3"));
    }

    fn make_pr_review() -> PrReviewResponse {
        PrReviewResponse {
            summary: "Good PR overall.".to_string(),
            verdict: "approve".to_string(),
            strengths: vec!["Clean code".to_string(), "Good tests".to_string()],
            concerns: vec!["Missing docs".to_string()],
            comments: vec![PrReviewComment {
                file: "src/lib.rs".to_string(),
                line: Some(42),
                comment: "Consider using a match here.".to_string(),
                severity: CommentSeverity::Suggestion,
                suggested_code: None,
            }],
            suggestions: vec!["Add a CHANGELOG entry.".to_string()],
            disclaimer: Some("AI-generated review.".to_string()),
        }
    }

    #[test]
    fn test_render_pr_review_markdown_basic() {
        let review = make_pr_review();
        let body = render_pr_review_markdown(&review, 0);
        assert!(body.contains("<!-- APTU_REVIEW -->"));
        assert!(body.contains("✅ Approve"));
        assert!(body.contains("Good PR overall."));
        assert!(body.contains("aptu"));
    }

    #[test]
    fn test_render_pr_review_markdown_empty_arrays() {
        let review = PrReviewResponse {
            summary: "LGTM".to_string(),
            verdict: "approve".to_string(),
            strengths: vec![],
            concerns: vec![],
            comments: vec![],
            suggestions: vec![],
            disclaimer: None,
        };
        let body = render_pr_review_markdown(&review, 3);
        assert!(body.contains("<!-- APTU_REVIEW -->"));
        assert!(!body.contains("### Strengths"));
        assert!(!body.contains("### Concerns"));
        assert!(!body.contains("### Inline Comments"));
        assert!(!body.contains("### Suggestions"));
    }

    #[test]
    fn test_render_pr_review_markdown_verdict_badges() {
        let mut r = make_pr_review();
        r.verdict = "approve".to_string();
        assert!(render_pr_review_markdown(&r, 0).contains("✅ Approve"));
        r.verdict = "request_changes".to_string();
        assert!(render_pr_review_markdown(&r, 0).contains("❌ Request Changes"));
        r.verdict = "request-changes".to_string();
        assert!(render_pr_review_markdown(&r, 0).contains("❌ Request Changes"));
        r.verdict = "comment".to_string();
        assert!(render_pr_review_markdown(&r, 0).contains("💬 Comment"));
    }

    #[test]
    fn test_render_pr_review_comment_body_plain_text() {
        let base = PrReviewComment {
            file: "f.rs".to_string(),
            line: Some(1),
            comment: "test msg".to_string(),
            severity: CommentSeverity::Issue,
            suggested_code: None,
        };
        // No admonition badges -- plain prose only
        let body = render_pr_review_comment_body(&base);
        assert!(!body.contains("[!CAUTION]"));
        assert!(!body.contains("[!WARNING]"));
        assert!(!body.contains("[!TIP]"));
        assert!(!body.contains("[!NOTE]"));
        assert!(body.contains("test msg"));
        // Severity variants all produce plain text
        let w = PrReviewComment {
            severity: CommentSeverity::Warning,
            ..base.clone()
        };
        assert!(!render_pr_review_comment_body(&w).contains("[!"));
        let s = PrReviewComment {
            severity: CommentSeverity::Suggestion,
            ..base.clone()
        };
        assert!(!render_pr_review_comment_body(&s).contains("[!"));
        let i = PrReviewComment {
            severity: CommentSeverity::Info,
            ..base.clone()
        };
        assert!(!render_pr_review_comment_body(&i).contains("[!"));
    }

    #[test]
    fn test_render_pr_review_markdown_notable_changes_shown() {
        let mut review = make_pr_review();
        review.concerns = vec![
            "Removes CodeQL without replacement".to_string(),
            "cargo-nextest not pinned".to_string(),
        ];
        let body = render_pr_review_markdown(&review, 6);
        assert!(body.contains("- Removes CodeQL without replacement"));
        assert!(body.contains("- cargo-nextest not pinned"));
    }

    #[test]
    fn test_render_pr_review_markdown_notable_changes_hidden() {
        let mut review = make_pr_review();
        review.concerns = vec!["Some concern".to_string()];
        let body = render_pr_review_markdown(&review, 3);
        assert!(!body.contains("- Some concern"));
    }

    #[test]
    fn test_render_pr_review_comment_body_with_suggestion() {
        let comment = PrReviewComment {
            file: "src/main.rs".to_string(),
            line: Some(10),
            comment: "Use ? instead of unwrap.".to_string(),
            severity: CommentSeverity::Warning,
            suggested_code: Some("    let x = foo()?;\n".to_string()),
        };
        let body = render_pr_review_comment_body(&comment);
        assert!(!body.contains("[!"));
        assert!(body.contains("Use ? instead of unwrap."));
        assert!(body.contains("```suggestion"));
        assert!(body.contains("let x = foo()?;"));
    }

    #[test]
    fn test_render_pr_review_comment_body_without_suggestion() {
        let comment = PrReviewComment {
            file: "src/main.rs".to_string(),
            line: Some(10),
            comment: "Consider refactoring this module.".to_string(),
            severity: CommentSeverity::Info,
            suggested_code: None,
        };
        let body = render_pr_review_comment_body(&comment);
        assert!(!body.contains("[!"));
        assert!(!body.contains("```suggestion"));
    }
}