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