use crate::types::Confidence;
use crate::usage::{SkillUsageEvent, UsageAnalytics};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use tracing::{debug, trace};
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum SkillCategory {
Testing,
Debugging,
Documentation,
Refactoring,
Performance,
Security,
#[default]
General,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct OutcomeMetrics {
pub session_duration_ms: Option<f64>,
pub retry_rate: Option<f64>,
pub success_indicators: Vec<String>,
pub failure_indicators: Vec<String>,
pub sessions_analyzed: usize,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExpectedOutcome {
pub category: SkillCategory,
pub baseline_metrics: OutcomeMetrics,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DeviationEvidence {
pub sessions_analyzed: usize,
pub actual_metrics: OutcomeMetrics,
pub expected_metrics: OutcomeMetrics,
pub deviations: Vec<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DeviationScore {
pub skill_uri: String,
pub deviation: f64,
pub confidence: Confidence,
pub evidence: DeviationEvidence,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EffectivenessMetric {
pub skill_uri: String,
pub with_skill_outcomes: OutcomeMetrics,
pub without_skill_outcomes: OutcomeMetrics,
pub improvement_factor: f64,
}
const TESTING_KEYWORDS: &[&str] = &[
"test", "testing", "tdd", "bdd", "coverage", "spec", "assert", "mock", "pytest", "jest",
];
const DEBUGGING_KEYWORDS: &[&str] = &[
"debug",
"debugging",
"troubleshoot",
"diagnose",
"fix",
"error",
"bug",
"trace",
];
const DOCUMENTATION_KEYWORDS: &[&str] = &[
"doc",
"docs",
"documentation",
"readme",
"comment",
"explain",
"guide",
"tutorial",
];
const REFACTORING_KEYWORDS: &[&str] = &[
"refactor",
"refactoring",
"clean",
"cleanup",
"simplify",
"restructure",
"rename",
];
const PERFORMANCE_KEYWORDS: &[&str] = &[
"perf",
"performance",
"optimize",
"optimization",
"fast",
"speed",
"benchmark",
"cache",
];
const SECURITY_KEYWORDS: &[&str] = &[
"security",
"secure",
"auth",
"authentication",
"vulnerability",
"audit",
"penetration",
];
pub fn infer_skill_category(skill_name: &str) -> SkillCategory {
let lower = skill_name.to_lowercase();
for kw in TESTING_KEYWORDS {
if lower.contains(kw) {
return SkillCategory::Testing;
}
}
for kw in DEBUGGING_KEYWORDS {
if lower.contains(kw) {
return SkillCategory::Debugging;
}
}
for kw in DOCUMENTATION_KEYWORDS {
if lower.contains(kw) {
return SkillCategory::Documentation;
}
}
for kw in REFACTORING_KEYWORDS {
if lower.contains(kw) {
return SkillCategory::Refactoring;
}
}
for kw in PERFORMANCE_KEYWORDS {
if lower.contains(kw) {
return SkillCategory::Performance;
}
}
for kw in SECURITY_KEYWORDS {
if lower.contains(kw) {
return SkillCategory::Security;
}
}
SkillCategory::General
}
pub fn get_baseline_expectations(category: SkillCategory) -> ExpectedOutcome {
let baseline_metrics = match category {
SkillCategory::Testing => OutcomeMetrics {
session_duration_ms: Some(120_000.0), retry_rate: Some(0.15), success_indicators: vec![
"tests pass".to_string(),
"coverage".to_string(),
"assertions".to_string(),
"green".to_string(),
],
failure_indicators: vec![
"tests fail".to_string(),
"timeout".to_string(),
"assertion failed".to_string(),
],
sessions_analyzed: 0,
},
SkillCategory::Debugging => OutcomeMetrics {
session_duration_ms: Some(300_000.0), retry_rate: Some(0.25), success_indicators: vec![
"fixed".to_string(),
"resolved".to_string(),
"working".to_string(),
"found the issue".to_string(),
],
failure_indicators: vec![
"still broken".to_string(),
"error persists".to_string(),
"crash".to_string(),
],
sessions_analyzed: 0,
},
SkillCategory::Documentation => OutcomeMetrics {
session_duration_ms: Some(180_000.0), retry_rate: Some(0.10), success_indicators: vec![
"documented".to_string(),
"examples".to_string(),
"clear".to_string(),
],
failure_indicators: vec![
"unclear".to_string(),
"missing".to_string(),
"incomplete".to_string(),
],
sessions_analyzed: 0,
},
SkillCategory::Refactoring => OutcomeMetrics {
session_duration_ms: Some(240_000.0), retry_rate: Some(0.20), success_indicators: vec![
"cleaner".to_string(),
"simplified".to_string(),
"improved".to_string(),
],
failure_indicators: vec![
"broke".to_string(),
"regression".to_string(),
"more complex".to_string(),
],
sessions_analyzed: 0,
},
SkillCategory::Performance => OutcomeMetrics {
session_duration_ms: Some(360_000.0), retry_rate: Some(0.30), success_indicators: vec![
"faster".to_string(),
"optimized".to_string(),
"benchmark".to_string(),
"improved".to_string(),
],
failure_indicators: vec![
"slower".to_string(),
"regression".to_string(),
"timeout".to_string(),
],
sessions_analyzed: 0,
},
SkillCategory::Security => OutcomeMetrics {
session_duration_ms: Some(300_000.0), retry_rate: Some(0.20), success_indicators: vec![
"secure".to_string(),
"patched".to_string(),
"vulnerability fixed".to_string(),
],
failure_indicators: vec![
"vulnerable".to_string(),
"exploit".to_string(),
"insecure".to_string(),
],
sessions_analyzed: 0,
},
SkillCategory::General => OutcomeMetrics {
session_duration_ms: None, retry_rate: None, success_indicators: vec![],
failure_indicators: vec![],
sessions_analyzed: 0,
},
};
ExpectedOutcome {
category,
baseline_metrics,
}
}
const MIN_SESSIONS_FOR_DEVIATION: usize = 3;
pub fn compute_deviation_score(
skill_uri: &str,
analytics: &UsageAnalytics,
session_events: &[SkillUsageEvent],
) -> Option<DeviationScore> {
let skill_events: Vec<_> = session_events
.iter()
.filter(|e| e.skill_path == skill_uri)
.collect();
if skill_events.len() < MIN_SESSIONS_FOR_DEVIATION {
debug!(
skill_uri,
events = skill_events.len(),
min_required = MIN_SESSIONS_FOR_DEVIATION,
"Insufficient data for deviation scoring"
);
return None;
}
let category = infer_skill_category(skill_uri);
let expected = get_baseline_expectations(category);
let actual_metrics = compute_actual_metrics(&skill_events, analytics);
let mut deviation_components = Vec::new();
let mut total_deviation = 0.0;
let mut component_count = 0;
if let (Some(expected_duration), Some(actual_duration)) = (
expected.baseline_metrics.session_duration_ms,
actual_metrics.session_duration_ms,
) {
let duration_ratio = actual_duration / expected_duration;
let duration_deviation = if duration_ratio > 2.0 {
-0.3 } else if duration_ratio < 0.3 {
-0.2 } else {
0.1 };
deviation_components.push(format!(
"Duration ratio: {:.2}x expected (deviation: {:.2})",
duration_ratio, duration_deviation
));
total_deviation += duration_deviation;
component_count += 1;
}
if let (Some(expected_retry), Some(actual_retry)) = (
expected.baseline_metrics.retry_rate,
actual_metrics.retry_rate,
) {
let retry_deviation = expected_retry - actual_retry; deviation_components.push(format!(
"Retry rate: {:.1}% (expected {:.1}%, deviation: {:.2})",
actual_retry * 100.0,
expected_retry * 100.0,
retry_deviation
));
total_deviation += retry_deviation;
component_count += 1;
}
let success_matches = count_keyword_matches(
&actual_metrics.success_indicators,
&expected.baseline_metrics.success_indicators,
);
let failure_matches = count_keyword_matches(
&actual_metrics.failure_indicators,
&expected.baseline_metrics.failure_indicators,
);
if !expected.baseline_metrics.success_indicators.is_empty() {
let keyword_deviation =
((success_matches as f64 * 0.1) - (failure_matches as f64 * 0.15)).clamp(-1.0, 1.0);
deviation_components.push(format!(
"Keywords: {} success, {} failure (deviation: {:.2})",
success_matches, failure_matches, keyword_deviation
));
total_deviation += keyword_deviation;
component_count += 1;
}
let normalized_deviation = if component_count > 0 {
(total_deviation / component_count as f64).clamp(-1.0, 1.0)
} else {
0.0
};
let confidence = Confidence::new((skill_events.len() as f64 / 20.0).min(1.0));
Some(DeviationScore {
skill_uri: skill_uri.to_string(),
deviation: normalized_deviation,
confidence,
evidence: DeviationEvidence {
sessions_analyzed: skill_events.len(),
actual_metrics,
expected_metrics: expected.baseline_metrics,
deviations: deviation_components,
},
})
}
fn compute_actual_metrics(
events: &[&SkillUsageEvent],
_analytics: &UsageAnalytics, ) -> OutcomeMetrics {
if events.is_empty() {
trace!("No events provided for metrics computation");
return OutcomeMetrics::default();
}
let mut session_durations: HashMap<&str, (u64, u64)> = HashMap::new();
for event in events {
let entry = session_durations
.entry(&event.session_id)
.or_insert((u64::MAX, 0));
entry.0 = entry.0.min(event.timestamp);
entry.1 = entry.1.max(event.timestamp);
}
let avg_duration_ms: f64 = if !session_durations.is_empty() {
session_durations
.values()
.map(|(start, end)| (end.saturating_sub(*start) * 1000) as f64)
.sum::<f64>()
/ session_durations.len() as f64
} else {
0.0
};
let total_events = events.len();
let unique_sessions = session_durations.len();
let events_per_session = total_events as f64 / unique_sessions.max(1) as f64;
let retry_rate = ((events_per_session - 1.0) / 5.0).clamp(0.0, 1.0);
let mut success_indicators = Vec::new();
let mut failure_indicators = Vec::new();
for event in events {
if let Some(ref context) = event.prompt_context {
let lower = context.to_lowercase();
if lower.contains("success")
|| lower.contains("pass")
|| lower.contains("working")
|| lower.contains("fixed")
{
success_indicators.push(context.chars().take(50).collect());
}
if lower.contains("error")
|| lower.contains("fail")
|| lower.contains("broken")
|| lower.contains("crash")
{
failure_indicators.push(context.chars().take(50).collect());
}
}
}
OutcomeMetrics {
session_duration_ms: Some(avg_duration_ms),
retry_rate: Some(retry_rate),
success_indicators,
failure_indicators,
sessions_analyzed: unique_sessions,
}
}
fn count_keyword_matches(actual: &[String], expected: &[String]) -> usize {
let mut matches = 0;
for actual_kw in actual {
let lower = actual_kw.to_lowercase();
for expected_kw in expected {
if lower.contains(&expected_kw.to_lowercase()) {
matches += 1;
break;
}
}
}
matches
}
const MIN_SESSIONS_FOR_EFFECTIVENESS: usize = 5;
pub fn compute_effectiveness(
skill_uri: &str,
analytics: &UsageAnalytics,
session_events: &[SkillUsageEvent],
) -> Option<EffectivenessMetric> {
let skill_sessions: std::collections::HashSet<_> = session_events
.iter()
.filter(|e| e.skill_path == skill_uri)
.map(|e| e.session_id.as_str())
.collect();
let all_sessions: std::collections::HashSet<_> = session_events
.iter()
.map(|e| e.session_id.as_str())
.collect();
let without_skill_sessions: Vec<_> =
all_sessions.difference(&skill_sessions).cloned().collect();
if skill_sessions.len() < MIN_SESSIONS_FOR_EFFECTIVENESS
|| without_skill_sessions.len() < MIN_SESSIONS_FOR_EFFECTIVENESS
{
debug!(
skill_uri,
with_skill = skill_sessions.len(),
without_skill = without_skill_sessions.len(),
min_required = MIN_SESSIONS_FOR_EFFECTIVENESS,
"Insufficient sessions for effectiveness comparison"
);
return None;
}
let with_skill_events: Vec<_> = session_events
.iter()
.filter(|e| skill_sessions.contains(e.session_id.as_str()))
.collect();
let without_skill_events: Vec<_> = session_events
.iter()
.filter(|e| without_skill_sessions.contains(&e.session_id.as_str()))
.collect();
let with_skill_metrics = compute_actual_metrics(&with_skill_events, analytics);
let without_skill_metrics = compute_actual_metrics(&without_skill_events, analytics);
let improvement_factor = if let (Some(with_retry), Some(without_retry)) = (
with_skill_metrics.retry_rate,
without_skill_metrics.retry_rate,
) {
if with_retry > 0.0 && without_retry > 0.001 {
without_retry / with_retry
} else if with_retry > 0.0 {
0.5
} else {
1.5
}
} else {
trace!(
skill_uri,
"No retry rate data available, using neutral improvement factor"
);
1.0 };
Some(EffectivenessMetric {
skill_uri: skill_uri.to_string(),
with_skill_outcomes: with_skill_metrics,
without_skill_outcomes: without_skill_metrics,
improvement_factor: improvement_factor.clamp(0.1, 10.0),
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_infer_skill_category_testing() {
assert_eq!(
infer_skill_category("pytest-helper"),
SkillCategory::Testing
);
assert_eq!(infer_skill_category("tdd-workflow"), SkillCategory::Testing);
assert_eq!(
infer_skill_category("unit-test-generator"),
SkillCategory::Testing
);
}
#[test]
fn test_infer_skill_category_debugging() {
assert_eq!(
infer_skill_category("debug-assistant"),
SkillCategory::Debugging
);
assert_eq!(
infer_skill_category("troubleshoot-errors"),
SkillCategory::Debugging
);
}
#[test]
fn test_infer_skill_category_general() {
assert_eq!(
infer_skill_category("random-helper"),
SkillCategory::General
);
assert_eq!(infer_skill_category("my-skill"), SkillCategory::General);
}
#[test]
fn test_get_baseline_expectations() {
let testing_baseline = get_baseline_expectations(SkillCategory::Testing);
assert_eq!(testing_baseline.category, SkillCategory::Testing);
assert!(testing_baseline
.baseline_metrics
.session_duration_ms
.is_some());
assert!(testing_baseline.baseline_metrics.retry_rate.is_some());
assert!(!testing_baseline
.baseline_metrics
.success_indicators
.is_empty());
let general_baseline = get_baseline_expectations(SkillCategory::General);
assert_eq!(general_baseline.category, SkillCategory::General);
assert!(general_baseline
.baseline_metrics
.session_duration_ms
.is_none());
}
#[test]
fn test_count_keyword_matches() {
let actual = vec!["tests pass".to_string(), "all working".to_string()];
let expected = vec![
"pass".to_string(),
"working".to_string(),
"green".to_string(),
];
assert_eq!(count_keyword_matches(&actual, &expected), 2);
}
#[test]
fn test_compute_deviation_score_insufficient_data() {
let analytics = UsageAnalytics::default();
let events = vec![SkillUsageEvent {
timestamp: 1000,
skill_path: "test-skill".to_string(),
session_id: "s1".to_string(),
prompt_context: None,
}];
let result = compute_deviation_score("test-skill", &analytics, &events);
assert!(result.is_none()); }
#[test]
fn test_compute_deviation_score_with_data() {
let analytics = UsageAnalytics::default();
let events = vec![
SkillUsageEvent {
timestamp: 1000,
skill_path: "pytest-helper".to_string(),
session_id: "s1".to_string(),
prompt_context: Some("run tests".to_string()),
},
SkillUsageEvent {
timestamp: 2000,
skill_path: "pytest-helper".to_string(),
session_id: "s2".to_string(),
prompt_context: Some("tests pass!".to_string()),
},
SkillUsageEvent {
timestamp: 3000,
skill_path: "pytest-helper".to_string(),
session_id: "s3".to_string(),
prompt_context: Some("all tests passing".to_string()),
},
];
let result = compute_deviation_score("pytest-helper", &analytics, &events);
assert!(result.is_some());
let score = result.unwrap();
assert_eq!(score.skill_uri, "pytest-helper");
assert!(score.confidence.value() > 0.0);
assert!(score.deviation >= -1.0 && score.deviation <= 1.0);
}
#[test]
fn test_compute_effectiveness_insufficient_data() {
let analytics = UsageAnalytics::default();
let events = vec![
SkillUsageEvent {
timestamp: 1000,
skill_path: "my-skill".to_string(),
session_id: "s1".to_string(),
prompt_context: None,
},
SkillUsageEvent {
timestamp: 2000,
skill_path: "other-skill".to_string(),
session_id: "s2".to_string(),
prompt_context: None,
},
];
let result = compute_effectiveness("my-skill", &analytics, &events);
assert!(result.is_none()); }
#[test]
fn test_deviation_score_clamps_to_valid_range() {
let analytics = UsageAnalytics::default();
let events: Vec<_> = (0..10)
.map(|i| SkillUsageEvent {
timestamp: 1000 + i * 100,
skill_path: "pytest-helper".to_string(),
session_id: format!("s{}", i),
prompt_context: Some("error error error fail crash broken".to_string()),
})
.collect();
let result = compute_deviation_score("pytest-helper", &analytics, &events);
assert!(result.is_some());
let score = result.unwrap();
assert!(
score.deviation >= -1.0 && score.deviation <= 1.0,
"Deviation {} should be in [-1.0, 1.0]",
score.deviation
);
}
#[test]
fn test_deviation_score_positive_for_success() {
let analytics = UsageAnalytics::default();
let events: Vec<_> = (0..5)
.map(|i| SkillUsageEvent {
timestamp: 1000 + i * 100,
skill_path: "pytest-helper".to_string(),
session_id: format!("s{}", i),
prompt_context: Some("tests pass! all working correctly".to_string()),
})
.collect();
let result = compute_deviation_score("pytest-helper", &analytics, &events);
assert!(result.is_some());
let score = result.unwrap();
assert!(
!score.evidence.actual_metrics.success_indicators.is_empty(),
"Should detect success indicators"
);
}
#[test]
fn test_deviation_score_confidence_scales_with_samples() {
let analytics = UsageAnalytics::default();
let small_events: Vec<_> = (0..3)
.map(|i| SkillUsageEvent {
timestamp: 1000 + i * 100,
skill_path: "test-skill".to_string(),
session_id: format!("s{}", i),
prompt_context: None,
})
.collect();
let small_result = compute_deviation_score("test-skill", &analytics, &small_events);
assert!(small_result.is_some());
let small_confidence = small_result.unwrap().confidence.value();
let large_events: Vec<_> = (0..20)
.map(|i| SkillUsageEvent {
timestamp: 1000 + i * 100,
skill_path: "test-skill".to_string(),
session_id: format!("s{}", i),
prompt_context: None,
})
.collect();
let large_result = compute_deviation_score("test-skill", &analytics, &large_events);
assert!(large_result.is_some());
let large_confidence = large_result.unwrap().confidence.value();
assert!(
large_confidence >= small_confidence,
"Larger sample ({}) should have >= confidence than smaller sample ({})",
large_confidence,
small_confidence
);
}
#[test]
fn test_deviation_score_at_minimum_sessions() {
let analytics = UsageAnalytics::default();
let events: Vec<_> = (0..MIN_SESSIONS_FOR_DEVIATION)
.map(|i| SkillUsageEvent {
timestamp: 1000 + i as u64 * 100,
skill_path: "edge-skill".to_string(),
session_id: format!("s{}", i),
prompt_context: None,
})
.collect();
let result = compute_deviation_score("edge-skill", &analytics, &events);
assert!(
result.is_some(),
"Should compute score at exactly minimum sessions"
);
}
#[test]
fn test_deviation_score_below_minimum_sessions() {
let analytics = UsageAnalytics::default();
let events: Vec<_> = (0..MIN_SESSIONS_FOR_DEVIATION - 1)
.map(|i| SkillUsageEvent {
timestamp: 1000 + i as u64 * 100,
skill_path: "edge-skill".to_string(),
session_id: format!("s{}", i),
prompt_context: None,
})
.collect();
let result = compute_deviation_score("edge-skill", &analytics, &events);
assert!(
result.is_none(),
"Should return None below minimum sessions"
);
}
#[test]
fn test_deviation_with_general_category_no_expectations() {
let analytics = UsageAnalytics::default();
let events: Vec<_> = (0..5)
.map(|i| SkillUsageEvent {
timestamp: 1000 + i * 100,
skill_path: "random-helper-tool".to_string(),
session_id: format!("s{}", i),
prompt_context: Some("working on task".to_string()),
})
.collect();
let result = compute_deviation_score("random-helper-tool", &analytics, &events);
assert!(result.is_some());
let score = result.unwrap();
assert!(score.deviation >= -1.0 && score.deviation <= 1.0);
}
}