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