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