1use 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 Init(InitArgs),
15 Telemetry {
18 #[arg(value_enum)]
19 action: TelemetryAction,
20 },
21 #[command(name = "otel-headers", hide = true)]
26 OtelHeaders {
27 #[arg(long)]
29 server_url: Option<String>,
30 },
31 Status {
33 #[arg(long)]
37 session_id: Option<String>,
38 },
39 #[command(hide = true)]
43 Stream {
44 #[arg(long)]
45 event: String,
46 #[arg(long, value_enum, default_value = "claude-code")]
49 agent: crate::agent::Agent,
50 },
51 #[command(name = "session-start", hide = true)]
57 SessionStart,
58 #[command(name = "user-prompt", hide = true)]
64 UserPrompt,
65 Check,
67 Sync,
69 Stats,
71 Login(LoginArgs),
73 Logout,
75 #[command(hide = true)]
79 CommitPush,
80 Flush,
82 Verify {
84 #[arg(long)]
86 commits: Option<String>,
87 #[arg(long)]
89 range: Option<String>,
90 },
91 #[command(name = "verify-start")]
101 VerifyStart {
102 #[arg(long)]
107 session_id: Option<String>,
108 },
109 #[command(name = "agent-policies")]
116 AgentPolicies,
117 Proxy {
119 #[command(subcommand)]
120 cmd: ProxyCmd,
121 },
122 Context {
124 #[command(subcommand)]
125 action: ContextAction,
126 },
127 Repo {
129 #[command(subcommand)]
130 cmd: RepoCmd,
131 },
132 Project {
134 #[command(subcommand)]
135 cmd: ProjectCmd,
136 },
137}
138
139#[derive(clap::Args, Clone)]
141pub struct InitArgs {
142 #[arg(long)]
144 pub server_url: Option<String>,
145 #[arg(long, value_enum)]
150 pub claude_settings: Option<commands::init::ClaudeSettingsTarget>,
151 #[arg(long)]
154 pub no_gitignore: bool,
155 #[arg(long)]
159 pub no_user_context: bool,
160 #[arg(long, conflicts_with = "no_user_context")]
164 pub user_context: Option<String>,
165 #[arg(
177 long,
178 conflicts_with_all = ["server_url", "claude_settings", "no_gitignore"]
179 )]
180 pub global: bool,
181 #[arg(long, value_enum, default_value = "claude-code")]
189 pub agent: crate::agent::Agent,
190 #[arg(long, conflicts_with = "no_claude_telemetry")]
199 pub claude_telemetry: bool,
200 #[arg(long)]
204 pub no_claude_telemetry: bool,
205 #[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 #[arg(long, requires = "workspace")]
226 pub project: Option<String>,
227}
228
229#[derive(clap::Args)]
231pub struct LoginArgs {
232 #[arg(long)]
234 pub server_url: String,
235 #[arg(long)]
238 pub no_browser: bool,
239}
240
241#[derive(clap::Subcommand)]
243pub enum ContextAction {
244 Set {
253 #[arg(long)]
255 flow: Option<String>,
256 #[arg(long)]
258 label: Vec<String>,
259 #[arg(long)]
261 param: Vec<String>,
262 #[arg(long)]
264 global: bool,
265 #[arg(long)]
267 user: bool,
268 },
269 Update {
277 #[arg(long)]
279 flow: Option<String>,
280 #[arg(long)]
282 label: Vec<String>,
283 #[arg(long)]
285 param: Vec<String>,
286 #[arg(long = "remove-label")]
288 remove_label: Vec<String>,
289 #[arg(long = "remove-param")]
291 remove_param: Vec<String>,
292 #[arg(long)]
294 global: bool,
295 #[arg(long)]
297 user: bool,
298 },
299 Show,
306 Clear {
311 #[arg(long)]
313 global: bool,
314 #[arg(long)]
316 user: bool,
317 },
318 #[command(group(clap::ArgGroup::new("source_mode").multiple(false)))]
322 Source {
323 #[arg(long, group = "source_mode")]
325 enable: bool,
326 #[arg(long, group = "source_mode")]
328 disable: bool,
329 #[arg(long, group = "source_mode")]
331 path: Option<String>,
332 #[arg(long, group = "source_mode")]
334 default: bool,
335 },
336}
337
338#[derive(clap::Subcommand)]
339pub enum ProxyCmd {
340 Info,
343}
344
345fn 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#[derive(Clone, Copy, PartialEq, Eq)]
385enum TelemetryChoice {
386 On,
388 Off,
390 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
404fn 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
424fn 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 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 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 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 Err(e) => eprintln!("Warning: Claude Code telemetry not configured: {e}"),
541 }
542}
543
544pub 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
558pub 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
570pub 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 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 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 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 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 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 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 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 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 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 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 if let Err(e) = commands::session_start::run().await {
892 eprintln!("SessionStart error: {e}");
893 }
894 }
895 Command::UserPrompt => {
896 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 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 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 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 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 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 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}