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