Skip to main content

skrills_intelligence/usage/
behavioral.rs

1//! Behavioral analysis of session tool sequences, file access patterns, and outcomes.
2//!
3//! This module extends the basic skill usage tracking with rich behavioral data:
4//! - Tool call sequences within sessions (not just skill invocations)
5//! - File access patterns (Read/Write/Edit operations)
6//! - Session outcome detection (success/failure/partial)
7
8use super::{SkillUsageEvent, UsageAnalytics};
9use crate::types::Confidence;
10use serde::{Deserialize, Serialize};
11use std::collections::{HashMap, HashSet};
12use tracing::trace;
13
14// ============================================================================
15// Helper Functions
16// ============================================================================
17
18/// Truncate a string safely at UTF-8 character boundaries.
19fn safe_truncate(s: &str, max_len: usize) -> String {
20    if s.len() <= max_len {
21        s.to_string()
22    } else {
23        let mut end = max_len.saturating_sub(3); // Leave room for "..."
24        while !s.is_char_boundary(end) && end > 0 {
25            end -= 1;
26        }
27        format!("{}...", &s[..end])
28    }
29}
30
31// ============================================================================
32// Core Data Structures
33// ============================================================================
34
35/// Status of a tool execution.
36#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
37pub enum ToolStatus {
38    /// Tool executed successfully.
39    Success,
40    /// Tool execution resulted in an error.
41    Error { message: String },
42    /// Tool partially succeeded.
43    Partial,
44    /// Status could not be determined.
45    #[default]
46    Unknown,
47}
48
49/// A single tool call within a session.
50#[derive(Debug, Clone, Serialize, Deserialize)]
51pub struct ToolCall {
52    /// Tool name (e.g., "Read", "Write", "Bash", "Skill").
53    pub name: String,
54    /// Unix timestamp of the call.
55    pub timestamp: u64,
56    /// Truncated summary of input parameters (max 200 chars).
57    pub input_summary: String,
58    /// Execution status.
59    pub status: ToolStatus,
60}
61
62/// Type of file operation.
63#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
64pub enum FileOperation {
65    /// File was read.
66    Read,
67    /// File was written/created.
68    Write,
69    /// File was edited (partial modification).
70    Edit {
71        /// Optional line range affected.
72        line_range: Option<(u64, u64)>,
73    },
74}
75
76/// A file access event within a session.
77#[derive(Debug, Clone, Serialize, Deserialize)]
78pub struct FileAccess {
79    /// File path (relative when possible, truncated to 200 chars).
80    pub path: String,
81    /// Type of operation performed.
82    pub operation: FileOperation,
83    /// Unix timestamp of the access.
84    pub timestamp: u64,
85    /// Truncated prompt context that led to this access.
86    pub context: Option<String>,
87}
88
89/// Status of a session outcome.
90#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
91pub enum OutcomeStatus {
92    /// Task completed successfully (no errors, tests pass, etc.).
93    Success,
94    /// Task failed (errors, crashes, abandoned).
95    Failure,
96    /// Mixed results (some progress, some issues).
97    Partial,
98    /// Insufficient data to determine outcome.
99    #[default]
100    Inconclusive,
101}
102
103/// Analysis of a session's outcome.
104#[derive(Debug, Clone, Serialize, Deserialize)]
105pub struct SessionOutcome {
106    /// Session identifier.
107    pub session_id: String,
108    /// Detected outcome status.
109    pub status: OutcomeStatus,
110    /// Confidence in the outcome detection (0.0 - 1.0).
111    pub confidence: Confidence,
112    /// Evidence supporting the outcome determination.
113    pub evidence: Vec<String>,
114    /// Session duration in seconds.
115    pub duration_seconds: u64,
116}
117
118/// Enriched event combining skill usage with behavioral context.
119#[derive(Debug, Clone, Serialize, Deserialize)]
120pub struct BehavioralEvent {
121    /// Original skill usage event.
122    pub skill_usage: SkillUsageEventData,
123    /// Sequence of tool calls in this session context.
124    pub tool_sequence: Vec<ToolCall>,
125    /// Files accessed during this session.
126    pub files_accessed: Vec<FileAccess>,
127    /// Session outcome if determinable.
128    pub session_outcome: Option<SessionOutcome>,
129}
130
131/// Serializable version of SkillUsageEvent.
132#[derive(Debug, Clone, Serialize, Deserialize)]
133pub struct SkillUsageEventData {
134    pub timestamp: u64,
135    pub skill_path: String,
136    pub session_id: String,
137    pub prompt_context: Option<String>,
138}
139
140impl From<&SkillUsageEvent> for SkillUsageEventData {
141    fn from(event: &SkillUsageEvent) -> Self {
142        Self {
143            timestamp: event.timestamp,
144            skill_path: event.skill_path.clone(),
145            session_id: event.session_id.clone(),
146            prompt_context: event.prompt_context.clone(),
147        }
148    }
149}
150
151// ============================================================================
152// Aggregated Pattern Structures
153// ============================================================================
154
155/// Aggregated behavioral patterns across multiple sessions.
156#[derive(Debug, Clone, Default, Serialize, Deserialize)]
157pub struct BehavioralPatterns {
158    /// Common tool sequences per skill (skill_path -> sequences).
159    pub common_tool_sequences: HashMap<String, Vec<Vec<String>>>,
160    /// File access patterns per skill (skill_path -> file patterns).
161    pub file_access_patterns: HashMap<String, Vec<String>>,
162    /// Indicators that correlate with successful sessions.
163    pub success_indicators: Vec<String>,
164    /// Indicators that correlate with failed sessions.
165    pub failure_indicators: Vec<String>,
166    /// Sessions analyzed for these patterns.
167    pub sessions_analyzed: usize,
168    /// Tool frequency across all sessions.
169    pub tool_frequency: HashMap<String, u64>,
170}
171
172// ============================================================================
173// Pattern Extraction Functions
174// ============================================================================
175
176/// Extract tool calls from raw session JSONL content.
177///
178/// Parses tool_use and tool_result blocks from Claude Code session format.
179pub fn extract_tool_calls(session_content: &str) -> Vec<ToolCall> {
180    let mut tool_calls = Vec::new();
181
182    for line in session_content.lines() {
183        if let Ok(json) = serde_json::from_str::<serde_json::Value>(line) {
184            // Look for tool_use in content blocks
185            if let Some(content) = json.get("content").and_then(|c| c.as_array()) {
186                for block in content {
187                    if block.get("type").and_then(|t| t.as_str()) == Some("tool_use") {
188                        if let Some(name) = block.get("name").and_then(|n| n.as_str()) {
189                            let input_summary = block
190                                .get("input")
191                                .map(|i| safe_truncate(&i.to_string(), 200))
192                                .unwrap_or_default();
193
194                            let timestamp =
195                                json.get("timestamp").and_then(|t| t.as_u64()).unwrap_or_else(|| {
196                                    trace!("timestamp missing or invalid in tool_use block, defaulting to 0");
197                                    0
198                                });
199
200                            tool_calls.push(ToolCall {
201                                name: name.to_string(),
202                                timestamp,
203                                input_summary,
204                                status: ToolStatus::Unknown,
205                            });
206                        }
207                    }
208                }
209            }
210
211            // Look for tool_result to update status
212            if let Some(content) = json.get("content").and_then(|c| c.as_array()) {
213                for block in content {
214                    if block.get("type").and_then(|t| t.as_str()) == Some("tool_result") {
215                        let is_error = block
216                            .get("is_error")
217                            .and_then(|e| e.as_bool())
218                            .unwrap_or(false);
219
220                        // Update most recent tool call's status
221                        if let Some(last_call) = tool_calls.last_mut() {
222                            if last_call.status == ToolStatus::Unknown {
223                                last_call.status = if is_error {
224                                    let error_msg = block
225                                        .get("content")
226                                        .and_then(|c| c.as_str())
227                                        .unwrap_or("Unknown error")
228                                        .chars()
229                                        .take(200)
230                                        .collect();
231                                    ToolStatus::Error { message: error_msg }
232                                } else {
233                                    ToolStatus::Success
234                                };
235                            }
236                        }
237                    }
238                }
239            }
240        }
241    }
242
243    tool_calls
244}
245
246/// Extract file access events from tool calls.
247pub fn extract_file_accesses(tool_calls: &[ToolCall]) -> Vec<FileAccess> {
248    let mut accesses = Vec::new();
249
250    for call in tool_calls {
251        let operation = match call.name.as_str() {
252            "Read" => Some(FileOperation::Read),
253            "Write" => Some(FileOperation::Write),
254            "Edit" => Some(FileOperation::Edit { line_range: None }),
255            _ => None,
256        };
257
258        if let Some(op) = operation {
259            // Extract file path from input summary
260            if let Some(path) = extract_file_path(&call.input_summary) {
261                accesses.push(FileAccess {
262                    path,
263                    operation: op,
264                    timestamp: call.timestamp,
265                    context: None,
266                });
267            }
268        }
269    }
270
271    accesses
272}
273
274/// Extract file path from tool input summary.
275fn extract_file_path(input_summary: &str) -> Option<String> {
276    // Parse JSON input to find file_path parameter
277    if let Ok(json) = serde_json::from_str::<serde_json::Value>(input_summary) {
278        if let Some(path) = json.get("file_path").and_then(|p| p.as_str()) {
279            return Some(safe_truncate(path, 200));
280        }
281    }
282    None
283}
284
285// ============================================================================
286// Session Outcome Detection
287// ============================================================================
288
289/// Keywords indicating successful completion.
290const SUCCESS_KEYWORDS: &[&str] = &[
291    "tests pass",
292    "all tests",
293    "success",
294    "completed",
295    "done",
296    "fixed",
297    "resolved",
298    "working",
299    "build succeeded",
300    "no errors",
301];
302
303/// Keywords indicating failure.
304const FAILURE_KEYWORDS: &[&str] = &[
305    "error",
306    "failed",
307    "failure",
308    "crash",
309    "exception",
310    "traceback",
311    "panic",
312    "timeout",
313    "rejected",
314    "broken",
315    "still broken",
316];
317
318/// Detect session outcome from tool calls and context.
319pub fn detect_session_outcome(
320    session_id: &str,
321    tool_calls: &[ToolCall],
322    prompt_contexts: &[Option<String>],
323) -> SessionOutcome {
324    if tool_calls.is_empty() {
325        trace!(
326            session_id,
327            "No tool calls in session, returning Inconclusive outcome"
328        );
329        return SessionOutcome {
330            session_id: session_id.to_string(),
331            status: OutcomeStatus::Inconclusive,
332            confidence: Confidence::zero(),
333            evidence: vec!["No tool calls in session".to_string()],
334            duration_seconds: 0,
335        };
336    }
337
338    let mut evidence = Vec::new();
339    let mut success_signals = 0;
340    let mut failure_signals = 0;
341
342    // Analyze tool execution statuses
343    let error_count = tool_calls
344        .iter()
345        .filter(|c| matches!(c.status, ToolStatus::Error { .. }))
346        .count();
347    let success_count = tool_calls
348        .iter()
349        .filter(|c| c.status == ToolStatus::Success)
350        .count();
351
352    if error_count > 0 {
353        evidence.push(format!("{} tool errors detected", error_count));
354        failure_signals += error_count;
355    }
356    if success_count > 0 {
357        evidence.push(format!("{} successful tool calls", success_count));
358        success_signals += 1;
359    }
360
361    // Check last few tool calls for indicators
362    let recent_calls: Vec<_> = tool_calls.iter().rev().take(5).collect();
363    let recent_errors = recent_calls
364        .iter()
365        .filter(|c| matches!(c.status, ToolStatus::Error { .. }))
366        .count();
367
368    if recent_errors == 0 && !recent_calls.is_empty() {
369        evidence.push("No errors in final 5 tool calls".to_string());
370        success_signals += 2;
371    } else if recent_errors > 2 {
372        evidence.push("Multiple errors in final tool calls".to_string());
373        failure_signals += 2;
374    }
375
376    // Analyze prompt contexts for keywords
377    for context in prompt_contexts.iter().flatten() {
378        let lower = context.to_lowercase();
379        for kw in SUCCESS_KEYWORDS {
380            if lower.contains(kw) {
381                success_signals += 1;
382                evidence.push(format!("Success keyword detected: '{}'", kw));
383            }
384        }
385        for kw in FAILURE_KEYWORDS {
386            if lower.contains(kw) {
387                failure_signals += 1;
388                evidence.push(format!("Failure keyword detected: '{}'", kw));
389            }
390        }
391    }
392
393    // Check for retry patterns (same tool called repeatedly)
394    let retry_count = detect_retry_pattern(tool_calls);
395    if retry_count > 3 {
396        evidence.push(format!(
397            "Retry pattern detected: {} consecutive similar calls",
398            retry_count
399        ));
400        failure_signals += retry_count / 2;
401    }
402
403    // Calculate duration
404    let duration_seconds = if !tool_calls.is_empty() {
405        let start = tool_calls.iter().map(|c| c.timestamp).min().unwrap_or(0);
406        let end = tool_calls.iter().map(|c| c.timestamp).max().unwrap_or(0);
407        end.saturating_sub(start)
408    } else {
409        0
410    };
411
412    // Duration heuristics
413    if duration_seconds < 30 {
414        evidence.push("Very short session (<30s)".to_string());
415        failure_signals += 1; // May indicate abandoned session
416    } else if duration_seconds > 60 {
417        evidence.push(format!("Engaged session ({}s)", duration_seconds));
418        success_signals += 1;
419    }
420
421    // Determine outcome
422    let total_signals = success_signals + failure_signals;
423    let (status, confidence) = if total_signals == 0 {
424        (OutcomeStatus::Inconclusive, Confidence::new(0.3))
425    } else {
426        let success_ratio = success_signals as f64 / total_signals as f64;
427        let conf_value = (total_signals as f64 / 10.0).min(1.0);
428
429        if success_ratio > 0.7 {
430            (OutcomeStatus::Success, Confidence::new(conf_value))
431        } else if success_ratio < 0.3 {
432            (OutcomeStatus::Failure, Confidence::new(conf_value))
433        } else {
434            (OutcomeStatus::Partial, Confidence::new(conf_value * 0.8))
435        }
436    };
437
438    SessionOutcome {
439        session_id: session_id.to_string(),
440        status,
441        confidence,
442        evidence,
443        duration_seconds,
444    }
445}
446
447/// Detect retry patterns (consecutive calls to the same tool with similar inputs).
448fn detect_retry_pattern(tool_calls: &[ToolCall]) -> usize {
449    let mut max_consecutive = 0;
450    let mut current_consecutive = 1;
451    let mut prev_name: Option<&str> = None;
452
453    for call in tool_calls {
454        if Some(call.name.as_str()) == prev_name {
455            current_consecutive += 1;
456            max_consecutive = max_consecutive.max(current_consecutive);
457        } else {
458            current_consecutive = 1;
459        }
460        prev_name = Some(&call.name);
461    }
462
463    max_consecutive
464}
465
466// ============================================================================
467// Pattern Aggregation
468// ============================================================================
469
470/// Build aggregated behavioral patterns from multiple sessions.
471pub fn build_behavioral_patterns(
472    events: &[BehavioralEvent],
473    analytics: &UsageAnalytics,
474) -> BehavioralPatterns {
475    let mut common_tool_sequences: HashMap<String, Vec<Vec<String>>> = HashMap::new();
476    let mut file_access_patterns: HashMap<String, Vec<String>> = HashMap::new();
477    let mut success_indicators: HashSet<String> = HashSet::new();
478    let mut failure_indicators: HashSet<String> = HashSet::new();
479    let mut tool_frequency: HashMap<String, u64> = HashMap::new();
480
481    for event in events {
482        let skill_path = &event.skill_usage.skill_path;
483
484        // Collect tool sequences (first 10 tools after skill invocation)
485        let sequence: Vec<String> = event
486            .tool_sequence
487            .iter()
488            .take(10)
489            .map(|t| t.name.clone())
490            .collect();
491
492        if !sequence.is_empty() {
493            common_tool_sequences
494                .entry(skill_path.clone())
495                .or_default()
496                .push(sequence);
497        }
498
499        // Collect file patterns
500        for access in &event.files_accessed {
501            file_access_patterns
502                .entry(skill_path.clone())
503                .or_default()
504                .push(access.path.clone());
505        }
506
507        // Collect success/failure indicators
508        if let Some(ref outcome) = event.session_outcome {
509            match outcome.status {
510                OutcomeStatus::Success => {
511                    for ev in &outcome.evidence {
512                        if ev.contains("Success keyword") || ev.contains("No errors") {
513                            success_indicators.insert(ev.clone());
514                        }
515                    }
516                }
517                OutcomeStatus::Failure => {
518                    for ev in &outcome.evidence {
519                        if ev.contains("Failure keyword") || ev.contains("error") {
520                            failure_indicators.insert(ev.clone());
521                        }
522                    }
523                }
524                _ => {}
525            }
526        }
527
528        // Track tool frequency
529        for call in &event.tool_sequence {
530            *tool_frequency.entry(call.name.clone()).or_insert(0) += 1;
531        }
532    }
533
534    // Deduplicate file patterns (keep unique per skill)
535    for patterns in file_access_patterns.values_mut() {
536        let unique: HashSet<_> = patterns.drain(..).collect();
537        *patterns = unique.into_iter().collect();
538    }
539
540    // Get sessions count from analytics
541    let sessions_analyzed = analytics.sessions_analyzed;
542
543    BehavioralPatterns {
544        common_tool_sequences,
545        file_access_patterns,
546        success_indicators: success_indicators.into_iter().collect(),
547        failure_indicators: failure_indicators.into_iter().collect(),
548        sessions_analyzed,
549        tool_frequency,
550    }
551}
552
553/// Extract common n-grams from tool sequences.
554pub fn extract_common_ngrams(
555    sequences: &[Vec<String>],
556    n: usize,
557    min_count: usize,
558) -> Vec<(Vec<String>, usize)> {
559    let mut ngram_counts: HashMap<Vec<String>, usize> = HashMap::new();
560
561    for sequence in sequences {
562        if sequence.len() >= n {
563            for window in sequence.windows(n) {
564                *ngram_counts.entry(window.to_vec()).or_insert(0) += 1;
565            }
566        }
567    }
568
569    let mut common: Vec<_> = ngram_counts
570        .into_iter()
571        .filter(|(_, count)| *count >= min_count)
572        .collect();
573
574    common.sort_by_key(|b| std::cmp::Reverse(b.1));
575    common
576}
577
578// ============================================================================
579// Tests
580// ============================================================================
581
582#[cfg(test)]
583mod tests {
584    use super::*;
585
586    #[test]
587    fn test_tool_status_default() {
588        assert_eq!(ToolStatus::default(), ToolStatus::Unknown);
589    }
590
591    #[test]
592    fn test_outcome_status_default() {
593        assert_eq!(OutcomeStatus::default(), OutcomeStatus::Inconclusive);
594    }
595
596    #[test]
597    fn test_extract_file_path() {
598        let input = r#"{"file_path":"/home/user/project/src/main.rs"}"#;
599        let path = extract_file_path(input);
600        assert_eq!(path, Some("/home/user/project/src/main.rs".to_string()));
601    }
602
603    #[test]
604    fn test_extract_file_path_truncates_long_paths() {
605        let long_path = "/".to_string() + &"a".repeat(300);
606        let input = format!(r#"{{"file_path":"{}"}}"#, long_path);
607        let path = extract_file_path(&input).unwrap();
608        assert!(path.len() <= 200);
609        assert!(path.ends_with("..."));
610    }
611
612    #[test]
613    fn test_detect_retry_pattern() {
614        let calls = vec![
615            ToolCall {
616                name: "Read".to_string(),
617                timestamp: 1000,
618                input_summary: "{}".to_string(),
619                status: ToolStatus::Success,
620            },
621            ToolCall {
622                name: "Read".to_string(),
623                timestamp: 2000,
624                input_summary: "{}".to_string(),
625                status: ToolStatus::Error {
626                    message: "not found".to_string(),
627                },
628            },
629            ToolCall {
630                name: "Read".to_string(),
631                timestamp: 3000,
632                input_summary: "{}".to_string(),
633                status: ToolStatus::Success,
634            },
635        ];
636
637        assert_eq!(detect_retry_pattern(&calls), 3);
638    }
639
640    #[test]
641    fn test_detect_session_outcome_empty() {
642        let outcome = detect_session_outcome("test-session", &[], &[]);
643        assert_eq!(outcome.status, OutcomeStatus::Inconclusive);
644        assert_eq!(outcome.confidence, Confidence::zero());
645    }
646
647    #[test]
648    fn test_detect_session_outcome_success() {
649        let calls = vec![
650            ToolCall {
651                name: "Read".to_string(),
652                timestamp: 1000,
653                input_summary: "{}".to_string(),
654                status: ToolStatus::Success,
655            },
656            ToolCall {
657                name: "Write".to_string(),
658                timestamp: 2000,
659                input_summary: "{}".to_string(),
660                status: ToolStatus::Success,
661            },
662            ToolCall {
663                name: "Bash".to_string(),
664                timestamp: 3000 + 60, // 60+ seconds later
665                input_summary: "{}".to_string(),
666                status: ToolStatus::Success,
667            },
668        ];
669
670        let contexts = vec![Some("Great, tests pass!".to_string())];
671        let outcome = detect_session_outcome("test-session", &calls, &contexts);
672
673        assert_eq!(outcome.status, OutcomeStatus::Success);
674        assert!(outcome.confidence.value() > 0.3);
675    }
676
677    #[test]
678    fn test_detect_session_outcome_failure() {
679        let calls = vec![
680            ToolCall {
681                name: "Bash".to_string(),
682                timestamp: 1000,
683                input_summary: "{}".to_string(),
684                status: ToolStatus::Error {
685                    message: "command failed".to_string(),
686                },
687            },
688            ToolCall {
689                name: "Bash".to_string(),
690                timestamp: 1010,
691                input_summary: "{}".to_string(),
692                status: ToolStatus::Error {
693                    message: "command failed again".to_string(),
694                },
695            },
696        ];
697
698        let contexts = vec![Some("Error: build failed".to_string())];
699        let outcome = detect_session_outcome("test-session", &calls, &contexts);
700
701        assert_eq!(outcome.status, OutcomeStatus::Failure);
702    }
703
704    #[test]
705    fn test_extract_common_ngrams() {
706        let sequences = vec![
707            vec!["Read".to_string(), "Edit".to_string(), "Write".to_string()],
708            vec!["Read".to_string(), "Edit".to_string(), "Write".to_string()],
709            vec!["Read".to_string(), "Bash".to_string()],
710        ];
711
712        let bigrams = extract_common_ngrams(&sequences, 2, 2);
713
714        // "Read", "Edit" should appear 2 times
715        assert!(bigrams.iter().any(|(gram, count)| gram
716            == &vec!["Read".to_string(), "Edit".to_string()]
717            && *count == 2));
718    }
719
720    #[test]
721    fn test_extract_file_accesses() {
722        let calls = vec![
723            ToolCall {
724                name: "Read".to_string(),
725                timestamp: 1000,
726                input_summary: r#"{"file_path":"/src/main.rs"}"#.to_string(),
727                status: ToolStatus::Success,
728            },
729            ToolCall {
730                name: "Bash".to_string(),
731                timestamp: 2000,
732                input_summary: r#"{"command":"ls"}"#.to_string(),
733                status: ToolStatus::Success,
734            },
735            ToolCall {
736                name: "Write".to_string(),
737                timestamp: 3000,
738                input_summary: r#"{"file_path":"/src/lib.rs"}"#.to_string(),
739                status: ToolStatus::Success,
740            },
741        ];
742
743        let accesses = extract_file_accesses(&calls);
744
745        assert_eq!(accesses.len(), 2);
746        assert_eq!(accesses[0].path, "/src/main.rs");
747        assert_eq!(accesses[0].operation, FileOperation::Read);
748        assert_eq!(accesses[1].path, "/src/lib.rs");
749        assert_eq!(accesses[1].operation, FileOperation::Write);
750    }
751
752    // ========================================================================
753    // TC-4: N-gram edge cases
754    // ========================================================================
755
756    #[test]
757    fn test_extract_common_ngrams_empty_sequences() {
758        let sequences: Vec<Vec<String>> = vec![];
759        let result = extract_common_ngrams(&sequences, 2, 1);
760        assert!(result.is_empty(), "Empty input should produce empty output");
761    }
762
763    #[test]
764    fn test_extract_common_ngrams_single_empty_sequence() {
765        let sequences = vec![vec![]];
766        let result = extract_common_ngrams(&sequences, 2, 1);
767        assert!(
768            result.is_empty(),
769            "Empty sequence should produce no n-grams"
770        );
771    }
772
773    #[test]
774    fn test_extract_common_ngrams_n_greater_than_length() {
775        let sequences = vec![vec!["Read".to_string(), "Write".to_string()]];
776        // Request 3-grams from a 2-element sequence
777        let result = extract_common_ngrams(&sequences, 3, 1);
778        assert!(
779            result.is_empty(),
780            "n > sequence length should produce no n-grams"
781        );
782    }
783
784    #[test]
785    fn test_extract_common_ngrams_n_equals_length() {
786        let sequences = vec![
787            vec!["Read".to_string(), "Write".to_string()],
788            vec!["Read".to_string(), "Write".to_string()],
789        ];
790        // Request 2-grams from 2-element sequences
791        let result = extract_common_ngrams(&sequences, 2, 1);
792        assert_eq!(result.len(), 1);
793        assert_eq!(
794            result[0],
795            (vec!["Read".to_string(), "Write".to_string()], 2)
796        );
797    }
798
799    #[test]
800    fn test_extract_common_ngrams_min_count_filters() {
801        let sequences = vec![
802            vec!["A".to_string(), "B".to_string(), "C".to_string()],
803            vec!["A".to_string(), "B".to_string(), "D".to_string()],
804            vec!["X".to_string(), "Y".to_string(), "Z".to_string()],
805        ];
806        // min_count=2 should only return "A","B" which appears twice
807        let result = extract_common_ngrams(&sequences, 2, 2);
808        assert_eq!(result.len(), 1);
809        assert_eq!(result[0].0, vec!["A".to_string(), "B".to_string()]);
810        assert_eq!(result[0].1, 2);
811    }
812
813    // ========================================================================
814    // TC-6: build_behavioral_patterns tests
815    // ========================================================================
816
817    fn make_behavioral_event(
818        skill_path: &str,
819        session_id: &str,
820        tools: Vec<&str>,
821        files: Vec<(&str, FileOperation)>,
822        outcome_status: OutcomeStatus,
823        evidence: Vec<&str>,
824    ) -> BehavioralEvent {
825        BehavioralEvent {
826            skill_usage: SkillUsageEventData {
827                timestamp: 1000,
828                skill_path: skill_path.to_string(),
829                session_id: session_id.to_string(),
830                prompt_context: Some("test context".to_string()),
831            },
832            tool_sequence: tools
833                .into_iter()
834                .enumerate()
835                .map(|(i, name)| ToolCall {
836                    name: name.to_string(),
837                    timestamp: 1000 + i as u64 * 100,
838                    input_summary: "{}".to_string(),
839                    status: ToolStatus::Success,
840                })
841                .collect(),
842            files_accessed: files
843                .into_iter()
844                .map(|(path, op)| FileAccess {
845                    path: path.to_string(),
846                    operation: op,
847                    timestamp: 1000,
848                    context: None,
849                })
850                .collect(),
851            session_outcome: Some(SessionOutcome {
852                session_id: session_id.to_string(),
853                status: outcome_status,
854                confidence: Confidence::new(0.8),
855                evidence: evidence.into_iter().map(|s| s.to_string()).collect(),
856                duration_seconds: 60,
857            }),
858        }
859    }
860
861    #[test]
862    fn test_build_behavioral_patterns_empty_events() {
863        let analytics = UsageAnalytics {
864            sessions_analyzed: 0,
865            ..Default::default()
866        };
867        let patterns = build_behavioral_patterns(&[], &analytics);
868
869        assert!(patterns.common_tool_sequences.is_empty());
870        assert!(patterns.file_access_patterns.is_empty());
871        assert!(patterns.success_indicators.is_empty());
872        assert!(patterns.failure_indicators.is_empty());
873        assert_eq!(patterns.sessions_analyzed, 0);
874    }
875
876    #[test]
877    fn test_build_behavioral_patterns_collects_tool_sequences() {
878        let events = vec![
879            make_behavioral_event(
880                "skill-a",
881                "s1",
882                vec!["Read", "Edit", "Write"],
883                vec![],
884                OutcomeStatus::Success,
885                vec![],
886            ),
887            make_behavioral_event(
888                "skill-a",
889                "s2",
890                vec!["Bash", "Read"],
891                vec![],
892                OutcomeStatus::Success,
893                vec![],
894            ),
895        ];
896        let analytics = UsageAnalytics {
897            sessions_analyzed: 2,
898            ..Default::default()
899        };
900
901        let patterns = build_behavioral_patterns(&events, &analytics);
902
903        assert!(patterns.common_tool_sequences.contains_key("skill-a"));
904        let sequences = &patterns.common_tool_sequences["skill-a"];
905        assert_eq!(sequences.len(), 2);
906    }
907
908    #[test]
909    fn test_build_behavioral_patterns_collects_file_patterns() {
910        let events = vec![make_behavioral_event(
911            "skill-b",
912            "s1",
913            vec!["Read"],
914            vec![
915                ("/src/main.rs", FileOperation::Read),
916                ("/src/lib.rs", FileOperation::Write),
917            ],
918            OutcomeStatus::Success,
919            vec![],
920        )];
921        let analytics = UsageAnalytics::default();
922
923        let patterns = build_behavioral_patterns(&events, &analytics);
924
925        assert!(patterns.file_access_patterns.contains_key("skill-b"));
926        let files = &patterns.file_access_patterns["skill-b"];
927        assert_eq!(files.len(), 2);
928        assert!(files.contains(&"/src/main.rs".to_string()));
929        assert!(files.contains(&"/src/lib.rs".to_string()));
930    }
931
932    #[test]
933    fn test_build_behavioral_patterns_deduplicates_files() {
934        let events = vec![
935            make_behavioral_event(
936                "skill-c",
937                "s1",
938                vec!["Read"],
939                vec![("/src/main.rs", FileOperation::Read)],
940                OutcomeStatus::Success,
941                vec![],
942            ),
943            make_behavioral_event(
944                "skill-c",
945                "s2",
946                vec!["Read"],
947                vec![("/src/main.rs", FileOperation::Read)], // Same file
948                OutcomeStatus::Success,
949                vec![],
950            ),
951        ];
952        let analytics = UsageAnalytics::default();
953
954        let patterns = build_behavioral_patterns(&events, &analytics);
955
956        let files = &patterns.file_access_patterns["skill-c"];
957        // Should be deduplicated to 1
958        assert_eq!(files.len(), 1);
959    }
960
961    #[test]
962    fn test_build_behavioral_patterns_collects_success_indicators() {
963        let events = vec![make_behavioral_event(
964            "skill-d",
965            "s1",
966            vec!["Bash"],
967            vec![],
968            OutcomeStatus::Success,
969            vec!["Success keyword: tests pass", "No errors detected"],
970        )];
971        let analytics = UsageAnalytics::default();
972
973        let patterns = build_behavioral_patterns(&events, &analytics);
974
975        assert!(!patterns.success_indicators.is_empty());
976        assert!(patterns
977            .success_indicators
978            .iter()
979            .any(|s| s.contains("Success keyword")));
980    }
981
982    #[test]
983    fn test_build_behavioral_patterns_collects_failure_indicators() {
984        let events = vec![make_behavioral_event(
985            "skill-e",
986            "s1",
987            vec!["Bash"],
988            vec![],
989            OutcomeStatus::Failure,
990            vec!["Failure keyword: build failed", "error: compilation failed"],
991        )];
992        let analytics = UsageAnalytics::default();
993
994        let patterns = build_behavioral_patterns(&events, &analytics);
995
996        assert!(!patterns.failure_indicators.is_empty());
997        assert!(patterns
998            .failure_indicators
999            .iter()
1000            .any(|s| s.contains("error")));
1001    }
1002
1003    #[test]
1004    fn test_build_behavioral_patterns_tracks_tool_frequency() {
1005        let events = vec![
1006            make_behavioral_event(
1007                "skill-f",
1008                "s1",
1009                vec!["Read", "Read", "Write"],
1010                vec![],
1011                OutcomeStatus::Success,
1012                vec![],
1013            ),
1014            make_behavioral_event(
1015                "skill-f",
1016                "s2",
1017                vec!["Read", "Bash"],
1018                vec![],
1019                OutcomeStatus::Success,
1020                vec![],
1021            ),
1022        ];
1023        let analytics = UsageAnalytics::default();
1024
1025        let patterns = build_behavioral_patterns(&events, &analytics);
1026
1027        assert_eq!(patterns.tool_frequency.get("Read"), Some(&3));
1028        assert_eq!(patterns.tool_frequency.get("Write"), Some(&1));
1029        assert_eq!(patterns.tool_frequency.get("Bash"), Some(&1));
1030    }
1031}