tracevault-cli 0.29.5

CLI tool for Visdom Trace - AI code tracing and attribution
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
//! The `tracevault` command surface and its dispatch, shared by the
//! `tracevault` binary and by `visdom` (which mounts it under `visdom trace`).

use std::env;

use crate::commands::project::ProjectCmd;
use crate::commands::repo::RepoCmd;
use crate::{commands, config, install_state};

#[derive(clap::Subcommand)]
pub enum Command {
    /// Initialize TraceVault in current repository
    Init(InitArgs),
    /// Claude Code telemetry (cost over OpenTelemetry, on by default): `on`,
    /// `off` (remembered across upgrades) or `status`.
    Telemetry {
        #[arg(value_enum)]
        action: TelemetryAction,
    },
    /// Print the Authorization header for Claude Code's OpenTelemetry export,
    /// as JSON, from the TraceVault credential store. Installed as
    /// `otelHeadersHelper` by `tracevault init --claude-telemetry` — not
    /// intended to be run manually.
    #[command(name = "otel-headers", hide = true)]
    OtelHeaders {
        /// The server telemetry is exported to: the credential must be for it.
        #[arg(long)]
        server_url: Option<String>,
    },
    /// Show current session status
    Status {
        /// Session to inspect for the workspace binding; defaults to
        /// $TRACEVAULT_SESSION_ID (in Amp: $AMP_CURRENT_THREAD_ID), else the
        /// most recent session that has a workspace binding.
        #[arg(long)]
        session_id: Option<String>,
    },
    /// Stream hook events to server in real-time.
    /// Installed into .claude/settings.json by `tracevault init` and invoked
    /// by Claude Code on every tool event — not intended to be run manually.
    #[command(hide = true)]
    Stream {
        #[arg(long)]
        event: String,
        /// Which agent this hook belongs to (sets the request's tool + protocol
        /// version). Defaults to claude-code so existing installs are unchanged.
        #[arg(long, value_enum, default_value = "claude-code")]
        agent: crate::agent::Agent,
    },
    /// SessionStart hook: exports the session id, binds an unbound session to
    /// the repo of its checkout's origin remote, and injects the bound repo's
    /// policies as additionalContext. Installed by `tracevault init` (per-repo
    /// or --global) into the Claude Code settings or the Codex hooks.json —
    /// not intended to be run manually.
    #[command(name = "session-start", hide = true)]
    SessionStart,
    /// UserPromptSubmit hook: reinforces the bound repo's policies as
    /// additionalContext when the effective repo has changed since the last
    /// injection. Installed by `tracevault init` (per-repo or --global) into
    /// the Claude Code settings or the Codex hooks.json — not intended to be
    /// run manually.
    #[command(name = "user-prompt", hide = true)]
    UserPrompt,
    /// Check session policies before pushing
    Check,
    /// Sync repo remote URL with the TraceVault server
    Sync,
    /// Show local session statistics
    Stats,
    /// Log in to a TraceVault server
    Login(LoginArgs),
    /// Log out from the TraceVault server
    Logout,
    /// Push commit metadata to the server.
    /// Installed into .git/hooks/post-commit by `tracevault init` and
    /// invoked by git after every commit — not intended to be run manually.
    #[command(hide = true)]
    CommitPush,
    /// Force-sync all pending events to server
    Flush,
    /// Verify commits are registered and sealed on the TraceVault server
    Verify {
        /// Comma-separated list of commit SHAs
        #[arg(long)]
        commits: Option<String>,
        /// Git commit range (e.g. abc1234..def5678)
        #[arg(long)]
        range: Option<String>,
    },
    /// Open (or re-open) a verification phase for the current session.
    ///
    /// A verification phase declares that the agent has finished making changes
    /// and is now running quality checks. Only tool calls made after this point
    /// are evaluated by verification_phase-scoped policies. Calling this again
    /// resets the phase, discarding earlier verification events.
    ///
    /// In single-agent setups the current session is detected automatically.
    /// In multi-agent setups, pass --session-id to target the correct session.
    #[command(name = "verify-start")]
    VerifyStart {
        /// Explicit session ID to open the window for. When omitted, the
        /// invoking session ($TRACEVAULT_SESSION_ID; in Amp: $AMP_CURRENT_THREAD_ID)
        /// is used if it has events in this worktree, else the session is
        /// detected by worktree.
        #[arg(long)]
        session_id: Option<String>,
    },
    /// Print agent-readable instructions derived from active policies.
    ///
    /// Fetches the rendered instructions from the server for the current repo
    /// and prints them to stdout. Designed to be invoked from CLAUDE.md (or
    /// equivalent) at session start so the agent's behaviour matches the
    /// policies configured on the TraceVault server.
    #[command(name = "agent-policies")]
    AgentPolicies,
    /// LLM proxy commands.
    Proxy {
        #[command(subcommand)]
        cmd: ProxyCmd,
    },
    /// Manage the active context (flow ID, labels, params) attached to events.
    Context {
        #[command(subcommand)]
        action: ContextAction,
    },
    /// Bind/inspect the repo a detached session is working on (workspace mode).
    Repo {
        #[command(subcommand)]
        cmd: RepoCmd,
    },
    /// Bind/inspect the project a detached session is attributed to.
    Project {
        #[command(subcommand)]
        cmd: ProjectCmd,
    },
}

/// Arguments of `init`.
#[derive(clap::Args)]
pub struct InitArgs {
    /// TraceVault server URL for repo registration
    #[arg(long)]
    pub server_url: Option<String>,
    /// Where to install Claude Code hooks: `shared` (.claude/settings.json,
    /// typically committed) or `local` (.claude/settings.local.json,
    /// personal/git-ignored). When omitted, prompts interactively if stdin
    /// is a TTY, otherwise defaults to `shared`.
    #[arg(long, value_enum)]
    pub claude_settings: Option<commands::init::ClaudeSettingsTarget>,
    /// Skip updating .gitignore. Use this when your project manages
    /// .gitignore separately or you want to commit the Claude settings files.
    #[arg(long)]
    pub no_gitignore: bool,
    /// Disable the cross-repo user-level context for this project. Also
    /// applies to `--global`, where it disables the user-level context
    /// instead of the per-repo one.
    #[arg(long)]
    pub no_user_context: bool,
    /// Enable the user-level context and read it from this explicit path
    /// (conflicts with --no-user-context). Also applies to `--global`,
    /// where it sets the path the user-level context is read from.
    #[arg(long, conflicts_with = "no_user_context")]
    pub user_context: Option<String>,
    /// Install TraceVault once for ALL sessions of the chosen --agent on
    /// this machine, instead of initializing the current repo: Claude Code
    /// hooks into ~/.claude/ (settings.json + CLAUDE.md), Codex hooks into
    /// ~/.codex/ (hooks.json + AGENTS.md), the GSD extension via
    /// `gsd install` (global), the OpenCode plugin into the user config
    /// dir's opencode/plugins/, or the Amp plugin into
    /// $XDG_CONFIG_HOME/amp/plugins/ (~/.config/amp/plugins/ when unset).
    /// Does not require git. Also writes a
    /// user-level context config (honoring --no-user-context /
    /// --user-context). Conflicts with the per-repo-only flags
    /// --server-url, --claude-settings and --no-gitignore.
    #[arg(
        long,
        conflicts_with_all = ["server_url", "claude_settings", "no_gitignore"]
    )]
    pub global: bool,
    /// Which agent to install hooks for. The default installs Claude Code
    /// hooks (.claude/settings.json or settings.local.json); `codex` writes
    /// .codex/hooks.json; `gsd` (alias `gsd2`) registers the GSD extension
    /// with `gsd install -l`; `opencode` writes
    /// .opencode/plugins/tracevault.ts; `amp` writes
    /// .amp/plugins/tracevault/index.ts. With --global, the user-level
    /// equivalents instead.
    #[arg(long, value_enum, default_value = "claude-code")]
    pub agent: crate::agent::Agent,
    /// Export Claude Code's own per-request cost to TraceVault over
    /// OpenTelemetry (the default): writes the OTel log exporter settings
    /// and an `otelHeadersHelper` (`tracevault otel-headers`) into the
    /// USER-level ~/.claude/settings.json, per-repo or with --global. An
    /// existing exporter setup is left untouched (collector instructions
    /// are printed instead). Without either flag, an interactive init asks
    /// (default yes), and a non-interactive one enables it unless you
    /// opted out before.
    #[arg(long, conflicts_with = "no_claude_telemetry")]
    pub claude_telemetry: bool,
    /// Opt out of Claude Code telemetry: removes TraceVault's entries from
    /// ~/.claude/settings.json and records the choice, so neither a later
    /// `init` nor a CLI upgrade turns it back on.
    #[arg(long)]
    pub no_claude_telemetry: bool,
    /// Bind this directory to one project, for every session started
    /// under it (an umbrella folder of checkouts, for example): resolves
    /// --project once on the server and writes its id to
    /// .tracevault/config.toml here (created if missing). Works outside
    /// git; installs no hooks (use --global for those) and binds no repo.
    #[arg(
        long,
        requires = "project",
        conflicts_with_all = [
            "global",
            "claude_settings",
            "no_gitignore",
            "no_user_context",
            "user_context",
            "claude_telemetry",
            "no_claude_telemetry",
        ]
    )]
    pub workspace: bool,
    /// The project name for --workspace.
    #[arg(long, requires = "workspace")]
    pub project: Option<String>,
}

/// Arguments of `login`.
#[derive(clap::Args)]
pub struct LoginArgs {
    /// TraceVault server URL
    #[arg(long)]
    pub server_url: String,
    /// Do not try to open a browser; just print the URL.
    /// Useful inside Docker / CI / SSH without X11.
    #[arg(long)]
    pub no_browser: bool,
}

/// Sub-actions for `tracevault context`.
#[derive(clap::Subcommand)]
pub enum ContextAction {
    /// Set the context, replacing any previously saved context entirely.
    ///
    /// In a linked worktree the per-worktree file is written by default.
    /// In the primary checkout the global file is written.
    /// Use --global to force the global file from anywhere.
    ///
    /// Omitted dimensions are left empty. This clears labels and params that
    /// are not re-specified.
    Set {
        /// Active flow ID to associate with events
        #[arg(long)]
        flow: Option<String>,
        /// Labels to attach (repeatable; comma-separated values accepted)
        #[arg(long)]
        label: Vec<String>,
        /// Params to attach, in key=value form (repeatable)
        #[arg(long)]
        param: Vec<String>,
        /// Write to the global context file regardless of worktree scope
        #[arg(long)]
        global: bool,
        /// Write to the resolved user-context file instead (wins over --global)
        #[arg(long)]
        user: bool,
    },
    /// Update the existing context, merging changes in.
    ///
    /// In a linked worktree the per-worktree file is updated by default.
    /// Use --global to force the global file from anywhere.
    ///
    /// Sets --flow if provided; unions --label with existing; inserts/overwrites
    /// --param keys; removes --remove-label / --remove-param entries.
    Update {
        /// New flow ID (replaces current flow if provided)
        #[arg(long)]
        flow: Option<String>,
        /// Labels to add (repeatable; comma-separated values accepted)
        #[arg(long)]
        label: Vec<String>,
        /// Params to add or overwrite, in key=value form (repeatable)
        #[arg(long)]
        param: Vec<String>,
        /// Labels to remove (repeatable; comma-separated values accepted)
        #[arg(long = "remove-label")]
        remove_label: Vec<String>,
        /// Param keys to remove (repeatable)
        #[arg(long = "remove-param")]
        remove_param: Vec<String>,
        /// Write to the global context file regardless of worktree scope
        #[arg(long)]
        global: bool,
        /// Write to the resolved user-context file instead (wins over --global)
        #[arg(long)]
        user: bool,
    },
    /// Show the current context, layer by layer (pretty JSON).
    ///
    /// Prints up to four sections: User (always; its header says whether the
    /// user layer is enabled and which file it reads), Global (repo-wide),
    /// This worktree (linked only), and Effective (the merged result that the
    /// hook stamps, each value annotated with the layer it came from).
    Show,
    /// Clear all context (flow, labels, params).
    ///
    /// In a linked worktree the per-worktree file is cleared by default.
    /// Use --global to force clearing the global file from anywhere.
    Clear {
        /// Clear the global context file regardless of worktree scope
        #[arg(long)]
        global: bool,
        /// Clear the resolved user-context file instead (wins over --global)
        #[arg(long)]
        user: bool,
    },
    /// Enable/disable or point the project's user-level context source.
    ///
    /// The mode flags are mutually exclusive: at most one may be given.
    #[command(group(clap::ArgGroup::new("source_mode").multiple(false)))]
    Source {
        /// Enable the user context at the default path
        #[arg(long, group = "source_mode")]
        enable: bool,
        /// Disable the user context
        #[arg(long, group = "source_mode")]
        disable: bool,
        /// Enable and read the user context from this explicit path
        #[arg(long, group = "source_mode")]
        path: Option<String>,
        /// Enable and clear any explicit path back to the default location
        #[arg(long, group = "source_mode")]
        default: bool,
    },
}

#[derive(clap::Subcommand)]
pub enum ProxyCmd {
    /// Print the proxy URL and setup instructions for AI tools (Claude Code,
    /// GSD2, Cursor, Codex CLI, etc.).
    Info,
}

/// Write the user-level context config during a `--global` init and print the
/// standard summary. Every agent's `--global` arm ends with this identical
/// bootstrap, so it lives in one place. Exits the process on a fatal flag error,
/// mirroring the per-arm behavior it replaces.
fn finish_global_user_context(no_user_context: bool, user_context: Option<String>) {
    let requested = match config::UserContext::from_init_flags(no_user_context, user_context) {
        Ok(r) => r,
        Err(e) => {
            eprintln!("Error: {e}");
            std::process::exit(1);
        }
    };
    match commands::init::write_global_user_config_in(&config::tv_config_root(), requested) {
        Ok(active) => {
            println!(
                "User-level context config: {}",
                config::user_config_path().display()
            );
            match active {
                Some(ctx) => println!("User-level context file: {}", ctx.display()),
                None => println!("User-level context is disabled (`--no-user-context`)."),
            }
            println!(
                "Edit it with `tracevault context set --user …`; disable with \
                 `tracevault init --global --no-user-context`."
            );
        }
        Err(e) => eprintln!("Warning: could not write user-level context config: {e}"),
    }
}

#[derive(Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum TelemetryAction {
    On,
    Off,
    Status,
}

/// What the user asked for Claude Code telemetry.
#[derive(Clone, Copy, PartialEq, Eq)]
enum TelemetryChoice {
    /// `--claude-telemetry` / `telemetry on`.
    On,
    /// `--no-claude-telemetry` / `telemetry off`.
    Off,
    /// Neither flag: on, unless the user opted out before (VIS-1109).
    Default,
}

impl TelemetryChoice {
    fn from_flags(on: bool, off: bool) -> Self {
        match (on, off) {
            (true, _) => Self::On,
            (_, true) => Self::Off,
            _ => Self::Default,
        }
    }
}

/// Record in the install state that this machine's telemetry is settled at
/// this version, so the upgrade step does not redo it, and who owns the
/// helper interval when this install found out (`added_interval`, see
/// `interval_added_by_install`). Best-effort.
fn record_telemetry_choice(opt_out: Option<bool>, added_interval: Option<bool>) {
    let result = install_state::update_in(&config::tv_config_root(), |s| {
        s.configured_version = Some(install_state::CURRENT_VERSION.to_string());
        if added_interval.is_some() {
            s.telemetry_added_interval = added_interval;
        }
        if let Some(opt_out) = opt_out {
            s.claude_telemetry_opt_out = opt_out;
            s.telemetry_auto_enabled = None;
        }
    });
    if let Err(e) = result {
        eprintln!("Warning: could not record the Claude Code telemetry choice: {e}");
    }
}

/// Configure Claude Code telemetry after a successful `init` (or for
/// `telemetry on|off`). On by default (VIS-1109): `Default` enables it
/// unless the user opted out before, asking first in a terminal. `Off`
/// removes our settings and records the opt-out, which only an explicit `On`
/// clears. `Default` never turns on telemetry while Claude Code is set to
/// export content (prompt text etc.). A failure exits non-zero only when the
/// user asked explicitly; an existing exporter setup is not a failure (it is
/// left alone, by design).
fn finish_claude_telemetry(
    choice: TelemetryChoice,
    project_root: &std::path::Path,
    server_flag: Option<&str>,
) {
    use commands::claude_telemetry::{content_logging_in, is_off, prompt, Environment};
    let Some(claude_dir) = dirs::home_dir().map(|h| h.join(".claude")) else {
        eprintln!("Error: cannot determine home directory");
        std::process::exit(1);
    };
    let config_root = config::tv_config_root();
    let env = Environment::current(&claude_dir);
    let explicit = choice != TelemetryChoice::Default;
    let content = || content_logging_in(&claude_dir, &env);
    // Ask before taking the lock below: the answer may take a while.
    let mut choice = choice;
    if choice == TelemetryChoice::Default
        && !install_state::load_in(&config_root).claude_telemetry_opt_out
        && is_off(&claude_dir)
        && content().is_empty()
        && std::io::IsTerminal::is_terminal(&std::io::stdin())
        && !prompt().unwrap_or(true)
    {
        choice = TelemetryChoice::Off;
    }
    // The upgrade step changes the same settings and state (VIS-1109).
    let _lock = match install_state::Lock::take(&config_root, std::time::Duration::from_secs(10)) {
        Ok(lock) => lock,
        Err(e) if explicit => {
            eprintln!("Error: Claude Code telemetry not changed: {e}");
            std::process::exit(1);
        }
        Err(e) => {
            eprintln!("Warning: Claude Code telemetry not configured: {e}");
            return;
        }
    };
    let state = install_state::load_in(&config_root);
    let off = |claude_dir: &std::path::Path| match commands::claude_telemetry::uninstall(
        claude_dir,
        &env,
        state.telemetry_added_interval,
    ) {
        Ok(removed) => {
            if removed {
                println!(
                    "Claude Code telemetry is off (removed TraceVault's settings from {})",
                    claude_dir.join("settings.json").display()
                );
            } else {
                println!("Claude Code telemetry is off");
            }
            record_telemetry_choice(Some(true), None);
        }
        Err(e) => {
            eprintln!("Error: could not turn Claude Code telemetry off: {e}");
            std::process::exit(1);
        }
    };
    match choice {
        TelemetryChoice::Off => return off(&claude_dir),
        TelemetryChoice::Default if state.claude_telemetry_opt_out => {
            println!(
                "Claude Code telemetry stays off, as you chose earlier \
                 (`tracevault telemetry on` to enable it)"
            );
            return;
        }
        TelemetryChoice::Default if is_off(&claude_dir) && !content().is_empty() => {
            // Not recorded: nothing was decided.
            eprintln!(
                "Warning: Claude Code telemetry not turned on: Claude Code is set to export \
                 content ({}); run `tracevault telemetry on` to send it to TraceVault anyway",
                content().join("; ")
            );
            return;
        }
        _ => {}
    }
    let interval_ours = commands::claude_telemetry::interval_added_by_install(&claude_dir);
    let result = commands::claude_telemetry::telemetry_server_url(project_root, server_flag)
        .and_then(|url| {
            commands::claude_telemetry::install(&claude_dir, &url, &env)
                .map(|outcome| (url, outcome))
                .map_err(|e| e.to_string())
        });
    match result {
        Ok((url, commands::claude_telemetry::InstallOutcome::Configured)) => {
            println!(
                "Claude Code telemetry exports to {} (configured in {}; restart Claude Code to \
                 apply; `tracevault telemetry off` to disable)",
                commands::claude_telemetry::logs_endpoint(&url),
                claude_dir.join("settings.json").display()
            );
            record_telemetry_choice(Some(false), interval_ours);
        }
        Ok((url, commands::claude_telemetry::InstallOutcome::Foreign(reasons))) => {
            eprintln!(
                "{}",
                commands::claude_telemetry::collector_instructions(&url, &reasons)
            );
            record_telemetry_choice(explicit.then_some(false), None);
        }
        Err(e) if explicit => {
            eprintln!("Error: Claude Code telemetry not configured: {e}");
            std::process::exit(1);
        }
        // Not recorded: the upgrade step retries in a later session.
        Err(e) => eprintln!("Warning: Claude Code telemetry not configured: {e}"),
    }
}

/// Commands that agents and git run from installed hooks. Their output is
/// parsed (or shown inside the agent), so nothing extra may be printed there.
pub fn is_hook_invoked(cmd: &Command) -> bool {
    matches!(
        cmd,
        Command::Stream { .. }
            | Command::SessionStart
            | Command::UserPrompt
            | Command::CommitPush
            | Command::Check
            | Command::OtelHeaders { .. }
    )
}

/// The one-line notice the `tracevault` binary prints for commands a person
/// runs; `None` for hook-invoked ones.
pub fn deprecation_notice(cmd: &Command) -> Option<&'static str> {
    if is_hook_invoked(cmd) {
        return None;
    }
    Some(
        "note: `tracevault` is deprecated and will be replaced by `visdom` (same commands under \
         `visdom trace …`; `visdom login`, `visdom init`).",
    )
}

/// Run one command. Failures print their own message and exit the process
/// with a non-zero status, exactly as the `tracevault` binary always did.
pub async fn run(cmd: Command) {
    match cmd {
        Command::Init(InitArgs {
            server_url,
            claude_settings,
            no_gitignore,
            no_user_context,
            user_context,
            global,
            agent,
            claude_telemetry,
            no_claude_telemetry,
            workspace,
            project,
        }) => {
            if workspace {
                let cwd = env::current_dir().expect("Cannot determine current directory");
                // `requires = "project"` guarantees it.
                let name = project.expect("--workspace requires --project");
                match commands::init::init_workspace(&cwd, &name, server_url.as_deref()).await {
                    Ok(bound) => {
                        println!(
                            "Workspace {} bound to project {} (id: {})",
                            cwd.display(),
                            bound.project_name,
                            bound.project_id
                        );
                        println!("Wrote {}", bound.config_path.display());
                        println!(
                            "Every session started under this directory is recorded to that \
                             project unless it runs `tracevault project switch` or binds a repo \
                             with its own configuration."
                        );
                        println!(
                            "No hooks were installed: if this machine has no global install yet, \
                             run `tracevault init --global`."
                        );
                    }
                    Err(e) => {
                        eprintln!("Error: {e}");
                        std::process::exit(1);
                    }
                }
                return;
            }
            if (claude_telemetry || no_claude_telemetry) && agent != crate::agent::Agent::ClaudeCode
            {
                eprintln!(
                    "Error: --claude-telemetry and --no-claude-telemetry only apply to \
                     --agent claude-code (use `tracevault telemetry off` instead)"
                );
                std::process::exit(1);
            }
            let telemetry = TelemetryChoice::from_flags(claude_telemetry, no_claude_telemetry);
            // Reject flag combinations that don't apply to the selected agent
            // (e.g. --claude-settings with --agent codex) rather than silently
            // ignoring them.
            if let Err(e) = commands::init::validate_init_flags(agent, claude_settings.is_some()) {
                eprintln!("Error: {e}");
                std::process::exit(1);
            }
            if global {
                // VIS-1256: `init` migrates a legacy `default_project` in any
                // mode — here, in the config the current directory's hooks
                // read — before anything is installed.
                let cwd = env::current_dir().expect("Cannot determine current directory");
                if let Err(e) = commands::init::migrate_cwd_config(&cwd).await {
                    eprintln!("Error: {e}");
                    std::process::exit(1);
                }
                // Explicit match (not `matches!(.., Codex)` + fallthrough) so a
                // future agent variant can't silently fall through to the Claude
                // Code branch and report success while installing nothing for it.
                match agent {
                    crate::agent::Agent::Codex => {
                        let codex_dir = match dirs::home_dir() {
                            Some(home) => home.join(".codex"),
                            None => {
                                eprintln!("Error: cannot determine home directory");
                                std::process::exit(1);
                            }
                        };
                        match commands::init::install_global_codex_hooks(&codex_dir) {
                            Ok(()) => {
                                println!(
                                    "Installed TraceVault Codex hooks in {}",
                                    codex_dir.join("hooks.json").display()
                                );
                                println!(
                                    "Added workspace-mode instructions to {}",
                                    codex_dir.join("AGENTS.md").display()
                                );
                                println!(
                                    "These apply to ALL Codex CLI sessions on this machine, not just this repo."
                                );
                                println!("{}", commands::init::codex_hook_trust_notice());
                            }
                            Err(e) => {
                                eprintln!("Error: {e}");
                                std::process::exit(1);
                            }
                        }

                        finish_global_user_context(no_user_context, user_context);
                        return;
                    }
                    crate::agent::Agent::Gsd => {
                        // GSD (pi) loads extensions from a user-global
                        // ~/.gsd/extensions/ directory, so a global install
                        // just runs `gsd install` without `-l`, registering
                        // the extension for ALL GSD sessions on this
                        // machine rather than one repo.
                        match commands::init::install_gsd_extension(None) {
                            Ok(()) => {
                                println!(
                                    "This applies to ALL GSD sessions on this machine, not just this repo."
                                );
                            }
                            Err(e) => {
                                eprintln!("Error: {e}");
                                std::process::exit(1);
                            }
                        }

                        finish_global_user_context(no_user_context, user_context);
                        return;
                    }
                    crate::agent::Agent::ClaudeCode => {
                        let claude_dir = match dirs::home_dir() {
                            Some(home) => home.join(".claude"),
                            None => {
                                eprintln!("Error: cannot determine home directory");
                                std::process::exit(1);
                            }
                        };
                        match commands::init::install_global_hooks(&claude_dir) {
                            Ok(()) => {
                                println!(
                                    "Installed TraceVault hooks in {}",
                                    claude_dir.join("settings.json").display()
                                );
                                println!("Updated {}", claude_dir.join("CLAUDE.md").display());
                                println!(
                                    "These apply to ALL Claude Code sessions on this machine, not just this repo."
                                );
                            }
                            Err(e) => {
                                eprintln!("Error: {e}");
                                std::process::exit(1);
                            }
                        }

                        finish_global_user_context(no_user_context, user_context);
                        let cwd = env::current_dir().expect("Cannot determine current directory");
                        finish_claude_telemetry(telemetry, &cwd, None);
                        return;
                    }
                    crate::agent::Agent::OpenCode => {
                        // OpenCode auto-loads plugins from the user-global
                        // ~/.config/opencode/plugins/ directory, so a global
                        // install writes there directly, applying to ALL
                        // OpenCode sessions on this machine rather than one
                        // repo.
                        if let Err(e) = commands::init::install_opencode_plugin(None) {
                            eprintln!("Error: {e}");
                            std::process::exit(1);
                        }
                        println!(
                            "This applies to ALL OpenCode sessions on this machine, not just this repo."
                        );

                        finish_global_user_context(no_user_context, user_context);
                        return;
                    }
                    crate::agent::Agent::Amp => {
                        // Amp loads system plugins from its user config dir
                        // for every session, so a global install writes
                        // there directly.
                        match commands::init::install_amp_plugin(None) {
                            Ok(path) => {
                                println!(
                                    "Installed the TraceVault Amp plugin in {}",
                                    path.display()
                                );
                                println!(
                                    "This applies to ALL Amp sessions on this machine, not just this repo."
                                );
                                println!("{}", commands::init::amp_headless_notice());
                            }
                            Err(e) => {
                                eprintln!("Error: {e}");
                                std::process::exit(1);
                            }
                        }

                        finish_global_user_context(no_user_context, user_context);
                        return;
                    }
                }
            }

            let cwd = env::current_dir().expect("Cannot determine current directory");
            let user_context =
                match config::UserContext::from_init_flags(no_user_context, user_context) {
                    // `None`: no flag, so `init` keeps the stored value
                    // (on by default when there is none).
                    Ok(r) => r,
                    Err(e) => {
                        eprintln!("Error: {e}");
                        std::process::exit(1);
                    }
                };
            match commands::init::init_in_directory(
                &cwd,
                server_url.as_deref(),
                claude_settings,
                no_gitignore,
                user_context,
                agent,
            )
            .await
            {
                Ok(entry) => {
                    println!("TraceVault initialized in {}", cwd.display());
                    if entry.is_empty() {
                        // GSD (pi): the extension lives in the user-global
                        // ~/.gsd/extensions/tracevault/, not in the repo — there's
                        // no per-repo hook file to report or gitignore.
                        println!(
                            "{} extension installed (~/.gsd/extensions/tracevault/)",
                            agent.label()
                        );
                        println!("Git hooks installed (pre-push, post-commit)");
                        println!("Added .tracevault/ to .gitignore");
                    } else {
                        println!("{} hooks installed ({entry})", agent.label());
                        println!("Git hooks installed (pre-push, post-commit)");
                        println!("Added .tracevault/ and {entry} to .gitignore");
                    }
                    println!(
                        "Nothing needs to be committed — all TraceVault files are local only."
                    );
                    println!(
                        "Other contributors run `tracevault init` to set up their own local hooks."
                    );
                    if agent == crate::agent::Agent::ClaudeCode {
                        finish_claude_telemetry(telemetry, &cwd, server_url.as_deref());
                    }
                }
                Err(e) => {
                    eprintln!("Error: {e}");
                    std::process::exit(1);
                }
            }
        }
        Command::Status { session_id } => {
            let cwd = env::current_dir().expect("Cannot determine current directory");
            let project_root = crate::paths::resolve_project_root(&cwd).root;
            let effective = commands::status::effective_session_id(
                session_id,
                crate::session_state::env_session_id(),
            );
            let code =
                commands::status::run_status(&project_root, &cwd, effective.as_deref()).await;
            if code != 0 {
                std::process::exit(code);
            }
        }
        Command::OtelHeaders { server_url } => {
            let cwd = env::current_dir().expect("Cannot determine current directory");
            match commands::claude_telemetry::otel_headers(&cwd, server_url.as_deref()).await {
                Ok(headers) => println!("{headers}"),
                Err(e) => {
                    eprintln!("tracevault otel-headers: {e}");
                    std::process::exit(1);
                }
            }
        }
        Command::Telemetry { action } => {
            let cwd = env::current_dir().expect("Cannot determine current directory");
            let project_root = crate::paths::resolve_project_root(&cwd).root;
            match action {
                TelemetryAction::On => {
                    finish_claude_telemetry(TelemetryChoice::On, &project_root, None)
                }
                TelemetryAction::Off => {
                    finish_claude_telemetry(TelemetryChoice::Off, &project_root, None)
                }
                TelemetryAction::Status => {
                    let server_url = crate::credentials::resolve_credentials_quiet(&project_root)
                        .ok()
                        .and_then(|(url, _)| url);
                    println!(
                        "{}",
                        commands::status::telemetry_status_line(server_url.as_deref())
                    );
                }
            }
        }
        Command::Stream { event, agent } => {
            if let Err(e) = commands::stream::run_stream(&event, agent).await {
                eprintln!("Stream error: {e}");
            }
        }
        Command::SessionStart => {
            // The hook itself always prints a valid HookOutput JSON payload
            // before returning; an Err here is a genuine last-resort case
            // (e.g. stdin unreadable) and — same as `Stream` — must never
            // turn into a non-zero exit, which would block the Claude Code
            // session from starting.
            if let Err(e) = commands::session_start::run().await {
                eprintln!("SessionStart error: {e}");
            }
        }
        Command::UserPrompt => {
            // Same reasoning as `SessionStart`: this hook always prints a
            // valid HookOutput JSON payload before returning; an Err here
            // must never turn into a non-zero exit, which would block the
            // prompt from being submitted.
            if let Err(e) = commands::user_prompt::run().await {
                eprintln!("UserPromptSubmit error: {e}");
            }
        }
        Command::Check => {
            let cwd = env::current_dir().expect("Cannot determine current directory");
            let project_root = crate::paths::resolve_project_root(&cwd).root;
            if let Err(e) = commands::check::check_policies(&project_root, &cwd).await {
                eprintln!("Check error: {e}");
                std::process::exit(1);
            }
        }
        Command::Sync => {
            let cwd = env::current_dir().expect("Cannot determine current directory");
            let project_root = crate::paths::resolve_project_root(&cwd).root;
            if let Err(e) = commands::sync::sync_repo(&project_root).await {
                eprintln!("Sync error: {e}");
                std::process::exit(1);
            }
        }
        Command::Stats => {
            let cwd = env::current_dir().expect("Cannot determine current directory");
            let project_root = crate::paths::resolve_project_root(&cwd).root;
            if let Err(e) = commands::stats::show_stats(&project_root) {
                eprintln!("Stats error: {e}");
            }
        }
        Command::Login(LoginArgs {
            server_url,
            no_browser,
        }) => {
            if let Err(e) = commands::login::login(&server_url, no_browser).await {
                eprintln!("Login error: {e}");
                // Non-zero exit matters here: a scripted `tracevault login &&
                // ...`, and above all the "account has no `tracevault`
                // grant" case (which saves credentials but is NOT a usable
                // login), must not look like success.
                std::process::exit(1);
            }
        }
        Command::Logout => {
            if let Err(e) = commands::logout::logout().await {
                eprintln!("Logout error: {e}");
                std::process::exit(1);
            }
        }
        Command::CommitPush => {
            let cwd = env::current_dir().expect("Cannot determine current directory");
            let project_root = crate::paths::resolve_project_root(&cwd).root;
            if let Err(e) = commands::commit_push::run_commit_push(&project_root, &cwd).await {
                eprintln!("Commit push error: {e}");
            }
        }
        Command::Flush => {
            let cwd = env::current_dir().expect("Cannot determine current directory");
            let project_root = crate::paths::resolve_project_root(&cwd).root;
            if let Err(e) = commands::flush::run_flush(&project_root).await {
                eprintln!("Flush error: {e}");
            }
        }
        Command::Verify { commits, range } => {
            let cwd = env::current_dir().expect("Cannot determine current directory");
            let project_root = crate::paths::resolve_project_root(&cwd).root;
            if let Err(e) =
                commands::verify::verify(&project_root, &cwd, commits.as_deref(), range.as_deref())
                    .await
            {
                eprintln!("Verify error: {e}");
                std::process::exit(1);
            }
        }
        Command::VerifyStart { session_id } => {
            let cwd = env::current_dir().expect("Cannot determine current directory");
            let project_root = crate::paths::resolve_project_root(&cwd).root;
            let env_session_id = crate::session_state::env_session_id();
            if let Err(e) = commands::verification_phase::open_verification_phase(
                &project_root,
                &cwd,
                session_id.as_deref(),
                env_session_id.as_deref(),
            )
            .await
            {
                eprintln!("Error: {e}");
                std::process::exit(1);
            }
        }
        Command::AgentPolicies => {
            let cwd = env::current_dir().expect("Cannot determine current directory");
            let project_root = crate::paths::resolve_project_root(&cwd).root;
            if let Err(e) = commands::agent_policies::run(&project_root).await {
                eprintln!("Error: {e}");
                std::process::exit(1);
            }
        }
        Command::Proxy { cmd } => match cmd {
            ProxyCmd::Info => {
                let code = commands::proxy::run_proxy_info();
                if code != 0 {
                    std::process::exit(code);
                }
            }
        },
        Command::Context { action } => {
            let cwd = env::current_dir().expect("Cannot determine current directory");
            let result = match action {
                ContextAction::Set {
                    flow,
                    label,
                    param,
                    global,
                    user,
                } => commands::context::run_set(&cwd, flow, label, param, global, user),
                ContextAction::Update {
                    flow,
                    label,
                    param,
                    remove_label,
                    remove_param,
                    global,
                    user,
                } => commands::context::run_update(
                    &cwd,
                    flow,
                    label,
                    param,
                    remove_label,
                    remove_param,
                    global,
                    user,
                ),
                ContextAction::Show => commands::context::run_show(&cwd),
                ContextAction::Clear { global, user } => {
                    commands::context::run_clear(&cwd, global, user)
                }
                ContextAction::Source {
                    enable,
                    disable,
                    path,
                    default,
                } => commands::context::run_source(&cwd, enable, disable, path, default),
            };
            if let Err(e) = result {
                eprintln!("Context error: {e}");
                std::process::exit(1);
            }
        }
        Command::Repo { cmd } => {
            let cwd = env::current_dir().expect("Cannot determine current directory");
            let project_root = crate::paths::resolve_project_root(&cwd).root;
            if let Err(e) = commands::repo::run(cmd, &project_root, &cwd).await {
                eprintln!("Repo error: {e}");
                std::process::exit(1);
            }
        }
        Command::Project { cmd } => {
            let cwd = env::current_dir().expect("Cannot determine current directory");
            let project_root = crate::paths::resolve_project_root(&cwd).root;
            if let Err(e) = commands::project::run(cmd, &project_root, &cwd).await {
                eprintln!("Project error: {e}");
                std::process::exit(1);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{deprecation_notice, Command};
    use clap::Parser;

    #[derive(Parser)]
    #[command(name = "tracevault")]
    struct Cli {
        #[command(subcommand)]
        _command: Command,
    }

    #[test]
    fn deprecation_notice_skips_hook_commands() {
        for cmd in [
            Command::SessionStart,
            Command::Check,
            Command::CommitPush,
            Command::UserPrompt,
        ] {
            assert!(deprecation_notice(&cmd).is_none());
        }
    }

    #[test]
    fn deprecation_notice_for_interactive_commands() {
        for cmd in [Command::Stats, Command::Logout] {
            let notice = deprecation_notice(&cmd).expect("a notice");
            assert!(notice.contains("visdom"), "{notice}");
        }
    }

    #[test]
    fn init_user_context_flags_conflict() {
        // `--no-user-context` and `--user-context <path>` are mutually exclusive
        // and must be rejected up front rather than silently prioritizing one.
        // `Cli` has no `Debug` impl, so match instead of `expect_err`.
        let err = match Cli::try_parse_from([
            "tracevault",
            "init",
            "--no-user-context",
            "--user-context",
            "/tmp/ctx.json",
        ]) {
            Ok(_) => panic!("both flags together must be a parse error"),
            Err(e) => e,
        };
        assert_eq!(err.kind(), clap::error::ErrorKind::ArgumentConflict);
    }

    #[test]
    fn init_user_context_flags_are_ok_alone() {
        assert!(Cli::try_parse_from(["tracevault", "init", "--no-user-context"]).is_ok());
        assert!(
            Cli::try_parse_from(["tracevault", "init", "--user-context", "/tmp/ctx.json"]).is_ok()
        );
    }

    #[test]
    fn context_source_mode_flags_conflict() {
        // The `source` mode flags are mutually exclusive; two together must be a
        // parse-time conflict rather than relying on run_source precedence.
        for extra in [["--enable", "--disable"], ["--disable", "--default"]] {
            let err = match Cli::try_parse_from(
                ["tracevault", "context", "source"].into_iter().chain(extra),
            ) {
                Ok(_) => panic!("{extra:?} together must be a parse error"),
                Err(e) => e,
            };
            assert_eq!(err.kind(), clap::error::ErrorKind::ArgumentConflict);
        }
        // --path with --disable also conflicts.
        let err = match Cli::try_parse_from([
            "tracevault",
            "context",
            "source",
            "--path",
            "/tmp/ctx.json",
            "--disable",
        ]) {
            Ok(_) => panic!("--path with --disable must be a parse error"),
            Err(e) => e,
        };
        assert_eq!(err.kind(), clap::error::ErrorKind::ArgumentConflict);
    }

    #[test]
    fn context_source_single_mode_is_ok() {
        assert!(Cli::try_parse_from(["tracevault", "context", "source", "--enable"]).is_ok());
        assert!(Cli::try_parse_from([
            "tracevault",
            "context",
            "source",
            "--path",
            "/tmp/ctx.json"
        ])
        .is_ok());
    }

    /// Rendered `--help` of the subcommand at `path`, whitespace-collapsed so
    /// assertions don't depend on line wrapping.
    fn long_help(path: &[&str]) -> String {
        use clap::CommandFactory;
        let mut cmd = Cli::command();
        let mut sub = &mut cmd;
        for name in path {
            sub = sub
                .find_subcommand_mut(name)
                .unwrap_or_else(|| panic!("no subcommand {name}"));
        }
        sub.render_long_help()
            .to_string()
            .split_whitespace()
            .collect::<Vec<_>>()
            .join(" ")
    }

    #[test]
    fn init_help_names_every_agent_install_target() {
        let help = long_help(&["init"]);
        for needle in [
            ".codex/hooks.json",
            "gsd install -l",
            ".opencode/plugins/tracevault.ts",
            "~/.codex/",
            "OpenCode plugin",
            ".amp/plugins/tracevault/index.ts",
            "$XDG_CONFIG_HOME/amp/plugins/",
            "~/.config/amp/plugins/",
            "--server-url, --claude-settings and --no-gitignore",
        ] {
            assert!(
                help.contains(needle),
                "init --help lacks {needle:?}: {help}"
            );
        }
        assert!(!help.contains("for ALL Claude Code sessions"), "{help}");
        // The opencode value's clap-naming note is an implementation comment.
        assert!(!help.contains("kebab-case"), "{help}");
    }

    #[test]
    fn hook_command_help_says_per_repo_init_installs_them() {
        for name in ["session-start", "user-prompt"] {
            let help = long_help(&[name]);
            assert!(help.contains("per-repo or --global"), "{name}: {help}");
            assert!(help.contains("Codex hooks.json"), "{name}: {help}");
        }
    }

    #[test]
    fn context_show_help_lists_the_user_section() {
        let help = long_help(&["context", "show"]);
        assert!(help.contains("User (always;"), "{help}");
        assert!(!help.contains("three sections"), "{help}");
    }
}