toolpath-cli 0.3.0

CLI for deriving, querying, and visualizing Toolpath provenance
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
#[cfg(not(target_os = "emscripten"))]
use anyhow::Context;
use anyhow::Result;
use clap::Subcommand;
use std::path::PathBuf;

#[derive(Subcommand, Debug)]
pub enum ListSource {
    /// List git branches in a repository
    Git {
        /// Path to the git repository
        #[arg(short, long, default_value = ".")]
        repo: PathBuf,

        /// Remote name for URI generation
        #[arg(long, default_value = "origin")]
        remote: String,
    },
    /// List GitHub pull requests
    Github {
        /// Repository in owner/repo format
        #[arg(short, long)]
        repo: String,
    },
    /// List Claude projects or sessions
    Claude {
        /// Project path — if omitted, lists all projects
        #[arg(short, long)]
        project: Option<String>,
    },
}

pub fn run(source: ListSource, json: bool) -> Result<()> {
    match source {
        ListSource::Git { repo, remote } => run_git(repo, remote, json),
        ListSource::Github { repo } => run_github(repo, json),
        ListSource::Claude { project } => run_claude(project, json),
    }
}

fn run_git(repo_path: PathBuf, remote: String, json: bool) -> Result<()> {
    #[cfg(target_os = "emscripten")]
    {
        let _ = (repo_path, remote, json);
        anyhow::bail!(
            "'path list git' requires a native environment with access to a git repository"
        );
    }

    #[cfg(not(target_os = "emscripten"))]
    {
        let repo_path = if repo_path.is_absolute() {
            repo_path
        } else {
            std::env::current_dir()?.join(&repo_path)
        };

        let repo = git2::Repository::open(&repo_path)
            .with_context(|| format!("Failed to open repository at {:?}", repo_path))?;

        let uri = toolpath_git::get_repo_uri(&repo, &remote)?;
        let branches = toolpath_git::list_branches(&repo)?;

        if json {
            let items: Vec<serde_json::Value> = branches
                .iter()
                .map(|b| {
                    serde_json::json!({
                        "name": b.name,
                        "head": b.head,
                        "subject": b.subject,
                        "author": b.author,
                        "timestamp": b.timestamp,
                    })
                })
                .collect();
            let output = serde_json::json!({
                "source": "git",
                "uri": uri,
                "branches": items,
            });
            println!("{}", serde_json::to_string_pretty(&output)?);
        } else {
            println!("Repository: {}", uri);
            println!();
            if branches.is_empty() {
                println!("  (no local branches)");
            } else {
                for b in &branches {
                    println!("  {} {} {}", b.head_short, b.name, truncate(&b.subject, 60));
                }
            }
        }
        Ok(())
    }
}

fn run_github(repo: String, json: bool) -> Result<()> {
    #[cfg(target_os = "emscripten")]
    {
        let _ = (repo, json);
        anyhow::bail!("'path list github' requires a native environment with network access");
    }

    #[cfg(not(target_os = "emscripten"))]
    {
        let (owner, repo_name) = repo
            .split_once('/')
            .ok_or_else(|| anyhow::anyhow!("Repository must be in owner/repo format"))?;

        let token = toolpath_github::resolve_token()?;
        let config = toolpath_github::DeriveConfig {
            token,
            ..Default::default()
        };

        let prs = toolpath_github::list_pull_requests(owner, repo_name, &config)?;

        if json {
            let items: Vec<serde_json::Value> = prs
                .iter()
                .map(|pr| {
                    serde_json::json!({
                        "number": pr.number,
                        "title": pr.title,
                        "state": pr.state,
                        "author": pr.author,
                        "head_branch": pr.head_branch,
                        "base_branch": pr.base_branch,
                        "created_at": pr.created_at,
                        "updated_at": pr.updated_at,
                    })
                })
                .collect();
            let output = serde_json::json!({
                "source": "github",
                "repo": format!("{}/{}", owner, repo_name),
                "pull_requests": items,
            });
            println!("{}", serde_json::to_string_pretty(&output)?);
        } else {
            println!("Pull requests for {}/{}:", owner, repo_name);
            println!();
            if prs.is_empty() {
                println!("  (none)");
            } else {
                for pr in &prs {
                    println!(
                        "  #{:<5} {:>8} {}  {}",
                        pr.number,
                        pr.state,
                        pr.author,
                        truncate(&pr.title, 50),
                    );
                }
            }
        }
        Ok(())
    }
}

fn run_claude(project: Option<String>, json: bool) -> Result<()> {
    let manager = toolpath_claude::ClaudeConvo::new();

    match project {
        None => list_claude_projects(&manager, json),
        Some(project_path) => list_claude_sessions(&manager, &project_path, json),
    }
}

fn list_claude_projects(manager: &toolpath_claude::ClaudeConvo, json: bool) -> Result<()> {
    let projects = manager
        .list_projects()
        .map_err(|e| anyhow::anyhow!("{}", e))?;

    if json {
        let items: Vec<serde_json::Value> = projects
            .iter()
            .map(|p| serde_json::json!({ "path": p }))
            .collect();
        let output = serde_json::json!({
            "source": "claude",
            "projects": items,
        });
        println!("{}", serde_json::to_string_pretty(&output)?);
    } else {
        println!("Claude projects:");
        println!();
        if projects.is_empty() {
            println!("  (none)");
        } else {
            for p in &projects {
                println!("  {}", p);
            }
        }
    }
    Ok(())
}

fn list_claude_sessions(
    manager: &toolpath_claude::ClaudeConvo,
    project_path: &str,
    json: bool,
) -> Result<()> {
    let metadata = manager
        .list_conversation_metadata(project_path)
        .map_err(|e| anyhow::anyhow!("{}", e))?;

    if json {
        let items: Vec<serde_json::Value> = metadata
            .iter()
            .map(|m| {
                serde_json::json!({
                    "session_id": m.session_id,
                    "messages": m.message_count,
                    "started_at": m.started_at.map(|t| t.to_rfc3339()),
                    "last_activity": m.last_activity.map(|t| t.to_rfc3339()),
                })
            })
            .collect();
        let output = serde_json::json!({
            "source": "claude",
            "project": project_path,
            "sessions": items,
        });
        println!("{}", serde_json::to_string_pretty(&output)?);
    } else {
        println!("Sessions for {}:", project_path);
        println!();
        if metadata.is_empty() {
            println!("  (none)");
        } else {
            for m in &metadata {
                let date = m
                    .last_activity
                    .map(|t| t.format("%Y-%m-%d %H:%M").to_string())
                    .unwrap_or_else(|| "unknown".to_string());
                println!("  {} {:>4} msgs  {}", &m.session_id, m.message_count, date);
            }
        }
    }
    Ok(())
}

#[cfg(not(target_os = "emscripten"))]
fn truncate(s: &str, max: usize) -> String {
    if s.chars().count() <= max {
        s.to_string()
    } else {
        let truncated: String = s.chars().take(max - 3).collect();
        format!("{}...", truncated)
    }
}

#[cfg(all(test, not(target_os = "emscripten")))]
mod tests {
    use super::*;

    fn init_temp_repo() -> (tempfile::TempDir, git2::Repository) {
        let dir = tempfile::tempdir().unwrap();
        let repo = git2::Repository::init(dir.path()).unwrap();
        let mut config = repo.config().unwrap();
        config.set_str("user.name", "Test User").unwrap();
        config.set_str("user.email", "test@example.com").unwrap();
        (dir, repo)
    }

    fn create_commit(
        repo: &git2::Repository,
        message: &str,
        file_name: &str,
        content: &str,
        parent: Option<&git2::Commit>,
    ) -> git2::Oid {
        let mut index = repo.index().unwrap();
        let file_path = repo.workdir().unwrap().join(file_name);
        std::fs::write(&file_path, content).unwrap();
        index.add_path(std::path::Path::new(file_name)).unwrap();
        index.write().unwrap();
        let tree_id = index.write_tree().unwrap();
        let tree = repo.find_tree(tree_id).unwrap();
        let sig = repo.signature().unwrap();
        let parents: Vec<&git2::Commit> = parent.into_iter().collect();
        repo.commit(Some("HEAD"), &sig, &sig, message, &tree, &parents)
            .unwrap()
    }

    #[test]
    fn test_run_git_human_readable() {
        let (dir, repo) = init_temp_repo();
        create_commit(&repo, "initial commit", "file.txt", "hello", None);

        let result = run_git(dir.path().to_path_buf(), "origin".to_string(), false);
        assert!(result.is_ok());
    }

    #[test]
    fn test_run_git_json() {
        let (dir, repo) = init_temp_repo();
        create_commit(&repo, "initial commit", "file.txt", "hello", None);

        let result = run_git(dir.path().to_path_buf(), "origin".to_string(), true);
        assert!(result.is_ok());
    }

    #[test]
    fn test_run_git_invalid_repo() {
        let dir = tempfile::tempdir().unwrap();
        let result = run_git(dir.path().to_path_buf(), "origin".to_string(), false);
        assert!(result.is_err());
    }

    #[test]
    fn test_truncate_short() {
        assert_eq!(truncate("hello", 10), "hello");
    }

    #[test]
    fn test_truncate_exact() {
        assert_eq!(truncate("hello", 5), "hello");
    }

    #[test]
    fn test_truncate_long() {
        let result = truncate("hello world, this is a long string", 15);
        assert!(result.ends_with("..."));
        assert_eq!(result.chars().count(), 15);
    }

    #[test]
    fn test_truncate_multibyte() {
        let result = truncate("日本語のテスト文字列です", 8);
        assert!(result.ends_with("..."));
        assert_eq!(result.chars().count(), 8);
    }

    fn setup_claude_manager() -> (tempfile::TempDir, toolpath_claude::ClaudeConvo) {
        let temp = tempfile::tempdir().unwrap();
        let claude_dir = temp.path().join(".claude");
        let project_dir = claude_dir.join("projects/-test-project");
        std::fs::create_dir_all(&project_dir).unwrap();

        let entry1 = r#"{"type":"user","uuid":"uuid-1","timestamp":"2024-01-01T00:00:00Z","cwd":"/test/project","message":{"role":"user","content":"Hello"}}"#;
        let entry2 = r#"{"type":"assistant","uuid":"uuid-2","timestamp":"2024-01-01T00:01:00Z","message":{"role":"assistant","content":"Hi there"}}"#;
        std::fs::write(
            project_dir.join("session-abc.jsonl"),
            format!("{}\n{}\n", entry1, entry2),
        )
        .unwrap();

        let resolver = toolpath_claude::PathResolver::new().with_claude_dir(&claude_dir);
        let manager = toolpath_claude::ClaudeConvo::with_resolver(resolver);
        (temp, manager)
    }

    #[test]
    fn test_list_claude_projects_human() {
        let (_temp, manager) = setup_claude_manager();
        let result = list_claude_projects(&manager, false);
        assert!(result.is_ok());
    }

    #[test]
    fn test_list_claude_projects_json() {
        let (_temp, manager) = setup_claude_manager();
        let result = list_claude_projects(&manager, true);
        assert!(result.is_ok());
    }

    #[test]
    fn test_list_claude_projects_empty() {
        let temp = tempfile::tempdir().unwrap();
        let claude_dir = temp.path().join(".claude");
        let projects_dir = claude_dir.join("projects");
        std::fs::create_dir_all(&projects_dir).unwrap();

        let resolver = toolpath_claude::PathResolver::new().with_claude_dir(&claude_dir);
        let manager = toolpath_claude::ClaudeConvo::with_resolver(resolver);

        let result = list_claude_projects(&manager, false);
        assert!(result.is_ok());
    }

    #[test]
    fn test_list_claude_sessions_human() {
        let (_temp, manager) = setup_claude_manager();
        let result = list_claude_sessions(&manager, "/test/project", false);
        assert!(result.is_ok());
    }

    #[test]
    fn test_list_claude_sessions_json() {
        let (_temp, manager) = setup_claude_manager();
        let result = list_claude_sessions(&manager, "/test/project", true);
        assert!(result.is_ok());
    }

    #[test]
    fn test_list_claude_sessions_empty() {
        let temp = tempfile::tempdir().unwrap();
        let claude_dir = temp.path().join(".claude");
        let projects_dir = claude_dir.join("projects/-empty-project");
        std::fs::create_dir_all(&projects_dir).unwrap();

        let resolver = toolpath_claude::PathResolver::new().with_claude_dir(&claude_dir);
        let manager = toolpath_claude::ClaudeConvo::with_resolver(resolver);

        let result = list_claude_sessions(&manager, "/empty/project", false);
        assert!(result.is_ok());
    }

    #[test]
    fn test_run_claude_projects() {
        let (_temp, manager) = setup_claude_manager();
        // Test the dispatch to list_claude_projects through run_claude-like path
        let result = list_claude_projects(&manager, false);
        assert!(result.is_ok());
    }
}