Skip to main content

tj_core/session/
discovery.rs

1//! Discover Claude Code session JSONL files for a project.
2//!
3//! Sessions live at `~/.claude/projects/<encoded-path>/<uuid>.jsonl`.
4//! The encoded path replaces non-alphanumeric chars (except `-`) with `-`.
5
6use std::path::{Path, PathBuf};
7
8/// Resolve the Claude Code config directory.
9/// Uses `CLAUDE_CONFIG_DIR` env if set, otherwise `~/.claude`.
10pub fn claude_config_dir() -> anyhow::Result<PathBuf> {
11    if let Ok(custom) = std::env::var("CLAUDE_CONFIG_DIR") {
12        if !custom.is_empty() {
13            return Ok(PathBuf::from(custom));
14        }
15    }
16    let home = dirs_home()?;
17    Ok(home.join(".claude"))
18}
19
20/// Get the projects directory where session files live.
21pub fn projects_dir() -> anyhow::Result<PathBuf> {
22    Ok(claude_config_dir()?.join("projects"))
23}
24
25/// Encode a filesystem path into the Claude Code project directory name format.
26/// Non-alphanumeric chars (except `-`) are replaced with `-`.
27pub fn encode_project_path(path: &str) -> String {
28    path.chars()
29        .map(|c| {
30            if c.is_alphanumeric() || c == '-' {
31                c
32            } else {
33                '-'
34            }
35        })
36        .collect()
37}
38
39/// Find the project directory for a given filesystem path.
40/// Tries exact match first, then prefix match for worktree variants.
41pub fn find_project_dir(project_path: &Path) -> anyhow::Result<Option<PathBuf>> {
42    let projects = projects_dir()?;
43    if !projects.exists() {
44        return Ok(None);
45    }
46
47    let encoded = encode_project_path(&project_path.to_string_lossy());
48
49    // Try exact match first.
50    let exact = projects.join(&encoded);
51    if exact.is_dir() {
52        return Ok(Some(exact));
53    }
54
55    // Try case-insensitive match (WSL paths can differ in case).
56    let encoded_lower = encoded.to_lowercase();
57    if let Ok(entries) = std::fs::read_dir(&projects) {
58        for entry in entries.flatten() {
59            let name = entry.file_name().to_string_lossy().to_string();
60            if name.to_lowercase() == encoded_lower && entry.path().is_dir() {
61                return Ok(Some(entry.path()));
62            }
63        }
64    }
65
66    Ok(None)
67}
68
69/// List all session JSONL files in a project directory.
70/// Excludes agent files (starting with `agent-`).
71/// Returns files sorted by modification time (newest first).
72pub fn list_sessions(project_dir: &Path) -> anyhow::Result<Vec<PathBuf>> {
73    let mut sessions: Vec<(PathBuf, std::time::SystemTime)> = Vec::new();
74
75    for entry in std::fs::read_dir(project_dir)? {
76        let entry = entry?;
77        let path = entry.path();
78        let name = entry.file_name().to_string_lossy().to_string();
79
80        if !name.ends_with(".jsonl") {
81            continue;
82        }
83        // Skip agent sessions.
84        if name.starts_with("agent-") {
85            continue;
86        }
87
88        let mtime = entry
89            .metadata()
90            .and_then(|m| m.modified())
91            .unwrap_or(std::time::UNIX_EPOCH);
92
93        sessions.push((path, mtime));
94    }
95
96    // Sort newest first.
97    sessions.sort_by(|a, b| b.1.cmp(&a.1));
98    Ok(sessions.into_iter().map(|(p, _)| p).collect())
99}
100
101/// List all project directories in Claude Code config.
102pub fn list_all_projects() -> anyhow::Result<Vec<(String, PathBuf)>> {
103    let projects = projects_dir()?;
104    if !projects.exists() {
105        return Ok(vec![]);
106    }
107
108    let mut result = Vec::new();
109    for entry in std::fs::read_dir(&projects)? {
110        let entry = entry?;
111        if entry.path().is_dir() {
112            let name = entry.file_name().to_string_lossy().to_string();
113            // Decode the project name back to a readable path.
114            let decoded = decode_project_path(&name);
115            result.push((decoded, entry.path()));
116        }
117    }
118    result.sort_by(|a, b| a.0.cmp(&b.0));
119    Ok(result)
120}
121
122/// Decode an encoded project directory name back to a readable path.
123/// This is approximate — we can't distinguish `-` from original `/`.
124fn decode_project_path(encoded: &str) -> String {
125    // Common pattern: leading `--` means the path started with a path separator.
126    // Replace double dashes carefully.
127    encoded.to_string()
128}
129
130fn dirs_home() -> anyhow::Result<PathBuf> {
131    directories::BaseDirs::new()
132        .map(|d| d.home_dir().to_path_buf())
133        .ok_or_else(|| anyhow::anyhow!("could not resolve home directory"))
134}
135
136#[cfg(test)]
137mod tests {
138    use super::*;
139
140    #[test]
141    fn encode_path_replaces_separators() {
142        let encoded = encode_project_path("/home/user/project");
143        assert_eq!(encoded, "-home-user-project");
144    }
145
146    #[test]
147    fn encode_preserves_dashes() {
148        let encoded = encode_project_path("/home/my-project");
149        assert_eq!(encoded, "-home-my-project");
150    }
151
152    #[test]
153    fn encode_wsl_path() {
154        let encoded = encode_project_path("\\\\wsl.localhost\\ubuntu\\home\\user\\project");
155        assert_eq!(encoded, "--wsl-localhost-ubuntu-home-user-project");
156    }
157
158    // --- list_sessions() ---
159
160    #[test]
161    fn list_sessions_returns_jsonl_files_skipping_agent_files() {
162        let dir = tempfile::tempdir().unwrap();
163        // Create regular session files.
164        std::fs::write(dir.path().join("sess-001.jsonl"), "{}").unwrap();
165        std::fs::write(dir.path().join("sess-002.jsonl"), "{}").unwrap();
166        // Create agent files that should be skipped.
167        std::fs::write(dir.path().join("agent-abc.jsonl"), "{}").unwrap();
168        std::fs::write(dir.path().join("agent-def.jsonl"), "{}").unwrap();
169        // Create non-jsonl files that should be skipped.
170        std::fs::write(dir.path().join("notes.txt"), "hello").unwrap();
171        std::fs::write(dir.path().join("data.json"), "{}").unwrap();
172
173        let sessions = list_sessions(dir.path()).unwrap();
174        assert_eq!(sessions.len(), 2);
175        let names: Vec<String> = sessions
176            .iter()
177            .map(|p| p.file_name().unwrap().to_string_lossy().to_string())
178            .collect();
179        assert!(names.contains(&"sess-001.jsonl".to_string()));
180        assert!(names.contains(&"sess-002.jsonl".to_string()));
181        assert!(!names.iter().any(|n| n.starts_with("agent-")));
182    }
183
184    #[test]
185    fn list_sessions_sorted_by_mtime_newest_first() {
186        let dir = tempfile::tempdir().unwrap();
187
188        // Create files with different modification times.
189        let older = dir.path().join("older.jsonl");
190        std::fs::write(&older, "{}").unwrap();
191
192        // Sleep briefly to ensure different mtime.
193        std::thread::sleep(std::time::Duration::from_millis(50));
194
195        let newer = dir.path().join("newer.jsonl");
196        std::fs::write(&newer, "{}").unwrap();
197
198        let sessions = list_sessions(dir.path()).unwrap();
199        assert_eq!(sessions.len(), 2);
200        // Newest file should come first.
201        let first_name = sessions[0].file_name().unwrap().to_string_lossy().to_string();
202        assert_eq!(first_name, "newer.jsonl");
203    }
204
205    #[test]
206    fn list_sessions_empty_directory() {
207        let dir = tempfile::tempdir().unwrap();
208        let sessions = list_sessions(dir.path()).unwrap();
209        assert!(sessions.is_empty());
210    }
211
212    #[test]
213    fn list_sessions_nonexistent_directory() {
214        let result = list_sessions(Path::new("/nonexistent/path/xyz"));
215        assert!(result.is_err());
216    }
217
218    // --- list_all_projects() ---
219
220    #[test]
221    fn list_all_projects_with_temp_dir() {
222        let dir = tempfile::tempdir().unwrap();
223        // Override CLAUDE_CONFIG_DIR for this test.
224        let config_dir = dir.path();
225        let projects = config_dir.join("projects");
226        std::fs::create_dir_all(&projects).unwrap();
227
228        // Create project directories.
229        std::fs::create_dir(projects.join("-home-user-project-alpha")).unwrap();
230        std::fs::create_dir(projects.join("-home-user-project-beta")).unwrap();
231        // Create a file (should be skipped — not a directory).
232        std::fs::write(projects.join("not-a-dir.txt"), "").unwrap();
233
234        // We can't easily test list_all_projects() because it uses projects_dir()
235        // which reads CLAUDE_CONFIG_DIR. Instead, test the directory listing logic directly.
236        let mut result = Vec::new();
237        for entry in std::fs::read_dir(&projects).unwrap() {
238            let entry = entry.unwrap();
239            if entry.path().is_dir() {
240                let name = entry.file_name().to_string_lossy().to_string();
241                let decoded = decode_project_path(&name);
242                result.push((decoded, entry.path()));
243            }
244        }
245        result.sort_by(|a, b| a.0.cmp(&b.0));
246
247        assert_eq!(result.len(), 2);
248        assert!(result[0].0.contains("alpha"));
249        assert!(result[1].0.contains("beta"));
250    }
251
252    // --- find_project_dir() with CLAUDE_CONFIG_DIR env override ---
253
254    #[test]
255    fn find_project_dir_with_env_override() {
256        let dir = tempfile::tempdir().unwrap();
257        let projects = dir.path().join("projects");
258        std::fs::create_dir_all(&projects).unwrap();
259
260        // Create a project directory matching an encoded path.
261        let encoded = encode_project_path("/home/user/myproject");
262        std::fs::create_dir(projects.join(&encoded)).unwrap();
263
264        // Set the env override.
265        std::env::set_var("CLAUDE_CONFIG_DIR", dir.path().to_str().unwrap());
266
267        let result = find_project_dir(Path::new("/home/user/myproject"));
268
269        // Clean up env before assertions (to avoid affecting other tests).
270        std::env::remove_var("CLAUDE_CONFIG_DIR");
271
272        let found = result.unwrap();
273        assert!(found.is_some());
274        let found_path = found.unwrap();
275        assert!(found_path.ends_with(&encoded));
276    }
277
278    #[test]
279    fn find_project_dir_returns_none_when_no_match() {
280        let dir = tempfile::tempdir().unwrap();
281        let projects = dir.path().join("projects");
282        std::fs::create_dir_all(&projects).unwrap();
283
284        std::env::set_var("CLAUDE_CONFIG_DIR", dir.path().to_str().unwrap());
285
286        let result = find_project_dir(Path::new("/nonexistent/project"));
287
288        std::env::remove_var("CLAUDE_CONFIG_DIR");
289
290        assert!(result.unwrap().is_none());
291    }
292
293    #[test]
294    fn find_project_dir_returns_none_when_projects_dir_missing() {
295        let dir = tempfile::tempdir().unwrap();
296        // Don't create a "projects" subdir — it doesn't exist.
297
298        std::env::set_var("CLAUDE_CONFIG_DIR", dir.path().to_str().unwrap());
299
300        let result = find_project_dir(Path::new("/home/user/myproject"));
301
302        std::env::remove_var("CLAUDE_CONFIG_DIR");
303
304        assert!(result.unwrap().is_none());
305    }
306
307    // --- decode_project_path ---
308
309    #[test]
310    fn decode_project_path_returns_same_string() {
311        // Current implementation is identity — just verify it doesn't panic.
312        let decoded = decode_project_path("-home-user-project");
313        assert_eq!(decoded, "-home-user-project");
314    }
315
316    // --- claude_config_dir ---
317
318    #[test]
319    fn claude_config_dir_respects_env_var() {
320        std::env::set_var("CLAUDE_CONFIG_DIR", "/tmp/custom-claude-config");
321        let dir = claude_config_dir().unwrap();
322        std::env::remove_var("CLAUDE_CONFIG_DIR");
323        assert_eq!(dir, PathBuf::from("/tmp/custom-claude-config"));
324    }
325
326    #[test]
327    fn claude_config_dir_ignores_empty_env_var() {
328        std::env::set_var("CLAUDE_CONFIG_DIR", "");
329        let dir = claude_config_dir().unwrap();
330        std::env::remove_var("CLAUDE_CONFIG_DIR");
331        // Should fall back to home dir + .claude.
332        assert!(dir.to_string_lossy().ends_with(".claude"));
333    }
334}