Skip to main content

agentic_codebase/collective/
patterns.rs

1//! Pattern aggregation.
2//!
3//! Types and utilities for extracting, categorising, and aggregating
4//! usage patterns from code graphs.
5
6use serde::{Deserialize, Serialize};
7
8/// The category of a usage pattern.
9#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
10pub enum PatternCategory {
11    /// A structural design pattern (e.g., Singleton, Factory).
12    DesignPattern,
13    /// An API usage pattern (e.g., common call sequences).
14    ApiUsage,
15    /// An error handling pattern (e.g., retry with backoff).
16    ErrorHandling,
17    /// A concurrency pattern (e.g., producer-consumer).
18    Concurrency,
19    /// A data transformation pattern (e.g., map-filter-reduce).
20    DataTransform,
21    /// A testing pattern (e.g., AAA, fixture-based).
22    TestingPattern,
23}
24
25impl std::fmt::Display for PatternCategory {
26    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
27        match self {
28            Self::DesignPattern => write!(f, "design-pattern"),
29            Self::ApiUsage => write!(f, "api-usage"),
30            Self::ErrorHandling => write!(f, "error-handling"),
31            Self::Concurrency => write!(f, "concurrency"),
32            Self::DataTransform => write!(f, "data-transform"),
33            Self::TestingPattern => write!(f, "testing-pattern"),
34        }
35    }
36}
37
38/// Complexity bucket for classifying code units.
39#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
40pub enum ComplexityBucket {
41    /// Cyclomatic complexity 1-5.
42    Low,
43    /// Cyclomatic complexity 6-15.
44    Medium,
45    /// Cyclomatic complexity 16-30.
46    High,
47    /// Cyclomatic complexity > 30.
48    VeryHigh,
49}
50
51impl ComplexityBucket {
52    /// Classify a complexity value into a bucket.
53    pub fn from_complexity(complexity: u32) -> Self {
54        match complexity {
55            0..=5 => Self::Low,
56            6..=15 => Self::Medium,
57            16..=30 => Self::High,
58            _ => Self::VeryHigh,
59        }
60    }
61}
62
63impl std::fmt::Display for ComplexityBucket {
64    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
65        match self {
66            Self::Low => write!(f, "low"),
67            Self::Medium => write!(f, "medium"),
68            Self::High => write!(f, "high"),
69            Self::VeryHigh => write!(f, "very-high"),
70        }
71    }
72}
73
74/// Quality assessment of a pattern.
75#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
76pub enum PatternQuality {
77    /// Well-established, widely used pattern.
78    Established,
79    /// Emerging pattern, growing in usage.
80    Emerging,
81    /// Declining pattern, being replaced.
82    Declining,
83    /// Unknown or unclassified quality.
84    Unknown,
85}
86
87impl std::fmt::Display for PatternQuality {
88    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
89        match self {
90            Self::Established => write!(f, "established"),
91            Self::Emerging => write!(f, "emerging"),
92            Self::Declining => write!(f, "declining"),
93            Self::Unknown => write!(f, "unknown"),
94        }
95    }
96}
97
98/// Structural signature of a usage pattern.
99#[derive(Debug, Clone, Serialize, Deserialize)]
100pub struct PatternSignature {
101    /// Language this pattern was observed in.
102    pub language: String,
103    /// Category of the pattern.
104    pub category: PatternCategory,
105    /// Structural hash for deduplication.
106    pub structure_hash: String,
107    /// Human-readable description of the pattern structure.
108    pub description: String,
109}
110
111/// A detected usage pattern with metadata.
112#[derive(Debug, Clone, Serialize, Deserialize)]
113pub struct UsagePattern {
114    /// Pattern signature for identification.
115    pub signature: PatternSignature,
116    /// How many times this pattern was observed.
117    pub occurrence_count: u32,
118    /// Quality assessment.
119    pub quality: PatternQuality,
120    /// Confidence (0.0 to 1.0).
121    pub confidence: f32,
122    /// Typical complexity bucket for code using this pattern.
123    pub typical_complexity: ComplexityBucket,
124    /// Example file paths where this pattern was found.
125    pub example_paths: Vec<String>,
126}
127
128/// Extracts usage patterns from a code graph.
129///
130/// Currently a placeholder implementation that demonstrates the type system
131/// without performing deep pattern mining.
132#[derive(Debug, Clone)]
133pub struct PatternExtractor {
134    /// Minimum number of occurrences to report a pattern.
135    min_occurrences: u32,
136}
137
138impl PatternExtractor {
139    /// Create a new pattern extractor.
140    pub fn new() -> Self {
141        Self { min_occurrences: 2 }
142    }
143
144    /// Create a pattern extractor with a custom minimum occurrence threshold.
145    pub fn with_min_occurrences(min_occurrences: u32) -> Self {
146        Self { min_occurrences }
147    }
148
149    /// Extract patterns from a code graph.
150    ///
151    /// This is a placeholder implementation. In a full implementation,
152    /// this would perform structural pattern mining on the graph.
153    /// Currently returns an empty list.
154    pub fn extract(&self, _graph: &crate::graph::CodeGraph) -> Vec<UsagePattern> {
155        // Placeholder: real implementation would mine the graph for patterns.
156        tracing::debug!(
157            "PatternExtractor::extract called (min_occurrences={}); returning empty (placeholder).",
158            self.min_occurrences
159        );
160        Vec::new()
161    }
162
163    /// Get the minimum occurrence threshold.
164    pub fn min_occurrences(&self) -> u32 {
165        self.min_occurrences
166    }
167}
168
169impl Default for PatternExtractor {
170    fn default() -> Self {
171        Self::new()
172    }
173}