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:softwaremill/tracevault.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/softwaremill/tracevault.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 all tracevault files local — update root .gitignore (unless opted out)
111    if !no_gitignore {
112        update_root_gitignore(project_root)?;
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(project_root: &Path) -> Result<(), io::Error> {
196    let path = project_root.join(".gitignore");
197    let existing = if path.exists() {
198        fs::read_to_string(&path)?
199    } else {
200        String::new()
201    };
202
203    // Always gitignore both Claude settings files regardless of which target
204    // was chosen: settings.json contains hook config (personal install), and
205    // settings.local.json is the conventional per-user override file.
206    let needed: Vec<&str> = [
207        ".tracevault/",
208        ".claude/settings.json",
209        ".claude/settings.local.json",
210    ]
211    .iter()
212    .copied()
213    .filter(|entry| !existing.lines().any(|line| line.trim() == *entry))
214    .collect();
215
216    if needed.is_empty() {
217        return Ok(());
218    }
219
220    let mut content = existing;
221    if !content.is_empty() && !content.ends_with('\n') {
222        content.push('\n');
223    }
224    content.push_str("\n# TraceVault — local only, do not commit\n");
225    for entry in needed {
226        content.push_str(entry);
227        content.push('\n');
228    }
229
230    fs::write(path, content)
231}
232
233fn git_repo_name(project_root: &Path) -> String {
234    std::process::Command::new("git")
235        .args(["rev-parse", "--show-toplevel"])
236        .current_dir(project_root)
237        .output()
238        .ok()
239        .filter(|o| o.status.success())
240        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
241        .as_deref()
242        .and_then(|p| p.rsplit('/').next())
243        .map(String::from)
244        .unwrap_or_else(|| "unknown".into())
245}
246
247const HOOK_MARKER: &str = "# tracevault:enforce";
248const OLD_HOOK_MARKER: &str = "# tracevault:auto-push";
249
250fn install_git_hook(project_root: &Path) -> Result<(), io::Error> {
251    let hooks_dir = project_root.join(".git/hooks");
252    fs::create_dir_all(&hooks_dir)?;
253
254    let hook_path = hooks_dir.join("pre-push");
255    let tracevault_block = format!(
256        "{HOOK_MARKER}\ntracevault sync 2>/dev/null || true\ntracevault check || {{ echo \"tracevault: policy check failed\"; exit 1; }}\n"
257    );
258
259    if hook_path.exists() {
260        let existing = fs::read_to_string(&hook_path)?;
261
262        // Already has new-style hook
263        if existing.contains(HOOK_MARKER) {
264            return Ok(());
265        }
266
267        // Replace old-style hook block if present
268        if existing.contains(OLD_HOOK_MARKER) {
269            let mut new_content = String::new();
270            let mut skip = false;
271            for line in existing.lines() {
272                if line.contains(OLD_HOOK_MARKER) {
273                    skip = true;
274                    continue;
275                }
276                if skip {
277                    // Skip old tracevault lines (they start with "tracevault " or are empty continuations)
278                    if line.starts_with("tracevault ") {
279                        continue;
280                    }
281                    skip = false;
282                }
283                new_content.push_str(line);
284                new_content.push('\n');
285            }
286            if !new_content.ends_with('\n') {
287                new_content.push('\n');
288            }
289            new_content.push_str(&tracevault_block);
290            fs::write(&hook_path, new_content)?;
291        } else {
292            // Append to existing hook
293            let mut content = existing;
294            if !content.ends_with('\n') {
295                content.push('\n');
296            }
297            content.push_str(&tracevault_block);
298            fs::write(&hook_path, content)?;
299        }
300    } else {
301        let content = format!("#!/bin/sh\n{tracevault_block}");
302        fs::write(&hook_path, content)?;
303    }
304
305    // Make executable
306    #[cfg(unix)]
307    {
308        use std::os::unix::fs::PermissionsExt;
309        let mut perms = fs::metadata(&hook_path)?.permissions();
310        perms.set_mode(0o755);
311        fs::set_permissions(&hook_path, perms)?;
312    }
313
314    Ok(())
315}
316
317const POST_COMMIT_MARKER: &str = "# tracevault:post-commit";
318
319fn install_post_commit_hook(project_root: &Path) -> Result<(), io::Error> {
320    let hooks_dir = project_root.join(".git/hooks");
321    fs::create_dir_all(&hooks_dir)?;
322
323    let hook_path = hooks_dir.join("post-commit");
324    let tracevault_block = format!("{POST_COMMIT_MARKER}\ntracevault commit-push 2>/dev/null &\n");
325
326    if hook_path.exists() {
327        let existing = fs::read_to_string(&hook_path)?;
328
329        if existing.contains(POST_COMMIT_MARKER) {
330            return Ok(());
331        }
332
333        let mut content = existing;
334        if !content.ends_with('\n') {
335            content.push('\n');
336        }
337        content.push_str(&tracevault_block);
338        fs::write(&hook_path, content)?;
339    } else {
340        let content = format!("#!/bin/sh\n{tracevault_block}");
341        fs::write(&hook_path, content)?;
342    }
343
344    #[cfg(unix)]
345    {
346        use std::os::unix::fs::PermissionsExt;
347        let mut perms = fs::metadata(&hook_path)?.permissions();
348        perms.set_mode(0o755);
349        fs::set_permissions(&hook_path, perms)?;
350    }
351
352    Ok(())
353}
354
355fn install_claude_hooks(
356    project_root: &Path,
357    target: ClaudeSettingsTarget,
358) -> Result<(), io::Error> {
359    let claude_dir = project_root.join(".claude");
360    fs::create_dir_all(&claude_dir)?;
361
362    let filename = target.filename();
363    let settings_path = claude_dir.join(filename);
364    let mut settings: serde_json::Value = if settings_path.exists() {
365        let content = fs::read_to_string(&settings_path)?;
366        serde_json::from_str(&content).map_err(|e| {
367            io::Error::new(
368                io::ErrorKind::InvalidData,
369                format!("Failed to parse .claude/{filename}: {e}"),
370            )
371        })?
372    } else {
373        serde_json::json!({})
374    };
375
376    let hooks = tracevault_hooks();
377
378    // Merge hooks into existing settings
379    let settings_obj = settings.as_object_mut().ok_or_else(|| {
380        io::Error::new(
381            io::ErrorKind::InvalidData,
382            format!(".claude/{filename} is not a JSON object"),
383        )
384    })?;
385
386    settings_obj.insert("hooks".to_string(), hooks);
387
388    let formatted = serde_json::to_string_pretty(&settings)
389        .map_err(|e| io::Error::other(format!("Failed to serialize settings: {e}")))?;
390    fs::write(&settings_path, formatted)?;
391
392    Ok(())
393}
394
395pub fn tracevault_hooks() -> serde_json::Value {
396    serde_json::json!({
397        "PreToolUse": [{
398            "matcher": "Write|Edit|Bash",
399            "hooks": [{
400                "type": "command",
401                "command": "tracevault stream --event pre-tool-use",
402                "timeout": 10,
403                "statusMessage": "TraceVault: streaming pre-tool event"
404            }]
405        }],
406        "PostToolUse": [{
407            "matcher": "",
408            "hooks": [{
409                "type": "command",
410                "command": "tracevault stream --event post-tool-use",
411                "timeout": 10,
412                "statusMessage": "TraceVault: streaming post-tool event"
413            }]
414        }],
415        "Notification": [{
416            "matcher": "",
417            "hooks": [{
418                "type": "command",
419                "command": "tracevault stream --event notification",
420                "timeout": 10,
421                "statusMessage": "TraceVault: streaming notification"
422            }]
423        }],
424        "Stop": [{
425            "matcher": "",
426            "hooks": [{
427                "type": "command",
428                "command": "tracevault stream --event stop",
429                "timeout": 10,
430                "statusMessage": "TraceVault: finalizing session"
431            }]
432        }]
433    })
434}
435
436#[cfg(test)]
437mod tests {
438    use super::*;
439
440    #[test]
441    fn parse_github_org_ssh() {
442        assert_eq!(
443            parse_github_org("git@github.com:myorg/myrepo.git"),
444            Some("myorg".into())
445        );
446    }
447
448    #[test]
449    fn parse_github_org_https() {
450        assert_eq!(
451            parse_github_org("https://github.com/myorg/myrepo"),
452            Some("myorg".into())
453        );
454    }
455
456    #[test]
457    fn parse_github_org_non_github_returns_none() {
458        assert_eq!(parse_github_org("https://gitlab.com/org/repo"), None);
459    }
460
461    #[test]
462    fn parse_github_org_invalid() {
463        assert_eq!(parse_github_org("not-a-url"), None);
464    }
465}