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