microscope_memory/
meta_supervision.rs1use std::collections::VecDeque;
5use std::sync::{Arc, RwLock};
6use std::time::{SystemTime, UNIX_EPOCH};
7
8#[derive(Debug, Clone)]
10pub struct PerformanceMetrics {
11 pub timestamp: u64,
12 pub response_time_ms: f32,
13 pub memory_usage_mb: f32,
14 pub attention_efficiency: f32, pub goal_progress: f32, pub error_rate: f32, pub overall_score: f32,
18}
19
20pub struct MetaSupervisor {
22 metrics_history: Arc<RwLock<VecDeque<PerformanceMetrics>>>,
23 correction_strategies: Vec<String>,
24 performance_thresholds: (f32, f32, f32), last_correction_time: u64,
26 correction_cooldown_secs: u64,
27}
28
29impl Default for MetaSupervisor {
30 fn default() -> Self {
31 Self::new()
32 }
33}
34
35impl MetaSupervisor {
36 pub fn new() -> Self {
38 Self {
39 metrics_history: Arc::new(RwLock::new(VecDeque::with_capacity(100))),
40 correction_strategies: vec![
41 "reduce_complexity".to_string(),
42 "increase_attention_focus".to_string(),
43 "optimize_memory_usage".to_string(),
44 "adjust_suppression_threshold".to_string(),
45 "reallocate_resources".to_string(),
46 ],
47 performance_thresholds: (0.7, 0.5, 0.3),
48 last_correction_time: 0,
49 correction_cooldown_secs: 60, }
51 }
52
53 pub fn record_metrics(
55 &mut self,
56 response_time_ms: f32,
57 memory_usage_mb: f32,
58 attention_efficiency: f32,
59 goal_progress: f32,
60 error_rate: f32,
61 ) -> PerformanceMetrics {
62 let timestamp = SystemTime::now()
63 .duration_since(UNIX_EPOCH)
64 .unwrap()
65 .as_secs();
66
67 let overall_score = 0.3 * (1.0 - (response_time_ms / 1000.0).min(1.0))
69 + 0.2 * (1.0 - (memory_usage_mb / 1000.0).min(1.0))
70 + 0.2 * attention_efficiency
71 + 0.2 * goal_progress
72 + 0.1 * (1.0 - error_rate);
73
74 let metrics = PerformanceMetrics {
75 timestamp,
76 response_time_ms,
77 memory_usage_mb,
78 attention_efficiency,
79 goal_progress,
80 error_rate,
81 overall_score,
82 };
83
84 let mut history = crate::sync_guard::write_lock(&self.metrics_history);
86 if history.len() >= 100 {
87 history.pop_front(); }
89 history.push_back(metrics.clone());
90
91 metrics
92 }
93
94 pub fn evaluate_and_correct(&mut self) -> Option<String> {
96 let history = crate::sync_guard::read_lock(&self.metrics_history);
97
98 if history.is_empty() {
99 return None;
100 }
101
102 let current_time = SystemTime::now()
103 .duration_since(UNIX_EPOCH)
104 .unwrap()
105 .as_secs();
106
107 if current_time - self.last_correction_time < self.correction_cooldown_secs {
109 return None;
110 }
111
112 let recent: Vec<&PerformanceMetrics> = history.iter().rev().take(10).collect();
114 let avg_score: f32 =
115 recent.iter().map(|m| m.overall_score).sum::<f32>() / recent.len() as f32;
116
117 let (warning_threshold, alert_threshold, critical_threshold) = self.performance_thresholds;
118
119 if avg_score < critical_threshold {
120 self.last_correction_time = current_time;
121 Some("critical_performance_degradation".to_string())
122 } else if avg_score < alert_threshold {
123 self.last_correction_time = current_time;
124 Some(self.select_correction_strategy("alert"))
125 } else if avg_score < warning_threshold {
126 self.last_correction_time = current_time;
127 Some(self.select_correction_strategy("warning"))
128 } else {
129 None
130 }
131 }
132
133 fn select_correction_strategy(&self, severity: &str) -> String {
135 match severity {
136 "critical" => "reallocate_resources".to_string(),
137 "alert" => {
138 if self.correction_strategies.len() > 1 {
139 self.correction_strategies[1].clone()
140 } else {
141 "increase_attention_focus".to_string()
142 }
143 }
144 "warning" => {
145 if !self.correction_strategies.is_empty() {
146 self.correction_strategies[0].clone()
147 } else {
148 "reduce_complexity".to_string()
149 }
150 }
151 _ => "adjust_parameters".to_string(),
152 }
153 }
154
155 pub fn analyze_trends(&self) -> (f32, f32) {
157 let history = crate::sync_guard::read_lock(&self.metrics_history);
158
159 if history.len() < 2 {
160 return (0.0, 0.0);
161 }
162
163 let first_half: Vec<&PerformanceMetrics> = history.iter().take(history.len() / 2).collect();
164 let second_half: Vec<&PerformanceMetrics> =
165 history.iter().skip(history.len() / 2).collect();
166
167 if first_half.is_empty() || second_half.is_empty() {
168 return (0.0, 0.0);
169 }
170
171 let first_avg: f32 =
172 first_half.iter().map(|m| m.overall_score).sum::<f32>() / first_half.len() as f32;
173 let second_avg: f32 =
174 second_half.iter().map(|m| m.overall_score).sum::<f32>() / second_half.len() as f32;
175
176 let trend = second_avg - first_avg;
177 let volatility = self.calculate_volatility(&history);
178
179 (trend, volatility)
180 }
181
182 fn calculate_volatility(&self, history: &VecDeque<PerformanceMetrics>) -> f32 {
184 if history.len() < 2 {
185 return 0.0;
186 }
187
188 let scores: Vec<f32> = history.iter().map(|m| m.overall_score).collect();
189 let mean = scores.iter().sum::<f32>() / scores.len() as f32;
190
191 let variance = scores
192 .iter()
193 .map(|&score| (score - mean).powi(2))
194 .sum::<f32>()
195 / scores.len() as f32;
196
197 variance.sqrt()
198 }
199
200 pub fn get_summary(&self) -> (f32, f32, f32) {
202 let history = crate::sync_guard::read_lock(&self.metrics_history);
203
204 if history.is_empty() {
205 return (0.0, 0.0, 0.0);
206 }
207
208 let current = history.back().unwrap().overall_score;
209 let (trend, volatility) = self.analyze_trends();
210
211 (current, trend, volatility)
212 }
213
214 pub fn add_correction_strategy(&mut self, strategy: &str) {
216 self.correction_strategies.push(strategy.to_string());
217 }
218}
219
220pub fn generate_report(supervisor: &MetaSupervisor) -> String {
222 let (current_score, trend, volatility) = supervisor.get_summary();
223 let (warning, alert, critical) = supervisor.performance_thresholds;
224
225 format!(
226 "Performance Report:\n\
227 Current Score: {:.2}\n\
228 Trend: {:.2}\n\
229 Volatility: {:.2}\n\
230 Thresholds - Warning: {:.2}, Alert: {:.2}, Critical: {:.2}\n\
231 Status: {}",
232 current_score,
233 trend,
234 volatility,
235 warning,
236 alert,
237 critical,
238 if current_score >= warning {
239 "Optimal"
240 } else if current_score >= alert {
241 "Warning"
242 } else if current_score >= critical {
243 "Alert"
244 } else {
245 "Critical"
246 }
247 )
248}