Skip to main content

tracevault_cli/
cli.rs

1//! The `tracevault` command surface and its dispatch, shared by the
2//! `tracevault` binary and by `visdom` (which mounts it under `visdom trace`).
3
4use crate::program::{CLI, TOP};
5use std::env;
6
7use crate::commands::project::ProjectCmd;
8use crate::commands::repo::RepoCmd;
9use crate::{commands, config, install_state};
10
11#[derive(clap::Subcommand)]
12pub enum Command {
13    /// Initialize Visdom in current repository
14    Init(InitArgs),
15    /// Claude Code telemetry (cost over OpenTelemetry, on by default): `on`,
16    /// `off` (remembered across upgrades) or `status`.
17    Telemetry {
18        #[arg(value_enum)]
19        action: TelemetryAction,
20    },
21    /// Print the Authorization header for Claude Code's OpenTelemetry export,
22    /// as JSON, from the Visdom credential store. Installed as
23    /// `otelHeadersHelper` by `init --claude-telemetry` — not
24    /// intended to be run manually.
25    #[command(name = "otel-headers", hide = true)]
26    OtelHeaders {
27        /// The server telemetry is exported to: the credential must be for it.
28        #[arg(long)]
29        server_url: Option<String>,
30    },
31    /// Show current session status
32    Status {
33        /// Session to inspect for the workspace binding; defaults to
34        /// the session id the session-start hook exported (in Amp: $AMP_CURRENT_THREAD_ID), else the
35        /// most recent session that has a workspace binding.
36        #[arg(long)]
37        session_id: Option<String>,
38    },
39    /// Stream hook events to server in real-time.
40    /// Installed into .claude/settings.json by `init` and invoked
41    /// by Claude Code on every tool event — not intended to be run manually.
42    #[command(hide = true)]
43    Stream {
44        #[arg(long)]
45        event: String,
46        /// Which agent this hook belongs to (sets the request's tool + protocol
47        /// version). Defaults to claude-code so existing installs are unchanged.
48        #[arg(long, value_enum, default_value = "claude-code")]
49        agent: crate::agent::Agent,
50    },
51    /// SessionStart hook: exports the session id, binds an unbound session to
52    /// the repo of its checkout's origin remote, and injects the bound repo's
53    /// policies as additionalContext. Installed by `init` (per-repo
54    /// or --global) into the Claude Code settings or the Codex hooks.json —
55    /// not intended to be run manually.
56    #[command(name = "session-start", hide = true)]
57    SessionStart,
58    /// UserPromptSubmit hook: reinforces the bound repo's policies as
59    /// additionalContext when the effective repo has changed since the last
60    /// injection. Installed by `init` (per-repo or --global) into
61    /// the Claude Code settings or the Codex hooks.json — not intended to be
62    /// run manually.
63    #[command(name = "user-prompt", hide = true)]
64    UserPrompt,
65    /// Check session policies before pushing
66    Check,
67    /// Sync repo remote URL with the Visdom server
68    Sync,
69    /// Show local session statistics
70    Stats,
71    /// Log in to a Visdom server
72    Login(LoginArgs),
73    /// Log out from the Visdom server
74    Logout,
75    /// Push commit metadata to the server.
76    /// Installed into .git/hooks/post-commit by `init` and
77    /// invoked by git after every commit — not intended to be run manually.
78    #[command(hide = true)]
79    CommitPush,
80    /// Force-sync all pending events to server
81    Flush,
82    /// Verify commits are registered and sealed on the Visdom server
83    Verify {
84        /// Comma-separated list of commit SHAs
85        #[arg(long)]
86        commits: Option<String>,
87        /// Git commit range (e.g. abc1234..def5678)
88        #[arg(long)]
89        range: Option<String>,
90    },
91    /// Open (or re-open) a verification phase for the current session.
92    ///
93    /// A verification phase declares that the agent has finished making changes
94    /// and is now running quality checks. Only tool calls made after this point
95    /// are evaluated by verification_phase-scoped policies. Calling this again
96    /// resets the phase, discarding earlier verification events.
97    ///
98    /// In single-agent setups the current session is detected automatically.
99    /// In multi-agent setups, pass --session-id to target the correct session.
100    #[command(name = "verify-start")]
101    VerifyStart {
102        /// Explicit session ID to open the window for. When omitted, the
103        /// invoking session (the session id the session-start hook exported; in Amp: $AMP_CURRENT_THREAD_ID)
104        /// is used if it has events in this worktree, else the session is
105        /// detected by worktree.
106        #[arg(long)]
107        session_id: Option<String>,
108    },
109    /// Print agent-readable instructions derived from active policies.
110    ///
111    /// Fetches the rendered instructions from the server for the current repo
112    /// and prints them to stdout. Designed to be invoked from CLAUDE.md (or
113    /// equivalent) at session start so the agent's behaviour matches the
114    /// policies configured on the Visdom server.
115    #[command(name = "agent-policies")]
116    AgentPolicies,
117    /// LLM proxy commands.
118    Proxy {
119        #[command(subcommand)]
120        cmd: ProxyCmd,
121    },
122    /// Manage the active context (flow ID, labels, params) attached to events.
123    Context {
124        #[command(subcommand)]
125        action: ContextAction,
126    },
127    /// Bind/inspect the repo a detached session is working on (workspace mode).
128    Repo {
129        #[command(subcommand)]
130        cmd: RepoCmd,
131    },
132    /// Bind/inspect the project a detached session is attributed to.
133    Project {
134        #[command(subcommand)]
135        cmd: ProjectCmd,
136    },
137}
138
139/// Arguments of `init`.
140#[derive(clap::Args, Clone)]
141pub struct InitArgs {
142    /// Visdom server URL for repo registration
143    #[arg(long)]
144    pub server_url: Option<String>,
145    /// Where to install Claude Code hooks: `shared` (.claude/settings.json,
146    /// typically committed) or `local` (.claude/settings.local.json,
147    /// personal/git-ignored). When omitted, prompts interactively if stdin
148    /// is a TTY, otherwise defaults to `shared`.
149    #[arg(long, value_enum)]
150    pub claude_settings: Option<commands::init::ClaudeSettingsTarget>,
151    /// Skip updating .gitignore. Use this when your project manages
152    /// .gitignore separately or you want to commit the Claude settings files.
153    #[arg(long)]
154    pub no_gitignore: bool,
155    /// Disable the cross-repo user-level context for this project. Also
156    /// applies to `--global`, where it disables the user-level context
157    /// instead of the per-repo one.
158    #[arg(long)]
159    pub no_user_context: bool,
160    /// Enable the user-level context and read it from this explicit path
161    /// (conflicts with --no-user-context). Also applies to `--global`,
162    /// where it sets the path the user-level context is read from.
163    #[arg(long, conflicts_with = "no_user_context")]
164    pub user_context: Option<String>,
165    /// Install Visdom once for ALL sessions of the chosen --agent on
166    /// this machine, instead of initializing the current repo: Claude Code
167    /// hooks into ~/.claude/ (settings.json + CLAUDE.md), Codex hooks into
168    /// ~/.codex/ (hooks.json + AGENTS.md), the GSD extension via
169    /// `gsd install` (global), the OpenCode plugin into the user config
170    /// dir's opencode/plugins/, or the Amp plugin into
171    /// $XDG_CONFIG_HOME/amp/plugins/ (~/.config/amp/plugins/ when unset).
172    /// Does not require git. Also writes a
173    /// user-level context config (honoring --no-user-context /
174    /// --user-context). Conflicts with the per-repo-only flags
175    /// --server-url, --claude-settings and --no-gitignore.
176    #[arg(
177        long,
178        conflicts_with_all = ["server_url", "claude_settings", "no_gitignore"]
179    )]
180    pub global: bool,
181    /// Which agent to install hooks for. The default installs Claude Code
182    /// hooks (.claude/settings.json or settings.local.json); `codex` writes
183    /// .codex/hooks.json; `gsd` (alias `gsd2`) registers the GSD extension
184    /// with `gsd install -l`; `opencode` writes
185    /// a plugin under .opencode/plugins/; `amp` writes
186    /// a plugin under .amp/plugins/. With --global, the user-level
187    /// equivalents instead.
188    #[arg(long, value_enum, default_value = "claude-code")]
189    pub agent: crate::agent::Agent,
190    /// Export Claude Code's own per-request cost to Visdom over
191    /// OpenTelemetry (the default): writes the OTel log exporter settings
192    /// and an `otelHeadersHelper` (the `otel-headers` command) into the
193    /// USER-level ~/.claude/settings.json, per-repo or with --global. An
194    /// existing exporter setup is left untouched (collector instructions
195    /// are printed instead). Without either flag, an interactive init asks
196    /// (default yes), and a non-interactive one enables it unless you
197    /// opted out before.
198    #[arg(long, conflicts_with = "no_claude_telemetry")]
199    pub claude_telemetry: bool,
200    /// Opt out of Claude Code telemetry: removes Visdom's entries from
201    /// ~/.claude/settings.json and records the choice, so neither a later
202    /// `init` nor a CLI upgrade turns it back on.
203    #[arg(long)]
204    pub no_claude_telemetry: bool,
205    /// Bind this directory to one project, for every session started
206    /// under it (an umbrella folder of checkouts, for example): resolves
207    /// --project once on the server and writes its id to
208    /// .visdom/tracing.toml here (created if missing). Works outside
209    /// git; installs no hooks (use --global for those) and binds no repo.
210    #[arg(
211        long,
212        requires = "project",
213        conflicts_with_all = [
214            "global",
215            "claude_settings",
216            "no_gitignore",
217            "no_user_context",
218            "user_context",
219            "claude_telemetry",
220            "no_claude_telemetry",
221        ]
222    )]
223    pub workspace: bool,
224    /// The project name for --workspace.
225    #[arg(long, requires = "workspace")]
226    pub project: Option<String>,
227}
228
229/// Arguments of `login`.
230#[derive(clap::Args)]
231pub struct LoginArgs {
232    /// Visdom server URL
233    #[arg(long)]
234    pub server_url: String,
235    /// Do not try to open a browser; just print the URL.
236    /// Useful inside Docker / CI / SSH without X11.
237    #[arg(long)]
238    pub no_browser: bool,
239}
240
241/// Sub-actions for `context`.
242#[derive(clap::Subcommand)]
243pub enum ContextAction {
244    /// Set the context, replacing any previously saved context entirely.
245    ///
246    /// In a linked worktree the per-worktree file is written by default.
247    /// In the primary checkout the global file is written.
248    /// Use --global to force the global file from anywhere.
249    ///
250    /// Omitted dimensions are left empty. This clears labels and params that
251    /// are not re-specified.
252    Set {
253        /// Active flow ID to associate with events
254        #[arg(long)]
255        flow: Option<String>,
256        /// Labels to attach (repeatable; comma-separated values accepted)
257        #[arg(long)]
258        label: Vec<String>,
259        /// Params to attach, in key=value form (repeatable)
260        #[arg(long)]
261        param: Vec<String>,
262        /// Write to the global context file regardless of worktree scope
263        #[arg(long)]
264        global: bool,
265        /// Write to the resolved user-context file instead (wins over --global)
266        #[arg(long)]
267        user: bool,
268    },
269    /// Update the existing context, merging changes in.
270    ///
271    /// In a linked worktree the per-worktree file is updated by default.
272    /// Use --global to force the global file from anywhere.
273    ///
274    /// Sets --flow if provided; unions --label with existing; inserts/overwrites
275    /// --param keys; removes --remove-label / --remove-param entries.
276    Update {
277        /// New flow ID (replaces current flow if provided)
278        #[arg(long)]
279        flow: Option<String>,
280        /// Labels to add (repeatable; comma-separated values accepted)
281        #[arg(long)]
282        label: Vec<String>,
283        /// Params to add or overwrite, in key=value form (repeatable)
284        #[arg(long)]
285        param: Vec<String>,
286        /// Labels to remove (repeatable; comma-separated values accepted)
287        #[arg(long = "remove-label")]
288        remove_label: Vec<String>,
289        /// Param keys to remove (repeatable)
290        #[arg(long = "remove-param")]
291        remove_param: Vec<String>,
292        /// Write to the global context file regardless of worktree scope
293        #[arg(long)]
294        global: bool,
295        /// Write to the resolved user-context file instead (wins over --global)
296        #[arg(long)]
297        user: bool,
298    },
299    /// Show the current context, layer by layer (pretty JSON).
300    ///
301    /// Prints up to four sections: User (always; its header says whether the
302    /// user layer is enabled and which file it reads), Global (repo-wide),
303    /// This worktree (linked only), and Effective (the merged result that the
304    /// hook stamps, each value annotated with the layer it came from).
305    Show,
306    /// Clear all context (flow, labels, params).
307    ///
308    /// In a linked worktree the per-worktree file is cleared by default.
309    /// Use --global to force clearing the global file from anywhere.
310    Clear {
311        /// Clear the global context file regardless of worktree scope
312        #[arg(long)]
313        global: bool,
314        /// Clear the resolved user-context file instead (wins over --global)
315        #[arg(long)]
316        user: bool,
317    },
318    /// Enable/disable or point the project's user-level context source.
319    ///
320    /// The mode flags are mutually exclusive: at most one may be given.
321    #[command(group(clap::ArgGroup::new("source_mode").multiple(false)))]
322    Source {
323        /// Enable the user context at the default path
324        #[arg(long, group = "source_mode")]
325        enable: bool,
326        /// Disable the user context
327        #[arg(long, group = "source_mode")]
328        disable: bool,
329        /// Enable and read the user context from this explicit path
330        #[arg(long, group = "source_mode")]
331        path: Option<String>,
332        /// Enable and clear any explicit path back to the default location
333        #[arg(long, group = "source_mode")]
334        default: bool,
335    },
336}
337
338#[derive(clap::Subcommand)]
339pub enum ProxyCmd {
340    /// Print the proxy URL and setup instructions for AI tools (Claude Code,
341    /// GSD2, Cursor, Codex CLI, etc.).
342    Info,
343}
344
345/// Write the user-level context config during a `--global` init and print the
346/// standard summary. Every agent's `--global` arm ends with this identical
347/// bootstrap, so it lives in one place. Exits the process on a fatal flag error,
348/// mirroring the per-arm behavior it replaces.
349fn finish_global_user_context(no_user_context: bool, user_context: Option<String>) {
350    let requested = match config::UserContext::from_init_flags(no_user_context, user_context) {
351        Ok(r) => r,
352        Err(e) => {
353            eprintln!("Error: {e}");
354            std::process::exit(1);
355        }
356    };
357    match commands::init::write_global_user_config_in(&config::tv_config_root(), requested) {
358        Ok(active) => {
359            println!(
360                "User-level context config: {}",
361                config::user_config_path().display()
362            );
363            match active {
364                Some(ctx) => println!("User-level context file: {}", ctx.display()),
365                None => println!("User-level context is disabled (`--no-user-context`)."),
366            }
367            println!(
368                "Edit it with `{CLI} context set --user …`; disable with \
369                 `{TOP} init --global --no-user-context`."
370            );
371        }
372        Err(e) => eprintln!("Warning: could not write user-level context config: {e}"),
373    }
374}
375
376#[derive(Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
377pub enum TelemetryAction {
378    On,
379    Off,
380    Status,
381}
382
383/// What the user asked for Claude Code telemetry.
384#[derive(Clone, Copy, PartialEq, Eq)]
385enum TelemetryChoice {
386    /// `--claude-telemetry` / `telemetry on`.
387    On,
388    /// `--no-claude-telemetry` / `telemetry off`.
389    Off,
390    /// Neither flag: on, unless the user opted out before (VIS-1109).
391    Default,
392}
393
394impl TelemetryChoice {
395    fn from_flags(on: bool, off: bool) -> Self {
396        match (on, off) {
397            (true, _) => Self::On,
398            (_, true) => Self::Off,
399            _ => Self::Default,
400        }
401    }
402}
403
404/// Record in the install state that this machine's telemetry is settled at
405/// this version, so the upgrade step does not redo it, and who owns the
406/// helper interval when this install found out (`added_interval`, see
407/// `interval_added_by_install`). Best-effort.
408fn record_telemetry_choice(opt_out: Option<bool>, added_interval: Option<bool>) {
409    let result = install_state::update_in(&config::tv_config_root(), |s| {
410        s.configured_version = Some(install_state::CURRENT_VERSION.to_string());
411        if added_interval.is_some() {
412            s.telemetry_added_interval = added_interval;
413        }
414        if let Some(opt_out) = opt_out {
415            s.claude_telemetry_opt_out = opt_out;
416            s.telemetry_auto_enabled = None;
417        }
418    });
419    if let Err(e) = result {
420        eprintln!("Warning: could not record the Claude Code telemetry choice: {e}");
421    }
422}
423
424/// Configure Claude Code telemetry after a successful `init` (or for
425/// `telemetry on|off`). On by default (VIS-1109): `Default` enables it
426/// unless the user opted out before, asking first in a terminal. `Off`
427/// removes our settings and records the opt-out, which only an explicit `On`
428/// clears. `Default` never turns on telemetry while Claude Code is set to
429/// export content (prompt text etc.). A failure exits non-zero only when the
430/// user asked explicitly; an existing exporter setup is not a failure (it is
431/// left alone, by design).
432fn finish_claude_telemetry(
433    choice: TelemetryChoice,
434    project_root: &std::path::Path,
435    server_flag: Option<&str>,
436) {
437    use commands::claude_telemetry::{content_logging_in, is_off, prompt, Environment};
438    let Some(claude_dir) = dirs::home_dir().map(|h| h.join(".claude")) else {
439        eprintln!("Error: cannot determine home directory");
440        std::process::exit(1);
441    };
442    let config_root = config::tv_config_root();
443    let env = Environment::current(&claude_dir);
444    let explicit = choice != TelemetryChoice::Default;
445    let content = || content_logging_in(&claude_dir, &env);
446    // Ask before taking the lock below: the answer may take a while.
447    let mut choice = choice;
448    if choice == TelemetryChoice::Default
449        && !install_state::load_in(&config_root).claude_telemetry_opt_out
450        && is_off(&claude_dir)
451        && content().is_empty()
452        && std::io::IsTerminal::is_terminal(&std::io::stdin())
453        && !prompt().unwrap_or(true)
454    {
455        choice = TelemetryChoice::Off;
456    }
457    // The upgrade step changes the same settings and state (VIS-1109).
458    let _lock = match install_state::Lock::take(&config_root, std::time::Duration::from_secs(10)) {
459        Ok(lock) => lock,
460        Err(e) if explicit => {
461            eprintln!("Error: Claude Code telemetry not changed: {e}");
462            std::process::exit(1);
463        }
464        Err(e) => {
465            eprintln!("Warning: Claude Code telemetry not configured: {e}");
466            return;
467        }
468    };
469    let state = install_state::load_in(&config_root);
470    let off = |claude_dir: &std::path::Path| match commands::claude_telemetry::uninstall(
471        claude_dir,
472        &env,
473        state.telemetry_added_interval,
474    ) {
475        Ok(removed) => {
476            if removed {
477                println!(
478                    "Claude Code telemetry is off (removed Visdom's settings from {})",
479                    claude_dir.join("settings.json").display()
480                );
481            } else {
482                println!("Claude Code telemetry is off");
483            }
484            record_telemetry_choice(Some(true), None);
485        }
486        Err(e) => {
487            eprintln!("Error: could not turn Claude Code telemetry off: {e}");
488            std::process::exit(1);
489        }
490    };
491    match choice {
492        TelemetryChoice::Off => return off(&claude_dir),
493        TelemetryChoice::Default if state.claude_telemetry_opt_out => {
494            println!(
495                "Claude Code telemetry stays off, as you chose earlier \
496                 (`{CLI} telemetry on` to enable it)"
497            );
498            return;
499        }
500        TelemetryChoice::Default if is_off(&claude_dir) && !content().is_empty() => {
501            // Not recorded: nothing was decided.
502            eprintln!(
503                "Warning: Claude Code telemetry not turned on: Claude Code is set to export \
504                 content ({}); run `{CLI} telemetry on` to send it to Visdom anyway",
505                content().join("; ")
506            );
507            return;
508        }
509        _ => {}
510    }
511    let interval_ours = commands::claude_telemetry::interval_added_by_install(&claude_dir);
512    let result = commands::claude_telemetry::telemetry_server_url(project_root, server_flag)
513        .and_then(|url| {
514            commands::claude_telemetry::install(&claude_dir, &url, &env)
515                .map(|outcome| (url, outcome))
516                .map_err(|e| e.to_string())
517        });
518    match result {
519        Ok((url, commands::claude_telemetry::InstallOutcome::Configured)) => {
520            println!(
521                "Claude Code telemetry exports to {} (configured in {}; restart Claude Code to \
522                 apply; `{CLI} telemetry off` to disable)",
523                commands::claude_telemetry::logs_endpoint(&url),
524                claude_dir.join("settings.json").display()
525            );
526            record_telemetry_choice(Some(false), interval_ours);
527        }
528        Ok((url, commands::claude_telemetry::InstallOutcome::Foreign(reasons))) => {
529            eprintln!(
530                "{}",
531                commands::claude_telemetry::collector_instructions(&url, &reasons)
532            );
533            record_telemetry_choice(explicit.then_some(false), None);
534        }
535        Err(e) if explicit => {
536            eprintln!("Error: Claude Code telemetry not configured: {e}");
537            std::process::exit(1);
538        }
539        // Not recorded: the upgrade step retries in a later session.
540        Err(e) => eprintln!("Warning: Claude Code telemetry not configured: {e}"),
541    }
542}
543
544/// Commands that agents and git run from installed hooks. Their output is
545/// parsed (or shown inside the agent), so nothing extra may be printed there.
546pub fn is_hook_invoked(cmd: &Command) -> bool {
547    matches!(
548        cmd,
549        Command::Stream { .. }
550            | Command::SessionStart
551            | Command::UserPrompt
552            | Command::CommitPush
553            | Command::Check
554            | Command::OtelHeaders { .. }
555    )
556}
557
558/// The one-line notice the `tracevault` binary prints for commands a person
559/// runs; `None` for hook-invoked ones.
560pub fn deprecation_notice(cmd: &Command) -> Option<&'static str> {
561    if is_hook_invoked(cmd) {
562        return None;
563    }
564    Some(
565        "note: `tracevault` is deprecated and will be replaced by `visdom` (same commands under \
566         `visdom trace …`; `visdom login`, `visdom init`).",
567    )
568}
569
570/// Run one command. Failures print their own message and exit the process
571/// with a non-zero status, exactly as the `tracevault` binary always did.
572pub async fn run(cmd: Command) {
573    match cmd {
574        Command::Init(InitArgs {
575            server_url,
576            claude_settings,
577            no_gitignore,
578            no_user_context,
579            user_context,
580            global,
581            agent,
582            claude_telemetry,
583            no_claude_telemetry,
584            workspace,
585            project,
586        }) => {
587            // Files an earlier release kept under `tracevault` names move to
588            // their `visdom` ones first, so everything below writes beside
589            // them. A machine-wide setup leaves the current directory alone.
590            let mut carried = commands::relocate::carry_over_user();
591            if !global {
592                if let Ok(cwd) = env::current_dir() {
593                    carried.extend(commands::relocate::carry_over_repo(&cwd));
594                }
595            }
596            for line in carried {
597                println!("{line}");
598            }
599            if workspace {
600                let cwd = env::current_dir().expect("Cannot determine current directory");
601                // `requires = "project"` guarantees it.
602                let name = project.expect("--workspace requires --project");
603                match commands::init::init_workspace(&cwd, &name, server_url.as_deref()).await {
604                    Ok(bound) => {
605                        println!(
606                            "Workspace {} bound to project {} (id: {})",
607                            cwd.display(),
608                            bound.project_name,
609                            bound.project_id
610                        );
611                        println!("Wrote {}", bound.config_path.display());
612                        println!(
613                            "Every session started under this directory is recorded to that \
614                             project unless it runs `{CLI} project switch` or binds a repo \
615                             with its own configuration."
616                        );
617                        println!(
618                            "No hooks were installed: if this machine has no global install yet, \
619                             run `{TOP} init --global`."
620                        );
621                    }
622                    Err(e) => {
623                        eprintln!("Error: {e}");
624                        std::process::exit(1);
625                    }
626                }
627                return;
628            }
629            if (claude_telemetry || no_claude_telemetry) && agent != crate::agent::Agent::ClaudeCode
630            {
631                eprintln!(
632                    "Error: --claude-telemetry and --no-claude-telemetry only apply to \
633                     --agent claude-code (use `{CLI} telemetry off` instead)"
634                );
635                std::process::exit(1);
636            }
637            let telemetry = TelemetryChoice::from_flags(claude_telemetry, no_claude_telemetry);
638            // Reject flag combinations that don't apply to the selected agent
639            // (e.g. --claude-settings with --agent codex) rather than silently
640            // ignoring them.
641            if let Err(e) = commands::init::validate_init_flags(agent, claude_settings.is_some()) {
642                eprintln!("Error: {e}");
643                std::process::exit(1);
644            }
645            if global {
646                // VIS-1256: `init` migrates a legacy `default_project` in any
647                // mode — here, in the config the current directory's hooks
648                // read — before anything is installed.
649                let cwd = env::current_dir().expect("Cannot determine current directory");
650                if let Err(e) = commands::init::migrate_cwd_config(&cwd).await {
651                    eprintln!("Error: {e}");
652                    std::process::exit(1);
653                }
654                // Explicit match (not `matches!(.., Codex)` + fallthrough) so a
655                // future agent variant can't silently fall through to the Claude
656                // Code branch and report success while installing nothing for it.
657                match agent {
658                    crate::agent::Agent::Codex => {
659                        let codex_dir = match dirs::home_dir() {
660                            Some(home) => home.join(".codex"),
661                            None => {
662                                eprintln!("Error: cannot determine home directory");
663                                std::process::exit(1);
664                            }
665                        };
666                        match commands::init::install_global_codex_hooks(&codex_dir) {
667                            Ok(()) => {
668                                println!(
669                                    "Installed Visdom Codex hooks in {}",
670                                    codex_dir.join("hooks.json").display()
671                                );
672                                println!(
673                                    "Added workspace-mode instructions to {}",
674                                    codex_dir.join("AGENTS.md").display()
675                                );
676                                println!(
677                                    "These apply to ALL Codex CLI sessions on this machine, not just this repo."
678                                );
679                                println!("{}", commands::init::codex_hook_trust_notice());
680                            }
681                            Err(e) => {
682                                eprintln!("Error: {e}");
683                                std::process::exit(1);
684                            }
685                        }
686
687                        finish_global_user_context(no_user_context, user_context);
688                        return;
689                    }
690                    crate::agent::Agent::Gsd => {
691                        // GSD (pi) loads extensions from a user-global
692                        // ~/.gsd/extensions/ directory, so a global install
693                        // just runs `gsd install` without `-l`, registering
694                        // the extension for ALL GSD sessions on this
695                        // machine rather than one repo.
696                        match commands::init::install_gsd_extension(None) {
697                            Ok(()) => {
698                                println!(
699                                    "This applies to ALL GSD sessions on this machine, not just this repo."
700                                );
701                            }
702                            Err(e) => {
703                                eprintln!("Error: {e}");
704                                std::process::exit(1);
705                            }
706                        }
707
708                        finish_global_user_context(no_user_context, user_context);
709                        return;
710                    }
711                    crate::agent::Agent::ClaudeCode => {
712                        let claude_dir = match dirs::home_dir() {
713                            Some(home) => home.join(".claude"),
714                            None => {
715                                eprintln!("Error: cannot determine home directory");
716                                std::process::exit(1);
717                            }
718                        };
719                        match commands::init::install_global_hooks(&claude_dir) {
720                            Ok(()) => {
721                                println!(
722                                    "Installed Visdom hooks in {}",
723                                    claude_dir.join("settings.json").display()
724                                );
725                                println!("Updated {}", claude_dir.join("CLAUDE.md").display());
726                                println!(
727                                    "These apply to ALL Claude Code sessions on this machine, not just this repo."
728                                );
729                            }
730                            Err(e) => {
731                                eprintln!("Error: {e}");
732                                std::process::exit(1);
733                            }
734                        }
735
736                        finish_global_user_context(no_user_context, user_context);
737                        let cwd = env::current_dir().expect("Cannot determine current directory");
738                        finish_claude_telemetry(telemetry, &cwd, None);
739                        return;
740                    }
741                    crate::agent::Agent::OpenCode => {
742                        // OpenCode auto-loads plugins from the user-global
743                        // ~/.config/opencode/plugins/ directory, so a global
744                        // install writes there directly, applying to ALL
745                        // OpenCode sessions on this machine rather than one
746                        // repo.
747                        if let Err(e) = commands::init::install_opencode_plugin(None) {
748                            eprintln!("Error: {e}");
749                            std::process::exit(1);
750                        }
751                        println!(
752                            "This applies to ALL OpenCode sessions on this machine, not just this repo."
753                        );
754
755                        finish_global_user_context(no_user_context, user_context);
756                        return;
757                    }
758                    crate::agent::Agent::Amp => {
759                        // Amp loads system plugins from its user config dir
760                        // for every session, so a global install writes
761                        // there directly.
762                        match commands::init::install_amp_plugin(None) {
763                            Ok(path) => {
764                                println!("Installed the Visdom Amp plugin in {}", path.display());
765                                println!(
766                                    "This applies to ALL Amp sessions on this machine, not just this repo."
767                                );
768                                println!("{}", commands::init::amp_headless_notice());
769                            }
770                            Err(e) => {
771                                eprintln!("Error: {e}");
772                                std::process::exit(1);
773                            }
774                        }
775
776                        finish_global_user_context(no_user_context, user_context);
777                        return;
778                    }
779                }
780            }
781
782            let cwd = env::current_dir().expect("Cannot determine current directory");
783            let user_context =
784                match config::UserContext::from_init_flags(no_user_context, user_context) {
785                    // `None`: no flag, so `init` keeps the stored value
786                    // (on by default when there is none).
787                    Ok(r) => r,
788                    Err(e) => {
789                        eprintln!("Error: {e}");
790                        std::process::exit(1);
791                    }
792                };
793            match commands::init::init_in_directory(
794                &cwd,
795                server_url.as_deref(),
796                claude_settings,
797                no_gitignore,
798                user_context,
799                agent,
800            )
801            .await
802            {
803                Ok(entry) => {
804                    println!("Visdom initialized in {}", cwd.display());
805                    if entry.is_empty() {
806                        // GSD (pi): the extension lives in the user-global
807                        // ~/.gsd/extensions/tracevault/, not in the repo — there's
808                        // no per-repo hook file to report or gitignore.
809                        println!("{} extension installed", agent.label());
810                        println!("Git hooks installed (pre-push, post-commit)");
811                        println!(
812                            "Tracing state is kept in .visdom/ (ignored by its own .gitignore)"
813                        );
814                    } else {
815                        println!("{} hooks installed ({entry})", agent.label());
816                        println!("Git hooks installed (pre-push, post-commit)");
817                        println!("Added {entry} to .gitignore");
818                        println!(
819                            "Tracing state is kept in .visdom/ (ignored by its own .gitignore)"
820                        );
821                    }
822                    println!("Nothing needs to be committed — all Visdom files are local only.");
823                    println!(
824                        "Other contributors run `{TOP} init` to set up their own local hooks."
825                    );
826                    if agent == crate::agent::Agent::ClaudeCode {
827                        finish_claude_telemetry(telemetry, &cwd, server_url.as_deref());
828                    }
829                }
830                Err(e) => {
831                    eprintln!("Error: {e}");
832                    std::process::exit(1);
833                }
834            }
835        }
836        Command::Status { session_id } => {
837            let cwd = env::current_dir().expect("Cannot determine current directory");
838            let project_root = crate::paths::resolve_project_root(&cwd).root;
839            let effective = commands::status::effective_session_id(
840                session_id,
841                crate::session_state::env_session_id(),
842            );
843            let code =
844                commands::status::run_status(&project_root, &cwd, effective.as_deref()).await;
845            if code != 0 {
846                std::process::exit(code);
847            }
848        }
849        Command::OtelHeaders { server_url } => {
850            let cwd = env::current_dir().expect("Cannot determine current directory");
851            match commands::claude_telemetry::otel_headers(&cwd, server_url.as_deref()).await {
852                Ok(headers) => println!("{headers}"),
853                Err(e) => {
854                    eprintln!("{CLI} otel-headers: {e}");
855                    std::process::exit(1);
856                }
857            }
858        }
859        Command::Telemetry { action } => {
860            let cwd = env::current_dir().expect("Cannot determine current directory");
861            let project_root = crate::paths::resolve_project_root(&cwd).root;
862            match action {
863                TelemetryAction::On => {
864                    finish_claude_telemetry(TelemetryChoice::On, &project_root, None)
865                }
866                TelemetryAction::Off => {
867                    finish_claude_telemetry(TelemetryChoice::Off, &project_root, None)
868                }
869                TelemetryAction::Status => {
870                    let server_url = crate::credentials::resolve_credentials_quiet(&project_root)
871                        .ok()
872                        .and_then(|(url, _)| url);
873                    println!(
874                        "{}",
875                        commands::status::telemetry_status_line(server_url.as_deref())
876                    );
877                }
878            }
879        }
880        Command::Stream { event, agent } => {
881            if let Err(e) = commands::stream::run_stream(&event, agent).await {
882                eprintln!("Stream error: {e}");
883            }
884        }
885        Command::SessionStart => {
886            // The hook itself always prints a valid HookOutput JSON payload
887            // before returning; an Err here is a genuine last-resort case
888            // (e.g. stdin unreadable) and — same as `Stream` — must never
889            // turn into a non-zero exit, which would block the Claude Code
890            // session from starting.
891            if let Err(e) = commands::session_start::run().await {
892                eprintln!("SessionStart error: {e}");
893            }
894        }
895        Command::UserPrompt => {
896            // Same reasoning as `SessionStart`: this hook always prints a
897            // valid HookOutput JSON payload before returning; an Err here
898            // must never turn into a non-zero exit, which would block the
899            // prompt from being submitted.
900            if let Err(e) = commands::user_prompt::run().await {
901                eprintln!("UserPromptSubmit error: {e}");
902            }
903        }
904        Command::Check => {
905            let cwd = env::current_dir().expect("Cannot determine current directory");
906            let project_root = crate::paths::resolve_project_root(&cwd).root;
907            if let Err(e) = commands::check::check_policies(&project_root, &cwd).await {
908                eprintln!("Check error: {e}");
909                std::process::exit(1);
910            }
911        }
912        Command::Sync => {
913            let cwd = env::current_dir().expect("Cannot determine current directory");
914            let project_root = crate::paths::resolve_project_root(&cwd).root;
915            if let Err(e) = commands::sync::sync_repo(&project_root).await {
916                eprintln!("Sync error: {e}");
917                std::process::exit(1);
918            }
919        }
920        Command::Stats => {
921            let cwd = env::current_dir().expect("Cannot determine current directory");
922            let project_root = crate::paths::resolve_project_root(&cwd).root;
923            if let Err(e) = commands::stats::show_stats(&project_root) {
924                eprintln!("Stats error: {e}");
925            }
926        }
927        Command::Login(LoginArgs {
928            server_url,
929            no_browser,
930        }) => {
931            if let Err(e) = commands::login::login(&server_url, no_browser).await {
932                eprintln!("Login error: {e}");
933                // Non-zero exit matters here: a scripted `tracevault login &&
934                // ...`, and above all the "account has no `tracevault`
935                // grant" case (which saves credentials but is NOT a usable
936                // login), must not look like success.
937                std::process::exit(1);
938            }
939        }
940        Command::Logout => {
941            if let Err(e) = commands::logout::logout().await {
942                eprintln!("Logout error: {e}");
943                std::process::exit(1);
944            }
945        }
946        Command::CommitPush => {
947            let cwd = env::current_dir().expect("Cannot determine current directory");
948            let project_root = crate::paths::resolve_project_root(&cwd).root;
949            if let Err(e) = commands::commit_push::run_commit_push(&project_root, &cwd).await {
950                eprintln!("Commit push error: {e}");
951            }
952        }
953        Command::Flush => {
954            let cwd = env::current_dir().expect("Cannot determine current directory");
955            let project_root = crate::paths::resolve_project_root(&cwd).root;
956            if let Err(e) = commands::flush::run_flush(&project_root).await {
957                eprintln!("Flush error: {e}");
958            }
959        }
960        Command::Verify { commits, range } => {
961            let cwd = env::current_dir().expect("Cannot determine current directory");
962            let project_root = crate::paths::resolve_project_root(&cwd).root;
963            if let Err(e) =
964                commands::verify::verify(&project_root, &cwd, commits.as_deref(), range.as_deref())
965                    .await
966            {
967                eprintln!("Verify error: {e}");
968                std::process::exit(1);
969            }
970        }
971        Command::VerifyStart { session_id } => {
972            let cwd = env::current_dir().expect("Cannot determine current directory");
973            let project_root = crate::paths::resolve_project_root(&cwd).root;
974            let env_session_id = crate::session_state::env_session_id();
975            if let Err(e) = commands::verification_phase::open_verification_phase(
976                &project_root,
977                &cwd,
978                session_id.as_deref(),
979                env_session_id.as_deref(),
980            )
981            .await
982            {
983                eprintln!("Error: {e}");
984                std::process::exit(1);
985            }
986        }
987        Command::AgentPolicies => {
988            let cwd = env::current_dir().expect("Cannot determine current directory");
989            let project_root = crate::paths::resolve_project_root(&cwd).root;
990            if let Err(e) = commands::agent_policies::run(&project_root).await {
991                eprintln!("Error: {e}");
992                std::process::exit(1);
993            }
994        }
995        Command::Proxy { cmd } => match cmd {
996            ProxyCmd::Info => {
997                let code = commands::proxy::run_proxy_info();
998                if code != 0 {
999                    std::process::exit(code);
1000                }
1001            }
1002        },
1003        Command::Context { action } => {
1004            let cwd = env::current_dir().expect("Cannot determine current directory");
1005            let result = match action {
1006                ContextAction::Set {
1007                    flow,
1008                    label,
1009                    param,
1010                    global,
1011                    user,
1012                } => commands::context::run_set(&cwd, flow, label, param, global, user),
1013                ContextAction::Update {
1014                    flow,
1015                    label,
1016                    param,
1017                    remove_label,
1018                    remove_param,
1019                    global,
1020                    user,
1021                } => commands::context::run_update(
1022                    &cwd,
1023                    flow,
1024                    label,
1025                    param,
1026                    remove_label,
1027                    remove_param,
1028                    global,
1029                    user,
1030                ),
1031                ContextAction::Show => commands::context::run_show(&cwd),
1032                ContextAction::Clear { global, user } => {
1033                    commands::context::run_clear(&cwd, global, user)
1034                }
1035                ContextAction::Source {
1036                    enable,
1037                    disable,
1038                    path,
1039                    default,
1040                } => commands::context::run_source(&cwd, enable, disable, path, default),
1041            };
1042            if let Err(e) = result {
1043                eprintln!("Context error: {e}");
1044                std::process::exit(1);
1045            }
1046        }
1047        Command::Repo { cmd } => {
1048            let cwd = env::current_dir().expect("Cannot determine current directory");
1049            let project_root = crate::paths::resolve_project_root(&cwd).root;
1050            if let Err(e) = commands::repo::run(cmd, &project_root, &cwd).await {
1051                eprintln!("Repo error: {e}");
1052                std::process::exit(1);
1053            }
1054        }
1055        Command::Project { cmd } => {
1056            let cwd = env::current_dir().expect("Cannot determine current directory");
1057            let project_root = crate::paths::resolve_project_root(&cwd).root;
1058            if let Err(e) = commands::project::run(cmd, &project_root, &cwd).await {
1059                eprintln!("Project error: {e}");
1060                std::process::exit(1);
1061            }
1062        }
1063    }
1064}
1065
1066#[cfg(test)]
1067mod tests {
1068    use super::{deprecation_notice, Command};
1069    use clap::Parser;
1070
1071    #[derive(Parser)]
1072    #[command(name = "tracevault")]
1073    struct Cli {
1074        #[command(subcommand)]
1075        _command: Command,
1076    }
1077
1078    #[test]
1079    fn deprecation_notice_skips_hook_commands() {
1080        for cmd in [
1081            Command::SessionStart,
1082            Command::Check,
1083            Command::CommitPush,
1084            Command::UserPrompt,
1085        ] {
1086            assert!(deprecation_notice(&cmd).is_none());
1087        }
1088    }
1089
1090    #[test]
1091    fn deprecation_notice_for_interactive_commands() {
1092        for cmd in [Command::Stats, Command::Logout] {
1093            let notice = deprecation_notice(&cmd).expect("a notice");
1094            assert!(notice.contains("visdom"), "{notice}");
1095        }
1096    }
1097
1098    #[test]
1099    fn init_user_context_flags_conflict() {
1100        // `--no-user-context` and `--user-context <path>` are mutually exclusive
1101        // and must be rejected up front rather than silently prioritizing one.
1102        // `Cli` has no `Debug` impl, so match instead of `expect_err`.
1103        let err = match Cli::try_parse_from([
1104            "tracevault",
1105            "init",
1106            "--no-user-context",
1107            "--user-context",
1108            "/tmp/ctx.json",
1109        ]) {
1110            Ok(_) => panic!("both flags together must be a parse error"),
1111            Err(e) => e,
1112        };
1113        assert_eq!(err.kind(), clap::error::ErrorKind::ArgumentConflict);
1114    }
1115
1116    #[test]
1117    fn init_user_context_flags_are_ok_alone() {
1118        assert!(Cli::try_parse_from(["tracevault", "init", "--no-user-context"]).is_ok());
1119        assert!(
1120            Cli::try_parse_from(["tracevault", "init", "--user-context", "/tmp/ctx.json"]).is_ok()
1121        );
1122    }
1123
1124    #[test]
1125    fn context_source_mode_flags_conflict() {
1126        // The `source` mode flags are mutually exclusive; two together must be a
1127        // parse-time conflict rather than relying on run_source precedence.
1128        for extra in [["--enable", "--disable"], ["--disable", "--default"]] {
1129            let err = match Cli::try_parse_from(
1130                ["tracevault", "context", "source"].into_iter().chain(extra),
1131            ) {
1132                Ok(_) => panic!("{extra:?} together must be a parse error"),
1133                Err(e) => e,
1134            };
1135            assert_eq!(err.kind(), clap::error::ErrorKind::ArgumentConflict);
1136        }
1137        // --path with --disable also conflicts.
1138        let err = match Cli::try_parse_from([
1139            "tracevault",
1140            "context",
1141            "source",
1142            "--path",
1143            "/tmp/ctx.json",
1144            "--disable",
1145        ]) {
1146            Ok(_) => panic!("--path with --disable must be a parse error"),
1147            Err(e) => e,
1148        };
1149        assert_eq!(err.kind(), clap::error::ErrorKind::ArgumentConflict);
1150    }
1151
1152    #[test]
1153    fn context_source_single_mode_is_ok() {
1154        assert!(Cli::try_parse_from(["tracevault", "context", "source", "--enable"]).is_ok());
1155        assert!(Cli::try_parse_from([
1156            "tracevault",
1157            "context",
1158            "source",
1159            "--path",
1160            "/tmp/ctx.json"
1161        ])
1162        .is_ok());
1163    }
1164
1165    /// Rendered `--help` of the subcommand at `path`, whitespace-collapsed so
1166    /// assertions don't depend on line wrapping.
1167    fn long_help(path: &[&str]) -> String {
1168        use clap::CommandFactory;
1169        let mut cmd = Cli::command();
1170        let mut sub = &mut cmd;
1171        for name in path {
1172            sub = sub
1173                .find_subcommand_mut(name)
1174                .unwrap_or_else(|| panic!("no subcommand {name}"));
1175        }
1176        sub.render_long_help()
1177            .to_string()
1178            .split_whitespace()
1179            .collect::<Vec<_>>()
1180            .join(" ")
1181    }
1182
1183    #[test]
1184    fn init_help_names_every_agent_install_target() {
1185        let help = long_help(&["init"]);
1186        for needle in [
1187            ".codex/hooks.json",
1188            "gsd install -l",
1189            ".opencode/plugins/",
1190            "~/.codex/",
1191            "OpenCode plugin",
1192            ".amp/plugins/",
1193            "$XDG_CONFIG_HOME/amp/plugins/",
1194            "~/.config/amp/plugins/",
1195            "--server-url, --claude-settings and --no-gitignore",
1196        ] {
1197            assert!(
1198                help.contains(needle),
1199                "init --help lacks {needle:?}: {help}"
1200            );
1201        }
1202        assert!(!help.contains("for ALL Claude Code sessions"), "{help}");
1203        // The opencode value's clap-naming note is an implementation comment.
1204        assert!(!help.contains("kebab-case"), "{help}");
1205    }
1206
1207    #[test]
1208    fn hook_command_help_says_per_repo_init_installs_them() {
1209        for name in ["session-start", "user-prompt"] {
1210            let help = long_help(&[name]);
1211            assert!(help.contains("per-repo or --global"), "{name}: {help}");
1212            assert!(help.contains("Codex hooks.json"), "{name}: {help}");
1213        }
1214    }
1215
1216    #[test]
1217    fn context_show_help_lists_the_user_section() {
1218        let help = long_help(&["context", "show"]);
1219        assert!(help.contains("User (always;"), "{help}");
1220        assert!(!help.contains("three sections"), "{help}");
1221    }
1222}