Skip to main content

datasphere/
session.rs

1//! Session discovery - find all transcripts in ~/.claude/projects/<project-id>/
2//!
3//! Claude Code stores transcripts as JSONL files with UUID names directly in the project
4//! directory. The project-id is derived from the absolute path with slashes replaced by dashes.
5//!
6//! AIDEV-NOTE: This module is foundational for the distill command which needs to process
7//! all sessions in batch. Used by yz-yb9q (distill CLI).
8
9use chrono::{DateTime, Utc};
10use std::path::{Path, PathBuf};
11use std::time::SystemTime;
12
13/// Information about a discovered session transcript
14#[derive(Debug, Clone)]
15pub struct SessionInfo {
16    /// Session UUID (filename without .jsonl extension)
17    pub session_id: String,
18
19    /// Full path to the transcript file
20    pub transcript_path: PathBuf,
21
22    /// Last modification time
23    pub modified_at: DateTime<Utc>,
24
25    /// File size in bytes
26    pub size_bytes: u64,
27}
28
29/// Compute project-id from a project path
30/// Converts absolute path to Claude's project-id format: slashes become dashes
31///
32/// Example: /Users/drazen/playground/ai-omnibus/wm -> -Users-drazen-playground-ai-omnibus-wm
33pub fn compute_project_id(project_path: &Path) -> String {
34    // Get absolute path
35    let abs_path = project_path
36        .canonicalize()
37        .unwrap_or_else(|_| project_path.to_path_buf());
38
39    // Convert to string and replace / with -
40    let path_str = abs_path.to_string_lossy();
41    path_str.replace('/', "-")
42}
43
44/// Get the Claude projects directory (~/.claude/projects/)
45pub fn claude_projects_dir() -> Option<PathBuf> {
46    dirs::home_dir().map(|home| home.join(".claude").join("projects"))
47}
48
49/// Get the project directory for a given project path
50/// Returns None if the directory doesn't exist
51pub fn get_project_dir(project_path: &Path) -> Option<PathBuf> {
52    let projects_dir = claude_projects_dir()?;
53    let project_id = compute_project_id(project_path);
54    let project_dir = projects_dir.join(&project_id);
55
56    if project_dir.exists() {
57        Some(project_dir)
58    } else {
59        None
60    }
61}
62
63/// Discover all session transcripts for a project
64///
65/// Returns sessions sorted by modification time (newest first)
66pub fn discover_sessions(project_path: &Path) -> Result<Vec<SessionInfo>, String> {
67    let project_dir = get_project_dir(project_path)
68        .ok_or_else(|| format!("No Claude project directory found for {:?}", project_path))?;
69
70    discover_sessions_in_dir(&project_dir)
71}
72
73/// Discover all session transcripts in a specific directory
74pub fn discover_sessions_in_dir(project_dir: &Path) -> Result<Vec<SessionInfo>, String> {
75    let entries = std::fs::read_dir(project_dir)
76        .map_err(|e| format!("Failed to read project directory: {}", e))?;
77
78    let mut sessions: Vec<SessionInfo> = entries
79        .filter_map(|entry| entry.ok())
80        .filter_map(|entry| {
81            let path = entry.path();
82
83            // Only consider .jsonl files
84            if path.extension().and_then(|e| e.to_str()) != Some("jsonl") {
85                return None;
86            }
87
88            // Session ID is the filename without extension
89            let session_id = path.file_stem()?.to_str()?.to_string();
90
91            // Skip agent sessions (Task tool subagent transcripts)
92            // AIDEV-NOTE: Agent sessions start with "agent-" and are typically
93            // short, focused tool invocations - not valuable for knowledge extraction.
94            if session_id.starts_with("agent-") {
95                return None;
96            }
97
98            // Get metadata for timestamps and size
99            let metadata = std::fs::metadata(&path).ok()?;
100            let modified = metadata.modified().ok()?;
101            let size_bytes = metadata.len();
102
103            // Convert SystemTime to DateTime<Utc>
104            let modified_at = system_time_to_datetime(modified)?;
105
106            Some(SessionInfo {
107                session_id,
108                transcript_path: path,
109                modified_at,
110                size_bytes,
111            })
112        })
113        .collect();
114
115    // Sort by modification time, newest first
116    sessions.sort_by(|a, b| b.modified_at.cmp(&a.modified_at));
117
118    Ok(sessions)
119}
120
121/// Convert SystemTime to DateTime<Utc>
122fn system_time_to_datetime(st: SystemTime) -> Option<DateTime<Utc>> {
123    let duration = st.duration_since(std::time::UNIX_EPOCH).ok()?;
124    DateTime::from_timestamp(duration.as_secs() as i64, duration.subsec_nanos())
125}
126
127/// Get the current project path
128/// Uses CLAUDE_PROJECT_DIR if set, otherwise current working directory
129pub fn current_project_path() -> PathBuf {
130    if let Ok(project_dir) = std::env::var("CLAUDE_PROJECT_DIR") {
131        PathBuf::from(project_dir)
132    } else {
133        std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))
134    }
135}
136
137/// Information about a Claude project directory
138#[derive(Debug, Clone)]
139pub struct ProjectInfo {
140    /// Project ID (directory name in ~/.claude/projects/)
141    pub project_id: String,
142
143    /// Full path to the project directory
144    pub project_dir: PathBuf,
145
146    /// Number of session files
147    pub session_count: usize,
148}
149
150/// List all Claude projects in ~/.claude/projects/
151///
152/// Returns projects sorted alphabetically by project_id
153pub fn list_all_projects() -> Result<Vec<ProjectInfo>, String> {
154    let projects_dir = claude_projects_dir()
155        .ok_or_else(|| "Could not determine Claude projects directory".to_string())?;
156
157    if !projects_dir.exists() {
158        return Ok(Vec::new());
159    }
160
161    let entries = std::fs::read_dir(&projects_dir)
162        .map_err(|e| format!("Failed to read projects directory: {}", e))?;
163
164    let mut projects: Vec<ProjectInfo> = entries
165        .filter_map(|entry| entry.ok())
166        .filter_map(|entry| {
167            let path = entry.path();
168
169            // Only consider directories
170            if !path.is_dir() {
171                return None;
172            }
173
174            let project_id = path.file_name()?.to_str()?.to_string();
175
176            // Count .jsonl files (sessions)
177            let session_count = std::fs::read_dir(&path)
178                .ok()?
179                .filter_map(|e| e.ok())
180                .filter(|e| {
181                    e.path()
182                        .extension()
183                        .and_then(|ext| ext.to_str())
184                        == Some("jsonl")
185                })
186                .count();
187
188            Some(ProjectInfo {
189                project_id,
190                project_dir: path,
191                session_count,
192            })
193        })
194        .collect();
195
196    // Sort alphabetically
197    projects.sort_by(|a, b| a.project_id.cmp(&b.project_id));
198
199    Ok(projects)
200}
201
202/// Find projects matching a filter string (case-insensitive substring match)
203pub fn find_projects_by_filter(filter: &str) -> Result<Vec<ProjectInfo>, String> {
204    let all_projects = list_all_projects()?;
205    let filter_lower = filter.to_lowercase();
206
207    Ok(all_projects
208        .into_iter()
209        .filter(|p| p.project_id.to_lowercase().contains(&filter_lower))
210        .collect())
211}
212
213#[cfg(test)]
214mod tests {
215    use super::*;
216
217    #[test]
218    fn test_compute_project_id() {
219        let path = Path::new("/Users/drazen/playground/ai-omnibus/wm");
220        let id = compute_project_id(path);
221        // Note: canonicalize may resolve symlinks differently, but the format should be correct
222        assert!(id.starts_with("-"));
223        assert!(id.contains("-wm"));
224        assert!(!id.contains("/"));
225    }
226
227    #[test]
228    fn test_claude_projects_dir() {
229        let dir = claude_projects_dir();
230        assert!(dir.is_some());
231        let path = dir.unwrap();
232        assert!(path.ends_with(".claude/projects") || path.to_string_lossy().contains(".claude"));
233    }
234}