1use 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 Init(InitArgs),
14 Telemetry {
17 #[arg(value_enum)]
18 action: TelemetryAction,
19 },
20 #[command(name = "otel-headers", hide = true)]
25 OtelHeaders {
26 #[arg(long)]
28 server_url: Option<String>,
29 },
30 Status {
32 #[arg(long)]
36 session_id: Option<String>,
37 },
38 #[command(hide = true)]
42 Stream {
43 #[arg(long)]
44 event: String,
45 #[arg(long, value_enum, default_value = "claude-code")]
48 agent: crate::agent::Agent,
49 },
50 #[command(name = "session-start", hide = true)]
56 SessionStart,
57 #[command(name = "user-prompt", hide = true)]
63 UserPrompt,
64 Check,
66 Sync,
68 Stats,
70 Login(LoginArgs),
72 Logout,
74 #[command(hide = true)]
78 CommitPush,
79 Flush,
81 Verify {
83 #[arg(long)]
85 commits: Option<String>,
86 #[arg(long)]
88 range: Option<String>,
89 },
90 #[command(name = "verify-start")]
100 VerifyStart {
101 #[arg(long)]
106 session_id: Option<String>,
107 },
108 #[command(name = "agent-policies")]
115 AgentPolicies,
116 Proxy {
118 #[command(subcommand)]
119 cmd: ProxyCmd,
120 },
121 Context {
123 #[command(subcommand)]
124 action: ContextAction,
125 },
126 Repo {
128 #[command(subcommand)]
129 cmd: RepoCmd,
130 },
131 Project {
133 #[command(subcommand)]
134 cmd: ProjectCmd,
135 },
136}
137
138#[derive(clap::Args)]
140pub struct InitArgs {
141 #[arg(long)]
143 pub server_url: Option<String>,
144 #[arg(long, value_enum)]
149 pub claude_settings: Option<commands::init::ClaudeSettingsTarget>,
150 #[arg(long)]
153 pub no_gitignore: bool,
154 #[arg(long)]
158 pub no_user_context: bool,
159 #[arg(long, conflicts_with = "no_user_context")]
163 pub user_context: Option<String>,
164 #[arg(
176 long,
177 conflicts_with_all = ["server_url", "claude_settings", "no_gitignore"]
178 )]
179 pub global: bool,
180 #[arg(long, value_enum, default_value = "claude-code")]
188 pub agent: crate::agent::Agent,
189 #[arg(long, conflicts_with = "no_claude_telemetry")]
198 pub claude_telemetry: bool,
199 #[arg(long)]
203 pub no_claude_telemetry: bool,
204 #[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 #[arg(long, requires = "workspace")]
225 pub project: Option<String>,
226}
227
228#[derive(clap::Args)]
230pub struct LoginArgs {
231 #[arg(long)]
233 pub server_url: String,
234 #[arg(long)]
237 pub no_browser: bool,
238}
239
240#[derive(clap::Subcommand)]
242pub enum ContextAction {
243 Set {
252 #[arg(long)]
254 flow: Option<String>,
255 #[arg(long)]
257 label: Vec<String>,
258 #[arg(long)]
260 param: Vec<String>,
261 #[arg(long)]
263 global: bool,
264 #[arg(long)]
266 user: bool,
267 },
268 Update {
276 #[arg(long)]
278 flow: Option<String>,
279 #[arg(long)]
281 label: Vec<String>,
282 #[arg(long)]
284 param: Vec<String>,
285 #[arg(long = "remove-label")]
287 remove_label: Vec<String>,
288 #[arg(long = "remove-param")]
290 remove_param: Vec<String>,
291 #[arg(long)]
293 global: bool,
294 #[arg(long)]
296 user: bool,
297 },
298 Show,
305 Clear {
310 #[arg(long)]
312 global: bool,
313 #[arg(long)]
315 user: bool,
316 },
317 #[command(group(clap::ArgGroup::new("source_mode").multiple(false)))]
321 Source {
322 #[arg(long, group = "source_mode")]
324 enable: bool,
325 #[arg(long, group = "source_mode")]
327 disable: bool,
328 #[arg(long, group = "source_mode")]
330 path: Option<String>,
331 #[arg(long, group = "source_mode")]
333 default: bool,
334 },
335}
336
337#[derive(clap::Subcommand)]
338pub enum ProxyCmd {
339 Info,
342}
343
344fn 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#[derive(Clone, Copy, PartialEq, Eq)]
384enum TelemetryChoice {
385 On,
387 Off,
389 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
403fn 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
423fn 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 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 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 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 Err(e) => eprintln!("Warning: Claude Code telemetry not configured: {e}"),
540 }
541}
542
543pub 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
557pub 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
569pub 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 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 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 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 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 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 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 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 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 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 if let Err(e) = commands::session_start::run().await {
882 eprintln!("SessionStart error: {e}");
883 }
884 }
885 Command::UserPrompt => {
886 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 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 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 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 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 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 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}