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