skrills-intelligence 0.8.2

Intelligent skill recommendations based on usage patterns and project context.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
//! Comparative evaluation for skill effectiveness and deviation scoring.
//!
//! This module compares actual skill-assisted work against expected outcomes
//! to identify underperforming skills and highlight proven effective ones.

use crate::types::Confidence;
use crate::usage::{SkillUsageEvent, UsageAnalytics};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use tracing::{debug, trace};

// ============================================================================
// Skill Categories and Expected Outcomes
// ============================================================================

/// Functional category of a skill.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum SkillCategory {
    /// Testing-related skills (test generation, coverage, assertions).
    Testing,
    /// Debugging and troubleshooting skills.
    Debugging,
    /// Documentation and explanation skills.
    Documentation,
    /// Code refactoring and cleanup skills.
    Refactoring,
    /// Performance optimization skills.
    Performance,
    /// Security-focused skills.
    Security,
    /// General-purpose skills with no specific expectations.
    #[default]
    General,
}

/// Metrics used to measure session outcomes.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct OutcomeMetrics {
    /// Expected/actual session duration in milliseconds.
    pub session_duration_ms: Option<f64>,
    /// Expected/actual retry or error rate (0.0 - 1.0).
    pub retry_rate: Option<f64>,
    /// Keywords indicating success.
    pub success_indicators: Vec<String>,
    /// Keywords indicating failure.
    pub failure_indicators: Vec<String>,
    /// Number of sessions this metric is based on.
    pub sessions_analyzed: usize,
}

/// Expected outcomes for a skill category.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExpectedOutcome {
    /// The skill category.
    pub category: SkillCategory,
    /// Baseline metrics for this category.
    pub baseline_metrics: OutcomeMetrics,
}

// ============================================================================
// Deviation and Effectiveness Scoring
// ============================================================================

/// Evidence supporting a deviation score.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DeviationEvidence {
    /// Number of sessions analyzed.
    pub sessions_analyzed: usize,
    /// Actual observed metrics.
    pub actual_metrics: OutcomeMetrics,
    /// Expected baseline metrics.
    pub expected_metrics: OutcomeMetrics,
    /// Specific deviations detected.
    pub deviations: Vec<String>,
}

/// Deviation score comparing actual vs expected outcomes.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DeviationScore {
    /// Skill URI being evaluated.
    pub skill_uri: String,
    /// Deviation value (-1.0 to 1.0, negative = worse than expected).
    pub deviation: f64,
    /// Confidence in the measurement (0.0 - 1.0).
    pub confidence: Confidence,
    /// Evidence supporting this score.
    pub evidence: DeviationEvidence,
}

/// Effectiveness metric comparing skill-assisted vs non-skill sessions.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EffectivenessMetric {
    /// Skill URI being evaluated.
    pub skill_uri: String,
    /// Outcomes from sessions that used this skill.
    pub with_skill_outcomes: OutcomeMetrics,
    /// Outcomes from comparable sessions without this skill.
    pub without_skill_outcomes: OutcomeMetrics,
    /// Improvement factor (> 1.0 = improvement, < 1.0 = regression).
    pub improvement_factor: f64,
}

// ============================================================================
// Category Inference
// ============================================================================

/// Keywords used to infer skill categories.
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",
];

/// Infer the skill category from the skill name/path.
pub fn infer_skill_category(skill_name: &str) -> SkillCategory {
    let lower = skill_name.to_lowercase();

    // Check each category's keywords
    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
}

/// Get baseline expected outcomes for a skill category.
pub fn get_baseline_expectations(category: SkillCategory) -> ExpectedOutcome {
    let baseline_metrics = match category {
        SkillCategory::Testing => OutcomeMetrics {
            session_duration_ms: Some(120_000.0), // 2 minutes
            retry_rate: Some(0.15),               // 15% retry rate
            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), // 5 minutes
            retry_rate: Some(0.25),               // 25% retry rate
            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), // 3 minutes
            retry_rate: Some(0.10),               // 10% retry rate
            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), // 4 minutes
            retry_rate: Some(0.20),               // 20% retry rate
            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), // 6 minutes
            retry_rate: Some(0.30),               // 30% retry rate
            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), // 5 minutes
            retry_rate: Some(0.20),               // 20% retry rate
            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, // No expectation
            retry_rate: None,          // No expectation
            success_indicators: vec![],
            failure_indicators: vec![],
            sessions_analyzed: 0,
        },
    };

    ExpectedOutcome {
        category,
        baseline_metrics,
    }
}

// ============================================================================
// Deviation Computation
// ============================================================================

/// Minimum sessions required for reliable deviation scoring.
const MIN_SESSIONS_FOR_DEVIATION: usize = 3;

/// Compute deviation score for a skill based on usage analytics.
pub fn compute_deviation_score(
    skill_uri: &str,
    analytics: &UsageAnalytics,
    session_events: &[SkillUsageEvent],
) -> Option<DeviationScore> {
    // Filter events for this skill
    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;
    }

    // Infer category and get baseline
    let category = infer_skill_category(skill_uri);
    let expected = get_baseline_expectations(category);

    // Compute actual metrics from events
    let actual_metrics = compute_actual_metrics(&skill_events, analytics);

    // Calculate deviation components
    let mut deviation_components = Vec::new();
    let mut total_deviation = 0.0;
    let mut component_count = 0;

    // Duration deviation
    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;
        // Longer than expected is slightly negative, much shorter is concerning
        let duration_deviation = if duration_ratio > 2.0 {
            -0.3 // Taking too long
        } else if duration_ratio < 0.3 {
            -0.2 // Suspiciously fast (might be abandoned)
        } else {
            0.1 // Within expected range
        };

        deviation_components.push(format!(
            "Duration ratio: {:.2}x expected (deviation: {:.2})",
            duration_ratio, duration_deviation
        ));
        total_deviation += duration_deviation;
        component_count += 1;
    }

    // Retry rate deviation
    if let (Some(expected_retry), Some(actual_retry)) = (
        expected.baseline_metrics.retry_rate,
        actual_metrics.retry_rate,
    ) {
        let retry_deviation = expected_retry - actual_retry; // Lower retry = positive
        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;
    }

    // Keyword matching
    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;
    }

    // Normalize deviation to [-1.0, 1.0]
    let normalized_deviation = if component_count > 0 {
        (total_deviation / component_count as f64).clamp(-1.0, 1.0)
    } else {
        0.0
    };

    // Calculate confidence based on sample size
    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,
        },
    })
}

/// Compute actual metrics from skill usage events.
fn compute_actual_metrics(
    events: &[&SkillUsageEvent],
    _analytics: &UsageAnalytics, // Reserved for future behavioral analysis integration
) -> OutcomeMetrics {
    if events.is_empty() {
        trace!("No events provided for metrics computation");
        return OutcomeMetrics::default();
    }

    // Group by session and calculate duration
    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
    };

    // Estimate retry rate from frequency (higher frequency in same session = retries)
    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);

    // Collect keywords from prompt contexts
    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();
            // Check for common success/failure patterns
            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,
    }
}

/// Count how many keywords from `actual` match keywords in `expected`.
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
}

// ============================================================================
// Effectiveness Computation
// ============================================================================

/// Minimum sessions required for effectiveness comparison.
const MIN_SESSIONS_FOR_EFFECTIVENESS: usize = 5;

/// Compute effectiveness by comparing sessions with and without this skill.
pub fn compute_effectiveness(
    skill_uri: &str,
    analytics: &UsageAnalytics,
    session_events: &[SkillUsageEvent],
) -> Option<EffectivenessMetric> {
    // Collect sessions that used this skill
    let skill_sessions: std::collections::HashSet<_> = session_events
        .iter()
        .filter(|e| e.skill_path == skill_uri)
        .map(|e| e.session_id.as_str())
        .collect();

    // Collect all sessions
    let all_sessions: std::collections::HashSet<_> = session_events
        .iter()
        .map(|e| e.session_id.as_str())
        .collect();

    // Sessions without this skill
    let without_skill_sessions: Vec<_> =
        all_sessions.difference(&skill_sessions).cloned().collect();

    // Need minimum samples for both groups
    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;
    }

    // Get events for each group
    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();

    // Compute metrics for each group
    let with_skill_metrics = compute_actual_metrics(&with_skill_events, analytics);
    let without_skill_metrics = compute_actual_metrics(&without_skill_events, analytics);

    // Calculate improvement factor
    // Lower retry rate is better, so invert the comparison
    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 {
            // Both have retries - calculate ratio (higher = better)
            without_retry / with_retry
        } else if with_retry > 0.0 {
            // Baseline has no retries but skill introduces some - slight negative
            0.5
        } else {
            // No retries with skill = good improvement
            1.5
        }
    } else {
        trace!(
            skill_uri,
            "No retry rate data available, using neutral improvement factor"
        );
        1.0 // No data, assume neutral
    };

    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),
    })
}

// ============================================================================
// Tests
// ============================================================================

#[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()); // Only 1 event, need at least 3
    }

    #[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()); // Not enough sessions in either group
    }

    // ========================================================================
    // TC-5: Deviation score boundary conditions
    // ========================================================================

    #[test]
    fn test_deviation_score_clamps_to_valid_range() {
        let analytics = UsageAnalytics::default();
        // Create many events with extreme failure indicators
        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();
        // Deviation must be clamped to [-1.0, 1.0]
        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();
        // Create events with success indicators
        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();
        // Should have some success keywords matching
        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();

        // Small sample (just above minimum)
        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();

        // Larger sample
        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();

        // Larger sample should have higher confidence
        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();
        // Exactly MIN_SESSIONS_FOR_DEVIATION (3) events
        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();
        // Exactly MIN_SESSIONS_FOR_DEVIATION - 1 events
        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();
        // Use a skill name that maps to General category (no baseline expectations)
        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();
        // General category has no success/failure indicators, so keyword deviation should be 0
        // Deviation should still be in valid range
        assert!(score.deviation >= -1.0 && score.deviation <= 1.0);
    }
}