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
420
421
#[cfg(not(target_os = "emscripten"))]
use anyhow::Context;
use anyhow::Result;
use clap::Subcommand;
use std::path::PathBuf;

#[derive(Subcommand, Debug)]
pub enum DeriveSource {
    /// Derive from git repository history
    Git {
        /// Path to the git repository
        #[arg(short, long, default_value = ".")]
        repo: PathBuf,

        /// Branch name(s). Format: `name` or `name:start`
        #[arg(short, long, required = true)]
        branch: Vec<String>,

        /// Global base commit (overrides per-branch starts)
        #[arg(long)]
        base: Option<String>,

        /// Remote name for URI generation
        #[arg(long, default_value = "origin")]
        remote: String,

        /// Graph title (for multi-branch output)
        #[arg(long)]
        title: Option<String>,
    },
    /// Derive from a GitHub pull request
    Github {
        /// PR URL (e.g. <https://github.com/owner/repo/pull/42>)
        #[arg(index = 1)]
        url: Option<String>,

        /// Repository in owner/repo format (alternative to URL)
        #[arg(short, long)]
        repo: Option<String>,

        /// Pull request number (required with --repo)
        #[arg(long)]
        pr: Option<u64>,

        /// Exclude CI check runs
        #[arg(long)]
        no_ci: bool,

        /// Exclude reviews and comments
        #[arg(long)]
        no_comments: bool,
    },
    /// Derive from Claude conversation logs
    Claude {
        /// Project path (e.g., /Users/alex/myproject)
        #[arg(short, long)]
        project: String,

        /// Specific session ID
        #[arg(short, long)]
        session: Option<String>,

        /// Process all sessions in the project
        #[arg(long)]
        all: bool,
    },
}

pub fn run(source: DeriveSource, pretty: bool) -> Result<()> {
    match source {
        DeriveSource::Git {
            repo,
            branch,
            base,
            remote,
            title,
        } => run_git(repo, branch, base, remote, title, pretty),
        DeriveSource::Github {
            url,
            repo,
            pr,
            no_ci,
            no_comments,
        } => run_github(url, repo, pr, no_ci, no_comments, pretty),
        DeriveSource::Claude {
            project,
            session,
            all,
        } => run_claude(project, session, all, pretty),
    }
}

fn run_git(
    repo_path: PathBuf,
    branches: Vec<String>,
    base: Option<String>,
    remote: String,
    title: Option<String>,
    pretty: bool,
) -> Result<()> {
    #[cfg(target_os = "emscripten")]
    {
        let _ = (repo_path, branches, base, remote, title, pretty);
        anyhow::bail!(
            "'path derive 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 config = toolpath_git::DeriveConfig {
            remote,
            title,
            base,
        };

        let doc = toolpath_git::derive(&repo, &branches, &config)?;

        let json = if pretty {
            doc.to_json_pretty()?
        } else {
            doc.to_json()?
        };

        println!("{}", json);
        Ok(())
    }
}

fn run_github(
    url: Option<String>,
    repo: Option<String>,
    pr: Option<u64>,
    no_ci: bool,
    no_comments: bool,
    pretty: bool,
) -> Result<()> {
    #[cfg(target_os = "emscripten")]
    {
        let _ = (url, repo, pr, no_ci, no_comments, pretty);
        anyhow::bail!("'path derive github' requires a native environment with network access");
    }

    #[cfg(not(target_os = "emscripten"))]
    {
        // Resolve owner/repo/pr from either a URL or --repo/--pr flags
        let (owner, repo_name, pr_number) = if let Some(url_str) = &url {
            let parsed = toolpath_github::parse_pr_url(url_str).ok_or_else(|| {
                anyhow::anyhow!("Invalid PR URL. Expected: https://github.com/owner/repo/pull/N")
            })?;
            (parsed.owner, parsed.repo, parsed.number)
        } else if let (Some(repo_str), Some(pr_num)) = (&repo, pr) {
            let (o, r) = repo_str
                .split_once('/')
                .ok_or_else(|| anyhow::anyhow!("Repository must be in owner/repo format"))?;
            (o.to_string(), r.to_string(), pr_num)
        } else {
            anyhow::bail!(
                "Provide a PR URL or both --repo and --pr.\n\
                 Usage: path derive github https://github.com/owner/repo/pull/42\n\
                 Usage: path derive github --repo owner/repo --pr 42"
            );
        };

        let token = toolpath_github::resolve_token()?;
        let config = toolpath_github::DeriveConfig {
            token,
            include_ci: !no_ci,
            include_comments: !no_comments,
            ..Default::default()
        };

        let path = toolpath_github::derive_pull_request(&owner, &repo_name, pr_number, &config)?;
        let doc = toolpath::v1::Document::Path(path);

        let json = if pretty {
            doc.to_json_pretty()?
        } else {
            doc.to_json()?
        };

        println!("{}", json);
        Ok(())
    }
}

fn run_claude(project: String, session: Option<String>, all: bool, pretty: bool) -> Result<()> {
    let manager = toolpath_claude::ClaudeConvo::new();
    run_claude_with_manager(&manager, project, session, all, pretty)
}

fn run_claude_with_manager(
    manager: &toolpath_claude::ClaudeConvo,
    project: String,
    session: Option<String>,
    all: bool,
    pretty: bool,
) -> Result<()> {
    let config = toolpath_claude::derive::DeriveConfig {
        project_path: Some(project.clone()),
        include_thinking: false,
    };

    let docs: Vec<toolpath::v1::Path> = if let Some(session_id) = session {
        let convo = manager
            .read_conversation(&project, &session_id)
            .map_err(|e| anyhow::anyhow!("{}", e))?;
        vec![toolpath_claude::derive::derive_path(&convo, &config)]
    } else if all {
        let convos = manager
            .read_all_conversations(&project)
            .map_err(|e| anyhow::anyhow!("{}", e))?;
        toolpath_claude::derive::derive_project(&convos, &config)
    } else {
        // Default: most recent conversation
        let convo = manager
            .most_recent_conversation(&project)
            .map_err(|e| anyhow::anyhow!("{}", e))?
            .ok_or_else(|| anyhow::anyhow!("No conversations found for project: {}", project))?;
        vec![toolpath_claude::derive::derive_path(&convo, &config)]
    };

    for path in &docs {
        let doc = toolpath::v1::Document::Path(path.clone());
        let json = if pretty {
            doc.to_json_pretty()?
        } else {
            doc.to_json()?
        };
        println!("{}", json);
    }

    Ok(())
}

#[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_single_branch() {
        let (dir, repo) = init_temp_repo();
        let oid = create_commit(&repo, "initial commit", "file.txt", "hello", None);
        let c1 = repo.find_commit(oid).unwrap();
        create_commit(&repo, "second", "file.txt", "world", Some(&c1));

        let default = toolpath_git::list_branches(&repo)
            .unwrap()
            .first()
            .unwrap()
            .name
            .clone();

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

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

        let default = toolpath_git::list_branches(&repo)
            .unwrap()
            .first()
            .unwrap()
            .name
            .clone();

        let result = run_git(
            dir.path().to_path_buf(),
            vec![default],
            None,
            "origin".to_string(),
            None,
            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(),
            vec!["main".to_string()],
            None,
            "origin".to_string(),
            None,
            false,
        );
        assert!(result.is_err());
    }

    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:00:01Z","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_run_claude_session() {
        let (_temp, manager) = setup_claude_manager();
        let result = run_claude_with_manager(
            &manager,
            "/test/project".to_string(),
            Some("session-abc".to_string()),
            false,
            false,
        );
        assert!(result.is_ok());
    }

    #[test]
    fn test_run_claude_session_pretty() {
        let (_temp, manager) = setup_claude_manager();
        let result = run_claude_with_manager(
            &manager,
            "/test/project".to_string(),
            Some("session-abc".to_string()),
            false,
            true,
        );
        assert!(result.is_ok());
    }

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

    #[test]
    fn test_run_claude_all() {
        let (_temp, manager) = setup_claude_manager();
        let result =
            run_claude_with_manager(&manager, "/test/project".to_string(), None, true, false);
        assert!(result.is_ok());
    }

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

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

        let result =
            run_claude_with_manager(&manager, "/empty/project".to_string(), None, false, false);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("No conversations found")
        );
    }
}