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;
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
88pub async fn init_in_directory(
89    project_root: &Path,
90    server_url: Option<&str>,
91    claude_settings: Option<ClaudeSettingsTarget>,
92    no_gitignore: bool,
93) -> Result<ClaudeSettingsTarget, io::Error> {
94    // Check for git repository
95    if !project_root.join(".git").exists() {
96        return Err(io::Error::new(
97            io::ErrorKind::NotFound,
98            "Not a git repository. Run 'git init' first.",
99        ));
100    }
101
102    let target = resolve_claude_target(claude_settings)?;
103
104    // Create .tracevault/ directory
105    let config_dir = TracevaultConfig::config_dir(project_root);
106    fs::create_dir_all(&config_dir)?;
107    fs::create_dir_all(config_dir.join("sessions"))?;
108    fs::create_dir_all(config_dir.join("cache"))?;
109
110    // Keep tracevault's files local — update root .gitignore (unless opted out)
111    if !no_gitignore {
112        update_root_gitignore(project_root, target)?;
113    }
114
115    // Register repo on server if authenticated, server URL known, and git remote available
116    let remote_url = git_remote_url(project_root);
117    if remote_url.is_none() {
118        eprintln!("Warning: no git remote 'origin' configured. Skipping server registration.");
119        eprintln!("Run 'git remote add origin <url>' then 'tracevault sync' to register.");
120    }
121
122    // Extract org slug from GitHub remote URL
123    let org_slug = remote_url.as_deref().and_then(parse_github_org);
124
125    // Write config (include server_url and org_slug if available)
126    let mut config = TracevaultConfig::default();
127    if let Some(url) = server_url {
128        config.server_url = Some(url.to_string());
129    }
130    config.org_slug = org_slug.clone();
131    fs::write(
132        TracevaultConfig::config_path(project_root),
133        config.to_toml(),
134    )?;
135
136    // Install Claude Code hooks into the chosen settings file
137    install_claude_hooks(project_root, target)?;
138
139    // Install git hooks
140    install_git_hook(project_root)?;
141    install_post_commit_hook(project_root)?;
142
143    // Detect AI tools in the project
144    let detected = crate::hooks::detect_tools(project_root);
145    for tool in &detected {
146        println!("  Detected: {}", tool.name());
147    }
148
149    let (resolved_url, resolved_token) = crate::api_client::resolve_credentials(project_root);
150    let effective_url = server_url.map(String::from).or(resolved_url);
151
152    if resolved_token.is_none() {
153        eprintln!("Not logged in. Run 'tracevault login' to register this repo with the server.");
154    } else if let (Some(url), Some(remote), Some(slug)) = (effective_url, remote_url, org_slug) {
155        let client = ApiClient::new(&url, resolved_token.as_deref());
156        let repo_name = git_repo_name(project_root);
157
158        match client
159            .register_repo(
160                &slug,
161                crate::api_client::RegisterRepoRequest {
162                    repo_name,
163                    github_url: Some(remote),
164                },
165            )
166            .await
167        {
168            Ok(resp) => {
169                println!("Repo registered on server (id: {})", resp.repo_id);
170                // Save repo_id to config
171                if let Some(mut cfg) = TracevaultConfig::load(project_root) {
172                    cfg.repo_id = Some(resp.repo_id.to_string());
173                    let _ = fs::write(TracevaultConfig::config_path(project_root), cfg.to_toml());
174                }
175            }
176            Err(e) => {
177                let msg = e.to_string();
178                if msg.contains("404") {
179                    eprintln!("Warning: organization '{}' not found on the server.", slug);
180                    eprintln!(
181                        "Create it first at your TraceVault instance, then run 'tracevault sync'."
182                    );
183                } else if msg.contains("403") {
184                    eprintln!("Warning: you are not a member of organization '{}'.", slug);
185                } else {
186                    eprintln!("Warning: could not register repo on server: {e}");
187                }
188            }
189        }
190    }
191
192    Ok(target)
193}
194
195fn update_root_gitignore(
196    project_root: &Path,
197    target: ClaudeSettingsTarget,
198) -> Result<(), io::Error> {
199    let path = project_root.join(".gitignore");
200    let existing = if path.exists() {
201        fs::read_to_string(&path)?
202    } else {
203        String::new()
204    };
205
206    // Only ignore what `init` actually creates or modifies: the `.tracevault/`
207    // directory and the single Claude settings file we wrote hooks into. The
208    // other settings file is left untouched, so we don't add it here.
209    let needed: Vec<&str> = [".tracevault/", target.gitignore_entry()]
210        .iter()
211        .copied()
212        .filter(|entry| !existing.lines().any(|line| line.trim() == *entry))
213        .collect();
214
215    if needed.is_empty() {
216        return Ok(());
217    }
218
219    let mut content = existing;
220    if !content.is_empty() && !content.ends_with('\n') {
221        content.push('\n');
222    }
223    content.push_str("\n# TraceVault — local only, do not commit\n");
224    for entry in needed {
225        content.push_str(entry);
226        content.push('\n');
227    }
228
229    fs::write(path, content)
230}
231
232fn git_repo_name(project_root: &Path) -> String {
233    std::process::Command::new("git")
234        .args(["rev-parse", "--show-toplevel"])
235        .current_dir(project_root)
236        .output()
237        .ok()
238        .filter(|o| o.status.success())
239        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
240        .as_deref()
241        .and_then(|p| p.rsplit('/').next())
242        .map(String::from)
243        .unwrap_or_else(|| "unknown".into())
244}
245
246const HOOK_MARKER: &str = "# tracevault:enforce";
247const OLD_HOOK_MARKER: &str = "# tracevault:auto-push";
248
249fn install_git_hook(project_root: &Path) -> Result<(), io::Error> {
250    let hooks_dir = project_root.join(".git/hooks");
251    fs::create_dir_all(&hooks_dir)?;
252
253    let hook_path = hooks_dir.join("pre-push");
254    let tracevault_block = format!(
255        "{HOOK_MARKER}\ntracevault sync 2>/dev/null || true\ntracevault check || {{ echo \"tracevault: policy check failed\"; exit 1; }}\n"
256    );
257
258    if hook_path.exists() {
259        let existing = fs::read_to_string(&hook_path)?;
260
261        // Already has new-style hook
262        if existing.contains(HOOK_MARKER) {
263            return Ok(());
264        }
265
266        // Replace old-style hook block if present
267        if existing.contains(OLD_HOOK_MARKER) {
268            let mut new_content = String::new();
269            let mut skip = false;
270            for line in existing.lines() {
271                if line.contains(OLD_HOOK_MARKER) {
272                    skip = true;
273                    continue;
274                }
275                if skip {
276                    // Skip old tracevault lines (they start with "tracevault " or are empty continuations)
277                    if line.starts_with("tracevault ") {
278                        continue;
279                    }
280                    skip = false;
281                }
282                new_content.push_str(line);
283                new_content.push('\n');
284            }
285            if !new_content.ends_with('\n') {
286                new_content.push('\n');
287            }
288            new_content.push_str(&tracevault_block);
289            fs::write(&hook_path, new_content)?;
290        } else {
291            // Append to existing hook
292            let mut content = existing;
293            if !content.ends_with('\n') {
294                content.push('\n');
295            }
296            content.push_str(&tracevault_block);
297            fs::write(&hook_path, content)?;
298        }
299    } else {
300        let content = format!("#!/bin/sh\n{tracevault_block}");
301        fs::write(&hook_path, content)?;
302    }
303
304    // Make executable
305    #[cfg(unix)]
306    {
307        use std::os::unix::fs::PermissionsExt;
308        let mut perms = fs::metadata(&hook_path)?.permissions();
309        perms.set_mode(0o755);
310        fs::set_permissions(&hook_path, perms)?;
311    }
312
313    Ok(())
314}
315
316const POST_COMMIT_MARKER: &str = "# tracevault:post-commit";
317
318fn install_post_commit_hook(project_root: &Path) -> Result<(), io::Error> {
319    let hooks_dir = project_root.join(".git/hooks");
320    fs::create_dir_all(&hooks_dir)?;
321
322    let hook_path = hooks_dir.join("post-commit");
323    let tracevault_block = format!("{POST_COMMIT_MARKER}\ntracevault commit-push 2>/dev/null &\n");
324
325    if hook_path.exists() {
326        let existing = fs::read_to_string(&hook_path)?;
327
328        if existing.contains(POST_COMMIT_MARKER) {
329            return Ok(());
330        }
331
332        let mut content = existing;
333        if !content.ends_with('\n') {
334            content.push('\n');
335        }
336        content.push_str(&tracevault_block);
337        fs::write(&hook_path, content)?;
338    } else {
339        let content = format!("#!/bin/sh\n{tracevault_block}");
340        fs::write(&hook_path, content)?;
341    }
342
343    #[cfg(unix)]
344    {
345        use std::os::unix::fs::PermissionsExt;
346        let mut perms = fs::metadata(&hook_path)?.permissions();
347        perms.set_mode(0o755);
348        fs::set_permissions(&hook_path, perms)?;
349    }
350
351    Ok(())
352}
353
354fn install_claude_hooks(
355    project_root: &Path,
356    target: ClaudeSettingsTarget,
357) -> Result<(), io::Error> {
358    let claude_dir = project_root.join(".claude");
359    fs::create_dir_all(&claude_dir)?;
360
361    let filename = target.filename();
362    let settings_path = claude_dir.join(filename);
363    let mut settings: serde_json::Value = if settings_path.exists() {
364        let content = fs::read_to_string(&settings_path)?;
365        serde_json::from_str(&content).map_err(|e| {
366            io::Error::new(
367                io::ErrorKind::InvalidData,
368                format!("Failed to parse .claude/{filename}: {e}"),
369            )
370        })?
371    } else {
372        serde_json::json!({})
373    };
374
375    let hooks = tracevault_hooks();
376
377    // Merge hooks into existing settings
378    let settings_obj = settings.as_object_mut().ok_or_else(|| {
379        io::Error::new(
380            io::ErrorKind::InvalidData,
381            format!(".claude/{filename} is not a JSON object"),
382        )
383    })?;
384
385    settings_obj.insert("hooks".to_string(), hooks);
386
387    let formatted = serde_json::to_string_pretty(&settings)
388        .map_err(|e| io::Error::other(format!("Failed to serialize settings: {e}")))?;
389    fs::write(&settings_path, formatted)?;
390
391    Ok(())
392}
393
394pub fn tracevault_hooks() -> serde_json::Value {
395    serde_json::json!({
396        "PreToolUse": [{
397            "matcher": "Write|Edit|Bash",
398            "hooks": [{
399                "type": "command",
400                "command": "tracevault stream --event pre-tool-use",
401                "timeout": 10,
402                "statusMessage": "TraceVault: streaming pre-tool event"
403            }]
404        }],
405        "PostToolUse": [{
406            "matcher": "",
407            "hooks": [{
408                "type": "command",
409                "command": "tracevault stream --event post-tool-use",
410                "timeout": 10,
411                "statusMessage": "TraceVault: streaming post-tool event"
412            }]
413        }],
414        "Notification": [{
415            "matcher": "",
416            "hooks": [{
417                "type": "command",
418                "command": "tracevault stream --event notification",
419                "timeout": 10,
420                "statusMessage": "TraceVault: streaming notification"
421            }]
422        }],
423        "Stop": [{
424            "matcher": "",
425            "hooks": [{
426                "type": "command",
427                "command": "tracevault stream --event stop",
428                "timeout": 10,
429                "statusMessage": "TraceVault: finalizing session"
430            }]
431        }]
432    })
433}
434
435#[cfg(test)]
436mod tests {
437    use super::*;
438
439    #[test]
440    fn parse_github_org_ssh() {
441        assert_eq!(
442            parse_github_org("git@github.com:myorg/myrepo.git"),
443            Some("myorg".into())
444        );
445    }
446
447    #[test]
448    fn parse_github_org_https() {
449        assert_eq!(
450            parse_github_org("https://github.com/myorg/myrepo"),
451            Some("myorg".into())
452        );
453    }
454
455    #[test]
456    fn parse_github_org_non_github_returns_none() {
457        assert_eq!(parse_github_org("https://gitlab.com/org/repo"), None);
458    }
459
460    #[test]
461    fn parse_github_org_invalid() {
462        assert_eq!(parse_github_org("not-a-url"), None);
463    }
464}