Skip to main content

tracevault_cli/commands/
init.rs

1use crate::api_client::ApiClient;
2use crate::config::{user_config_path_in, TracevaultConfig, UserContext};
3use crate::context::Context;
4use crate::resolution::{git_remote_url, git_repo_name, RegistrationPlan};
5use std::fs;
6use std::io::{self, BufRead, IsTerminal, Write};
7use std::path::{Path, PathBuf};
8
9/// Which Claude Code settings file to install hooks into.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
11pub enum ClaudeSettingsTarget {
12    /// .claude/settings.json — typically committed/shared with the team.
13    Shared,
14    /// .claude/settings.local.json — personal, conventionally git-ignored.
15    Local,
16}
17
18impl ClaudeSettingsTarget {
19    pub fn filename(self) -> &'static str {
20        match self {
21            ClaudeSettingsTarget::Shared => "settings.json",
22            ClaudeSettingsTarget::Local => "settings.local.json",
23        }
24    }
25
26    pub fn gitignore_entry(self) -> &'static str {
27        match self {
28            ClaudeSettingsTarget::Shared => ".claude/settings.json",
29            ClaudeSettingsTarget::Local => ".claude/settings.local.json",
30        }
31    }
32}
33
34/// Resolve which settings file to use. If the caller passed an explicit
35/// choice, honor it. Otherwise prompt interactively when stdin is a TTY,
36/// or fall back to Shared for non-interactive callers (CI, scripts, tests).
37fn resolve_claude_target(
38    explicit: Option<ClaudeSettingsTarget>,
39) -> io::Result<ClaudeSettingsTarget> {
40    if let Some(target) = explicit {
41        return Ok(target);
42    }
43    if !io::stdin().is_terminal() {
44        return Ok(ClaudeSettingsTarget::Shared);
45    }
46
47    let stdout = io::stdout();
48    let mut stdout = stdout.lock();
49    write!(
50        stdout,
51        "Install Claude Code hooks into [s]hared (.claude/settings.json) or [l]ocal (.claude/settings.local.json)? [s]: "
52    )?;
53    stdout.flush()?;
54
55    let mut line = String::new();
56    io::stdin().lock().read_line(&mut line)?;
57    let answer = line.trim().to_lowercase();
58    Ok(match answer.as_str() {
59        "l" | "local" => ClaudeSettingsTarget::Local,
60        _ => ClaudeSettingsTarget::Shared,
61    })
62}
63
64/// If `dir` is inside a LINKED git worktree (not the primary checkout), return
65/// the primary worktree root. Returns `None` for the primary checkout or a
66/// non-git directory.
67///
68/// A linked worktree has `git --git-dir` (e.g. `<primary>/.git/worktrees/<name>`)
69/// distinct from `git --git-common-dir` (`<primary>/.git`); in the primary
70/// checkout the two are equal. The primary root is the parent of the common dir.
71fn linked_worktree_primary(dir: &Path) -> Option<PathBuf> {
72    let output = std::process::Command::new("git")
73        .args(["rev-parse", "--git-dir", "--git-common-dir"])
74        .current_dir(dir)
75        .output()
76        .ok()?;
77    if !output.status.success() {
78        return None;
79    }
80    let stdout = String::from_utf8(output.stdout).ok()?;
81    let mut lines = stdout.lines();
82    let git_dir = lines.next()?.trim();
83    let git_common_dir = lines.next()?.trim();
84
85    // git may return paths relative to `dir`; join (absolute args replace the
86    // base) then canonicalize so the comparison is robust.
87    let git_dir = dir.join(git_dir).canonicalize().ok()?;
88    let git_common_dir = dir.join(git_common_dir).canonicalize().ok()?;
89
90    if git_dir == git_common_dir {
91        None // primary checkout
92    } else {
93        git_common_dir.parent().map(Path::to_path_buf)
94    }
95}
96
97/// Validate init flag combinations against the selected agent. `--claude-settings`
98/// selects between `.claude/settings.json` and `settings.local.json`, so it only
99/// applies to the Claude Code agent — `--agent codex` always writes
100/// `.codex/hooks.json`. Returns a human-readable error for an incompatible combo
101/// so the CLI rejects it instead of silently ignoring the flag.
102pub fn validate_init_flags(
103    agent: crate::agent::Agent,
104    claude_settings_set: bool,
105) -> Result<(), String> {
106    if matches!(
107        agent,
108        crate::agent::Agent::Codex | crate::agent::Agent::Gsd | crate::agent::Agent::OpenCode
109    ) && claude_settings_set
110    {
111        return Err("--claude-settings only applies to --agent claude-code".to_string());
112    }
113    Ok(())
114}
115
116pub async fn init_in_directory(
117    project_root: &Path,
118    server_url: Option<&str>,
119    claude_settings: Option<ClaudeSettingsTarget>,
120    no_gitignore: bool,
121    user_context: UserContext,
122    agent: crate::agent::Agent,
123) -> Result<String, io::Error> {
124    // Check for git repository
125    if !project_root.join(".git").exists() {
126        return Err(io::Error::new(
127            io::ErrorKind::NotFound,
128            "Not a git repository. Run 'git init' first.",
129        ));
130    }
131
132    // Refuse to initialize from a linked worktree: TraceVault's `.tracevault/`,
133    // git hooks, and Claude settings all belong in the primary checkout (which
134    // every worktree shares). Initializing here would create a stray
135    // `.tracevault/` in this worktree instead. (In a linked worktree `.git` is a
136    // file, so the check above passes — this guard is what catches it.)
137    if let Some(primary) = linked_worktree_primary(project_root) {
138        return Err(io::Error::new(
139            io::ErrorKind::Unsupported,
140            format!(
141                "Run `tracevault init` from the primary checkout ({}), not a linked worktree. \
142                 cd there and run it again — all worktrees share the primary's .tracevault/.",
143                primary.display()
144            ),
145        ));
146    }
147
148    // Resolve the hook-file gitignore entry per agent. Claude has a
149    // shared/local settings choice; Codex has a single .codex/hooks.json.
150    let (claude_target, hook_gitignore_entry): (Option<ClaudeSettingsTarget>, String) = match agent
151    {
152        crate::agent::Agent::ClaudeCode => {
153            let target = resolve_claude_target(claude_settings)?;
154            (Some(target), target.gitignore_entry().to_string())
155        }
156        crate::agent::Agent::Codex => (None, ".codex/hooks.json".to_string()),
157        // GSD (pi) itself creates `.gsd/settings.json` in the repo when
158        // `install_gsd_extension` shells out to `gsd install <dir> -l` (a
159        // project-local package registration, analogous to Claude's
160        // `.claude/settings.local.json`) — that's GSD's own local install
161        // state, not something the user should commit.
162        crate::agent::Agent::Gsd => (None, ".gsd/".to_string()),
163        // The OpenCode plugin is installed project-locally as
164        // `.opencode/plugins/tracevault.ts` — ignore the whole `.opencode/`
165        // directory rather than just the plugin file, in case OpenCode
166        // itself later writes other local state there.
167        crate::agent::Agent::OpenCode => (None, ".opencode/".to_string()),
168    };
169
170    // Create .tracevault/ directory
171    let config_dir = TracevaultConfig::config_dir(project_root);
172    fs::create_dir_all(&config_dir)?;
173    fs::create_dir_all(config_dir.join("sessions"))?;
174    fs::create_dir_all(config_dir.join("cache"))?;
175    // Self-contained ignore for runtime artifacts, so this `.tracevault/` is
176    // safe even if the root .gitignore doesn't cover it.
177    TracevaultConfig::ensure_gitignore(&config_dir)?;
178
179    // Keep tracevault's files local — update root .gitignore (unless opted out)
180    if !no_gitignore {
181        update_root_gitignore(project_root, &hook_gitignore_entry)?;
182    }
183
184    // Register repo on server if authenticated, server URL known, and git remote available
185    let remote_url = git_remote_url(project_root);
186    if remote_url.is_none() {
187        eprintln!("Warning: no git remote 'origin' configured. Skipping server registration.");
188        eprintln!("Run 'git remote add origin <url>' then 'tracevault sync' to register.");
189    }
190
191    // The repo a previous `init` bound, read before the config is rewritten:
192    // re-running `init` keeps it if its codebase still links it.
193    let previous_repo_id = TracevaultConfig::load(project_root)
194        .and_then(|c| c.repo_id)
195        .and_then(|id| id.parse::<uuid::Uuid>().ok());
196
197    // Write config (include server_url if available)
198    let mut config = TracevaultConfig::default();
199    if let Some(url) = server_url {
200        config.server_url = Some(url.to_string());
201    }
202    config.user_context = Some(user_context);
203    fs::write(
204        TracevaultConfig::config_path(project_root),
205        config.to_toml(),
206    )?;
207
208    // Install the selected agent's hooks.
209    match agent {
210        crate::agent::Agent::ClaudeCode => {
211            // `claude_target` is `Some` for the Claude agent by construction above.
212            let target =
213                claude_target.expect("claude settings target is resolved for the Claude agent");
214            install_claude_hooks(project_root, target)?;
215        }
216        crate::agent::Agent::Codex => {
217            install_codex_hooks(project_root)?;
218            println!("{}", codex_hook_trust_notice());
219        }
220        crate::agent::Agent::Gsd => {
221            // GSD (pi) loads extensions from the user-global ~/.gsd/, not from
222            // anything in the repo, so even the repo-local `init` path installs
223            // there — the repo itself only needs the .tracevault/ binding + git
224            // hooks set up above, which the extension shells out to `tracevault`
225            // to use. `Some(project_root)` makes `install_gsd_extension` run
226            // `gsd install -l` from this repo, registering the extension as a
227            // project-local install.
228            install_gsd_extension(Some(project_root))?;
229        }
230        crate::agent::Agent::OpenCode => {
231            install_opencode_plugin(Some(project_root))?;
232        }
233    }
234
235    // Install git hooks
236    install_git_hook(project_root)?;
237    install_post_commit_hook(project_root)?;
238
239    // Detect AI tools in the project
240    let detected = crate::hooks::detect_tools(project_root);
241    for tool in &detected {
242        println!("  Detected: {}", tool.name());
243    }
244
245    // A credential/URL mismatch aborts `init`: it would otherwise register the
246    // repo against whichever instance the env var names while holding another
247    // instance's session. `io::Error::other` because this function's error type
248    // is `io::Error`.
249    let (resolved_url, resolved_credential) =
250        crate::credentials::resolve_credentials_quiet(project_root)
251            .map_err(|e| io::Error::other(e.to_string()))?;
252    let effective_url = server_url.map(String::from).or(resolved_url);
253
254    if resolved_credential.is_none() {
255        eprintln!("Not logged in. Run 'tracevault login' to register this repo with the server.");
256    } else if let (Some(url), Some(remote)) = (effective_url, remote_url) {
257        let client = ApiClient::with_credential(&url, resolved_credential);
258        let repo_name = git_repo_name(project_root);
259        // Captured before `remote` is moved into the request below, so the
260        // codebase-resolve step doesn't need to shell out to git again.
261        let origin_url = remote.clone();
262
263        // A remote whose codebase already has a repo record binds to it:
264        // registering would upsert by THIS checkout's directory name, i.e. a
265        // second record for the same codebase whenever the names differ.
266        match crate::resolution::plan_registration(
267            &client,
268            &origin_url,
269            &repo_name,
270            previous_repo_id,
271        )
272        .await
273        {
274            Ok(RegistrationPlan::Existing(codebase, repo_id)) => {
275                println!(
276                    "Bound to existing repo {} (id: {repo_id}); not registering another record \
277                     for this codebase",
278                    codebase
279                        .repos
280                        .iter()
281                        .find(|r| r.id == repo_id)
282                        .map_or("", |r| r.name.as_str())
283                );
284                println!(
285                    "{}",
286                    crate::resolution::codebase_line(
287                        codebase.remote.name.as_deref(),
288                        &codebase.remote.normalized_url,
289                        &codebase.remote.clone_status
290                    )
291                );
292                persist_repo_binding(project_root, repo_id, Some(&codebase.remote));
293            }
294            Ok(RegistrationPlan::Ambiguous(codebase)) => {
295                eprintln!(
296                    "Warning: codebase {} already has {} repo records ({}) and none is named \
297                     '{repo_name}'; not registering another. Set `repo_id = \"<id>\"` in \
298                     .tracevault/config.toml to the one this checkout belongs to.",
299                    codebase.display_name(),
300                    codebase.repos.len(),
301                    codebase.repo_list()
302                );
303            }
304            Ok(RegistrationPlan::Register) => {
305                register_new_repo(&client, project_root, repo_name, origin_url).await;
306            }
307            // Without knowing what the server already has, registering could
308            // create the duplicate this check exists to prevent.
309            Err(e) => {
310                eprintln!(
311                    "Warning: could not check the server for an existing repo of this remote \
312                     ({e}); not registering. Run `tracevault init` again once the server is \
313                     reachable."
314                );
315            }
316        }
317    }
318
319    Ok(hook_gitignore_entry)
320}
321
322/// Record the repo this checkout binds — and its codebase, display-only — in
323/// an existing `.tracevault/config.toml`, returning whether it was written.
324///
325/// Never creates the config: a checkout without one is in workspace mode (a
326/// global install binds sessions with `repo switch`), and writing one would
327/// silently pin it to bound mode. A failed write never fails the caller.
328pub(crate) fn persist_repo_binding(
329    project_root: &Path,
330    repo_id: uuid::Uuid,
331    codebase: Option<&crate::api_client::ResolveRemoteResponse>,
332) -> bool {
333    let Some(mut cfg) = TracevaultConfig::load(project_root) else {
334        return false;
335    };
336    cfg.repo_id = Some(repo_id.to_string());
337    if let Some(remote) = codebase {
338        cfg.remote_id = Some(remote.remote_id.to_string());
339        cfg.codebase_name = remote.name.clone();
340    }
341    fs::write(TracevaultConfig::config_path(project_root), cfg.to_toml()).is_ok()
342}
343
344/// Register a repo for a remote the server has no live repo for, and persist
345/// its id (plus the codebase, display-only) to config.toml. Failure is a
346/// warning, never a failed `init`.
347async fn register_new_repo(
348    client: &ApiClient,
349    project_root: &Path,
350    repo_name: String,
351    origin_url: String,
352) {
353    match client
354        .register_repo(crate::api_client::RegisterRepoRequest {
355            repo_name,
356            github_url: Some(origin_url.clone()),
357        })
358        .await
359    {
360        Ok(resp) => {
361            println!("Repo registered on server (id: {})", resp.repo_id);
362            // Save repo_id to config
363            if let Some(mut cfg) = TracevaultConfig::load(project_root) {
364                cfg.repo_id = Some(resp.repo_id.to_string());
365                // Best-effort: resolve the codebase (deduped by normalized
366                // remote URL) and surface it to the user. Must never fail
367                // init — `repo_id` above stays authoritative for ingest;
368                // `remote_id`/`codebase_name` here are recorded for
369                // display only.
370                if let Ok(Some(remote)) = client.resolve_remote(&origin_url).await {
371                    println!(
372                        "{}",
373                        crate::resolution::codebase_line(
374                            remote.name.as_deref(),
375                            &remote.normalized_url,
376                            &remote.clone_status
377                        )
378                    );
379                    cfg.remote_id = Some(remote.remote_id.to_string());
380                    cfg.codebase_name = remote.name.clone();
381                }
382                let _ = fs::write(TracevaultConfig::config_path(project_root), cfg.to_toml());
383            }
384        }
385        Err(e) => {
386            eprintln!("{}", registration_failure_message(e.as_ref()));
387        }
388    }
389}
390
391/// The warning line for a failed repo registration during `init`. A 403 means
392/// the token is valid but not authorized to register this repo — distinct
393/// from a network/server fault, so it gets its own actionable wording; a 404
394/// means this server build doesn't recognize the registration route at all,
395/// which most plausibly means the CLI is newer than the server (a CLI/server
396/// version mismatch). Registration failure is non-fatal to `init` either
397/// way (a warning, not an aborted init — the repo can be registered later
398/// via `tracevault sync`).
399///
400/// Matches on the exact status-prefix shape `ApiClient::register_repo`
401/// produces (`"Server returned {status} ..."`, from its `authed_send_json`
402/// call) rather than a bare `.contains("403")`/`.contains("404")` — a
403/// response body that happens to contain that digit string (e.g. a proxy
404/// error page) must not be misclassified.
405fn registration_failure_message(err: &dyn std::error::Error) -> String {
406    let msg = err.to_string();
407    if msg.starts_with("Server returned 403 ") {
408        "Warning: you are not authorized to register this repo.".to_string()
409    } else if msg.starts_with("Server returned 404 ") {
410        "Warning: could not register repo on server (404) — this endpoint may not exist on \
411         this server yet, possibly a CLI/server version mismatch. Run `tracevault sync` again \
412         once the server is upgraded."
413            .to_string()
414    } else {
415        format!("Warning: could not register repo on server: {err}")
416    }
417}
418
419fn update_root_gitignore(project_root: &Path, settings_entry: &str) -> Result<(), io::Error> {
420    let path = project_root.join(".gitignore");
421    let existing = if path.exists() {
422        fs::read_to_string(&path)?
423    } else {
424        String::new()
425    };
426
427    // Only ignore what `init` actually creates or modifies: the `.tracevault/`
428    // directory and the single settings file we wrote hooks into. The
429    // other settings file is left untouched, so we don't add it here. An
430    // empty `settings_entry` means the agent writes nothing into the repo at
431    // all — skip it rather than appending a blank line.
432    let needed: Vec<&str> = [".tracevault/", settings_entry]
433        .iter()
434        .copied()
435        .filter(|entry| !entry.is_empty() && !existing.lines().any(|line| line.trim() == *entry))
436        .collect();
437
438    if needed.is_empty() {
439        return Ok(());
440    }
441
442    let mut content = existing;
443    if !content.is_empty() && !content.ends_with('\n') {
444        content.push('\n');
445    }
446    content.push_str("\n# TraceVault — local only, do not commit\n");
447    for entry in needed {
448        content.push_str(entry);
449        content.push('\n');
450    }
451
452    fs::write(path, content)
453}
454
455const HOOK_MARKER: &str = "# tracevault:enforce";
456const OLD_HOOK_MARKER: &str = "# tracevault:auto-push";
457
458fn install_git_hook(project_root: &Path) -> Result<(), io::Error> {
459    let hooks_dir = project_root.join(".git/hooks");
460    fs::create_dir_all(&hooks_dir)?;
461
462    let hook_path = hooks_dir.join("pre-push");
463    // Capture git's pre-push ref list once, then feed it to `check` explicitly
464    // rather than relying on it inheriting stdin from the hook process. `sync`
465    // never reads stdin, so today it reaches `check` anyway — this only drops
466    // the dependency on that inheritance for hooks installed from here on;
467    // already-installed hooks keep working without re-running `tracevault
468    // init`.
469    let tracevault_block = format!(
470        "{HOOK_MARKER}\n\
471         # Capture git's pre-push ref list once; `check` uses it to determine\n\
472         # which files are being pushed.\n\
473         tracevault_prepush_stdin=$(cat)\n\
474         tracevault sync 2>/dev/null || true\n\
475         printf '%s' \"$tracevault_prepush_stdin\" | tracevault check || {{ echo \"tracevault: policy check failed\"; exit 1; }}\n"
476    );
477
478    if hook_path.exists() {
479        let existing = fs::read_to_string(&hook_path)?;
480
481        // Already has new-style hook
482        if existing.contains(HOOK_MARKER) {
483            return Ok(());
484        }
485
486        // Replace old-style hook block if present
487        if existing.contains(OLD_HOOK_MARKER) {
488            let mut new_content = String::new();
489            let mut skip = false;
490            for line in existing.lines() {
491                if line.contains(OLD_HOOK_MARKER) {
492                    skip = true;
493                    continue;
494                }
495                if skip {
496                    // Skip old tracevault lines (they start with "tracevault " or are empty continuations)
497                    if line.starts_with("tracevault ") {
498                        continue;
499                    }
500                    skip = false;
501                }
502                new_content.push_str(line);
503                new_content.push('\n');
504            }
505            if !new_content.ends_with('\n') {
506                new_content.push('\n');
507            }
508            new_content.push_str(&tracevault_block);
509            fs::write(&hook_path, new_content)?;
510        } else {
511            // Append to existing hook
512            let mut content = existing;
513            if !content.ends_with('\n') {
514                content.push('\n');
515            }
516            content.push_str(&tracevault_block);
517            fs::write(&hook_path, content)?;
518        }
519    } else {
520        let content = format!("#!/bin/sh\n{tracevault_block}");
521        fs::write(&hook_path, content)?;
522    }
523
524    // Make executable
525    #[cfg(unix)]
526    {
527        use std::os::unix::fs::PermissionsExt;
528        let mut perms = fs::metadata(&hook_path)?.permissions();
529        perms.set_mode(0o755);
530        fs::set_permissions(&hook_path, perms)?;
531    }
532
533    Ok(())
534}
535
536const POST_COMMIT_MARKER: &str = "# tracevault:post-commit";
537
538fn install_post_commit_hook(project_root: &Path) -> Result<(), io::Error> {
539    let hooks_dir = project_root.join(".git/hooks");
540    fs::create_dir_all(&hooks_dir)?;
541
542    let hook_path = hooks_dir.join("post-commit");
543    let tracevault_block = format!("{POST_COMMIT_MARKER}\ntracevault commit-push 2>/dev/null &\n");
544
545    if hook_path.exists() {
546        let existing = fs::read_to_string(&hook_path)?;
547
548        if existing.contains(POST_COMMIT_MARKER) {
549            return Ok(());
550        }
551
552        let mut content = existing;
553        if !content.ends_with('\n') {
554            content.push('\n');
555        }
556        content.push_str(&tracevault_block);
557        fs::write(&hook_path, content)?;
558    } else {
559        let content = format!("#!/bin/sh\n{tracevault_block}");
560        fs::write(&hook_path, content)?;
561    }
562
563    #[cfg(unix)]
564    {
565        use std::os::unix::fs::PermissionsExt;
566        let mut perms = fs::metadata(&hook_path)?.permissions();
567        perms.set_mode(0o755);
568        fs::set_permissions(&hook_path, perms)?;
569    }
570
571    Ok(())
572}
573
574fn install_claude_hooks(
575    project_root: &Path,
576    target: ClaudeSettingsTarget,
577) -> Result<(), io::Error> {
578    let claude_dir = project_root.join(".claude");
579    fs::create_dir_all(&claude_dir)?;
580
581    let filename = target.filename();
582    let settings_path = claude_dir.join(filename);
583    let mut settings: serde_json::Value = if settings_path.exists() {
584        let content = fs::read_to_string(&settings_path)?;
585        serde_json::from_str(&content).map_err(|e| {
586            io::Error::new(
587                io::ErrorKind::InvalidData,
588                format!("Failed to parse .claude/{filename}: {e}"),
589            )
590        })?
591    } else {
592        serde_json::json!({})
593    };
594
595    let hooks = tracevault_hooks();
596
597    // Merge hooks into existing settings
598    let settings_obj = settings.as_object_mut().ok_or_else(|| {
599        io::Error::new(
600            io::ErrorKind::InvalidData,
601            format!(".claude/{filename} is not a JSON object"),
602        )
603    })?;
604
605    settings_obj.insert("hooks".to_string(), hooks);
606
607    let formatted = serde_json::to_string_pretty(&settings)
608        .map_err(|e| io::Error::other(format!("Failed to serialize settings: {e}")))?;
609    fs::write(&settings_path, formatted)?;
610
611    Ok(())
612}
613
614pub fn tracevault_hooks() -> serde_json::Value {
615    serde_json::json!({
616        "PreToolUse": [{
617            "matcher": "Write|Edit|Bash",
618            "hooks": [{
619                "type": "command",
620                "command": "tracevault stream --event pre-tool-use",
621                "timeout": 10,
622                "statusMessage": "TraceVault: streaming pre-tool event"
623            }]
624        }],
625        "PostToolUse": [{
626            "matcher": "",
627            "hooks": [{
628                "type": "command",
629                "command": "tracevault stream --event post-tool-use",
630                "timeout": 10,
631                "statusMessage": "TraceVault: streaming post-tool event"
632            }]
633        }],
634        "Notification": [{
635            "matcher": "",
636            "hooks": [{
637                "type": "command",
638                "command": "tracevault stream --event notification",
639                "timeout": 10,
640                "statusMessage": "TraceVault: streaming notification"
641            }]
642        }],
643        "Stop": [{
644            "matcher": "",
645            "hooks": [{
646                "type": "command",
647                "command": "tracevault stream --event stop",
648                "timeout": 10,
649                "statusMessage": "TraceVault: finalizing session"
650            }]
651        }],
652        "SessionStart": [{
653            "matcher": "",
654            "hooks": [{
655                "type": "command",
656                "command": "tracevault session-start",
657                "timeout": 10,
658                "statusMessage": "TraceVault: session start"
659            }]
660        }],
661        "UserPromptSubmit": [{
662            "matcher": "",
663            "hooks": [{
664                "type": "command",
665                "command": "tracevault user-prompt",
666                "timeout": 10,
667                "statusMessage": "TraceVault: policy reinforcement"
668            }]
669        }]
670    })
671}
672
673/// Codex CLI hook set, mirroring `tracevault_hooks()` but with Codex commands.
674/// What to tell the user after Codex hooks are installed.
675///
676/// Writing `hooks.json` is only half the setup: Codex >= 0.153 gates hooks
677/// behind persisted *hook trust*, and a non-interactive `codex exec` skips
678/// untrusted hooks without printing anything — so capture looks installed and
679/// silently produces no sessions until trust is granted once. Observed on
680/// Codex 0.153.4, where neither `codex doctor` nor `codex features` reports
681/// the trust state, which is why the CLI has to say it here.
682pub fn codex_hook_trust_notice() -> &'static str {
683    "Codex gates hooks behind hook trust: until it is granted, `codex exec` skips them \
684     silently and no session is captured. Run `codex` once interactively in a repo and \
685     approve the hook-trust prompt; unattended runs (CI) can pass \
686     `--dangerously-bypass-hook-trust` instead."
687}
688
689/// Capture hooks carry `--agent codex`; the injection hooks (session-start /
690/// user-prompt) are agent-agnostic. Matchers are `""` (all tools).
691///
692/// We intentionally do NOT register a `PreToolUse` hook for Codex. Unlike Claude
693/// Code — whose `PreToolUse` is scoped to `Write|Edit|Bash` — the CLI does no
694/// Codex-specific pre-tool work, and `PostToolUse` + `Stop` already stream the
695/// (incremental, offset-tracked) rollout. A pre-tool hook on every tool call
696/// would only double the per-call streaming for no added capture. No
697/// `Notification` event either (Codex has none).
698pub fn codex_hooks() -> serde_json::Value {
699    serde_json::json!({
700        "SessionStart": [{
701            "matcher": "",
702            "hooks": [{ "type": "command", "command": "tracevault session-start", "timeout": 10, "statusMessage": "TraceVault: session start" }]
703        }],
704        "UserPromptSubmit": [{
705            "matcher": "",
706            "hooks": [{ "type": "command", "command": "tracevault user-prompt", "timeout": 10, "statusMessage": "TraceVault: policy reinforcement" }]
707        }],
708        "PostToolUse": [{
709            "matcher": "",
710            "hooks": [{ "type": "command", "command": "tracevault stream --event post-tool-use --agent codex", "timeout": 10, "statusMessage": "TraceVault: streaming post-tool event" }]
711        }],
712        "Stop": [{
713            "matcher": "",
714            "hooks": [{ "type": "command", "command": "tracevault stream --event stop --agent codex", "timeout": 10, "statusMessage": "TraceVault: finalizing session" }]
715        }]
716    })
717}
718
719/// Embedded pi/GSD extension source (bundled at build time — see
720/// `assets/gsd-extension/{index.ts,package.json,extension-manifest.json}`,
721/// the checked-in source this installer writes verbatim).
722const GSD_EXT_INDEX_TS: &str = include_str!("../../assets/gsd-extension/index.ts");
723const GSD_EXT_PACKAGE_JSON: &str = include_str!("../../assets/gsd-extension/package.json");
724const GSD_EXT_MANIFEST_JSON: &str =
725    include_str!("../../assets/gsd-extension/extension-manifest.json");
726
727/// Path of the stable directory (under the user's config dir) that holds the
728/// TraceVault GSD extension source, shared by `install_gsd_extension` so the
729/// write and the `gsd install` invocation always agree on where it lives.
730fn gsd_extension_source_dir() -> io::Result<PathBuf> {
731    let config_dir = dirs::config_dir().or_else(|| dirs::home_dir().map(|h| h.join(".config")));
732    let config_dir = config_dir
733        .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "no config or home dir"))?;
734    Ok(config_dir.join("tracevault").join("gsd-extension"))
735}
736
737/// Install the TraceVault pi/GSD extension and register it with GSD so it
738/// actually loads.
739///
740/// GSD (pi) only loads an extension that (a) has an `extension-manifest.json`
741/// in its directory *and* (b) was registered via `gsd install <dir>` — a
742/// hand-written `registry.json` entry is inert (`gsd list` won't show it).
743/// So this writes the extension source (`index.ts`, `package.json`,
744/// `extension-manifest.json`) to a stable, idempotent source directory
745/// (`<config_dir>/tracevault/gsd-extension`), best-effort cleans up any
746/// stale/inert registration left behind by an older version of this
747/// installer, and then shells out to `gsd install` to register + load it.
748///
749/// `project_root` selects how `gsd install` is invoked:
750/// - `Some(repo)`: project-local install (`gsd install <dir> -l`, run with
751///   `repo` as the working directory) — used by `tracevault init`.
752/// - `None`: global install (`gsd install <dir>`, applies to all GSD
753///   sessions on this machine) — used by `tracevault init --global`.
754///
755/// If the `gsd` binary can't be found or the install command fails, this
756/// does NOT fail `init`: it prints a warning explaining how to finish the
757/// registration by hand and returns `Ok(())`. The extension source is still
758/// written either way, so the user (or a later retry) has something to
759/// register.
760pub fn install_gsd_extension(project_root: Option<&Path>) -> io::Result<()> {
761    let home =
762        dirs::home_dir().ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "no home dir"))?;
763    let gsd_home = home.join(".gsd");
764
765    let source_dir = gsd_extension_source_dir()?;
766    fs::create_dir_all(&source_dir)?;
767    fs::write(source_dir.join("index.ts"), GSD_EXT_INDEX_TS)?;
768    fs::write(source_dir.join("package.json"), GSD_EXT_PACKAGE_JSON)?;
769    fs::write(
770        source_dir.join("extension-manifest.json"),
771        GSD_EXT_MANIFEST_JSON,
772    )?;
773
774    // Best-effort cleanup of the OLD, broken install (hand-written registry
775    // entries that GSD never actually loaded). Never blocks the rest of the
776    // install — see `cleanup_stale_gsd_registration`.
777    if let Err(e) = cleanup_stale_gsd_registration(&gsd_home) {
778        eprintln!("Warning: could not clean up the previous GSD extension registration: {e}");
779    }
780
781    // Register + load the extension via the `gsd` CLI. `gsd install` is what
782    // actually makes GSD load the extension; our own registry.json edits
783    // never did.
784    let local_flag = project_root.is_some();
785    let mut cmd = std::process::Command::new("gsd");
786    cmd.arg("install").arg(&source_dir);
787    if let Some(root) = project_root {
788        cmd.arg("-l");
789        cmd.current_dir(root);
790    }
791
792    let retry_hint = format!(
793        "gsd install {}{}",
794        source_dir.display(),
795        if local_flag { " -l" } else { "" }
796    );
797
798    match cmd.output() {
799        Ok(output) if output.status.success() => {
800            println!(
801                "TraceVault: installed and registered the GSD extension ({}).",
802                source_dir.display()
803            );
804        }
805        Ok(output) => {
806            eprintln!(
807                "TraceVault: installed the GSD extension source to {}, but `gsd install` failed:\n{}Ensure `gsd` is on PATH and run: `{retry_hint}` to enable capture.",
808                source_dir.display(),
809                String::from_utf8_lossy(&output.stderr),
810            );
811        }
812        Err(e) => {
813            eprintln!(
814                "TraceVault: installed the GSD extension source to {}, but could not run `gsd install` ({e}). Ensure `gsd` is on PATH and run: `{retry_hint}` to enable capture.",
815                source_dir.display(),
816            );
817        }
818    }
819
820    Ok(())
821}
822
823/// TraceVault OpenCode plugin source, embedded from the checked-in assets
824/// this installer writes verbatim (mirrors the GSD extension embeds above).
825const OPENCODE_PLUGIN_INDEX: &str = include_str!("../../assets/opencode-plugin/index.ts");
826
827/// Install the TraceVault OpenCode plugin. `project_root = Some(dir)` installs
828/// project-local at `<dir>/.opencode/plugins/tracevault.ts`; `None` installs
829/// global at `~/.config/opencode/plugins/tracevault.ts` (using the same
830/// config-dir resolution as `gsd_extension_source_dir` above). OpenCode
831/// auto-loads `*.ts` modules from that directory — no separate "install"
832/// command. Returns an error on failure (unresolvable config dir, or a write
833/// error) so the caller aborts init loudly, consistent with the Codex/GSD arms
834/// — a swallowed failure would make `init` report success while no plugin was
835/// written, silently disabling capture.
836///
837/// A FLAT `.ts` file is used rather than a `tracevault/` package directory: a
838/// package subdir (index.ts + package.json) makes OpenCode try to resolve it as
839/// an npm package and stalls at startup offline, whereas a flat module loads
840/// directly (both confirmed during the capture spike). The plugin only imports
841/// the `node:child_process` builtin, so it needs no package manifest.
842pub fn install_opencode_plugin(project_root: Option<&Path>) -> io::Result<()> {
843    let plugins_dir = match project_root {
844        Some(root) => root.join(".opencode").join("plugins"),
845        None => {
846            let config_dir =
847                dirs::config_dir().or_else(|| dirs::home_dir().map(|h| h.join(".config")));
848            config_dir
849                .ok_or_else(|| {
850                    io::Error::new(
851                        io::ErrorKind::NotFound,
852                        "could not determine the config directory for the OpenCode plugin install",
853                    )
854                })?
855                .join("opencode")
856                .join("plugins")
857        }
858    };
859
860    write_opencode_plugin_files(&plugins_dir)
861}
862
863fn write_opencode_plugin_files(plugins_dir: &Path) -> io::Result<()> {
864    fs::create_dir_all(plugins_dir)?;
865    fs::write(plugins_dir.join("tracevault.ts"), OPENCODE_PLUGIN_INDEX)?;
866    Ok(())
867}
868
869/// Best-effort cleanup of the extension registration left behind by an OLDER
870/// version of this installer: the `tracevault-tracker` directory (an earlier,
871/// incorrect Codex-clone `hooks.json` shim that impersonated this extension
872/// under the wrong name) and any registry entries for `tracevault-tracker` or
873/// `tracevault` — both are inert now that `gsd install` manages registration.
874///
875/// If `registry.json` is missing, there's nothing to clean up. If it exists
876/// but fails to parse, or its shape is not a valid registry (root not an
877/// object, or a non-object `entries` field), it is structurally corrupt: we
878/// leave it byte-for-byte untouched (skip cleanup) rather than risk
879/// destroying every other extension the user has registered.
880pub fn cleanup_stale_gsd_registration(gsd_home: &Path) -> io::Result<()> {
881    let ext_root = gsd_home.join("extensions");
882    let reg_path = ext_root.join("registry.json");
883
884    // Validate the registry BEFORE mutating anything under ~/.gsd. If it exists
885    // but is structurally corrupt (unparseable, or a non-object root/`entries`),
886    // leave the extensions directory entirely untouched — not even the stale
887    // tracker dir is removed — so a corrupt registry yields zero mutation.
888    let reg: Option<serde_json::Value> = if reg_path.exists() {
889        let content = fs::read_to_string(&reg_path)?;
890        let parsed: serde_json::Value = match serde_json::from_str(&content) {
891            Ok(v) => v,
892            Err(_) => return Ok(()), // corrupt: touch nothing
893        };
894        let corrupt = match parsed.as_object() {
895            None => true,
896            Some(obj) => matches!(obj.get("entries"), Some(v) if !v.is_object()),
897        };
898        if corrupt {
899            return Ok(()); // structurally corrupt: touch nothing
900        }
901        Some(parsed)
902    } else {
903        None
904    };
905
906    // Registry is valid or absent — now safe to remove the superseded tracker shim.
907    let stale = ext_root.join("tracevault-tracker");
908    if stale.exists() {
909        fs::remove_dir_all(&stale)?;
910    }
911
912    // Drop stale registry entries (only when a valid registry exists).
913    if let Some(mut reg) = reg {
914        if let Some(entries) = reg.get_mut("entries").and_then(|e| e.as_object_mut()) {
915            let removed_tracker = entries.remove("tracevault-tracker").is_some();
916            let removed_inert = entries.remove("tracevault").is_some();
917            if removed_tracker || removed_inert {
918                // Atomic write (temp file + rename), pretty-printed.
919                let tmp = reg_path.with_extension("json.tmp");
920                fs::write(&tmp, serde_json::to_string_pretty(&reg)?)?;
921                fs::rename(&tmp, &reg_path)?;
922            }
923        }
924    }
925    Ok(())
926}
927
928/// Read `hooks_path` as a JSON object (or `{}` if absent), deep-merge `ours`
929/// into its `hooks` map via [`merge_hooks`] (idempotent, never clobbers existing
930/// hooks/keys), and write the result back atomically (sibling temp file +
931/// rename). Shared by the hook-file installers so the read → merge →
932/// atomic-write pattern lives in exactly one place. Works for both Claude's
933/// `settings.json` and Codex's `hooks.json`, whose roots are the object
934/// `merge_hooks` mutates (`root["hooks"]`). On a merge error (malformed
935/// existing file) it returns before writing, so the target is never clobbered
936/// and no temp file is left behind.
937fn merge_hooks_into_file(hooks_path: &Path, ours: &serde_json::Value) -> io::Result<()> {
938    // Defense-in-depth against path traversal: callers pass a constant filename
939    // joined to a home/cwd base (global callers additionally go through
940    // `safe_join`), so a `..` component should never appear — reject it outright
941    // rather than read/write through it.
942    if hooks_path
943        .components()
944        .any(|c| c == std::path::Component::ParentDir)
945    {
946        return Err(io::Error::new(
947            io::ErrorKind::InvalidInput,
948            format!("refusing to use path with '..': {}", hooks_path.display()),
949        ));
950    }
951    let mut root: serde_json::Value = if hooks_path.exists() {
952        let content = fs::read_to_string(hooks_path)?;
953        serde_json::from_str(&content).map_err(|e| {
954            io::Error::new(
955                io::ErrorKind::InvalidData,
956                format!("Failed to parse {}: {e}", hooks_path.display()),
957            )
958        })?
959    } else {
960        serde_json::json!({})
961    };
962
963    merge_hooks(&mut root, ours, hooks_path)?;
964
965    let formatted = serde_json::to_string_pretty(&root).map_err(|e| {
966        io::Error::other(format!("Failed to serialize {}: {e}", hooks_path.display()))
967    })?;
968    let tmp = hooks_path.with_extension("json.tmp");
969    fs::write(&tmp, formatted)?;
970    fs::rename(&tmp, hooks_path)?;
971    Ok(())
972}
973
974/// Deep-merge the Codex hook set into `<project_root>/.codex/hooks.json`,
975/// creating it if absent (idempotent, never clobbers existing hooks/keys,
976/// atomic write). Repo-local counterpart of [`install_global_codex_hooks`].
977pub fn install_codex_hooks(project_root: &Path) -> io::Result<()> {
978    let codex_dir = project_root.join(".codex");
979    fs::create_dir_all(&codex_dir)?;
980    merge_hooks_into_file(&codex_dir.join("hooks.json"), &codex_hooks())
981}
982
983/// Install TraceVault's Codex hooks into `<codex_dir>/hooks.json` and append a
984/// workspace-mode instruction block to `<codex_dir>/AGENTS.md` (idempotent,
985/// atomic), mirroring the Claude global install's `settings.json` + `CLAUDE.md`.
986/// Intended for `tracevault init --global --agent codex`. Codex reads `AGENTS.md`
987/// for agent instructions, so the workspace-mode block reaches detached Codex
988/// sessions the same way the `CLAUDE.md` block reaches Claude ones.
989pub fn install_global_codex_hooks(codex_dir: &Path) -> io::Result<()> {
990    fs::create_dir_all(codex_dir)?;
991    // Canonicalize the base so safe_join keeps target files directly within it.
992    let base = codex_dir.canonicalize()?;
993    merge_hooks_into_file(&safe_join(&base, "hooks.json")?, &codex_hooks())?;
994    append_workspace_md(&safe_join(&base, "AGENTS.md")?)
995}
996
997// Workspace-mode instruction block. Agent-agnostic (it only references
998// `tracevault repo …`), so it's shared verbatim between the Claude global
999// install's `CLAUDE.md` and the Codex global install's `AGENTS.md`.
1000const GLOBAL_CLAUDE_MD_MARKER: &str = "<!-- tracevault:workspace-mode -->";
1001
1002const GLOBAL_CLAUDE_MD_BLOCK: &str = "\
1003<!-- tracevault:workspace-mode -->
1004## TraceVault (workspace mode)
1005You may be running detached from any single repository. Before working on a repo, run
1006`tracevault repo switch <path>` to bind tracing and fetch that repo's policies; treat its
1007output as binding. Use `--path <path>` on `tracevault repo status` for a one-off. Repos must
1008already be registered with TraceVault.
1009";
1010
1011/// Append the workspace-mode instruction block to `md_path` (creating it if
1012/// absent), idempotently — guarded by [`GLOBAL_CLAUDE_MD_MARKER`], so a re-run
1013/// never duplicates it and any existing user content is preserved. Shared by
1014/// the Claude global install (`CLAUDE.md`) and the Codex global install
1015/// (`AGENTS.md`).
1016fn append_workspace_md(md_path: &Path) -> io::Result<()> {
1017    // Defense-in-depth against path traversal (see `merge_hooks_into_file`).
1018    if md_path
1019        .components()
1020        .any(|c| c == std::path::Component::ParentDir)
1021    {
1022        return Err(io::Error::new(
1023            io::ErrorKind::InvalidInput,
1024            format!("refusing to use path with '..': {}", md_path.display()),
1025        ));
1026    }
1027    let existing = if md_path.exists() {
1028        fs::read_to_string(md_path)?
1029    } else {
1030        String::new()
1031    };
1032    if existing.contains(GLOBAL_CLAUDE_MD_MARKER) {
1033        return Ok(());
1034    }
1035    let mut content = existing;
1036    if !content.is_empty() && !content.ends_with('\n') {
1037        content.push('\n');
1038    }
1039    if !content.is_empty() {
1040        content.push('\n');
1041    }
1042    content.push_str(GLOBAL_CLAUDE_MD_BLOCK);
1043    fs::write(md_path, content)
1044}
1045
1046/// Join a constant file name to `base` and confirm the result stays directly
1047/// within `base` — defense-in-depth so a path derived from the environment
1048/// ($HOME) cannot escape the intended `.claude` directory.
1049fn safe_join(base: &Path, name: &str) -> io::Result<PathBuf> {
1050    let joined = base.join(name);
1051    if joined.parent() != Some(base) {
1052        return Err(io::Error::new(
1053            io::ErrorKind::InvalidInput,
1054            format!(
1055                "refusing to access path outside {}: {}",
1056                base.display(),
1057                joined.display()
1058            ),
1059        ));
1060    }
1061    Ok(joined)
1062}
1063
1064/// Merge our hook entries into an existing `settings["hooks"]` object, per
1065/// event, appending our entry only if no existing entry in that event's
1066/// array already has an inner hook with the same `command` (dedupe → makes
1067/// repeated calls idempotent). Never removes or overwrites the user's other
1068/// hooks or top-level keys.
1069///
1070/// Absent values (no top-level `settings`, no `hooks` key, no entry for a
1071/// given event) are created fresh — that's fine. But if an EXISTING value
1072/// has an unexpected shape (top-level `settings` isn't an object, an
1073/// existing `hooks` isn't an object, or an existing per-event value isn't an
1074/// array), this errors loudly instead of silently discarding it, mirroring
1075/// `install_claude_hooks`'s treatment of a non-object settings file.
1076fn merge_hooks(
1077    settings: &mut serde_json::Value,
1078    ours: &serde_json::Value,
1079    path: &Path,
1080) -> io::Result<()> {
1081    if settings.is_null() {
1082        *settings = serde_json::json!({});
1083    }
1084    let settings_obj = settings.as_object_mut().ok_or_else(|| {
1085        io::Error::new(
1086            io::ErrorKind::InvalidData,
1087            format!("{} is not a JSON object", path.display()),
1088        )
1089    })?;
1090
1091    let hooks_value = settings_obj
1092        .entry("hooks")
1093        .or_insert_with(|| serde_json::json!({}));
1094    let hooks_obj = hooks_value.as_object_mut().ok_or_else(|| {
1095        io::Error::new(
1096            io::ErrorKind::InvalidData,
1097            format!("{} \"hooks\" key is not a JSON object", path.display()),
1098        )
1099    })?;
1100
1101    let Some(ours_obj) = ours.as_object() else {
1102        return Ok(());
1103    };
1104
1105    for (event, our_array) in ours_obj {
1106        let Some(our_entries) = our_array.as_array() else {
1107            continue;
1108        };
1109
1110        let existing_value = hooks_obj
1111            .entry(event.clone())
1112            .or_insert_with(|| serde_json::json!([]));
1113        let existing_array = existing_value.as_array_mut().ok_or_else(|| {
1114            io::Error::new(
1115                io::ErrorKind::InvalidData,
1116                format!(
1117                    "{} \"hooks\".\"{event}\" is not a JSON array",
1118                    path.display()
1119                ),
1120            )
1121        })?;
1122
1123        for our_entry in our_entries {
1124            let our_command = entry_command(our_entry);
1125            let already_present = existing_array
1126                .iter()
1127                .any(|existing_entry| entry_contains_command(existing_entry, our_command));
1128            if !already_present {
1129                existing_array.push(our_entry.clone());
1130            }
1131        }
1132    }
1133
1134    Ok(())
1135}
1136
1137/// Extract the inner `hooks[0].command` string from a hook-event entry, if
1138/// present.
1139fn entry_command(entry: &serde_json::Value) -> Option<&str> {
1140    entry.get("hooks")?.get(0)?.get("command")?.as_str()
1141}
1142
1143/// Whether any of `entry`'s inner `hooks[].command` values equal `cmd`. Unlike
1144/// `entry_command` (which only looks at `hooks[0]`), this scans the whole
1145/// inner `hooks` array — a user entry can have our command anywhere in it
1146/// (e.g. `hooks[1]`), and missing that would let a duplicate get appended.
1147fn entry_contains_command(entry: &serde_json::Value, cmd: Option<&str>) -> bool {
1148    let Some(hooks) = entry.get("hooks").and_then(|h| h.as_array()) else {
1149        return false;
1150    };
1151    hooks
1152        .iter()
1153        .any(|hook| hook.get("command").and_then(|c| c.as_str()) == cmd)
1154}
1155
1156/// Install TraceVault's Claude Code hooks into `claude_dir/settings.json`
1157/// (deep-merged, never clobbering existing hooks/keys) and append a
1158/// workspace-mode instruction block to `claude_dir/CLAUDE.md` (idempotent,
1159/// guarded by a marker comment). Intended for `tracevault init --global`,
1160/// installing once for all Claude Code sessions rather than per-repo.
1161pub fn install_global_hooks(claude_dir: &Path) -> io::Result<()> {
1162    fs::create_dir_all(claude_dir)?;
1163
1164    // Canonicalize the base to defend against path traversal attacks.
1165    // safe_join will verify that target files stay directly within this base.
1166    let base = claude_dir.canonicalize()?;
1167
1168    // --- settings.json: deep-merge hooks (atomic) ---
1169    merge_hooks_into_file(&safe_join(&base, "settings.json")?, &tracevault_hooks())?;
1170
1171    // --- CLAUDE.md: append the workspace-mode instruction block, idempotently ---
1172    append_workspace_md(&safe_join(&base, "CLAUDE.md")?)
1173}
1174
1175/// Write the user-level `config.toml` (under `config_root`) carrying the
1176/// user-context setting. An EXISTING user config is preserved (this mirrors the
1177/// "don't clobber" contract of the global-hooks install): `requested` overrides
1178/// the user_context when a flag was given; otherwise an existing value is kept,
1179/// and only a first-time setup (no existing config) defaults to enabled.
1180/// When the resulting layer is enabled, the referenced context file is seeded
1181/// (empty) if absent — a custom `--user-context <path>` seeds THAT file, a
1182/// disabled layer seeds nothing. Returns the active context file path (the file
1183/// the hook will read), or `None` when the layer is disabled. Used by `init --global`.
1184pub fn write_global_user_config_in(
1185    config_root: &Path,
1186    requested: Option<UserContext>,
1187) -> io::Result<Option<PathBuf>> {
1188    fs::create_dir_all(config_root)?;
1189    // Preserve an existing (valid) user config; malformed/missing → start fresh.
1190    let mut config = crate::config::try_load_user_config_in(config_root)
1191        .ok()
1192        .flatten()
1193        .unwrap_or_default();
1194    // Requested flag wins; else keep an existing value; else first-run default = enabled.
1195    let user_context = requested
1196        .or_else(|| config.user_context.clone())
1197        .unwrap_or(UserContext::Toggle(true));
1198    let active = user_context
1199        .resolve()
1200        .map(|_| user_context.path_in(config_root));
1201    config.user_context = Some(user_context);
1202    fs::write(user_config_path_in(config_root), config.to_toml())?;
1203    if let Some(ref ctx_path) = active {
1204        if !ctx_path.exists() {
1205            Context::default().save_to(ctx_path)?;
1206        }
1207    }
1208    Ok(active)
1209}
1210
1211#[cfg(test)]
1212mod tests {
1213    use super::*;
1214    use std::io::{BufRead, BufReader, Write};
1215    use std::net::TcpListener;
1216    use std::thread;
1217
1218    /// Installing the hooks is not enough on Codex >= 0.153: they are gated
1219    /// behind persisted hook trust, and `codex exec` skips untrusted hooks
1220    /// silently. The notice must say how to grant that trust interactively and
1221    /// name the flag that unblocks unattended runs — otherwise a user (or a CI
1222    /// image) reads "Installed" and gets no capture at all.
1223    #[test]
1224    fn codex_hook_trust_notice_explains_how_to_grant_trust() {
1225        let notice = codex_hook_trust_notice();
1226        assert!(
1227            notice.contains("hook trust"),
1228            "notice must name what is missing: {notice}"
1229        );
1230        assert!(
1231            notice.contains("codex") && notice.contains("approve"),
1232            "notice must tell the user to run codex and approve the prompt: {notice}"
1233        );
1234        assert!(
1235            notice.contains("--dangerously-bypass-hook-trust"),
1236            "notice must name the flag for unattended/CI runs: {notice}"
1237        );
1238        assert!(
1239            notice.contains("silently"),
1240            "notice must say the failure is silent, which is why it needs saying: {notice}"
1241        );
1242    }
1243
1244    /// Spawn a one-shot raw-HTTP server that returns `response` to the first
1245    /// request it accepts (mirrors `commands::repo`'s test module).
1246    fn spawn_once(response: String) -> String {
1247        let response: &'static str = Box::leak(response.into_boxed_str());
1248        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1249        let addr = listener.local_addr().unwrap();
1250        thread::spawn(move || {
1251            if let Ok((stream, _)) = listener.accept() {
1252                let mut reader = BufReader::new(stream);
1253                let mut request_line = String::new();
1254                let _ = reader.read_line(&mut request_line);
1255                let mut stream = reader.into_inner();
1256                let _ = stream.write_all(response.as_bytes());
1257                let _ = stream.flush();
1258            }
1259        });
1260        format!("http://{addr}")
1261    }
1262
1263    /// Format a raw HTTP/1.1 response with the given `status` line and a
1264    /// correct `Content-Length` for `body`.
1265    fn http_response(status: &str, body: &str) -> String {
1266        format!(
1267            "HTTP/1.1 {}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
1268            status,
1269            body.len(),
1270            body
1271        )
1272    }
1273
1274    fn add_origin_remote(dir: &Path, url: &str) {
1275        let ok = std::process::Command::new("git")
1276            .args(["-C", &dir.to_string_lossy(), "remote", "add", "origin", url])
1277            .status()
1278            .expect("git remote add failed")
1279            .success();
1280        assert!(ok, "git remote add must succeed");
1281    }
1282
1283    #[test]
1284    fn linked_worktree_primary_detects_linked_and_primary() {
1285        let tmp = tempfile::tempdir().unwrap();
1286        let repo = tmp.path().join("repo");
1287        let wt = tmp.path().join("linked-wt");
1288        std::fs::create_dir_all(&repo).unwrap();
1289        crate::test_helpers::init_git_repo(&repo);
1290        crate::test_helpers::add_worktree(&repo, &wt);
1291
1292        // Primary checkout → None.
1293        assert!(
1294            linked_worktree_primary(&repo).is_none(),
1295            "primary checkout must not be flagged as a linked worktree"
1296        );
1297        // Linked worktree → Some(primary root).
1298        let primary = linked_worktree_primary(&wt).expect("linked worktree must be detected");
1299        assert_eq!(
1300            primary.canonicalize().unwrap(),
1301            repo.canonicalize().unwrap(),
1302            "must resolve to the primary repo root"
1303        );
1304    }
1305
1306    #[test]
1307    fn linked_worktree_primary_none_for_non_git() {
1308        let tmp = tempfile::tempdir().unwrap();
1309        assert!(
1310            linked_worktree_primary(tmp.path()).is_none(),
1311            "a non-git directory is not a linked worktree"
1312        );
1313    }
1314
1315    #[test]
1316    fn merge_hooks_into_empty_settings_adds_all_our_events() {
1317        let mut settings = serde_json::json!({});
1318        let ours = tracevault_hooks();
1319        merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1320
1321        let hooks = settings.get("hooks").unwrap();
1322        for event in [
1323            "PreToolUse",
1324            "PostToolUse",
1325            "Notification",
1326            "Stop",
1327            "SessionStart",
1328            "UserPromptSubmit",
1329        ] {
1330            assert!(hooks.get(event).is_some(), "missing event {event}");
1331        }
1332    }
1333
1334    #[test]
1335    fn merge_hooks_preserves_unrelated_user_hook_and_keys() {
1336        let mut settings = serde_json::json!({
1337            "model": "opus",
1338            "hooks": {
1339                "PreToolUse": [{
1340                    "matcher": "",
1341                    "hooks": [{ "type": "command", "command": "my-own-hook" }]
1342                }]
1343            }
1344        });
1345        let ours = tracevault_hooks();
1346        merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1347
1348        // Other top-level keys preserved.
1349        assert_eq!(settings.get("model").unwrap(), "opus");
1350
1351        let pre_tool_use = settings["hooks"]["PreToolUse"].as_array().unwrap();
1352        // Both the user's own hook and ours are present.
1353        assert_eq!(pre_tool_use.len(), 2);
1354        let commands: Vec<&str> = pre_tool_use
1355            .iter()
1356            .map(|e| entry_command(e).unwrap())
1357            .collect();
1358        assert!(commands.contains(&"my-own-hook"));
1359        assert!(commands.contains(&"tracevault stream --event pre-tool-use"));
1360
1361        // Other events were added fresh.
1362        assert!(settings["hooks"]["SessionStart"].is_array());
1363    }
1364
1365    #[test]
1366    fn merge_hooks_is_idempotent() {
1367        let mut settings = serde_json::json!({});
1368        let ours = tracevault_hooks();
1369        merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1370        merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1371
1372        for event in [
1373            "PreToolUse",
1374            "PostToolUse",
1375            "Notification",
1376            "Stop",
1377            "SessionStart",
1378            "UserPromptSubmit",
1379        ] {
1380            let arr = settings["hooks"][event].as_array().unwrap();
1381            assert_eq!(arr.len(), 1, "event {event} should not be duplicated");
1382        }
1383    }
1384
1385    #[test]
1386    fn merge_hooks_dedupes_command_found_in_non_first_inner_hook() {
1387        // The existing PreToolUse entry has our command at hooks[1], not
1388        // hooks[0] — a naive `entry_command` (hooks[0] only) comparison would
1389        // miss it and append a duplicate entry.
1390        let mut settings = serde_json::json!({
1391            "hooks": {
1392                "PreToolUse": [{
1393                    "matcher": "Write|Edit|Bash",
1394                    "hooks": [
1395                        { "type": "command", "command": "other" },
1396                        { "type": "command", "command": "tracevault stream --event pre-tool-use" }
1397                    ]
1398                }]
1399            }
1400        });
1401        let ours = tracevault_hooks();
1402        merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1403
1404        let pre_tool_use = settings["hooks"]["PreToolUse"].as_array().unwrap();
1405        assert_eq!(
1406            pre_tool_use.len(),
1407            1,
1408            "must not append a duplicate PreToolUse entry when our command is present at hooks[1]"
1409        );
1410    }
1411
1412    #[test]
1413    fn merge_hooks_errors_on_non_object_top_level() {
1414        let mut settings = serde_json::json!([1, 2, 3]);
1415        let ours = tracevault_hooks();
1416        let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
1417        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1418        assert!(err.to_string().contains("settings.json"));
1419    }
1420
1421    #[test]
1422    fn merge_hooks_errors_on_non_object_top_level_number() {
1423        let mut settings = serde_json::json!(42);
1424        let ours = tracevault_hooks();
1425        let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
1426        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1427    }
1428
1429    #[test]
1430    fn merge_hooks_errors_on_non_object_hooks() {
1431        let mut settings = serde_json::json!({ "hooks": "not-an-object" });
1432        let ours = tracevault_hooks();
1433        let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
1434        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1435        assert!(err.to_string().contains("hooks"));
1436    }
1437
1438    #[test]
1439    fn merge_hooks_errors_on_non_array_event_value() {
1440        let mut settings = serde_json::json!({
1441            "hooks": {
1442                "PreToolUse": "not-an-array"
1443            }
1444        });
1445        let ours = tracevault_hooks();
1446        let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
1447        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1448        assert!(err.to_string().contains("PreToolUse"));
1449    }
1450
1451    #[test]
1452    fn install_global_hooks_writes_settings_and_claude_md() {
1453        let tmp = tempfile::tempdir().unwrap();
1454        let claude_dir = tmp.path().join(".claude");
1455
1456        install_global_hooks(&claude_dir).unwrap();
1457
1458        let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
1459        let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
1460        for event in ["SessionStart", "UserPromptSubmit", "PreToolUse"] {
1461            assert!(settings["hooks"].get(event).is_some(), "missing {event}");
1462        }
1463
1464        let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
1465        assert!(claude_md.contains(GLOBAL_CLAUDE_MD_MARKER));
1466    }
1467
1468    #[test]
1469    fn install_global_hooks_is_idempotent() {
1470        let tmp = tempfile::tempdir().unwrap();
1471        let claude_dir = tmp.path().join(".claude");
1472
1473        install_global_hooks(&claude_dir).unwrap();
1474        install_global_hooks(&claude_dir).unwrap();
1475
1476        let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
1477        let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
1478        for event in [
1479            "PreToolUse",
1480            "PostToolUse",
1481            "Notification",
1482            "Stop",
1483            "SessionStart",
1484            "UserPromptSubmit",
1485        ] {
1486            let arr = settings["hooks"][event].as_array().unwrap();
1487            assert_eq!(arr.len(), 1, "event {event} should not be duplicated");
1488        }
1489
1490        let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
1491        let marker_count = claude_md.matches(GLOBAL_CLAUDE_MD_MARKER).count();
1492        assert_eq!(
1493            marker_count, 1,
1494            "CLAUDE.md marker should appear exactly once"
1495        );
1496    }
1497
1498    #[test]
1499    fn install_global_hooks_preserves_existing_claude_md_content() {
1500        let tmp = tempfile::tempdir().unwrap();
1501        let claude_dir = tmp.path().join(".claude");
1502        fs::create_dir_all(&claude_dir).unwrap();
1503        fs::write(
1504            claude_dir.join("CLAUDE.md"),
1505            "# My existing notes\nSome content.\n",
1506        )
1507        .unwrap();
1508
1509        install_global_hooks(&claude_dir).unwrap();
1510
1511        let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
1512        assert!(claude_md.contains("# My existing notes"));
1513        assert!(claude_md.contains(GLOBAL_CLAUDE_MD_MARKER));
1514    }
1515
1516    #[test]
1517    fn install_global_hooks_settings_write_is_atomic_no_tmp_leftover() {
1518        let tmp = tempfile::tempdir().unwrap();
1519        let claude_dir = tmp.path().join(".claude");
1520
1521        install_global_hooks(&claude_dir).unwrap();
1522
1523        let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
1524        let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
1525        assert!(settings["hooks"].get("SessionStart").is_some());
1526
1527        let leftover = fs::read_dir(&claude_dir)
1528            .unwrap()
1529            .filter_map(|e| e.ok())
1530            .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
1531        assert!(
1532            !leftover,
1533            "no settings.json.tmp should remain after install"
1534        );
1535    }
1536
1537    #[test]
1538    fn install_global_hooks_errors_on_non_object_settings_and_does_not_overwrite() {
1539        let tmp = tempfile::tempdir().unwrap();
1540        let claude_dir = tmp.path().join(".claude");
1541        fs::create_dir_all(&claude_dir).unwrap();
1542        let settings_path = claude_dir.join("settings.json");
1543        let original = "[1, 2, 3]";
1544        fs::write(&settings_path, original).unwrap();
1545
1546        let err = install_global_hooks(&claude_dir).unwrap_err();
1547        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1548
1549        // The original (malformed-for-our-purposes but validly-JSON) file
1550        // must be untouched, and no stray tmp file left behind.
1551        let after = fs::read_to_string(&settings_path).unwrap();
1552        assert_eq!(after, original);
1553        let leftover = fs::read_dir(&claude_dir)
1554            .unwrap()
1555            .filter_map(|e| e.ok())
1556            .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
1557        assert!(!leftover, "no tmp file should be left behind on error");
1558    }
1559
1560    #[test]
1561    fn install_global_hooks_errors_on_non_object_hooks_key_and_does_not_overwrite() {
1562        let tmp = tempfile::tempdir().unwrap();
1563        let claude_dir = tmp.path().join(".claude");
1564        fs::create_dir_all(&claude_dir).unwrap();
1565        let settings_path = claude_dir.join("settings.json");
1566        let original = r#"{"hooks": "oops"}"#;
1567        fs::write(&settings_path, original).unwrap();
1568
1569        let err = install_global_hooks(&claude_dir).unwrap_err();
1570        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1571
1572        let after = fs::read_to_string(&settings_path).unwrap();
1573        assert_eq!(after, original);
1574    }
1575
1576    #[test]
1577    fn install_global_hooks_errors_on_non_array_event_and_does_not_overwrite() {
1578        let tmp = tempfile::tempdir().unwrap();
1579        let claude_dir = tmp.path().join(".claude");
1580        fs::create_dir_all(&claude_dir).unwrap();
1581        let settings_path = claude_dir.join("settings.json");
1582        let original = r#"{"hooks": {"PreToolUse": "oops"}}"#;
1583        fs::write(&settings_path, original).unwrap();
1584
1585        let err = install_global_hooks(&claude_dir).unwrap_err();
1586        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1587
1588        let after = fs::read_to_string(&settings_path).unwrap();
1589        assert_eq!(after, original);
1590    }
1591
1592    #[test]
1593    fn safe_join_allows_direct_child_file() {
1594        let tmp = tempfile::tempdir().unwrap();
1595        let base = tmp.path();
1596        let result = safe_join(base, "settings.json").unwrap();
1597        assert_eq!(result.parent(), Some(base));
1598        assert_eq!(result.file_name().unwrap(), "settings.json");
1599    }
1600
1601    #[test]
1602    fn safe_join_rejects_path_traversal() {
1603        let tmp = tempfile::tempdir().unwrap();
1604        let base = tmp.path();
1605        let result = safe_join(base, "../evil");
1606        assert!(result.is_err());
1607        let err = result.unwrap_err();
1608        assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
1609        assert!(err.to_string().contains("refusing to access path outside"));
1610    }
1611
1612    #[test]
1613    fn safe_join_rejects_absolute_path() {
1614        let tmp = tempfile::tempdir().unwrap();
1615        let base = tmp.path();
1616        let result = safe_join(base, "/etc/passwd");
1617        // An absolute path joined to a base will replace the base,
1618        // so parent will not equal base.
1619        assert!(result.is_err());
1620    }
1621
1622    #[test]
1623    fn write_global_user_config_enables_and_creates_context() {
1624        let root = tempfile::tempdir().unwrap();
1625        let active = write_global_user_config_in(root.path(), None).unwrap();
1626        let cfg = crate::config::try_load_user_config_in(root.path())
1627            .unwrap()
1628            .unwrap();
1629        // Validate against the INJECTED root (resolve_in), not tv_config_root():
1630        // a first-run default enables at the `context.json` under `root`.
1631        assert_eq!(
1632            cfg.user_context.unwrap().resolve_in(root.path()),
1633            Some(crate::config::default_user_context_path_in(root.path()))
1634        );
1635        let ctx = crate::config::default_user_context_path_in(root.path());
1636        assert_eq!(active, Some(ctx.clone()));
1637        assert!(ctx.exists());
1638    }
1639
1640    #[test]
1641    fn write_global_user_config_can_disable() {
1642        let root = tempfile::tempdir().unwrap();
1643        let active = write_global_user_config_in(
1644            root.path(),
1645            Some(crate::config::UserContext::Toggle(false)),
1646        )
1647        .unwrap();
1648        let cfg = crate::config::try_load_user_config_in(root.path())
1649            .unwrap()
1650            .unwrap();
1651        assert!(matches!(
1652            cfg.user_context,
1653            Some(crate::config::UserContext::Toggle(false))
1654        ));
1655        assert_eq!(active, None, "disabled → no active context path");
1656        // A disabled layer must NOT seed a context file.
1657        assert!(
1658            !crate::config::default_user_context_path_in(root.path()).exists(),
1659            "disabled user context must not create a context.json"
1660        );
1661    }
1662
1663    #[test]
1664    fn write_global_user_config_custom_path_seeds_that_file_only() {
1665        let root = tempfile::tempdir().unwrap();
1666        let custom = root.path().join("custom-ctx.json");
1667        let active = write_global_user_config_in(
1668            root.path(),
1669            Some(crate::config::UserContext::Path(
1670                custom.to_string_lossy().into_owned(),
1671            )),
1672        )
1673        .unwrap();
1674        assert_eq!(active, Some(custom.clone()));
1675        assert!(custom.exists(), "the configured custom path must be seeded");
1676        assert!(
1677            !crate::config::default_user_context_path_in(root.path()).exists(),
1678            "the default context.json must NOT be created when a custom path is configured"
1679        );
1680    }
1681
1682    #[test]
1683    fn write_global_user_config_preserves_existing_on_rerun_without_flags() {
1684        let root = tempfile::tempdir().unwrap();
1685        let custom = root.path().join("custom-ctx.json");
1686        // First run pins a custom path.
1687        write_global_user_config_in(
1688            root.path(),
1689            Some(crate::config::UserContext::Path(
1690                custom.to_string_lossy().into_owned(),
1691            )),
1692        )
1693        .unwrap();
1694        // Re-run with NO flags must NOT reset it back to the default.
1695        let active = write_global_user_config_in(root.path(), None).unwrap();
1696        assert_eq!(
1697            active,
1698            Some(custom.clone()),
1699            "re-run without flags must preserve the custom path"
1700        );
1701        let cfg = crate::config::try_load_user_config_in(root.path())
1702            .unwrap()
1703            .unwrap();
1704        assert_eq!(cfg.user_context.unwrap().path_in(root.path()), custom);
1705    }
1706
1707    #[test]
1708    fn install_global_codex_hooks_writes_and_is_idempotent() {
1709        let tmp = tempfile::tempdir().unwrap();
1710        let codex_dir = tmp.path().join(".codex");
1711
1712        install_global_codex_hooks(&codex_dir).unwrap();
1713        install_global_codex_hooks(&codex_dir).unwrap();
1714
1715        let v: serde_json::Value =
1716            serde_json::from_str(&fs::read_to_string(codex_dir.join("hooks.json")).unwrap())
1717                .unwrap();
1718        for event in ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"] {
1719            let arr = v["hooks"][event].as_array().unwrap();
1720            assert_eq!(arr.len(), 1, "event {event} must not be duplicated");
1721        }
1722        assert!(v["hooks"].get("PreToolUse").is_none());
1723        // AGENTS.md carries the workspace-mode block exactly once across re-runs.
1724        let agents_md = fs::read_to_string(codex_dir.join("AGENTS.md")).unwrap();
1725        assert_eq!(
1726            agents_md.matches(GLOBAL_CLAUDE_MD_MARKER).count(),
1727            1,
1728            "AGENTS.md workspace-mode block must appear exactly once"
1729        );
1730        // No stray temp file left behind.
1731        let leftover = fs::read_dir(&codex_dir)
1732            .unwrap()
1733            .filter_map(|e| e.ok())
1734            .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
1735        assert!(!leftover);
1736    }
1737
1738    #[test]
1739    fn codex_hooks_has_expected_events_and_commands() {
1740        let h = codex_hooks();
1741        for event in ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"] {
1742            assert!(h.get(event).is_some(), "missing codex event {event}");
1743        }
1744        // No PreToolUse (intentionally dropped — PostToolUse + Stop capture the
1745        // rollout; a pre-tool hook would only double per-call streaming) and no
1746        // Notification event (Codex has none).
1747        assert!(h.get("PreToolUse").is_none());
1748        assert!(h.get("Notification").is_none());
1749        // Capture commands carry --agent codex; injection hooks do not need it.
1750        let cmd = |e: &str| h[e][0]["hooks"][0]["command"].as_str().unwrap().to_string();
1751        assert_eq!(
1752            cmd("PostToolUse"),
1753            "tracevault stream --event post-tool-use --agent codex"
1754        );
1755        assert_eq!(cmd("Stop"), "tracevault stream --event stop --agent codex");
1756        assert_eq!(cmd("SessionStart"), "tracevault session-start");
1757        assert_eq!(cmd("UserPromptSubmit"), "tracevault user-prompt");
1758        // Matchers are "" (all tools) — Codex edits arrive via the transcript.
1759        assert_eq!(h["PostToolUse"][0]["matcher"].as_str().unwrap(), "");
1760    }
1761
1762    #[test]
1763    fn install_codex_hooks_writes_hooks_json_and_is_idempotent() {
1764        let tmp = tempfile::tempdir().unwrap();
1765        install_codex_hooks(tmp.path()).unwrap();
1766        install_codex_hooks(tmp.path()).unwrap();
1767
1768        let content = fs::read_to_string(tmp.path().join(".codex").join("hooks.json")).unwrap();
1769        let v: serde_json::Value = serde_json::from_str(&content).unwrap();
1770        for event in ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"] {
1771            let arr = v["hooks"][event].as_array().unwrap();
1772            assert_eq!(
1773                arr.len(),
1774                1,
1775                "event {event} must not be duplicated on re-run"
1776            );
1777        }
1778        assert!(v["hooks"].get("PreToolUse").is_none());
1779    }
1780
1781    #[test]
1782    fn install_codex_hooks_preserves_existing_user_hook() {
1783        let tmp = tempfile::tempdir().unwrap();
1784        let codex_dir = tmp.path().join(".codex");
1785        fs::create_dir_all(&codex_dir).unwrap();
1786        // Seed a user hook under an event we install (PostToolUse) plus one under
1787        // an event we DON'T (PreToolUse) — both must survive the merge.
1788        fs::write(
1789            codex_dir.join("hooks.json"),
1790            r#"{"hooks":{"PostToolUse":[{"matcher":"","hooks":[{"type":"command","command":"my-own"}]}],"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"user-pretool"}]}]}}"#,
1791        )
1792        .unwrap();
1793
1794        install_codex_hooks(tmp.path()).unwrap();
1795
1796        let v: serde_json::Value =
1797            serde_json::from_str(&fs::read_to_string(codex_dir.join("hooks.json")).unwrap())
1798                .unwrap();
1799        // Our PostToolUse command is merged in alongside the user's own.
1800        let post_cmds: Vec<&str> = v["hooks"]["PostToolUse"]
1801            .as_array()
1802            .unwrap()
1803            .iter()
1804            .map(|e| e["hooks"][0]["command"].as_str().unwrap())
1805            .collect();
1806        assert!(
1807            post_cmds.contains(&"my-own"),
1808            "user PostToolUse hook preserved"
1809        );
1810        assert!(post_cmds.contains(&"tracevault stream --event post-tool-use --agent codex"));
1811        // The user's PreToolUse hook is left untouched (we install no PreToolUse).
1812        let pre_cmds: Vec<&str> = v["hooks"]["PreToolUse"]
1813            .as_array()
1814            .unwrap()
1815            .iter()
1816            .map(|e| e["hooks"][0]["command"].as_str().unwrap())
1817            .collect();
1818        assert_eq!(pre_cmds, vec!["user-pretool"], "unmanaged event untouched");
1819    }
1820
1821    #[test]
1822    fn validate_init_flags_rejects_claude_settings_with_codex() {
1823        assert!(validate_init_flags(crate::agent::Agent::Codex, true).is_err());
1824    }
1825
1826    #[test]
1827    fn validate_init_flags_allows_codex_without_claude_settings() {
1828        assert!(validate_init_flags(crate::agent::Agent::Codex, false).is_ok());
1829    }
1830
1831    #[test]
1832    fn validate_init_flags_allows_claude_with_claude_settings() {
1833        assert!(validate_init_flags(crate::agent::Agent::ClaudeCode, true).is_ok());
1834    }
1835
1836    #[test]
1837    fn merge_hooks_into_file_rejects_parent_dir() {
1838        let tmp = tempfile::tempdir().unwrap();
1839        let bad = tmp.path().join("..").join("hooks.json");
1840        let err = merge_hooks_into_file(&bad, &codex_hooks()).unwrap_err();
1841        assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
1842    }
1843
1844    #[test]
1845    fn append_workspace_md_rejects_parent_dir() {
1846        let tmp = tempfile::tempdir().unwrap();
1847        let bad = tmp.path().join("..").join("AGENTS.md");
1848        let err = append_workspace_md(&bad).unwrap_err();
1849        assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
1850    }
1851
1852    #[tokio::test]
1853    async fn init_in_directory_codex_installs_codex_hooks_and_gitignores() {
1854        let tmp = tempfile::tempdir().unwrap();
1855        let root = tmp.path();
1856        crate::test_helpers::init_git_repo(root);
1857
1858        let entry = init_in_directory(
1859            root,
1860            None,
1861            None,
1862            false,
1863            crate::config::UserContext::Toggle(false),
1864            crate::agent::Agent::Codex,
1865        )
1866        .await
1867        .unwrap();
1868
1869        // Codex hooks file written; Claude settings NOT created.
1870        assert!(root.join(".codex").join("hooks.json").exists());
1871        assert!(!root.join(".claude").join("settings.json").exists());
1872        assert_eq!(entry, ".codex/hooks.json");
1873
1874        // .gitignore covers the codex hooks file.
1875        let gi = fs::read_to_string(root.join(".gitignore")).unwrap();
1876        assert!(gi.contains(".codex/hooks.json"));
1877        assert!(gi.contains(".tracevault/"));
1878    }
1879
1880    /// A successful `POST /api/v1/repos` during `init` must persist the
1881    /// returned `repo_id` into `.tracevault/config.toml` — this is the
1882    /// "everything worked" happy path of the registration step at the end of
1883    /// `init_in_directory`, previously untested.
1884    ///
1885    /// `XDG_CONFIG_HOME` is redirected so this doesn't read/write the
1886    /// developer's real `~/.config/tracevault/credentials.json`;
1887    /// `TRACEVAULT_API_KEY` is pinned directly since `resolve_credentials`
1888    /// checks it before the credentials file. `_env_lock` serializes this
1889    /// against other tests in the crate that mutate the same env vars
1890    /// (see `test_helpers::lock_env_mutation`).
1891    #[tokio::test]
1892    async fn init_in_directory_registers_repo_and_persists_repo_id() {
1893        let _env_lock = crate::test_helpers::lock_env_mutation().await;
1894        let tmp = tempfile::tempdir().unwrap();
1895        let root = tmp.path();
1896        crate::test_helpers::init_git_repo(root);
1897        add_origin_remote(root, "git@github.com:org/repo.git");
1898
1899        let repo_id = "11111111-1111-4111-8111-111111111111";
1900        let body = format!(r#"{{"repo_id":"{repo_id}"}}"#);
1901        // The remote is unknown (domain 404), so init registers; the resolve
1902        // after registering may fail, it is display-only.
1903        let (base, _rx) = crate::test_helpers::spawn_seq(vec![
1904            http_response("404 Not Found", NO_REMOTE),
1905            http_response("200 OK", &body),
1906        ]);
1907
1908        let mut _guard = crate::test_helpers::EnvVarGuard::new();
1909        _guard.set("XDG_CONFIG_HOME", tmp.path());
1910        _guard.set("TRACEVAULT_API_KEY", "tok");
1911        _guard.remove("TRACEVAULT_SERVER_URL");
1912
1913        init_in_directory(
1914            root,
1915            Some(&base),
1916            None,
1917            true,
1918            crate::config::UserContext::Toggle(false),
1919            crate::agent::Agent::Codex,
1920        )
1921        .await
1922        .unwrap();
1923
1924        let cfg = crate::config::TracevaultConfig::load(root).expect("config.toml written by init");
1925        assert_eq!(
1926            cfg.repo_id,
1927            Some(repo_id.to_string()),
1928            "successful registration must persist repo_id to config.toml"
1929        );
1930    }
1931
1932    /// A 403 on `POST /api/v1/repos` must be a non-fatal warning (`init`
1933    /// still succeeds and installs hooks) and must NOT persist a `repo_id` —
1934    /// there's nothing valid to persist. The exact wording of the warning is
1935    /// covered by `registration_failure_message_flags_403_as_not_authorized`
1936    /// below.
1937    #[tokio::test]
1938    async fn init_in_directory_registration_403_does_not_persist_repo_id() {
1939        let _env_lock = crate::test_helpers::lock_env_mutation().await;
1940        let tmp = tempfile::tempdir().unwrap();
1941        let root = tmp.path();
1942        crate::test_helpers::init_git_repo(root);
1943        add_origin_remote(root, "git@github.com:org/repo.git");
1944
1945        let (base, _rx) = crate::test_helpers::spawn_seq(vec![
1946            http_response("404 Not Found", NO_REMOTE),
1947            http_response("403 Forbidden", ""),
1948        ]);
1949
1950        let mut _guard = crate::test_helpers::EnvVarGuard::new();
1951        _guard.set("XDG_CONFIG_HOME", tmp.path());
1952        _guard.set("TRACEVAULT_API_KEY", "tok");
1953        _guard.remove("TRACEVAULT_SERVER_URL");
1954
1955        let entry = init_in_directory(
1956            root,
1957            Some(&base),
1958            None,
1959            true,
1960            crate::config::UserContext::Toggle(false),
1961            crate::agent::Agent::Codex,
1962        )
1963        .await
1964        .expect("a registration failure (403) must not abort init itself");
1965        assert_eq!(entry, ".codex/hooks.json");
1966
1967        let cfg = crate::config::TracevaultConfig::load(root).expect("config.toml written by init");
1968        assert!(
1969            cfg.repo_id.is_none(),
1970            "a 403 registration failure must not persist a repo_id"
1971        );
1972    }
1973
1974    /// The actual error shape `ApiClient::register_repo` produces for a 403
1975    /// response (via the same mock-server harness) must be recognized by
1976    /// `registration_failure_message` as a not-authorized case, not a
1977    /// generic server fault.
1978    #[tokio::test]
1979    async fn registration_failure_message_flags_403_as_not_authorized() {
1980        let base = spawn_once(http_response("403 Forbidden", ""));
1981        let client = ApiClient::new(&base, Some("tok"));
1982        let err = client
1983            .register_repo(crate::api_client::RegisterRepoRequest {
1984                repo_name: "repo".into(),
1985                github_url: Some("git@github.com:org/repo.git".into()),
1986            })
1987            .await
1988            .unwrap_err();
1989        let msg = registration_failure_message(err.as_ref());
1990        assert!(
1991            msg.contains("not authorized"),
1992            "403 registration failure must surface a not-authorized message; got: {msg}"
1993        );
1994    }
1995
1996    /// A non-403 registration failure (e.g. a 500) keeps the generic
1997    /// "could not register" wording, distinguishing it from the 403 case.
1998    #[tokio::test]
1999    async fn registration_failure_message_generic_for_non_403() {
2000        let base = spawn_once(http_response("500 Internal Server Error", ""));
2001        let client = ApiClient::new(&base, Some("tok"));
2002        let err = client
2003            .register_repo(crate::api_client::RegisterRepoRequest {
2004                repo_name: "repo".into(),
2005                github_url: Some("git@github.com:org/repo.git".into()),
2006            })
2007            .await
2008            .unwrap_err();
2009        let msg = registration_failure_message(err.as_ref());
2010        assert!(
2011            msg.contains("could not register repo on server"),
2012            "got: {msg}"
2013        );
2014        assert!(!msg.contains("not authorized"), "got: {msg}");
2015    }
2016
2017    /// A 500 whose BODY happens to contain the digits "403" (e.g. a proxy
2018    /// error page quoting an unrelated status) must not be misclassified as
2019    /// a 403-not-authorized failure — the match must key on the actual
2020    /// status prefix, not a bare substring search over the whole message.
2021    #[tokio::test]
2022    async fn registration_failure_message_does_not_misclassify_403_in_body() {
2023        let base = spawn_once(http_response(
2024            "500 Internal Server Error",
2025            "upstream error 403 from proxy",
2026        ));
2027        let client = ApiClient::new(&base, Some("tok"));
2028        let err = client
2029            .register_repo(crate::api_client::RegisterRepoRequest {
2030                repo_name: "repo".into(),
2031                github_url: Some("git@github.com:org/repo.git".into()),
2032            })
2033            .await
2034            .unwrap_err();
2035        let msg = registration_failure_message(err.as_ref());
2036        assert!(
2037            !msg.contains("not authorized"),
2038            "a 403 substring in the body must not trigger the not-authorized message; got: {msg}"
2039        );
2040        assert!(
2041            msg.contains("could not register repo on server"),
2042            "got: {msg}"
2043        );
2044    }
2045
2046    /// A 404 (the registration route doesn't exist on this server) surfaces a
2047    /// CLI/server version-mismatch hint rather than the generic wording, so
2048    /// the user has an actionable next step instead of an opaque status code.
2049    #[tokio::test]
2050    async fn registration_failure_message_flags_404_as_version_mismatch() {
2051        let base = spawn_once(http_response("404 Not Found", ""));
2052        let client = ApiClient::new(&base, Some("tok"));
2053        let err = client
2054            .register_repo(crate::api_client::RegisterRepoRequest {
2055                repo_name: "repo".into(),
2056                github_url: Some("git@github.com:org/repo.git".into()),
2057            })
2058            .await
2059            .unwrap_err();
2060        let msg = registration_failure_message(err.as_ref());
2061        assert!(
2062            msg.to_lowercase().contains("version mismatch"),
2063            "a 404 registration failure should hint at a version mismatch; got: {msg}"
2064        );
2065    }
2066
2067    // ── VIS-1018: init never registers a second repo for a known remote ───────
2068
2069    /// The server's domain-404 body for an untracked remote.
2070    const NO_REMOTE: &str = r#"{"error":"No remote for that URL"}"#;
2071    const REMOTE_ID: &str = "2280a1c9-0000-4000-8000-000000000003";
2072    const CANONICAL: &str = "44000761-0000-4000-8000-000000000001";
2073    const STRAY: &str = "7995d35d-0000-4000-8000-000000000002";
2074
2075    fn resolve_remote_ok() -> String {
2076        http_response(
2077            "200 OK",
2078            &format!(
2079                r#"{{"remote_id":"{REMOTE_ID}","name":"tracing","normalized_url":"github.com/org/repo","clone_status":"ready"}}"#
2080            ),
2081        )
2082    }
2083
2084    fn remote_detail(repos: &[(&str, &str)]) -> String {
2085        let repos: Vec<String> = repos
2086            .iter()
2087            .map(|(id, name)| format!(r#"{{"id":"{id}","name":"{name}"}}"#))
2088            .collect();
2089        http_response(
2090            "200 OK",
2091            &format!(
2092                r#"{{"name":"tracing","normalized_url":"github.com/org/repo","clone_status":"ready","repos":[{}]}}"#,
2093                repos.join(",")
2094            ),
2095        )
2096    }
2097
2098    /// Run `init` against `responses` and return the persisted repo_id and
2099    /// every request the server saw.
2100    async fn init_against(root: &Path, responses: Vec<String>) -> (Option<String>, Vec<String>) {
2101        let (base, rx) = crate::test_helpers::spawn_seq(responses);
2102        let mut _guard = crate::test_helpers::EnvVarGuard::new();
2103        _guard.set("XDG_CONFIG_HOME", root);
2104        _guard.set("TRACEVAULT_API_KEY", "tok");
2105        _guard.remove("TRACEVAULT_SERVER_URL");
2106
2107        init_in_directory(
2108            root,
2109            Some(&base),
2110            None,
2111            true,
2112            crate::config::UserContext::Toggle(false),
2113            crate::agent::Agent::Codex,
2114        )
2115        .await
2116        .expect("init succeeds");
2117
2118        let cfg = crate::config::TracevaultConfig::load(root).expect("config.toml written by init");
2119        (cfg.repo_id, rx.try_iter().collect())
2120    }
2121
2122    fn registered(requests: &[String]) -> bool {
2123        requests.iter().any(|r| r.starts_with("POST /api/v1/repos"))
2124    }
2125
2126    /// The prod incident: the checkout's directory is not named like the
2127    /// remote's existing repo. init binds that repo, and registers nothing.
2128    #[tokio::test]
2129    async fn init_binds_the_existing_repo_of_a_known_remote() {
2130        let _env_lock = crate::test_helpers::lock_env_mutation().await;
2131        let tmp = tempfile::tempdir().unwrap();
2132        crate::test_helpers::init_git_repo(tmp.path());
2133        add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
2134
2135        let (repo_id, requests) = init_against(
2136            tmp.path(),
2137            vec![
2138                resolve_remote_ok(),
2139                remote_detail(&[(CANONICAL, "tracevault")]),
2140            ],
2141        )
2142        .await;
2143
2144        assert_eq!(repo_id.as_deref(), Some(CANONICAL));
2145        assert!(!registered(&requests), "requests: {requests:?}");
2146    }
2147
2148    /// Several records and one is named like this checkout: that one — the
2149    /// record registering would have upserted anyway.
2150    #[tokio::test]
2151    async fn init_binds_the_record_named_like_the_checkout() {
2152        let _env_lock = crate::test_helpers::lock_env_mutation().await;
2153        let tmp = tempfile::tempdir().unwrap();
2154        crate::test_helpers::init_git_repo(tmp.path());
2155        add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
2156        let dir_name = crate::resolution::git_repo_name(tmp.path());
2157
2158        let (repo_id, requests) = init_against(
2159            tmp.path(),
2160            vec![
2161                resolve_remote_ok(),
2162                remote_detail(&[(CANONICAL, "tracevault"), (STRAY, &dir_name)]),
2163            ],
2164        )
2165        .await;
2166
2167        assert_eq!(repo_id.as_deref(), Some(STRAY));
2168        assert!(!registered(&requests));
2169    }
2170
2171    /// Re-running init keeps the repo the previous config.toml bound.
2172    #[tokio::test]
2173    async fn init_rerun_keeps_the_previously_bound_repo() {
2174        let _env_lock = crate::test_helpers::lock_env_mutation().await;
2175        let tmp = tempfile::tempdir().unwrap();
2176        crate::test_helpers::init_git_repo(tmp.path());
2177        add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
2178        fs::create_dir_all(tmp.path().join(".tracevault")).unwrap();
2179        fs::write(
2180            tmp.path().join(".tracevault/config.toml"),
2181            format!("repo_id = \"{STRAY}\"\n"),
2182        )
2183        .unwrap();
2184
2185        let (repo_id, requests) = init_against(
2186            tmp.path(),
2187            vec![
2188                resolve_remote_ok(),
2189                remote_detail(&[(CANONICAL, "tracevault"), (STRAY, "tracing-old")]),
2190            ],
2191        )
2192        .await;
2193
2194        assert_eq!(repo_id.as_deref(), Some(STRAY));
2195        assert!(!registered(&requests));
2196    }
2197
2198    /// Several records, nothing says which: no guess, no new record.
2199    #[tokio::test]
2200    async fn init_registers_nothing_when_the_codebase_is_ambiguous() {
2201        let _env_lock = crate::test_helpers::lock_env_mutation().await;
2202        let tmp = tempfile::tempdir().unwrap();
2203        crate::test_helpers::init_git_repo(tmp.path());
2204        add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
2205
2206        let (repo_id, requests) = init_against(
2207            tmp.path(),
2208            vec![
2209                resolve_remote_ok(),
2210                remote_detail(&[(CANONICAL, "tracevault"), (STRAY, "tracing-old")]),
2211            ],
2212        )
2213        .await;
2214
2215        assert_eq!(repo_id, None);
2216        assert!(!registered(&requests));
2217    }
2218
2219    /// A known codebase with no live repo (e.g. its last one was tombstoned)
2220    /// still registers.
2221    #[tokio::test]
2222    async fn init_registers_for_a_codebase_without_live_repos() {
2223        let _env_lock = crate::test_helpers::lock_env_mutation().await;
2224        let tmp = tempfile::tempdir().unwrap();
2225        crate::test_helpers::init_git_repo(tmp.path());
2226        add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
2227
2228        let (repo_id, requests) = init_against(
2229            tmp.path(),
2230            vec![
2231                resolve_remote_ok(),
2232                remote_detail(&[]),
2233                http_response("201 Created", &format!(r#"{{"repo_id":"{CANONICAL}"}}"#)),
2234            ],
2235        )
2236        .await;
2237
2238        assert_eq!(repo_id.as_deref(), Some(CANONICAL));
2239        assert!(registered(&requests));
2240    }
2241
2242    /// If the server cannot say what it has, init does not register blind.
2243    #[tokio::test]
2244    async fn init_does_not_register_when_the_remote_check_fails() {
2245        let _env_lock = crate::test_helpers::lock_env_mutation().await;
2246        let tmp = tempfile::tempdir().unwrap();
2247        crate::test_helpers::init_git_repo(tmp.path());
2248        add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
2249
2250        let (repo_id, requests) = init_against(
2251            tmp.path(),
2252            vec![http_response("500 Internal Server Error", "{}")],
2253        )
2254        .await;
2255
2256        assert_eq!(repo_id, None);
2257        assert!(!registered(&requests));
2258    }
2259}