tracevault-cli 0.29.7

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
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
//! Claude Code OpenTelemetry export to Visdom (VIS-1081): `init
//! --claude-telemetry` and `tracevault otel-headers`. On by default since
//! VIS-1109; `--no-claude-telemetry` removes our settings again ([`uninstall`]).
//!
//! Claude Code reports its own cost per API call (`api_request.cost_usd`) only
//! over OpenTelemetry. `init --claude-telemetry` points its log exporter at the
//! server's `/otlp/v1/logs` receiver, in the USER-level `~/.claude/settings.json`
//! (Claude Code ignores OTel exporter variables in a repository's settings).
//! The bearer token is never written there: `otelHeadersHelper` runs
//! `tracevault otel-headers`, which prints it from the credential store.
//!
//! Claude Code applies the helper's headers to every OTLP exporter it runs, so
//! an existing exporter setup (the user's own collector, metrics, a static
//! header) is never merged with ours: it would receive Visdom's token.
//! Such a setup is left untouched and the collector route is printed instead.

use crate::api_client::ApiClient;
use crate::credentials::{same_server, Credential};
use crate::program::{ENV, TOP};
use serde_json::{json, Value};
use std::fs;
use std::io::{self, BufRead, IsTerminal, Write};
use std::path::Path;

pub const ENABLE_TELEMETRY: &str = "CLAUDE_CODE_ENABLE_TELEMETRY";
pub const LOGS_EXPORTER: &str = "OTEL_LOGS_EXPORTER";
pub const LOGS_PROTOCOL: &str = "OTEL_EXPORTER_OTLP_LOGS_PROTOCOL";
pub const LOGS_ENDPOINT: &str = "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT";
/// How often Claude Code re-runs the headers helper. Its default (29 minutes)
/// outlives a Keycloak access token (5 minutes), so the header would go stale.
pub const HELPER_INTERVAL: &str = "CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS";
pub const HEADERS_HELPER: &str = "otelHeadersHelper";

/// Path of the server's OTLP logs receiver (VIS-1079).
const LOGS_PATH: &str = "/otlp/v1/logs";
/// Every 3 minutes, in milliseconds (see [`HELPER_INTERVAL`]).
const HELPER_INTERVAL_MS: &str = "180000";
/// The validity `otel-headers` guarantees a token has: one helper interval
/// plus a minute of slack, so the header outlives the gap to the next run.
pub const HEADER_MIN_VALID_SECS: i64 = 180 + 60;
/// The subcommand our helper command runs, after `tracevault` or
/// `visdom trace`. Anything else is the user's own.
const HELPER_SUBCOMMAND: &str = "otel-headers";

/// What follows `otel-headers` when `helper` is our command.
fn helper_arguments(helper: &str) -> Option<&str> {
    crate::program::subcommand(helper)?
        .strip_prefix(HELPER_SUBCOMMAND)
        .filter(|rest| rest.is_empty() || rest.starts_with(' '))
}

/// `<server>/otlp/v1/logs`.
pub fn logs_endpoint(server_url: &str) -> String {
    format!("{}{LOGS_PATH}", server_url.trim_end_matches('/'))
}

/// The `otelHeadersHelper` command. It names the server so `otel-headers`
/// can refuse to hand a token for another instance to this endpoint.
pub fn helper_command(server_url: &str) -> String {
    helper_command_for(server_url, crate::program::is_visdom())
}

/// [`helper_command`] for the binary chosen by `visdom`.
fn helper_command_for(server_url: &str, visdom: bool) -> String {
    format!(
        "{} {HELPER_SUBCOMMAND} --server-url {}",
        crate::program::name(visdom),
        server_url.trim_end_matches('/')
    )
}

/// The server URL must be an http(s) URL that is safe to put unquoted into
/// the helper's command line, which Claude Code runs through a shell.
fn validate_server_url(server_url: &str) -> Result<(), String> {
    let parsed = url::Url::parse(server_url)
        .map_err(|e| format!("invalid Visdom server URL `{server_url}`: {e}"))?;
    if !matches!(parsed.scheme(), "http" | "https") {
        return Err(format!(
            "Visdom server URL `{server_url}` must be http:// or https://"
        ));
    }
    let shell_safe = server_url
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || ":/._~%-".contains(c));
    if !shell_safe {
        return Err(format!(
            "Visdom server URL `{server_url}` contains characters that cannot go into \
             Claude Code's otelHeadersHelper command"
        ));
    }
    Ok(())
}

fn is_our_helper(value: &Value) -> bool {
    value
        .as_str()
        .is_some_and(|s| helper_arguments(s).is_some())
}

/// The receiver of the server our helper command names, if `helper` is ours
/// and names one.
fn helper_logs_endpoint(helper: Option<&Value>) -> Option<String> {
    helper
        .and_then(Value::as_str)
        .and_then(helper_arguments)
        .and_then(|rest| rest.trim().strip_prefix("--server-url "))
        .map(|server| logs_endpoint(server.trim()))
}

fn as_text(value: &Value) -> String {
    match value {
        Value::String(s) => s.clone(),
        other => other.to_string(),
    }
}

/// What, besides `~/.claude/settings.json`, decides where Claude Code's
/// telemetry goes: the managed settings Claude Code applies above the user's
/// (each with a label naming its source), and the `OTEL_*` variables of the
/// environment `init`/`status` runs in, which Claude Code also sees when
/// started from it.
#[derive(Debug, Default)]
pub struct Environment {
    pub managed: Vec<(String, Value)>,
    pub shell: Vec<(String, String)>,
}

impl Environment {
    /// This machine's: the file-based managed settings (`managed-settings.json`
    /// and `managed-settings.d/*.json` in the system directory), the cached
    /// server-managed settings (`<claude_dir>/remote-settings.json`), and the
    /// process environment. MDM profiles and registry policies are not read.
    pub fn current(claude_dir: &Path) -> Self {
        let system_dir = if cfg!(target_os = "macos") {
            Path::new("/Library/Application Support/ClaudeCode")
        } else if cfg!(windows) {
            Path::new(r"C:\Program Files\ClaudeCode")
        } else {
            Path::new("/etc/claude-code")
        };
        let mut files = vec![system_dir.join("managed-settings.json")];
        if let Ok(entries) = fs::read_dir(system_dir.join("managed-settings.d")) {
            let mut drop_ins: Vec<_> = entries
                .filter_map(|e| e.ok().map(|e| e.path()))
                .filter(|p| {
                    p.extension().is_some_and(|x| x == "json")
                        && !p
                            .file_name()
                            .is_some_and(|n| n.to_string_lossy().starts_with('.'))
                })
                .collect();
            drop_ins.sort();
            files.extend(drop_ins);
        }
        files.push(claude_dir.join("remote-settings.json"));
        let managed = files
            .into_iter()
            .filter_map(|path| {
                let doc = serde_json::from_str(&fs::read_to_string(&path).ok()?).ok()?;
                Some((path.display().to_string(), doc))
            })
            .collect();
        Self {
            managed,
            shell: std::env::vars()
                .filter(|(k, _)| k.starts_with("OTEL_") || k == "BETA_TRACING_ENDPOINT")
                .collect(),
        }
    }
}

/// Exporter settings that are not Visdom's, each described for the user
/// (header values are never printed). `settings` is the parsed
/// `~/.claude/settings.json`, `env` what else decides (see [`Environment`]).
/// An endpoint counts as ours when it is `expected`, or — only in the user
/// file, which a re-run rewrites — the receiver of the server our helper names
/// (an install for another server). Anywhere else (managed settings, the
/// shell) it must be `expected`: those keep routing exports after the helper
/// moves to a new server, which would send the new server's token to the old
/// one. An OTLP protocol other than HTTP from there is foreign too: it would
/// override ours, and helper headers only apply over HTTP (the receiver takes
/// both `http/protobuf` and `http/json`). The same goes for our own helper
/// there: it must name the `expected` server, since it overrides ours. Detailed
/// beta tracing is foreign as well: with it, Claude Code sends its logs to
/// `BETA_TRACING_ENDPOINT` instead.
pub fn foreign_exporter_settings(
    settings: &Value,
    env: &Environment,
    expected_endpoint: Option<&str>,
) -> Vec<String> {
    let helper_endpoint = helper_logs_endpoint(settings.get(HEADERS_HELPER));
    let mut reasons = Vec::new();
    let docs = std::iter::once(("~/.claude/settings.json", settings, true)).chain(
        env.managed
            .iter()
            .map(|(label, doc)| (label.as_str(), doc, false)),
    );
    let mut entries = Vec::new();
    for (label, doc, user_file) in docs {
        if let Some(h) = doc.get(HEADERS_HELPER) {
            let ours = if user_file {
                is_our_helper(h)
            } else {
                expected_endpoint.is_some()
                    && helper_logs_endpoint(Some(h)).as_deref() == expected_endpoint
            };
            if !ours {
                reasons.push(format!("{HEADERS_HELPER} = `{}` (in {label})", as_text(h)));
            }
        }
        if let Some(vars) = doc.get("env").and_then(Value::as_object) {
            entries.extend(
                vars.iter()
                    .map(|(k, v)| (k.clone(), as_text(v), label, user_file)),
            );
        }
    }
    entries.extend(
        env.shell
            .iter()
            .map(|(k, v)| (k.clone(), v.clone(), "the shell environment", false)),
    );
    for (key, value, source, user_file) in entries {
        let foreign = match key.as_str() {
            LOGS_EXPORTER => value != "otlp",
            "OTEL_METRICS_EXPORTER" | "OTEL_TRACES_EXPORTER" => {
                !matches!(value.as_str(), "" | "none")
            }
            LOGS_ENDPOINT => {
                expected_endpoint != Some(value.as_str())
                    && !(user_file && helper_endpoint.as_deref() == Some(value.as_str()))
            }
            LOGS_PROTOCOL | "OTEL_EXPORTER_OTLP_PROTOCOL" if !user_file => {
                !matches!(value.as_str(), "http/protobuf" | "http/json")
            }
            "BETA_TRACING_ENDPOINT" => true,
            k if k.starts_with("OTEL_EXPORTER_OTLP_") && k.ends_with("ENDPOINT") => true,
            k if k.starts_with("OTEL_EXPORTER_OTLP_") && k.ends_with("HEADERS") => {
                reasons.push(format!("{key} is set (in {source})"));
                continue;
            }
            _ => false,
        };
        if foreign {
            reasons.push(format!("{key}={value} (in {source})"));
        }
    }
    reasons
}

/// What `init --claude-telemetry` did to `~/.claude/settings.json`.
#[derive(Debug, PartialEq, Eq)]
pub enum InstallOutcome {
    /// Written (or already exactly so) for this server.
    Configured,
    /// Another exporter setup is present; nothing was changed.
    Foreign(Vec<String>),
}

/// Bring `settings` to export Claude Code's logs to `server_url`, unless
/// another exporter setup is present (then nothing is changed). Every key we
/// do not own is kept; a helper interval the user set is theirs to keep.
pub fn merge_telemetry(
    settings: &mut Value,
    server_url: &str,
    env: &Environment,
) -> io::Result<InstallOutcome> {
    let endpoint = logs_endpoint(server_url);
    let root = settings.as_object_mut().ok_or_else(|| {
        io::Error::new(
            io::ErrorKind::InvalidData,
            "~/.claude/settings.json is not a JSON object",
        )
    })?;
    if root.get("env").is_some_and(|e| !e.is_object()) {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            "~/.claude/settings.json \"env\" is not a JSON object",
        ));
    }
    let reasons = foreign_exporter_settings(&Value::Object(root.clone()), env, Some(&endpoint));
    if !reasons.is_empty() {
        return Ok(InstallOutcome::Foreign(reasons));
    }

    let env = root
        .entry("env")
        .or_insert_with(|| json!({}))
        .as_object_mut()
        .expect("checked above");
    for (key, value) in [
        (ENABLE_TELEMETRY, "1"),
        (LOGS_EXPORTER, "otlp"),
        (LOGS_PROTOCOL, "http/protobuf"),
        (LOGS_ENDPOINT, endpoint.as_str()),
    ] {
        env.insert(key.to_string(), json!(value));
    }
    env.entry(HELPER_INTERVAL)
        .or_insert_with(|| json!(HELPER_INTERVAL_MS));
    // The helper names the binary that installs it — and `visdom` still,
    // once it does (see `crate::program`).
    let visdom = crate::program::installs_visdom(
        root.get(HEADERS_HELPER)
            .and_then(Value::as_str)
            .is_some_and(crate::program::is_visdom_command),
    );
    root.insert(
        HEADERS_HELPER.to_string(),
        json!(helper_command_for(server_url, visdom)),
    );
    Ok(InstallOutcome::Configured)
}

/// [`merge_telemetry`] applied to `<claude_dir>/settings.json` (created if
/// absent, written atomically, untouched when already current or foreign).
pub fn install(
    claude_dir: &Path,
    server_url: &str,
    env: &Environment,
) -> io::Result<InstallOutcome> {
    validate_server_url(server_url).map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?;
    fs::create_dir_all(claude_dir)?;
    let base = claude_dir.canonicalize()?;
    let path = crate::commands::init::safe_join(&base, "settings.json")?;
    let mut outcome = InstallOutcome::Configured;
    crate::commands::init::update_json_file(&path, "Claude Code telemetry", |root| {
        outcome = merge_telemetry(root, server_url, env)?;
        Ok(())
    })?;
    Ok(outcome)
}

/// Bring `settings` back to what it was before [`merge_telemetry`]: our
/// `otelHeadersHelper`, and the `env` entries that still hold the values we
/// write. The exporter entries are recognised by the endpoint our helper
/// names, so without our helper nothing in `env` is touched (it could be
/// anyone's). `CLAUDE_CODE_ENABLE_TELEMETRY` and `OTEL_LOGS_EXPORTER` stay
/// when another exporter still uses them — in this file, the managed settings
/// or the shell (`outside`; our own endpoint there, inherited by a shell
/// Claude Code started, is not another exporter). The helper interval goes
/// only when `added_interval` says we added it (`None`: not known, for an
/// install older than that record; then our value counts as ours).
/// Returns whether anything was removed.
pub fn remove_telemetry(
    settings: &mut Value,
    outside: &Environment,
    added_interval: Option<bool>,
) -> io::Result<bool> {
    let root = settings.as_object_mut().ok_or_else(|| {
        io::Error::new(
            io::ErrorKind::InvalidData,
            "~/.claude/settings.json is not a JSON object",
        )
    })?;
    if !root.get(HEADERS_HELPER).is_some_and(is_our_helper) {
        return Ok(false);
    }
    let ours = helper_logs_endpoint(root.remove(HEADERS_HELPER).as_ref());
    let Some(env) = root.get_mut("env").and_then(Value::as_object_mut) else {
        return Ok(true);
    };
    let holds = |env: &serde_json::Map<String, Value>, key: &str, value: &str| {
        env.get(key).is_some_and(|v| as_text(v) == value)
    };
    // The interval only paces our helper, which is gone.
    if added_interval != Some(false) && holds(env, HELPER_INTERVAL, HELPER_INTERVAL_MS) {
        env.remove(HELPER_INTERVAL);
    }
    // The exporter entries are ours while the endpoint is ours or gone; once
    // the user pointed it elsewhere, they serve the user's own exporter.
    let endpoint_ours_or_gone = match env.get(LOGS_ENDPOINT).map(as_text) {
        None => true,
        Some(e) => ours.as_deref() == Some(e.as_str()),
    };
    if endpoint_ours_or_gone {
        env.remove(LOGS_ENDPOINT);
        if holds(env, LOGS_PROTOCOL, "http/protobuf") {
            env.remove(LOGS_PROTOCOL);
        }
        let is_exporter = |k: &str, v: &str| match k {
            "OTEL_METRICS_EXPORTER" | "OTEL_TRACES_EXPORTER" => !matches!(v, "" | "none"),
            LOGS_ENDPOINT if ours.as_deref() == Some(v) => false,
            k => k.starts_with("OTEL_EXPORTER_OTLP_") && k.ends_with("ENDPOINT"),
        };
        let other_exporter = env
            .iter()
            .map(|(k, v)| (k.clone(), as_text(v)))
            .chain(
                outside
                    .managed
                    .iter()
                    .filter_map(|(_, doc)| doc.get("env").and_then(Value::as_object))
                    .flatten()
                    .map(|(k, v)| (k.clone(), as_text(v))),
            )
            .chain(outside.shell.iter().cloned())
            .any(|(k, v)| is_exporter(&k, &v));
        if !other_exporter {
            for (key, value) in [(LOGS_EXPORTER, "otlp"), (ENABLE_TELEMETRY, "1")] {
                if holds(env, key, value) {
                    env.remove(key);
                }
            }
        }
    }
    if env.is_empty() {
        root.remove("env");
    }
    Ok(true)
}

/// [`remove_telemetry`] applied to `<claude_dir>/settings.json` (untouched
/// when absent or holding nothing of ours). Returns whether anything was
/// removed.
pub fn uninstall(
    claude_dir: &Path,
    outside: &Environment,
    added_interval: Option<bool>,
) -> io::Result<bool> {
    if !claude_dir.join("settings.json").exists() {
        return Ok(false);
    }
    let base = claude_dir.canonicalize()?;
    let path = crate::commands::init::safe_join(&base, "settings.json")?;
    let mut removed = false;
    crate::commands::init::update_json_file(&path, "Claude Code telemetry", |root| {
        removed = remove_telemetry(root, outside, added_interval)?;
        Ok(())
    })?;
    Ok(removed)
}

/// Who will own the helper interval after [`install`] (whose merge keeps an
/// existing one), checked before it runs, for the caller to record:
/// `Some(true)` when the install will add it, `Some(false)` when the user
/// already set it without our telemetry, and `None` when it sits next to our
/// own helper already (an earlier install: keep what was recorded).
pub fn interval_added_by_install(claude_dir: &Path) -> Option<bool> {
    let settings = fs::read_to_string(claude_dir.join("settings.json"))
        .ok()
        .and_then(|s| serde_json::from_str::<Value>(&s).ok())
        .unwrap_or_else(|| json!({}));
    if settings["env"].get(HELPER_INTERVAL).is_none() {
        Some(true)
    } else if settings.get(HEADERS_HELPER).is_some_and(is_our_helper) {
        None
    } else {
        Some(false)
    }
}

/// Claude Code variables that add content (prompt text, tool input and
/// output, responses, raw API bodies) to the telemetry it exports. All are off
/// by default, and Visdom never sets them.
const CONTENT_LOGGING: [&str; 5] = [
    "OTEL_LOG_USER_PROMPTS",
    "OTEL_LOG_TOOL_DETAILS",
    "OTEL_LOG_TOOL_CONTENT",
    "OTEL_LOG_ASSISTANT_RESPONSES",
    "OTEL_LOG_RAW_API_BODIES",
];

/// Content-logging variables switched on in `settings`'s `env`, the managed
/// settings or the shell (see [`Environment`]). Turning telemetry on without
/// the user asking must not send that content, so the upgrade step skips it
/// while any is on.
pub fn content_logging_settings(settings: &Value, env: &Environment) -> Vec<String> {
    let docs = std::iter::once(("~/.claude/settings.json", settings))
        .chain(env.managed.iter().map(|(label, doc)| (label.as_str(), doc)));
    let mut entries: Vec<(String, String, &str)> = Vec::new();
    for (label, doc) in docs {
        if let Some(vars) = doc.get("env").and_then(Value::as_object) {
            entries.extend(vars.iter().map(|(k, v)| (k.clone(), as_text(v), label)));
        }
    }
    entries.extend(
        env.shell
            .iter()
            .map(|(k, v)| (k.clone(), v.clone(), "the shell environment")),
    );
    entries
        .into_iter()
        .filter(|(key, value, _)| {
            CONTENT_LOGGING.contains(&key.as_str())
                && !matches!(value.trim().to_lowercase().as_str(), "" | "0" | "false")
        })
        .map(|(key, value, source)| format!("{key}={value} (in {source})"))
        .collect()
}

/// [`content_logging_settings`] for `<claude_dir>/settings.json` (missing or
/// unparseable: `{}`).
pub fn content_logging_in(claude_dir: &Path, env: &Environment) -> Vec<String> {
    let settings = fs::read_to_string(claude_dir.join("settings.json"))
        .ok()
        .and_then(|s| serde_json::from_str::<Value>(&s).ok())
        .unwrap_or_else(|| json!({}));
    content_logging_settings(&settings, env)
}

/// Telemetry as `status` reports it.
#[derive(Debug, PartialEq, Eq)]
pub enum TelemetryState {
    /// No Visdom telemetry settings.
    Off,
    /// Visdom's settings, with whatever is missing or wrong in them.
    Ours {
        endpoint: Option<String>,
        missing: Vec<&'static str>,
    },
    /// Another exporter setup; `ours_too` when our helper is also installed,
    /// i.e. Visdom's token goes to those exporters as well.
    Foreign {
        reasons: Vec<String>,
        ours_too: bool,
    },
}

pub fn inspect(
    settings: &Value,
    env: &Environment,
    expected_endpoint: Option<&str>,
) -> TelemetryState {
    let helper_ours = settings.get(HEADERS_HELPER).is_some_and(is_our_helper);
    let reasons = foreign_exporter_settings(settings, env, expected_endpoint);
    if !reasons.is_empty() {
        return TelemetryState::Foreign {
            reasons,
            ours_too: helper_ours,
        };
    }
    let env = settings.get("env");
    let get = |key: &str| env.and_then(|e| e.get(key)).map(as_text);
    let endpoint = get(LOGS_ENDPOINT);
    if !helper_ours && endpoint.is_none() {
        return TelemetryState::Off;
    }
    let mut missing = Vec::new();
    if get(ENABLE_TELEMETRY).as_deref() != Some("1") {
        missing.push(ENABLE_TELEMETRY);
    }
    if get(LOGS_EXPORTER).as_deref() != Some("otlp") {
        missing.push(LOGS_EXPORTER);
    }
    if get(LOGS_PROTOCOL).as_deref() != Some("http/protobuf") {
        missing.push(LOGS_PROTOCOL);
    }
    if endpoint.is_none() {
        missing.push(LOGS_ENDPOINT);
    }
    if !helper_ours {
        missing.push(HEADERS_HELPER);
    }
    TelemetryState::Ours { endpoint, missing }
}

/// What to do instead when Claude Code telemetry already goes elsewhere: send
/// a copy of the `api_request` events to Visdom from the user's own
/// OpenTelemetry Collector.
pub fn collector_instructions(server_url: &str, reasons: &[String]) -> String {
    let server = server_url.trim_end_matches('/');
    let mut out = String::from(
        "Claude Code telemetry is already exported elsewhere, so Visdom left \
         ~/.claude/settings.json unchanged:\n",
    );
    for r in reasons {
        out.push_str(&format!("  - {r}\n"));
    }
    out.push_str(&format!(
        "To also send Claude Code's cost to Visdom, forward its `api_request` events from \
         your OpenTelemetry Collector (authenticate with a Visdom API key):\n\
         \n\
         processors:\n\
         \x20 filter/visdom:\n\
         \x20   error_mode: ignore\n\
         \x20   logs:\n\
         \x20     log_record:\n\
         \x20       - 'attributes[\"event.name\"] != \"api_request\"'\n\
         exporters:\n\
         \x20 otlphttp/visdom:\n\
         \x20   endpoint: {server}/otlp\n\
         \x20   headers:\n\
         \x20     Authorization: \"Bearer ${{env:{ENV}_API_KEY}}\"\n\
         service:\n\
         \x20 pipelines:\n\
         \x20   logs/visdom:\n\
         \x20     receivers: [otlp]\n\
         \x20     processors: [filter/visdom]\n\
         \x20     exporters: [otlphttp/visdom]\n"
    ));
    out
}

/// The server telemetry is exported to: the one the resolved credential
/// belongs to. `flag` (`init --server-url`) must agree with it, since
/// `otel-headers` will only ever hand out that credential.
pub fn telemetry_server_url(project_root: &Path, flag: Option<&str>) -> Result<String, String> {
    let (resolved, credential) =
        crate::credentials::resolve_credentials_quiet(project_root).map_err(|e| e.to_string())?;
    if credential.is_none() {
        return Err(not_logged_in(flag.or(resolved.as_deref())));
    }
    match (flag, resolved.as_deref()) {
        (Some(flag), Some(resolved)) if !same_server(flag, resolved) => Err(format!(
            "you are logged in to {resolved}, not {flag}: Claude Code telemetry can only be \
             authenticated with the credential of the server it is sent to. Run \
             `{TOP} login --server-url {flag}` first."
        )),
        (Some(url), _) | (None, Some(url)) => Ok(url.trim_end_matches('/').to_string()),
        (None, None) => Err(crate::program::say(
            "no Visdom server URL configured: run `tracevault login --server-url <URL>` \
             or set TRACEVAULT_SERVER_URL",
        )
        .to_string()),
    }
}

fn not_logged_in(url: Option<&str>) -> String {
    format!(
        "Not logged in to Visdom, so Claude Code telemetry cannot be authenticated. Run \
         `{TOP} login --server-url {}` (or set {ENV}_API_KEY).",
        url.unwrap_or("<URL>")
    )
}

/// Ask whether to enable telemetry, during an interactive `init` (stdin is a
/// TTY) that passed neither `--claude-telemetry` nor `--no-claude-telemetry`.
/// Defaults to yes (VIS-1109); without a terminal the answer is that default.
pub fn prompt() -> io::Result<bool> {
    if !io::stdin().is_terminal() {
        return Ok(true);
    }
    ask(&mut io::stdin().lock(), &mut io::stdout().lock())
}

/// The question [`prompt`] asks, on any input/output: no only for `n`/`no`.
fn ask(input: &mut impl BufRead, output: &mut impl Write) -> io::Result<bool> {
    write!(
        output,
        "Also send Claude Code's per-request cost to Visdom over OpenTelemetry \
         (writes ~/.claude/settings.json)? [Y/n]: "
    )?;
    output.flush()?;
    let mut line = String::new();
    input.read_line(&mut line)?;
    Ok(!matches!(line.trim().to_lowercase().as_str(), "n" | "no"))
}

/// Whether `<claude_dir>/settings.json` has no Visdom or other telemetry
/// configured yet, i.e. whether the interactive prompt has anything to offer.
pub fn is_off(claude_dir: &Path) -> bool {
    let settings = fs::read_to_string(claude_dir.join("settings.json"))
        .ok()
        .and_then(|s| serde_json::from_str::<Value>(&s).ok())
        .unwrap_or_else(|| json!({}));
    inspect(&settings, &Environment::current(claude_dir), None) == TelemetryState::Off
}

/// `tracevault otel-headers`: the JSON object Claude Code's
/// `otelHeadersHelper` expects, `{"Authorization": "Bearer …"}`, built from
/// the credential that resolves in `cwd`. With `server_url` (what `init`
/// writes into the helper command) that credential must belong to that
/// server, so a later login elsewhere never sends its token to this endpoint.
pub async fn otel_headers(cwd: &Path, server_url: Option<&str>) -> Result<String, String> {
    let project_root = crate::paths::resolve_project_root(cwd).root;
    let (resolved, credential) =
        crate::credentials::resolve_credentials_quiet(&project_root).map_err(|e| e.to_string())?;
    let Some(credential) = credential else {
        return Err(not_logged_in(server_url.or(resolved.as_deref())));
    };
    if let (Some(wanted), Some(resolved)) = (server_url, resolved.as_deref()) {
        if !same_server(wanted, resolved) {
            return Err(format!(
                "the Visdom credential is for {resolved}, but Claude Code telemetry is \
                 configured for {wanted}. Run `{TOP} login --server-url {wanted}`, or \
                 `{TOP} init --claude-telemetry` to export to {resolved} instead."
            ));
        }
    }
    let token = match &credential {
        Credential::ApiKey(key) => key.clone(),
        Credential::Keycloak(_) => {
            let base = server_url.or(resolved.as_deref()).unwrap_or_default();
            ApiClient::with_credential(base, Some(credential))
                .bearer_valid_for(HEADER_MIN_VALID_SECS)
                .await
                .map_err(|e| e.to_string())?
                .unwrap_or_default()
        }
    };
    Ok(json!({ "Authorization": format!("Bearer {token}") }).to_string())
}

#[cfg(test)]
pub(crate) mod tests {
    use super::*;

    const SERVER: &str = "https://tv.example.com";

    pub(crate) fn shell(key: &str, value: &str) -> Environment {
        Environment {
            shell: vec![(key.to_string(), value.to_string())],
            ..Default::default()
        }
    }

    fn merged(mut settings: Value, env: &Environment) -> (Value, InstallOutcome) {
        let outcome = merge_telemetry(&mut settings, SERVER, env).unwrap();
        (settings, outcome)
    }

    #[test]
    fn fresh_settings_get_env_and_helper() {
        let (s, outcome) = merged(json!({}), &Environment::default());
        assert_eq!(outcome, InstallOutcome::Configured);
        assert_eq!(
            s,
            json!({
                "env": {
                    "CLAUDE_CODE_ENABLE_TELEMETRY": "1",
                    "OTEL_LOGS_EXPORTER": "otlp",
                    "OTEL_EXPORTER_OTLP_LOGS_PROTOCOL": "http/protobuf",
                    "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT": "https://tv.example.com/otlp/v1/logs",
                    "CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS": "180000"
                },
                "otelHeadersHelper": "tracevault otel-headers --server-url https://tv.example.com"
            })
        );
        let text = s.to_string();
        assert!(!text.contains("tvk_") && !text.contains("Bearer"), "{text}");
    }

    #[test]
    fn existing_env_and_other_keys_are_kept() {
        let (s, outcome) = merged(
            json!({
                "model": "opus",
                "hooks": {"Stop": []},
                "env": {"FOO": "bar", "CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS": "60000",
                        "OTEL_METRICS_EXPORTER": "none"}
            }),
            &Environment::default(),
        );
        assert_eq!(outcome, InstallOutcome::Configured);
        assert_eq!(s["model"], "opus");
        assert_eq!(s["hooks"], json!({"Stop": []}));
        assert_eq!(s["env"]["FOO"], "bar");
        assert_eq!(s["env"]["OTEL_METRICS_EXPORTER"], "none");
        // The user's own helper interval wins.
        assert_eq!(s["env"][HELPER_INTERVAL], "60000");
        assert_eq!(s["env"][LOGS_EXPORTER], "otlp");
    }

    #[test]
    fn rerun_is_idempotent() {
        let (once, _) = merged(json!({"a": 1}), &Environment::default());
        let (twice, outcome) = merged(once.clone(), &Environment::default());
        assert_eq!(outcome, InstallOutcome::Configured);
        assert_eq!(once, twice);
    }

    #[test]
    fn our_install_for_another_server_is_replaced() {
        let mut s = json!({});
        merge_telemetry(&mut s, "https://old.example.com", &Environment::default()).unwrap();
        let (s, outcome) = merged(s, &Environment::default());
        assert_eq!(outcome, InstallOutcome::Configured);
        assert_eq!(
            s["env"][LOGS_ENDPOINT],
            "https://tv.example.com/otlp/v1/logs"
        );
        assert_eq!(
            s[HEADERS_HELPER],
            "tracevault otel-headers --server-url https://tv.example.com"
        );
    }

    fn assert_left_alone(settings: Value, env: &Environment, mentions: &str) {
        let (after, outcome) = merged(settings.clone(), env);
        assert_eq!(after, settings, "a foreign setup must not be touched");
        match outcome {
            InstallOutcome::Foreign(reasons) => assert!(
                reasons.iter().any(|r| r.contains(mentions)),
                "{reasons:?} should mention {mentions}"
            ),
            other => panic!("expected Foreign, got {other:?}"),
        }
    }

    #[test]
    fn foreign_logs_exporter_is_left_alone() {
        assert_left_alone(
            json!({"env": {"OTEL_LOGS_EXPORTER": "console"}}),
            &Environment::default(),
            "OTEL_LOGS_EXPORTER=console",
        );
    }

    #[test]
    fn foreign_logs_endpoint_is_left_alone() {
        assert_left_alone(
            json!({"env": {
                "OTEL_LOGS_EXPORTER": "otlp",
                "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT": "https://collector.corp/v1/logs"
            }}),
            &Environment::default(),
            "https://collector.corp/v1/logs",
        );
    }

    #[test]
    fn generic_endpoint_metrics_and_static_headers_are_foreign() {
        assert_left_alone(
            json!({"env": {"OTEL_EXPORTER_OTLP_ENDPOINT": "http://localhost:4318"}}),
            &Environment::default(),
            "OTEL_EXPORTER_OTLP_ENDPOINT",
        );
        assert_left_alone(
            json!({"env": {"OTEL_METRICS_EXPORTER": "otlp"}}),
            &Environment::default(),
            "OTEL_METRICS_EXPORTER",
        );
        assert_left_alone(
            json!({"env": {"OTEL_EXPORTER_OTLP_HEADERS": "Authorization=Bearer secret"}}),
            &Environment::default(),
            "OTEL_EXPORTER_OTLP_HEADERS is set",
        );
    }

    #[test]
    fn beta_tracing_endpoint_is_foreign() {
        assert_left_alone(
            json!({"env": {"ENABLE_BETA_TRACING_DETAILED": "1",
                           "BETA_TRACING_ENDPOINT": "https://collector.corp"}}),
            &Environment::default(),
            "BETA_TRACING_ENDPOINT",
        );
        assert_left_alone(
            json!({}),
            &shell("BETA_TRACING_ENDPOINT", "https://collector.corp"),
            "BETA_TRACING_ENDPOINT",
        );
    }

    #[test]
    fn the_prompt_defaults_to_yes() {
        let answer = |text: &str| {
            let mut out = Vec::new();
            let yes = ask(&mut text.as_bytes(), &mut out).unwrap();
            assert!(String::from_utf8(out).unwrap().contains("[Y/n]"));
            yes
        };
        assert!(answer("y\n"));
        assert!(answer(" Yes \n"));
        assert!(answer("\n"));
        assert!(answer(""));
        assert!(!answer("n\n"));
        assert!(!answer(" NO \n"));
    }

    #[test]
    fn remove_restores_settings_from_before_the_install() {
        let before = json!({"model": "opus", "env": {"FOO": "bar"}, "hooks": {"Stop": []}});
        let (mut s, _) = merged(before.clone(), &Environment::default());
        assert!(remove_telemetry(&mut s, &Environment::default(), None).unwrap());
        assert_eq!(s, before);

        let (mut s, _) = merged(json!({}), &Environment::default());
        assert!(remove_telemetry(&mut s, &Environment::default(), None).unwrap());
        assert_eq!(s, json!({}), "an env object we created goes too");
        assert!(
            !remove_telemetry(&mut s, &Environment::default(), None).unwrap(),
            "nothing left to remove"
        );
    }

    #[test]
    fn remove_keeps_values_the_user_changed_or_shares() {
        let (mut s, _) = merged(
            json!({"env": {HELPER_INTERVAL: "60000", "OTEL_METRICS_EXPORTER": "none"}}),
            &Environment::default(),
        );
        // Changed after the install: the user's now.
        s["env"][LOGS_PROTOCOL] = json!("http/json");
        remove_telemetry(&mut s, &Environment::default(), None).unwrap();
        assert_eq!(
            s,
            json!({"env": {HELPER_INTERVAL: "60000", "OTEL_METRICS_EXPORTER": "none",
                           LOGS_PROTOCOL: "http/json"}})
        );

        // Another exporter still needs telemetry and the OTLP logs exporter.
        let (mut s, _) = merged(json!({}), &Environment::default());
        s["env"]["OTEL_METRICS_EXPORTER"] = json!("otlp");
        remove_telemetry(&mut s, &Environment::default(), None).unwrap();
        assert_eq!(s["env"][ENABLE_TELEMETRY], "1");
        assert_eq!(s["env"][LOGS_EXPORTER], "otlp");
        assert!(s["env"].get(LOGS_ENDPOINT).is_none());
        assert!(s.get(HEADERS_HELPER).is_none());
    }

    #[test]
    fn remove_never_touches_a_foreign_setup() {
        // No helper of ours: the env could be anyone's.
        let foreign = json!({"env": {ENABLE_TELEMETRY: "1", LOGS_EXPORTER: "otlp",
                                     LOGS_ENDPOINT: "https://tv.example.com/otlp/v1/logs"},
                             HEADERS_HELPER: "/opt/corp/token"});
        let mut s = foreign.clone();
        assert!(!remove_telemetry(&mut s, &Environment::default(), None).unwrap());
        assert_eq!(s, foreign);

        // Our helper next to someone else's endpoint: only the helper goes
        // (it hands our token to that endpoint).
        let mut s = json!({"env": {LOGS_ENDPOINT: "https://collector.corp/v1/logs",
                                   LOGS_EXPORTER: "otlp"},
                           HEADERS_HELPER: helper_command(SERVER)});
        assert!(remove_telemetry(&mut s, &Environment::default(), None).unwrap());
        assert_eq!(
            s,
            json!({"env": {LOGS_ENDPOINT: "https://collector.corp/v1/logs",
                           LOGS_EXPORTER: "otlp"}})
        );
    }

    #[test]
    fn remove_keeps_shared_keys_for_an_exporter_in_the_shell_or_managed_settings() {
        let managed = Environment {
            managed: vec![(
                "managed".to_string(),
                json!({"env": {"OTEL_TRACES_EXPORTER": "otlp"}}),
            )],
            ..Default::default()
        };
        for outside in [shell("OTEL_METRICS_EXPORTER", "otlp"), managed] {
            let (mut s, _) = merged(json!({}), &Environment::default());
            remove_telemetry(&mut s, &outside, None).unwrap();
            assert_eq!(s["env"][ENABLE_TELEMETRY], "1", "{outside:?}");
            assert!(s["env"].get(LOGS_ENDPOINT).is_none());
        }
    }

    #[test]
    fn our_endpoint_inherited_by_the_shell_is_not_another_exporter() {
        // `telemetry off` run from Claude Code's Bash tool sees our settings
        // in its environment.
        let (mut s, _) = merged(json!({}), &Environment::default());
        let inherited = shell(LOGS_ENDPOINT, "https://tv.example.com/otlp/v1/logs");
        assert!(remove_telemetry(&mut s, &inherited, None).unwrap());
        assert_eq!(s, json!({}));
    }

    #[test]
    fn a_helper_interval_the_user_had_before_survives_removal() {
        let (mut s, _) = merged(
            json!({"env": {HELPER_INTERVAL: HELPER_INTERVAL_MS}}),
            &Environment::default(),
        );
        remove_telemetry(&mut s, &Environment::default(), Some(false)).unwrap();
        assert_eq!(s, json!({"env": {HELPER_INTERVAL: HELPER_INTERVAL_MS}}));

        let (mut s, _) = merged(json!({}), &Environment::default());
        remove_telemetry(&mut s, &Environment::default(), Some(true)).unwrap();
        assert_eq!(s, json!({}));
    }

    #[test]
    fn interval_ownership_is_known_before_the_install() {
        let dir = tempfile::tempdir().unwrap();
        assert_eq!(interval_added_by_install(dir.path()), Some(true));
        fs::write(
            dir.path().join("settings.json"),
            json!({"env": {HELPER_INTERVAL: HELPER_INTERVAL_MS}}).to_string(),
        )
        .unwrap();
        assert_eq!(interval_added_by_install(dir.path()), Some(false));
        fs::remove_file(dir.path().join("settings.json")).unwrap();
        install(dir.path(), SERVER, &Environment::default()).unwrap();
        assert_eq!(
            interval_added_by_install(dir.path()),
            None,
            "a re-run cannot tell"
        );
    }

    #[test]
    fn removal_still_cleans_up_when_the_user_removed_the_endpoint() {
        let (mut s, _) = merged(json!({}), &Environment::default());
        s["env"].as_object_mut().unwrap().remove(LOGS_ENDPOINT);
        remove_telemetry(&mut s, &Environment::default(), Some(true)).unwrap();
        assert_eq!(s, json!({}));

        // Pointed at their own collector: only what serves no one goes.
        let (mut s, _) = merged(json!({}), &Environment::default());
        s["env"][LOGS_ENDPOINT] = json!("https://collector.corp/v1/logs");
        remove_telemetry(&mut s, &Environment::default(), Some(true)).unwrap();
        assert!(s["env"].get(HELPER_INTERVAL).is_none());
        assert_eq!(s["env"][LOGS_EXPORTER], "otlp");
        assert_eq!(s["env"][LOGS_ENDPOINT], "https://collector.corp/v1/logs");
    }

    #[test]
    fn uninstall_leaves_a_missing_file_missing() {
        let dir = tempfile::tempdir().unwrap();
        assert!(!uninstall(dir.path(), &Environment::default(), None).unwrap());
        assert!(!dir.path().join("settings.json").exists());
        install(dir.path(), SERVER, &Environment::default()).unwrap();
        assert!(uninstall(dir.path(), &Environment::default(), None).unwrap());
        assert_eq!(
            fs::read_to_string(dir.path().join("settings.json")).unwrap(),
            "{}"
        );
    }

    #[test]
    fn content_logging_is_found_anywhere_and_off_values_are_ignored() {
        let none = content_logging_settings(
            &json!({"env": {"OTEL_LOG_USER_PROMPTS": "0", "OTEL_LOG_TOOL_DETAILS": ""}}),
            &Environment::default(),
        );
        assert!(none.is_empty(), "{none:?}");
        let user = content_logging_settings(
            &json!({"env": {"OTEL_LOG_USER_PROMPTS": "1"}}),
            &Environment::default(),
        );
        assert_eq!(
            user,
            ["OTEL_LOG_USER_PROMPTS=1 (in ~/.claude/settings.json)"]
        );
        let shell = content_logging_settings(&json!({}), &shell("OTEL_LOG_RAW_API_BODIES", "1"));
        assert_eq!(shell.len(), 1);
        // Our own install sets none of them.
        let (s, _) = merged(json!({}), &Environment::default());
        assert!(content_logging_settings(&s, &Environment::default()).is_empty());
    }

    #[test]
    fn managed_endpoint_of_the_old_server_is_foreign_on_a_move() {
        // User file: our install for old.example.com. Managed settings pin
        // the logs endpoint to old.example.com too. Moving to tv.example.com
        // would leave exports going to old with tv's token.
        let mut user = json!({});
        merge_telemetry(
            &mut user,
            "https://old.example.com",
            &Environment::default(),
        )
        .unwrap();
        let env = Environment {
            managed: vec![(
                "managed".to_string(),
                json!({"env": {LOGS_ENDPOINT: "https://old.example.com/otlp/v1/logs"}}),
            )],
            ..Default::default()
        };
        assert_left_alone(user, &env, "old.example.com");
    }

    #[test]
    fn managed_helper_is_ours_only_for_the_expected_server() {
        let managed = |helper: &str| Environment {
            managed: vec![("managed".to_string(), json!({ HEADERS_HELPER: helper }))],
            ..Default::default()
        };
        // Pinned to another Visdom server: it overrides ours and would
        // refuse the new login's credential.
        assert_left_alone(
            json!({}),
            &managed("tracevault otel-headers --server-url https://old.example.com"),
            "old.example.com",
        );
        // Exactly what we would write: fine.
        let (_, outcome) = merged(json!({}), &managed(&helper_command(SERVER)));
        assert_eq!(outcome, InstallOutcome::Configured);
    }

    #[test]
    fn managed_http_json_protocol_is_accepted() {
        // The receiver takes OTLP/HTTP JSON as well as protobuf.
        let env = Environment {
            managed: vec![(
                "managed".to_string(),
                json!({"env": {LOGS_PROTOCOL: "http/json"}}),
            )],
            ..Default::default()
        };
        assert_eq!(merged(json!({}), &env).1, InstallOutcome::Configured);
    }

    #[test]
    fn managed_or_shell_grpc_protocol_is_foreign() {
        let env = Environment {
            managed: vec![(
                "managed".to_string(),
                json!({"env": {"OTEL_EXPORTER_OTLP_PROTOCOL": "grpc"}}),
            )],
            ..Default::default()
        };
        assert_left_alone(json!({}), &env, "OTEL_EXPORTER_OTLP_PROTOCOL=grpc");
        assert_left_alone(
            json!({}),
            &shell(LOGS_PROTOCOL, "grpc"),
            "OTEL_EXPORTER_OTLP_LOGS_PROTOCOL=grpc",
        );
        // In the user file the logs protocol is ours to set.
        let (s, outcome) = merged(
            json!({"env": {LOGS_PROTOCOL: "grpc"}}),
            &Environment::default(),
        );
        assert_eq!(outcome, InstallOutcome::Configured);
        assert_eq!(s["env"][LOGS_PROTOCOL], "http/protobuf");
    }

    #[test]
    fn exporter_in_managed_settings_is_foreign() {
        // An organisation's metrics exporter would receive our helper's token.
        let env = Environment {
            managed: vec![(
                "/etc/claude-code/managed-settings.json".to_string(),
                json!({"env": {"OTEL_METRICS_EXPORTER": "otlp",
                               "OTEL_EXPORTER_OTLP_METRICS_ENDPOINT": "https://corp/v1/metrics"}}),
            )],
            ..Default::default()
        };
        assert_left_alone(json!({}), &env, "/etc/claude-code/managed-settings.json");

        let helper = Environment {
            managed: vec![(
                "~/.claude/remote-settings.json".to_string(),
                json!({"otelHeadersHelper": "/opt/corp/token"}),
            )],
            ..Default::default()
        };
        assert_left_alone(json!({}), &helper, "remote-settings.json");

        // Managed settings that leave telemetry alone do not block it.
        let unrelated = Environment {
            managed: vec![(
                "m".to_string(),
                json!({"env": {"DISABLE_AUTOUPDATER": "1"}}),
            )],
            ..Default::default()
        };
        assert_eq!(merged(json!({}), &unrelated).1, InstallOutcome::Configured);
    }

    #[test]
    fn environment_reads_drop_ins_and_the_server_managed_cache() {
        // Only the cache under claude_dir is controllable here; the system
        // directory is whatever this machine has, so assert on the cache.
        let dir = tempfile::tempdir().unwrap();
        fs::write(
            dir.path().join("remote-settings.json"),
            r#"{"env": {"OTEL_LOGS_EXPORTER": "console"}}"#,
        )
        .unwrap();
        let env = Environment::current(dir.path());
        assert!(env
            .managed
            .iter()
            .any(|(label, doc)| label.ends_with("remote-settings.json")
                && doc["env"]["OTEL_LOGS_EXPORTER"] == "console"));
    }

    #[test]
    fn a_receiver_path_on_another_host_is_not_ours() {
        // Our helper names tv.example.com; the user then pointed the
        // endpoint at their own collector, which happens to use our path.
        let (mut s, _) = merged(json!({}), &Environment::default());
        s["env"][LOGS_ENDPOINT] = json!("https://collector.corp/otlp/v1/logs");
        assert_left_alone(s, &Environment::default(), "collector.corp");
    }

    #[test]
    fn foreign_header_values_are_never_reported() {
        let reasons = foreign_exporter_settings(
            &json!({"env": {"OTEL_EXPORTER_OTLP_HEADERS": "Authorization=Bearer secret"}}),
            &Environment::default(),
            None,
        );
        assert!(reasons.iter().all(|r| !r.contains("secret")), "{reasons:?}");
    }

    #[test]
    fn foreign_headers_helper_is_left_alone() {
        assert_left_alone(
            json!({"otelHeadersHelper": "/usr/local/bin/corp-otel-token"}),
            &Environment::default(),
            "corp-otel-token",
        );
    }

    #[test]
    fn exporter_in_the_shell_environment_is_foreign() {
        assert_left_alone(
            json!({"model": "opus"}),
            &shell("OTEL_EXPORTER_OTLP_ENDPOINT", "http://collector:4318"),
            "the shell environment",
        );
    }

    #[test]
    fn malformed_settings_are_an_error() {
        assert!(merge_telemetry(&mut json!([]), SERVER, &Environment::default()).is_err());
        assert!(
            merge_telemetry(&mut json!({"env": "x"}), SERVER, &Environment::default()).is_err()
        );
    }

    #[test]
    fn install_writes_file_and_rerun_keeps_it_byte_identical() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("settings.json");
        fs::write(&path, r#"{"model": "opus", "env": {"FOO": "1"}}"#).unwrap();
        assert_eq!(
            install(dir.path(), SERVER, &Environment::default()).unwrap(),
            InstallOutcome::Configured
        );
        let first = fs::read_to_string(&path).unwrap();
        let v: Value = serde_json::from_str(&first).unwrap();
        assert_eq!(v["model"], "opus");
        assert_eq!(v["env"]["FOO"], "1");
        assert_eq!(v["env"][ENABLE_TELEMETRY], "1");
        install(dir.path(), SERVER, &Environment::default()).unwrap();
        assert_eq!(fs::read_to_string(&path).unwrap(), first);
    }

    #[test]
    fn install_creates_settings_but_not_for_a_foreign_shell_setup() {
        let dir = tempfile::tempdir().unwrap();
        let env = shell("OTEL_LOGS_EXPORTER", "console");
        assert!(matches!(
            install(dir.path(), SERVER, &env).unwrap(),
            InstallOutcome::Foreign(_)
        ));
        assert!(!dir.path().join("settings.json").exists());
        install(dir.path(), SERVER, &Environment::default()).unwrap();
        assert!(dir.path().join("settings.json").exists());
    }

    #[test]
    fn install_rejects_urls_unsafe_for_the_helper_command() {
        let dir = tempfile::tempdir().unwrap();
        for bad in [
            "https://tv.example.com/;rm -rf ~",
            "https://tv.example.com/$(id)",
            "ftp://tv.example.com",
            "not a url",
        ] {
            assert!(
                install(dir.path(), bad, &Environment::default()).is_err(),
                "{bad}"
            );
        }
        assert!(!dir.path().join("settings.json").exists());
        install(
            dir.path(),
            "http://localhost:3000/",
            &Environment::default(),
        )
        .unwrap();
    }

    #[test]
    fn inspect_reports_off_ours_incomplete_and_foreign() {
        assert_eq!(
            inspect(&json!({}), &Environment::default(), None),
            TelemetryState::Off
        );
        assert_eq!(
            inspect(
                &json!({"env": {"CLAUDE_CODE_ENABLE_TELEMETRY": "1"}}),
                &Environment::default(),
                None
            ),
            TelemetryState::Off
        );

        let (configured, _) = merged(json!({}), &Environment::default());
        assert_eq!(
            inspect(&configured, &Environment::default(), None),
            TelemetryState::Ours {
                endpoint: Some("https://tv.example.com/otlp/v1/logs".to_string()),
                missing: vec![],
            }
        );

        let mut incomplete = configured.clone();
        incomplete["env"]
            .as_object_mut()
            .unwrap()
            .remove(LOGS_EXPORTER);
        assert!(matches!(
            inspect(&incomplete, &Environment::default(), None),
            TelemetryState::Ours { missing, .. } if missing == vec![LOGS_EXPORTER]
        ));

        let mut also_metrics = configured;
        also_metrics["env"]["OTEL_METRICS_EXPORTER"] = json!("otlp");
        assert!(matches!(
            inspect(&also_metrics, &Environment::default(), None),
            TelemetryState::Foreign { ours_too: true, .. }
        ));
    }

    #[test]
    fn collector_instructions_name_the_receiver_and_filter() {
        let text = collector_instructions("https://tv.example.com/", &["X=1".to_string()]);
        assert!(
            text.contains("endpoint: https://tv.example.com/otlp\n"),
            "{text}"
        );
        assert!(text.contains("\"api_request\""), "{text}");
        assert!(text.contains("  - X=1"), "{text}");
    }

    #[test]
    fn the_helper_is_ours_under_either_binary_name() {
        for helper in [
            "tracevault otel-headers --server-url https://tv.example.com",
            "visdom trace otel-headers --server-url https://tv.example.com",
        ] {
            assert!(is_our_helper(&json!(helper)), "{helper}");
            assert_eq!(
                helper_logs_endpoint(Some(&json!(helper))).as_deref(),
                Some("https://tv.example.com/otlp/v1/logs"),
                "{helper}"
            );
        }
        assert!(!is_our_helper(&json!("visdom trace otel-headers-mine")));
        assert!(!is_our_helper(&json!("my-helper otel-headers")));
        assert_eq!(
            helper_command_for("https://tv.example.com/", true),
            "visdom trace otel-headers --server-url https://tv.example.com"
        );
    }

    /// This test process is the `tracevault` binary's library, as the
    /// automatic upgrade is when a `tracevault` hook starts it: a helper that
    /// already calls `visdom` must come out of the merge calling `visdom`.
    #[test]
    fn a_refresh_keeps_a_helper_that_calls_visdom() {
        let visdom_helper = helper_command_for(SERVER, true);
        let (s, outcome) = merged(
            json!({ HEADERS_HELPER: visdom_helper }),
            &Environment::default(),
        );
        assert_eq!(outcome, InstallOutcome::Configured);
        assert_eq!(s[HEADERS_HELPER], json!(visdom_helper));
        // Moving to another server keeps the binary, too.
        let mut moved = s.clone();
        merge_telemetry(
            &mut moved,
            "https://other.example.com",
            &Environment::default(),
        )
        .unwrap();
        assert_eq!(
            moved[HEADERS_HELPER],
            json!("visdom trace otel-headers --server-url https://other.example.com")
        );
        // A helper of ours that calls `tracevault` stays that way here.
        let (s, _) = merged(
            json!({ HEADERS_HELPER: helper_command_for(SERVER, false) }),
            &Environment::default(),
        );
        assert_eq!(s[HEADERS_HELPER], json!(helper_command_for(SERVER, false)));
    }
}