aptu-core 0.2.19

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
// 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, 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
}

/// 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");
    }

    // 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,
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ai::types::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,
        };

        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,
        };

        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,
        };

        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"));
    }
}