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_key(|s| std::cmp::Reverse(s.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]
202            .file_name()
203            .unwrap()
204            .to_string_lossy()
205            .to_string();
206        assert_eq!(first_name, "newer.jsonl");
207    }
208
209    #[test]
210    fn list_sessions_empty_directory() {
211        let dir = tempfile::tempdir().unwrap();
212        let sessions = list_sessions(dir.path()).unwrap();
213        assert!(sessions.is_empty());
214    }
215
216    #[test]
217    fn list_sessions_nonexistent_directory() {
218        let result = list_sessions(Path::new("/nonexistent/path/xyz"));
219        assert!(result.is_err());
220    }
221
222    // --- list_all_projects() ---
223
224    #[test]
225    fn list_all_projects_with_temp_dir() {
226        let dir = tempfile::tempdir().unwrap();
227        // Override CLAUDE_CONFIG_DIR for this test.
228        let config_dir = dir.path();
229        let projects = config_dir.join("projects");
230        std::fs::create_dir_all(&projects).unwrap();
231
232        // Create project directories.
233        std::fs::create_dir(projects.join("-home-user-project-alpha")).unwrap();
234        std::fs::create_dir(projects.join("-home-user-project-beta")).unwrap();
235        // Create a file (should be skipped — not a directory).
236        std::fs::write(projects.join("not-a-dir.txt"), "").unwrap();
237
238        // We can't easily test list_all_projects() because it uses projects_dir()
239        // which reads CLAUDE_CONFIG_DIR. Instead, test the directory listing logic directly.
240        let mut result = Vec::new();
241        for entry in std::fs::read_dir(&projects).unwrap() {
242            let entry = entry.unwrap();
243            if entry.path().is_dir() {
244                let name = entry.file_name().to_string_lossy().to_string();
245                let decoded = decode_project_path(&name);
246                result.push((decoded, entry.path()));
247            }
248        }
249        result.sort_by(|a, b| a.0.cmp(&b.0));
250
251        assert_eq!(result.len(), 2);
252        assert!(result[0].0.contains("alpha"));
253        assert!(result[1].0.contains("beta"));
254    }
255
256    // --- find_project_dir() with CLAUDE_CONFIG_DIR env override ---
257
258    #[test]
259    fn find_project_dir_with_env_override() {
260        let dir = tempfile::tempdir().unwrap();
261        let projects = dir.path().join("projects");
262        std::fs::create_dir_all(&projects).unwrap();
263
264        // Create a project directory matching an encoded path.
265        let encoded = encode_project_path("/home/user/myproject");
266        std::fs::create_dir(projects.join(&encoded)).unwrap();
267
268        // Set the env override.
269        std::env::set_var("CLAUDE_CONFIG_DIR", dir.path().to_str().unwrap());
270
271        let result = find_project_dir(Path::new("/home/user/myproject"));
272
273        // Clean up env before assertions (to avoid affecting other tests).
274        std::env::remove_var("CLAUDE_CONFIG_DIR");
275
276        let found = result.unwrap();
277        assert!(found.is_some());
278        let found_path = found.unwrap();
279        assert!(found_path.ends_with(&encoded));
280    }
281
282    #[test]
283    fn find_project_dir_returns_none_when_no_match() {
284        let dir = tempfile::tempdir().unwrap();
285        let projects = dir.path().join("projects");
286        std::fs::create_dir_all(&projects).unwrap();
287
288        std::env::set_var("CLAUDE_CONFIG_DIR", dir.path().to_str().unwrap());
289
290        let result = find_project_dir(Path::new("/nonexistent/project"));
291
292        std::env::remove_var("CLAUDE_CONFIG_DIR");
293
294        assert!(result.unwrap().is_none());
295    }
296
297    #[test]
298    fn find_project_dir_returns_none_when_projects_dir_missing() {
299        let dir = tempfile::tempdir().unwrap();
300        // Don't create a "projects" subdir — it doesn't exist.
301
302        std::env::set_var("CLAUDE_CONFIG_DIR", dir.path().to_str().unwrap());
303
304        let result = find_project_dir(Path::new("/home/user/myproject"));
305
306        std::env::remove_var("CLAUDE_CONFIG_DIR");
307
308        assert!(result.unwrap().is_none());
309    }
310
311    // --- decode_project_path ---
312
313    #[test]
314    fn decode_project_path_returns_same_string() {
315        // Current implementation is identity — just verify it doesn't panic.
316        let decoded = decode_project_path("-home-user-project");
317        assert_eq!(decoded, "-home-user-project");
318    }
319
320    // --- claude_config_dir ---
321
322    #[test]
323    fn claude_config_dir_respects_env_var() {
324        std::env::set_var("CLAUDE_CONFIG_DIR", "/tmp/custom-claude-config");
325        let dir = claude_config_dir().unwrap();
326        std::env::remove_var("CLAUDE_CONFIG_DIR");
327        assert_eq!(dir, PathBuf::from("/tmp/custom-claude-config"));
328    }
329
330    #[test]
331    fn claude_config_dir_ignores_empty_env_var() {
332        std::env::set_var("CLAUDE_CONFIG_DIR", "");
333        let dir = claude_config_dir().unwrap();
334        std::env::remove_var("CLAUDE_CONFIG_DIR");
335        // Should fall back to home dir + .claude.
336        assert!(dir.to_string_lossy().ends_with(".claude"));
337    }
338}