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