Skip to main content

tracevault_cli/commands/
init.rs

1use crate::api_client::ApiClient;
2use crate::config::{user_config_path_in, TracevaultConfig, UserContext};
3use crate::context::Context;
4use std::fs;
5use std::io::{self, BufRead, IsTerminal, Write};
6use std::path::{Path, PathBuf};
7
8/// Which Claude Code settings file to install hooks into.
9#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
10pub enum ClaudeSettingsTarget {
11    /// .claude/settings.json — typically committed/shared with the team.
12    Shared,
13    /// .claude/settings.local.json — personal, conventionally git-ignored.
14    Local,
15}
16
17impl ClaudeSettingsTarget {
18    pub fn filename(self) -> &'static str {
19        match self {
20            ClaudeSettingsTarget::Shared => "settings.json",
21            ClaudeSettingsTarget::Local => "settings.local.json",
22        }
23    }
24
25    pub fn gitignore_entry(self) -> &'static str {
26        match self {
27            ClaudeSettingsTarget::Shared => ".claude/settings.json",
28            ClaudeSettingsTarget::Local => ".claude/settings.local.json",
29        }
30    }
31}
32
33/// Resolve which settings file to use. If the caller passed an explicit
34/// choice, honor it. Otherwise prompt interactively when stdin is a TTY,
35/// or fall back to Shared for non-interactive callers (CI, scripts, tests).
36fn resolve_claude_target(
37    explicit: Option<ClaudeSettingsTarget>,
38) -> io::Result<ClaudeSettingsTarget> {
39    if let Some(target) = explicit {
40        return Ok(target);
41    }
42    if !io::stdin().is_terminal() {
43        return Ok(ClaudeSettingsTarget::Shared);
44    }
45
46    let stdout = io::stdout();
47    let mut stdout = stdout.lock();
48    write!(
49        stdout,
50        "Install Claude Code hooks into [s]hared (.claude/settings.json) or [l]ocal (.claude/settings.local.json)? [s]: "
51    )?;
52    stdout.flush()?;
53
54    let mut line = String::new();
55    io::stdin().lock().read_line(&mut line)?;
56    let answer = line.trim().to_lowercase();
57    Ok(match answer.as_str() {
58        "l" | "local" => ClaudeSettingsTarget::Local,
59        _ => ClaudeSettingsTarget::Shared,
60    })
61}
62
63pub fn git_remote_url(project_root: &Path) -> Option<String> {
64    std::process::Command::new("git")
65        .args(["remote", "get-url", "origin"])
66        .current_dir(project_root)
67        .output()
68        .ok()
69        .filter(|o| o.status.success())
70        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
71        .filter(|s| !s.is_empty())
72}
73
74fn parse_github_org(remote_url: &str) -> Option<String> {
75    // SSH: git@github.com:VirtusLab/visdom-ai-tracing.git
76    if let Some(path) = remote_url.strip_prefix("git@github.com:") {
77        return path.split('/').next().map(String::from);
78    }
79    // HTTPS: https://github.com/VirtusLab/visdom-ai-tracing.git
80    if let Some(path) = remote_url
81        .strip_prefix("https://github.com/")
82        .or_else(|| remote_url.strip_prefix("http://github.com/"))
83    {
84        return path.split('/').next().map(String::from);
85    }
86    None
87}
88
89/// If `dir` is inside a LINKED git worktree (not the primary checkout), return
90/// the primary worktree root. Returns `None` for the primary checkout or a
91/// non-git directory.
92///
93/// A linked worktree has `git --git-dir` (e.g. `<primary>/.git/worktrees/<name>`)
94/// distinct from `git --git-common-dir` (`<primary>/.git`); in the primary
95/// checkout the two are equal. The primary root is the parent of the common dir.
96fn linked_worktree_primary(dir: &Path) -> Option<PathBuf> {
97    let output = std::process::Command::new("git")
98        .args(["rev-parse", "--git-dir", "--git-common-dir"])
99        .current_dir(dir)
100        .output()
101        .ok()?;
102    if !output.status.success() {
103        return None;
104    }
105    let stdout = String::from_utf8(output.stdout).ok()?;
106    let mut lines = stdout.lines();
107    let git_dir = lines.next()?.trim();
108    let git_common_dir = lines.next()?.trim();
109
110    // git may return paths relative to `dir`; join (absolute args replace the
111    // base) then canonicalize so the comparison is robust.
112    let git_dir = dir.join(git_dir).canonicalize().ok()?;
113    let git_common_dir = dir.join(git_common_dir).canonicalize().ok()?;
114
115    if git_dir == git_common_dir {
116        None // primary checkout
117    } else {
118        git_common_dir.parent().map(Path::to_path_buf)
119    }
120}
121
122pub async fn init_in_directory(
123    project_root: &Path,
124    server_url: Option<&str>,
125    claude_settings: Option<ClaudeSettingsTarget>,
126    no_gitignore: bool,
127    user_context: UserContext,
128) -> Result<ClaudeSettingsTarget, io::Error> {
129    // Check for git repository
130    if !project_root.join(".git").exists() {
131        return Err(io::Error::new(
132            io::ErrorKind::NotFound,
133            "Not a git repository. Run 'git init' first.",
134        ));
135    }
136
137    // Refuse to initialize from a linked worktree: TraceVault's `.tracevault/`,
138    // git hooks, and Claude settings all belong in the primary checkout (which
139    // every worktree shares). Initializing here would create a stray
140    // `.tracevault/` in this worktree instead. (In a linked worktree `.git` is a
141    // file, so the check above passes — this guard is what catches it.)
142    if let Some(primary) = linked_worktree_primary(project_root) {
143        return Err(io::Error::new(
144            io::ErrorKind::Unsupported,
145            format!(
146                "Run `tracevault init` from the primary checkout ({}), not a linked worktree. \
147                 cd there and run it again — all worktrees share the primary's .tracevault/.",
148                primary.display()
149            ),
150        ));
151    }
152
153    let target = resolve_claude_target(claude_settings)?;
154
155    // Create .tracevault/ directory
156    let config_dir = TracevaultConfig::config_dir(project_root);
157    fs::create_dir_all(&config_dir)?;
158    fs::create_dir_all(config_dir.join("sessions"))?;
159    fs::create_dir_all(config_dir.join("cache"))?;
160    // Self-contained ignore for runtime artifacts, so this `.tracevault/` is
161    // safe even if the root .gitignore doesn't cover it.
162    TracevaultConfig::ensure_gitignore(&config_dir)?;
163
164    // Keep tracevault's files local — update root .gitignore (unless opted out)
165    if !no_gitignore {
166        update_root_gitignore(project_root, target)?;
167    }
168
169    // Register repo on server if authenticated, server URL known, and git remote available
170    let remote_url = git_remote_url(project_root);
171    if remote_url.is_none() {
172        eprintln!("Warning: no git remote 'origin' configured. Skipping server registration.");
173        eprintln!("Run 'git remote add origin <url>' then 'tracevault sync' to register.");
174    }
175
176    // Extract org slug from GitHub remote URL
177    let org_slug = remote_url.as_deref().and_then(parse_github_org);
178
179    // Write config (include server_url and org_slug if available)
180    let mut config = TracevaultConfig::default();
181    if let Some(url) = server_url {
182        config.server_url = Some(url.to_string());
183    }
184    config.org_slug = org_slug.clone();
185    config.user_context = Some(user_context);
186    fs::write(
187        TracevaultConfig::config_path(project_root),
188        config.to_toml(),
189    )?;
190
191    // Install Claude Code hooks into the chosen settings file
192    install_claude_hooks(project_root, target)?;
193
194    // Install git hooks
195    install_git_hook(project_root)?;
196    install_post_commit_hook(project_root)?;
197
198    // Detect AI tools in the project
199    let detected = crate::hooks::detect_tools(project_root);
200    for tool in &detected {
201        println!("  Detected: {}", tool.name());
202    }
203
204    let (resolved_url, resolved_token) = crate::api_client::resolve_credentials(project_root);
205    let effective_url = server_url.map(String::from).or(resolved_url);
206
207    if resolved_token.is_none() {
208        eprintln!("Not logged in. Run 'tracevault login' to register this repo with the server.");
209    } else if let (Some(url), Some(remote), Some(slug)) = (effective_url, remote_url, org_slug) {
210        let client = ApiClient::new(&url, resolved_token.as_deref());
211        let repo_name = git_repo_name(project_root);
212
213        match client
214            .register_repo(
215                &slug,
216                crate::api_client::RegisterRepoRequest {
217                    repo_name,
218                    github_url: Some(remote),
219                },
220            )
221            .await
222        {
223            Ok(resp) => {
224                println!("Repo registered on server (id: {})", resp.repo_id);
225                // Save repo_id to config
226                if let Some(mut cfg) = TracevaultConfig::load(project_root) {
227                    cfg.repo_id = Some(resp.repo_id.to_string());
228                    let _ = fs::write(TracevaultConfig::config_path(project_root), cfg.to_toml());
229                }
230            }
231            Err(e) => {
232                let msg = e.to_string();
233                if msg.contains("404") {
234                    eprintln!("Warning: organization '{}' not found on the server.", slug);
235                    eprintln!(
236                        "Create it first at your TraceVault instance, then run 'tracevault sync'."
237                    );
238                } else if msg.contains("403") {
239                    eprintln!("Warning: you are not a member of organization '{}'.", slug);
240                } else {
241                    eprintln!("Warning: could not register repo on server: {e}");
242                }
243            }
244        }
245    }
246
247    Ok(target)
248}
249
250fn update_root_gitignore(
251    project_root: &Path,
252    target: ClaudeSettingsTarget,
253) -> Result<(), io::Error> {
254    let path = project_root.join(".gitignore");
255    let existing = if path.exists() {
256        fs::read_to_string(&path)?
257    } else {
258        String::new()
259    };
260
261    // Only ignore what `init` actually creates or modifies: the `.tracevault/`
262    // directory and the single Claude settings file we wrote hooks into. The
263    // other settings file is left untouched, so we don't add it here.
264    let needed: Vec<&str> = [".tracevault/", target.gitignore_entry()]
265        .iter()
266        .copied()
267        .filter(|entry| !existing.lines().any(|line| line.trim() == *entry))
268        .collect();
269
270    if needed.is_empty() {
271        return Ok(());
272    }
273
274    let mut content = existing;
275    if !content.is_empty() && !content.ends_with('\n') {
276        content.push('\n');
277    }
278    content.push_str("\n# TraceVault — local only, do not commit\n");
279    for entry in needed {
280        content.push_str(entry);
281        content.push('\n');
282    }
283
284    fs::write(path, content)
285}
286
287fn git_repo_name(project_root: &Path) -> String {
288    std::process::Command::new("git")
289        .args(["rev-parse", "--show-toplevel"])
290        .current_dir(project_root)
291        .output()
292        .ok()
293        .filter(|o| o.status.success())
294        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
295        .as_deref()
296        .and_then(|p| p.rsplit('/').next())
297        .map(String::from)
298        .unwrap_or_else(|| "unknown".into())
299}
300
301const HOOK_MARKER: &str = "# tracevault:enforce";
302const OLD_HOOK_MARKER: &str = "# tracevault:auto-push";
303
304fn install_git_hook(project_root: &Path) -> Result<(), io::Error> {
305    let hooks_dir = project_root.join(".git/hooks");
306    fs::create_dir_all(&hooks_dir)?;
307
308    let hook_path = hooks_dir.join("pre-push");
309    let tracevault_block = format!(
310        "{HOOK_MARKER}\ntracevault sync 2>/dev/null || true\ntracevault check || {{ echo \"tracevault: policy check failed\"; exit 1; }}\n"
311    );
312
313    if hook_path.exists() {
314        let existing = fs::read_to_string(&hook_path)?;
315
316        // Already has new-style hook
317        if existing.contains(HOOK_MARKER) {
318            return Ok(());
319        }
320
321        // Replace old-style hook block if present
322        if existing.contains(OLD_HOOK_MARKER) {
323            let mut new_content = String::new();
324            let mut skip = false;
325            for line in existing.lines() {
326                if line.contains(OLD_HOOK_MARKER) {
327                    skip = true;
328                    continue;
329                }
330                if skip {
331                    // Skip old tracevault lines (they start with "tracevault " or are empty continuations)
332                    if line.starts_with("tracevault ") {
333                        continue;
334                    }
335                    skip = false;
336                }
337                new_content.push_str(line);
338                new_content.push('\n');
339            }
340            if !new_content.ends_with('\n') {
341                new_content.push('\n');
342            }
343            new_content.push_str(&tracevault_block);
344            fs::write(&hook_path, new_content)?;
345        } else {
346            // Append to existing hook
347            let mut content = existing;
348            if !content.ends_with('\n') {
349                content.push('\n');
350            }
351            content.push_str(&tracevault_block);
352            fs::write(&hook_path, content)?;
353        }
354    } else {
355        let content = format!("#!/bin/sh\n{tracevault_block}");
356        fs::write(&hook_path, content)?;
357    }
358
359    // Make executable
360    #[cfg(unix)]
361    {
362        use std::os::unix::fs::PermissionsExt;
363        let mut perms = fs::metadata(&hook_path)?.permissions();
364        perms.set_mode(0o755);
365        fs::set_permissions(&hook_path, perms)?;
366    }
367
368    Ok(())
369}
370
371const POST_COMMIT_MARKER: &str = "# tracevault:post-commit";
372
373fn install_post_commit_hook(project_root: &Path) -> Result<(), io::Error> {
374    let hooks_dir = project_root.join(".git/hooks");
375    fs::create_dir_all(&hooks_dir)?;
376
377    let hook_path = hooks_dir.join("post-commit");
378    let tracevault_block = format!("{POST_COMMIT_MARKER}\ntracevault commit-push 2>/dev/null &\n");
379
380    if hook_path.exists() {
381        let existing = fs::read_to_string(&hook_path)?;
382
383        if existing.contains(POST_COMMIT_MARKER) {
384            return Ok(());
385        }
386
387        let mut content = existing;
388        if !content.ends_with('\n') {
389            content.push('\n');
390        }
391        content.push_str(&tracevault_block);
392        fs::write(&hook_path, content)?;
393    } else {
394        let content = format!("#!/bin/sh\n{tracevault_block}");
395        fs::write(&hook_path, content)?;
396    }
397
398    #[cfg(unix)]
399    {
400        use std::os::unix::fs::PermissionsExt;
401        let mut perms = fs::metadata(&hook_path)?.permissions();
402        perms.set_mode(0o755);
403        fs::set_permissions(&hook_path, perms)?;
404    }
405
406    Ok(())
407}
408
409fn install_claude_hooks(
410    project_root: &Path,
411    target: ClaudeSettingsTarget,
412) -> Result<(), io::Error> {
413    let claude_dir = project_root.join(".claude");
414    fs::create_dir_all(&claude_dir)?;
415
416    let filename = target.filename();
417    let settings_path = claude_dir.join(filename);
418    let mut settings: serde_json::Value = if settings_path.exists() {
419        let content = fs::read_to_string(&settings_path)?;
420        serde_json::from_str(&content).map_err(|e| {
421            io::Error::new(
422                io::ErrorKind::InvalidData,
423                format!("Failed to parse .claude/{filename}: {e}"),
424            )
425        })?
426    } else {
427        serde_json::json!({})
428    };
429
430    let hooks = tracevault_hooks();
431
432    // Merge hooks into existing settings
433    let settings_obj = settings.as_object_mut().ok_or_else(|| {
434        io::Error::new(
435            io::ErrorKind::InvalidData,
436            format!(".claude/{filename} is not a JSON object"),
437        )
438    })?;
439
440    settings_obj.insert("hooks".to_string(), hooks);
441
442    let formatted = serde_json::to_string_pretty(&settings)
443        .map_err(|e| io::Error::other(format!("Failed to serialize settings: {e}")))?;
444    fs::write(&settings_path, formatted)?;
445
446    Ok(())
447}
448
449pub fn tracevault_hooks() -> serde_json::Value {
450    serde_json::json!({
451        "PreToolUse": [{
452            "matcher": "Write|Edit|Bash",
453            "hooks": [{
454                "type": "command",
455                "command": "tracevault stream --event pre-tool-use",
456                "timeout": 10,
457                "statusMessage": "TraceVault: streaming pre-tool event"
458            }]
459        }],
460        "PostToolUse": [{
461            "matcher": "",
462            "hooks": [{
463                "type": "command",
464                "command": "tracevault stream --event post-tool-use",
465                "timeout": 10,
466                "statusMessage": "TraceVault: streaming post-tool event"
467            }]
468        }],
469        "Notification": [{
470            "matcher": "",
471            "hooks": [{
472                "type": "command",
473                "command": "tracevault stream --event notification",
474                "timeout": 10,
475                "statusMessage": "TraceVault: streaming notification"
476            }]
477        }],
478        "Stop": [{
479            "matcher": "",
480            "hooks": [{
481                "type": "command",
482                "command": "tracevault stream --event stop",
483                "timeout": 10,
484                "statusMessage": "TraceVault: finalizing session"
485            }]
486        }],
487        "SessionStart": [{
488            "matcher": "",
489            "hooks": [{
490                "type": "command",
491                "command": "tracevault session-start",
492                "timeout": 10,
493                "statusMessage": "TraceVault: session start"
494            }]
495        }],
496        "UserPromptSubmit": [{
497            "matcher": "",
498            "hooks": [{
499                "type": "command",
500                "command": "tracevault user-prompt",
501                "timeout": 10,
502                "statusMessage": "TraceVault: policy reinforcement"
503            }]
504        }]
505    })
506}
507
508const GLOBAL_CLAUDE_MD_MARKER: &str = "<!-- tracevault:workspace-mode -->";
509
510const GLOBAL_CLAUDE_MD_BLOCK: &str = "\
511<!-- tracevault:workspace-mode -->
512## TraceVault (workspace mode)
513You may be running detached from any single repository. Before working on a repo, run
514`tracevault repo switch <path>` to bind tracing and fetch that repo's policies; treat its
515output as binding. Use `--path <path>` on `tracevault repo status` for a one-off. Repos must
516already be registered with TraceVault.
517";
518
519/// Join a constant file name to `base` and confirm the result stays directly
520/// within `base` — defense-in-depth so a path derived from the environment
521/// ($HOME) cannot escape the intended `.claude` directory.
522fn safe_join(base: &Path, name: &str) -> io::Result<PathBuf> {
523    let joined = base.join(name);
524    if joined.parent() != Some(base) {
525        return Err(io::Error::new(
526            io::ErrorKind::InvalidInput,
527            format!(
528                "refusing to access path outside {}: {}",
529                base.display(),
530                joined.display()
531            ),
532        ));
533    }
534    Ok(joined)
535}
536
537/// Merge our hook entries into an existing `settings["hooks"]` object, per
538/// event, appending our entry only if no existing entry in that event's
539/// array already has an inner hook with the same `command` (dedupe → makes
540/// repeated calls idempotent). Never removes or overwrites the user's other
541/// hooks or top-level keys.
542///
543/// Absent values (no top-level `settings`, no `hooks` key, no entry for a
544/// given event) are created fresh — that's fine. But if an EXISTING value
545/// has an unexpected shape (top-level `settings` isn't an object, an
546/// existing `hooks` isn't an object, or an existing per-event value isn't an
547/// array), this errors loudly instead of silently discarding it, mirroring
548/// `install_claude_hooks`'s treatment of a non-object settings file.
549fn merge_hooks(
550    settings: &mut serde_json::Value,
551    ours: &serde_json::Value,
552    path: &Path,
553) -> io::Result<()> {
554    if settings.is_null() {
555        *settings = serde_json::json!({});
556    }
557    let settings_obj = settings.as_object_mut().ok_or_else(|| {
558        io::Error::new(
559            io::ErrorKind::InvalidData,
560            format!("{} is not a JSON object", path.display()),
561        )
562    })?;
563
564    let hooks_value = settings_obj
565        .entry("hooks")
566        .or_insert_with(|| serde_json::json!({}));
567    let hooks_obj = hooks_value.as_object_mut().ok_or_else(|| {
568        io::Error::new(
569            io::ErrorKind::InvalidData,
570            format!("{} \"hooks\" key is not a JSON object", path.display()),
571        )
572    })?;
573
574    let Some(ours_obj) = ours.as_object() else {
575        return Ok(());
576    };
577
578    for (event, our_array) in ours_obj {
579        let Some(our_entries) = our_array.as_array() else {
580            continue;
581        };
582
583        let existing_value = hooks_obj
584            .entry(event.clone())
585            .or_insert_with(|| serde_json::json!([]));
586        let existing_array = existing_value.as_array_mut().ok_or_else(|| {
587            io::Error::new(
588                io::ErrorKind::InvalidData,
589                format!(
590                    "{} \"hooks\".\"{event}\" is not a JSON array",
591                    path.display()
592                ),
593            )
594        })?;
595
596        for our_entry in our_entries {
597            let our_command = entry_command(our_entry);
598            let already_present = existing_array
599                .iter()
600                .any(|existing_entry| entry_contains_command(existing_entry, our_command));
601            if !already_present {
602                existing_array.push(our_entry.clone());
603            }
604        }
605    }
606
607    Ok(())
608}
609
610/// Extract the inner `hooks[0].command` string from a hook-event entry, if
611/// present.
612fn entry_command(entry: &serde_json::Value) -> Option<&str> {
613    entry.get("hooks")?.get(0)?.get("command")?.as_str()
614}
615
616/// Whether any of `entry`'s inner `hooks[].command` values equal `cmd`. Unlike
617/// `entry_command` (which only looks at `hooks[0]`), this scans the whole
618/// inner `hooks` array — a user entry can have our command anywhere in it
619/// (e.g. `hooks[1]`), and missing that would let a duplicate get appended.
620fn entry_contains_command(entry: &serde_json::Value, cmd: Option<&str>) -> bool {
621    let Some(hooks) = entry.get("hooks").and_then(|h| h.as_array()) else {
622        return false;
623    };
624    hooks
625        .iter()
626        .any(|hook| hook.get("command").and_then(|c| c.as_str()) == cmd)
627}
628
629/// Install TraceVault's Claude Code hooks into `claude_dir/settings.json`
630/// (deep-merged, never clobbering existing hooks/keys) and append a
631/// workspace-mode instruction block to `claude_dir/CLAUDE.md` (idempotent,
632/// guarded by a marker comment). Intended for `tracevault init --global`,
633/// installing once for all Claude Code sessions rather than per-repo.
634pub fn install_global_hooks(claude_dir: &Path) -> io::Result<()> {
635    fs::create_dir_all(claude_dir)?;
636
637    // Canonicalize the base to defend against path traversal attacks.
638    // safe_join will verify that target files stay directly within this base.
639    let base = claude_dir.canonicalize()?;
640
641    // --- settings.json: deep-merge hooks ---
642    let settings_path = safe_join(&base, "settings.json")?;
643    let mut settings: serde_json::Value = if settings_path.exists() {
644        let content = fs::read_to_string(&settings_path)?;
645        serde_json::from_str(&content).map_err(|e| {
646            io::Error::new(
647                io::ErrorKind::InvalidData,
648                format!("Failed to parse {}: {e}", settings_path.display()),
649            )
650        })?
651    } else {
652        serde_json::json!({})
653    };
654
655    merge_hooks(&mut settings, &tracevault_hooks(), &settings_path)?;
656
657    let formatted = serde_json::to_string_pretty(&settings)
658        .map_err(|e| io::Error::other(format!("Failed to serialize settings: {e}")))?;
659    // Write to a temp file in the same directory, then atomically rename over
660    // the target so a crash or ENOSPC mid-write can never truncate/corrupt
661    // the user's global settings.json.
662    let tmp_settings_path = settings_path.with_extension("json.tmp");
663    fs::write(&tmp_settings_path, formatted)?;
664    fs::rename(&tmp_settings_path, &settings_path)?;
665
666    // --- CLAUDE.md: append instruction block, idempotently ---
667    let claude_md_path = safe_join(&base, "CLAUDE.md")?;
668    let existing = if claude_md_path.exists() {
669        fs::read_to_string(&claude_md_path)?
670    } else {
671        String::new()
672    };
673
674    if !existing.contains(GLOBAL_CLAUDE_MD_MARKER) {
675        let mut content = existing;
676        if !content.is_empty() && !content.ends_with('\n') {
677            content.push('\n');
678        }
679        if !content.is_empty() {
680            content.push('\n');
681        }
682        content.push_str(GLOBAL_CLAUDE_MD_BLOCK);
683        fs::write(&claude_md_path, content)?;
684    }
685
686    Ok(())
687}
688
689/// Write the user-level `config.toml` (under `config_root`) carrying the
690/// user-context setting. An EXISTING user config is preserved (this mirrors the
691/// "don't clobber" contract of the global-hooks install): `requested` overrides
692/// the user_context when a flag was given; otherwise an existing value is kept,
693/// and only a first-time setup (no existing config) defaults to enabled.
694/// When the resulting layer is enabled, the referenced context file is seeded
695/// (empty) if absent — a custom `--user-context <path>` seeds THAT file, a
696/// disabled layer seeds nothing. Returns the active context file path (the file
697/// the hook will read), or `None` when the layer is disabled. Used by `init --global`.
698pub fn write_global_user_config_in(
699    config_root: &Path,
700    requested: Option<UserContext>,
701) -> io::Result<Option<PathBuf>> {
702    fs::create_dir_all(config_root)?;
703    // Preserve an existing (valid) user config; malformed/missing → start fresh.
704    let mut config = crate::config::try_load_user_config_in(config_root)
705        .ok()
706        .flatten()
707        .unwrap_or_default();
708    // Requested flag wins; else keep an existing value; else first-run default = enabled.
709    let user_context = requested
710        .or_else(|| config.user_context.clone())
711        .unwrap_or(UserContext::Toggle(true));
712    let active = user_context
713        .resolve()
714        .map(|_| user_context.path_in(config_root));
715    config.user_context = Some(user_context);
716    fs::write(user_config_path_in(config_root), config.to_toml())?;
717    if let Some(ref ctx_path) = active {
718        if !ctx_path.exists() {
719            Context::default().save_to(ctx_path)?;
720        }
721    }
722    Ok(active)
723}
724
725#[cfg(test)]
726mod tests {
727    use super::*;
728
729    #[test]
730    fn linked_worktree_primary_detects_linked_and_primary() {
731        let tmp = tempfile::tempdir().unwrap();
732        let repo = tmp.path().join("repo");
733        let wt = tmp.path().join("linked-wt");
734        std::fs::create_dir_all(&repo).unwrap();
735        crate::test_helpers::init_git_repo(&repo);
736        crate::test_helpers::add_worktree(&repo, &wt);
737
738        // Primary checkout → None.
739        assert!(
740            linked_worktree_primary(&repo).is_none(),
741            "primary checkout must not be flagged as a linked worktree"
742        );
743        // Linked worktree → Some(primary root).
744        let primary = linked_worktree_primary(&wt).expect("linked worktree must be detected");
745        assert_eq!(
746            primary.canonicalize().unwrap(),
747            repo.canonicalize().unwrap(),
748            "must resolve to the primary repo root"
749        );
750    }
751
752    #[test]
753    fn linked_worktree_primary_none_for_non_git() {
754        let tmp = tempfile::tempdir().unwrap();
755        assert!(
756            linked_worktree_primary(tmp.path()).is_none(),
757            "a non-git directory is not a linked worktree"
758        );
759    }
760
761    #[test]
762    fn parse_github_org_ssh() {
763        assert_eq!(
764            parse_github_org("git@github.com:myorg/myrepo.git"),
765            Some("myorg".into())
766        );
767    }
768
769    #[test]
770    fn parse_github_org_https() {
771        assert_eq!(
772            parse_github_org("https://github.com/myorg/myrepo"),
773            Some("myorg".into())
774        );
775    }
776
777    #[test]
778    fn parse_github_org_non_github_returns_none() {
779        assert_eq!(parse_github_org("https://gitlab.com/org/repo"), None);
780    }
781
782    #[test]
783    fn parse_github_org_invalid() {
784        assert_eq!(parse_github_org("not-a-url"), None);
785    }
786
787    #[test]
788    fn merge_hooks_into_empty_settings_adds_all_our_events() {
789        let mut settings = serde_json::json!({});
790        let ours = tracevault_hooks();
791        merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
792
793        let hooks = settings.get("hooks").unwrap();
794        for event in [
795            "PreToolUse",
796            "PostToolUse",
797            "Notification",
798            "Stop",
799            "SessionStart",
800            "UserPromptSubmit",
801        ] {
802            assert!(hooks.get(event).is_some(), "missing event {event}");
803        }
804    }
805
806    #[test]
807    fn merge_hooks_preserves_unrelated_user_hook_and_keys() {
808        let mut settings = serde_json::json!({
809            "model": "opus",
810            "hooks": {
811                "PreToolUse": [{
812                    "matcher": "",
813                    "hooks": [{ "type": "command", "command": "my-own-hook" }]
814                }]
815            }
816        });
817        let ours = tracevault_hooks();
818        merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
819
820        // Other top-level keys preserved.
821        assert_eq!(settings.get("model").unwrap(), "opus");
822
823        let pre_tool_use = settings["hooks"]["PreToolUse"].as_array().unwrap();
824        // Both the user's own hook and ours are present.
825        assert_eq!(pre_tool_use.len(), 2);
826        let commands: Vec<&str> = pre_tool_use
827            .iter()
828            .map(|e| entry_command(e).unwrap())
829            .collect();
830        assert!(commands.contains(&"my-own-hook"));
831        assert!(commands.contains(&"tracevault stream --event pre-tool-use"));
832
833        // Other events were added fresh.
834        assert!(settings["hooks"]["SessionStart"].is_array());
835    }
836
837    #[test]
838    fn merge_hooks_is_idempotent() {
839        let mut settings = serde_json::json!({});
840        let ours = tracevault_hooks();
841        merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
842        merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
843
844        for event in [
845            "PreToolUse",
846            "PostToolUse",
847            "Notification",
848            "Stop",
849            "SessionStart",
850            "UserPromptSubmit",
851        ] {
852            let arr = settings["hooks"][event].as_array().unwrap();
853            assert_eq!(arr.len(), 1, "event {event} should not be duplicated");
854        }
855    }
856
857    #[test]
858    fn merge_hooks_dedupes_command_found_in_non_first_inner_hook() {
859        // The existing PreToolUse entry has our command at hooks[1], not
860        // hooks[0] — a naive `entry_command` (hooks[0] only) comparison would
861        // miss it and append a duplicate entry.
862        let mut settings = serde_json::json!({
863            "hooks": {
864                "PreToolUse": [{
865                    "matcher": "Write|Edit|Bash",
866                    "hooks": [
867                        { "type": "command", "command": "other" },
868                        { "type": "command", "command": "tracevault stream --event pre-tool-use" }
869                    ]
870                }]
871            }
872        });
873        let ours = tracevault_hooks();
874        merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
875
876        let pre_tool_use = settings["hooks"]["PreToolUse"].as_array().unwrap();
877        assert_eq!(
878            pre_tool_use.len(),
879            1,
880            "must not append a duplicate PreToolUse entry when our command is present at hooks[1]"
881        );
882    }
883
884    #[test]
885    fn merge_hooks_errors_on_non_object_top_level() {
886        let mut settings = serde_json::json!([1, 2, 3]);
887        let ours = tracevault_hooks();
888        let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
889        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
890        assert!(err.to_string().contains("settings.json"));
891    }
892
893    #[test]
894    fn merge_hooks_errors_on_non_object_top_level_number() {
895        let mut settings = serde_json::json!(42);
896        let ours = tracevault_hooks();
897        let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
898        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
899    }
900
901    #[test]
902    fn merge_hooks_errors_on_non_object_hooks() {
903        let mut settings = serde_json::json!({ "hooks": "not-an-object" });
904        let ours = tracevault_hooks();
905        let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
906        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
907        assert!(err.to_string().contains("hooks"));
908    }
909
910    #[test]
911    fn merge_hooks_errors_on_non_array_event_value() {
912        let mut settings = serde_json::json!({
913            "hooks": {
914                "PreToolUse": "not-an-array"
915            }
916        });
917        let ours = tracevault_hooks();
918        let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
919        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
920        assert!(err.to_string().contains("PreToolUse"));
921    }
922
923    #[test]
924    fn install_global_hooks_writes_settings_and_claude_md() {
925        let tmp = tempfile::tempdir().unwrap();
926        let claude_dir = tmp.path().join(".claude");
927
928        install_global_hooks(&claude_dir).unwrap();
929
930        let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
931        let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
932        for event in ["SessionStart", "UserPromptSubmit", "PreToolUse"] {
933            assert!(settings["hooks"].get(event).is_some(), "missing {event}");
934        }
935
936        let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
937        assert!(claude_md.contains(GLOBAL_CLAUDE_MD_MARKER));
938    }
939
940    #[test]
941    fn install_global_hooks_is_idempotent() {
942        let tmp = tempfile::tempdir().unwrap();
943        let claude_dir = tmp.path().join(".claude");
944
945        install_global_hooks(&claude_dir).unwrap();
946        install_global_hooks(&claude_dir).unwrap();
947
948        let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
949        let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
950        for event in [
951            "PreToolUse",
952            "PostToolUse",
953            "Notification",
954            "Stop",
955            "SessionStart",
956            "UserPromptSubmit",
957        ] {
958            let arr = settings["hooks"][event].as_array().unwrap();
959            assert_eq!(arr.len(), 1, "event {event} should not be duplicated");
960        }
961
962        let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
963        let marker_count = claude_md.matches(GLOBAL_CLAUDE_MD_MARKER).count();
964        assert_eq!(
965            marker_count, 1,
966            "CLAUDE.md marker should appear exactly once"
967        );
968    }
969
970    #[test]
971    fn install_global_hooks_preserves_existing_claude_md_content() {
972        let tmp = tempfile::tempdir().unwrap();
973        let claude_dir = tmp.path().join(".claude");
974        fs::create_dir_all(&claude_dir).unwrap();
975        fs::write(
976            claude_dir.join("CLAUDE.md"),
977            "# My existing notes\nSome content.\n",
978        )
979        .unwrap();
980
981        install_global_hooks(&claude_dir).unwrap();
982
983        let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
984        assert!(claude_md.contains("# My existing notes"));
985        assert!(claude_md.contains(GLOBAL_CLAUDE_MD_MARKER));
986    }
987
988    #[test]
989    fn install_global_hooks_settings_write_is_atomic_no_tmp_leftover() {
990        let tmp = tempfile::tempdir().unwrap();
991        let claude_dir = tmp.path().join(".claude");
992
993        install_global_hooks(&claude_dir).unwrap();
994
995        let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
996        let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
997        assert!(settings["hooks"].get("SessionStart").is_some());
998
999        let leftover = fs::read_dir(&claude_dir)
1000            .unwrap()
1001            .filter_map(|e| e.ok())
1002            .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
1003        assert!(
1004            !leftover,
1005            "no settings.json.tmp should remain after install"
1006        );
1007    }
1008
1009    #[test]
1010    fn install_global_hooks_errors_on_non_object_settings_and_does_not_overwrite() {
1011        let tmp = tempfile::tempdir().unwrap();
1012        let claude_dir = tmp.path().join(".claude");
1013        fs::create_dir_all(&claude_dir).unwrap();
1014        let settings_path = claude_dir.join("settings.json");
1015        let original = "[1, 2, 3]";
1016        fs::write(&settings_path, original).unwrap();
1017
1018        let err = install_global_hooks(&claude_dir).unwrap_err();
1019        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1020
1021        // The original (malformed-for-our-purposes but validly-JSON) file
1022        // must be untouched, and no stray tmp file left behind.
1023        let after = fs::read_to_string(&settings_path).unwrap();
1024        assert_eq!(after, original);
1025        let leftover = fs::read_dir(&claude_dir)
1026            .unwrap()
1027            .filter_map(|e| e.ok())
1028            .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
1029        assert!(!leftover, "no tmp file should be left behind on error");
1030    }
1031
1032    #[test]
1033    fn install_global_hooks_errors_on_non_object_hooks_key_and_does_not_overwrite() {
1034        let tmp = tempfile::tempdir().unwrap();
1035        let claude_dir = tmp.path().join(".claude");
1036        fs::create_dir_all(&claude_dir).unwrap();
1037        let settings_path = claude_dir.join("settings.json");
1038        let original = r#"{"hooks": "oops"}"#;
1039        fs::write(&settings_path, original).unwrap();
1040
1041        let err = install_global_hooks(&claude_dir).unwrap_err();
1042        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1043
1044        let after = fs::read_to_string(&settings_path).unwrap();
1045        assert_eq!(after, original);
1046    }
1047
1048    #[test]
1049    fn install_global_hooks_errors_on_non_array_event_and_does_not_overwrite() {
1050        let tmp = tempfile::tempdir().unwrap();
1051        let claude_dir = tmp.path().join(".claude");
1052        fs::create_dir_all(&claude_dir).unwrap();
1053        let settings_path = claude_dir.join("settings.json");
1054        let original = r#"{"hooks": {"PreToolUse": "oops"}}"#;
1055        fs::write(&settings_path, original).unwrap();
1056
1057        let err = install_global_hooks(&claude_dir).unwrap_err();
1058        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1059
1060        let after = fs::read_to_string(&settings_path).unwrap();
1061        assert_eq!(after, original);
1062    }
1063
1064    #[test]
1065    fn safe_join_allows_direct_child_file() {
1066        let tmp = tempfile::tempdir().unwrap();
1067        let base = tmp.path();
1068        let result = safe_join(base, "settings.json").unwrap();
1069        assert_eq!(result.parent(), Some(base));
1070        assert_eq!(result.file_name().unwrap(), "settings.json");
1071    }
1072
1073    #[test]
1074    fn safe_join_rejects_path_traversal() {
1075        let tmp = tempfile::tempdir().unwrap();
1076        let base = tmp.path();
1077        let result = safe_join(base, "../evil");
1078        assert!(result.is_err());
1079        let err = result.unwrap_err();
1080        assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
1081        assert!(err.to_string().contains("refusing to access path outside"));
1082    }
1083
1084    #[test]
1085    fn safe_join_rejects_absolute_path() {
1086        let tmp = tempfile::tempdir().unwrap();
1087        let base = tmp.path();
1088        let result = safe_join(base, "/etc/passwd");
1089        // An absolute path joined to a base will replace the base,
1090        // so parent will not equal base.
1091        assert!(result.is_err());
1092    }
1093
1094    #[test]
1095    fn write_global_user_config_enables_and_creates_context() {
1096        let root = tempfile::tempdir().unwrap();
1097        let active = write_global_user_config_in(root.path(), None).unwrap();
1098        let cfg = crate::config::try_load_user_config_in(root.path())
1099            .unwrap()
1100            .unwrap();
1101        // Validate against the INJECTED root (resolve_in), not tv_config_root():
1102        // a first-run default enables at the `context.json` under `root`.
1103        assert_eq!(
1104            cfg.user_context.unwrap().resolve_in(root.path()),
1105            Some(crate::config::default_user_context_path_in(root.path()))
1106        );
1107        let ctx = crate::config::default_user_context_path_in(root.path());
1108        assert_eq!(active, Some(ctx.clone()));
1109        assert!(ctx.exists());
1110    }
1111
1112    #[test]
1113    fn write_global_user_config_can_disable() {
1114        let root = tempfile::tempdir().unwrap();
1115        let active = write_global_user_config_in(
1116            root.path(),
1117            Some(crate::config::UserContext::Toggle(false)),
1118        )
1119        .unwrap();
1120        let cfg = crate::config::try_load_user_config_in(root.path())
1121            .unwrap()
1122            .unwrap();
1123        assert!(matches!(
1124            cfg.user_context,
1125            Some(crate::config::UserContext::Toggle(false))
1126        ));
1127        assert_eq!(active, None, "disabled → no active context path");
1128        // A disabled layer must NOT seed a context file.
1129        assert!(
1130            !crate::config::default_user_context_path_in(root.path()).exists(),
1131            "disabled user context must not create a context.json"
1132        );
1133    }
1134
1135    #[test]
1136    fn write_global_user_config_custom_path_seeds_that_file_only() {
1137        let root = tempfile::tempdir().unwrap();
1138        let custom = root.path().join("custom-ctx.json");
1139        let active = write_global_user_config_in(
1140            root.path(),
1141            Some(crate::config::UserContext::Path(
1142                custom.to_string_lossy().into_owned(),
1143            )),
1144        )
1145        .unwrap();
1146        assert_eq!(active, Some(custom.clone()));
1147        assert!(custom.exists(), "the configured custom path must be seeded");
1148        assert!(
1149            !crate::config::default_user_context_path_in(root.path()).exists(),
1150            "the default context.json must NOT be created when a custom path is configured"
1151        );
1152    }
1153
1154    #[test]
1155    fn write_global_user_config_preserves_existing_on_rerun_without_flags() {
1156        let root = tempfile::tempdir().unwrap();
1157        let custom = root.path().join("custom-ctx.json");
1158        // First run pins a custom path.
1159        write_global_user_config_in(
1160            root.path(),
1161            Some(crate::config::UserContext::Path(
1162                custom.to_string_lossy().into_owned(),
1163            )),
1164        )
1165        .unwrap();
1166        // Re-run with NO flags must NOT reset it back to the default.
1167        let active = write_global_user_config_in(root.path(), None).unwrap();
1168        assert_eq!(
1169            active,
1170            Some(custom.clone()),
1171            "re-run without flags must preserve the custom path"
1172        );
1173        let cfg = crate::config::try_load_user_config_in(root.path())
1174            .unwrap()
1175            .unwrap();
1176        assert_eq!(cfg.user_context.unwrap().path_in(root.path()), custom);
1177    }
1178}