tracevault-cli 0.14.0

CLI tool for TraceVault - AI code tracing and attribution
Documentation
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
use crate::api_client::ApiClient;
use crate::config::TracevaultConfig;
use std::fs;
use std::io::{self, BufRead, IsTerminal, Write};
use std::path::Path;

/// Which Claude Code settings file to install hooks into.
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum ClaudeSettingsTarget {
    /// .claude/settings.json — typically committed/shared with the team.
    Shared,
    /// .claude/settings.local.json — personal, conventionally git-ignored.
    Local,
}

impl ClaudeSettingsTarget {
    pub fn filename(self) -> &'static str {
        match self {
            ClaudeSettingsTarget::Shared => "settings.json",
            ClaudeSettingsTarget::Local => "settings.local.json",
        }
    }

    pub fn gitignore_entry(self) -> &'static str {
        match self {
            ClaudeSettingsTarget::Shared => ".claude/settings.json",
            ClaudeSettingsTarget::Local => ".claude/settings.local.json",
        }
    }
}

/// Resolve which settings file to use. If the caller passed an explicit
/// choice, honor it. Otherwise prompt interactively when stdin is a TTY,
/// or fall back to Shared for non-interactive callers (CI, scripts, tests).
fn resolve_claude_target(
    explicit: Option<ClaudeSettingsTarget>,
) -> io::Result<ClaudeSettingsTarget> {
    if let Some(target) = explicit {
        return Ok(target);
    }
    if !io::stdin().is_terminal() {
        return Ok(ClaudeSettingsTarget::Shared);
    }

    let stdout = io::stdout();
    let mut stdout = stdout.lock();
    write!(
        stdout,
        "Install Claude Code hooks into [s]hared (.claude/settings.json) or [l]ocal (.claude/settings.local.json)? [s]: "
    )?;
    stdout.flush()?;

    let mut line = String::new();
    io::stdin().lock().read_line(&mut line)?;
    let answer = line.trim().to_lowercase();
    Ok(match answer.as_str() {
        "l" | "local" => ClaudeSettingsTarget::Local,
        _ => ClaudeSettingsTarget::Shared,
    })
}

pub fn git_remote_url(project_root: &Path) -> Option<String> {
    std::process::Command::new("git")
        .args(["remote", "get-url", "origin"])
        .current_dir(project_root)
        .output()
        .ok()
        .filter(|o| o.status.success())
        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
        .filter(|s| !s.is_empty())
}

fn parse_github_org(remote_url: &str) -> Option<String> {
    // SSH: git@github.com:softwaremill/tracevault.git
    if let Some(path) = remote_url.strip_prefix("git@github.com:") {
        return path.split('/').next().map(String::from);
    }
    // HTTPS: https://github.com/softwaremill/tracevault.git
    if let Some(path) = remote_url
        .strip_prefix("https://github.com/")
        .or_else(|| remote_url.strip_prefix("http://github.com/"))
    {
        return path.split('/').next().map(String::from);
    }
    None
}

pub async fn init_in_directory(
    project_root: &Path,
    server_url: Option<&str>,
    claude_settings: Option<ClaudeSettingsTarget>,
    no_gitignore: bool,
) -> Result<ClaudeSettingsTarget, io::Error> {
    // Check for git repository
    if !project_root.join(".git").exists() {
        return Err(io::Error::new(
            io::ErrorKind::NotFound,
            "Not a git repository. Run 'git init' first.",
        ));
    }

    let target = resolve_claude_target(claude_settings)?;

    // Create .tracevault/ directory
    let config_dir = TracevaultConfig::config_dir(project_root);
    fs::create_dir_all(&config_dir)?;
    fs::create_dir_all(config_dir.join("sessions"))?;
    fs::create_dir_all(config_dir.join("cache"))?;

    // Keep all tracevault files local — update root .gitignore (unless opted out)
    if !no_gitignore {
        update_root_gitignore(project_root)?;
    }

    // Register repo on server if authenticated, server URL known, and git remote available
    let remote_url = git_remote_url(project_root);
    if remote_url.is_none() {
        eprintln!("Warning: no git remote 'origin' configured. Skipping server registration.");
        eprintln!("Run 'git remote add origin <url>' then 'tracevault sync' to register.");
    }

    // Extract org slug from GitHub remote URL
    let org_slug = remote_url.as_deref().and_then(parse_github_org);

    // Write config (include server_url and org_slug if available)
    let mut config = TracevaultConfig::default();
    if let Some(url) = server_url {
        config.server_url = Some(url.to_string());
    }
    config.org_slug = org_slug.clone();
    fs::write(
        TracevaultConfig::config_path(project_root),
        config.to_toml(),
    )?;

    // Install Claude Code hooks into the chosen settings file
    install_claude_hooks(project_root, target)?;

    // Install git hooks
    install_git_hook(project_root)?;
    install_post_commit_hook(project_root)?;

    // Detect AI tools in the project
    let detected = crate::hooks::detect_tools(project_root);
    for tool in &detected {
        println!("  Detected: {}", tool.name());
    }

    let (resolved_url, resolved_token) = crate::api_client::resolve_credentials(project_root);
    let effective_url = server_url.map(String::from).or(resolved_url);

    if resolved_token.is_none() {
        eprintln!("Not logged in. Run 'tracevault login' to register this repo with the server.");
    } else if let (Some(url), Some(remote), Some(slug)) = (effective_url, remote_url, org_slug) {
        let client = ApiClient::new(&url, resolved_token.as_deref());
        let repo_name = git_repo_name(project_root);

        match client
            .register_repo(
                &slug,
                crate::api_client::RegisterRepoRequest {
                    repo_name,
                    github_url: Some(remote),
                },
            )
            .await
        {
            Ok(resp) => {
                println!("Repo registered on server (id: {})", resp.repo_id);
                // Save repo_id to config
                if let Some(mut cfg) = TracevaultConfig::load(project_root) {
                    cfg.repo_id = Some(resp.repo_id.to_string());
                    let _ = fs::write(TracevaultConfig::config_path(project_root), cfg.to_toml());
                }
            }
            Err(e) => {
                let msg = e.to_string();
                if msg.contains("404") {
                    eprintln!("Warning: organization '{}' not found on the server.", slug);
                    eprintln!(
                        "Create it first at your TraceVault instance, then run 'tracevault sync'."
                    );
                } else if msg.contains("403") {
                    eprintln!("Warning: you are not a member of organization '{}'.", slug);
                } else {
                    eprintln!("Warning: could not register repo on server: {e}");
                }
            }
        }
    }

    Ok(target)
}

fn update_root_gitignore(project_root: &Path) -> Result<(), io::Error> {
    let path = project_root.join(".gitignore");
    let existing = if path.exists() {
        fs::read_to_string(&path)?
    } else {
        String::new()
    };

    // Always gitignore both Claude settings files regardless of which target
    // was chosen: settings.json contains hook config (personal install), and
    // settings.local.json is the conventional per-user override file.
    let needed: Vec<&str> = [
        ".tracevault/",
        ".claude/settings.json",
        ".claude/settings.local.json",
    ]
    .iter()
    .copied()
    .filter(|entry| !existing.lines().any(|line| line.trim() == *entry))
    .collect();

    if needed.is_empty() {
        return Ok(());
    }

    let mut content = existing;
    if !content.is_empty() && !content.ends_with('\n') {
        content.push('\n');
    }
    content.push_str("\n# TraceVault — local only, do not commit\n");
    for entry in needed {
        content.push_str(entry);
        content.push('\n');
    }

    fs::write(path, content)
}

fn git_repo_name(project_root: &Path) -> String {
    std::process::Command::new("git")
        .args(["rev-parse", "--show-toplevel"])
        .current_dir(project_root)
        .output()
        .ok()
        .filter(|o| o.status.success())
        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
        .as_deref()
        .and_then(|p| p.rsplit('/').next())
        .map(String::from)
        .unwrap_or_else(|| "unknown".into())
}

const HOOK_MARKER: &str = "# tracevault:enforce";
const OLD_HOOK_MARKER: &str = "# tracevault:auto-push";

fn install_git_hook(project_root: &Path) -> Result<(), io::Error> {
    let hooks_dir = project_root.join(".git/hooks");
    fs::create_dir_all(&hooks_dir)?;

    let hook_path = hooks_dir.join("pre-push");
    let tracevault_block = format!(
        "{HOOK_MARKER}\ntracevault sync 2>/dev/null || true\ntracevault check || {{ echo \"tracevault: policy check failed\"; exit 1; }}\n"
    );

    if hook_path.exists() {
        let existing = fs::read_to_string(&hook_path)?;

        // Already has new-style hook
        if existing.contains(HOOK_MARKER) {
            return Ok(());
        }

        // Replace old-style hook block if present
        if existing.contains(OLD_HOOK_MARKER) {
            let mut new_content = String::new();
            let mut skip = false;
            for line in existing.lines() {
                if line.contains(OLD_HOOK_MARKER) {
                    skip = true;
                    continue;
                }
                if skip {
                    // Skip old tracevault lines (they start with "tracevault " or are empty continuations)
                    if line.starts_with("tracevault ") {
                        continue;
                    }
                    skip = false;
                }
                new_content.push_str(line);
                new_content.push('\n');
            }
            if !new_content.ends_with('\n') {
                new_content.push('\n');
            }
            new_content.push_str(&tracevault_block);
            fs::write(&hook_path, new_content)?;
        } else {
            // Append to existing hook
            let mut content = existing;
            if !content.ends_with('\n') {
                content.push('\n');
            }
            content.push_str(&tracevault_block);
            fs::write(&hook_path, content)?;
        }
    } else {
        let content = format!("#!/bin/sh\n{tracevault_block}");
        fs::write(&hook_path, content)?;
    }

    // Make executable
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mut perms = fs::metadata(&hook_path)?.permissions();
        perms.set_mode(0o755);
        fs::set_permissions(&hook_path, perms)?;
    }

    Ok(())
}

const POST_COMMIT_MARKER: &str = "# tracevault:post-commit";

fn install_post_commit_hook(project_root: &Path) -> Result<(), io::Error> {
    let hooks_dir = project_root.join(".git/hooks");
    fs::create_dir_all(&hooks_dir)?;

    let hook_path = hooks_dir.join("post-commit");
    let tracevault_block = format!("{POST_COMMIT_MARKER}\ntracevault commit-push 2>/dev/null &\n");

    if hook_path.exists() {
        let existing = fs::read_to_string(&hook_path)?;

        if existing.contains(POST_COMMIT_MARKER) {
            return Ok(());
        }

        let mut content = existing;
        if !content.ends_with('\n') {
            content.push('\n');
        }
        content.push_str(&tracevault_block);
        fs::write(&hook_path, content)?;
    } else {
        let content = format!("#!/bin/sh\n{tracevault_block}");
        fs::write(&hook_path, content)?;
    }

    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mut perms = fs::metadata(&hook_path)?.permissions();
        perms.set_mode(0o755);
        fs::set_permissions(&hook_path, perms)?;
    }

    Ok(())
}

fn install_claude_hooks(
    project_root: &Path,
    target: ClaudeSettingsTarget,
) -> Result<(), io::Error> {
    let claude_dir = project_root.join(".claude");
    fs::create_dir_all(&claude_dir)?;

    let filename = target.filename();
    let settings_path = claude_dir.join(filename);
    let mut settings: serde_json::Value = if settings_path.exists() {
        let content = fs::read_to_string(&settings_path)?;
        serde_json::from_str(&content).map_err(|e| {
            io::Error::new(
                io::ErrorKind::InvalidData,
                format!("Failed to parse .claude/{filename}: {e}"),
            )
        })?
    } else {
        serde_json::json!({})
    };

    let hooks = tracevault_hooks();

    // Merge hooks into existing settings
    let settings_obj = settings.as_object_mut().ok_or_else(|| {
        io::Error::new(
            io::ErrorKind::InvalidData,
            format!(".claude/{filename} is not a JSON object"),
        )
    })?;

    settings_obj.insert("hooks".to_string(), hooks);

    let formatted = serde_json::to_string_pretty(&settings)
        .map_err(|e| io::Error::other(format!("Failed to serialize settings: {e}")))?;
    fs::write(&settings_path, formatted)?;

    Ok(())
}

pub fn tracevault_hooks() -> serde_json::Value {
    serde_json::json!({
        "PreToolUse": [{
            "matcher": "Write|Edit|Bash",
            "hooks": [{
                "type": "command",
                "command": "tracevault stream --event pre-tool-use",
                "timeout": 10,
                "statusMessage": "TraceVault: streaming pre-tool event"
            }]
        }],
        "PostToolUse": [{
            "matcher": "",
            "hooks": [{
                "type": "command",
                "command": "tracevault stream --event post-tool-use",
                "timeout": 10,
                "statusMessage": "TraceVault: streaming post-tool event"
            }]
        }],
        "Notification": [{
            "matcher": "",
            "hooks": [{
                "type": "command",
                "command": "tracevault stream --event notification",
                "timeout": 10,
                "statusMessage": "TraceVault: streaming notification"
            }]
        }],
        "Stop": [{
            "matcher": "",
            "hooks": [{
                "type": "command",
                "command": "tracevault stream --event stop",
                "timeout": 10,
                "statusMessage": "TraceVault: finalizing session"
            }]
        }]
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_github_org_ssh() {
        assert_eq!(
            parse_github_org("git@github.com:myorg/myrepo.git"),
            Some("myorg".into())
        );
    }

    #[test]
    fn parse_github_org_https() {
        assert_eq!(
            parse_github_org("https://github.com/myorg/myrepo"),
            Some("myorg".into())
        );
    }

    #[test]
    fn parse_github_org_non_github_returns_none() {
        assert_eq!(parse_github_org("https://gitlab.com/org/repo"), None);
    }

    #[test]
    fn parse_github_org_invalid() {
        assert_eq!(parse_github_org("not-a-url"), None);
    }
}