Skip to main content

tracevault_cli/commands/
init.rs

1use crate::api_client::ApiClient;
2use crate::config::TracevaultConfig;
3use std::fs;
4use std::io::{self, BufRead, IsTerminal, Write};
5use std::path::{Path, PathBuf};
6
7/// Which Claude Code settings file to install hooks into.
8#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
9pub enum ClaudeSettingsTarget {
10    /// .claude/settings.json — typically committed/shared with the team.
11    Shared,
12    /// .claude/settings.local.json — personal, conventionally git-ignored.
13    Local,
14}
15
16impl ClaudeSettingsTarget {
17    pub fn filename(self) -> &'static str {
18        match self {
19            ClaudeSettingsTarget::Shared => "settings.json",
20            ClaudeSettingsTarget::Local => "settings.local.json",
21        }
22    }
23
24    pub fn gitignore_entry(self) -> &'static str {
25        match self {
26            ClaudeSettingsTarget::Shared => ".claude/settings.json",
27            ClaudeSettingsTarget::Local => ".claude/settings.local.json",
28        }
29    }
30}
31
32/// Resolve which settings file to use. If the caller passed an explicit
33/// choice, honor it. Otherwise prompt interactively when stdin is a TTY,
34/// or fall back to Shared for non-interactive callers (CI, scripts, tests).
35fn resolve_claude_target(
36    explicit: Option<ClaudeSettingsTarget>,
37) -> io::Result<ClaudeSettingsTarget> {
38    if let Some(target) = explicit {
39        return Ok(target);
40    }
41    if !io::stdin().is_terminal() {
42        return Ok(ClaudeSettingsTarget::Shared);
43    }
44
45    let stdout = io::stdout();
46    let mut stdout = stdout.lock();
47    write!(
48        stdout,
49        "Install Claude Code hooks into [s]hared (.claude/settings.json) or [l]ocal (.claude/settings.local.json)? [s]: "
50    )?;
51    stdout.flush()?;
52
53    let mut line = String::new();
54    io::stdin().lock().read_line(&mut line)?;
55    let answer = line.trim().to_lowercase();
56    Ok(match answer.as_str() {
57        "l" | "local" => ClaudeSettingsTarget::Local,
58        _ => ClaudeSettingsTarget::Shared,
59    })
60}
61
62pub fn git_remote_url(project_root: &Path) -> Option<String> {
63    std::process::Command::new("git")
64        .args(["remote", "get-url", "origin"])
65        .current_dir(project_root)
66        .output()
67        .ok()
68        .filter(|o| o.status.success())
69        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
70        .filter(|s| !s.is_empty())
71}
72
73fn parse_github_org(remote_url: &str) -> Option<String> {
74    // SSH: git@github.com:VirtusLab/visdom-ai-tracing.git
75    if let Some(path) = remote_url.strip_prefix("git@github.com:") {
76        return path.split('/').next().map(String::from);
77    }
78    // HTTPS: https://github.com/VirtusLab/visdom-ai-tracing.git
79    if let Some(path) = remote_url
80        .strip_prefix("https://github.com/")
81        .or_else(|| remote_url.strip_prefix("http://github.com/"))
82    {
83        return path.split('/').next().map(String::from);
84    }
85    None
86}
87
88/// If `dir` is inside a LINKED git worktree (not the primary checkout), return
89/// the primary worktree root. Returns `None` for the primary checkout or a
90/// non-git directory.
91///
92/// A linked worktree has `git --git-dir` (e.g. `<primary>/.git/worktrees/<name>`)
93/// distinct from `git --git-common-dir` (`<primary>/.git`); in the primary
94/// checkout the two are equal. The primary root is the parent of the common dir.
95fn linked_worktree_primary(dir: &Path) -> Option<PathBuf> {
96    let output = std::process::Command::new("git")
97        .args(["rev-parse", "--git-dir", "--git-common-dir"])
98        .current_dir(dir)
99        .output()
100        .ok()?;
101    if !output.status.success() {
102        return None;
103    }
104    let stdout = String::from_utf8(output.stdout).ok()?;
105    let mut lines = stdout.lines();
106    let git_dir = lines.next()?.trim();
107    let git_common_dir = lines.next()?.trim();
108
109    // git may return paths relative to `dir`; join (absolute args replace the
110    // base) then canonicalize so the comparison is robust.
111    let git_dir = dir.join(git_dir).canonicalize().ok()?;
112    let git_common_dir = dir.join(git_common_dir).canonicalize().ok()?;
113
114    if git_dir == git_common_dir {
115        None // primary checkout
116    } else {
117        git_common_dir.parent().map(Path::to_path_buf)
118    }
119}
120
121pub async fn init_in_directory(
122    project_root: &Path,
123    server_url: Option<&str>,
124    claude_settings: Option<ClaudeSettingsTarget>,
125    no_gitignore: bool,
126) -> Result<ClaudeSettingsTarget, io::Error> {
127    // Check for git repository
128    if !project_root.join(".git").exists() {
129        return Err(io::Error::new(
130            io::ErrorKind::NotFound,
131            "Not a git repository. Run 'git init' first.",
132        ));
133    }
134
135    // Refuse to initialize from a linked worktree: TraceVault's `.tracevault/`,
136    // git hooks, and Claude settings all belong in the primary checkout (which
137    // every worktree shares). Initializing here would create a stray
138    // `.tracevault/` in this worktree instead. (In a linked worktree `.git` is a
139    // file, so the check above passes — this guard is what catches it.)
140    if let Some(primary) = linked_worktree_primary(project_root) {
141        return Err(io::Error::new(
142            io::ErrorKind::Unsupported,
143            format!(
144                "Run `tracevault init` from the primary checkout ({}), not a linked worktree. \
145                 cd there and run it again — all worktrees share the primary's .tracevault/.",
146                primary.display()
147            ),
148        ));
149    }
150
151    let target = resolve_claude_target(claude_settings)?;
152
153    // Create .tracevault/ directory
154    let config_dir = TracevaultConfig::config_dir(project_root);
155    fs::create_dir_all(&config_dir)?;
156    fs::create_dir_all(config_dir.join("sessions"))?;
157    fs::create_dir_all(config_dir.join("cache"))?;
158
159    // Keep tracevault's files local — update root .gitignore (unless opted out)
160    if !no_gitignore {
161        update_root_gitignore(project_root, target)?;
162    }
163
164    // Register repo on server if authenticated, server URL known, and git remote available
165    let remote_url = git_remote_url(project_root);
166    if remote_url.is_none() {
167        eprintln!("Warning: no git remote 'origin' configured. Skipping server registration.");
168        eprintln!("Run 'git remote add origin <url>' then 'tracevault sync' to register.");
169    }
170
171    // Extract org slug from GitHub remote URL
172    let org_slug = remote_url.as_deref().and_then(parse_github_org);
173
174    // Write config (include server_url and org_slug if available)
175    let mut config = TracevaultConfig::default();
176    if let Some(url) = server_url {
177        config.server_url = Some(url.to_string());
178    }
179    config.org_slug = org_slug.clone();
180    fs::write(
181        TracevaultConfig::config_path(project_root),
182        config.to_toml(),
183    )?;
184
185    // Install Claude Code hooks into the chosen settings file
186    install_claude_hooks(project_root, target)?;
187
188    // Install git hooks
189    install_git_hook(project_root)?;
190    install_post_commit_hook(project_root)?;
191
192    // Detect AI tools in the project
193    let detected = crate::hooks::detect_tools(project_root);
194    for tool in &detected {
195        println!("  Detected: {}", tool.name());
196    }
197
198    let (resolved_url, resolved_token) = crate::api_client::resolve_credentials(project_root);
199    let effective_url = server_url.map(String::from).or(resolved_url);
200
201    if resolved_token.is_none() {
202        eprintln!("Not logged in. Run 'tracevault login' to register this repo with the server.");
203    } else if let (Some(url), Some(remote), Some(slug)) = (effective_url, remote_url, org_slug) {
204        let client = ApiClient::new(&url, resolved_token.as_deref());
205        let repo_name = git_repo_name(project_root);
206
207        match client
208            .register_repo(
209                &slug,
210                crate::api_client::RegisterRepoRequest {
211                    repo_name,
212                    github_url: Some(remote),
213                },
214            )
215            .await
216        {
217            Ok(resp) => {
218                println!("Repo registered on server (id: {})", resp.repo_id);
219                // Save repo_id to config
220                if let Some(mut cfg) = TracevaultConfig::load(project_root) {
221                    cfg.repo_id = Some(resp.repo_id.to_string());
222                    let _ = fs::write(TracevaultConfig::config_path(project_root), cfg.to_toml());
223                }
224            }
225            Err(e) => {
226                let msg = e.to_string();
227                if msg.contains("404") {
228                    eprintln!("Warning: organization '{}' not found on the server.", slug);
229                    eprintln!(
230                        "Create it first at your TraceVault instance, then run 'tracevault sync'."
231                    );
232                } else if msg.contains("403") {
233                    eprintln!("Warning: you are not a member of organization '{}'.", slug);
234                } else {
235                    eprintln!("Warning: could not register repo on server: {e}");
236                }
237            }
238        }
239    }
240
241    Ok(target)
242}
243
244fn update_root_gitignore(
245    project_root: &Path,
246    target: ClaudeSettingsTarget,
247) -> Result<(), io::Error> {
248    let path = project_root.join(".gitignore");
249    let existing = if path.exists() {
250        fs::read_to_string(&path)?
251    } else {
252        String::new()
253    };
254
255    // Only ignore what `init` actually creates or modifies: the `.tracevault/`
256    // directory and the single Claude settings file we wrote hooks into. The
257    // other settings file is left untouched, so we don't add it here.
258    let needed: Vec<&str> = [".tracevault/", target.gitignore_entry()]
259        .iter()
260        .copied()
261        .filter(|entry| !existing.lines().any(|line| line.trim() == *entry))
262        .collect();
263
264    if needed.is_empty() {
265        return Ok(());
266    }
267
268    let mut content = existing;
269    if !content.is_empty() && !content.ends_with('\n') {
270        content.push('\n');
271    }
272    content.push_str("\n# TraceVault — local only, do not commit\n");
273    for entry in needed {
274        content.push_str(entry);
275        content.push('\n');
276    }
277
278    fs::write(path, content)
279}
280
281fn git_repo_name(project_root: &Path) -> String {
282    std::process::Command::new("git")
283        .args(["rev-parse", "--show-toplevel"])
284        .current_dir(project_root)
285        .output()
286        .ok()
287        .filter(|o| o.status.success())
288        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
289        .as_deref()
290        .and_then(|p| p.rsplit('/').next())
291        .map(String::from)
292        .unwrap_or_else(|| "unknown".into())
293}
294
295const HOOK_MARKER: &str = "# tracevault:enforce";
296const OLD_HOOK_MARKER: &str = "# tracevault:auto-push";
297
298fn install_git_hook(project_root: &Path) -> Result<(), io::Error> {
299    let hooks_dir = project_root.join(".git/hooks");
300    fs::create_dir_all(&hooks_dir)?;
301
302    let hook_path = hooks_dir.join("pre-push");
303    let tracevault_block = format!(
304        "{HOOK_MARKER}\ntracevault sync 2>/dev/null || true\ntracevault check || {{ echo \"tracevault: policy check failed\"; exit 1; }}\n"
305    );
306
307    if hook_path.exists() {
308        let existing = fs::read_to_string(&hook_path)?;
309
310        // Already has new-style hook
311        if existing.contains(HOOK_MARKER) {
312            return Ok(());
313        }
314
315        // Replace old-style hook block if present
316        if existing.contains(OLD_HOOK_MARKER) {
317            let mut new_content = String::new();
318            let mut skip = false;
319            for line in existing.lines() {
320                if line.contains(OLD_HOOK_MARKER) {
321                    skip = true;
322                    continue;
323                }
324                if skip {
325                    // Skip old tracevault lines (they start with "tracevault " or are empty continuations)
326                    if line.starts_with("tracevault ") {
327                        continue;
328                    }
329                    skip = false;
330                }
331                new_content.push_str(line);
332                new_content.push('\n');
333            }
334            if !new_content.ends_with('\n') {
335                new_content.push('\n');
336            }
337            new_content.push_str(&tracevault_block);
338            fs::write(&hook_path, new_content)?;
339        } else {
340            // Append to existing hook
341            let mut content = existing;
342            if !content.ends_with('\n') {
343                content.push('\n');
344            }
345            content.push_str(&tracevault_block);
346            fs::write(&hook_path, content)?;
347        }
348    } else {
349        let content = format!("#!/bin/sh\n{tracevault_block}");
350        fs::write(&hook_path, content)?;
351    }
352
353    // Make executable
354    #[cfg(unix)]
355    {
356        use std::os::unix::fs::PermissionsExt;
357        let mut perms = fs::metadata(&hook_path)?.permissions();
358        perms.set_mode(0o755);
359        fs::set_permissions(&hook_path, perms)?;
360    }
361
362    Ok(())
363}
364
365const POST_COMMIT_MARKER: &str = "# tracevault:post-commit";
366
367fn install_post_commit_hook(project_root: &Path) -> Result<(), io::Error> {
368    let hooks_dir = project_root.join(".git/hooks");
369    fs::create_dir_all(&hooks_dir)?;
370
371    let hook_path = hooks_dir.join("post-commit");
372    let tracevault_block = format!("{POST_COMMIT_MARKER}\ntracevault commit-push 2>/dev/null &\n");
373
374    if hook_path.exists() {
375        let existing = fs::read_to_string(&hook_path)?;
376
377        if existing.contains(POST_COMMIT_MARKER) {
378            return Ok(());
379        }
380
381        let mut content = existing;
382        if !content.ends_with('\n') {
383            content.push('\n');
384        }
385        content.push_str(&tracevault_block);
386        fs::write(&hook_path, content)?;
387    } else {
388        let content = format!("#!/bin/sh\n{tracevault_block}");
389        fs::write(&hook_path, content)?;
390    }
391
392    #[cfg(unix)]
393    {
394        use std::os::unix::fs::PermissionsExt;
395        let mut perms = fs::metadata(&hook_path)?.permissions();
396        perms.set_mode(0o755);
397        fs::set_permissions(&hook_path, perms)?;
398    }
399
400    Ok(())
401}
402
403fn install_claude_hooks(
404    project_root: &Path,
405    target: ClaudeSettingsTarget,
406) -> Result<(), io::Error> {
407    let claude_dir = project_root.join(".claude");
408    fs::create_dir_all(&claude_dir)?;
409
410    let filename = target.filename();
411    let settings_path = claude_dir.join(filename);
412    let mut settings: serde_json::Value = if settings_path.exists() {
413        let content = fs::read_to_string(&settings_path)?;
414        serde_json::from_str(&content).map_err(|e| {
415            io::Error::new(
416                io::ErrorKind::InvalidData,
417                format!("Failed to parse .claude/{filename}: {e}"),
418            )
419        })?
420    } else {
421        serde_json::json!({})
422    };
423
424    let hooks = tracevault_hooks();
425
426    // Merge hooks into existing settings
427    let settings_obj = settings.as_object_mut().ok_or_else(|| {
428        io::Error::new(
429            io::ErrorKind::InvalidData,
430            format!(".claude/{filename} is not a JSON object"),
431        )
432    })?;
433
434    settings_obj.insert("hooks".to_string(), hooks);
435
436    let formatted = serde_json::to_string_pretty(&settings)
437        .map_err(|e| io::Error::other(format!("Failed to serialize settings: {e}")))?;
438    fs::write(&settings_path, formatted)?;
439
440    Ok(())
441}
442
443pub fn tracevault_hooks() -> serde_json::Value {
444    serde_json::json!({
445        "PreToolUse": [{
446            "matcher": "Write|Edit|Bash",
447            "hooks": [{
448                "type": "command",
449                "command": "tracevault stream --event pre-tool-use",
450                "timeout": 10,
451                "statusMessage": "TraceVault: streaming pre-tool event"
452            }]
453        }],
454        "PostToolUse": [{
455            "matcher": "",
456            "hooks": [{
457                "type": "command",
458                "command": "tracevault stream --event post-tool-use",
459                "timeout": 10,
460                "statusMessage": "TraceVault: streaming post-tool event"
461            }]
462        }],
463        "Notification": [{
464            "matcher": "",
465            "hooks": [{
466                "type": "command",
467                "command": "tracevault stream --event notification",
468                "timeout": 10,
469                "statusMessage": "TraceVault: streaming notification"
470            }]
471        }],
472        "Stop": [{
473            "matcher": "",
474            "hooks": [{
475                "type": "command",
476                "command": "tracevault stream --event stop",
477                "timeout": 10,
478                "statusMessage": "TraceVault: finalizing session"
479            }]
480        }]
481    })
482}
483
484#[cfg(test)]
485mod tests {
486    use super::*;
487
488    #[test]
489    fn linked_worktree_primary_detects_linked_and_primary() {
490        let tmp = tempfile::tempdir().unwrap();
491        let repo = tmp.path().join("repo");
492        let wt = tmp.path().join("linked-wt");
493        std::fs::create_dir_all(&repo).unwrap();
494        crate::test_helpers::init_git_repo(&repo);
495        crate::test_helpers::add_worktree(&repo, &wt);
496
497        // Primary checkout → None.
498        assert!(
499            linked_worktree_primary(&repo).is_none(),
500            "primary checkout must not be flagged as a linked worktree"
501        );
502        // Linked worktree → Some(primary root).
503        let primary = linked_worktree_primary(&wt).expect("linked worktree must be detected");
504        assert_eq!(
505            primary.canonicalize().unwrap(),
506            repo.canonicalize().unwrap(),
507            "must resolve to the primary repo root"
508        );
509    }
510
511    #[test]
512    fn linked_worktree_primary_none_for_non_git() {
513        let tmp = tempfile::tempdir().unwrap();
514        assert!(
515            linked_worktree_primary(tmp.path()).is_none(),
516            "a non-git directory is not a linked worktree"
517        );
518    }
519
520    #[test]
521    fn parse_github_org_ssh() {
522        assert_eq!(
523            parse_github_org("git@github.com:myorg/myrepo.git"),
524            Some("myorg".into())
525        );
526    }
527
528    #[test]
529    fn parse_github_org_https() {
530        assert_eq!(
531            parse_github_org("https://github.com/myorg/myrepo"),
532            Some("myorg".into())
533        );
534    }
535
536    #[test]
537    fn parse_github_org_non_github_returns_none() {
538        assert_eq!(parse_github_org("https://gitlab.com/org/repo"), None);
539    }
540
541    #[test]
542    fn parse_github_org_invalid() {
543        assert_eq!(parse_github_org("not-a-url"), None);
544    }
545}