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