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 crate::resolution::git_remote_url;
5use std::fs;
6use std::io::{self, BufRead, IsTerminal, Write};
7use std::path::{Path, PathBuf};
8
9/// Which Claude Code settings file to install hooks into.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
11pub enum ClaudeSettingsTarget {
12    /// .claude/settings.json — typically committed/shared with the team.
13    Shared,
14    /// .claude/settings.local.json — personal, conventionally git-ignored.
15    Local,
16}
17
18impl ClaudeSettingsTarget {
19    pub fn filename(self) -> &'static str {
20        match self {
21            ClaudeSettingsTarget::Shared => "settings.json",
22            ClaudeSettingsTarget::Local => "settings.local.json",
23        }
24    }
25
26    pub fn gitignore_entry(self) -> &'static str {
27        match self {
28            ClaudeSettingsTarget::Shared => ".claude/settings.json",
29            ClaudeSettingsTarget::Local => ".claude/settings.local.json",
30        }
31    }
32}
33
34/// Resolve which settings file to use. If the caller passed an explicit
35/// choice, honor it. Otherwise prompt interactively when stdin is a TTY,
36/// or fall back to Shared for non-interactive callers (CI, scripts, tests).
37fn resolve_claude_target(
38    explicit: Option<ClaudeSettingsTarget>,
39) -> io::Result<ClaudeSettingsTarget> {
40    if let Some(target) = explicit {
41        return Ok(target);
42    }
43    if !io::stdin().is_terminal() {
44        return Ok(ClaudeSettingsTarget::Shared);
45    }
46
47    let stdout = io::stdout();
48    let mut stdout = stdout.lock();
49    write!(
50        stdout,
51        "Install Claude Code hooks into [s]hared (.claude/settings.json) or [l]ocal (.claude/settings.local.json)? [s]: "
52    )?;
53    stdout.flush()?;
54
55    let mut line = String::new();
56    io::stdin().lock().read_line(&mut line)?;
57    let answer = line.trim().to_lowercase();
58    Ok(match answer.as_str() {
59        "l" | "local" => ClaudeSettingsTarget::Local,
60        _ => ClaudeSettingsTarget::Shared,
61    })
62}
63
64fn parse_github_org(remote_url: &str) -> Option<String> {
65    // SSH: git@github.com:VirtusLab/visdom-ai-tracing.git
66    if let Some(path) = remote_url.strip_prefix("git@github.com:") {
67        return path.split('/').next().map(String::from);
68    }
69    // HTTPS: https://github.com/VirtusLab/visdom-ai-tracing.git
70    if let Some(path) = remote_url
71        .strip_prefix("https://github.com/")
72        .or_else(|| remote_url.strip_prefix("http://github.com/"))
73    {
74        return path.split('/').next().map(String::from);
75    }
76    None
77}
78
79/// If `dir` is inside a LINKED git worktree (not the primary checkout), return
80/// the primary worktree root. Returns `None` for the primary checkout or a
81/// non-git directory.
82///
83/// A linked worktree has `git --git-dir` (e.g. `<primary>/.git/worktrees/<name>`)
84/// distinct from `git --git-common-dir` (`<primary>/.git`); in the primary
85/// checkout the two are equal. The primary root is the parent of the common dir.
86fn linked_worktree_primary(dir: &Path) -> Option<PathBuf> {
87    let output = std::process::Command::new("git")
88        .args(["rev-parse", "--git-dir", "--git-common-dir"])
89        .current_dir(dir)
90        .output()
91        .ok()?;
92    if !output.status.success() {
93        return None;
94    }
95    let stdout = String::from_utf8(output.stdout).ok()?;
96    let mut lines = stdout.lines();
97    let git_dir = lines.next()?.trim();
98    let git_common_dir = lines.next()?.trim();
99
100    // git may return paths relative to `dir`; join (absolute args replace the
101    // base) then canonicalize so the comparison is robust.
102    let git_dir = dir.join(git_dir).canonicalize().ok()?;
103    let git_common_dir = dir.join(git_common_dir).canonicalize().ok()?;
104
105    if git_dir == git_common_dir {
106        None // primary checkout
107    } else {
108        git_common_dir.parent().map(Path::to_path_buf)
109    }
110}
111
112/// Validate init flag combinations against the selected agent. `--claude-settings`
113/// selects between `.claude/settings.json` and `settings.local.json`, so it only
114/// applies to the Claude Code agent — `--agent codex` always writes
115/// `.codex/hooks.json`. Returns a human-readable error for an incompatible combo
116/// so the CLI rejects it instead of silently ignoring the flag.
117pub fn validate_init_flags(
118    agent: crate::agent::Agent,
119    claude_settings_set: bool,
120) -> Result<(), String> {
121    if matches!(
122        agent,
123        crate::agent::Agent::Codex | crate::agent::Agent::Gsd | crate::agent::Agent::OpenCode
124    ) && claude_settings_set
125    {
126        return Err("--claude-settings only applies to --agent claude-code".to_string());
127    }
128    Ok(())
129}
130
131pub async fn init_in_directory(
132    project_root: &Path,
133    server_url: Option<&str>,
134    claude_settings: Option<ClaudeSettingsTarget>,
135    no_gitignore: bool,
136    user_context: UserContext,
137    agent: crate::agent::Agent,
138) -> Result<String, io::Error> {
139    // Check for git repository
140    if !project_root.join(".git").exists() {
141        return Err(io::Error::new(
142            io::ErrorKind::NotFound,
143            "Not a git repository. Run 'git init' first.",
144        ));
145    }
146
147    // Refuse to initialize from a linked worktree: TraceVault's `.tracevault/`,
148    // git hooks, and Claude settings all belong in the primary checkout (which
149    // every worktree shares). Initializing here would create a stray
150    // `.tracevault/` in this worktree instead. (In a linked worktree `.git` is a
151    // file, so the check above passes — this guard is what catches it.)
152    if let Some(primary) = linked_worktree_primary(project_root) {
153        return Err(io::Error::new(
154            io::ErrorKind::Unsupported,
155            format!(
156                "Run `tracevault init` from the primary checkout ({}), not a linked worktree. \
157                 cd there and run it again — all worktrees share the primary's .tracevault/.",
158                primary.display()
159            ),
160        ));
161    }
162
163    // Resolve the hook-file gitignore entry per agent. Claude has a
164    // shared/local settings choice; Codex has a single .codex/hooks.json.
165    let (claude_target, hook_gitignore_entry): (Option<ClaudeSettingsTarget>, String) = match agent
166    {
167        crate::agent::Agent::ClaudeCode => {
168            let target = resolve_claude_target(claude_settings)?;
169            (Some(target), target.gitignore_entry().to_string())
170        }
171        crate::agent::Agent::Codex => (None, ".codex/hooks.json".to_string()),
172        // GSD (pi) itself creates `.gsd/settings.json` in the repo when
173        // `install_gsd_extension` shells out to `gsd install <dir> -l` (a
174        // project-local package registration, analogous to Claude's
175        // `.claude/settings.local.json`) — that's GSD's own local install
176        // state, not something the user should commit.
177        crate::agent::Agent::Gsd => (None, ".gsd/".to_string()),
178        // The OpenCode plugin is installed project-locally as
179        // `.opencode/plugins/tracevault.ts` — ignore the whole `.opencode/`
180        // directory rather than just the plugin file, in case OpenCode
181        // itself later writes other local state there.
182        crate::agent::Agent::OpenCode => (None, ".opencode/".to_string()),
183    };
184
185    // Create .tracevault/ directory
186    let config_dir = TracevaultConfig::config_dir(project_root);
187    fs::create_dir_all(&config_dir)?;
188    fs::create_dir_all(config_dir.join("sessions"))?;
189    fs::create_dir_all(config_dir.join("cache"))?;
190    // Self-contained ignore for runtime artifacts, so this `.tracevault/` is
191    // safe even if the root .gitignore doesn't cover it.
192    TracevaultConfig::ensure_gitignore(&config_dir)?;
193
194    // Keep tracevault's files local — update root .gitignore (unless opted out)
195    if !no_gitignore {
196        update_root_gitignore(project_root, &hook_gitignore_entry)?;
197    }
198
199    // Register repo on server if authenticated, server URL known, and git remote available
200    let remote_url = git_remote_url(project_root);
201    if remote_url.is_none() {
202        eprintln!("Warning: no git remote 'origin' configured. Skipping server registration.");
203        eprintln!("Run 'git remote add origin <url>' then 'tracevault sync' to register.");
204    }
205
206    // Extract org slug from GitHub remote URL
207    let org_slug = remote_url.as_deref().and_then(parse_github_org);
208
209    // Write config (include server_url and org_slug if available)
210    let mut config = TracevaultConfig::default();
211    if let Some(url) = server_url {
212        config.server_url = Some(url.to_string());
213    }
214    config.org_slug = org_slug.clone();
215    config.user_context = Some(user_context);
216    fs::write(
217        TracevaultConfig::config_path(project_root),
218        config.to_toml(),
219    )?;
220
221    // Install the selected agent's hooks.
222    match agent {
223        crate::agent::Agent::ClaudeCode => {
224            // `claude_target` is `Some` for the Claude agent by construction above.
225            let target =
226                claude_target.expect("claude settings target is resolved for the Claude agent");
227            install_claude_hooks(project_root, target)?;
228        }
229        crate::agent::Agent::Codex => install_codex_hooks(project_root)?,
230        crate::agent::Agent::Gsd => {
231            // GSD (pi) loads extensions from the user-global ~/.gsd/, not from
232            // anything in the repo, so even the repo-local `init` path installs
233            // there — the repo itself only needs the .tracevault/ binding + git
234            // hooks set up above, which the extension shells out to `tracevault`
235            // to use. `Some(project_root)` makes `install_gsd_extension` run
236            // `gsd install -l` from this repo, registering the extension as a
237            // project-local install.
238            install_gsd_extension(Some(project_root))?;
239        }
240        crate::agent::Agent::OpenCode => {
241            install_opencode_plugin(Some(project_root))?;
242        }
243    }
244
245    // Install git hooks
246    install_git_hook(project_root)?;
247    install_post_commit_hook(project_root)?;
248
249    // Detect AI tools in the project
250    let detected = crate::hooks::detect_tools(project_root);
251    for tool in &detected {
252        println!("  Detected: {}", tool.name());
253    }
254
255    let (resolved_url, resolved_token) = crate::api_client::resolve_credentials(project_root);
256    let effective_url = server_url.map(String::from).or(resolved_url);
257
258    if resolved_token.is_none() {
259        eprintln!("Not logged in. Run 'tracevault login' to register this repo with the server.");
260    } else if let (Some(url), Some(remote), Some(slug)) = (effective_url, remote_url, org_slug) {
261        let client = ApiClient::new(&url, resolved_token.as_deref());
262        let repo_name = git_repo_name(project_root);
263        // Captured before `remote` is moved into the request below, so the
264        // codebase-resolve step doesn't need to shell out to git again.
265        let origin_url = remote.clone();
266
267        match client
268            .register_repo(
269                &slug,
270                crate::api_client::RegisterRepoRequest {
271                    repo_name,
272                    github_url: Some(remote),
273                },
274            )
275            .await
276        {
277            Ok(resp) => {
278                println!("Repo registered on server (id: {})", resp.repo_id);
279                // Save repo_id to config
280                if let Some(mut cfg) = TracevaultConfig::load(project_root) {
281                    cfg.repo_id = Some(resp.repo_id.to_string());
282                    // Best-effort: resolve the codebase (deduped by normalized
283                    // remote URL) and surface it to the user. Must never fail
284                    // init — `repo_id` above stays authoritative for ingest;
285                    // `remote_id`/`codebase_name` here are recorded for
286                    // display only.
287                    if let Ok(Some(remote)) = client.resolve_remote(&slug, &origin_url).await {
288                        println!(
289                            "{}",
290                            crate::resolution::codebase_line(
291                                remote.name.as_deref(),
292                                &remote.normalized_url,
293                                &remote.clone_status
294                            )
295                        );
296                        cfg.remote_id = Some(remote.remote_id.to_string());
297                        cfg.codebase_name = remote.name.clone();
298                    }
299                    let _ = fs::write(TracevaultConfig::config_path(project_root), cfg.to_toml());
300                }
301            }
302            Err(e) => {
303                let msg = e.to_string();
304                if msg.contains("404") {
305                    eprintln!("Warning: organization '{}' not found on the server.", slug);
306                    eprintln!(
307                        "Create it first at your TraceVault instance, then run 'tracevault sync'."
308                    );
309                } else if msg.contains("403") {
310                    eprintln!("Warning: you are not a member of organization '{}'.", slug);
311                } else {
312                    eprintln!("Warning: could not register repo on server: {e}");
313                }
314            }
315        }
316    }
317
318    Ok(hook_gitignore_entry)
319}
320
321fn update_root_gitignore(project_root: &Path, settings_entry: &str) -> Result<(), io::Error> {
322    let path = project_root.join(".gitignore");
323    let existing = if path.exists() {
324        fs::read_to_string(&path)?
325    } else {
326        String::new()
327    };
328
329    // Only ignore what `init` actually creates or modifies: the `.tracevault/`
330    // directory and the single settings file we wrote hooks into. The
331    // other settings file is left untouched, so we don't add it here. An
332    // empty `settings_entry` means the agent writes nothing into the repo at
333    // all — skip it rather than appending a blank line.
334    let needed: Vec<&str> = [".tracevault/", settings_entry]
335        .iter()
336        .copied()
337        .filter(|entry| !entry.is_empty() && !existing.lines().any(|line| line.trim() == *entry))
338        .collect();
339
340    if needed.is_empty() {
341        return Ok(());
342    }
343
344    let mut content = existing;
345    if !content.is_empty() && !content.ends_with('\n') {
346        content.push('\n');
347    }
348    content.push_str("\n# TraceVault — local only, do not commit\n");
349    for entry in needed {
350        content.push_str(entry);
351        content.push('\n');
352    }
353
354    fs::write(path, content)
355}
356
357fn git_repo_name(project_root: &Path) -> String {
358    std::process::Command::new("git")
359        .args(["rev-parse", "--show-toplevel"])
360        .current_dir(project_root)
361        .output()
362        .ok()
363        .filter(|o| o.status.success())
364        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
365        .as_deref()
366        .and_then(|p| p.rsplit('/').next())
367        .map(String::from)
368        .unwrap_or_else(|| "unknown".into())
369}
370
371const HOOK_MARKER: &str = "# tracevault:enforce";
372const OLD_HOOK_MARKER: &str = "# tracevault:auto-push";
373
374fn install_git_hook(project_root: &Path) -> Result<(), io::Error> {
375    let hooks_dir = project_root.join(".git/hooks");
376    fs::create_dir_all(&hooks_dir)?;
377
378    let hook_path = hooks_dir.join("pre-push");
379    let tracevault_block = format!(
380        "{HOOK_MARKER}\ntracevault sync 2>/dev/null || true\ntracevault check || {{ echo \"tracevault: policy check failed\"; exit 1; }}\n"
381    );
382
383    if hook_path.exists() {
384        let existing = fs::read_to_string(&hook_path)?;
385
386        // Already has new-style hook
387        if existing.contains(HOOK_MARKER) {
388            return Ok(());
389        }
390
391        // Replace old-style hook block if present
392        if existing.contains(OLD_HOOK_MARKER) {
393            let mut new_content = String::new();
394            let mut skip = false;
395            for line in existing.lines() {
396                if line.contains(OLD_HOOK_MARKER) {
397                    skip = true;
398                    continue;
399                }
400                if skip {
401                    // Skip old tracevault lines (they start with "tracevault " or are empty continuations)
402                    if line.starts_with("tracevault ") {
403                        continue;
404                    }
405                    skip = false;
406                }
407                new_content.push_str(line);
408                new_content.push('\n');
409            }
410            if !new_content.ends_with('\n') {
411                new_content.push('\n');
412            }
413            new_content.push_str(&tracevault_block);
414            fs::write(&hook_path, new_content)?;
415        } else {
416            // Append to existing hook
417            let mut content = existing;
418            if !content.ends_with('\n') {
419                content.push('\n');
420            }
421            content.push_str(&tracevault_block);
422            fs::write(&hook_path, content)?;
423        }
424    } else {
425        let content = format!("#!/bin/sh\n{tracevault_block}");
426        fs::write(&hook_path, content)?;
427    }
428
429    // Make executable
430    #[cfg(unix)]
431    {
432        use std::os::unix::fs::PermissionsExt;
433        let mut perms = fs::metadata(&hook_path)?.permissions();
434        perms.set_mode(0o755);
435        fs::set_permissions(&hook_path, perms)?;
436    }
437
438    Ok(())
439}
440
441const POST_COMMIT_MARKER: &str = "# tracevault:post-commit";
442
443fn install_post_commit_hook(project_root: &Path) -> Result<(), io::Error> {
444    let hooks_dir = project_root.join(".git/hooks");
445    fs::create_dir_all(&hooks_dir)?;
446
447    let hook_path = hooks_dir.join("post-commit");
448    let tracevault_block = format!("{POST_COMMIT_MARKER}\ntracevault commit-push 2>/dev/null &\n");
449
450    if hook_path.exists() {
451        let existing = fs::read_to_string(&hook_path)?;
452
453        if existing.contains(POST_COMMIT_MARKER) {
454            return Ok(());
455        }
456
457        let mut content = existing;
458        if !content.ends_with('\n') {
459            content.push('\n');
460        }
461        content.push_str(&tracevault_block);
462        fs::write(&hook_path, content)?;
463    } else {
464        let content = format!("#!/bin/sh\n{tracevault_block}");
465        fs::write(&hook_path, content)?;
466    }
467
468    #[cfg(unix)]
469    {
470        use std::os::unix::fs::PermissionsExt;
471        let mut perms = fs::metadata(&hook_path)?.permissions();
472        perms.set_mode(0o755);
473        fs::set_permissions(&hook_path, perms)?;
474    }
475
476    Ok(())
477}
478
479fn install_claude_hooks(
480    project_root: &Path,
481    target: ClaudeSettingsTarget,
482) -> Result<(), io::Error> {
483    let claude_dir = project_root.join(".claude");
484    fs::create_dir_all(&claude_dir)?;
485
486    let filename = target.filename();
487    let settings_path = claude_dir.join(filename);
488    let mut settings: serde_json::Value = if settings_path.exists() {
489        let content = fs::read_to_string(&settings_path)?;
490        serde_json::from_str(&content).map_err(|e| {
491            io::Error::new(
492                io::ErrorKind::InvalidData,
493                format!("Failed to parse .claude/{filename}: {e}"),
494            )
495        })?
496    } else {
497        serde_json::json!({})
498    };
499
500    let hooks = tracevault_hooks();
501
502    // Merge hooks into existing settings
503    let settings_obj = settings.as_object_mut().ok_or_else(|| {
504        io::Error::new(
505            io::ErrorKind::InvalidData,
506            format!(".claude/{filename} is not a JSON object"),
507        )
508    })?;
509
510    settings_obj.insert("hooks".to_string(), hooks);
511
512    let formatted = serde_json::to_string_pretty(&settings)
513        .map_err(|e| io::Error::other(format!("Failed to serialize settings: {e}")))?;
514    fs::write(&settings_path, formatted)?;
515
516    Ok(())
517}
518
519pub fn tracevault_hooks() -> serde_json::Value {
520    serde_json::json!({
521        "PreToolUse": [{
522            "matcher": "Write|Edit|Bash",
523            "hooks": [{
524                "type": "command",
525                "command": "tracevault stream --event pre-tool-use",
526                "timeout": 10,
527                "statusMessage": "TraceVault: streaming pre-tool event"
528            }]
529        }],
530        "PostToolUse": [{
531            "matcher": "",
532            "hooks": [{
533                "type": "command",
534                "command": "tracevault stream --event post-tool-use",
535                "timeout": 10,
536                "statusMessage": "TraceVault: streaming post-tool event"
537            }]
538        }],
539        "Notification": [{
540            "matcher": "",
541            "hooks": [{
542                "type": "command",
543                "command": "tracevault stream --event notification",
544                "timeout": 10,
545                "statusMessage": "TraceVault: streaming notification"
546            }]
547        }],
548        "Stop": [{
549            "matcher": "",
550            "hooks": [{
551                "type": "command",
552                "command": "tracevault stream --event stop",
553                "timeout": 10,
554                "statusMessage": "TraceVault: finalizing session"
555            }]
556        }],
557        "SessionStart": [{
558            "matcher": "",
559            "hooks": [{
560                "type": "command",
561                "command": "tracevault session-start",
562                "timeout": 10,
563                "statusMessage": "TraceVault: session start"
564            }]
565        }],
566        "UserPromptSubmit": [{
567            "matcher": "",
568            "hooks": [{
569                "type": "command",
570                "command": "tracevault user-prompt",
571                "timeout": 10,
572                "statusMessage": "TraceVault: policy reinforcement"
573            }]
574        }]
575    })
576}
577
578/// Codex CLI hook set, mirroring `tracevault_hooks()` but with Codex commands.
579/// Capture hooks carry `--agent codex`; the injection hooks (session-start /
580/// user-prompt) are agent-agnostic. Matchers are `""` (all tools).
581///
582/// We intentionally do NOT register a `PreToolUse` hook for Codex. Unlike Claude
583/// Code — whose `PreToolUse` is scoped to `Write|Edit|Bash` — the CLI does no
584/// Codex-specific pre-tool work, and `PostToolUse` + `Stop` already stream the
585/// (incremental, offset-tracked) rollout. A pre-tool hook on every tool call
586/// would only double the per-call streaming for no added capture. No
587/// `Notification` event either (Codex has none).
588pub fn codex_hooks() -> serde_json::Value {
589    serde_json::json!({
590        "SessionStart": [{
591            "matcher": "",
592            "hooks": [{ "type": "command", "command": "tracevault session-start", "timeout": 10, "statusMessage": "TraceVault: session start" }]
593        }],
594        "UserPromptSubmit": [{
595            "matcher": "",
596            "hooks": [{ "type": "command", "command": "tracevault user-prompt", "timeout": 10, "statusMessage": "TraceVault: policy reinforcement" }]
597        }],
598        "PostToolUse": [{
599            "matcher": "",
600            "hooks": [{ "type": "command", "command": "tracevault stream --event post-tool-use --agent codex", "timeout": 10, "statusMessage": "TraceVault: streaming post-tool event" }]
601        }],
602        "Stop": [{
603            "matcher": "",
604            "hooks": [{ "type": "command", "command": "tracevault stream --event stop --agent codex", "timeout": 10, "statusMessage": "TraceVault: finalizing session" }]
605        }]
606    })
607}
608
609/// Embedded pi/GSD extension source (bundled at build time — see
610/// `assets/gsd-extension/{index.ts,package.json,extension-manifest.json}`,
611/// the checked-in source this installer writes verbatim).
612const GSD_EXT_INDEX_TS: &str = include_str!("../../assets/gsd-extension/index.ts");
613const GSD_EXT_PACKAGE_JSON: &str = include_str!("../../assets/gsd-extension/package.json");
614const GSD_EXT_MANIFEST_JSON: &str =
615    include_str!("../../assets/gsd-extension/extension-manifest.json");
616
617/// Path of the stable directory (under the user's config dir) that holds the
618/// TraceVault GSD extension source, shared by `install_gsd_extension` so the
619/// write and the `gsd install` invocation always agree on where it lives.
620fn gsd_extension_source_dir() -> io::Result<PathBuf> {
621    let config_dir = dirs::config_dir().or_else(|| dirs::home_dir().map(|h| h.join(".config")));
622    let config_dir = config_dir
623        .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "no config or home dir"))?;
624    Ok(config_dir.join("tracevault").join("gsd-extension"))
625}
626
627/// Install the TraceVault pi/GSD extension and register it with GSD so it
628/// actually loads.
629///
630/// GSD (pi) only loads an extension that (a) has an `extension-manifest.json`
631/// in its directory *and* (b) was registered via `gsd install <dir>` — a
632/// hand-written `registry.json` entry is inert (`gsd list` won't show it).
633/// So this writes the extension source (`index.ts`, `package.json`,
634/// `extension-manifest.json`) to a stable, idempotent source directory
635/// (`<config_dir>/tracevault/gsd-extension`), best-effort cleans up any
636/// stale/inert registration left behind by an older version of this
637/// installer, and then shells out to `gsd install` to register + load it.
638///
639/// `project_root` selects how `gsd install` is invoked:
640/// - `Some(repo)`: project-local install (`gsd install <dir> -l`, run with
641///   `repo` as the working directory) — used by `tracevault init`.
642/// - `None`: global install (`gsd install <dir>`, applies to all GSD
643///   sessions on this machine) — used by `tracevault init --global`.
644///
645/// If the `gsd` binary can't be found or the install command fails, this
646/// does NOT fail `init`: it prints a warning explaining how to finish the
647/// registration by hand and returns `Ok(())`. The extension source is still
648/// written either way, so the user (or a later retry) has something to
649/// register.
650pub fn install_gsd_extension(project_root: Option<&Path>) -> io::Result<()> {
651    let home =
652        dirs::home_dir().ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "no home dir"))?;
653    let gsd_home = home.join(".gsd");
654
655    let source_dir = gsd_extension_source_dir()?;
656    fs::create_dir_all(&source_dir)?;
657    fs::write(source_dir.join("index.ts"), GSD_EXT_INDEX_TS)?;
658    fs::write(source_dir.join("package.json"), GSD_EXT_PACKAGE_JSON)?;
659    fs::write(
660        source_dir.join("extension-manifest.json"),
661        GSD_EXT_MANIFEST_JSON,
662    )?;
663
664    // Best-effort cleanup of the OLD, broken install (hand-written registry
665    // entries that GSD never actually loaded). Never blocks the rest of the
666    // install — see `cleanup_stale_gsd_registration`.
667    if let Err(e) = cleanup_stale_gsd_registration(&gsd_home) {
668        eprintln!("Warning: could not clean up the previous GSD extension registration: {e}");
669    }
670
671    // Register + load the extension via the `gsd` CLI. `gsd install` is what
672    // actually makes GSD load the extension; our own registry.json edits
673    // never did.
674    let local_flag = project_root.is_some();
675    let mut cmd = std::process::Command::new("gsd");
676    cmd.arg("install").arg(&source_dir);
677    if let Some(root) = project_root {
678        cmd.arg("-l");
679        cmd.current_dir(root);
680    }
681
682    let retry_hint = format!(
683        "gsd install {}{}",
684        source_dir.display(),
685        if local_flag { " -l" } else { "" }
686    );
687
688    match cmd.output() {
689        Ok(output) if output.status.success() => {
690            println!(
691                "TraceVault: installed and registered the GSD extension ({}).",
692                source_dir.display()
693            );
694        }
695        Ok(output) => {
696            eprintln!(
697                "TraceVault: installed the GSD extension source to {}, but `gsd install` failed:\n{}Ensure `gsd` is on PATH and run: `{retry_hint}` to enable capture.",
698                source_dir.display(),
699                String::from_utf8_lossy(&output.stderr),
700            );
701        }
702        Err(e) => {
703            eprintln!(
704                "TraceVault: installed the GSD extension source to {}, but could not run `gsd install` ({e}). Ensure `gsd` is on PATH and run: `{retry_hint}` to enable capture.",
705                source_dir.display(),
706            );
707        }
708    }
709
710    Ok(())
711}
712
713/// TraceVault OpenCode plugin source, embedded from the checked-in assets
714/// this installer writes verbatim (mirrors the GSD extension embeds above).
715const OPENCODE_PLUGIN_INDEX: &str = include_str!("../../assets/opencode-plugin/index.ts");
716
717/// Install the TraceVault OpenCode plugin. `project_root = Some(dir)` installs
718/// project-local at `<dir>/.opencode/plugins/tracevault.ts`; `None` installs
719/// global at `~/.config/opencode/plugins/tracevault.ts` (using the same
720/// config-dir resolution as `gsd_extension_source_dir` above). OpenCode
721/// auto-loads `*.ts` modules from that directory — no separate "install"
722/// command. Returns an error on failure (unresolvable config dir, or a write
723/// error) so the caller aborts init loudly, consistent with the Codex/GSD arms
724/// — a swallowed failure would make `init` report success while no plugin was
725/// written, silently disabling capture.
726///
727/// A FLAT `.ts` file is used rather than a `tracevault/` package directory: a
728/// package subdir (index.ts + package.json) makes OpenCode try to resolve it as
729/// an npm package and stalls at startup offline, whereas a flat module loads
730/// directly (both confirmed during the capture spike). The plugin only imports
731/// the `node:child_process` builtin, so it needs no package manifest.
732pub fn install_opencode_plugin(project_root: Option<&Path>) -> io::Result<()> {
733    let plugins_dir = match project_root {
734        Some(root) => root.join(".opencode").join("plugins"),
735        None => {
736            let config_dir =
737                dirs::config_dir().or_else(|| dirs::home_dir().map(|h| h.join(".config")));
738            config_dir
739                .ok_or_else(|| {
740                    io::Error::new(
741                        io::ErrorKind::NotFound,
742                        "could not determine the config directory for the OpenCode plugin install",
743                    )
744                })?
745                .join("opencode")
746                .join("plugins")
747        }
748    };
749
750    write_opencode_plugin_files(&plugins_dir)
751}
752
753fn write_opencode_plugin_files(plugins_dir: &Path) -> io::Result<()> {
754    fs::create_dir_all(plugins_dir)?;
755    fs::write(plugins_dir.join("tracevault.ts"), OPENCODE_PLUGIN_INDEX)?;
756    Ok(())
757}
758
759/// Best-effort cleanup of the extension registration left behind by an OLDER
760/// version of this installer: the `tracevault-tracker` directory (an earlier,
761/// incorrect Codex-clone `hooks.json` shim that impersonated this extension
762/// under the wrong name) and any registry entries for `tracevault-tracker` or
763/// `tracevault` — both are inert now that `gsd install` manages registration.
764///
765/// If `registry.json` is missing, there's nothing to clean up. If it exists
766/// but fails to parse, or its shape is not a valid registry (root not an
767/// object, or a non-object `entries` field), it is structurally corrupt: we
768/// leave it byte-for-byte untouched (skip cleanup) rather than risk
769/// destroying every other extension the user has registered.
770pub fn cleanup_stale_gsd_registration(gsd_home: &Path) -> io::Result<()> {
771    let ext_root = gsd_home.join("extensions");
772    let reg_path = ext_root.join("registry.json");
773
774    // Validate the registry BEFORE mutating anything under ~/.gsd. If it exists
775    // but is structurally corrupt (unparseable, or a non-object root/`entries`),
776    // leave the extensions directory entirely untouched — not even the stale
777    // tracker dir is removed — so a corrupt registry yields zero mutation.
778    let reg: Option<serde_json::Value> = if reg_path.exists() {
779        let content = fs::read_to_string(&reg_path)?;
780        let parsed: serde_json::Value = match serde_json::from_str(&content) {
781            Ok(v) => v,
782            Err(_) => return Ok(()), // corrupt: touch nothing
783        };
784        let corrupt = match parsed.as_object() {
785            None => true,
786            Some(obj) => matches!(obj.get("entries"), Some(v) if !v.is_object()),
787        };
788        if corrupt {
789            return Ok(()); // structurally corrupt: touch nothing
790        }
791        Some(parsed)
792    } else {
793        None
794    };
795
796    // Registry is valid or absent — now safe to remove the superseded tracker shim.
797    let stale = ext_root.join("tracevault-tracker");
798    if stale.exists() {
799        fs::remove_dir_all(&stale)?;
800    }
801
802    // Drop stale registry entries (only when a valid registry exists).
803    if let Some(mut reg) = reg {
804        if let Some(entries) = reg.get_mut("entries").and_then(|e| e.as_object_mut()) {
805            let removed_tracker = entries.remove("tracevault-tracker").is_some();
806            let removed_inert = entries.remove("tracevault").is_some();
807            if removed_tracker || removed_inert {
808                // Atomic write (temp file + rename), pretty-printed.
809                let tmp = reg_path.with_extension("json.tmp");
810                fs::write(&tmp, serde_json::to_string_pretty(&reg)?)?;
811                fs::rename(&tmp, &reg_path)?;
812            }
813        }
814    }
815    Ok(())
816}
817
818/// Read `hooks_path` as a JSON object (or `{}` if absent), deep-merge `ours`
819/// into its `hooks` map via [`merge_hooks`] (idempotent, never clobbers existing
820/// hooks/keys), and write the result back atomically (sibling temp file +
821/// rename). Shared by the hook-file installers so the read → merge →
822/// atomic-write pattern lives in exactly one place. Works for both Claude's
823/// `settings.json` and Codex's `hooks.json`, whose roots are the object
824/// `merge_hooks` mutates (`root["hooks"]`). On a merge error (malformed
825/// existing file) it returns before writing, so the target is never clobbered
826/// and no temp file is left behind.
827fn merge_hooks_into_file(hooks_path: &Path, ours: &serde_json::Value) -> io::Result<()> {
828    // Defense-in-depth against path traversal: callers pass a constant filename
829    // joined to a home/cwd base (global callers additionally go through
830    // `safe_join`), so a `..` component should never appear — reject it outright
831    // rather than read/write through it.
832    if hooks_path
833        .components()
834        .any(|c| c == std::path::Component::ParentDir)
835    {
836        return Err(io::Error::new(
837            io::ErrorKind::InvalidInput,
838            format!("refusing to use path with '..': {}", hooks_path.display()),
839        ));
840    }
841    let mut root: serde_json::Value = if hooks_path.exists() {
842        let content = fs::read_to_string(hooks_path)?;
843        serde_json::from_str(&content).map_err(|e| {
844            io::Error::new(
845                io::ErrorKind::InvalidData,
846                format!("Failed to parse {}: {e}", hooks_path.display()),
847            )
848        })?
849    } else {
850        serde_json::json!({})
851    };
852
853    merge_hooks(&mut root, ours, hooks_path)?;
854
855    let formatted = serde_json::to_string_pretty(&root).map_err(|e| {
856        io::Error::other(format!("Failed to serialize {}: {e}", hooks_path.display()))
857    })?;
858    let tmp = hooks_path.with_extension("json.tmp");
859    fs::write(&tmp, formatted)?;
860    fs::rename(&tmp, hooks_path)?;
861    Ok(())
862}
863
864/// Deep-merge the Codex hook set into `<project_root>/.codex/hooks.json`,
865/// creating it if absent (idempotent, never clobbers existing hooks/keys,
866/// atomic write). Repo-local counterpart of [`install_global_codex_hooks`].
867pub fn install_codex_hooks(project_root: &Path) -> io::Result<()> {
868    let codex_dir = project_root.join(".codex");
869    fs::create_dir_all(&codex_dir)?;
870    merge_hooks_into_file(&codex_dir.join("hooks.json"), &codex_hooks())
871}
872
873/// Install TraceVault's Codex hooks into `<codex_dir>/hooks.json` and append a
874/// workspace-mode instruction block to `<codex_dir>/AGENTS.md` (idempotent,
875/// atomic), mirroring the Claude global install's `settings.json` + `CLAUDE.md`.
876/// Intended for `tracevault init --global --agent codex`. Codex reads `AGENTS.md`
877/// for agent instructions, so the workspace-mode block reaches detached Codex
878/// sessions the same way the `CLAUDE.md` block reaches Claude ones.
879pub fn install_global_codex_hooks(codex_dir: &Path) -> io::Result<()> {
880    fs::create_dir_all(codex_dir)?;
881    // Canonicalize the base so safe_join keeps target files directly within it.
882    let base = codex_dir.canonicalize()?;
883    merge_hooks_into_file(&safe_join(&base, "hooks.json")?, &codex_hooks())?;
884    append_workspace_md(&safe_join(&base, "AGENTS.md")?)
885}
886
887// Workspace-mode instruction block. Agent-agnostic (it only references
888// `tracevault repo …`), so it's shared verbatim between the Claude global
889// install's `CLAUDE.md` and the Codex global install's `AGENTS.md`.
890const GLOBAL_CLAUDE_MD_MARKER: &str = "<!-- tracevault:workspace-mode -->";
891
892const GLOBAL_CLAUDE_MD_BLOCK: &str = "\
893<!-- tracevault:workspace-mode -->
894## TraceVault (workspace mode)
895You may be running detached from any single repository. Before working on a repo, run
896`tracevault repo switch <path>` to bind tracing and fetch that repo's policies; treat its
897output as binding. Use `--path <path>` on `tracevault repo status` for a one-off. Repos must
898already be registered with TraceVault.
899";
900
901/// Append the workspace-mode instruction block to `md_path` (creating it if
902/// absent), idempotently — guarded by [`GLOBAL_CLAUDE_MD_MARKER`], so a re-run
903/// never duplicates it and any existing user content is preserved. Shared by
904/// the Claude global install (`CLAUDE.md`) and the Codex global install
905/// (`AGENTS.md`).
906fn append_workspace_md(md_path: &Path) -> io::Result<()> {
907    // Defense-in-depth against path traversal (see `merge_hooks_into_file`).
908    if md_path
909        .components()
910        .any(|c| c == std::path::Component::ParentDir)
911    {
912        return Err(io::Error::new(
913            io::ErrorKind::InvalidInput,
914            format!("refusing to use path with '..': {}", md_path.display()),
915        ));
916    }
917    let existing = if md_path.exists() {
918        fs::read_to_string(md_path)?
919    } else {
920        String::new()
921    };
922    if existing.contains(GLOBAL_CLAUDE_MD_MARKER) {
923        return Ok(());
924    }
925    let mut content = existing;
926    if !content.is_empty() && !content.ends_with('\n') {
927        content.push('\n');
928    }
929    if !content.is_empty() {
930        content.push('\n');
931    }
932    content.push_str(GLOBAL_CLAUDE_MD_BLOCK);
933    fs::write(md_path, content)
934}
935
936/// Join a constant file name to `base` and confirm the result stays directly
937/// within `base` — defense-in-depth so a path derived from the environment
938/// ($HOME) cannot escape the intended `.claude` directory.
939fn safe_join(base: &Path, name: &str) -> io::Result<PathBuf> {
940    let joined = base.join(name);
941    if joined.parent() != Some(base) {
942        return Err(io::Error::new(
943            io::ErrorKind::InvalidInput,
944            format!(
945                "refusing to access path outside {}: {}",
946                base.display(),
947                joined.display()
948            ),
949        ));
950    }
951    Ok(joined)
952}
953
954/// Merge our hook entries into an existing `settings["hooks"]` object, per
955/// event, appending our entry only if no existing entry in that event's
956/// array already has an inner hook with the same `command` (dedupe → makes
957/// repeated calls idempotent). Never removes or overwrites the user's other
958/// hooks or top-level keys.
959///
960/// Absent values (no top-level `settings`, no `hooks` key, no entry for a
961/// given event) are created fresh — that's fine. But if an EXISTING value
962/// has an unexpected shape (top-level `settings` isn't an object, an
963/// existing `hooks` isn't an object, or an existing per-event value isn't an
964/// array), this errors loudly instead of silently discarding it, mirroring
965/// `install_claude_hooks`'s treatment of a non-object settings file.
966fn merge_hooks(
967    settings: &mut serde_json::Value,
968    ours: &serde_json::Value,
969    path: &Path,
970) -> io::Result<()> {
971    if settings.is_null() {
972        *settings = serde_json::json!({});
973    }
974    let settings_obj = settings.as_object_mut().ok_or_else(|| {
975        io::Error::new(
976            io::ErrorKind::InvalidData,
977            format!("{} is not a JSON object", path.display()),
978        )
979    })?;
980
981    let hooks_value = settings_obj
982        .entry("hooks")
983        .or_insert_with(|| serde_json::json!({}));
984    let hooks_obj = hooks_value.as_object_mut().ok_or_else(|| {
985        io::Error::new(
986            io::ErrorKind::InvalidData,
987            format!("{} \"hooks\" key is not a JSON object", path.display()),
988        )
989    })?;
990
991    let Some(ours_obj) = ours.as_object() else {
992        return Ok(());
993    };
994
995    for (event, our_array) in ours_obj {
996        let Some(our_entries) = our_array.as_array() else {
997            continue;
998        };
999
1000        let existing_value = hooks_obj
1001            .entry(event.clone())
1002            .or_insert_with(|| serde_json::json!([]));
1003        let existing_array = existing_value.as_array_mut().ok_or_else(|| {
1004            io::Error::new(
1005                io::ErrorKind::InvalidData,
1006                format!(
1007                    "{} \"hooks\".\"{event}\" is not a JSON array",
1008                    path.display()
1009                ),
1010            )
1011        })?;
1012
1013        for our_entry in our_entries {
1014            let our_command = entry_command(our_entry);
1015            let already_present = existing_array
1016                .iter()
1017                .any(|existing_entry| entry_contains_command(existing_entry, our_command));
1018            if !already_present {
1019                existing_array.push(our_entry.clone());
1020            }
1021        }
1022    }
1023
1024    Ok(())
1025}
1026
1027/// Extract the inner `hooks[0].command` string from a hook-event entry, if
1028/// present.
1029fn entry_command(entry: &serde_json::Value) -> Option<&str> {
1030    entry.get("hooks")?.get(0)?.get("command")?.as_str()
1031}
1032
1033/// Whether any of `entry`'s inner `hooks[].command` values equal `cmd`. Unlike
1034/// `entry_command` (which only looks at `hooks[0]`), this scans the whole
1035/// inner `hooks` array — a user entry can have our command anywhere in it
1036/// (e.g. `hooks[1]`), and missing that would let a duplicate get appended.
1037fn entry_contains_command(entry: &serde_json::Value, cmd: Option<&str>) -> bool {
1038    let Some(hooks) = entry.get("hooks").and_then(|h| h.as_array()) else {
1039        return false;
1040    };
1041    hooks
1042        .iter()
1043        .any(|hook| hook.get("command").and_then(|c| c.as_str()) == cmd)
1044}
1045
1046/// Install TraceVault's Claude Code hooks into `claude_dir/settings.json`
1047/// (deep-merged, never clobbering existing hooks/keys) and append a
1048/// workspace-mode instruction block to `claude_dir/CLAUDE.md` (idempotent,
1049/// guarded by a marker comment). Intended for `tracevault init --global`,
1050/// installing once for all Claude Code sessions rather than per-repo.
1051pub fn install_global_hooks(claude_dir: &Path) -> io::Result<()> {
1052    fs::create_dir_all(claude_dir)?;
1053
1054    // Canonicalize the base to defend against path traversal attacks.
1055    // safe_join will verify that target files stay directly within this base.
1056    let base = claude_dir.canonicalize()?;
1057
1058    // --- settings.json: deep-merge hooks (atomic) ---
1059    merge_hooks_into_file(&safe_join(&base, "settings.json")?, &tracevault_hooks())?;
1060
1061    // --- CLAUDE.md: append the workspace-mode instruction block, idempotently ---
1062    append_workspace_md(&safe_join(&base, "CLAUDE.md")?)
1063}
1064
1065/// Write the user-level `config.toml` (under `config_root`) carrying the
1066/// user-context setting. An EXISTING user config is preserved (this mirrors the
1067/// "don't clobber" contract of the global-hooks install): `requested` overrides
1068/// the user_context when a flag was given; otherwise an existing value is kept,
1069/// and only a first-time setup (no existing config) defaults to enabled.
1070/// When the resulting layer is enabled, the referenced context file is seeded
1071/// (empty) if absent — a custom `--user-context <path>` seeds THAT file, a
1072/// disabled layer seeds nothing. Returns the active context file path (the file
1073/// the hook will read), or `None` when the layer is disabled. Used by `init --global`.
1074pub fn write_global_user_config_in(
1075    config_root: &Path,
1076    requested: Option<UserContext>,
1077) -> io::Result<Option<PathBuf>> {
1078    fs::create_dir_all(config_root)?;
1079    // Preserve an existing (valid) user config; malformed/missing → start fresh.
1080    let mut config = crate::config::try_load_user_config_in(config_root)
1081        .ok()
1082        .flatten()
1083        .unwrap_or_default();
1084    // Requested flag wins; else keep an existing value; else first-run default = enabled.
1085    let user_context = requested
1086        .or_else(|| config.user_context.clone())
1087        .unwrap_or(UserContext::Toggle(true));
1088    let active = user_context
1089        .resolve()
1090        .map(|_| user_context.path_in(config_root));
1091    config.user_context = Some(user_context);
1092    fs::write(user_config_path_in(config_root), config.to_toml())?;
1093    if let Some(ref ctx_path) = active {
1094        if !ctx_path.exists() {
1095            Context::default().save_to(ctx_path)?;
1096        }
1097    }
1098    Ok(active)
1099}
1100
1101#[cfg(test)]
1102mod tests {
1103    use super::*;
1104
1105    #[test]
1106    fn linked_worktree_primary_detects_linked_and_primary() {
1107        let tmp = tempfile::tempdir().unwrap();
1108        let repo = tmp.path().join("repo");
1109        let wt = tmp.path().join("linked-wt");
1110        std::fs::create_dir_all(&repo).unwrap();
1111        crate::test_helpers::init_git_repo(&repo);
1112        crate::test_helpers::add_worktree(&repo, &wt);
1113
1114        // Primary checkout → None.
1115        assert!(
1116            linked_worktree_primary(&repo).is_none(),
1117            "primary checkout must not be flagged as a linked worktree"
1118        );
1119        // Linked worktree → Some(primary root).
1120        let primary = linked_worktree_primary(&wt).expect("linked worktree must be detected");
1121        assert_eq!(
1122            primary.canonicalize().unwrap(),
1123            repo.canonicalize().unwrap(),
1124            "must resolve to the primary repo root"
1125        );
1126    }
1127
1128    #[test]
1129    fn linked_worktree_primary_none_for_non_git() {
1130        let tmp = tempfile::tempdir().unwrap();
1131        assert!(
1132            linked_worktree_primary(tmp.path()).is_none(),
1133            "a non-git directory is not a linked worktree"
1134        );
1135    }
1136
1137    #[test]
1138    fn parse_github_org_ssh() {
1139        assert_eq!(
1140            parse_github_org("git@github.com:myorg/myrepo.git"),
1141            Some("myorg".into())
1142        );
1143    }
1144
1145    #[test]
1146    fn parse_github_org_https() {
1147        assert_eq!(
1148            parse_github_org("https://github.com/myorg/myrepo"),
1149            Some("myorg".into())
1150        );
1151    }
1152
1153    #[test]
1154    fn parse_github_org_non_github_returns_none() {
1155        assert_eq!(parse_github_org("https://gitlab.com/org/repo"), None);
1156    }
1157
1158    #[test]
1159    fn parse_github_org_invalid() {
1160        assert_eq!(parse_github_org("not-a-url"), None);
1161    }
1162
1163    #[test]
1164    fn merge_hooks_into_empty_settings_adds_all_our_events() {
1165        let mut settings = serde_json::json!({});
1166        let ours = tracevault_hooks();
1167        merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1168
1169        let hooks = settings.get("hooks").unwrap();
1170        for event in [
1171            "PreToolUse",
1172            "PostToolUse",
1173            "Notification",
1174            "Stop",
1175            "SessionStart",
1176            "UserPromptSubmit",
1177        ] {
1178            assert!(hooks.get(event).is_some(), "missing event {event}");
1179        }
1180    }
1181
1182    #[test]
1183    fn merge_hooks_preserves_unrelated_user_hook_and_keys() {
1184        let mut settings = serde_json::json!({
1185            "model": "opus",
1186            "hooks": {
1187                "PreToolUse": [{
1188                    "matcher": "",
1189                    "hooks": [{ "type": "command", "command": "my-own-hook" }]
1190                }]
1191            }
1192        });
1193        let ours = tracevault_hooks();
1194        merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1195
1196        // Other top-level keys preserved.
1197        assert_eq!(settings.get("model").unwrap(), "opus");
1198
1199        let pre_tool_use = settings["hooks"]["PreToolUse"].as_array().unwrap();
1200        // Both the user's own hook and ours are present.
1201        assert_eq!(pre_tool_use.len(), 2);
1202        let commands: Vec<&str> = pre_tool_use
1203            .iter()
1204            .map(|e| entry_command(e).unwrap())
1205            .collect();
1206        assert!(commands.contains(&"my-own-hook"));
1207        assert!(commands.contains(&"tracevault stream --event pre-tool-use"));
1208
1209        // Other events were added fresh.
1210        assert!(settings["hooks"]["SessionStart"].is_array());
1211    }
1212
1213    #[test]
1214    fn merge_hooks_is_idempotent() {
1215        let mut settings = serde_json::json!({});
1216        let ours = tracevault_hooks();
1217        merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1218        merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1219
1220        for event in [
1221            "PreToolUse",
1222            "PostToolUse",
1223            "Notification",
1224            "Stop",
1225            "SessionStart",
1226            "UserPromptSubmit",
1227        ] {
1228            let arr = settings["hooks"][event].as_array().unwrap();
1229            assert_eq!(arr.len(), 1, "event {event} should not be duplicated");
1230        }
1231    }
1232
1233    #[test]
1234    fn merge_hooks_dedupes_command_found_in_non_first_inner_hook() {
1235        // The existing PreToolUse entry has our command at hooks[1], not
1236        // hooks[0] — a naive `entry_command` (hooks[0] only) comparison would
1237        // miss it and append a duplicate entry.
1238        let mut settings = serde_json::json!({
1239            "hooks": {
1240                "PreToolUse": [{
1241                    "matcher": "Write|Edit|Bash",
1242                    "hooks": [
1243                        { "type": "command", "command": "other" },
1244                        { "type": "command", "command": "tracevault stream --event pre-tool-use" }
1245                    ]
1246                }]
1247            }
1248        });
1249        let ours = tracevault_hooks();
1250        merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1251
1252        let pre_tool_use = settings["hooks"]["PreToolUse"].as_array().unwrap();
1253        assert_eq!(
1254            pre_tool_use.len(),
1255            1,
1256            "must not append a duplicate PreToolUse entry when our command is present at hooks[1]"
1257        );
1258    }
1259
1260    #[test]
1261    fn merge_hooks_errors_on_non_object_top_level() {
1262        let mut settings = serde_json::json!([1, 2, 3]);
1263        let ours = tracevault_hooks();
1264        let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
1265        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1266        assert!(err.to_string().contains("settings.json"));
1267    }
1268
1269    #[test]
1270    fn merge_hooks_errors_on_non_object_top_level_number() {
1271        let mut settings = serde_json::json!(42);
1272        let ours = tracevault_hooks();
1273        let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
1274        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1275    }
1276
1277    #[test]
1278    fn merge_hooks_errors_on_non_object_hooks() {
1279        let mut settings = serde_json::json!({ "hooks": "not-an-object" });
1280        let ours = tracevault_hooks();
1281        let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
1282        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1283        assert!(err.to_string().contains("hooks"));
1284    }
1285
1286    #[test]
1287    fn merge_hooks_errors_on_non_array_event_value() {
1288        let mut settings = serde_json::json!({
1289            "hooks": {
1290                "PreToolUse": "not-an-array"
1291            }
1292        });
1293        let ours = tracevault_hooks();
1294        let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
1295        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1296        assert!(err.to_string().contains("PreToolUse"));
1297    }
1298
1299    #[test]
1300    fn install_global_hooks_writes_settings_and_claude_md() {
1301        let tmp = tempfile::tempdir().unwrap();
1302        let claude_dir = tmp.path().join(".claude");
1303
1304        install_global_hooks(&claude_dir).unwrap();
1305
1306        let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
1307        let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
1308        for event in ["SessionStart", "UserPromptSubmit", "PreToolUse"] {
1309            assert!(settings["hooks"].get(event).is_some(), "missing {event}");
1310        }
1311
1312        let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
1313        assert!(claude_md.contains(GLOBAL_CLAUDE_MD_MARKER));
1314    }
1315
1316    #[test]
1317    fn install_global_hooks_is_idempotent() {
1318        let tmp = tempfile::tempdir().unwrap();
1319        let claude_dir = tmp.path().join(".claude");
1320
1321        install_global_hooks(&claude_dir).unwrap();
1322        install_global_hooks(&claude_dir).unwrap();
1323
1324        let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
1325        let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
1326        for event in [
1327            "PreToolUse",
1328            "PostToolUse",
1329            "Notification",
1330            "Stop",
1331            "SessionStart",
1332            "UserPromptSubmit",
1333        ] {
1334            let arr = settings["hooks"][event].as_array().unwrap();
1335            assert_eq!(arr.len(), 1, "event {event} should not be duplicated");
1336        }
1337
1338        let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
1339        let marker_count = claude_md.matches(GLOBAL_CLAUDE_MD_MARKER).count();
1340        assert_eq!(
1341            marker_count, 1,
1342            "CLAUDE.md marker should appear exactly once"
1343        );
1344    }
1345
1346    #[test]
1347    fn install_global_hooks_preserves_existing_claude_md_content() {
1348        let tmp = tempfile::tempdir().unwrap();
1349        let claude_dir = tmp.path().join(".claude");
1350        fs::create_dir_all(&claude_dir).unwrap();
1351        fs::write(
1352            claude_dir.join("CLAUDE.md"),
1353            "# My existing notes\nSome content.\n",
1354        )
1355        .unwrap();
1356
1357        install_global_hooks(&claude_dir).unwrap();
1358
1359        let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
1360        assert!(claude_md.contains("# My existing notes"));
1361        assert!(claude_md.contains(GLOBAL_CLAUDE_MD_MARKER));
1362    }
1363
1364    #[test]
1365    fn install_global_hooks_settings_write_is_atomic_no_tmp_leftover() {
1366        let tmp = tempfile::tempdir().unwrap();
1367        let claude_dir = tmp.path().join(".claude");
1368
1369        install_global_hooks(&claude_dir).unwrap();
1370
1371        let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
1372        let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
1373        assert!(settings["hooks"].get("SessionStart").is_some());
1374
1375        let leftover = fs::read_dir(&claude_dir)
1376            .unwrap()
1377            .filter_map(|e| e.ok())
1378            .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
1379        assert!(
1380            !leftover,
1381            "no settings.json.tmp should remain after install"
1382        );
1383    }
1384
1385    #[test]
1386    fn install_global_hooks_errors_on_non_object_settings_and_does_not_overwrite() {
1387        let tmp = tempfile::tempdir().unwrap();
1388        let claude_dir = tmp.path().join(".claude");
1389        fs::create_dir_all(&claude_dir).unwrap();
1390        let settings_path = claude_dir.join("settings.json");
1391        let original = "[1, 2, 3]";
1392        fs::write(&settings_path, original).unwrap();
1393
1394        let err = install_global_hooks(&claude_dir).unwrap_err();
1395        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1396
1397        // The original (malformed-for-our-purposes but validly-JSON) file
1398        // must be untouched, and no stray tmp file left behind.
1399        let after = fs::read_to_string(&settings_path).unwrap();
1400        assert_eq!(after, original);
1401        let leftover = fs::read_dir(&claude_dir)
1402            .unwrap()
1403            .filter_map(|e| e.ok())
1404            .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
1405        assert!(!leftover, "no tmp file should be left behind on error");
1406    }
1407
1408    #[test]
1409    fn install_global_hooks_errors_on_non_object_hooks_key_and_does_not_overwrite() {
1410        let tmp = tempfile::tempdir().unwrap();
1411        let claude_dir = tmp.path().join(".claude");
1412        fs::create_dir_all(&claude_dir).unwrap();
1413        let settings_path = claude_dir.join("settings.json");
1414        let original = r#"{"hooks": "oops"}"#;
1415        fs::write(&settings_path, original).unwrap();
1416
1417        let err = install_global_hooks(&claude_dir).unwrap_err();
1418        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1419
1420        let after = fs::read_to_string(&settings_path).unwrap();
1421        assert_eq!(after, original);
1422    }
1423
1424    #[test]
1425    fn install_global_hooks_errors_on_non_array_event_and_does_not_overwrite() {
1426        let tmp = tempfile::tempdir().unwrap();
1427        let claude_dir = tmp.path().join(".claude");
1428        fs::create_dir_all(&claude_dir).unwrap();
1429        let settings_path = claude_dir.join("settings.json");
1430        let original = r#"{"hooks": {"PreToolUse": "oops"}}"#;
1431        fs::write(&settings_path, original).unwrap();
1432
1433        let err = install_global_hooks(&claude_dir).unwrap_err();
1434        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1435
1436        let after = fs::read_to_string(&settings_path).unwrap();
1437        assert_eq!(after, original);
1438    }
1439
1440    #[test]
1441    fn safe_join_allows_direct_child_file() {
1442        let tmp = tempfile::tempdir().unwrap();
1443        let base = tmp.path();
1444        let result = safe_join(base, "settings.json").unwrap();
1445        assert_eq!(result.parent(), Some(base));
1446        assert_eq!(result.file_name().unwrap(), "settings.json");
1447    }
1448
1449    #[test]
1450    fn safe_join_rejects_path_traversal() {
1451        let tmp = tempfile::tempdir().unwrap();
1452        let base = tmp.path();
1453        let result = safe_join(base, "../evil");
1454        assert!(result.is_err());
1455        let err = result.unwrap_err();
1456        assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
1457        assert!(err.to_string().contains("refusing to access path outside"));
1458    }
1459
1460    #[test]
1461    fn safe_join_rejects_absolute_path() {
1462        let tmp = tempfile::tempdir().unwrap();
1463        let base = tmp.path();
1464        let result = safe_join(base, "/etc/passwd");
1465        // An absolute path joined to a base will replace the base,
1466        // so parent will not equal base.
1467        assert!(result.is_err());
1468    }
1469
1470    #[test]
1471    fn write_global_user_config_enables_and_creates_context() {
1472        let root = tempfile::tempdir().unwrap();
1473        let active = write_global_user_config_in(root.path(), None).unwrap();
1474        let cfg = crate::config::try_load_user_config_in(root.path())
1475            .unwrap()
1476            .unwrap();
1477        // Validate against the INJECTED root (resolve_in), not tv_config_root():
1478        // a first-run default enables at the `context.json` under `root`.
1479        assert_eq!(
1480            cfg.user_context.unwrap().resolve_in(root.path()),
1481            Some(crate::config::default_user_context_path_in(root.path()))
1482        );
1483        let ctx = crate::config::default_user_context_path_in(root.path());
1484        assert_eq!(active, Some(ctx.clone()));
1485        assert!(ctx.exists());
1486    }
1487
1488    #[test]
1489    fn write_global_user_config_can_disable() {
1490        let root = tempfile::tempdir().unwrap();
1491        let active = write_global_user_config_in(
1492            root.path(),
1493            Some(crate::config::UserContext::Toggle(false)),
1494        )
1495        .unwrap();
1496        let cfg = crate::config::try_load_user_config_in(root.path())
1497            .unwrap()
1498            .unwrap();
1499        assert!(matches!(
1500            cfg.user_context,
1501            Some(crate::config::UserContext::Toggle(false))
1502        ));
1503        assert_eq!(active, None, "disabled → no active context path");
1504        // A disabled layer must NOT seed a context file.
1505        assert!(
1506            !crate::config::default_user_context_path_in(root.path()).exists(),
1507            "disabled user context must not create a context.json"
1508        );
1509    }
1510
1511    #[test]
1512    fn write_global_user_config_custom_path_seeds_that_file_only() {
1513        let root = tempfile::tempdir().unwrap();
1514        let custom = root.path().join("custom-ctx.json");
1515        let active = write_global_user_config_in(
1516            root.path(),
1517            Some(crate::config::UserContext::Path(
1518                custom.to_string_lossy().into_owned(),
1519            )),
1520        )
1521        .unwrap();
1522        assert_eq!(active, Some(custom.clone()));
1523        assert!(custom.exists(), "the configured custom path must be seeded");
1524        assert!(
1525            !crate::config::default_user_context_path_in(root.path()).exists(),
1526            "the default context.json must NOT be created when a custom path is configured"
1527        );
1528    }
1529
1530    #[test]
1531    fn write_global_user_config_preserves_existing_on_rerun_without_flags() {
1532        let root = tempfile::tempdir().unwrap();
1533        let custom = root.path().join("custom-ctx.json");
1534        // First run pins a custom path.
1535        write_global_user_config_in(
1536            root.path(),
1537            Some(crate::config::UserContext::Path(
1538                custom.to_string_lossy().into_owned(),
1539            )),
1540        )
1541        .unwrap();
1542        // Re-run with NO flags must NOT reset it back to the default.
1543        let active = write_global_user_config_in(root.path(), None).unwrap();
1544        assert_eq!(
1545            active,
1546            Some(custom.clone()),
1547            "re-run without flags must preserve the custom path"
1548        );
1549        let cfg = crate::config::try_load_user_config_in(root.path())
1550            .unwrap()
1551            .unwrap();
1552        assert_eq!(cfg.user_context.unwrap().path_in(root.path()), custom);
1553    }
1554
1555    #[test]
1556    fn install_global_codex_hooks_writes_and_is_idempotent() {
1557        let tmp = tempfile::tempdir().unwrap();
1558        let codex_dir = tmp.path().join(".codex");
1559
1560        install_global_codex_hooks(&codex_dir).unwrap();
1561        install_global_codex_hooks(&codex_dir).unwrap();
1562
1563        let v: serde_json::Value =
1564            serde_json::from_str(&fs::read_to_string(codex_dir.join("hooks.json")).unwrap())
1565                .unwrap();
1566        for event in ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"] {
1567            let arr = v["hooks"][event].as_array().unwrap();
1568            assert_eq!(arr.len(), 1, "event {event} must not be duplicated");
1569        }
1570        assert!(v["hooks"].get("PreToolUse").is_none());
1571        // AGENTS.md carries the workspace-mode block exactly once across re-runs.
1572        let agents_md = fs::read_to_string(codex_dir.join("AGENTS.md")).unwrap();
1573        assert_eq!(
1574            agents_md.matches(GLOBAL_CLAUDE_MD_MARKER).count(),
1575            1,
1576            "AGENTS.md workspace-mode block must appear exactly once"
1577        );
1578        // No stray temp file left behind.
1579        let leftover = fs::read_dir(&codex_dir)
1580            .unwrap()
1581            .filter_map(|e| e.ok())
1582            .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
1583        assert!(!leftover);
1584    }
1585
1586    #[test]
1587    fn codex_hooks_has_expected_events_and_commands() {
1588        let h = codex_hooks();
1589        for event in ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"] {
1590            assert!(h.get(event).is_some(), "missing codex event {event}");
1591        }
1592        // No PreToolUse (intentionally dropped — PostToolUse + Stop capture the
1593        // rollout; a pre-tool hook would only double per-call streaming) and no
1594        // Notification event (Codex has none).
1595        assert!(h.get("PreToolUse").is_none());
1596        assert!(h.get("Notification").is_none());
1597        // Capture commands carry --agent codex; injection hooks do not need it.
1598        let cmd = |e: &str| h[e][0]["hooks"][0]["command"].as_str().unwrap().to_string();
1599        assert_eq!(
1600            cmd("PostToolUse"),
1601            "tracevault stream --event post-tool-use --agent codex"
1602        );
1603        assert_eq!(cmd("Stop"), "tracevault stream --event stop --agent codex");
1604        assert_eq!(cmd("SessionStart"), "tracevault session-start");
1605        assert_eq!(cmd("UserPromptSubmit"), "tracevault user-prompt");
1606        // Matchers are "" (all tools) — Codex edits arrive via the transcript.
1607        assert_eq!(h["PostToolUse"][0]["matcher"].as_str().unwrap(), "");
1608    }
1609
1610    #[test]
1611    fn install_codex_hooks_writes_hooks_json_and_is_idempotent() {
1612        let tmp = tempfile::tempdir().unwrap();
1613        install_codex_hooks(tmp.path()).unwrap();
1614        install_codex_hooks(tmp.path()).unwrap();
1615
1616        let content = fs::read_to_string(tmp.path().join(".codex").join("hooks.json")).unwrap();
1617        let v: serde_json::Value = serde_json::from_str(&content).unwrap();
1618        for event in ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"] {
1619            let arr = v["hooks"][event].as_array().unwrap();
1620            assert_eq!(
1621                arr.len(),
1622                1,
1623                "event {event} must not be duplicated on re-run"
1624            );
1625        }
1626        assert!(v["hooks"].get("PreToolUse").is_none());
1627    }
1628
1629    #[test]
1630    fn install_codex_hooks_preserves_existing_user_hook() {
1631        let tmp = tempfile::tempdir().unwrap();
1632        let codex_dir = tmp.path().join(".codex");
1633        fs::create_dir_all(&codex_dir).unwrap();
1634        // Seed a user hook under an event we install (PostToolUse) plus one under
1635        // an event we DON'T (PreToolUse) — both must survive the merge.
1636        fs::write(
1637            codex_dir.join("hooks.json"),
1638            r#"{"hooks":{"PostToolUse":[{"matcher":"","hooks":[{"type":"command","command":"my-own"}]}],"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"user-pretool"}]}]}}"#,
1639        )
1640        .unwrap();
1641
1642        install_codex_hooks(tmp.path()).unwrap();
1643
1644        let v: serde_json::Value =
1645            serde_json::from_str(&fs::read_to_string(codex_dir.join("hooks.json")).unwrap())
1646                .unwrap();
1647        // Our PostToolUse command is merged in alongside the user's own.
1648        let post_cmds: Vec<&str> = v["hooks"]["PostToolUse"]
1649            .as_array()
1650            .unwrap()
1651            .iter()
1652            .map(|e| e["hooks"][0]["command"].as_str().unwrap())
1653            .collect();
1654        assert!(
1655            post_cmds.contains(&"my-own"),
1656            "user PostToolUse hook preserved"
1657        );
1658        assert!(post_cmds.contains(&"tracevault stream --event post-tool-use --agent codex"));
1659        // The user's PreToolUse hook is left untouched (we install no PreToolUse).
1660        let pre_cmds: Vec<&str> = v["hooks"]["PreToolUse"]
1661            .as_array()
1662            .unwrap()
1663            .iter()
1664            .map(|e| e["hooks"][0]["command"].as_str().unwrap())
1665            .collect();
1666        assert_eq!(pre_cmds, vec!["user-pretool"], "unmanaged event untouched");
1667    }
1668
1669    #[test]
1670    fn validate_init_flags_rejects_claude_settings_with_codex() {
1671        assert!(validate_init_flags(crate::agent::Agent::Codex, true).is_err());
1672    }
1673
1674    #[test]
1675    fn validate_init_flags_allows_codex_without_claude_settings() {
1676        assert!(validate_init_flags(crate::agent::Agent::Codex, false).is_ok());
1677    }
1678
1679    #[test]
1680    fn validate_init_flags_allows_claude_with_claude_settings() {
1681        assert!(validate_init_flags(crate::agent::Agent::ClaudeCode, true).is_ok());
1682    }
1683
1684    #[test]
1685    fn merge_hooks_into_file_rejects_parent_dir() {
1686        let tmp = tempfile::tempdir().unwrap();
1687        let bad = tmp.path().join("..").join("hooks.json");
1688        let err = merge_hooks_into_file(&bad, &codex_hooks()).unwrap_err();
1689        assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
1690    }
1691
1692    #[test]
1693    fn append_workspace_md_rejects_parent_dir() {
1694        let tmp = tempfile::tempdir().unwrap();
1695        let bad = tmp.path().join("..").join("AGENTS.md");
1696        let err = append_workspace_md(&bad).unwrap_err();
1697        assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
1698    }
1699
1700    #[tokio::test]
1701    async fn init_in_directory_codex_installs_codex_hooks_and_gitignores() {
1702        let tmp = tempfile::tempdir().unwrap();
1703        let root = tmp.path();
1704        crate::test_helpers::init_git_repo(root);
1705
1706        let entry = init_in_directory(
1707            root,
1708            None,
1709            None,
1710            false,
1711            crate::config::UserContext::Toggle(false),
1712            crate::agent::Agent::Codex,
1713        )
1714        .await
1715        .unwrap();
1716
1717        // Codex hooks file written; Claude settings NOT created.
1718        assert!(root.join(".codex").join("hooks.json").exists());
1719        assert!(!root.join(".claude").join("settings.json").exists());
1720        assert_eq!(entry, ".codex/hooks.json");
1721
1722        // .gitignore covers the codex hooks file.
1723        let gi = fs::read_to_string(root.join(".gitignore")).unwrap();
1724        assert!(gi.contains(".codex/hooks.json"));
1725        assert!(gi.contains(".tracevault/"));
1726    }
1727}