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, git_repo_name, RegistrationPlan};
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
64/// If `dir` is inside a LINKED git worktree (not the primary checkout), return
65/// the primary worktree root. Returns `None` for the primary checkout or a
66/// non-git directory.
67///
68/// A linked worktree has `git --git-dir` (e.g. `<primary>/.git/worktrees/<name>`)
69/// distinct from `git --git-common-dir` (`<primary>/.git`); in the primary
70/// checkout the two are equal. The primary root is the parent of the common dir.
71fn linked_worktree_primary(dir: &Path) -> Option<PathBuf> {
72    let output = std::process::Command::new("git")
73        .args(["rev-parse", "--git-dir", "--git-common-dir"])
74        .current_dir(dir)
75        .output()
76        .ok()?;
77    if !output.status.success() {
78        return None;
79    }
80    let stdout = String::from_utf8(output.stdout).ok()?;
81    let mut lines = stdout.lines();
82    let git_dir = lines.next()?.trim();
83    let git_common_dir = lines.next()?.trim();
84
85    // git may return paths relative to `dir`; join (absolute args replace the
86    // base) then canonicalize so the comparison is robust.
87    let git_dir = dir.join(git_dir).canonicalize().ok()?;
88    let git_common_dir = dir.join(git_common_dir).canonicalize().ok()?;
89
90    if git_dir == git_common_dir {
91        None // primary checkout
92    } else {
93        git_common_dir.parent().map(Path::to_path_buf)
94    }
95}
96
97/// Validate init flag combinations against the selected agent. `--claude-settings`
98/// selects between `.claude/settings.json` and `settings.local.json`, so it only
99/// applies to the Claude Code agent — `--agent codex` always writes
100/// `.codex/hooks.json`. Returns a human-readable error for an incompatible combo
101/// so the CLI rejects it instead of silently ignoring the flag.
102pub fn validate_init_flags(
103    agent: crate::agent::Agent,
104    claude_settings_set: bool,
105) -> Result<(), String> {
106    if matches!(
107        agent,
108        crate::agent::Agent::Codex | crate::agent::Agent::Gsd | crate::agent::Agent::OpenCode
109    ) && claude_settings_set
110    {
111        return Err("--claude-settings only applies to --agent claude-code".to_string());
112    }
113    Ok(())
114}
115
116/// Set up TraceVault in `project_root`. An existing `.tracevault/config.toml`
117/// is kept and only overridden where this run says so: `server_url` and
118/// `user_context` (`None` = no flag given) replace the stored values; every
119/// other field, and any field not overridden, survives (VIS-1046).
120pub async fn init_in_directory(
121    project_root: &Path,
122    server_url: Option<&str>,
123    claude_settings: Option<ClaudeSettingsTarget>,
124    no_gitignore: bool,
125    user_context: Option<UserContext>,
126    agent: crate::agent::Agent,
127) -> Result<String, io::Error> {
128    // Check for git repository
129    if !project_root.join(".git").exists() {
130        return Err(io::Error::new(
131            io::ErrorKind::NotFound,
132            "Not a git repository. Run 'git init' first.",
133        ));
134    }
135
136    // Refuse to initialize from a linked worktree: TraceVault's `.tracevault/`,
137    // git hooks, and Claude settings all belong in the primary checkout (which
138    // every worktree shares). Initializing here would create a stray
139    // `.tracevault/` in this worktree instead. (In a linked worktree `.git` is a
140    // file, so the check above passes — this guard is what catches it.)
141    if let Some(primary) = linked_worktree_primary(project_root) {
142        return Err(io::Error::new(
143            io::ErrorKind::Unsupported,
144            format!(
145                "Run `tracevault init` from the primary checkout ({}), not a linked worktree. \
146                 cd there and run it again — all worktrees share the primary's .tracevault/.",
147                primary.display()
148            ),
149        ));
150    }
151
152    // Re-running `init` keeps the existing config (VIS-1046), so one that
153    // cannot be parsed stops it here, before anything is written: replacing
154    // it with defaults would throw away whatever the user had in it.
155    let existing_config = TracevaultConfig::try_load(project_root).map_err(|e| {
156        io::Error::new(
157            io::ErrorKind::InvalidData,
158            format!(
159                "cannot read the existing .tracevault/config.toml ({e}). Fix or remove it, \
160                 then run `tracevault init` again."
161            ),
162        )
163    })?;
164
165    // Credentials are resolved before anything is written. Without one the
166    // repo is never registered, no `repo_id` is persisted, and the hooks
167    // installed below would drop every event silently — so `init` refuses
168    // instead of leaving a setup that looks installed but records nothing
169    // (VIS-1045). A credential/URL mismatch aborts `init` too: it would
170    // otherwise register the repo against whichever instance the env var
171    // names while holding another instance's session.
172    // `io::Error::other` because this function's error type is `io::Error`.
173    let (resolved_url, resolved_credential) =
174        crate::credentials::resolve_credentials_quiet(project_root)
175            .map_err(|e| io::Error::other(e.to_string()))?;
176    let effective_url = server_url.map(String::from).or(resolved_url);
177    if resolved_credential.is_none() {
178        return Err(io::Error::new(
179            io::ErrorKind::PermissionDenied,
180            not_logged_in_message(effective_url.as_deref()),
181        ));
182    }
183
184    // Resolve the hook-file gitignore entry per agent. Claude has a
185    // shared/local settings choice; Codex has a single .codex/hooks.json.
186    let (claude_target, hook_gitignore_entry): (Option<ClaudeSettingsTarget>, String) = match agent
187    {
188        crate::agent::Agent::ClaudeCode => {
189            let target = resolve_claude_target(claude_settings)?;
190            (Some(target), target.gitignore_entry().to_string())
191        }
192        crate::agent::Agent::Codex => (None, ".codex/hooks.json".to_string()),
193        // GSD (pi) itself creates `.gsd/settings.json` in the repo when
194        // `install_gsd_extension` shells out to `gsd install <dir> -l` (a
195        // project-local package registration, analogous to Claude's
196        // `.claude/settings.local.json`) — that's GSD's own local install
197        // state, not something the user should commit.
198        crate::agent::Agent::Gsd => (None, ".gsd/".to_string()),
199        // The OpenCode plugin is installed project-locally as
200        // `.opencode/plugins/tracevault.ts` — ignore the whole `.opencode/`
201        // directory rather than just the plugin file, in case OpenCode
202        // itself later writes other local state there.
203        crate::agent::Agent::OpenCode => (None, ".opencode/".to_string()),
204    };
205
206    // Create .tracevault/ directory
207    let config_dir = TracevaultConfig::config_dir(project_root);
208    fs::create_dir_all(&config_dir)?;
209    fs::create_dir_all(config_dir.join("sessions"))?;
210    fs::create_dir_all(config_dir.join("cache"))?;
211    // Self-contained ignore for runtime artifacts, so this `.tracevault/` is
212    // safe even if the root .gitignore doesn't cover it.
213    TracevaultConfig::ensure_gitignore(&config_dir)?;
214
215    // Keep tracevault's files local — update root .gitignore (unless opted out)
216    if !no_gitignore {
217        update_root_gitignore(project_root, &hook_gitignore_entry)?;
218    }
219
220    // Register repo on server if authenticated, server URL known, and git remote available
221    let remote_url = git_remote_url(project_root);
222    if remote_url.is_none() {
223        eprintln!("Warning: no git remote 'origin' configured. Skipping server registration.");
224        eprintln!("Run 'git remote add origin <url>' then 'tracevault sync' to register.");
225    }
226
227    // Write config: the existing one with this run's flags applied, defaults
228    // only for what it lacks (`user_context` on, unless a flag says
229    // otherwise). Its `repo_id` stays in the file until registration below
230    // binds another one, so a re-run that cannot reach the server keeps it.
231    let mut config = existing_config.unwrap_or_default();
232    if let Some(url) = server_url {
233        config.server_url = Some(url.to_string());
234    }
235    config.user_context = user_context
236        .or(config.user_context)
237        .or(Some(UserContext::Toggle(true)));
238    config.save(project_root)?;
239
240    // The repo a previous `init` bound: re-running `init` keeps it if its
241    // codebase still links it.
242    let previous_repo_id = config
243        .repo_id
244        .as_deref()
245        .and_then(|id| id.parse::<uuid::Uuid>().ok());
246
247    // Install the selected agent's hooks.
248    match agent {
249        crate::agent::Agent::ClaudeCode => {
250            // `claude_target` is `Some` for the Claude agent by construction above.
251            let target =
252                claude_target.expect("claude settings target is resolved for the Claude agent");
253            install_claude_hooks(project_root, target)?;
254        }
255        crate::agent::Agent::Codex => {
256            install_codex_hooks(project_root)?;
257            println!("{}", codex_hook_trust_notice());
258        }
259        crate::agent::Agent::Gsd => {
260            // GSD (pi) loads extensions from the user-global ~/.gsd/, not from
261            // anything in the repo, so even the repo-local `init` path installs
262            // there — the repo itself only needs the .tracevault/ binding + git
263            // hooks set up above, which the extension shells out to `tracevault`
264            // to use. `Some(project_root)` makes `install_gsd_extension` run
265            // `gsd install -l` from this repo, registering the extension as a
266            // project-local install.
267            install_gsd_extension(Some(project_root))?;
268        }
269        crate::agent::Agent::OpenCode => {
270            install_opencode_plugin(Some(project_root))?;
271        }
272    }
273
274    // Install git hooks
275    install_git_hook(project_root)?;
276    install_post_commit_hook(project_root)?;
277
278    // Detect AI tools in the project
279    let detected = crate::hooks::detect_tools(project_root);
280    for tool in &detected {
281        println!("  Detected: {}", tool.name());
282    }
283
284    if let (Some(url), Some(remote)) = (effective_url, remote_url) {
285        let client = ApiClient::with_credential(&url, resolved_credential);
286        let repo_name = git_repo_name(project_root);
287        // Captured before `remote` is moved into the request below, so the
288        // codebase-resolve step doesn't need to shell out to git again.
289        let origin_url = remote.clone();
290
291        // A remote whose codebase already has a repo record binds to it:
292        // registering would upsert by THIS checkout's directory name, i.e. a
293        // second record for the same codebase whenever the names differ.
294        match crate::resolution::plan_registration(
295            &client,
296            &origin_url,
297            &repo_name,
298            previous_repo_id,
299        )
300        .await
301        {
302            Ok(RegistrationPlan::Existing(codebase, repo_id)) => {
303                println!(
304                    "Bound to existing repo {} (id: {repo_id}); not registering another record \
305                     for this codebase",
306                    codebase
307                        .repos
308                        .iter()
309                        .find(|r| r.id == repo_id)
310                        .map_or("", |r| r.name.as_str())
311                );
312                println!(
313                    "{}",
314                    crate::resolution::codebase_line(
315                        codebase.remote.name.as_deref(),
316                        &codebase.remote.normalized_url,
317                        &codebase.remote.clone_status
318                    )
319                );
320                persist_repo_binding(project_root, repo_id, Some(&codebase.remote));
321            }
322            Ok(RegistrationPlan::Ambiguous(codebase)) => {
323                eprintln!(
324                    "Warning: codebase {} already has {} repo records ({}) and none is named \
325                     '{repo_name}'; not registering another. Set `repo_id = \"<id>\"` in \
326                     .tracevault/config.toml to the one this checkout belongs to.",
327                    codebase.display_name(),
328                    codebase.repos.len(),
329                    codebase.repo_list()
330                );
331            }
332            Ok(RegistrationPlan::Register) => {
333                register_new_repo(&client, project_root, repo_name, origin_url).await;
334            }
335            // Without knowing what the server already has, registering could
336            // create the duplicate this check exists to prevent.
337            Err(e) => {
338                eprintln!(
339                    "Warning: could not check the server for an existing repo of this remote \
340                     ({e}); not registering. Run `tracevault init` again once the server is \
341                     reachable."
342                );
343            }
344        }
345    }
346
347    Ok(hook_gitignore_entry)
348}
349
350/// The error `init` fails with when no credential resolves: what went wrong,
351/// that nothing was installed, and the exact commands that fix it. `url` is
352/// the server URL already known (`--server-url`, `TRACEVAULT_SERVER_URL` or
353/// the project config), filled into the `login` command when present.
354pub fn not_logged_in_message(url: Option<&str>) -> String {
355    let url = url.unwrap_or("<URL>");
356    format!(
357        "Not logged in. Without a login TraceVault cannot register this repo, and its hooks \
358         would record nothing, so nothing was installed.\n\
359         Log in, then run init again:\n\
360         \n    tracevault login --server-url {url}\n    tracevault init\n\n\
361         (In CI, set TRACEVAULT_API_KEY instead of logging in.)"
362    )
363}
364
365/// Record the repo this checkout binds — and its codebase, display-only — in
366/// an existing `.tracevault/config.toml`, returning whether it was written.
367///
368/// Never creates the config: a checkout without one is in workspace mode (a
369/// global install binds sessions with `repo switch`), and writing one would
370/// silently pin it to bound mode. A failed write never fails the caller.
371pub(crate) fn persist_repo_binding(
372    project_root: &Path,
373    repo_id: uuid::Uuid,
374    codebase: Option<&crate::api_client::ResolveRemoteResponse>,
375) -> bool {
376    let Some(mut cfg) = TracevaultConfig::load(project_root) else {
377        return false;
378    };
379    cfg.repo_id = Some(repo_id.to_string());
380    if let Some(remote) = codebase {
381        cfg.remote_id = Some(remote.remote_id.to_string());
382        cfg.codebase_name = remote.name.clone();
383    }
384    cfg.save(project_root).is_ok()
385}
386
387/// Register a repo for a remote the server has no live repo for, and persist
388/// its id (plus the codebase, display-only) to config.toml. Failure is a
389/// warning, never a failed `init`.
390async fn register_new_repo(
391    client: &ApiClient,
392    project_root: &Path,
393    repo_name: String,
394    origin_url: String,
395) {
396    match client
397        .register_repo(crate::api_client::RegisterRepoRequest {
398            repo_name,
399            github_url: Some(origin_url.clone()),
400        })
401        .await
402    {
403        Ok(resp) => {
404            println!("Repo registered on server (id: {})", resp.repo_id);
405            // Save repo_id to config
406            if let Some(mut cfg) = TracevaultConfig::load(project_root) {
407                cfg.repo_id = Some(resp.repo_id.to_string());
408                // Best-effort: resolve the codebase (deduped by normalized
409                // remote URL) and surface it to the user. Must never fail
410                // init — `repo_id` above stays authoritative for ingest;
411                // `remote_id`/`codebase_name` here are recorded for
412                // display only.
413                if let Ok(Some(remote)) = client.resolve_remote(&origin_url).await {
414                    println!(
415                        "{}",
416                        crate::resolution::codebase_line(
417                            remote.name.as_deref(),
418                            &remote.normalized_url,
419                            &remote.clone_status
420                        )
421                    );
422                    cfg.remote_id = Some(remote.remote_id.to_string());
423                    cfg.codebase_name = remote.name.clone();
424                }
425                let _ = cfg.save(project_root);
426            }
427        }
428        Err(e) => {
429            eprintln!("{}", registration_failure_message(e.as_ref()));
430        }
431    }
432}
433
434/// The warning line for a failed repo registration during `init`. A 403 means
435/// the token is valid but not authorized to register this repo — distinct
436/// from a network/server fault, so it gets its own actionable wording; a 404
437/// means this server build doesn't recognize the registration route at all,
438/// which most plausibly means the CLI is newer than the server (a CLI/server
439/// version mismatch). Registration failure is non-fatal to `init` either
440/// way (a warning, not an aborted init — the repo can be registered later
441/// via `tracevault sync`).
442///
443/// Matches on the exact status-prefix shape `ApiClient::register_repo`
444/// produces (`"Server returned {status} ..."`, from its `authed_send_json`
445/// call) rather than a bare `.contains("403")`/`.contains("404")` — a
446/// response body that happens to contain that digit string (e.g. a proxy
447/// error page) must not be misclassified.
448fn registration_failure_message(err: &dyn std::error::Error) -> String {
449    let msg = err.to_string();
450    if msg.starts_with("Server returned 403 ") {
451        "Warning: you are not authorized to register this repo.".to_string()
452    } else if msg.starts_with("Server returned 404 ") {
453        "Warning: could not register repo on server (404) — this endpoint may not exist on \
454         this server yet, possibly a CLI/server version mismatch. Run `tracevault sync` again \
455         once the server is upgraded."
456            .to_string()
457    } else {
458        format!("Warning: could not register repo on server: {err}")
459    }
460}
461
462fn update_root_gitignore(project_root: &Path, settings_entry: &str) -> Result<(), io::Error> {
463    let path = project_root.join(".gitignore");
464    let existing = if path.exists() {
465        fs::read_to_string(&path)?
466    } else {
467        String::new()
468    };
469
470    // Only ignore what `init` actually creates or modifies: the `.tracevault/`
471    // directory and the single settings file we wrote hooks into. The
472    // other settings file is left untouched, so we don't add it here. An
473    // empty `settings_entry` means the agent writes nothing into the repo at
474    // all — skip it rather than appending a blank line.
475    let needed: Vec<&str> = [".tracevault/", settings_entry]
476        .iter()
477        .copied()
478        .filter(|entry| !entry.is_empty() && !existing.lines().any(|line| line.trim() == *entry))
479        .collect();
480
481    if needed.is_empty() {
482        return Ok(());
483    }
484
485    let mut content = existing;
486    if !content.is_empty() && !content.ends_with('\n') {
487        content.push('\n');
488    }
489    content.push_str("\n# TraceVault — local only, do not commit\n");
490    for entry in needed {
491        content.push_str(entry);
492        content.push('\n');
493    }
494
495    fs::write(path, content)
496}
497
498const HOOK_MARKER: &str = "# tracevault:enforce";
499const OLD_HOOK_MARKER: &str = "# tracevault:auto-push";
500
501fn install_git_hook(project_root: &Path) -> Result<(), io::Error> {
502    let hooks_dir = project_root.join(".git/hooks");
503    fs::create_dir_all(&hooks_dir)?;
504
505    let hook_path = hooks_dir.join("pre-push");
506    // Capture git's pre-push ref list once, then feed it to `check` explicitly
507    // rather than relying on it inheriting stdin from the hook process. `sync`
508    // never reads stdin, so today it reaches `check` anyway — this only drops
509    // the dependency on that inheritance for hooks installed from here on;
510    // already-installed hooks keep working without re-running `tracevault
511    // init`.
512    let tracevault_block = format!(
513        "{HOOK_MARKER}\n\
514         # Capture git's pre-push ref list once; `check` uses it to determine\n\
515         # which files are being pushed.\n\
516         tracevault_prepush_stdin=$(cat)\n\
517         tracevault sync 2>/dev/null || true\n\
518         printf '%s' \"$tracevault_prepush_stdin\" | tracevault check || {{ echo \"tracevault: policy check failed\"; exit 1; }}\n"
519    );
520
521    if hook_path.exists() {
522        let existing = fs::read_to_string(&hook_path)?;
523
524        // Already has new-style hook
525        if existing.contains(HOOK_MARKER) {
526            return Ok(());
527        }
528
529        // Replace old-style hook block if present
530        if existing.contains(OLD_HOOK_MARKER) {
531            let mut new_content = String::new();
532            let mut skip = false;
533            for line in existing.lines() {
534                if line.contains(OLD_HOOK_MARKER) {
535                    skip = true;
536                    continue;
537                }
538                if skip {
539                    // Skip old tracevault lines (they start with "tracevault " or are empty continuations)
540                    if line.starts_with("tracevault ") {
541                        continue;
542                    }
543                    skip = false;
544                }
545                new_content.push_str(line);
546                new_content.push('\n');
547            }
548            if !new_content.ends_with('\n') {
549                new_content.push('\n');
550            }
551            new_content.push_str(&tracevault_block);
552            fs::write(&hook_path, new_content)?;
553        } else {
554            // Append to existing hook
555            let mut content = existing;
556            if !content.ends_with('\n') {
557                content.push('\n');
558            }
559            content.push_str(&tracevault_block);
560            fs::write(&hook_path, content)?;
561        }
562    } else {
563        let content = format!("#!/bin/sh\n{tracevault_block}");
564        fs::write(&hook_path, content)?;
565    }
566
567    // Make executable
568    #[cfg(unix)]
569    {
570        use std::os::unix::fs::PermissionsExt;
571        let mut perms = fs::metadata(&hook_path)?.permissions();
572        perms.set_mode(0o755);
573        fs::set_permissions(&hook_path, perms)?;
574    }
575
576    Ok(())
577}
578
579const POST_COMMIT_MARKER: &str = "# tracevault:post-commit";
580
581fn install_post_commit_hook(project_root: &Path) -> Result<(), io::Error> {
582    let hooks_dir = project_root.join(".git/hooks");
583    fs::create_dir_all(&hooks_dir)?;
584
585    let hook_path = hooks_dir.join("post-commit");
586    let tracevault_block = format!("{POST_COMMIT_MARKER}\ntracevault commit-push 2>/dev/null &\n");
587
588    if hook_path.exists() {
589        let existing = fs::read_to_string(&hook_path)?;
590
591        if existing.contains(POST_COMMIT_MARKER) {
592            return Ok(());
593        }
594
595        let mut content = existing;
596        if !content.ends_with('\n') {
597            content.push('\n');
598        }
599        content.push_str(&tracevault_block);
600        fs::write(&hook_path, content)?;
601    } else {
602        let content = format!("#!/bin/sh\n{tracevault_block}");
603        fs::write(&hook_path, content)?;
604    }
605
606    #[cfg(unix)]
607    {
608        use std::os::unix::fs::PermissionsExt;
609        let mut perms = fs::metadata(&hook_path)?.permissions();
610        perms.set_mode(0o755);
611        fs::set_permissions(&hook_path, perms)?;
612    }
613
614    Ok(())
615}
616
617fn install_claude_hooks(
618    project_root: &Path,
619    target: ClaudeSettingsTarget,
620) -> Result<(), io::Error> {
621    let claude_dir = project_root.join(".claude");
622    fs::create_dir_all(&claude_dir)?;
623    merge_hooks_into_file(&claude_dir.join(target.filename()), &tracevault_hooks())
624}
625
626pub fn tracevault_hooks() -> serde_json::Value {
627    serde_json::json!({
628        "PreToolUse": [{
629            "matcher": "Write|Edit|Bash",
630            "hooks": [{
631                "type": "command",
632                "command": "tracevault stream --event pre-tool-use",
633                "timeout": 10,
634                "statusMessage": "TraceVault: streaming pre-tool event"
635            }]
636        }],
637        "PostToolUse": [{
638            "matcher": "",
639            "hooks": [{
640                "type": "command",
641                "command": "tracevault stream --event post-tool-use",
642                "timeout": 10,
643                "statusMessage": "TraceVault: streaming post-tool event"
644            }]
645        }],
646        "Notification": [{
647            "matcher": "",
648            "hooks": [{
649                "type": "command",
650                "command": "tracevault stream --event notification",
651                "timeout": 10,
652                "statusMessage": "TraceVault: streaming notification"
653            }]
654        }],
655        "Stop": [{
656            "matcher": "",
657            "hooks": [{
658                "type": "command",
659                "command": "tracevault stream --event stop",
660                "timeout": 10,
661                "statusMessage": "TraceVault: finalizing session"
662            }]
663        }],
664        // Every hook above also sends new subagent transcript lines; this one
665        // catches a background subagent that finishes after the last `Stop`.
666        "SubagentStop": [{
667            "matcher": "",
668            "hooks": [{
669                "type": "command",
670                "command": "tracevault stream --event subagent-stop",
671                "timeout": 10,
672                "statusMessage": "TraceVault: streaming subagent transcript"
673            }]
674        }],
675        "SessionStart": [{
676            "matcher": "",
677            "hooks": [{
678                "type": "command",
679                "command": "tracevault session-start",
680                "timeout": 10,
681                "statusMessage": "TraceVault: session start"
682            }]
683        }],
684        "UserPromptSubmit": [{
685            "matcher": "",
686            "hooks": [{
687                "type": "command",
688                "command": "tracevault user-prompt",
689                "timeout": 10,
690                "statusMessage": "TraceVault: policy reinforcement"
691            }]
692        }]
693    })
694}
695
696/// Codex CLI hook set, mirroring `tracevault_hooks()` but with Codex commands.
697/// What to tell the user after Codex hooks are installed.
698///
699/// Writing `hooks.json` is only half the setup: Codex >= 0.153 gates hooks
700/// behind persisted *hook trust*, and a non-interactive `codex exec` skips
701/// untrusted hooks without printing anything — so capture looks installed and
702/// silently produces no sessions until trust is granted once. Observed on
703/// Codex 0.153.4, where neither `codex doctor` nor `codex features` reports
704/// the trust state, which is why the CLI has to say it here.
705pub fn codex_hook_trust_notice() -> &'static str {
706    "Codex gates hooks behind hook trust: until it is granted, `codex exec` skips them \
707     silently and no session is captured. Run `codex` once interactively in a repo and \
708     approve the hook-trust prompt; unattended runs (CI) can pass \
709     `--dangerously-bypass-hook-trust` instead."
710}
711
712/// Capture hooks carry `--agent codex`; the injection hooks (session-start /
713/// user-prompt) are agent-agnostic. Matchers are `""` (all tools).
714///
715/// We intentionally do NOT register a `PreToolUse` hook for Codex. Unlike Claude
716/// Code — whose `PreToolUse` is scoped to `Write|Edit|Bash` — the CLI does no
717/// Codex-specific pre-tool work, and `PostToolUse` + `Stop` already stream the
718/// (incremental, offset-tracked) rollout. A pre-tool hook on every tool call
719/// would only double the per-call streaming for no added capture. No
720/// `Notification` event either (Codex has none).
721pub fn codex_hooks() -> serde_json::Value {
722    serde_json::json!({
723        "SessionStart": [{
724            "matcher": "",
725            "hooks": [{ "type": "command", "command": "tracevault session-start", "timeout": 10, "statusMessage": "TraceVault: session start" }]
726        }],
727        "UserPromptSubmit": [{
728            "matcher": "",
729            "hooks": [{ "type": "command", "command": "tracevault user-prompt", "timeout": 10, "statusMessage": "TraceVault: policy reinforcement" }]
730        }],
731        "PostToolUse": [{
732            "matcher": "",
733            "hooks": [{ "type": "command", "command": "tracevault stream --event post-tool-use --agent codex", "timeout": 10, "statusMessage": "TraceVault: streaming post-tool event" }]
734        }],
735        "Stop": [{
736            "matcher": "",
737            "hooks": [{ "type": "command", "command": "tracevault stream --event stop --agent codex", "timeout": 10, "statusMessage": "TraceVault: finalizing session" }]
738        }]
739    })
740}
741
742/// Embedded pi/GSD extension source (bundled at build time — see
743/// `assets/gsd-extension/{index.ts,package.json,extension-manifest.json}`,
744/// the checked-in source this installer writes verbatim).
745const GSD_EXT_INDEX_TS: &str = include_str!("../../assets/gsd-extension/index.ts");
746const GSD_EXT_PACKAGE_JSON: &str = include_str!("../../assets/gsd-extension/package.json");
747const GSD_EXT_MANIFEST_JSON: &str =
748    include_str!("../../assets/gsd-extension/extension-manifest.json");
749
750/// Path of the stable directory (under the user's config dir) that holds the
751/// TraceVault GSD extension source, shared by `install_gsd_extension` so the
752/// write and the `gsd install` invocation always agree on where it lives.
753fn gsd_extension_source_dir() -> io::Result<PathBuf> {
754    let config_dir = dirs::config_dir().or_else(|| dirs::home_dir().map(|h| h.join(".config")));
755    let config_dir = config_dir
756        .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "no config or home dir"))?;
757    Ok(config_dir.join("tracevault").join("gsd-extension"))
758}
759
760/// Install the TraceVault pi/GSD extension and register it with GSD so it
761/// actually loads.
762///
763/// GSD (pi) only loads an extension that (a) has an `extension-manifest.json`
764/// in its directory *and* (b) was registered via `gsd install <dir>` — a
765/// hand-written `registry.json` entry is inert (`gsd list` won't show it).
766/// So this writes the extension source (`index.ts`, `package.json`,
767/// `extension-manifest.json`) to a stable, idempotent source directory
768/// (`<config_dir>/tracevault/gsd-extension`), best-effort cleans up any
769/// stale/inert registration left behind by an older version of this
770/// installer, and then shells out to `gsd install` to register + load it.
771///
772/// `project_root` selects how `gsd install` is invoked:
773/// - `Some(repo)`: project-local install (`gsd install <dir> -l`, run with
774///   `repo` as the working directory) — used by `tracevault init`.
775/// - `None`: global install (`gsd install <dir>`, applies to all GSD
776///   sessions on this machine) — used by `tracevault init --global`.
777///
778/// If the `gsd` binary can't be found or the install command fails, this
779/// does NOT fail `init`: it prints a warning explaining how to finish the
780/// registration by hand and returns `Ok(())`. The extension source is still
781/// written either way, so the user (or a later retry) has something to
782/// register.
783pub fn install_gsd_extension(project_root: Option<&Path>) -> io::Result<()> {
784    let home =
785        dirs::home_dir().ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "no home dir"))?;
786    let gsd_home = home.join(".gsd");
787
788    let source_dir = gsd_extension_source_dir()?;
789    fs::create_dir_all(&source_dir)?;
790    fs::write(source_dir.join("index.ts"), GSD_EXT_INDEX_TS)?;
791    fs::write(source_dir.join("package.json"), GSD_EXT_PACKAGE_JSON)?;
792    fs::write(
793        source_dir.join("extension-manifest.json"),
794        GSD_EXT_MANIFEST_JSON,
795    )?;
796
797    // Best-effort cleanup of the OLD, broken install (hand-written registry
798    // entries that GSD never actually loaded). Never blocks the rest of the
799    // install — see `cleanup_stale_gsd_registration`.
800    if let Err(e) = cleanup_stale_gsd_registration(&gsd_home) {
801        eprintln!("Warning: could not clean up the previous GSD extension registration: {e}");
802    }
803
804    // Register + load the extension via the `gsd` CLI. `gsd install` is what
805    // actually makes GSD load the extension; our own registry.json edits
806    // never did.
807    let local_flag = project_root.is_some();
808    let mut cmd = std::process::Command::new("gsd");
809    cmd.arg("install").arg(&source_dir);
810    if let Some(root) = project_root {
811        cmd.arg("-l");
812        cmd.current_dir(root);
813    }
814
815    let retry_hint = format!(
816        "gsd install {}{}",
817        source_dir.display(),
818        if local_flag { " -l" } else { "" }
819    );
820
821    match cmd.output() {
822        Ok(output) if output.status.success() => {
823            println!(
824                "TraceVault: installed and registered the GSD extension ({}).",
825                source_dir.display()
826            );
827        }
828        Ok(output) => {
829            eprintln!(
830                "TraceVault: installed the GSD extension source to {}, but `gsd install` failed:\n{}Ensure `gsd` is on PATH and run: `{retry_hint}` to enable capture.",
831                source_dir.display(),
832                String::from_utf8_lossy(&output.stderr),
833            );
834        }
835        Err(e) => {
836            eprintln!(
837                "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.",
838                source_dir.display(),
839            );
840        }
841    }
842
843    Ok(())
844}
845
846/// TraceVault OpenCode plugin source, embedded from the checked-in assets
847/// this installer writes verbatim (mirrors the GSD extension embeds above).
848const OPENCODE_PLUGIN_INDEX: &str = include_str!("../../assets/opencode-plugin/index.ts");
849
850/// Install the TraceVault OpenCode plugin. `project_root = Some(dir)` installs
851/// project-local at `<dir>/.opencode/plugins/tracevault.ts`; `None` installs
852/// global at `~/.config/opencode/plugins/tracevault.ts` (using the same
853/// config-dir resolution as `gsd_extension_source_dir` above). OpenCode
854/// auto-loads `*.ts` modules from that directory — no separate "install"
855/// command. Returns an error on failure (unresolvable config dir, or a write
856/// error) so the caller aborts init loudly, consistent with the Codex/GSD arms
857/// — a swallowed failure would make `init` report success while no plugin was
858/// written, silently disabling capture.
859///
860/// A FLAT `.ts` file is used rather than a `tracevault/` package directory: a
861/// package subdir (index.ts + package.json) makes OpenCode try to resolve it as
862/// an npm package and stalls at startup offline, whereas a flat module loads
863/// directly (both confirmed during the capture spike). The plugin only imports
864/// the `node:child_process` builtin, so it needs no package manifest.
865pub fn install_opencode_plugin(project_root: Option<&Path>) -> io::Result<()> {
866    let plugins_dir = match project_root {
867        Some(root) => root.join(".opencode").join("plugins"),
868        None => {
869            let config_dir =
870                dirs::config_dir().or_else(|| dirs::home_dir().map(|h| h.join(".config")));
871            config_dir
872                .ok_or_else(|| {
873                    io::Error::new(
874                        io::ErrorKind::NotFound,
875                        "could not determine the config directory for the OpenCode plugin install",
876                    )
877                })?
878                .join("opencode")
879                .join("plugins")
880        }
881    };
882
883    write_opencode_plugin_files(&plugins_dir)
884}
885
886fn write_opencode_plugin_files(plugins_dir: &Path) -> io::Result<()> {
887    fs::create_dir_all(plugins_dir)?;
888    fs::write(plugins_dir.join("tracevault.ts"), OPENCODE_PLUGIN_INDEX)?;
889    Ok(())
890}
891
892/// Best-effort cleanup of the extension registration left behind by an OLDER
893/// version of this installer: the `tracevault-tracker` directory (an earlier,
894/// incorrect Codex-clone `hooks.json` shim that impersonated this extension
895/// under the wrong name) and any registry entries for `tracevault-tracker` or
896/// `tracevault` — both are inert now that `gsd install` manages registration.
897///
898/// If `registry.json` is missing, there's nothing to clean up. If it exists
899/// but fails to parse, or its shape is not a valid registry (root not an
900/// object, or a non-object `entries` field), it is structurally corrupt: we
901/// leave it byte-for-byte untouched (skip cleanup) rather than risk
902/// destroying every other extension the user has registered.
903pub fn cleanup_stale_gsd_registration(gsd_home: &Path) -> io::Result<()> {
904    let ext_root = gsd_home.join("extensions");
905    let reg_path = ext_root.join("registry.json");
906
907    // Validate the registry BEFORE mutating anything under ~/.gsd. If it exists
908    // but is structurally corrupt (unparseable, or a non-object root/`entries`),
909    // leave the extensions directory entirely untouched — not even the stale
910    // tracker dir is removed — so a corrupt registry yields zero mutation.
911    let reg: Option<serde_json::Value> = if reg_path.exists() {
912        let content = fs::read_to_string(&reg_path)?;
913        let parsed: serde_json::Value = match serde_json::from_str(&content) {
914            Ok(v) => v,
915            Err(_) => return Ok(()), // corrupt: touch nothing
916        };
917        let corrupt = match parsed.as_object() {
918            None => true,
919            Some(obj) => matches!(obj.get("entries"), Some(v) if !v.is_object()),
920        };
921        if corrupt {
922            return Ok(()); // structurally corrupt: touch nothing
923        }
924        Some(parsed)
925    } else {
926        None
927    };
928
929    // Registry is valid or absent — now safe to remove the superseded tracker shim.
930    let stale = ext_root.join("tracevault-tracker");
931    if stale.exists() {
932        fs::remove_dir_all(&stale)?;
933    }
934
935    // Drop stale registry entries (only when a valid registry exists).
936    if let Some(mut reg) = reg {
937        if let Some(entries) = reg.get_mut("entries").and_then(|e| e.as_object_mut()) {
938            let removed_tracker = entries.remove("tracevault-tracker").is_some();
939            let removed_inert = entries.remove("tracevault").is_some();
940            if removed_tracker || removed_inert {
941                // Atomic write (temp file + rename), pretty-printed.
942                let tmp = reg_path.with_extension("json.tmp");
943                fs::write(&tmp, serde_json::to_string_pretty(&reg)?)?;
944                fs::rename(&tmp, &reg_path)?;
945            }
946        }
947    }
948    Ok(())
949}
950
951/// Bring the TraceVault hooks in `hooks_path` to `ours` via [`merge_hooks`]
952/// (foreign hooks and other keys are kept), written through
953/// [`update_json_file`]. The one
954/// install path for every hook file — per-repo Claude (`settings.json` or
955/// `settings.local.json`), global Claude and Codex (`hooks.json`), whose roots
956/// are the object `merge_hooks` mutates (`root["hooks"]`). A file that is
957/// already current is not rewritten, so its formatting survives a re-run. On a
958/// merge error (malformed existing file) it returns before writing, so the
959/// target is never clobbered and no temp file is left behind.
960fn merge_hooks_into_file(hooks_path: &Path, ours: &serde_json::Value) -> io::Result<()> {
961    update_json_file(hooks_path, "its hooks", |root| {
962        merge_hooks(root, ours, hooks_path)
963    })
964}
965
966/// Read `path` as JSON (or `{}` if absent), apply `mutate`, and write the
967/// result back atomically (sibling temp file + rename), keeping the file's
968/// mode, a symlink's target, and — when `mutate` changed nothing — the file
969/// untouched. A missing file that `mutate` leaves as `{}` is not created. On a
970/// `mutate` error (malformed existing file) it returns before writing, so the
971/// target is never clobbered and no temp file is left behind. `what` names
972/// what is being updated, for the error when the file keeps changing.
973pub(crate) fn update_json_file(
974    path: &Path,
975    what: &str,
976    mut mutate: impl FnMut(&mut serde_json::Value) -> io::Result<()>,
977) -> io::Result<()> {
978    // Defense-in-depth against path traversal: callers pass a constant filename
979    // joined to a home/cwd base (global callers additionally go through
980    // `safe_join`), so a `..` component should never appear — reject it outright
981    // rather than read/write through it.
982    if path
983        .components()
984        .any(|c| c == std::path::Component::ParentDir)
985    {
986        return Err(io::Error::new(
987            io::ErrorKind::InvalidInput,
988            format!("refusing to use path with '..': {}", path.display()),
989        ));
990    }
991    // A settings file symlinked to a centrally managed config is updated at its
992    // target, so the link survives (renaming over it would replace it with a
993    // regular file). A dangling link fails here instead of being overwritten.
994    let target = match fs::symlink_metadata(path) {
995        Ok(meta) if meta.file_type().is_symlink() => fs::canonicalize(path)?,
996        _ => path.to_path_buf(),
997    };
998    // Another writer (a second `init`, Claude Code saving a permission) may
999    // change the file between our read and our rename; publishing then would
1000    // drop its change. So the file is re-read just before the rename and the
1001    // merge redone if it moved. This narrows the window, it cannot close it:
1002    // Claude Code takes no lock we could share.
1003    for _ in 0..3 {
1004        let existing = read_existing(&target)?;
1005        let mut root: serde_json::Value = match &existing {
1006            Some((_, content)) => serde_json::from_str(content).map_err(|e| {
1007                io::Error::new(
1008                    io::ErrorKind::InvalidData,
1009                    format!("Failed to parse {}: {e}", path.display()),
1010                )
1011            })?,
1012            None => serde_json::json!({}),
1013        };
1014
1015        let before = existing.is_some().then(|| root.to_string());
1016        mutate(&mut root)?;
1017        if before.as_deref() == Some(root.to_string().as_str())
1018            || (existing.is_none() && root == serde_json::json!({}))
1019        {
1020            return Ok(());
1021        }
1022
1023        let formatted = serde_json::to_string_pretty(&root).map_err(|e| {
1024            io::Error::other(format!("Failed to serialize {}: {e}", path.display()))
1025        })?;
1026        let tmp = unique_temp_sibling(&target);
1027        let published = write_owner_only(&tmp, formatted.as_bytes())
1028            .and_then(|()| {
1029                // Keep the mode the user gave the file (a 0600 settings.local.json
1030                // may carry credentials in `env`); a new file stays owner-only.
1031                match &existing {
1032                    Some((permissions, _)) => fs::set_permissions(&tmp, permissions.clone()),
1033                    None => Ok(()),
1034                }
1035            })
1036            .and_then(|()| {
1037                let unchanged = read_existing(&target)?.map(|(_, c)| c)
1038                    == existing.as_ref().map(|(_, c)| c.clone());
1039                if unchanged {
1040                    fs::rename(&tmp, &target).map(|()| true)
1041                } else {
1042                    Ok(false)
1043                }
1044            });
1045        match published {
1046            Ok(true) => return Ok(()),
1047            Ok(false) => {
1048                let _ = fs::remove_file(&tmp);
1049            }
1050            Err(e) => {
1051                let _ = fs::remove_file(&tmp);
1052                return Err(e);
1053            }
1054        }
1055    }
1056    Err(io::Error::other(format!(
1057        "{} kept changing while TraceVault updated {what}; re-run `tracevault init`",
1058        path.display()
1059    )))
1060}
1061
1062/// The permissions and contents of `path`, or `None` when it does not exist.
1063fn read_existing(path: &Path) -> io::Result<Option<(fs::Permissions, String)>> {
1064    let permissions = match fs::metadata(path) {
1065        Ok(meta) => meta.permissions(),
1066        Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None),
1067        Err(e) => return Err(e),
1068    };
1069    Ok(Some((permissions, fs::read_to_string(path)?)))
1070}
1071
1072/// A temp path next to `target` that no other install — in this process or a
1073/// concurrent one — uses, so two `init`s never write or publish each other's
1074/// half-written file.
1075fn unique_temp_sibling(target: &Path) -> PathBuf {
1076    static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1077    let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1078    let nanos = std::time::SystemTime::now()
1079        .duration_since(std::time::UNIX_EPOCH)
1080        .map(|d| d.subsec_nanos())
1081        .unwrap_or_default();
1082    let mut name = target.file_name().unwrap_or_default().to_os_string();
1083    name.push(format!(".{}.{n}.{nanos}.tmp", std::process::id()));
1084    target.with_file_name(name)
1085}
1086
1087/// Create `path` (which must not exist), readable only by its owner on Unix,
1088/// and write `contents` — so the temp copy of a settings file never exposes
1089/// it while being written.
1090fn write_owner_only(path: &Path, contents: &[u8]) -> io::Result<()> {
1091    let mut options = fs::OpenOptions::new();
1092    options.write(true).create_new(true);
1093    #[cfg(unix)]
1094    {
1095        use std::os::unix::fs::OpenOptionsExt;
1096        options.mode(0o600);
1097    }
1098    options.open(path)?.write_all(contents)
1099}
1100
1101/// Deep-merge the Codex hook set into `<project_root>/.codex/hooks.json`,
1102/// creating it if absent (idempotent, never clobbers existing hooks/keys,
1103/// atomic write). Repo-local counterpart of [`install_global_codex_hooks`].
1104pub fn install_codex_hooks(project_root: &Path) -> io::Result<()> {
1105    let codex_dir = project_root.join(".codex");
1106    fs::create_dir_all(&codex_dir)?;
1107    merge_hooks_into_file(&codex_dir.join("hooks.json"), &codex_hooks())
1108}
1109
1110/// Install TraceVault's Codex hooks into `<codex_dir>/hooks.json` and append a
1111/// workspace-mode instruction block to `<codex_dir>/AGENTS.md` (idempotent,
1112/// atomic), mirroring the Claude global install's `settings.json` + `CLAUDE.md`.
1113/// Intended for `tracevault init --global --agent codex`. Codex reads `AGENTS.md`
1114/// for agent instructions, so the workspace-mode block reaches detached Codex
1115/// sessions the same way the `CLAUDE.md` block reaches Claude ones.
1116pub fn install_global_codex_hooks(codex_dir: &Path) -> io::Result<()> {
1117    fs::create_dir_all(codex_dir)?;
1118    // Canonicalize the base so safe_join keeps target files directly within it.
1119    let base = codex_dir.canonicalize()?;
1120    merge_hooks_into_file(&safe_join(&base, "hooks.json")?, &codex_hooks())?;
1121    append_workspace_md(&safe_join(&base, "AGENTS.md")?)
1122}
1123
1124// Workspace-mode instruction block. Agent-agnostic (it only references
1125// `tracevault repo …`), so it's shared verbatim between the Claude global
1126// install's `CLAUDE.md` and the Codex global install's `AGENTS.md`.
1127const GLOBAL_CLAUDE_MD_MARKER: &str = "<!-- tracevault:workspace-mode -->";
1128
1129const GLOBAL_CLAUDE_MD_BLOCK: &str = "\
1130<!-- tracevault:workspace-mode -->
1131## TraceVault (workspace mode)
1132A session started in a registered repo's checkout is bound to that repo automatically. To work
1133on a different repo, run `tracevault repo switch <path>` to bind tracing and fetch that repo's
1134policies; treat its output as binding. Use `--path <path>` on `tracevault repo status` for a
1135one-off. Repos must already be registered with TraceVault.
1136";
1137
1138/// Append the workspace-mode instruction block to `md_path` (creating it if
1139/// absent), idempotently — guarded by [`GLOBAL_CLAUDE_MD_MARKER`], so a re-run
1140/// never duplicates it and any existing user content is preserved. Shared by
1141/// the Claude global install (`CLAUDE.md`) and the Codex global install
1142/// (`AGENTS.md`).
1143fn append_workspace_md(md_path: &Path) -> io::Result<()> {
1144    // Defense-in-depth against path traversal (see `merge_hooks_into_file`).
1145    if md_path
1146        .components()
1147        .any(|c| c == std::path::Component::ParentDir)
1148    {
1149        return Err(io::Error::new(
1150            io::ErrorKind::InvalidInput,
1151            format!("refusing to use path with '..': {}", md_path.display()),
1152        ));
1153    }
1154    let existing = if md_path.exists() {
1155        fs::read_to_string(md_path)?
1156    } else {
1157        String::new()
1158    };
1159    if existing.contains(GLOBAL_CLAUDE_MD_MARKER) {
1160        return Ok(());
1161    }
1162    let mut content = existing;
1163    if !content.is_empty() && !content.ends_with('\n') {
1164        content.push('\n');
1165    }
1166    if !content.is_empty() {
1167        content.push('\n');
1168    }
1169    content.push_str(GLOBAL_CLAUDE_MD_BLOCK);
1170    fs::write(md_path, content)
1171}
1172
1173/// Join a constant file name to `base` and confirm the result stays directly
1174/// within `base` — defense-in-depth so a path derived from the environment
1175/// ($HOME) cannot escape the intended `.claude` directory.
1176pub(crate) fn safe_join(base: &Path, name: &str) -> io::Result<PathBuf> {
1177    let joined = base.join(name);
1178    if joined.parent() != Some(base) {
1179        return Err(io::Error::new(
1180            io::ErrorKind::InvalidInput,
1181            format!(
1182                "refusing to access path outside {}: {}",
1183                base.display(),
1184                joined.display()
1185            ),
1186        ));
1187    }
1188    Ok(joined)
1189}
1190
1191/// An inner hook belongs to TraceVault when its `command` starts with
1192/// `tracevault ` — every hook command `init` has ever installed does, and a
1193/// user's own hook running something else never does. This is what lets a
1194/// re-run replace exactly our entries (old matcher, timeout, status message,
1195/// a dropped event) and nothing else.
1196const TRACEVAULT_COMMAND_PREFIX: &str = "tracevault ";
1197
1198fn is_tracevault_hook(hook: &serde_json::Value) -> bool {
1199    hook.get("command")
1200        .and_then(|c| c.as_str())
1201        .is_some_and(|c| c.starts_with(TRACEVAULT_COMMAND_PREFIX))
1202}
1203
1204/// Remove TraceVault-owned inner hooks from one event's matcher groups. A
1205/// group that held only our hooks is dropped; a group shared with foreign
1206/// hooks keeps them and everything else it had. Groups without any of our
1207/// hooks are left untouched. Returns the position of the first dropped group,
1208/// so the current set can go back where the old one was — which keeps a
1209/// re-run on an up-to-date file a no-op.
1210fn strip_tracevault_hooks(entries: &mut Vec<serde_json::Value>) -> Option<usize> {
1211    let mut slot = None;
1212    let mut kept = Vec::with_capacity(entries.len());
1213    for mut entry in entries.drain(..) {
1214        if let Some(inner) = entry.get_mut("hooks").and_then(|h| h.as_array_mut()) {
1215            let before = inner.len();
1216            inner.retain(|hook| !is_tracevault_hook(hook));
1217            if inner.is_empty() && before > 0 {
1218                slot.get_or_insert(kept.len());
1219                continue;
1220            }
1221        }
1222        kept.push(entry);
1223    }
1224    *entries = kept;
1225    slot
1226}
1227
1228/// Bring `settings["hooks"]` to exactly `ours` for TraceVault's entries while
1229/// keeping every foreign hook: our inner hooks (see [`is_tracevault_hook`])
1230/// are removed from every event, then the current `ours` entries are put back
1231/// in their place (appended for an event that had none). Re-running converges
1232/// to the current hook set, and events we no longer install lose our entries.
1233/// Top-level keys and foreign hooks are never touched.
1234///
1235/// Absent values (no `hooks` key, no entry for a given event) are created
1236/// fresh — that's fine; a missing file reaches here as `{}`. But if an
1237/// EXISTING value has an unexpected shape (top-level `settings` isn't an
1238/// object — `null` included —, an existing `hooks` isn't an object, or one of
1239/// our events isn't an array), this errors loudly instead of silently
1240/// discarding it. A foreign event whose value isn't an array is left as it is.
1241fn merge_hooks(
1242    settings: &mut serde_json::Value,
1243    ours: &serde_json::Value,
1244    path: &Path,
1245) -> io::Result<()> {
1246    let settings_obj = settings.as_object_mut().ok_or_else(|| {
1247        io::Error::new(
1248            io::ErrorKind::InvalidData,
1249            format!("{} is not a JSON object", path.display()),
1250        )
1251    })?;
1252
1253    let hooks_value = settings_obj
1254        .entry("hooks")
1255        .or_insert_with(|| serde_json::json!({}));
1256    let hooks_obj = hooks_value.as_object_mut().ok_or_else(|| {
1257        io::Error::new(
1258            io::ErrorKind::InvalidData,
1259            format!("{} \"hooks\" key is not a JSON object", path.display()),
1260        )
1261    })?;
1262
1263    let empty = serde_json::Map::new();
1264    let ours_obj = ours.as_object().unwrap_or(&empty);
1265
1266    // Validate before mutating anything, so an error leaves `settings` as read.
1267    for event in ours_obj.keys() {
1268        if hooks_obj.get(event).is_some_and(|v| !v.is_array()) {
1269            return Err(io::Error::new(
1270                io::ErrorKind::InvalidData,
1271                format!(
1272                    "{} \"hooks\".\"{event}\" is not a JSON array",
1273                    path.display()
1274                ),
1275            ));
1276        }
1277    }
1278
1279    let mut emptied = Vec::new();
1280    for (event, value) in hooks_obj.iter_mut() {
1281        let Some(existing) = value.as_array_mut() else {
1282            continue;
1283        };
1284        let had_entries = !existing.is_empty();
1285        let slot = strip_tracevault_hooks(existing);
1286        let our_entries = ours_obj.get(event).and_then(|v| v.as_array());
1287        match our_entries {
1288            Some(our_entries) => {
1289                let at = slot.unwrap_or(existing.len());
1290                existing.splice(at..at, our_entries.iter().cloned());
1291            }
1292            None if had_entries && existing.is_empty() => emptied.push(event.clone()),
1293            None => {}
1294        }
1295    }
1296    // An event that only ever held our (now retired) hooks goes away entirely.
1297    hooks_obj.retain(|event, _| !emptied.contains(event));
1298
1299    for (event, our_array) in ours_obj {
1300        if !hooks_obj.contains_key(event) {
1301            hooks_obj.insert(event.clone(), our_array.clone());
1302        }
1303    }
1304
1305    Ok(())
1306}
1307
1308/// Install TraceVault's Claude Code hooks into `claude_dir/settings.json`
1309/// (deep-merged, never clobbering existing hooks/keys) and append a
1310/// workspace-mode instruction block to `claude_dir/CLAUDE.md` (idempotent,
1311/// guarded by a marker comment). Intended for `tracevault init --global`,
1312/// installing once for all Claude Code sessions rather than per-repo.
1313pub fn install_global_hooks(claude_dir: &Path) -> io::Result<()> {
1314    fs::create_dir_all(claude_dir)?;
1315
1316    // Canonicalize the base to defend against path traversal attacks.
1317    // safe_join will verify that target files stay directly within this base.
1318    let base = claude_dir.canonicalize()?;
1319
1320    // --- settings.json: deep-merge hooks (atomic) ---
1321    merge_hooks_into_file(&safe_join(&base, "settings.json")?, &tracevault_hooks())?;
1322
1323    // --- CLAUDE.md: append the workspace-mode instruction block, idempotently ---
1324    append_workspace_md(&safe_join(&base, "CLAUDE.md")?)
1325}
1326
1327/// Write the user-level `config.toml` (under `config_root`) carrying the
1328/// user-context setting. An EXISTING user config is preserved (this mirrors the
1329/// "don't clobber" contract of the global-hooks install): `requested` overrides
1330/// the user_context when a flag was given; otherwise an existing value is kept,
1331/// and only a first-time setup (no existing config) defaults to enabled.
1332/// When the resulting layer is enabled, the referenced context file is seeded
1333/// (empty) if absent — a custom `--user-context <path>` seeds THAT file, a
1334/// disabled layer seeds nothing. Returns the active context file path (the file
1335/// the hook will read), or `None` when the layer is disabled. Used by `init --global`.
1336pub fn write_global_user_config_in(
1337    config_root: &Path,
1338    requested: Option<UserContext>,
1339) -> io::Result<Option<PathBuf>> {
1340    fs::create_dir_all(config_root)?;
1341    // Preserve an existing (valid) user config; malformed/missing → start fresh.
1342    let mut config = crate::config::try_load_user_config_in(config_root)
1343        .ok()
1344        .flatten()
1345        .unwrap_or_default();
1346    // Requested flag wins; else keep an existing value; else first-run default = enabled.
1347    let user_context = requested
1348        .or_else(|| config.user_context.clone())
1349        .unwrap_or(UserContext::Toggle(true));
1350    let active = user_context
1351        .resolve()
1352        .map(|_| user_context.path_in(config_root));
1353    config.user_context = Some(user_context);
1354    fs::write(user_config_path_in(config_root), config.to_toml())?;
1355    if let Some(ref ctx_path) = active {
1356        if !ctx_path.exists() {
1357            Context::default().save_to(ctx_path)?;
1358        }
1359    }
1360    Ok(active)
1361}
1362
1363#[cfg(test)]
1364mod tests {
1365    use super::*;
1366    use std::io::{BufRead, BufReader, Write};
1367    use std::net::TcpListener;
1368    use std::thread;
1369
1370    /// Installing the hooks is not enough on Codex >= 0.153: they are gated
1371    /// behind persisted hook trust, and `codex exec` skips untrusted hooks
1372    /// silently. The notice must say how to grant that trust interactively and
1373    /// name the flag that unblocks unattended runs — otherwise a user (or a CI
1374    /// image) reads "Installed" and gets no capture at all.
1375    #[test]
1376    fn codex_hook_trust_notice_explains_how_to_grant_trust() {
1377        let notice = codex_hook_trust_notice();
1378        assert!(
1379            notice.contains("hook trust"),
1380            "notice must name what is missing: {notice}"
1381        );
1382        assert!(
1383            notice.contains("codex") && notice.contains("approve"),
1384            "notice must tell the user to run codex and approve the prompt: {notice}"
1385        );
1386        assert!(
1387            notice.contains("--dangerously-bypass-hook-trust"),
1388            "notice must name the flag for unattended/CI runs: {notice}"
1389        );
1390        assert!(
1391            notice.contains("silently"),
1392            "notice must say the failure is silent, which is why it needs saying: {notice}"
1393        );
1394    }
1395
1396    /// Spawn a one-shot raw-HTTP server that returns `response` to the first
1397    /// request it accepts (mirrors `commands::repo`'s test module).
1398    fn spawn_once(response: String) -> String {
1399        let response: &'static str = Box::leak(response.into_boxed_str());
1400        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1401        let addr = listener.local_addr().unwrap();
1402        thread::spawn(move || {
1403            if let Ok((stream, _)) = listener.accept() {
1404                let mut reader = BufReader::new(stream);
1405                let mut request_line = String::new();
1406                let _ = reader.read_line(&mut request_line);
1407                let mut stream = reader.into_inner();
1408                let _ = stream.write_all(response.as_bytes());
1409                let _ = stream.flush();
1410            }
1411        });
1412        format!("http://{addr}")
1413    }
1414
1415    /// Format a raw HTTP/1.1 response with the given `status` line and a
1416    /// correct `Content-Length` for `body`.
1417    fn http_response(status: &str, body: &str) -> String {
1418        format!(
1419            "HTTP/1.1 {}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
1420            status,
1421            body.len(),
1422            body
1423        )
1424    }
1425
1426    fn add_origin_remote(dir: &Path, url: &str) {
1427        let ok = std::process::Command::new("git")
1428            .args(["-C", &dir.to_string_lossy(), "remote", "add", "origin", url])
1429            .status()
1430            .expect("git remote add failed")
1431            .success();
1432        assert!(ok, "git remote add must succeed");
1433    }
1434
1435    #[test]
1436    fn linked_worktree_primary_detects_linked_and_primary() {
1437        let tmp = tempfile::tempdir().unwrap();
1438        let repo = tmp.path().join("repo");
1439        let wt = tmp.path().join("linked-wt");
1440        std::fs::create_dir_all(&repo).unwrap();
1441        crate::test_helpers::init_git_repo(&repo);
1442        crate::test_helpers::add_worktree(&repo, &wt);
1443
1444        // Primary checkout → None.
1445        assert!(
1446            linked_worktree_primary(&repo).is_none(),
1447            "primary checkout must not be flagged as a linked worktree"
1448        );
1449        // Linked worktree → Some(primary root).
1450        let primary = linked_worktree_primary(&wt).expect("linked worktree must be detected");
1451        assert_eq!(
1452            primary.canonicalize().unwrap(),
1453            repo.canonicalize().unwrap(),
1454            "must resolve to the primary repo root"
1455        );
1456    }
1457
1458    #[test]
1459    fn linked_worktree_primary_none_for_non_git() {
1460        let tmp = tempfile::tempdir().unwrap();
1461        assert!(
1462            linked_worktree_primary(tmp.path()).is_none(),
1463            "a non-git directory is not a linked worktree"
1464        );
1465    }
1466
1467    /// The inner `hooks[0].command` of a hook-event entry, if present.
1468    fn entry_command(entry: &serde_json::Value) -> Option<&str> {
1469        entry.get("hooks")?.get(0)?.get("command")?.as_str()
1470    }
1471
1472    #[test]
1473    fn merge_hooks_into_empty_settings_adds_all_our_events() {
1474        let mut settings = serde_json::json!({});
1475        let ours = tracevault_hooks();
1476        merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1477
1478        let hooks = settings.get("hooks").unwrap();
1479        for event in [
1480            "PreToolUse",
1481            "PostToolUse",
1482            "Notification",
1483            "Stop",
1484            "SubagentStop",
1485            "SessionStart",
1486            "UserPromptSubmit",
1487        ] {
1488            assert!(hooks.get(event).is_some(), "missing event {event}");
1489        }
1490    }
1491
1492    #[test]
1493    fn merge_hooks_preserves_unrelated_user_hook_and_keys() {
1494        let mut settings = serde_json::json!({
1495            "model": "opus",
1496            "hooks": {
1497                "PreToolUse": [{
1498                    "matcher": "",
1499                    "hooks": [{ "type": "command", "command": "my-own-hook" }]
1500                }]
1501            }
1502        });
1503        let ours = tracevault_hooks();
1504        merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1505
1506        // Other top-level keys preserved.
1507        assert_eq!(settings.get("model").unwrap(), "opus");
1508
1509        let pre_tool_use = settings["hooks"]["PreToolUse"].as_array().unwrap();
1510        // Both the user's own hook and ours are present.
1511        assert_eq!(pre_tool_use.len(), 2);
1512        let commands: Vec<&str> = pre_tool_use
1513            .iter()
1514            .map(|e| entry_command(e).unwrap())
1515            .collect();
1516        assert!(commands.contains(&"my-own-hook"));
1517        assert!(commands.contains(&"tracevault stream --event pre-tool-use"));
1518
1519        // Other events were added fresh.
1520        assert!(settings["hooks"]["SessionStart"].is_array());
1521    }
1522
1523    #[test]
1524    fn merge_hooks_is_idempotent() {
1525        let mut settings = serde_json::json!({});
1526        let ours = tracevault_hooks();
1527        merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1528        merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1529
1530        for event in [
1531            "PreToolUse",
1532            "PostToolUse",
1533            "Notification",
1534            "Stop",
1535            "SubagentStop",
1536            "SessionStart",
1537            "UserPromptSubmit",
1538        ] {
1539            let arr = settings["hooks"][event].as_array().unwrap();
1540            assert_eq!(arr.len(), 1, "event {event} should not be duplicated");
1541        }
1542    }
1543
1544    #[test]
1545    fn merge_hooks_keeps_foreign_hook_sharing_a_group_with_ours() {
1546        // Our command sits at hooks[1] of a group the user owns: the group,
1547        // its matcher and the user's hook must survive unchanged, and our
1548        // command must end up exactly once — in its own current group.
1549        let mut settings = serde_json::json!({
1550            "hooks": {
1551                "PreToolUse": [{
1552                    "matcher": "Write|Edit|Bash",
1553                    "hooks": [
1554                        { "type": "command", "command": "other", "timeout": 3 },
1555                        { "type": "command", "command": "tracevault stream --event pre-tool-use" }
1556                    ]
1557                }]
1558            }
1559        });
1560        merge_hooks(
1561            &mut settings,
1562            &tracevault_hooks(),
1563            Path::new("settings.json"),
1564        )
1565        .unwrap();
1566
1567        let pre_tool_use = settings["hooks"]["PreToolUse"].as_array().unwrap();
1568        assert_eq!(
1569            pre_tool_use[0],
1570            serde_json::json!({
1571                "matcher": "Write|Edit|Bash",
1572                "hooks": [{ "type": "command", "command": "other", "timeout": 3 }]
1573            })
1574        );
1575        assert_eq!(
1576            &pre_tool_use[1..],
1577            tracevault_hooks()["PreToolUse"].as_array().unwrap()
1578        );
1579    }
1580
1581    /// A hook set as an older `init` wrote it: narrower PreToolUse matcher,
1582    /// timeout 5, no status messages and no SessionStart/UserPromptSubmit.
1583    fn stale_tracevault_hooks() -> serde_json::Value {
1584        let entry = |matcher: &str, event: &str| {
1585            serde_json::json!([{
1586                "matcher": matcher,
1587                "hooks": [{ "type": "command", "command": format!("tracevault stream --event {event}"), "timeout": 5 }]
1588            }])
1589        };
1590        serde_json::json!({
1591            "PreToolUse": entry("Write|Edit", "pre-tool-use"),
1592            "PostToolUse": entry("", "post-tool-use"),
1593            "Notification": entry("", "notification"),
1594            "Stop": entry("", "stop"),
1595        })
1596    }
1597
1598    #[test]
1599    fn merge_hooks_upgrades_stale_tracevault_entries() {
1600        let mut settings = serde_json::json!({ "hooks": stale_tracevault_hooks() });
1601        merge_hooks(
1602            &mut settings,
1603            &tracevault_hooks(),
1604            Path::new("settings.json"),
1605        )
1606        .unwrap();
1607        assert_eq!(settings["hooks"], tracevault_hooks());
1608    }
1609
1610    #[test]
1611    fn merge_hooks_removes_our_entries_from_events_we_no_longer_install() {
1612        // An older Codex install with a PreToolUse hook we have since dropped,
1613        // next to a foreign event and a foreign non-array value we don't own.
1614        let mut settings = serde_json::json!({
1615            "hooks": {
1616                "PreToolUse": [{ "matcher": "", "hooks": [{ "type": "command", "command": "tracevault stream --event pre-tool-use --agent codex" }] }],
1617                "SubagentStop": [{ "matcher": "", "hooks": [{ "type": "command", "command": "notify-me" }] }],
1618                "Custom": "left alone"
1619            }
1620        });
1621        merge_hooks(&mut settings, &codex_hooks(), Path::new("hooks.json")).unwrap();
1622
1623        let hooks = settings["hooks"].as_object().unwrap();
1624        assert!(!hooks.contains_key("PreToolUse"), "retired event must go");
1625        assert_eq!(hooks["SubagentStop"][0]["hooks"][0]["command"], "notify-me");
1626        assert_eq!(hooks["Custom"], "left alone");
1627        for (event, entries) in codex_hooks().as_object().unwrap() {
1628            assert_eq!(&hooks[event], entries, "{event}");
1629        }
1630    }
1631
1632    #[test]
1633    fn merge_hooks_rerun_keeps_our_entry_in_place() {
1634        // Ours first, a user hook added after it: a re-run must not move ours
1635        // behind the user's (that would rewrite an up-to-date file).
1636        let mut settings = serde_json::json!({ "hooks": tracevault_hooks() });
1637        settings["hooks"]["Stop"]
1638            .as_array_mut()
1639            .unwrap()
1640            .push(serde_json::json!({ "matcher": "", "hooks": [{ "type": "command", "command": "say done" }] }));
1641        let before = settings.clone();
1642        merge_hooks(
1643            &mut settings,
1644            &tracevault_hooks(),
1645            Path::new("settings.json"),
1646        )
1647        .unwrap();
1648        assert_eq!(settings.to_string(), before.to_string());
1649    }
1650
1651    #[test]
1652    fn merge_hooks_does_not_claim_commands_merely_mentioning_tracevault() {
1653        let foreign = serde_json::json!({
1654            "matcher": "",
1655            "hooks": [
1656                { "type": "command", "command": "tracevault-wrapper stream" },
1657                { "type": "command", "command": "echo tracevault stream" },
1658                { "type": "command", "command": " tracevault check" }
1659            ]
1660        });
1661        let mut settings = serde_json::json!({ "hooks": { "Stop": [foreign.clone()] } });
1662        merge_hooks(
1663            &mut settings,
1664            &tracevault_hooks(),
1665            Path::new("settings.json"),
1666        )
1667        .unwrap();
1668        assert_eq!(settings["hooks"]["Stop"][0], foreign);
1669        assert_eq!(settings["hooks"]["Stop"].as_array().unwrap().len(), 2);
1670    }
1671
1672    #[test]
1673    fn merge_hooks_errors_on_non_object_top_level() {
1674        let mut settings = serde_json::json!([1, 2, 3]);
1675        let ours = tracevault_hooks();
1676        let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
1677        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1678        assert!(err.to_string().contains("settings.json"));
1679    }
1680
1681    #[test]
1682    fn merge_hooks_errors_on_non_object_top_level_number() {
1683        let mut settings = serde_json::json!(42);
1684        let ours = tracevault_hooks();
1685        let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
1686        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1687    }
1688
1689    #[test]
1690    fn merge_hooks_errors_on_non_object_hooks() {
1691        let mut settings = serde_json::json!({ "hooks": "not-an-object" });
1692        let ours = tracevault_hooks();
1693        let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
1694        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1695        assert!(err.to_string().contains("hooks"));
1696    }
1697
1698    #[test]
1699    fn merge_hooks_errors_on_non_array_event_value() {
1700        let mut settings = serde_json::json!({
1701            "hooks": {
1702                "PreToolUse": "not-an-array"
1703            }
1704        });
1705        let ours = tracevault_hooks();
1706        let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
1707        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1708        assert!(err.to_string().contains("PreToolUse"));
1709    }
1710
1711    #[test]
1712    fn install_global_hooks_writes_settings_and_claude_md() {
1713        let tmp = tempfile::tempdir().unwrap();
1714        let claude_dir = tmp.path().join(".claude");
1715
1716        install_global_hooks(&claude_dir).unwrap();
1717
1718        let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
1719        let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
1720        for event in ["SessionStart", "UserPromptSubmit", "PreToolUse"] {
1721            assert!(settings["hooks"].get(event).is_some(), "missing {event}");
1722        }
1723
1724        let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
1725        assert!(claude_md.contains(GLOBAL_CLAUDE_MD_MARKER));
1726    }
1727
1728    #[test]
1729    fn install_global_hooks_is_idempotent() {
1730        let tmp = tempfile::tempdir().unwrap();
1731        let claude_dir = tmp.path().join(".claude");
1732
1733        install_global_hooks(&claude_dir).unwrap();
1734        install_global_hooks(&claude_dir).unwrap();
1735
1736        let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
1737        let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
1738        for event in [
1739            "PreToolUse",
1740            "PostToolUse",
1741            "Notification",
1742            "Stop",
1743            "SubagentStop",
1744            "SessionStart",
1745            "UserPromptSubmit",
1746        ] {
1747            let arr = settings["hooks"][event].as_array().unwrap();
1748            assert_eq!(arr.len(), 1, "event {event} should not be duplicated");
1749        }
1750
1751        let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
1752        let marker_count = claude_md.matches(GLOBAL_CLAUDE_MD_MARKER).count();
1753        assert_eq!(
1754            marker_count, 1,
1755            "CLAUDE.md marker should appear exactly once"
1756        );
1757    }
1758
1759    #[test]
1760    fn install_global_hooks_preserves_existing_claude_md_content() {
1761        let tmp = tempfile::tempdir().unwrap();
1762        let claude_dir = tmp.path().join(".claude");
1763        fs::create_dir_all(&claude_dir).unwrap();
1764        fs::write(
1765            claude_dir.join("CLAUDE.md"),
1766            "# My existing notes\nSome content.\n",
1767        )
1768        .unwrap();
1769
1770        install_global_hooks(&claude_dir).unwrap();
1771
1772        let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
1773        assert!(claude_md.contains("# My existing notes"));
1774        assert!(claude_md.contains(GLOBAL_CLAUDE_MD_MARKER));
1775    }
1776
1777    #[test]
1778    fn install_global_hooks_settings_write_is_atomic_no_tmp_leftover() {
1779        let tmp = tempfile::tempdir().unwrap();
1780        let claude_dir = tmp.path().join(".claude");
1781
1782        install_global_hooks(&claude_dir).unwrap();
1783
1784        let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
1785        let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
1786        assert!(settings["hooks"].get("SessionStart").is_some());
1787
1788        let leftover = fs::read_dir(&claude_dir)
1789            .unwrap()
1790            .filter_map(|e| e.ok())
1791            .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
1792        assert!(
1793            !leftover,
1794            "no settings.json.tmp should remain after install"
1795        );
1796    }
1797
1798    #[test]
1799    fn install_global_hooks_errors_on_non_object_settings_and_does_not_overwrite() {
1800        let tmp = tempfile::tempdir().unwrap();
1801        let claude_dir = tmp.path().join(".claude");
1802        fs::create_dir_all(&claude_dir).unwrap();
1803        let settings_path = claude_dir.join("settings.json");
1804        let original = "[1, 2, 3]";
1805        fs::write(&settings_path, original).unwrap();
1806
1807        let err = install_global_hooks(&claude_dir).unwrap_err();
1808        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1809
1810        // The original (malformed-for-our-purposes but validly-JSON) file
1811        // must be untouched, and no stray tmp file left behind.
1812        let after = fs::read_to_string(&settings_path).unwrap();
1813        assert_eq!(after, original);
1814        let leftover = fs::read_dir(&claude_dir)
1815            .unwrap()
1816            .filter_map(|e| e.ok())
1817            .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
1818        assert!(!leftover, "no tmp file should be left behind on error");
1819    }
1820
1821    #[test]
1822    fn install_global_hooks_errors_on_non_object_hooks_key_and_does_not_overwrite() {
1823        let tmp = tempfile::tempdir().unwrap();
1824        let claude_dir = tmp.path().join(".claude");
1825        fs::create_dir_all(&claude_dir).unwrap();
1826        let settings_path = claude_dir.join("settings.json");
1827        let original = r#"{"hooks": "oops"}"#;
1828        fs::write(&settings_path, original).unwrap();
1829
1830        let err = install_global_hooks(&claude_dir).unwrap_err();
1831        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1832
1833        let after = fs::read_to_string(&settings_path).unwrap();
1834        assert_eq!(after, original);
1835    }
1836
1837    #[test]
1838    fn install_global_hooks_errors_on_non_array_event_and_does_not_overwrite() {
1839        let tmp = tempfile::tempdir().unwrap();
1840        let claude_dir = tmp.path().join(".claude");
1841        fs::create_dir_all(&claude_dir).unwrap();
1842        let settings_path = claude_dir.join("settings.json");
1843        let original = r#"{"hooks": {"PreToolUse": "oops"}}"#;
1844        fs::write(&settings_path, original).unwrap();
1845
1846        let err = install_global_hooks(&claude_dir).unwrap_err();
1847        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1848
1849        let after = fs::read_to_string(&settings_path).unwrap();
1850        assert_eq!(after, original);
1851    }
1852
1853    #[test]
1854    fn safe_join_allows_direct_child_file() {
1855        let tmp = tempfile::tempdir().unwrap();
1856        let base = tmp.path();
1857        let result = safe_join(base, "settings.json").unwrap();
1858        assert_eq!(result.parent(), Some(base));
1859        assert_eq!(result.file_name().unwrap(), "settings.json");
1860    }
1861
1862    #[test]
1863    fn safe_join_rejects_path_traversal() {
1864        let tmp = tempfile::tempdir().unwrap();
1865        let base = tmp.path();
1866        let result = safe_join(base, "../evil");
1867        assert!(result.is_err());
1868        let err = result.unwrap_err();
1869        assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
1870        assert!(err.to_string().contains("refusing to access path outside"));
1871    }
1872
1873    #[test]
1874    fn safe_join_rejects_absolute_path() {
1875        let tmp = tempfile::tempdir().unwrap();
1876        let base = tmp.path();
1877        let result = safe_join(base, "/etc/passwd");
1878        // An absolute path joined to a base will replace the base,
1879        // so parent will not equal base.
1880        assert!(result.is_err());
1881    }
1882
1883    #[test]
1884    fn write_global_user_config_enables_and_creates_context() {
1885        let root = tempfile::tempdir().unwrap();
1886        let active = write_global_user_config_in(root.path(), None).unwrap();
1887        let cfg = crate::config::try_load_user_config_in(root.path())
1888            .unwrap()
1889            .unwrap();
1890        // Validate against the INJECTED root (resolve_in), not tv_config_root():
1891        // a first-run default enables at the `context.json` under `root`.
1892        assert_eq!(
1893            cfg.user_context.unwrap().resolve_in(root.path()),
1894            Some(crate::config::default_user_context_path_in(root.path()))
1895        );
1896        let ctx = crate::config::default_user_context_path_in(root.path());
1897        assert_eq!(active, Some(ctx.clone()));
1898        assert!(ctx.exists());
1899    }
1900
1901    #[test]
1902    fn write_global_user_config_can_disable() {
1903        let root = tempfile::tempdir().unwrap();
1904        let active = write_global_user_config_in(
1905            root.path(),
1906            Some(crate::config::UserContext::Toggle(false)),
1907        )
1908        .unwrap();
1909        let cfg = crate::config::try_load_user_config_in(root.path())
1910            .unwrap()
1911            .unwrap();
1912        assert!(matches!(
1913            cfg.user_context,
1914            Some(crate::config::UserContext::Toggle(false))
1915        ));
1916        assert_eq!(active, None, "disabled → no active context path");
1917        // A disabled layer must NOT seed a context file.
1918        assert!(
1919            !crate::config::default_user_context_path_in(root.path()).exists(),
1920            "disabled user context must not create a context.json"
1921        );
1922    }
1923
1924    #[test]
1925    fn write_global_user_config_custom_path_seeds_that_file_only() {
1926        let root = tempfile::tempdir().unwrap();
1927        let custom = root.path().join("custom-ctx.json");
1928        let active = write_global_user_config_in(
1929            root.path(),
1930            Some(crate::config::UserContext::Path(
1931                custom.to_string_lossy().into_owned(),
1932            )),
1933        )
1934        .unwrap();
1935        assert_eq!(active, Some(custom.clone()));
1936        assert!(custom.exists(), "the configured custom path must be seeded");
1937        assert!(
1938            !crate::config::default_user_context_path_in(root.path()).exists(),
1939            "the default context.json must NOT be created when a custom path is configured"
1940        );
1941    }
1942
1943    #[test]
1944    fn write_global_user_config_preserves_existing_on_rerun_without_flags() {
1945        let root = tempfile::tempdir().unwrap();
1946        let custom = root.path().join("custom-ctx.json");
1947        // First run pins a custom path.
1948        write_global_user_config_in(
1949            root.path(),
1950            Some(crate::config::UserContext::Path(
1951                custom.to_string_lossy().into_owned(),
1952            )),
1953        )
1954        .unwrap();
1955        // Re-run with NO flags must NOT reset it back to the default.
1956        let active = write_global_user_config_in(root.path(), None).unwrap();
1957        assert_eq!(
1958            active,
1959            Some(custom.clone()),
1960            "re-run without flags must preserve the custom path"
1961        );
1962        let cfg = crate::config::try_load_user_config_in(root.path())
1963            .unwrap()
1964            .unwrap();
1965        assert_eq!(cfg.user_context.unwrap().path_in(root.path()), custom);
1966    }
1967
1968    #[test]
1969    fn install_global_codex_hooks_writes_and_is_idempotent() {
1970        let tmp = tempfile::tempdir().unwrap();
1971        let codex_dir = tmp.path().join(".codex");
1972
1973        install_global_codex_hooks(&codex_dir).unwrap();
1974        install_global_codex_hooks(&codex_dir).unwrap();
1975
1976        let v: serde_json::Value =
1977            serde_json::from_str(&fs::read_to_string(codex_dir.join("hooks.json")).unwrap())
1978                .unwrap();
1979        for event in ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"] {
1980            let arr = v["hooks"][event].as_array().unwrap();
1981            assert_eq!(arr.len(), 1, "event {event} must not be duplicated");
1982        }
1983        assert!(v["hooks"].get("PreToolUse").is_none());
1984        // AGENTS.md carries the workspace-mode block exactly once across re-runs.
1985        let agents_md = fs::read_to_string(codex_dir.join("AGENTS.md")).unwrap();
1986        assert_eq!(
1987            agents_md.matches(GLOBAL_CLAUDE_MD_MARKER).count(),
1988            1,
1989            "AGENTS.md workspace-mode block must appear exactly once"
1990        );
1991        // No stray temp file left behind.
1992        let leftover = fs::read_dir(&codex_dir)
1993            .unwrap()
1994            .filter_map(|e| e.ok())
1995            .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
1996        assert!(!leftover);
1997    }
1998
1999    #[test]
2000    fn codex_hooks_has_expected_events_and_commands() {
2001        let h = codex_hooks();
2002        for event in ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"] {
2003            assert!(h.get(event).is_some(), "missing codex event {event}");
2004        }
2005        // No PreToolUse (intentionally dropped — PostToolUse + Stop capture the
2006        // rollout; a pre-tool hook would only double per-call streaming) and no
2007        // Notification event (Codex has none).
2008        assert!(h.get("PreToolUse").is_none());
2009        assert!(h.get("Notification").is_none());
2010        // Capture commands carry --agent codex; injection hooks do not need it.
2011        let cmd = |e: &str| h[e][0]["hooks"][0]["command"].as_str().unwrap().to_string();
2012        assert_eq!(
2013            cmd("PostToolUse"),
2014            "tracevault stream --event post-tool-use --agent codex"
2015        );
2016        assert_eq!(cmd("Stop"), "tracevault stream --event stop --agent codex");
2017        assert_eq!(cmd("SessionStart"), "tracevault session-start");
2018        assert_eq!(cmd("UserPromptSubmit"), "tracevault user-prompt");
2019        // Matchers are "" (all tools) — Codex edits arrive via the transcript.
2020        assert_eq!(h["PostToolUse"][0]["matcher"].as_str().unwrap(), "");
2021    }
2022
2023    #[test]
2024    fn install_codex_hooks_writes_hooks_json_and_is_idempotent() {
2025        let tmp = tempfile::tempdir().unwrap();
2026        install_codex_hooks(tmp.path()).unwrap();
2027        install_codex_hooks(tmp.path()).unwrap();
2028
2029        let content = fs::read_to_string(tmp.path().join(".codex").join("hooks.json")).unwrap();
2030        let v: serde_json::Value = serde_json::from_str(&content).unwrap();
2031        for event in ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"] {
2032            let arr = v["hooks"][event].as_array().unwrap();
2033            assert_eq!(
2034                arr.len(),
2035                1,
2036                "event {event} must not be duplicated on re-run"
2037            );
2038        }
2039        assert!(v["hooks"].get("PreToolUse").is_none());
2040    }
2041
2042    #[test]
2043    fn install_codex_hooks_preserves_existing_user_hook() {
2044        let tmp = tempfile::tempdir().unwrap();
2045        let codex_dir = tmp.path().join(".codex");
2046        fs::create_dir_all(&codex_dir).unwrap();
2047        // Seed a user hook under an event we install (PostToolUse) plus one under
2048        // an event we DON'T (PreToolUse) — both must survive the merge.
2049        fs::write(
2050            codex_dir.join("hooks.json"),
2051            r#"{"hooks":{"PostToolUse":[{"matcher":"","hooks":[{"type":"command","command":"my-own"}]}],"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"user-pretool"}]}]}}"#,
2052        )
2053        .unwrap();
2054
2055        install_codex_hooks(tmp.path()).unwrap();
2056
2057        let v: serde_json::Value =
2058            serde_json::from_str(&fs::read_to_string(codex_dir.join("hooks.json")).unwrap())
2059                .unwrap();
2060        // Our PostToolUse command is merged in alongside the user's own.
2061        let post_cmds: Vec<&str> = v["hooks"]["PostToolUse"]
2062            .as_array()
2063            .unwrap()
2064            .iter()
2065            .map(|e| e["hooks"][0]["command"].as_str().unwrap())
2066            .collect();
2067        assert!(
2068            post_cmds.contains(&"my-own"),
2069            "user PostToolUse hook preserved"
2070        );
2071        assert!(post_cmds.contains(&"tracevault stream --event post-tool-use --agent codex"));
2072        // The user's PreToolUse hook is left untouched (we install no PreToolUse).
2073        let pre_cmds: Vec<&str> = v["hooks"]["PreToolUse"]
2074            .as_array()
2075            .unwrap()
2076            .iter()
2077            .map(|e| e["hooks"][0]["command"].as_str().unwrap())
2078            .collect();
2079        assert_eq!(pre_cmds, vec!["user-pretool"], "unmanaged event untouched");
2080    }
2081
2082    /// A settings file a user might really have: other keys, foreign hooks in
2083    /// their own groups and in a group shared with ours, keys in non-sorted
2084    /// order, and a stale TraceVault install.
2085    const FOREIGN_SETTINGS: &str = r#"{
2086  "permissions": { "allow": ["Bash(ls)"] },
2087  "hooks": {
2088    "PreToolUse": [
2089      { "matcher": "Bash", "hooks": [ { "type": "command", "command": "./guard.sh", "timeout": 7 } ] },
2090      { "matcher": "Write|Edit", "hooks": [
2091        { "type": "command", "command": "tracevault stream --event pre-tool-use", "timeout": 5 },
2092        { "type": "command", "command": "prettier --check", "statusMessage": "fmt" }
2093      ] }
2094    ],
2095    "Stop": [ { "matcher": "", "hooks": [ { "type": "command", "command": "tracevault stream --event stop", "timeout": 5 } ] } ],
2096    "SubagentStop": [ { "hooks": [ { "command": "notify", "type": "command" } ], "matcher": "" } ]
2097  },
2098  "model": "opus"
2099}"#;
2100
2101    /// Serialised forms of the foreign entries in [`FOREIGN_SETTINGS`], as
2102    /// they must appear after an install: unchanged values, unchanged key
2103    /// order; the shared group just loses our hook.
2104    fn expected_foreign_entries() -> Vec<String> {
2105        [
2106            r#"{"matcher":"Bash","hooks":[{"type":"command","command":"./guard.sh","timeout":7}]}"#,
2107            r#"{"matcher":"Write|Edit","hooks":[{"type":"command","command":"prettier --check","statusMessage":"fmt"}]}"#,
2108            r#"{"hooks":[{"command":"notify","type":"command"}],"matcher":""}"#,
2109        ]
2110        .map(String::from)
2111        .to_vec()
2112    }
2113
2114    fn holds_tracevault_hook(entry: &serde_json::Value) -> bool {
2115        entry["hooks"]
2116            .as_array()
2117            .unwrap()
2118            .iter()
2119            .any(is_tracevault_hook)
2120    }
2121
2122    fn assert_installed_over_foreign(path: &Path, ours: &serde_json::Value) {
2123        let v: serde_json::Value =
2124            serde_json::from_str(&fs::read_to_string(path).unwrap()).unwrap();
2125        assert_eq!(
2126            v.as_object().unwrap().keys().collect::<Vec<_>>(),
2127            ["permissions", "hooks", "model"],
2128            "top-level keys kept, in their order"
2129        );
2130        assert_eq!(
2131            v["permissions"],
2132            serde_json::json!({ "allow": ["Bash(ls)"] })
2133        );
2134        let hooks = v["hooks"].as_object().unwrap();
2135        let foreign: Vec<String> = hooks
2136            .values()
2137            .flat_map(|entries| entries.as_array().unwrap())
2138            .filter(|e| !holds_tracevault_hook(e))
2139            .map(|e| e.to_string())
2140            .collect();
2141        assert_eq!(foreign, expected_foreign_entries());
2142        let ours = ours.as_object().unwrap();
2143        for (event, entries) in hooks {
2144            let mine: Vec<&serde_json::Value> = entries
2145                .as_array()
2146                .unwrap()
2147                .iter()
2148                .filter(|e| holds_tracevault_hook(e))
2149                .collect();
2150            let want: Vec<&serde_json::Value> = ours
2151                .get(event)
2152                .map(|o| o.as_array().unwrap().iter().collect())
2153                .unwrap_or_default();
2154            assert_eq!(mine, want, "TraceVault entries under {event}");
2155        }
2156        for event in ours.keys() {
2157            assert!(hooks.contains_key(event), "missing {event}");
2158        }
2159    }
2160
2161    #[test]
2162    fn install_claude_hooks_keeps_foreign_hooks_in_both_settings_files() {
2163        for target in [ClaudeSettingsTarget::Shared, ClaudeSettingsTarget::Local] {
2164            let tmp = tempfile::tempdir().unwrap();
2165            let path = tmp.path().join(".claude").join(target.filename());
2166            fs::create_dir_all(path.parent().unwrap()).unwrap();
2167            fs::write(&path, FOREIGN_SETTINGS).unwrap();
2168
2169            install_claude_hooks(tmp.path(), target).unwrap();
2170            assert_installed_over_foreign(&path, &tracevault_hooks());
2171
2172            // A second run finds the file current and leaves its bytes alone.
2173            let after_first = fs::read(&path).unwrap();
2174            install_claude_hooks(tmp.path(), target).unwrap();
2175            assert_eq!(fs::read(&path).unwrap(), after_first, "{target:?}");
2176        }
2177    }
2178
2179    #[test]
2180    fn install_global_hooks_keeps_foreign_hooks_and_upgrades_ours() {
2181        let tmp = tempfile::tempdir().unwrap();
2182        let claude_dir = tmp.path().join(".claude");
2183        fs::create_dir_all(&claude_dir).unwrap();
2184        fs::write(claude_dir.join("settings.json"), FOREIGN_SETTINGS).unwrap();
2185
2186        install_global_hooks(&claude_dir).unwrap();
2187        assert_installed_over_foreign(&claude_dir.join("settings.json"), &tracevault_hooks());
2188    }
2189
2190    #[test]
2191    fn install_codex_hooks_keeps_foreign_hooks_and_upgrades_ours() {
2192        for global in [false, true] {
2193            let tmp = tempfile::tempdir().unwrap();
2194            let codex_dir = tmp.path().join(".codex");
2195            fs::create_dir_all(&codex_dir).unwrap();
2196            fs::write(codex_dir.join("hooks.json"), FOREIGN_SETTINGS).unwrap();
2197
2198            if global {
2199                install_global_codex_hooks(&codex_dir).unwrap();
2200            } else {
2201                install_codex_hooks(tmp.path()).unwrap();
2202            }
2203            assert_installed_over_foreign(&codex_dir.join("hooks.json"), &codex_hooks());
2204        }
2205    }
2206
2207    #[test]
2208    fn up_to_date_hook_file_is_not_rewritten() {
2209        // Hand-formatted (4-space indent) but already current: no reformatting.
2210        let tmp = tempfile::tempdir().unwrap();
2211        let path = tmp.path().join(".claude/settings.json");
2212        fs::create_dir_all(path.parent().unwrap()).unwrap();
2213        let mut body = Vec::new();
2214        let fmt = serde_json::ser::PrettyFormatter::with_indent(b"    ");
2215        let mut ser = serde_json::Serializer::with_formatter(&mut body, fmt);
2216        serde::Serialize::serialize(
2217            &serde_json::json!({ "hooks": tracevault_hooks() }),
2218            &mut ser,
2219        )
2220        .unwrap();
2221        fs::write(&path, &body).unwrap();
2222
2223        install_claude_hooks(tmp.path(), ClaudeSettingsTarget::Shared).unwrap();
2224        assert_eq!(fs::read(&path).unwrap(), body);
2225    }
2226
2227    #[test]
2228    fn install_claude_hooks_refuses_malformed_settings_without_clobbering() {
2229        for (target, body) in [
2230            (ClaudeSettingsTarget::Shared, "{ not json"),
2231            (ClaudeSettingsTarget::Local, "[1, 2]"),
2232            (ClaudeSettingsTarget::Shared, "null"),
2233            (ClaudeSettingsTarget::Shared, r#"{"hooks": []}"#),
2234            (ClaudeSettingsTarget::Local, r#"{"hooks": {"Stop": {}}}"#),
2235        ] {
2236            let tmp = tempfile::tempdir().unwrap();
2237            let path = tmp.path().join(".claude").join(target.filename());
2238            fs::create_dir_all(path.parent().unwrap()).unwrap();
2239            fs::write(&path, body).unwrap();
2240
2241            let err = install_claude_hooks(tmp.path(), target).unwrap_err();
2242            assert_eq!(err.kind(), io::ErrorKind::InvalidData, "{body}");
2243            assert_eq!(
2244                fs::read_to_string(&path).unwrap(),
2245                body,
2246                "file must be untouched"
2247            );
2248            assert_eq!(
2249                fs::read_dir(path.parent().unwrap()).unwrap().count(),
2250                1,
2251                "no temp file left behind"
2252            );
2253        }
2254    }
2255
2256    #[test]
2257    fn concurrent_installs_never_publish_a_partial_file() {
2258        // Two writers flip the file between two hook sets, so every call
2259        // rewrites it, while a reader keeps parsing it: the file must always
2260        // be there and complete, and no temp file may remain. A writer that
2261        // keeps losing the race gives up with the "kept changing" error
2262        // rather than publishing a stale snapshot.
2263        let tmp = tempfile::tempdir().unwrap();
2264        let path = tmp.path().join("settings.json");
2265        fs::write(&path, FOREIGN_SETTINGS).unwrap();
2266        let done = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
2267        let reader = {
2268            let (path, done) = (path.clone(), done.clone());
2269            std::thread::spawn(move || {
2270                while !done.load(std::sync::atomic::Ordering::Relaxed) {
2271                    let body = fs::read_to_string(&path).unwrap();
2272                    serde_json::from_str::<serde_json::Value>(&body).unwrap();
2273                }
2274            })
2275        };
2276        let writers: Vec<_> = [tracevault_hooks(), codex_hooks()]
2277            .into_iter()
2278            .map(|ours| {
2279                let path = path.clone();
2280                std::thread::spawn(move || {
2281                    for _ in 0..200 {
2282                        if let Err(e) = merge_hooks_into_file(&path, &ours) {
2283                            assert!(e.to_string().contains("kept changing"), "{e}");
2284                        }
2285                    }
2286                })
2287            })
2288            .collect();
2289        for writer in writers {
2290            writer.join().unwrap();
2291        }
2292        done.store(true, std::sync::atomic::Ordering::Relaxed);
2293        reader.join().unwrap();
2294        let v: serde_json::Value =
2295            serde_json::from_str(&fs::read_to_string(&path).unwrap()).unwrap();
2296        assert_eq!(v["model"], "opus");
2297        assert_eq!(
2298            fs::read_dir(tmp.path()).unwrap().count(),
2299            1,
2300            "no temp file left"
2301        );
2302    }
2303
2304    #[cfg(unix)]
2305    #[test]
2306    fn install_claude_hooks_keeps_file_permissions() {
2307        use std::os::unix::fs::PermissionsExt;
2308        let tmp = tempfile::tempdir().unwrap();
2309        let path = tmp.path().join(".claude/settings.local.json");
2310        fs::create_dir_all(path.parent().unwrap()).unwrap();
2311        fs::write(&path, FOREIGN_SETTINGS).unwrap();
2312        fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).unwrap();
2313
2314        install_claude_hooks(tmp.path(), ClaudeSettingsTarget::Local).unwrap();
2315
2316        let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777;
2317        assert_eq!(mode, 0o600);
2318        assert_installed_over_foreign(&path, &tracevault_hooks());
2319    }
2320
2321    #[cfg(unix)]
2322    #[test]
2323    fn install_claude_hooks_updates_symlinked_settings_at_its_target() {
2324        let tmp = tempfile::tempdir().unwrap();
2325        let central = tmp.path().join("central/claude-settings.json");
2326        fs::create_dir_all(central.parent().unwrap()).unwrap();
2327        fs::write(&central, FOREIGN_SETTINGS).unwrap();
2328        let link = tmp.path().join("repo/.claude/settings.json");
2329        fs::create_dir_all(link.parent().unwrap()).unwrap();
2330        std::os::unix::fs::symlink(&central, &link).unwrap();
2331
2332        install_claude_hooks(&tmp.path().join("repo"), ClaudeSettingsTarget::Shared).unwrap();
2333
2334        assert!(fs::symlink_metadata(&link)
2335            .unwrap()
2336            .file_type()
2337            .is_symlink());
2338        assert_installed_over_foreign(&central, &tracevault_hooks());
2339    }
2340
2341    #[cfg(unix)]
2342    #[test]
2343    fn install_claude_hooks_refuses_dangling_symlink() {
2344        let tmp = tempfile::tempdir().unwrap();
2345        let link = tmp.path().join(".claude/settings.json");
2346        fs::create_dir_all(link.parent().unwrap()).unwrap();
2347        std::os::unix::fs::symlink(tmp.path().join("gone.json"), &link).unwrap();
2348
2349        assert!(install_claude_hooks(tmp.path(), ClaudeSettingsTarget::Shared).is_err());
2350        assert!(fs::symlink_metadata(&link)
2351            .unwrap()
2352            .file_type()
2353            .is_symlink());
2354        assert!(!tmp.path().join("gone.json").exists());
2355    }
2356
2357    #[test]
2358    fn validate_init_flags_rejects_claude_settings_with_codex() {
2359        assert!(validate_init_flags(crate::agent::Agent::Codex, true).is_err());
2360    }
2361
2362    #[test]
2363    fn validate_init_flags_allows_codex_without_claude_settings() {
2364        assert!(validate_init_flags(crate::agent::Agent::Codex, false).is_ok());
2365    }
2366
2367    #[test]
2368    fn validate_init_flags_allows_claude_with_claude_settings() {
2369        assert!(validate_init_flags(crate::agent::Agent::ClaudeCode, true).is_ok());
2370    }
2371
2372    #[test]
2373    fn merge_hooks_into_file_rejects_parent_dir() {
2374        let tmp = tempfile::tempdir().unwrap();
2375        let bad = tmp.path().join("..").join("hooks.json");
2376        let err = merge_hooks_into_file(&bad, &codex_hooks()).unwrap_err();
2377        assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
2378    }
2379
2380    #[test]
2381    fn append_workspace_md_rejects_parent_dir() {
2382        let tmp = tempfile::tempdir().unwrap();
2383        let bad = tmp.path().join("..").join("AGENTS.md");
2384        let err = append_workspace_md(&bad).unwrap_err();
2385        assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
2386    }
2387
2388    #[tokio::test]
2389    async fn init_in_directory_codex_installs_codex_hooks_and_gitignores() {
2390        let tmp = tempfile::tempdir().unwrap();
2391        let root = tmp.path();
2392        crate::test_helpers::init_git_repo(root);
2393        // `init` refuses to run without a credential; a per-repo one keeps
2394        // this test independent of the process env and the user's login.
2395        fs::create_dir_all(root.join(".tracevault")).unwrap();
2396        fs::write(
2397            root.join(".tracevault/config.toml"),
2398            "api_key = \"tvk_test\"\n",
2399        )
2400        .unwrap();
2401
2402        let entry = init_in_directory(
2403            root,
2404            None,
2405            None,
2406            false,
2407            Some(crate::config::UserContext::Toggle(false)),
2408            crate::agent::Agent::Codex,
2409        )
2410        .await
2411        .unwrap();
2412
2413        // Codex hooks file written; Claude settings NOT created.
2414        assert!(root.join(".codex").join("hooks.json").exists());
2415        assert!(!root.join(".claude").join("settings.json").exists());
2416        assert_eq!(entry, ".codex/hooks.json");
2417
2418        // .gitignore covers the codex hooks file.
2419        let gi = fs::read_to_string(root.join(".gitignore")).unwrap();
2420        assert!(gi.contains(".codex/hooks.json"));
2421        assert!(gi.contains(".tracevault/"));
2422    }
2423
2424    /// A successful `POST /api/v1/repos` during `init` must persist the
2425    /// returned `repo_id` into `.tracevault/config.toml` — this is the
2426    /// "everything worked" happy path of the registration step at the end of
2427    /// `init_in_directory`, previously untested.
2428    ///
2429    /// `XDG_CONFIG_HOME` is redirected so this doesn't read/write the
2430    /// developer's real `~/.config/tracevault/credentials.json`;
2431    /// `TRACEVAULT_API_KEY` is pinned directly since `resolve_credentials`
2432    /// checks it before the credentials file. `_env_lock` serializes this
2433    /// against other tests in the crate that mutate the same env vars
2434    /// (see `test_helpers::lock_env_mutation`).
2435    #[tokio::test]
2436    async fn init_in_directory_registers_repo_and_persists_repo_id() {
2437        let _env_lock = crate::test_helpers::lock_env_mutation().await;
2438        let tmp = tempfile::tempdir().unwrap();
2439        let root = tmp.path();
2440        crate::test_helpers::init_git_repo(root);
2441        add_origin_remote(root, "git@github.com:org/repo.git");
2442
2443        let repo_id = "11111111-1111-4111-8111-111111111111";
2444        let body = format!(r#"{{"repo_id":"{repo_id}"}}"#);
2445        // The remote is unknown (domain 404), so init registers; the resolve
2446        // after registering may fail, it is display-only.
2447        let (base, _rx) = crate::test_helpers::spawn_seq(vec![
2448            http_response("404 Not Found", NO_REMOTE),
2449            http_response("200 OK", &body),
2450        ]);
2451
2452        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2453        _guard.set("XDG_CONFIG_HOME", tmp.path());
2454        _guard.set("TRACEVAULT_API_KEY", "tok");
2455        _guard.remove("TRACEVAULT_SERVER_URL");
2456
2457        init_in_directory(
2458            root,
2459            Some(&base),
2460            None,
2461            true,
2462            Some(crate::config::UserContext::Toggle(false)),
2463            crate::agent::Agent::Codex,
2464        )
2465        .await
2466        .unwrap();
2467
2468        let cfg = crate::config::TracevaultConfig::load(root).expect("config.toml written by init");
2469        assert_eq!(
2470            cfg.repo_id,
2471            Some(repo_id.to_string()),
2472            "successful registration must persist repo_id to config.toml"
2473        );
2474    }
2475
2476    /// A 403 on `POST /api/v1/repos` must be a non-fatal warning (`init`
2477    /// still succeeds and installs hooks) and must NOT persist a `repo_id` —
2478    /// there's nothing valid to persist. The exact wording of the warning is
2479    /// covered by `registration_failure_message_flags_403_as_not_authorized`
2480    /// below.
2481    #[tokio::test]
2482    async fn init_in_directory_registration_403_does_not_persist_repo_id() {
2483        let _env_lock = crate::test_helpers::lock_env_mutation().await;
2484        let tmp = tempfile::tempdir().unwrap();
2485        let root = tmp.path();
2486        crate::test_helpers::init_git_repo(root);
2487        add_origin_remote(root, "git@github.com:org/repo.git");
2488
2489        let (base, _rx) = crate::test_helpers::spawn_seq(vec![
2490            http_response("404 Not Found", NO_REMOTE),
2491            http_response("403 Forbidden", ""),
2492        ]);
2493
2494        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2495        _guard.set("XDG_CONFIG_HOME", tmp.path());
2496        _guard.set("TRACEVAULT_API_KEY", "tok");
2497        _guard.remove("TRACEVAULT_SERVER_URL");
2498
2499        let entry = init_in_directory(
2500            root,
2501            Some(&base),
2502            None,
2503            true,
2504            Some(crate::config::UserContext::Toggle(false)),
2505            crate::agent::Agent::Codex,
2506        )
2507        .await
2508        .expect("a registration failure (403) must not abort init itself");
2509        assert_eq!(entry, ".codex/hooks.json");
2510
2511        let cfg = crate::config::TracevaultConfig::load(root).expect("config.toml written by init");
2512        assert!(
2513            cfg.repo_id.is_none(),
2514            "a 403 registration failure must not persist a repo_id"
2515        );
2516    }
2517
2518    /// The actual error shape `ApiClient::register_repo` produces for a 403
2519    /// response (via the same mock-server harness) must be recognized by
2520    /// `registration_failure_message` as a not-authorized case, not a
2521    /// generic server fault.
2522    #[tokio::test]
2523    async fn registration_failure_message_flags_403_as_not_authorized() {
2524        let base = spawn_once(http_response("403 Forbidden", ""));
2525        let client = ApiClient::new(&base, Some("tok"));
2526        let err = client
2527            .register_repo(crate::api_client::RegisterRepoRequest {
2528                repo_name: "repo".into(),
2529                github_url: Some("git@github.com:org/repo.git".into()),
2530            })
2531            .await
2532            .unwrap_err();
2533        let msg = registration_failure_message(err.as_ref());
2534        assert!(
2535            msg.contains("not authorized"),
2536            "403 registration failure must surface a not-authorized message; got: {msg}"
2537        );
2538    }
2539
2540    /// A non-403 registration failure (e.g. a 500) keeps the generic
2541    /// "could not register" wording, distinguishing it from the 403 case.
2542    #[tokio::test]
2543    async fn registration_failure_message_generic_for_non_403() {
2544        let base = spawn_once(http_response("500 Internal Server Error", ""));
2545        let client = ApiClient::new(&base, Some("tok"));
2546        let err = client
2547            .register_repo(crate::api_client::RegisterRepoRequest {
2548                repo_name: "repo".into(),
2549                github_url: Some("git@github.com:org/repo.git".into()),
2550            })
2551            .await
2552            .unwrap_err();
2553        let msg = registration_failure_message(err.as_ref());
2554        assert!(
2555            msg.contains("could not register repo on server"),
2556            "got: {msg}"
2557        );
2558        assert!(!msg.contains("not authorized"), "got: {msg}");
2559    }
2560
2561    /// A 500 whose BODY happens to contain the digits "403" (e.g. a proxy
2562    /// error page quoting an unrelated status) must not be misclassified as
2563    /// a 403-not-authorized failure — the match must key on the actual
2564    /// status prefix, not a bare substring search over the whole message.
2565    #[tokio::test]
2566    async fn registration_failure_message_does_not_misclassify_403_in_body() {
2567        let base = spawn_once(http_response(
2568            "500 Internal Server Error",
2569            "upstream error 403 from proxy",
2570        ));
2571        let client = ApiClient::new(&base, Some("tok"));
2572        let err = client
2573            .register_repo(crate::api_client::RegisterRepoRequest {
2574                repo_name: "repo".into(),
2575                github_url: Some("git@github.com:org/repo.git".into()),
2576            })
2577            .await
2578            .unwrap_err();
2579        let msg = registration_failure_message(err.as_ref());
2580        assert!(
2581            !msg.contains("not authorized"),
2582            "a 403 substring in the body must not trigger the not-authorized message; got: {msg}"
2583        );
2584        assert!(
2585            msg.contains("could not register repo on server"),
2586            "got: {msg}"
2587        );
2588    }
2589
2590    /// A 404 (the registration route doesn't exist on this server) surfaces a
2591    /// CLI/server version-mismatch hint rather than the generic wording, so
2592    /// the user has an actionable next step instead of an opaque status code.
2593    #[tokio::test]
2594    async fn registration_failure_message_flags_404_as_version_mismatch() {
2595        let base = spawn_once(http_response("404 Not Found", ""));
2596        let client = ApiClient::new(&base, Some("tok"));
2597        let err = client
2598            .register_repo(crate::api_client::RegisterRepoRequest {
2599                repo_name: "repo".into(),
2600                github_url: Some("git@github.com:org/repo.git".into()),
2601            })
2602            .await
2603            .unwrap_err();
2604        let msg = registration_failure_message(err.as_ref());
2605        assert!(
2606            msg.to_lowercase().contains("version mismatch"),
2607            "a 404 registration failure should hint at a version mismatch; got: {msg}"
2608        );
2609    }
2610
2611    // ── VIS-1018: init never registers a second repo for a known remote ───────
2612
2613    /// The server's domain-404 body for an untracked remote.
2614    const NO_REMOTE: &str = r#"{"error":"No remote for that URL"}"#;
2615    const REMOTE_ID: &str = "2280a1c9-0000-4000-8000-000000000003";
2616    const CANONICAL: &str = "44000761-0000-4000-8000-000000000001";
2617    const STRAY: &str = "7995d35d-0000-4000-8000-000000000002";
2618
2619    fn resolve_remote_ok() -> String {
2620        http_response(
2621            "200 OK",
2622            &format!(
2623                r#"{{"remote_id":"{REMOTE_ID}","name":"tracing","normalized_url":"github.com/org/repo","clone_status":"ready"}}"#
2624            ),
2625        )
2626    }
2627
2628    fn remote_detail(repos: &[(&str, &str)]) -> String {
2629        let repos: Vec<String> = repos
2630            .iter()
2631            .map(|(id, name)| format!(r#"{{"id":"{id}","name":"{name}"}}"#))
2632            .collect();
2633        http_response(
2634            "200 OK",
2635            &format!(
2636                r#"{{"name":"tracing","normalized_url":"github.com/org/repo","clone_status":"ready","repos":[{}]}}"#,
2637                repos.join(",")
2638            ),
2639        )
2640    }
2641
2642    /// Run `init` against `responses` and return the persisted repo_id and
2643    /// every request the server saw.
2644    async fn init_against(root: &Path, responses: Vec<String>) -> (Option<String>, Vec<String>) {
2645        let (base, rx) = crate::test_helpers::spawn_seq(responses);
2646        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2647        _guard.set("XDG_CONFIG_HOME", root);
2648        _guard.set("TRACEVAULT_API_KEY", "tok");
2649        _guard.remove("TRACEVAULT_SERVER_URL");
2650
2651        init_in_directory(
2652            root,
2653            Some(&base),
2654            None,
2655            true,
2656            Some(crate::config::UserContext::Toggle(false)),
2657            crate::agent::Agent::Codex,
2658        )
2659        .await
2660        .expect("init succeeds");
2661
2662        let cfg = crate::config::TracevaultConfig::load(root).expect("config.toml written by init");
2663        (cfg.repo_id, rx.try_iter().collect())
2664    }
2665
2666    fn registered(requests: &[String]) -> bool {
2667        requests.iter().any(|r| r.starts_with("POST /api/v1/repos"))
2668    }
2669
2670    /// The prod incident: the checkout's directory is not named like the
2671    /// remote's existing repo. init binds that repo, and registers nothing.
2672    #[tokio::test]
2673    async fn init_binds_the_existing_repo_of_a_known_remote() {
2674        let _env_lock = crate::test_helpers::lock_env_mutation().await;
2675        let tmp = tempfile::tempdir().unwrap();
2676        crate::test_helpers::init_git_repo(tmp.path());
2677        add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
2678
2679        let (repo_id, requests) = init_against(
2680            tmp.path(),
2681            vec![
2682                resolve_remote_ok(),
2683                remote_detail(&[(CANONICAL, "tracevault")]),
2684            ],
2685        )
2686        .await;
2687
2688        assert_eq!(repo_id.as_deref(), Some(CANONICAL));
2689        assert!(!registered(&requests), "requests: {requests:?}");
2690    }
2691
2692    /// Several records and one is named like this checkout: that one — the
2693    /// record registering would have upserted anyway.
2694    #[tokio::test]
2695    async fn init_binds_the_record_named_like_the_checkout() {
2696        let _env_lock = crate::test_helpers::lock_env_mutation().await;
2697        let tmp = tempfile::tempdir().unwrap();
2698        crate::test_helpers::init_git_repo(tmp.path());
2699        add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
2700        let dir_name = crate::resolution::git_repo_name(tmp.path());
2701
2702        let (repo_id, requests) = init_against(
2703            tmp.path(),
2704            vec![
2705                resolve_remote_ok(),
2706                remote_detail(&[(CANONICAL, "tracevault"), (STRAY, &dir_name)]),
2707            ],
2708        )
2709        .await;
2710
2711        assert_eq!(repo_id.as_deref(), Some(STRAY));
2712        assert!(!registered(&requests));
2713    }
2714
2715    /// Re-running init keeps the repo the previous config.toml bound.
2716    #[tokio::test]
2717    async fn init_rerun_keeps_the_previously_bound_repo() {
2718        let _env_lock = crate::test_helpers::lock_env_mutation().await;
2719        let tmp = tempfile::tempdir().unwrap();
2720        crate::test_helpers::init_git_repo(tmp.path());
2721        add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
2722        fs::create_dir_all(tmp.path().join(".tracevault")).unwrap();
2723        fs::write(
2724            tmp.path().join(".tracevault/config.toml"),
2725            format!("repo_id = \"{STRAY}\"\n"),
2726        )
2727        .unwrap();
2728
2729        let (repo_id, requests) = init_against(
2730            tmp.path(),
2731            vec![
2732                resolve_remote_ok(),
2733                remote_detail(&[(CANONICAL, "tracevault"), (STRAY, "tracing-old")]),
2734            ],
2735        )
2736        .await;
2737
2738        assert_eq!(repo_id.as_deref(), Some(STRAY));
2739        assert!(!registered(&requests));
2740    }
2741
2742    /// Recording the binding keeps the rest of the config, including a
2743    /// hand-written `api_key` the struct never serializes (VIS-1046).
2744    #[tokio::test]
2745    async fn init_binding_keeps_the_rest_of_the_config() {
2746        let _env_lock = crate::test_helpers::lock_env_mutation().await;
2747        let tmp = tempfile::tempdir().unwrap();
2748        crate::test_helpers::init_git_repo(tmp.path());
2749        add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
2750        fs::create_dir_all(tmp.path().join(".tracevault")).unwrap();
2751        fs::write(
2752            tmp.path().join(".tracevault/config.toml"),
2753            "api_key = \"tvk_kept\"\ndefault_project = \"payments\"\nuser_context = false\n",
2754        )
2755        .unwrap();
2756
2757        let (repo_id, _) = init_against(
2758            tmp.path(),
2759            vec![
2760                resolve_remote_ok(),
2761                remote_detail(&[(CANONICAL, "tracevault")]),
2762            ],
2763        )
2764        .await;
2765
2766        assert_eq!(repo_id.as_deref(), Some(CANONICAL));
2767        let cfg = crate::config::TracevaultConfig::load(tmp.path()).unwrap();
2768        assert_eq!(cfg.api_key.as_deref(), Some("tvk_kept"));
2769        assert_eq!(cfg.default_project.as_deref(), Some("payments"));
2770    }
2771
2772    /// A re-run that cannot reach the server keeps the bound `repo_id`: it is
2773    /// never dropped, not even until registration would re-add it.
2774    #[tokio::test]
2775    async fn init_rerun_keeps_repo_id_when_the_server_check_fails() {
2776        let _env_lock = crate::test_helpers::lock_env_mutation().await;
2777        let tmp = tempfile::tempdir().unwrap();
2778        crate::test_helpers::init_git_repo(tmp.path());
2779        add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
2780        fs::create_dir_all(tmp.path().join(".tracevault")).unwrap();
2781        fs::write(
2782            tmp.path().join(".tracevault/config.toml"),
2783            format!("repo_id = \"{STRAY}\"\n"),
2784        )
2785        .unwrap();
2786
2787        let (repo_id, requests) = init_against(
2788            tmp.path(),
2789            vec![http_response("500 Internal Server Error", "{}")],
2790        )
2791        .await;
2792
2793        assert_eq!(repo_id.as_deref(), Some(STRAY));
2794        assert!(!registered(&requests));
2795    }
2796
2797    /// Several records, nothing says which: no guess, no new record.
2798    #[tokio::test]
2799    async fn init_registers_nothing_when_the_codebase_is_ambiguous() {
2800        let _env_lock = crate::test_helpers::lock_env_mutation().await;
2801        let tmp = tempfile::tempdir().unwrap();
2802        crate::test_helpers::init_git_repo(tmp.path());
2803        add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
2804
2805        let (repo_id, requests) = init_against(
2806            tmp.path(),
2807            vec![
2808                resolve_remote_ok(),
2809                remote_detail(&[(CANONICAL, "tracevault"), (STRAY, "tracing-old")]),
2810            ],
2811        )
2812        .await;
2813
2814        assert_eq!(repo_id, None);
2815        assert!(!registered(&requests));
2816    }
2817
2818    /// A known codebase with no live repo (e.g. its last one was tombstoned)
2819    /// still registers.
2820    #[tokio::test]
2821    async fn init_registers_for_a_codebase_without_live_repos() {
2822        let _env_lock = crate::test_helpers::lock_env_mutation().await;
2823        let tmp = tempfile::tempdir().unwrap();
2824        crate::test_helpers::init_git_repo(tmp.path());
2825        add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
2826
2827        let (repo_id, requests) = init_against(
2828            tmp.path(),
2829            vec![
2830                resolve_remote_ok(),
2831                remote_detail(&[]),
2832                http_response("201 Created", &format!(r#"{{"repo_id":"{CANONICAL}"}}"#)),
2833            ],
2834        )
2835        .await;
2836
2837        assert_eq!(repo_id.as_deref(), Some(CANONICAL));
2838        assert!(registered(&requests));
2839    }
2840
2841    /// If the server cannot say what it has, init does not register blind.
2842    #[tokio::test]
2843    async fn init_does_not_register_when_the_remote_check_fails() {
2844        let _env_lock = crate::test_helpers::lock_env_mutation().await;
2845        let tmp = tempfile::tempdir().unwrap();
2846        crate::test_helpers::init_git_repo(tmp.path());
2847        add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
2848
2849        let (repo_id, requests) = init_against(
2850            tmp.path(),
2851            vec![http_response("500 Internal Server Error", "{}")],
2852        )
2853        .await;
2854
2855        assert_eq!(repo_id, None);
2856        assert!(!registered(&requests));
2857    }
2858}