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