Skip to main content

diff_risk_core/
report.rs

1//! Output types: [`Finding`], [`RiskReport`], and supporting enums.
2
3use serde::{Deserialize, Serialize};
4
5/// Categories of semantic risk, as enumerated in the `diff-risk` specification.
6#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
7#[serde(rename_all = "snake_case")]
8pub enum RiskCategory {
9    /// A. Public API contract changes (signatures, visibility, return types).
10    ApiContract,
11    /// B. Async boundary changes (`.await`, `spawn`, `block_on`, blocking calls).
12    AsyncBoundary,
13    /// C. Serde / schema drift (renamed fields, changed field types).
14    SerdeDrift,
15    /// D. Auth & permission gate modifications.
16    AuthGate,
17    /// E. Concurrency and memory-safety primitives (`Mutex`, `RwLock`, `Arc`, `unsafe`).
18    Concurrency,
19    /// Everything else — low-risk logic or cosmetic changes.
20    Other,
21}
22
23impl RiskCategory {
24    /// Human-readable display name matching the README headings.
25    #[must_use]
26    pub fn label(self) -> &'static str {
27        match self {
28            Self::ApiContract => "API Contract Change",
29            Self::AsyncBoundary => "Async Boundary Change",
30            Self::SerdeDrift => "Serde Schema Drift",
31            Self::AuthGate => "Auth / Permission Gate",
32            Self::Concurrency => "Concurrency / Memory Safety",
33            Self::Other => "Other",
34        }
35    }
36}
37
38/// Severity of an individual finding.
39///
40/// Maps to the scoring weights applied in [`crate::scoring::score_findings`].
41#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
42#[serde(rename_all = "snake_case")]
43pub enum Severity {
44    /// Cosmetic or low-risk change.
45    Low,
46    /// Requires a closer look but unlikely to be dangerous alone.
47    Medium,
48    /// High-risk change — likely to surprise or break things.
49    High,
50    /// Security- or safety-critical change.
51    Critical,
52}
53
54impl Severity {
55    /// Numeric weight used by [`crate::scoring::score_findings`].
56    #[must_use]
57    pub fn weight(self) -> f32 {
58        match self {
59            Self::Low => 1.0,
60            Self::Medium => 3.0,
61            Self::High => 6.0,
62            Self::Critical => 9.0,
63        }
64    }
65
66    /// Short emoji marker for human-readable output.
67    #[must_use]
68    pub fn marker(self) -> &'static str {
69        match self {
70            Self::Low => "✅",
71            Self::Medium => "🟡",
72            Self::High => "⚠️",
73            Self::Critical => "🚨",
74        }
75    }
76}
77
78/// A single detector hit against a specific file/line region.
79#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
80pub struct Finding {
81    /// Category this finding belongs to.
82    pub category: RiskCategory,
83    /// Severity assigned by the detector.
84    pub severity: Severity,
85    /// File path, as reported in the diff header.
86    pub file: String,
87    /// 1-based line number in the new file, or `None` for whole-file findings.
88    pub line: Option<u32>,
89    /// Short human-readable explanation.
90    pub message: String,
91}
92
93/// Aggregated output of an analysis run.
94#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
95pub struct RiskReport {
96    /// All findings, in detector-defined order.
97    pub findings: Vec<Finding>,
98    /// Overall risk score on a 0.0–10.0 scale.
99    pub score: f32,
100}
101
102impl RiskReport {
103    /// Return findings filtered to a single category.
104    #[must_use]
105    pub fn findings_for(&self, category: RiskCategory) -> Vec<&Finding> {
106        self.findings
107            .iter()
108            .filter(|f| f.category == category)
109            .collect()
110    }
111
112    /// Highest severity observed in the report, if any findings exist.
113    #[must_use]
114    pub fn max_severity(&self) -> Option<Severity> {
115        self.findings.iter().map(|f| f.severity).max()
116    }
117}