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
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
//! Behavioral analysis of session tool sequences, file access patterns, and outcomes.
//!
//! This module extends the basic skill usage tracking with rich behavioral data:
//! - Tool call sequences within sessions (not just skill invocations)
//! - File access patterns (Read/Write/Edit operations)
//! - Session outcome detection (success/failure/partial)

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

// ============================================================================
// Helper Functions
// ============================================================================

/// Truncate a string safely at UTF-8 character boundaries.
fn safe_truncate(s: &str, max_len: usize) -> String {
    if s.len() <= max_len {
        s.to_string()
    } else {
        let mut end = max_len.saturating_sub(3); // Leave room for "..."
        while !s.is_char_boundary(end) && end > 0 {
            end -= 1;
        }
        format!("{}...", &s[..end])
    }
}

// ============================================================================
// Core Data Structures
// ============================================================================

/// Status of a tool execution.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub enum ToolStatus {
    /// Tool executed successfully.
    Success,
    /// Tool execution resulted in an error.
    Error { message: String },
    /// Tool partially succeeded.
    Partial,
    /// Status could not be determined.
    #[default]
    Unknown,
}

/// A single tool call within a session.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolCall {
    /// Tool name (e.g., "Read", "Write", "Bash", "Skill").
    pub name: String,
    /// Unix timestamp of the call.
    pub timestamp: u64,
    /// Truncated summary of input parameters (max 200 chars).
    pub input_summary: String,
    /// Execution status.
    pub status: ToolStatus,
}

/// Type of file operation.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum FileOperation {
    /// File was read.
    Read,
    /// File was written/created.
    Write,
    /// File was edited (partial modification).
    Edit {
        /// Optional line range affected.
        line_range: Option<(u64, u64)>,
    },
}

/// A file access event within a session.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileAccess {
    /// File path (relative when possible, truncated to 200 chars).
    pub path: String,
    /// Type of operation performed.
    pub operation: FileOperation,
    /// Unix timestamp of the access.
    pub timestamp: u64,
    /// Truncated prompt context that led to this access.
    pub context: Option<String>,
}

/// Status of a session outcome.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub enum OutcomeStatus {
    /// Task completed successfully (no errors, tests pass, etc.).
    Success,
    /// Task failed (errors, crashes, abandoned).
    Failure,
    /// Mixed results (some progress, some issues).
    Partial,
    /// Insufficient data to determine outcome.
    #[default]
    Inconclusive,
}

/// Analysis of a session's outcome.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionOutcome {
    /// Session identifier.
    pub session_id: String,
    /// Detected outcome status.
    pub status: OutcomeStatus,
    /// Confidence in the outcome detection (0.0 - 1.0).
    pub confidence: Confidence,
    /// Evidence supporting the outcome determination.
    pub evidence: Vec<String>,
    /// Session duration in seconds.
    pub duration_seconds: u64,
}

/// Enriched event combining skill usage with behavioral context.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BehavioralEvent {
    /// Original skill usage event.
    pub skill_usage: SkillUsageEventData,
    /// Sequence of tool calls in this session context.
    pub tool_sequence: Vec<ToolCall>,
    /// Files accessed during this session.
    pub files_accessed: Vec<FileAccess>,
    /// Session outcome if determinable.
    pub session_outcome: Option<SessionOutcome>,
}

/// Serializable version of SkillUsageEvent.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SkillUsageEventData {
    pub timestamp: u64,
    pub skill_path: String,
    pub session_id: String,
    pub prompt_context: Option<String>,
}

impl From<&SkillUsageEvent> for SkillUsageEventData {
    fn from(event: &SkillUsageEvent) -> Self {
        Self {
            timestamp: event.timestamp,
            skill_path: event.skill_path.clone(),
            session_id: event.session_id.clone(),
            prompt_context: event.prompt_context.clone(),
        }
    }
}

// ============================================================================
// Aggregated Pattern Structures
// ============================================================================

/// Aggregated behavioral patterns across multiple sessions.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct BehavioralPatterns {
    /// Common tool sequences per skill (skill_path -> sequences).
    pub common_tool_sequences: HashMap<String, Vec<Vec<String>>>,
    /// File access patterns per skill (skill_path -> file patterns).
    pub file_access_patterns: HashMap<String, Vec<String>>,
    /// Indicators that correlate with successful sessions.
    pub success_indicators: Vec<String>,
    /// Indicators that correlate with failed sessions.
    pub failure_indicators: Vec<String>,
    /// Sessions analyzed for these patterns.
    pub sessions_analyzed: usize,
    /// Tool frequency across all sessions.
    pub tool_frequency: HashMap<String, u64>,
}

// ============================================================================
// Pattern Extraction Functions
// ============================================================================

/// Extract tool calls from raw session JSONL content.
///
/// Parses tool_use and tool_result blocks from Claude Code session format.
pub fn extract_tool_calls(session_content: &str) -> Vec<ToolCall> {
    let mut tool_calls = Vec::new();

    for line in session_content.lines() {
        if let Ok(json) = serde_json::from_str::<serde_json::Value>(line) {
            // Look for tool_use in content blocks
            if let Some(content) = json.get("content").and_then(|c| c.as_array()) {
                for block in content {
                    if block.get("type").and_then(|t| t.as_str()) == Some("tool_use") {
                        if let Some(name) = block.get("name").and_then(|n| n.as_str()) {
                            let input_summary = block
                                .get("input")
                                .map(|i| safe_truncate(&i.to_string(), 200))
                                .unwrap_or_default();

                            let timestamp =
                                json.get("timestamp").and_then(|t| t.as_u64()).unwrap_or_else(|| {
                                    trace!("timestamp missing or invalid in tool_use block, defaulting to 0");
                                    0
                                });

                            tool_calls.push(ToolCall {
                                name: name.to_string(),
                                timestamp,
                                input_summary,
                                status: ToolStatus::Unknown,
                            });
                        }
                    }
                }
            }

            // Look for tool_result to update status
            if let Some(content) = json.get("content").and_then(|c| c.as_array()) {
                for block in content {
                    if block.get("type").and_then(|t| t.as_str()) == Some("tool_result") {
                        let is_error = block
                            .get("is_error")
                            .and_then(|e| e.as_bool())
                            .unwrap_or(false);

                        // Update most recent tool call's status
                        if let Some(last_call) = tool_calls.last_mut() {
                            if last_call.status == ToolStatus::Unknown {
                                last_call.status = if is_error {
                                    let error_msg = block
                                        .get("content")
                                        .and_then(|c| c.as_str())
                                        .unwrap_or("Unknown error")
                                        .chars()
                                        .take(200)
                                        .collect();
                                    ToolStatus::Error { message: error_msg }
                                } else {
                                    ToolStatus::Success
                                };
                            }
                        }
                    }
                }
            }
        }
    }

    tool_calls
}

/// Extract file access events from tool calls.
pub fn extract_file_accesses(tool_calls: &[ToolCall]) -> Vec<FileAccess> {
    let mut accesses = Vec::new();

    for call in tool_calls {
        let operation = match call.name.as_str() {
            "Read" => Some(FileOperation::Read),
            "Write" => Some(FileOperation::Write),
            "Edit" => Some(FileOperation::Edit { line_range: None }),
            _ => None,
        };

        if let Some(op) = operation {
            // Extract file path from input summary
            if let Some(path) = extract_file_path(&call.input_summary) {
                accesses.push(FileAccess {
                    path,
                    operation: op,
                    timestamp: call.timestamp,
                    context: None,
                });
            }
        }
    }

    accesses
}

/// Extract file path from tool input summary.
fn extract_file_path(input_summary: &str) -> Option<String> {
    // Parse JSON input to find file_path parameter
    if let Ok(json) = serde_json::from_str::<serde_json::Value>(input_summary) {
        if let Some(path) = json.get("file_path").and_then(|p| p.as_str()) {
            return Some(safe_truncate(path, 200));
        }
    }
    None
}

// ============================================================================
// Session Outcome Detection
// ============================================================================

/// Keywords indicating successful completion.
const SUCCESS_KEYWORDS: &[&str] = &[
    "tests pass",
    "all tests",
    "success",
    "completed",
    "done",
    "fixed",
    "resolved",
    "working",
    "build succeeded",
    "no errors",
];

/// Keywords indicating failure.
const FAILURE_KEYWORDS: &[&str] = &[
    "error",
    "failed",
    "failure",
    "crash",
    "exception",
    "traceback",
    "panic",
    "timeout",
    "rejected",
    "broken",
    "still broken",
];

/// Detect session outcome from tool calls and context.
pub fn detect_session_outcome(
    session_id: &str,
    tool_calls: &[ToolCall],
    prompt_contexts: &[Option<String>],
) -> SessionOutcome {
    if tool_calls.is_empty() {
        trace!(
            session_id,
            "No tool calls in session, returning Inconclusive outcome"
        );
        return SessionOutcome {
            session_id: session_id.to_string(),
            status: OutcomeStatus::Inconclusive,
            confidence: Confidence::zero(),
            evidence: vec!["No tool calls in session".to_string()],
            duration_seconds: 0,
        };
    }

    let mut evidence = Vec::new();
    let mut success_signals = 0;
    let mut failure_signals = 0;

    // Analyze tool execution statuses
    let error_count = tool_calls
        .iter()
        .filter(|c| matches!(c.status, ToolStatus::Error { .. }))
        .count();
    let success_count = tool_calls
        .iter()
        .filter(|c| c.status == ToolStatus::Success)
        .count();

    if error_count > 0 {
        evidence.push(format!("{} tool errors detected", error_count));
        failure_signals += error_count;
    }
    if success_count > 0 {
        evidence.push(format!("{} successful tool calls", success_count));
        success_signals += 1;
    }

    // Check last few tool calls for indicators
    let recent_calls: Vec<_> = tool_calls.iter().rev().take(5).collect();
    let recent_errors = recent_calls
        .iter()
        .filter(|c| matches!(c.status, ToolStatus::Error { .. }))
        .count();

    if recent_errors == 0 && !recent_calls.is_empty() {
        evidence.push("No errors in final 5 tool calls".to_string());
        success_signals += 2;
    } else if recent_errors > 2 {
        evidence.push("Multiple errors in final tool calls".to_string());
        failure_signals += 2;
    }

    // Analyze prompt contexts for keywords
    for context in prompt_contexts.iter().flatten() {
        let lower = context.to_lowercase();
        for kw in SUCCESS_KEYWORDS {
            if lower.contains(kw) {
                success_signals += 1;
                evidence.push(format!("Success keyword detected: '{}'", kw));
            }
        }
        for kw in FAILURE_KEYWORDS {
            if lower.contains(kw) {
                failure_signals += 1;
                evidence.push(format!("Failure keyword detected: '{}'", kw));
            }
        }
    }

    // Check for retry patterns (same tool called repeatedly)
    let retry_count = detect_retry_pattern(tool_calls);
    if retry_count > 3 {
        evidence.push(format!(
            "Retry pattern detected: {} consecutive similar calls",
            retry_count
        ));
        failure_signals += retry_count / 2;
    }

    // Calculate duration
    let duration_seconds = if !tool_calls.is_empty() {
        let start = tool_calls.iter().map(|c| c.timestamp).min().unwrap_or(0);
        let end = tool_calls.iter().map(|c| c.timestamp).max().unwrap_or(0);
        end.saturating_sub(start)
    } else {
        0
    };

    // Duration heuristics
    if duration_seconds < 30 {
        evidence.push("Very short session (<30s)".to_string());
        failure_signals += 1; // May indicate abandoned session
    } else if duration_seconds > 60 {
        evidence.push(format!("Engaged session ({}s)", duration_seconds));
        success_signals += 1;
    }

    // Determine outcome
    let total_signals = success_signals + failure_signals;
    let (status, confidence) = if total_signals == 0 {
        (OutcomeStatus::Inconclusive, Confidence::new(0.3))
    } else {
        let success_ratio = success_signals as f64 / total_signals as f64;
        let conf_value = (total_signals as f64 / 10.0).min(1.0);

        if success_ratio > 0.7 {
            (OutcomeStatus::Success, Confidence::new(conf_value))
        } else if success_ratio < 0.3 {
            (OutcomeStatus::Failure, Confidence::new(conf_value))
        } else {
            (OutcomeStatus::Partial, Confidence::new(conf_value * 0.8))
        }
    };

    SessionOutcome {
        session_id: session_id.to_string(),
        status,
        confidence,
        evidence,
        duration_seconds,
    }
}

/// Detect retry patterns (consecutive calls to the same tool with similar inputs).
fn detect_retry_pattern(tool_calls: &[ToolCall]) -> usize {
    let mut max_consecutive = 0;
    let mut current_consecutive = 1;
    let mut prev_name: Option<&str> = None;

    for call in tool_calls {
        if Some(call.name.as_str()) == prev_name {
            current_consecutive += 1;
            max_consecutive = max_consecutive.max(current_consecutive);
        } else {
            current_consecutive = 1;
        }
        prev_name = Some(&call.name);
    }

    max_consecutive
}

// ============================================================================
// Pattern Aggregation
// ============================================================================

/// Build aggregated behavioral patterns from multiple sessions.
pub fn build_behavioral_patterns(
    events: &[BehavioralEvent],
    analytics: &UsageAnalytics,
) -> BehavioralPatterns {
    let mut common_tool_sequences: HashMap<String, Vec<Vec<String>>> = HashMap::new();
    let mut file_access_patterns: HashMap<String, Vec<String>> = HashMap::new();
    let mut success_indicators: HashSet<String> = HashSet::new();
    let mut failure_indicators: HashSet<String> = HashSet::new();
    let mut tool_frequency: HashMap<String, u64> = HashMap::new();

    for event in events {
        let skill_path = &event.skill_usage.skill_path;

        // Collect tool sequences (first 10 tools after skill invocation)
        let sequence: Vec<String> = event
            .tool_sequence
            .iter()
            .take(10)
            .map(|t| t.name.clone())
            .collect();

        if !sequence.is_empty() {
            common_tool_sequences
                .entry(skill_path.clone())
                .or_default()
                .push(sequence);
        }

        // Collect file patterns
        for access in &event.files_accessed {
            file_access_patterns
                .entry(skill_path.clone())
                .or_default()
                .push(access.path.clone());
        }

        // Collect success/failure indicators
        if let Some(ref outcome) = event.session_outcome {
            match outcome.status {
                OutcomeStatus::Success => {
                    for ev in &outcome.evidence {
                        if ev.contains("Success keyword") || ev.contains("No errors") {
                            success_indicators.insert(ev.clone());
                        }
                    }
                }
                OutcomeStatus::Failure => {
                    for ev in &outcome.evidence {
                        if ev.contains("Failure keyword") || ev.contains("error") {
                            failure_indicators.insert(ev.clone());
                        }
                    }
                }
                _ => {}
            }
        }

        // Track tool frequency
        for call in &event.tool_sequence {
            *tool_frequency.entry(call.name.clone()).or_insert(0) += 1;
        }
    }

    // Deduplicate file patterns (keep unique per skill)
    for patterns in file_access_patterns.values_mut() {
        let unique: HashSet<_> = patterns.drain(..).collect();
        *patterns = unique.into_iter().collect();
    }

    // Get sessions count from analytics
    let sessions_analyzed = analytics.sessions_analyzed;

    BehavioralPatterns {
        common_tool_sequences,
        file_access_patterns,
        success_indicators: success_indicators.into_iter().collect(),
        failure_indicators: failure_indicators.into_iter().collect(),
        sessions_analyzed,
        tool_frequency,
    }
}

/// Extract common n-grams from tool sequences.
pub fn extract_common_ngrams(
    sequences: &[Vec<String>],
    n: usize,
    min_count: usize,
) -> Vec<(Vec<String>, usize)> {
    let mut ngram_counts: HashMap<Vec<String>, usize> = HashMap::new();

    for sequence in sequences {
        if sequence.len() >= n {
            for window in sequence.windows(n) {
                *ngram_counts.entry(window.to_vec()).or_insert(0) += 1;
            }
        }
    }

    let mut common: Vec<_> = ngram_counts
        .into_iter()
        .filter(|(_, count)| *count >= min_count)
        .collect();

    common.sort_by_key(|b| std::cmp::Reverse(b.1));
    common
}

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

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_tool_status_default() {
        assert_eq!(ToolStatus::default(), ToolStatus::Unknown);
    }

    #[test]
    fn test_outcome_status_default() {
        assert_eq!(OutcomeStatus::default(), OutcomeStatus::Inconclusive);
    }

    #[test]
    fn test_extract_file_path() {
        let input = r#"{"file_path":"/home/user/project/src/main.rs"}"#;
        let path = extract_file_path(input);
        assert_eq!(path, Some("/home/user/project/src/main.rs".to_string()));
    }

    #[test]
    fn test_extract_file_path_truncates_long_paths() {
        let long_path = "/".to_string() + &"a".repeat(300);
        let input = format!(r#"{{"file_path":"{}"}}"#, long_path);
        let path = extract_file_path(&input).unwrap();
        assert!(path.len() <= 200);
        assert!(path.ends_with("..."));
    }

    #[test]
    fn test_detect_retry_pattern() {
        let calls = vec![
            ToolCall {
                name: "Read".to_string(),
                timestamp: 1000,
                input_summary: "{}".to_string(),
                status: ToolStatus::Success,
            },
            ToolCall {
                name: "Read".to_string(),
                timestamp: 2000,
                input_summary: "{}".to_string(),
                status: ToolStatus::Error {
                    message: "not found".to_string(),
                },
            },
            ToolCall {
                name: "Read".to_string(),
                timestamp: 3000,
                input_summary: "{}".to_string(),
                status: ToolStatus::Success,
            },
        ];

        assert_eq!(detect_retry_pattern(&calls), 3);
    }

    #[test]
    fn test_detect_session_outcome_empty() {
        let outcome = detect_session_outcome("test-session", &[], &[]);
        assert_eq!(outcome.status, OutcomeStatus::Inconclusive);
        assert_eq!(outcome.confidence, Confidence::zero());
    }

    #[test]
    fn test_detect_session_outcome_success() {
        let calls = vec![
            ToolCall {
                name: "Read".to_string(),
                timestamp: 1000,
                input_summary: "{}".to_string(),
                status: ToolStatus::Success,
            },
            ToolCall {
                name: "Write".to_string(),
                timestamp: 2000,
                input_summary: "{}".to_string(),
                status: ToolStatus::Success,
            },
            ToolCall {
                name: "Bash".to_string(),
                timestamp: 3000 + 60, // 60+ seconds later
                input_summary: "{}".to_string(),
                status: ToolStatus::Success,
            },
        ];

        let contexts = vec![Some("Great, tests pass!".to_string())];
        let outcome = detect_session_outcome("test-session", &calls, &contexts);

        assert_eq!(outcome.status, OutcomeStatus::Success);
        assert!(outcome.confidence.value() > 0.3);
    }

    #[test]
    fn test_detect_session_outcome_failure() {
        let calls = vec![
            ToolCall {
                name: "Bash".to_string(),
                timestamp: 1000,
                input_summary: "{}".to_string(),
                status: ToolStatus::Error {
                    message: "command failed".to_string(),
                },
            },
            ToolCall {
                name: "Bash".to_string(),
                timestamp: 1010,
                input_summary: "{}".to_string(),
                status: ToolStatus::Error {
                    message: "command failed again".to_string(),
                },
            },
        ];

        let contexts = vec![Some("Error: build failed".to_string())];
        let outcome = detect_session_outcome("test-session", &calls, &contexts);

        assert_eq!(outcome.status, OutcomeStatus::Failure);
    }

    #[test]
    fn test_extract_common_ngrams() {
        let sequences = vec![
            vec!["Read".to_string(), "Edit".to_string(), "Write".to_string()],
            vec!["Read".to_string(), "Edit".to_string(), "Write".to_string()],
            vec!["Read".to_string(), "Bash".to_string()],
        ];

        let bigrams = extract_common_ngrams(&sequences, 2, 2);

        // "Read", "Edit" should appear 2 times
        assert!(bigrams.iter().any(|(gram, count)| gram
            == &vec!["Read".to_string(), "Edit".to_string()]
            && *count == 2));
    }

    #[test]
    fn test_extract_file_accesses() {
        let calls = vec![
            ToolCall {
                name: "Read".to_string(),
                timestamp: 1000,
                input_summary: r#"{"file_path":"/src/main.rs"}"#.to_string(),
                status: ToolStatus::Success,
            },
            ToolCall {
                name: "Bash".to_string(),
                timestamp: 2000,
                input_summary: r#"{"command":"ls"}"#.to_string(),
                status: ToolStatus::Success,
            },
            ToolCall {
                name: "Write".to_string(),
                timestamp: 3000,
                input_summary: r#"{"file_path":"/src/lib.rs"}"#.to_string(),
                status: ToolStatus::Success,
            },
        ];

        let accesses = extract_file_accesses(&calls);

        assert_eq!(accesses.len(), 2);
        assert_eq!(accesses[0].path, "/src/main.rs");
        assert_eq!(accesses[0].operation, FileOperation::Read);
        assert_eq!(accesses[1].path, "/src/lib.rs");
        assert_eq!(accesses[1].operation, FileOperation::Write);
    }

    // ========================================================================
    // TC-4: N-gram edge cases
    // ========================================================================

    #[test]
    fn test_extract_common_ngrams_empty_sequences() {
        let sequences: Vec<Vec<String>> = vec![];
        let result = extract_common_ngrams(&sequences, 2, 1);
        assert!(result.is_empty(), "Empty input should produce empty output");
    }

    #[test]
    fn test_extract_common_ngrams_single_empty_sequence() {
        let sequences = vec![vec![]];
        let result = extract_common_ngrams(&sequences, 2, 1);
        assert!(
            result.is_empty(),
            "Empty sequence should produce no n-grams"
        );
    }

    #[test]
    fn test_extract_common_ngrams_n_greater_than_length() {
        let sequences = vec![vec!["Read".to_string(), "Write".to_string()]];
        // Request 3-grams from a 2-element sequence
        let result = extract_common_ngrams(&sequences, 3, 1);
        assert!(
            result.is_empty(),
            "n > sequence length should produce no n-grams"
        );
    }

    #[test]
    fn test_extract_common_ngrams_n_equals_length() {
        let sequences = vec![
            vec!["Read".to_string(), "Write".to_string()],
            vec!["Read".to_string(), "Write".to_string()],
        ];
        // Request 2-grams from 2-element sequences
        let result = extract_common_ngrams(&sequences, 2, 1);
        assert_eq!(result.len(), 1);
        assert_eq!(
            result[0],
            (vec!["Read".to_string(), "Write".to_string()], 2)
        );
    }

    #[test]
    fn test_extract_common_ngrams_min_count_filters() {
        let sequences = vec![
            vec!["A".to_string(), "B".to_string(), "C".to_string()],
            vec!["A".to_string(), "B".to_string(), "D".to_string()],
            vec!["X".to_string(), "Y".to_string(), "Z".to_string()],
        ];
        // min_count=2 should only return "A","B" which appears twice
        let result = extract_common_ngrams(&sequences, 2, 2);
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].0, vec!["A".to_string(), "B".to_string()]);
        assert_eq!(result[0].1, 2);
    }

    // ========================================================================
    // TC-6: build_behavioral_patterns tests
    // ========================================================================

    fn make_behavioral_event(
        skill_path: &str,
        session_id: &str,
        tools: Vec<&str>,
        files: Vec<(&str, FileOperation)>,
        outcome_status: OutcomeStatus,
        evidence: Vec<&str>,
    ) -> BehavioralEvent {
        BehavioralEvent {
            skill_usage: SkillUsageEventData {
                timestamp: 1000,
                skill_path: skill_path.to_string(),
                session_id: session_id.to_string(),
                prompt_context: Some("test context".to_string()),
            },
            tool_sequence: tools
                .into_iter()
                .enumerate()
                .map(|(i, name)| ToolCall {
                    name: name.to_string(),
                    timestamp: 1000 + i as u64 * 100,
                    input_summary: "{}".to_string(),
                    status: ToolStatus::Success,
                })
                .collect(),
            files_accessed: files
                .into_iter()
                .map(|(path, op)| FileAccess {
                    path: path.to_string(),
                    operation: op,
                    timestamp: 1000,
                    context: None,
                })
                .collect(),
            session_outcome: Some(SessionOutcome {
                session_id: session_id.to_string(),
                status: outcome_status,
                confidence: Confidence::new(0.8),
                evidence: evidence.into_iter().map(|s| s.to_string()).collect(),
                duration_seconds: 60,
            }),
        }
    }

    #[test]
    fn test_build_behavioral_patterns_empty_events() {
        let analytics = UsageAnalytics {
            sessions_analyzed: 0,
            ..Default::default()
        };
        let patterns = build_behavioral_patterns(&[], &analytics);

        assert!(patterns.common_tool_sequences.is_empty());
        assert!(patterns.file_access_patterns.is_empty());
        assert!(patterns.success_indicators.is_empty());
        assert!(patterns.failure_indicators.is_empty());
        assert_eq!(patterns.sessions_analyzed, 0);
    }

    #[test]
    fn test_build_behavioral_patterns_collects_tool_sequences() {
        let events = vec![
            make_behavioral_event(
                "skill-a",
                "s1",
                vec!["Read", "Edit", "Write"],
                vec![],
                OutcomeStatus::Success,
                vec![],
            ),
            make_behavioral_event(
                "skill-a",
                "s2",
                vec!["Bash", "Read"],
                vec![],
                OutcomeStatus::Success,
                vec![],
            ),
        ];
        let analytics = UsageAnalytics {
            sessions_analyzed: 2,
            ..Default::default()
        };

        let patterns = build_behavioral_patterns(&events, &analytics);

        assert!(patterns.common_tool_sequences.contains_key("skill-a"));
        let sequences = &patterns.common_tool_sequences["skill-a"];
        assert_eq!(sequences.len(), 2);
    }

    #[test]
    fn test_build_behavioral_patterns_collects_file_patterns() {
        let events = vec![make_behavioral_event(
            "skill-b",
            "s1",
            vec!["Read"],
            vec![
                ("/src/main.rs", FileOperation::Read),
                ("/src/lib.rs", FileOperation::Write),
            ],
            OutcomeStatus::Success,
            vec![],
        )];
        let analytics = UsageAnalytics::default();

        let patterns = build_behavioral_patterns(&events, &analytics);

        assert!(patterns.file_access_patterns.contains_key("skill-b"));
        let files = &patterns.file_access_patterns["skill-b"];
        assert_eq!(files.len(), 2);
        assert!(files.contains(&"/src/main.rs".to_string()));
        assert!(files.contains(&"/src/lib.rs".to_string()));
    }

    #[test]
    fn test_build_behavioral_patterns_deduplicates_files() {
        let events = vec![
            make_behavioral_event(
                "skill-c",
                "s1",
                vec!["Read"],
                vec![("/src/main.rs", FileOperation::Read)],
                OutcomeStatus::Success,
                vec![],
            ),
            make_behavioral_event(
                "skill-c",
                "s2",
                vec!["Read"],
                vec![("/src/main.rs", FileOperation::Read)], // Same file
                OutcomeStatus::Success,
                vec![],
            ),
        ];
        let analytics = UsageAnalytics::default();

        let patterns = build_behavioral_patterns(&events, &analytics);

        let files = &patterns.file_access_patterns["skill-c"];
        // Should be deduplicated to 1
        assert_eq!(files.len(), 1);
    }

    #[test]
    fn test_build_behavioral_patterns_collects_success_indicators() {
        let events = vec![make_behavioral_event(
            "skill-d",
            "s1",
            vec!["Bash"],
            vec![],
            OutcomeStatus::Success,
            vec!["Success keyword: tests pass", "No errors detected"],
        )];
        let analytics = UsageAnalytics::default();

        let patterns = build_behavioral_patterns(&events, &analytics);

        assert!(!patterns.success_indicators.is_empty());
        assert!(patterns
            .success_indicators
            .iter()
            .any(|s| s.contains("Success keyword")));
    }

    #[test]
    fn test_build_behavioral_patterns_collects_failure_indicators() {
        let events = vec![make_behavioral_event(
            "skill-e",
            "s1",
            vec!["Bash"],
            vec![],
            OutcomeStatus::Failure,
            vec!["Failure keyword: build failed", "error: compilation failed"],
        )];
        let analytics = UsageAnalytics::default();

        let patterns = build_behavioral_patterns(&events, &analytics);

        assert!(!patterns.failure_indicators.is_empty());
        assert!(patterns
            .failure_indicators
            .iter()
            .any(|s| s.contains("error")));
    }

    #[test]
    fn test_build_behavioral_patterns_tracks_tool_frequency() {
        let events = vec![
            make_behavioral_event(
                "skill-f",
                "s1",
                vec!["Read", "Read", "Write"],
                vec![],
                OutcomeStatus::Success,
                vec![],
            ),
            make_behavioral_event(
                "skill-f",
                "s2",
                vec!["Read", "Bash"],
                vec![],
                OutcomeStatus::Success,
                vec![],
            ),
        ];
        let analytics = UsageAnalytics::default();

        let patterns = build_behavioral_patterns(&events, &analytics);

        assert_eq!(patterns.tool_frequency.get("Read"), Some(&3));
        assert_eq!(patterns.tool_frequency.get("Write"), Some(&1));
        assert_eq!(patterns.tool_frequency.get("Bash"), Some(&1));
    }
}