Skip to main content

skrills_intelligence/usage/
mod.rs

1//! Usage analytics from Claude Code and Codex CLI session data.
2
3mod analytics;
4pub mod behavioral;
5mod claude_parser;
6mod codex_parser;
7
8pub use analytics::{build_analytics, get_cooccurring_skills, recency_score};
9pub use behavioral::{
10    build_behavioral_patterns, detect_session_outcome, extract_common_ngrams,
11    extract_file_accesses, extract_tool_calls, BehavioralEvent, BehavioralPatterns, FileAccess,
12    FileOperation, OutcomeStatus, SessionOutcome, SkillUsageEventData, ToolCall, ToolStatus,
13};
14pub use claude_parser::{parse_claude_command_history, parse_claude_sessions};
15pub use codex_parser::{
16    parse_codex_command_history, parse_codex_sessions, parse_codex_skills_history,
17};
18
19use crate::types::Confidence;
20use serde::{Deserialize, Serialize};
21use std::collections::HashMap;
22
23/// Aggregated skill usage statistics from session history.
24#[derive(Debug, Clone, Default, Serialize, Deserialize)]
25pub struct UsageAnalytics {
26    /// Skill usage frequency (skill_path -> count).
27    pub frequency: HashMap<String, u64>,
28    /// Skill recency scores (skill_path -> last_used_timestamp).
29    pub recency: HashMap<String, u64>,
30    /// Skills commonly used together (skill_a -> (skill_b -> co-occurrence_count)).
31    pub cooccurrence: HashMap<String, HashMap<String, u64>>,
32    /// Prompt text -> skill affinities (for semantic matching).
33    pub prompt_affinities: Vec<PromptAffinity>,
34    /// User command history entries.
35    pub command_history: Vec<CommandEntry>,
36    /// Total sessions analyzed.
37    pub sessions_analyzed: usize,
38    /// Time range of analyzed data.
39    pub time_range: Option<TimeRange>,
40}
41
42/// Prompt-to-skill affinity mapping.
43#[derive(Debug, Clone, Serialize, Deserialize)]
44pub struct PromptAffinity {
45    /// Keywords/trigrams extracted from prompts.
46    pub keywords: Vec<String>,
47    /// Skills invoked after this prompt type.
48    pub associated_skills: Vec<String>,
49    /// Confidence score (0.0 - 1.0).
50    pub confidence: Confidence,
51}
52
53/// A user command entered in the CLI.
54#[derive(Debug, Clone, Serialize, Deserialize)]
55pub struct CommandEntry {
56    /// The command text entered by the user.
57    pub text: String,
58    /// Unix timestamp when command was entered.
59    pub timestamp: u64,
60    /// Session ID this command belongs to.
61    pub session_id: String,
62    /// Project path if available.
63    pub project: Option<String>,
64}
65
66/// Time range for analytics data.
67#[derive(Debug, Clone, Serialize, Deserialize)]
68pub struct TimeRange {
69    pub start: u64,
70    pub end: u64,
71}
72
73/// A single skill usage event extracted from session data.
74#[derive(Debug, Clone)]
75pub struct SkillUsageEvent {
76    /// Unix timestamp of the event.
77    pub timestamp: u64,
78    /// Skill path or URI.
79    pub skill_path: String,
80    /// Session ID this event belongs to.
81    pub session_id: String,
82    /// Prompt context that led to this skill being used.
83    pub prompt_context: Option<String>,
84}
85
86// ============================================================================
87// Persistence Functions
88// ============================================================================
89
90/// Default path for analytics cache file.
91///
92/// Returns `~/.skrills/analytics_cache.json` or `None` if home dir unavailable.
93pub fn default_analytics_cache_path() -> Option<std::path::PathBuf> {
94    dirs::home_dir().map(|h| h.join(".skrills").join("analytics_cache.json"))
95}
96
97/// Save usage analytics to a JSON file.
98///
99/// Creates parent directories if they don't exist.
100///
101/// # Errors
102/// Returns error if file cannot be written or serialization fails.
103pub fn save_analytics(analytics: &UsageAnalytics, path: &std::path::Path) -> anyhow::Result<()> {
104    if let Some(parent) = path.parent() {
105        std::fs::create_dir_all(parent)?;
106    }
107    let json = serde_json::to_string_pretty(analytics)?;
108    std::fs::write(path, json)?;
109    Ok(())
110}
111
112/// Load usage analytics from a JSON file.
113///
114/// Returns `None` if file doesn't exist.
115///
116/// # Errors
117/// Returns error if file cannot be read or deserialization fails.
118pub fn load_analytics(path: &std::path::Path) -> anyhow::Result<Option<UsageAnalytics>> {
119    if !path.exists() {
120        return Ok(None);
121    }
122    let json = std::fs::read_to_string(path)?;
123    let analytics: UsageAnalytics = serde_json::from_str(&json)?;
124    Ok(Some(analytics))
125}
126
127/// Load analytics from default cache location, or build fresh if not cached.
128///
129/// This is the recommended entry point for consumers that want cached analytics.
130///
131/// # Arguments
132/// * `force_rebuild` - If true, ignores cache and rebuilds from session data
133/// * `auto_save` - If true, saves rebuilt analytics to cache
134pub fn load_or_build_analytics(
135    force_rebuild: bool,
136    auto_save: bool,
137) -> anyhow::Result<UsageAnalytics> {
138    let cache_path = default_analytics_cache_path();
139
140    // Try loading from cache first (unless force_rebuild)
141    if !force_rebuild {
142        if let Some(ref path) = cache_path {
143            if let Ok(Some(cached)) = load_analytics(path) {
144                return Ok(cached);
145            }
146        }
147    }
148
149    // Build fresh analytics from session data
150    let home = dirs::home_dir().ok_or(crate::IntelligenceError::HomeDirectoryNotFound)?;
151
152    let claude_projects = home.join(".claude").join("projects");
153    let codex_sessions = home.join(".codex").join("sessions");
154
155    let claude_events = parse_claude_sessions(&claude_projects)?;
156    let codex_events = parse_codex_sessions(&codex_sessions)?;
157
158    let mut all_events = claude_events;
159    all_events.extend(codex_events);
160
161    let analytics = build_analytics(all_events);
162
163    // Auto-save if requested
164    if auto_save {
165        if let Some(ref path) = cache_path {
166            if let Err(e) = save_analytics(&analytics, path) {
167                tracing::warn!(path = %path.display(), error = %e, "Failed to save analytics cache");
168            }
169        }
170    }
171
172    Ok(analytics)
173}
174
175#[cfg(test)]
176mod tests {
177    use super::*;
178    use tempfile::tempdir;
179
180    #[test]
181    fn test_default_analytics_cache_path() {
182        // Should return Some path when HOME is available
183        let path = default_analytics_cache_path();
184        if let Some(p) = path {
185            assert!(p.ends_with("analytics_cache.json"));
186            assert!(p.to_string_lossy().contains(".skrills"));
187        }
188        // Note: test passes even if HOME unavailable (returns None)
189    }
190
191    #[test]
192    fn test_save_and_load_analytics_roundtrip() {
193        let temp = tempdir().unwrap();
194        let cache_path = temp.path().join("analytics_cache.json");
195
196        // Create sample analytics
197        let mut analytics = UsageAnalytics {
198            sessions_analyzed: 42,
199            ..Default::default()
200        };
201        analytics.frequency.insert("test-skill".to_string(), 10);
202
203        // Save
204        save_analytics(&analytics, &cache_path).unwrap();
205        assert!(cache_path.exists());
206
207        // Load
208        let loaded = load_analytics(&cache_path).unwrap();
209        assert!(loaded.is_some());
210        let loaded = loaded.unwrap();
211        assert_eq!(loaded.sessions_analyzed, 42);
212        assert_eq!(loaded.frequency.get("test-skill"), Some(&10));
213    }
214
215    #[test]
216    fn test_load_analytics_missing_file() {
217        let temp = tempdir().unwrap();
218        let missing_path = temp.path().join("nonexistent.json");
219
220        // Should return None for missing file, not error
221        let result = load_analytics(&missing_path).unwrap();
222        assert!(result.is_none());
223    }
224
225    #[test]
226    fn test_save_analytics_creates_parent_dirs() {
227        let temp = tempdir().unwrap();
228        let nested_path = temp
229            .path()
230            .join("deep")
231            .join("nested")
232            .join("analytics.json");
233
234        let analytics = UsageAnalytics::default();
235        save_analytics(&analytics, &nested_path).unwrap();
236        assert!(nested_path.exists());
237    }
238
239    #[test]
240    fn test_load_analytics_invalid_json() {
241        let temp = tempdir().unwrap();
242        let bad_path = temp.path().join("bad.json");
243        std::fs::write(&bad_path, "not valid json {{{").unwrap();
244
245        // Should return error for invalid JSON
246        let result = load_analytics(&bad_path);
247        assert!(result.is_err());
248    }
249}