agentic_codebase/collective/
delta.rs1use serde::{Deserialize, Serialize};
7
8use crate::types::AcbError;
9use crate::types::AcbResult;
10
11#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
13pub enum MistakeCategory {
14 BugPattern,
16 PerformanceAntiPattern,
18 SecurityVulnerability,
20 ApiMisuse,
22 CodeSmell,
24}
25
26impl std::fmt::Display for MistakeCategory {
27 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
28 match self {
29 Self::BugPattern => write!(f, "bug-pattern"),
30 Self::PerformanceAntiPattern => write!(f, "performance-anti-pattern"),
31 Self::SecurityVulnerability => write!(f, "security-vulnerability"),
32 Self::ApiMisuse => write!(f, "api-misuse"),
33 Self::CodeSmell => write!(f, "code-smell"),
34 }
35 }
36}
37
38#[derive(Debug, Clone, Serialize, Deserialize)]
40pub struct MistakeReport {
41 pub category: MistakeCategory,
43 pub description: String,
45 pub pattern_signature: String,
47 pub suggestion: String,
49 pub severity: f32,
51}
52
53#[derive(Debug, Clone, Serialize, Deserialize)]
58pub struct CollectiveDelta {
59 pub version: u32,
61 pub delta_id: String,
63 pub created_at: u64,
65 pub source_id: String,
67 pub patterns: Vec<DeltaPattern>,
69 pub mistakes: Vec<MistakeReport>,
71}
72
73#[derive(Debug, Clone, Serialize, Deserialize)]
75pub struct DeltaPattern {
76 pub name: String,
78 pub language: String,
80 pub signature: String,
82 pub occurrence_count: u32,
84 pub confidence: f32,
86}
87
88impl CollectiveDelta {
89 pub fn new(source_id: String) -> Self {
91 let now = crate::types::now_micros();
92 Self {
93 version: 1,
94 delta_id: String::new(),
95 created_at: now,
96 source_id,
97 patterns: Vec::new(),
98 mistakes: Vec::new(),
99 }
100 }
101
102 pub fn add_pattern(&mut self, pattern: DeltaPattern) {
104 self.patterns.push(pattern);
105 }
106
107 pub fn add_mistake(&mut self, mistake: MistakeReport) {
109 self.mistakes.push(mistake);
110 }
111
112 pub fn finalize(&mut self) -> AcbResult<()> {
114 let json = serde_json::to_vec(self)
115 .map_err(|e| AcbError::Compression(format!("Failed to serialize delta: {}", e)))?;
116 let hash = blake3::hash(&json);
117 self.delta_id = hash.to_hex().to_string();
118 Ok(())
119 }
120
121 pub fn compress(&self) -> AcbResult<Vec<u8>> {
125 let json = serde_json::to_vec(self)
126 .map_err(|e| AcbError::Compression(format!("Failed to serialize delta: {}", e)))?;
127 let compressed = lz4_flex::compress_prepend_size(&json);
128 Ok(compressed)
129 }
130
131 pub fn decompress(data: &[u8]) -> AcbResult<Self> {
135 let decompressed = lz4_flex::decompress_size_prepended(data)
136 .map_err(|e| AcbError::Compression(format!("Failed to decompress delta: {}", e)))?;
137 let delta: CollectiveDelta = serde_json::from_slice(&decompressed)
138 .map_err(|e| AcbError::Compression(format!("Failed to deserialize delta: {}", e)))?;
139 Ok(delta)
140 }
141
142 pub fn is_empty(&self) -> bool {
144 self.patterns.is_empty() && self.mistakes.is_empty()
145 }
146}