pmat 2.93.1

PMAT - Zero-config AI context generation and code quality toolkit (CLI, MCP, HTTP)
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
//! GitHub Actions integration for unified quality system
//!
//! Provides quality gates and automation through GitHub Actions workflows

use crate::unified_quality::enforcement::{Decision, DiffAnalysis, ErrorBudgetEnforcer};
use crate::unified_quality::foundation::QualityMonitor;
use anyhow::Result;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;

/// GitHub Actions integration for quality enforcement
pub struct GitHubActionsIntegration {
    /// Quality monitor
    monitor: QualityMonitor,

    /// Error budget enforcer  
    enforcer: ErrorBudgetEnforcer,

    /// Integration configuration
    config: GitHubConfig,
}

/// GitHub Actions configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GitHubConfig {
    /// Repository owner/name
    pub repository: String,

    /// GitHub token for API access
    pub token: String,

    /// Quality gate thresholds
    pub quality_thresholds: QualityThresholds,

    /// Workflow triggers
    pub triggers: WorkflowTriggers,

    /// Comment settings
    pub comments: CommentConfig,
}

/// Quality thresholds for GitHub Actions
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QualityThresholds {
    /// Maximum allowed complexity increase
    pub max_complexity_increase: u32,

    /// Maximum allowed SATD increase
    pub max_satd_increase: u32,

    /// Minimum coverage requirement
    pub min_coverage: f64,

    /// Block PR if thresholds exceeded
    pub block_on_violation: bool,
}

impl Default for QualityThresholds {
    fn default() -> Self {
        Self {
            max_complexity_increase: 50,
            max_satd_increase: 5,
            min_coverage: 0.8,
            block_on_violation: true,
        }
    }
}

/// Workflow triggers configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkflowTriggers {
    /// Run on pull request
    pub on_pull_request: bool,

    /// Run on push to main
    pub on_push_main: bool,

    /// Run on schedule
    pub on_schedule: Option<String>,

    /// Specific branches to monitor
    pub branches: Vec<String>,
}

impl Default for WorkflowTriggers {
    fn default() -> Self {
        Self {
            on_pull_request: true,
            on_push_main: true,
            on_schedule: Some("0 6 * * 1".to_string()), // Weekly on Monday 6 AM
            branches: vec!["main".to_string(), "master".to_string()],
        }
    }
}

/// Comment configuration for GitHub
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CommentConfig {
    /// Post quality summary as PR comment
    pub post_summary: bool,

    /// Post detailed metrics
    pub post_details: bool,

    /// Update existing comments
    pub update_existing: bool,

    /// Comment template
    pub template: CommentTemplate,
}

impl Default for CommentConfig {
    fn default() -> Self {
        Self {
            post_summary: true,
            post_details: false,
            update_existing: true,
            template: CommentTemplate::default(),
        }
    }
}

/// Comment template configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CommentTemplate {
    /// Header for quality reports
    pub header: String,

    /// Success message template
    pub success_template: String,

    /// Warning message template  
    pub warning_template: String,

    /// Failure message template
    pub failure_template: String,
}

impl Default for CommentTemplate {
    fn default() -> Self {
        Self {
            header: "## 📊 Code Quality Report".to_string(),
            success_template: "✅ **Quality checks passed!**\n\n- Complexity: {complexity}\n- SATD Count: {satd_count}\n- Coverage: {coverage:.1%}".to_string(),
            warning_template: "⚠️ **Quality warnings detected:**\n\n{warnings}\n\n- Complexity: {complexity}\n- SATD Count: {satd_count}\n- Coverage: {coverage:.1%}".to_string(),
            failure_template: "❌ **Quality checks failed:**\n\n{failures}\n\n- Complexity: {complexity}\n- SATD Count: {satd_count}\n- Coverage: {coverage:.1%}\n\nPlease address these issues before merging.".to_string(),
        }
    }
}

/// GitHub Actions workflow result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkflowResult {
    /// Overall status
    pub status: WorkflowStatus,

    /// Quality analysis results
    pub analysis: QualityAnalysis,

    /// Enforcement decision
    pub decision: Decision,

    /// Generated comment (if any)
    pub comment: Option<String>,

    /// Workflow outputs for GitHub Actions
    pub outputs: HashMap<String, String>,
}

/// Workflow execution status
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum WorkflowStatus {
    /// Quality checks passed
    Success,

    /// Quality issues found but not blocking
    Warning,

    /// Quality checks failed - blocking merge
    Failure,

    /// Error during execution
    Error(String),
}

/// Quality analysis summary
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QualityAnalysis {
    /// Files analyzed
    pub files_analyzed: usize,

    /// Total complexity
    pub total_complexity: u32,

    /// Complexity change from base
    pub complexity_change: i32,

    /// SATD count
    pub satd_count: u32,

    /// SATD change from base
    pub satd_change: i32,

    /// Test coverage
    pub coverage: f64,

    /// Coverage change from base
    pub coverage_change: f64,

    /// Quality violations found
    pub violations: Vec<QualityViolation>,
}

/// Quality violation details
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QualityViolation {
    /// File path
    pub file: String,

    /// Violation type
    pub violation_type: String,

    /// Severity level
    pub severity: ViolationSeverity,

    /// Description
    pub message: String,

    /// Line number (if applicable)
    pub line: Option<u32>,
}

/// Violation severity levels
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ViolationSeverity {
    Info,
    Warning,
    Error,
    Critical,
}

impl GitHubActionsIntegration {
    /// Create new GitHub Actions integration
    #[must_use] 
    pub fn new(
        monitor: QualityMonitor,
        enforcer: ErrorBudgetEnforcer,
        config: GitHubConfig,
    ) -> Self {
        Self {
            monitor,
            enforcer,
            config,
        }
    }

    /// Run quality analysis for pull request
    pub async fn analyze_pull_request(
        &mut self,
        _pr_number: u32,
        _base_ref: String,
        _head_ref: String,
        changed_files: Vec<PathBuf>,
    ) -> Result<WorkflowResult> {
        // Analyze changed files
        let mut total_complexity = 0;
        let mut total_satd = 0;
        let mut violations = Vec::new();

        for file in &changed_files {
            if let Some(metrics) = self.monitor.get_metrics(file) {
                total_complexity += metrics.complexity;
                total_satd += metrics.satd_count;

                // Check for violations
                if metrics.complexity > self.config.quality_thresholds.max_complexity_increase {
                    violations.push(QualityViolation {
                        file: file.to_string_lossy().to_string(),
                        violation_type: "complexity".to_string(),
                        severity: ViolationSeverity::Error,
                        message: format!(
                            "Complexity {} exceeds threshold {}",
                            metrics.complexity,
                            self.config.quality_thresholds.max_complexity_increase
                        ),
                        line: None,
                    });
                }
            }
        }

        // Create diff analysis for enforcer
        let diff = DiffAnalysis {
            complexity_change: total_complexity as i32, // Simplified - would need base comparison
            satd_change: total_satd as i32,
            coverage_change: 0.0, // Would need actual coverage analysis
            files_changed: changed_files
                .iter()
                .map(|p| p.to_string_lossy().to_string())
                .collect(),
        };

        // Get enforcement decision
        let team_id = self.extract_team_from_repository();
        let decision = self.enforcer.check_commit(&team_id, &diff);

        // Determine workflow status
        let status = match &decision {
            Decision::Approved => {
                if violations.is_empty() {
                    WorkflowStatus::Success
                } else {
                    WorkflowStatus::Warning
                }
            }
            Decision::Warning(_) => WorkflowStatus::Warning,
            Decision::RequiresApproval { .. } => WorkflowStatus::Warning,
            Decision::Blocked { .. } => WorkflowStatus::Failure,
        };

        // Create analysis summary
        let analysis = QualityAnalysis {
            files_analyzed: changed_files.len(),
            total_complexity,
            complexity_change: total_complexity as i32,
            satd_count: total_satd,
            satd_change: total_satd as i32,
            coverage: 0.8, // Would need actual coverage calculation
            coverage_change: 0.0,
            violations,
        };

        // Generate comment if configured
        let comment = if self.config.comments.post_summary {
            Some(self.generate_comment(&status, &analysis, &decision))
        } else {
            None
        };

        // Create workflow outputs
        let mut outputs = HashMap::new();
        outputs.insert("status".to_string(), format!("{status:?}"));
        outputs.insert("complexity".to_string(), total_complexity.to_string());
        outputs.insert("satd_count".to_string(), total_satd.to_string());
        outputs.insert(
            "files_analyzed".to_string(),
            changed_files.len().to_string(),
        );
        outputs.insert(
            "violations".to_string(),
            analysis.violations.len().to_string(),
        );

        Ok(WorkflowResult {
            status,
            analysis,
            decision,
            comment,
            outputs,
        })
    }

    /// Generate GitHub Actions workflow YAML
    #[must_use] 
    pub fn generate_workflow_yaml(&self) -> String {
        let triggers = &self.config.triggers;
        let thresholds = &self.config.quality_thresholds;

        format!(
            r#"name: Quality Gate
on:
  pull_request:
    branches: [{}]
  push:
    branches: [{}]
  schedule:
    - cron: '{}'

jobs:
  quality-gate:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      pull-requests: write
      checks: write
    
    steps:
    - uses: actions/checkout@v4
      with:
        fetch-depth: 0
    
    - name: Setup Rust
      uses: actions-rs/toolchain@v1
      with:
        toolchain: stable
        profile: minimal
        override: true
    
    - name: Install PMAT
      run: cargo install pmat --version latest
    
    - name: Run Quality Analysis
      id: quality
      run: |
        # Run PMAT unified quality analysis
        pmat unified-quality analyze \
          --max-complexity {} \
          --max-satd {} \
          --min-coverage {} \
          --output-format github-actions \
          --changed-files-only ${{{{ github.event_name == 'pull_request' }}}}
    
    - name: Update PR Comment
      if: github.event_name == 'pull_request'
      uses: actions/github-script@v7
      with:
        script: |
          const analysis = JSON.parse(process.env.QUALITY_ANALYSIS);
          const comment = process.env.QUALITY_COMMENT;
          
          // Find existing comment
          const comments = await github.rest.issues.listComments({{
            owner: context.repo.owner,
            repo: context.repo.repo,
            issue_number: context.issue.number,
          }});
          
          const existingComment = comments.data.find(
            comment => comment.body.includes('📊 Code Quality Report')
          );
          
          if (existingComment && {}) {{
            // Update existing comment
            await github.rest.issues.updateComment({{
              owner: context.repo.owner,
              repo: context.repo.repo,
              comment_id: existingComment.id,
              body: comment,
            }});
          }} else {{
            // Create new comment
            await github.rest.issues.createComment({{
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: context.issue.number,
              body: comment,
            }});
          }}
      env:
        QUALITY_ANALYSIS: ${{{{ steps.quality.outputs.analysis }}}}
        QUALITY_COMMENT: ${{{{ steps.quality.outputs.comment }}}}
    
    - name: Set Status Check
      if: always()
      run: |
        status="${{{{ steps.quality.outputs.status }}}}"
        if [ "$status" = "Success" ]; then
          exit 0
        elif [ "$status" = "Warning" ]; then
          echo "::warning::Quality warnings detected"
          exit 0
        else
          echo "::error::Quality checks failed"
          exit 1
        fi
"#,
            triggers.branches.join(", "),
            triggers.branches.join(", "),
            triggers.on_schedule.as_deref().unwrap_or("0 6 * * 1"),
            thresholds.max_complexity_increase,
            thresholds.max_satd_increase,
            thresholds.min_coverage,
            self.config.comments.update_existing,
        )
    }

    /// Generate comment text based on analysis results
    fn generate_comment(
        &self,
        status: &WorkflowStatus,
        analysis: &QualityAnalysis,
        decision: &Decision,
    ) -> String {
        let template = &self.config.comments.template;
        let mut comment = format!("{}\n\n", template.header);

        match status {
            WorkflowStatus::Success => {
                comment.push_str(
                    &template
                        .success_template
                        .replace("{complexity}", &analysis.total_complexity.to_string())
                        .replace("{satd_count}", &analysis.satd_count.to_string())
                        .replace("{coverage}", &format!("{:.1}", analysis.coverage * 100.0)),
                );
            }
            WorkflowStatus::Warning => {
                let warnings = analysis
                    .violations
                    .iter()
                    .filter(|v| matches!(v.severity, ViolationSeverity::Warning))
                    .map(|v| format!("- {}: {}", v.file, v.message))
                    .collect::<Vec<_>>()
                    .join("\n");

                comment.push_str(
                    &template
                        .warning_template
                        .replace("{warnings}", &warnings)
                        .replace("{complexity}", &analysis.total_complexity.to_string())
                        .replace("{satd_count}", &analysis.satd_count.to_string())
                        .replace("{coverage}", &format!("{:.1}", analysis.coverage * 100.0)),
                );
            }
            WorkflowStatus::Failure => {
                let failures = analysis
                    .violations
                    .iter()
                    .filter(|v| {
                        matches!(
                            v.severity,
                            ViolationSeverity::Error | ViolationSeverity::Critical
                        )
                    })
                    .map(|v| format!("- {}: {}", v.file, v.message))
                    .collect::<Vec<_>>()
                    .join("\n");

                comment.push_str(
                    &template
                        .failure_template
                        .replace("{failures}", &failures)
                        .replace("{complexity}", &analysis.total_complexity.to_string())
                        .replace("{satd_count}", &analysis.satd_count.to_string())
                        .replace("{coverage}", &format!("{:.1}", analysis.coverage * 100.0)),
                );
            }
            WorkflowStatus::Error(e) => {
                comment.push_str(&format!("❌ **Error during quality analysis:**\n\n{e}"));
            }
        }

        // Add decision details
        match decision {
            Decision::Approved => {
                comment.push_str("\n\n✅ **Error budget status:** Approved");
            }
            Decision::Warning(msg) => {
                comment.push_str(&format!("\n\n⚠️ **Error budget status:** Warning\n{msg}"));
            }
            Decision::RequiresApproval { approvers, .. } => {
                comment.push_str(&format!(
                    "\n\n👥 **Error budget status:** Requires approval from: {}",
                    approvers.join(", ")
                ));
            }
            Decision::Blocked { suggestion, .. } => {
                comment.push_str(&format!(
                    "\n\n🚫 **Error budget status:** Blocked\n\n{suggestion}"
                ));
            }
        }

        comment.push_str(&format!(
            "\n\n---\n📊 **Summary:**\n- Files analyzed: {}\n- Complexity change: {:+}\n- SATD change: {:+}\n- Coverage: {:.1}%",
            analysis.files_analyzed,
            analysis.complexity_change,
            analysis.satd_change,
            analysis.coverage * 100.0
        ));

        comment
    }

    /// Extract team identifier from repository name
    fn extract_team_from_repository(&self) -> String {
        // Simple heuristic: use repository owner as team
        self.config
            .repository
            .split('/')
            .next()
            .unwrap_or("default")
            .to_string()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::unified_quality::enforcement::EnforcerConfig;
    use crate::unified_quality::foundation::MonitorConfig;

    #[test]
    fn test_github_config_default() {
        let thresholds = QualityThresholds::default();
        assert_eq!(thresholds.max_complexity_increase, 50);
        assert_eq!(thresholds.max_satd_increase, 5);
        assert_eq!(thresholds.min_coverage, 0.8);
        assert!(thresholds.block_on_violation);
    }

    #[test]
    fn test_workflow_triggers_default() {
        let triggers = WorkflowTriggers::default();
        assert!(triggers.on_pull_request);
        assert!(triggers.on_push_main);
        assert!(triggers.on_schedule.is_some());
        assert_eq!(triggers.branches.len(), 2);
    }

    #[test]
    fn test_comment_template_default() {
        let template = CommentTemplate::default();
        assert!(template.header.contains("Code Quality Report"));
        assert!(template.success_template.contains("Quality checks passed"));
        assert!(template.failure_template.contains("Quality checks failed"));
    }

    #[test]
    fn test_workflow_yaml_generation() {
        let monitor = QualityMonitor::new(MonitorConfig::default()).unwrap();
        let enforcer = ErrorBudgetEnforcer::new(EnforcerConfig::default());
        let config = GitHubConfig {
            repository: "owner/repo".to_string(),
            token: "token".to_string(),
            quality_thresholds: QualityThresholds::default(),
            triggers: WorkflowTriggers::default(),
            comments: CommentConfig::default(),
        };

        let integration = GitHubActionsIntegration::new(monitor, enforcer, config);
        let yaml = integration.generate_workflow_yaml();

        assert!(yaml.contains("name: Quality Gate"));
        assert!(yaml.contains("pull_request:"));
        assert!(yaml.contains("pmat unified-quality analyze"));
    }

    #[test]
    fn test_violation_severity_ordering() {
        let severities = vec![
            ViolationSeverity::Info,
            ViolationSeverity::Warning,
            ViolationSeverity::Error,
            ViolationSeverity::Critical,
        ];

        // Just test that all variants exist and can be created
        assert_eq!(severities.len(), 4);
    }

    #[test]
    fn test_team_extraction() {
        let monitor = QualityMonitor::new(MonitorConfig::default()).unwrap();
        let enforcer = ErrorBudgetEnforcer::new(EnforcerConfig::default());
        let config = GitHubConfig {
            repository: "my-org/my-repo".to_string(),
            token: "token".to_string(),
            quality_thresholds: QualityThresholds::default(),
            triggers: WorkflowTriggers::default(),
            comments: CommentConfig::default(),
        };

        let integration = GitHubActionsIntegration::new(monitor, enforcer, config);
        let team = integration.extract_team_from_repository();
        assert_eq!(team, "my-org");
    }

    #[test]
    fn test_workflow_status_variants() {
        let statuses = vec![
            WorkflowStatus::Success,
            WorkflowStatus::Warning,
            WorkflowStatus::Failure,
            WorkflowStatus::Error("test".to_string()),
        ];

        assert_eq!(statuses.len(), 4);

        // Test Debug formatting
        format!("{:?}", WorkflowStatus::Success);
        format!("{:?}", WorkflowStatus::Error("test".to_string()));
    }
}