Skip to main content

tracevault_cli/commands/
init.rs

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