1use chrono::{DateTime, Utc};
2use hashbrown::HashMap;
3use serde::{Deserialize, Serialize};
4use std::collections::VecDeque;
5use std::fmt::Write as _;
6
7const DOCTOR_UNDERUTILIZED_THRESHOLD: f64 = 0.5;
10
11#[derive(Debug, Clone, Serialize, Deserialize)]
12pub struct SkillMetrics {
13 pub total_skills: u64,
14 pub active_skills: u64,
15 pub total_executions: u64,
16 pub skill_stats: HashMap<String, SkillStats>,
17 pub recent_skill_usage: VecDeque<SkillUsageRecord>,
18}
19
20#[derive(Debug, Clone, Serialize, Deserialize)]
21pub struct SkillStats {
22 pub name: String,
23 pub language: String,
24 pub execution_count: u64,
25 pub success_count: u64,
26 pub total_duration_ms: u64,
27 pub created_at: DateTime<Utc>,
28 pub last_used: DateTime<Utc>,
29}
30
31#[derive(Debug, Clone, Serialize, Deserialize)]
32pub struct SkillUsageRecord {
33 pub skill_name: String,
34 pub success: bool,
35 pub duration_ms: u64,
36 pub timestamp: DateTime<Utc>,
37}
38
39impl SkillMetrics {
40 pub fn new() -> Self {
41 Self {
42 total_skills: 0,
43 active_skills: 0,
44 total_executions: 0,
45 skill_stats: HashMap::new(),
46 recent_skill_usage: VecDeque::with_capacity(100),
47 }
48 }
49
50 pub fn record_created(&mut self, skill_name: String, language: String) {
51 if self.skill_stats.contains_key(&skill_name) {
54 return;
55 }
56 self.total_skills += 1;
57 self.active_skills += 1;
58
59 self.skill_stats.insert(
60 skill_name.clone(),
61 SkillStats {
62 name: skill_name,
63 language,
64 execution_count: 0,
65 success_count: 0,
66 total_duration_ms: 0,
67 created_at: Utc::now(),
68 last_used: Utc::now(),
69 },
70 );
71 }
72
73 pub fn record_deleted(&mut self, skill_name: String) {
74 if self.skill_stats.remove(&skill_name).is_some() {
76 self.active_skills = self.active_skills.saturating_sub(1);
77 }
78 }
79
80 pub fn record_execution(&mut self, skill_name: String, duration_ms: u64, success: bool) {
81 self.total_executions += 1;
82
83 if let Some(stats) = self.skill_stats.get_mut(&skill_name) {
84 stats.execution_count += 1;
85 if success {
86 stats.success_count += 1;
87 }
88 stats.total_duration_ms += duration_ms;
89 stats.last_used = Utc::now();
90 }
91
92 let record = SkillUsageRecord {
93 skill_name,
94 success,
95 duration_ms,
96 timestamp: Utc::now(),
97 };
98
99 if self.recent_skill_usage.len() >= 100 {
100 self.recent_skill_usage.pop_front();
101 }
102 self.recent_skill_usage.push_back(record);
103 }
104
105 pub fn reuse_ratio(&self) -> f64 {
106 if self.active_skills > 0 && self.total_executions > 0 {
107 self.total_executions as f64 / self.active_skills as f64
108 } else {
109 0.0
110 }
111 }
112
113 pub fn get_skill_success_rate(&self, skill_name: &str) -> f64 {
114 if let Some(stats) = self.skill_stats.get(skill_name) {
115 if stats.execution_count > 0 {
116 stats.success_count as f64 / stats.execution_count as f64
117 } else {
118 0.0
119 }
120 } else {
121 0.0
122 }
123 }
124
125 pub fn get_skill_avg_duration(&self, skill_name: &str) -> u64 {
126 if let Some(stats) = self.skill_stats.get(skill_name) {
127 stats.total_duration_ms.checked_div(stats.execution_count).unwrap_or(0)
128 } else {
129 0
130 }
131 }
132
133 pub fn get_underutilized_skills(&self, threshold: f64) -> Vec<String> {
134 let avg_usage = if self.active_skills > 0 {
135 self.total_executions as f64 / self.active_skills as f64
136 } else {
137 0.0
138 };
139
140 self.skill_stats
141 .iter()
142 .filter(|(_, stats)| (stats.execution_count as f64) < (avg_usage * threshold))
143 .map(|(name, _)| name.clone())
144 .collect()
145 }
146
147 #[must_use]
152 pub fn doctor_report(&self) -> String {
153 if self.skill_stats.is_empty() {
154 return "No skills tracked yet this session.".to_string();
155 }
156
157 let mut report = String::new();
158 let removed = self.total_skills.saturating_sub(self.active_skills);
159 let _ = writeln!(
160 report,
161 "Skill health: {} active, {} removed ({} total) | {} executions | reuse ratio {:.1}",
162 self.active_skills,
163 removed,
164 self.total_skills,
165 self.total_executions,
166 self.reuse_ratio()
167 );
168
169 let mut names: Vec<&str> = self.skill_stats.keys().map(String::as_str).collect();
170 names.sort_unstable();
171 report.push_str("name | kind | execs | success | avg ms | last used\n");
172 for name in names {
173 let Some(stats) = self.skill_stats.get(name) else {
174 continue;
175 };
176 let success_pct = self.get_skill_success_rate(name) * 100.0;
177 let _ = writeln!(
178 report,
179 "{} | {} | {} | {:.0}% | {} | {}",
180 stats.name,
181 stats.language,
182 stats.execution_count,
183 success_pct,
184 self.get_skill_avg_duration(name),
185 stats.last_used.format("%Y-%m-%d %H:%M:%S UTC")
186 );
187 }
188
189 let mut underutilized = self.get_underutilized_skills(DOCTOR_UNDERUTILIZED_THRESHOLD);
190 underutilized.sort();
191 if underutilized.is_empty() {
192 report.push_str("Underutilized: none.");
193 } else {
194 let _ = writeln!(report, "Underutilized (below 50% of mean usage) - prune or merge candidates:");
195 for name in underutilized {
196 let execs = self.skill_stats.get(&name).map(|stats| stats.execution_count).unwrap_or(0);
197 let _ = writeln!(report, "- {name} ({execs} execs)");
198 }
199 }
200 report
201 }
202}
203
204impl Default for SkillMetrics {
205 fn default() -> Self {
206 Self::new()
207 }
208}
209
210#[cfg(test)]
211mod tests {
212 use super::*;
213
214 #[test]
215 fn test_record_created() {
216 let mut metrics = SkillMetrics::new();
217 metrics.record_created("filter_test_files".to_owned(), "python3".to_owned());
218
219 assert_eq!(metrics.total_skills, 1);
220 assert_eq!(metrics.active_skills, 1);
221 assert!(metrics.skill_stats.contains_key("filter_test_files"));
222 }
223
224 #[test]
225 fn test_record_deleted() {
226 let mut metrics = SkillMetrics::new();
227 metrics.record_created("skill1".to_owned(), "python3".to_owned());
228 metrics.record_deleted("skill1".to_owned());
229
230 assert_eq!(metrics.active_skills, 0);
231 assert!(!metrics.skill_stats.contains_key("skill1"));
232 }
233
234 #[test]
235 fn test_record_execution() {
236 let mut metrics = SkillMetrics::new();
237 metrics.record_created("analyze".to_owned(), "python3".to_owned());
238 metrics.record_execution("analyze".to_owned(), 1000, true);
239 metrics.record_execution("analyze".to_owned(), 950, true);
240
241 assert_eq!(metrics.total_executions, 2);
242 let stats = metrics.skill_stats.get("analyze").unwrap();
243 assert_eq!(stats.execution_count, 2);
244 assert_eq!(stats.success_count, 2);
245 assert_eq!(stats.total_duration_ms, 1950);
246 }
247
248 #[test]
249 fn test_reuse_ratio() {
250 let mut metrics = SkillMetrics::new();
251 metrics.record_created("skill1".to_owned(), "python3".to_owned());
252 metrics.record_created("skill2".to_owned(), "javascript".to_owned());
253 metrics.record_execution("skill1".to_owned(), 100, true);
254 metrics.record_execution("skill1".to_owned(), 100, true);
255 metrics.record_execution("skill2".to_owned(), 200, true);
256
257 assert!((metrics.reuse_ratio() - 3.0 / 2.0).abs() < f64::EPSILON);
258 }
259
260 #[test]
261 fn test_success_rate() {
262 let mut metrics = SkillMetrics::new();
263 metrics.record_created("test".to_owned(), "python3".to_owned());
264 metrics.record_execution("test".to_owned(), 100, true);
265 metrics.record_execution("test".to_owned(), 100, true);
266 metrics.record_execution("test".to_owned(), 100, false);
267
268 let success_rate = metrics.get_skill_success_rate("test");
269 assert!((success_rate - 2.0 / 3.0).abs() < 0.01);
270 }
271
272 #[test]
273 fn test_avg_duration() {
274 let mut metrics = SkillMetrics::new();
275 metrics.record_created("perf".to_owned(), "javascript".to_owned());
276 metrics.record_execution("perf".to_owned(), 500, true);
277 metrics.record_execution("perf".to_owned(), 600, true);
278 metrics.record_execution("perf".to_owned(), 400, true);
279
280 let avg = metrics.get_skill_avg_duration("perf");
281 assert_eq!(avg, 500);
282 }
283
284 #[test]
285 fn test_underutilized_skills() {
286 let mut metrics = SkillMetrics::new();
287 metrics.record_created("popular".to_owned(), "python3".to_owned());
288 metrics.record_created("unpopular".to_owned(), "python3".to_owned());
289
290 for _ in 0..10 {
291 metrics.record_execution("popular".to_owned(), 100, true);
292 }
293 metrics.record_execution("unpopular".to_owned(), 100, true);
294
295 let underutilized = metrics.get_underutilized_skills(0.5);
296 assert!(underutilized.contains(&"unpopular".to_owned()));
297 }
298
299 #[test]
300 fn test_record_created_is_idempotent_and_preserves_history() {
301 let mut metrics = SkillMetrics::new();
302 metrics.record_created("alpha".to_owned(), "agent_skill".to_owned());
303 metrics.record_execution("alpha".to_owned(), 100, true);
304
305 metrics.record_created("alpha".to_owned(), "agent_skill".to_owned());
306
307 assert_eq!(metrics.total_skills, 1);
308 assert_eq!(metrics.active_skills, 1);
309 let stats = metrics.skill_stats.get("alpha").unwrap();
310 assert_eq!(stats.execution_count, 1);
311 assert_eq!(stats.success_count, 1);
312 }
313
314 #[test]
315 fn test_doctor_report_empty_state() {
316 let report = SkillMetrics::new().doctor_report();
317
318 assert_eq!(report, "No skills tracked yet this session.");
319 }
320
321 #[test]
322 fn test_doctor_report_flags_quiet_skill_and_keeps_busy_one() {
323 let mut metrics = SkillMetrics::new();
324 metrics.record_created("busy".to_owned(), "agent_skill".to_owned());
325 metrics.record_created("quiet".to_owned(), "built_in".to_owned());
326 for _ in 0..10 {
327 metrics.record_execution("busy".to_owned(), 100, true);
328 }
329 metrics.record_execution("busy".to_owned(), 100, false);
330 metrics.record_execution("quiet".to_owned(), 50, true);
331
332 let report = metrics.doctor_report();
333
334 assert!(report.contains("2 active"), "{report}");
335 assert!(report.contains("12 executions"), "{report}");
336 let busy_pos = report.find("busy | agent_skill | 11 | 91% | 100 |").expect("busy row");
339 let quiet_pos = report.find("quiet | built_in | 1 | 100% | 50 |").expect("quiet row");
340 assert!(busy_pos < quiet_pos, "rows sorted by name:\n{report}");
341 assert!(report.contains("- quiet (1 execs)"), "{report}");
342 assert!(!report.contains("- busy ("), "{report}");
343 }
344
345 #[test]
346 fn test_doctor_report_without_executions_names_no_candidates() {
347 let mut metrics = SkillMetrics::new();
348 metrics.record_created("idle".to_owned(), "agent_skill".to_owned());
349
350 let report = metrics.doctor_report();
351
352 assert!(report.contains("idle | agent_skill | 0 | 0% | 0 |"), "{report}");
353 assert!(report.contains("Underutilized: none."), "{report}");
354 }
355}