tracevault-cli 0.29.2

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
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
use crate::credentials::{resolve_credentials, Credential, Credentials, KeycloakSession};
use serde::{Deserialize, Serialize};
use std::error::Error;
use std::fmt;
use std::path::Path;
use std::sync::Arc;
use tokio::sync::Mutex;
use url::Url;

pub struct ApiClient {
    base_url: String,
    credential: Option<ClientCredential>,
    client: reqwest::Client,
    /// Injectable "now" (unix seconds). Only the token-refresh window reads
    /// it; tests override it so the boundary is deterministic instead of
    /// depending on wall-clock time.
    now: fn() -> i64,
}

/// A [`Credential`] prepared for use by a client.
///
/// A Keycloak session sits behind an `Arc<Mutex<..>>` so several concurrent
/// in-process requests (the stream hook drains a queue with a shared client)
/// serialise on ONE refresh instead of each racing to mint its own and
/// invalidating the others' refresh token.
enum ClientCredential {
    ApiKey(String),
    Keycloak(Arc<Mutex<KeycloakSession>>),
}

/// Why a request could not be given a bearer token.
///
/// Separate from [`GetMeError`] because it is produced before any request
/// goes out, and separate from a plain string because callers must be able
/// to distinguish "this session is dead, log in again" from "we couldn't
/// reach the IdP right now".
#[derive(Debug)]
pub enum AuthError {
    /// The refresh token was rejected: the user must log in again.
    SessionExpired,
    /// The refresh attempt itself failed (IdP unreachable, 5xx, ...).
    Refresh(String),
}

impl fmt::Display for AuthError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::SessionExpired => write!(
                f,
                "your session has expired — run `tracevault login` to sign in again"
            ),
            Self::Refresh(m) => write!(f, "could not refresh the access token: {m}"),
        }
    }
}

impl std::error::Error for AuthError {}

/// Wall-clock unix seconds; the production value of [`ApiClient::now`].
fn now_unix() -> i64 {
    chrono::Utc::now().timestamp()
}

/// The value of the `x-tracevault-project-attribution` header: the two
/// spellings the server accepts, and no others.
///
/// A type rather than a `&str` because the wire contract is closed on the
/// server side and fails LOUDLY: `explicit` and `derived` are the only
/// accepted values, and anything else — a typo, a future mode this build
/// does not know about, a hand-passed literal — is a `400`, not a silently
/// ignored header. Every value is produced today by
/// `commands::stream::attribution_mode`, so the invariant already holds, but
/// it holds only by convention: one new call site passing `"Explicit"` or
/// `"forced"` would turn a working hook into a hard client error. An enum
/// moves that from "documented" to "unrepresentable", the same move that
/// makes `ClientErrorKind` and `ForceStatus` types.
///
/// The CLI's own tolerance runs the other way, deliberately: an unrecognised
/// `TRACEVAULT_PROJECT_ATTRIBUTION` reads as `Derived` rather than being
/// forwarded (see `commands::stream::attribution_mode`), so a typo'd env var
/// never reaches the server to be rejected. This enum is what keeps that
/// function the only place a mode is decided.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AttributionMode {
    /// TraceVault checks repo→project membership itself. The default, and
    /// what an absent header also means.
    Derived,
    /// The caller owns attribution and the server skips the membership
    /// check. A trust claim, gated server-side (`Operator` + a Control Plane
    /// identity).
    Explicit,
}

impl AttributionMode {
    /// The wire spelling. THE one place a mode becomes a string — the header
    /// write in [`ApiClient::stream_event_for_project`] and the [`fmt::Display`]
    /// impl below both go through this match, so no surface can invent a
    /// third spelling or disagree with the wire.
    pub fn as_header_value(self) -> &'static str {
        match self {
            Self::Derived => "derived",
            Self::Explicit => "explicit",
        }
    }
}

impl fmt::Display for AttributionMode {
    /// Deliberately the same word the header carries: `project status` prints
    /// the mode a hook would send, and a separate spelling for human output
    /// would be a second thing to keep in agreement with the wire.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_header_value())
    }
}

#[derive(Serialize)]
pub struct RegisterRepoRequest {
    pub repo_name: String,
    pub github_url: Option<String>,
}

#[derive(Debug, Deserialize)]
pub struct RegisterRepoResponse {
    pub repo_id: uuid::Uuid,
}

#[derive(Debug, Deserialize)]
pub struct ResolveRemoteResponse {
    pub remote_id: uuid::Uuid,
    #[serde(default)]
    pub name: Option<String>,
    pub normalized_url: String,
    pub clone_status: String,
}

#[derive(Debug, Clone, Deserialize)]
pub struct RemoteRepoRef {
    pub id: uuid::Uuid,
    pub name: String,
}

// The server's RemoteDetailResponse flattens the remote fields at top level and
// adds a `repos` array; serde ignores any other top-level fields.
#[derive(Deserialize)]
pub struct RemoteDetail {
    #[serde(default)]
    pub name: Option<String>,
    pub normalized_url: String,
    pub clone_status: String,
    pub repos: Vec<RemoteRepoRef>,
}

#[derive(Debug, Serialize)]
pub struct CheckPoliciesRequest {
    pub sessions: Vec<SessionCheckData>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub commit_sha: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub changed_paths: Option<Vec<String>>,
}

#[derive(Debug, Serialize)]
pub struct SessionCheckData {
    pub session_id: String,
    pub tool_calls: Option<serde_json::Value>,
    pub files_modified: Option<Vec<String>>,
    pub total_tool_calls: Option<i32>,
}

#[derive(Debug, Deserialize)]
pub struct CheckPoliciesResponse {
    pub passed: bool,
    pub results: Vec<CheckResultItem>,
    pub blocked: bool,
}

#[derive(Debug, Deserialize)]
pub struct CheckResultItem {
    pub rule_name: String,
    pub result: String,
    pub action: String,
    pub severity: String,
    pub details: String,
}

#[derive(Debug, Deserialize)]
pub struct RepoListItem {
    pub id: uuid::Uuid,
    pub name: String,
    #[serde(default)]
    pub github_url: Option<String>,
    #[serde(default)]
    pub clone_status: Option<String>,
}

/// Response shape for the `policies/agent-instructions` endpoint.
#[derive(Debug, Clone, Deserialize)]
pub struct AgentInstructionsResponse {
    #[allow(dead_code)]
    pub format: String,
    pub content: String,
}

#[derive(Debug, Deserialize)]
pub struct MeResponse {
    #[allow(dead_code)]
    pub user_id: uuid::Uuid,
    pub email: String,
    pub name: Option<String>,
    /// The role the server derived for this caller (from Keycloak realm
    /// roles or Control Plane grants for a Keycloak bearer). Optional so this
    /// CLI keeps parsing a server that predates the field.
    #[serde(default)]
    pub role: Option<String>,
}

#[derive(Debug)]
pub enum GetMeError {
    /// 401 — token is missing or invalid.
    Unauthorized,
    /// 403 — the token is valid but the account is not authorized (for a
    /// Keycloak bearer: it has no `tracevault` grant in Control Plane). Distinct from
    /// `Unauthorized` because the fix is "an admin grants a role", not
    /// "log in again".
    Forbidden(String),
    /// Transport-level failure (DNS, TCP, TLS, timeout).
    Network(String),
    /// HTTP ≥ 400 other than 401/403, or malformed JSON.
    Server(String),
}

impl std::fmt::Display for GetMeError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Unauthorized => write!(f, "unauthorized (token invalid or expired)"),
            Self::Forbidden(m) => write!(f, "forbidden (account not authorized): {m}"),
            Self::Network(m) => write!(f, "network error: {m}"),
            Self::Server(m) => write!(f, "server error: {m}"),
        }
    }
}

impl std::error::Error for GetMeError {}

#[derive(Debug, Serialize)]
pub struct CiVerifyRequest {
    pub commits: Vec<String>,
}

#[derive(Debug, Deserialize)]
pub struct CiVerifyResponse {
    pub status: String,
    pub total_commits: usize,
    pub registered_commits: usize,
    pub sealed_commits: usize,
    pub policy_passed_commits: usize,
    pub results: Vec<CommitVerifyResult>,
}

#[derive(Debug, Deserialize)]
pub struct CommitVerifyResult {
    pub commit_sha: String,
    pub status: String,
    pub registered: bool,
    pub sealed: bool,
    pub signature_valid: bool,
    pub chain_valid: bool,
    pub policy_results: Vec<CiPolicyResult>,
}

#[derive(Debug, Deserialize)]
pub struct CiPolicyResult {
    pub rule_name: String,
    pub result: String,
    pub action: String,
    pub severity: String,
    pub details: String,
}

/// One project in `GET /api/v1/projects`. Server sends more
/// fields; only these two are consumed today.
#[derive(Debug, Deserialize)]
pub struct ProjectListItem {
    pub id: uuid::Uuid,
    pub name: String,
}

/// A repo linked to a project (member of `ProjectDetail::repos`).
#[derive(Debug, Deserialize)]
pub struct ProjectRepoRef {
    pub id: uuid::Uuid,
}

/// Full detail for a project. Server sends more fields; only `repos` is
/// consumed today.
#[derive(Debug, Deserialize)]
pub struct ProjectDetail {
    pub repos: Vec<ProjectRepoRef>,
}

/// Outcome of `ApiClient::resolve_project`, distinguishing "no project"
/// (404) from "ambiguous, multiple candidates" (409) — unlike
/// `resolve_remote`, which only distinguishes found/not-found.
#[derive(Debug)]
pub enum ResolveProjectOutcome {
    Resolved(uuid::Uuid),
    None,
    Ambiguous,
}

/// Wire shape of a successful `resolve_project` response.
#[derive(Deserialize)]
struct ResolveProjectResponse {
    project_id: uuid::Uuid,
}

impl ApiClient {
    /// Construct a client authenticated with a raw API key (or nothing).
    ///
    /// Part of the crate's public API and the shape every test constructs, so
    /// it stays exactly as it was. Command code goes through
    /// [`ApiClient::with_credential`] instead, which is why the `tracevault`
    /// BINARY target — where nothing but the lib's tests calls this — would
    /// otherwise report it as dead.
    #[allow(dead_code)]
    pub fn new(base_url: &str, api_key: Option<&str>) -> Self {
        Self::with_credential(base_url, api_key.map(|k| Credential::ApiKey(k.to_string())))
    }

    /// Construct a client from a resolved [`Credential`].
    ///
    /// Takes an `Option` because every caller resolves credentials that may
    /// be absent (`resolve_credentials` returns an `Option`), and an
    /// unauthenticated client is a legitimate state — several commands
    /// degrade gracefully rather than failing when nothing is configured.
    pub fn with_credential(base_url: &str, credential: Option<Credential>) -> Self {
        Self {
            base_url: base_url.trim_end_matches('/').to_string(),
            credential: credential.map(|c| match c {
                Credential::ApiKey(k) => ClientCredential::ApiKey(k),
                Credential::Keycloak(s) => ClientCredential::Keycloak(Arc::new(Mutex::new(s))),
            }),
            client: reqwest::Client::builder()
                .timeout(std::time::Duration::from_secs(60))
                .build()
                .unwrap_or_default(),
            now: now_unix,
        }
    }

    /// Test-only clock override, so the refresh window can be exercised
    /// without waiting for a token to actually age.
    #[cfg(test)]
    fn with_now(mut self, now: fn() -> i64) -> Self {
        self.now = now;
        self
    }

    /// The bearer token to present, refreshing first if needed.
    ///
    /// * `ApiKey` → the key verbatim. Never refreshed, never rotated: this is
    ///   the automation path and it must stay a pure passthrough.
    /// * `Keycloak` → refresh when the access token is inside
    ///   [`crate::credentials::REFRESH_WINDOW_SECS`] of expiry, persist the
    ///   new tokens, and return the fresh one. The session mutex is held
    ///   across the refresh so concurrent callers wait for it instead of
    ///   each starting their own.
    async fn bearer(&self) -> Result<Option<String>, AuthError> {
        match &self.credential {
            None => Ok(None),
            Some(ClientCredential::ApiKey(key)) => Ok(Some(key.clone())),
            Some(ClientCredential::Keycloak(session)) => {
                let mut guard = session.lock().await;
                if guard.needs_refresh((self.now)()) {
                    self.refresh_locked(&mut guard).await?;
                }
                Ok(Some(guard.access_token.clone()))
            }
        }
    }

    /// The bearer token for a caller that hands it to someone else to use
    /// for a while (`tracevault otel-headers`: Claude Code reuses the header
    /// until it runs the helper again). A Keycloak access token with less than
    /// `min_valid_secs` left is refreshed first, so it does not expire between
    /// two runs. An API key is returned as is.
    pub async fn bearer_valid_for(&self, min_valid_secs: i64) -> Result<Option<String>, AuthError> {
        match &self.credential {
            Some(ClientCredential::Keycloak(session)) => {
                let mut guard = session.lock().await;
                let too_short = |s: &KeycloakSession| {
                    s.access_expires_at.saturating_sub((self.now)()) < min_valid_secs
                };
                // `refresh_locked` may only adopt another process's session,
                // which can still be too short for us; then the adopted (now
                // current) session is refreshed for real. Two rounds at most,
                // so a token lifetime below the minimum cannot loop.
                for _ in 0..2 {
                    if !too_short(&guard) {
                        break;
                    }
                    self.refresh_locked(&mut guard).await?;
                }
                // Still too short after a real refresh: the IdP issues tokens
                // that live less than the minimum. The token is still handed
                // out — it authenticates for most of the interval, where an
                // error would authenticate nothing — but the caller is told.
                if too_short(&guard) {
                    eprintln!(
                        "Warning: the access token is valid for less than {min_valid_secs}s even \
                         after a refresh; requests made with it later may be rejected"
                    );
                }
                Ok(Some(guard.access_token.clone()))
            }
            _ => self.bearer().await,
        }
    }

    /// Refresh the held session in place and persist it. Caller holds the
    /// session lock, which is what makes "one refresh at a time" true.
    ///
    /// # Residual cross-process race, and why it is currently benign
    ///
    /// The on-disk adopt below closes the SEQUENTIAL case (something already
    /// finished refreshing before we started) but only NARROWS the concurrent
    /// one: two hooks spawned at the same instant can both read the same
    /// session before either writes, and the window is this function's
    /// discovery GET plus its token POST. Both would then present the same
    /// refresh token.
    ///
    /// That is harmless ONLY because the realm keeps Keycloak's
    /// `revokeRefreshToken` at its default (off): a re-presented refresh token
    /// stays valid, so the worst outcome is one wasted round trip and a
    /// last-writer-wins access token, both invisible to the user. If that
    /// realm setting is ever enabled, the second presenter gets
    /// `invalid_grant` — surfacing as a spurious "your session has expired" —
    /// and this code then needs a real inter-process file lock around
    /// read-refresh-write, not just the adopt.
    ///
    /// # Both directions are scoped to this client's server
    ///
    /// There is exactly ONE credentials file, but a machine can be pointed at
    /// more than one TraceVault instance. So the adopt only reads, and
    /// `persist_session` only writes, when that file's `server_url` is this
    /// client's `base_url` (see [`crate::credentials::same_server`]).
    /// Unscoped, a long-running `tracevault stream` against instance A plus a
    /// `tracevault login` to instance B in another terminal would make A adopt
    /// B's session and send B's access token to A — disclosing a token to a
    /// host it was never minted for — and A's next refresh would then overwrite
    /// B's credentials, signing the user out of B.
    async fn refresh_locked(&self, session: &mut KeycloakSession) -> Result<(), AuthError> {
        let now = (self.now)();

        // Someone else may have refreshed already: another process (two git
        // hooks firing at once), or another `ApiClient` in this process that
        // was built from the same on-disk credential before either refreshed.
        //
        // Adopt when EITHER holds, because they catch different IdPs:
        //
        // * the on-disk access token outlives ours — the on-disk session is
        //   genuinely newer. This is the only signal available on an IdP that
        //   does NOT rotate refresh tokens (RFC 6749 permits omitting
        //   `refresh_token` on a refresh, which `KeycloakSession::apply`
        //   handles), where the refresh token is identical everywhere and a
        //   token-comparison alone would never fire — leaving `tracevault
        //   status`, which builds three clients from one credential, doing three
        //   redundant refreshes.
        // * the on-disk refresh token differs from ours — ours has been
        //   superseded, and on a ROTATING IdP already consumed. This must adopt
        //   even when the adopted session is itself older and still needs a
        //   refresh (then falling through to refresh with the ADOPTED token),
        //   because refreshing with a consumed token is a guaranteed
        //   `invalid_grant`.
        //
        // Deliberately NOT "the access tokens differ": that would also adopt a
        // strictly older session.
        //
        // There is deliberately no test asserting "never adopt an older
        // session", because that property is unreachable where it would be
        // desirable and undesirable where it is reachable. Through `bearer` it
        // cannot be observed: this function is only entered when OURS is inside
        // the refresh window, so an older disk session is inside it too and
        // control falls through to a real refresh either way. Through
        // `force_refresh` it IS reachable — and there, adopting a different
        // token is exactly what we want, since the one we hold was just
        // rejected. A test naming the downgrade would therefore have to be
        // vacuous to pass; the predicate's existence is instead covered by the
        // 401 retry tests, which fail if it always adopts.
        //
        // ... and only from a file that is still this server's (see above).
        if let Some(disk) = Credentials::load()
            .filter(|c| crate::credentials::same_server(&c.server_url, &self.base_url))
            .and_then(|c| c.auth)
        {
            let disk_is_newer = disk.access_expires_at > session.access_expires_at;
            let ours_superseded = disk.refresh_token != session.refresh_token;
            if disk_is_newer || ours_superseded {
                let disk_needs_refresh = disk.needs_refresh(now);
                *session = disk;
                if !disk_needs_refresh {
                    return Ok(());
                }
            }
        }

        // Discovery is re-fetched per refresh rather than cached: a refresh
        // happens at most once per access-token lifetime (minutes), and
        // caching it would mean a rotated realm endpoint needs a re-login.
        let discovery = crate::oidc::discover(&self.client, &session.issuer)
            .await
            .map_err(auth_error)?;
        let tokens = crate::oidc::refresh(
            &self.client,
            &discovery,
            &session.client_id,
            &session.refresh_token,
        )
        .await
        .map_err(auth_error)?;
        session.apply(&tokens, now);

        // Best-effort, and scoped to this server (see the doc comment): a token
        // that can't be written to disk still works for THIS process, so
        // failing the request would be worse than a warning. The message
        // deliberately contains no token material.
        if let Err(e) = Credentials::persist_session(&self.base_url, session) {
            eprintln!("Warning: could not save refreshed credentials: {e}");
        }
        Ok(())
    }

    /// Force one refresh after an unexpected 401 and return the new token.
    ///
    /// `Ok(None)` means "not refreshable" (API key or no credential), which
    /// is the signal not to retry. `stale` is the token that just got
    /// rejected: if another task already refreshed while we waited for the
    /// lock, the current token is already different and is reused instead of
    /// refreshing a second time.
    async fn force_refresh(&self, stale: Option<&str>) -> Result<Option<String>, AuthError> {
        let Some(ClientCredential::Keycloak(session)) = &self.credential else {
            return Ok(None);
        };
        let mut guard = session.lock().await;
        if Some(guard.access_token.as_str()) != stale {
            return Ok(Some(guard.access_token.clone()));
        }
        self.refresh_locked(&mut guard).await?;
        Ok(Some(guard.access_token.clone()))
    }

    pub async fn register_repo(
        &self,
        req: RegisterRepoRequest,
    ) -> Result<RegisterRepoResponse, Box<dyn Error>> {
        let builder = self
            .client
            .post(format!("{}/api/v1/repos", self.base_url))
            .json(&req);
        self.authed_send_json(builder, |status| format!("Server returned {status}"))
            .await
    }

    /// Attach a bearer token (if there is one) to a request. Shared by every
    /// authenticated request builder so header attachment has exactly one
    /// implementation.
    fn attach_auth(
        builder: reqwest::RequestBuilder,
        token: Option<&str>,
    ) -> reqwest::RequestBuilder {
        match token {
            Some(t) => builder.header("Authorization", format!("Bearer {t}")),
            None => builder,
        }
    }

    /// Attach the bearer token and send `builder`. The shared first step of
    /// every authenticated request; callers that need bespoke status-code
    /// handling (e.g. treating 404/409 as non-error outcomes) use this
    /// directly instead of `authed_send_json`.
    ///
    /// On an unexpected 401 with a refreshable (Keycloak) credential the
    /// request is retried EXACTLY once against a force-refreshed token —
    /// covering a server-side session invalidation or a clock skew that the
    /// proactive expiry window missed. The retry is a bare `send`, not a
    /// recursive call, so a server that answers 401 unconditionally cannot
    /// make this loop. An API key never retries: a 401 on a `tvk_` key is a
    /// real rejection and re-sending it would just double every failure.
    async fn send_authed(
        &self,
        builder: reqwest::RequestBuilder,
    ) -> Result<reqwest::Response, Box<dyn Error>> {
        // Cloned BEFORE sending: a builder is consumed by `send`. `None`
        // means the body isn't replayable, in which case we simply don't
        // retry.
        let retry = builder.try_clone();
        let token = self.bearer().await?;
        let resp = Self::attach_auth(builder, token.as_deref()).send().await?;

        if resp.status() != reqwest::StatusCode::UNAUTHORIZED {
            return Ok(resp);
        }
        let Some(retry) = retry else {
            return Ok(resp);
        };
        match self.force_refresh(token.as_deref()).await? {
            Some(fresh) => Ok(Self::attach_auth(retry, Some(&fresh)).send().await?),
            // Not refreshable — surface the original 401 unchanged.
            None => Ok(resp),
        }
    }

    /// Check that `resp`'s status is a success and deserialize its JSON
    /// body; otherwise build an error as `"{err_prefix(status)}: {body}"`.
    /// `err_prefix` receives the status so each caller can format its own
    /// distinct message (parenthesized status, bare status, ...) — this
    /// helper only supplies the shared "check status, else deserialize"
    /// shape, not the message wording.
    async fn success_json<T, F>(resp: reqwest::Response, err_prefix: F) -> Result<T, Box<dyn Error>>
    where
        T: serde::de::DeserializeOwned,
        F: FnOnce(reqwest::StatusCode) -> String,
    {
        let status = resp.status();
        if !status.is_success() {
            let body = resp.text().await.unwrap_or_default();
            return Err(format!("{}: {}", err_prefix(status), body).into());
        }
        Ok(resp.json().await?)
    }

    /// Attach the bearer token, send `builder`, and deserialize a successful
    /// JSON response — the shared shape of every simple authenticated
    /// request/response method (`send_authed` + `success_json`).
    ///
    /// NOTE: callers whose `err_prefix` renders the status as `"({status})"`
    /// (e.g. `stream_event`'s `"Stream failed ({status})"`) produce error
    /// strings containing `"(404 "`/`"(403 "`/etc. —
    /// `commands::stream::deterministic_client_error_kind` matches on exactly
    /// that substring shape to classify a stream-send failure, and to tell a 403
    /// apart from the binding statuses. If you change how a status is rendered
    /// here, check that function (and its tests) still pass.
    async fn authed_send_json<T, F>(
        &self,
        builder: reqwest::RequestBuilder,
        err_prefix: F,
    ) -> Result<T, Box<dyn Error>>
    where
        T: serde::de::DeserializeOwned,
        F: FnOnce(reqwest::StatusCode) -> String,
    {
        let resp = self.send_authed(builder).await?;
        Self::success_json(resp, err_prefix).await
    }

    /// GET `{base}{path}` with the bearer token, mapping failures into
    /// `GetMeError` (401 → `Unauthorized`, 403 → `Forbidden`, transport →
    /// `Network`, other non-2xx or bad JSON → `Server`). Shared by the
    /// credential-scoped GETs so auth/error handling lives in one place.
    ///
    /// Goes through `send_authed`, so a Keycloak access token is refreshed
    /// before the call (and once after a 401) exactly like every other
    /// request. A refresh failure is mapped by cause: a dead session is
    /// `Unauthorized` ("log in again"), an unreachable IdP is `Network`
    /// ("cannot confirm") — `tracevault status` renders those very
    /// differently, so collapsing them would misreport a network blip as a
    /// revoked login.
    async fn authed_get_json<T: serde::de::DeserializeOwned>(
        &self,
        path: &str,
    ) -> Result<T, GetMeError> {
        let builder = self.client.get(format!("{}{}", self.base_url, path));
        let resp = self.send_authed(builder).await.map_err(get_me_send_error)?;

        let status = resp.status();
        if status == reqwest::StatusCode::UNAUTHORIZED {
            return Err(GetMeError::Unauthorized);
        }
        if status == reqwest::StatusCode::FORBIDDEN {
            let body = resp.text().await.unwrap_or_default();
            return Err(GetMeError::Forbidden(body));
        }
        if !status.is_success() {
            let body = resp.text().await.unwrap_or_default();
            return Err(GetMeError::Server(format!("{status}: {body}")));
        }

        resp.json::<T>()
            .await
            .map_err(|e| GetMeError::Server(e.to_string()))
    }

    /// GET /api/v1/auth/me — validates the bearer token and returns user
    /// identity. Used by `tracevault status` to distinguish "logged out",
    /// "expired token", and "server unreachable".
    pub async fn get_me(&self) -> Result<MeResponse, GetMeError> {
        self.authed_get_json("/api/v1/auth/me").await
    }

    pub async fn list_repos(&self) -> Result<Vec<RepoListItem>, Box<dyn Error>> {
        let builder = self.client.get(format!("{}/api/v1/repos", self.base_url));
        self.authed_send_json(builder, |status| format!("Failed to list repos ({status})"))
            .await
    }

    pub async fn get_agent_instructions(
        &self,
        repo_id: &uuid::Uuid,
    ) -> Result<AgentInstructionsResponse, Box<dyn Error>> {
        let builder = self.client.get(format!(
            "{}/api/v1/repos/{}/policies/agent-instructions",
            self.base_url, repo_id
        ));
        self.authed_send_json(builder, |status| {
            format!("Failed to fetch agent instructions ({status})")
        })
        .await
    }

    pub async fn verify_commits(
        &self,
        repo_id: &uuid::Uuid,
        req: CiVerifyRequest,
    ) -> Result<CiVerifyResponse, Box<dyn Error>> {
        let builder = self
            .client
            .post(format!(
                "{}/api/v1/repos/{}/ci/verify",
                self.base_url, repo_id
            ))
            .json(&req);
        self.authed_send_json(builder, |status| format!("CI verify failed ({status})"))
            .await
    }

    pub async fn push_commit(
        &self,
        repo_id: &str,
        req: &tracevault_protocol::streaming::CommitPushRequest,
    ) -> Result<tracevault_protocol::streaming::CommitPushResponse, Box<dyn Error>> {
        let builder = self
            .client
            .post(format!(
                "{}/api/v1/repos/{}/commits",
                self.base_url, repo_id
            ))
            .json(req);
        self.authed_send_json(builder, |status| format!("Commit push failed ({status})"))
            .await
    }

    pub async fn stream_event(
        &self,
        repo_id: &str,
        req: &tracevault_protocol::streaming::StreamEventRequest,
    ) -> Result<tracevault_protocol::streaming::StreamEventResponse, Box<dyn Error>> {
        let builder = self
            .client
            .post(format!("{}/api/v1/repos/{}/stream", self.base_url, repo_id))
            .json(req);
        self.authed_send_json(builder, |status| format!("Stream failed ({status})"))
            .await
    }

    /// Project-scoped variant of `stream_event`: posts to the project's
    /// stream endpoint with the project in the path and `repo_id` — when
    /// there is one — as a query param rather than a path segment. The query
    /// is built with `Url::query_pairs_mut`, mirroring `resolve_project`'s
    /// `?git_url=`, so `repo_id` is percent-encoded rather than
    /// string-interpolated into the URL.
    ///
    /// `repo_id` is `None` for a repo-less session, and the pair is then
    /// omitted entirely: the server declares it optional
    /// (`ProjectStreamQuery::repo_id: Option<Uuid>`) and would reject an
    /// empty value as a malformed UUID.
    ///
    /// Called from `commands::stream::send_stream_event` for both the
    /// `Attribution::Repo { project: Some(_) }` and `Attribution::ProjectOnly`
    /// routes.
    ///
    /// `mode` is the attribution this send declares — decided by
    /// `commands::stream::attribution_mode` and rendered into the
    /// `x-tracevault-project-attribution` header by
    /// [`AttributionMode::as_header_value`], which is the only place it
    /// becomes a string.
    ///
    /// It is an [`AttributionMode`], not a `&str`, because the server
    /// accepts exactly two values and rejects everything else with a `400`
    /// — see that type's doc comment. (An older SERVER simply does not read
    /// the header, which is the one direction that does degrade quietly, to
    /// derived attribution.)
    pub async fn stream_event_for_project(
        &self,
        project_id: uuid::Uuid,
        repo_id: Option<&str>,
        mode: AttributionMode,
        req: &tracevault_protocol::streaming::StreamEventRequest,
    ) -> Result<tracevault_protocol::streaming::StreamEventResponse, Box<dyn Error>> {
        let mut url = Url::parse(&format!(
            "{}/api/v1/projects/{}/stream",
            self.base_url, project_id
        ))?;
        // `repo_id` is OPTIONAL server-side (`ProjectStreamQuery::repo_id:
        // Option<Uuid>` — "repo-less (0-repo) projects are supported"), so a
        // repo-less session must omit the pair entirely. Appending an empty
        // value instead would be parsed as a malformed UUID and 400.
        if let Some(repo_id) = repo_id {
            url.query_pairs_mut().append_pair("repo_id", repo_id);
        }
        let builder = self
            .client
            .post(url)
            .header("x-tracevault-project-attribution", mode.as_header_value())
            .json(req);
        self.authed_send_json(builder, |status| {
            format!("Project stream failed ({status})")
        })
        .await
    }

    pub async fn check_policies(
        &self,
        repo_id: &uuid::Uuid,
        req: CheckPoliciesRequest,
    ) -> Result<CheckPoliciesResponse, Box<dyn Error>> {
        let builder = self
            .client
            .post(format!(
                "{}/api/v1/repos/{}/policies/check",
                self.base_url, repo_id
            ))
            .json(&req);
        self.authed_send_json(builder, |status| format!("Policy check failed ({status})"))
            .await
    }

    /// Resolve a git URL to its codebase (git remote) by NORMALIZED URL —
    /// deduped, unlike an exact `github_url` match. `Ok(None)` if the
    /// codebase isn't tracked: a genuine domain 404, identified by the
    /// server's JSON error envelope (see [`is_domain_error_body`]). A bare
    /// 404 with no such body — axum's built-in "no route matched" fallback
    /// — is surfaced as `Err` instead, since it means this server doesn't
    /// have this route at all (most plausibly a CLI/server version skew,
    /// e.g. this CLI shipped ahead of a server that still uses the old
    /// org-scoped paths) rather than an absent codebase.
    pub async fn resolve_remote(
        &self,
        git_url: &str,
    ) -> Result<Option<ResolveRemoteResponse>, Box<dyn std::error::Error>> {
        let mut url = Url::parse(&format!("{}/api/v1/remotes/resolve", self.base_url))?;
        url.query_pairs_mut().append_pair("git_url", git_url);
        let resp = self.send_authed(self.client.get(url)).await?;
        if resp.status() == reqwest::StatusCode::NOT_FOUND {
            let body = resp.text().await.unwrap_or_default();
            return if is_domain_error_body(&body) {
                Ok(None)
            } else {
                Err(version_skew_404_error("resolve_remote"))
            };
        }
        let parsed: ResolveRemoteResponse =
            Self::success_json(resp, |status| format!("resolve_remote failed ({status})")).await?;
        Ok(Some(parsed))
    }

    /// Full detail for a remote (codebase): its display name, normalized URL,
    /// clone status, and linked repos.
    pub async fn get_remote_detail(
        &self,
        remote_id: uuid::Uuid,
    ) -> Result<RemoteDetail, Box<dyn std::error::Error>> {
        let builder = self
            .client
            .get(format!("{}/api/v1/remotes/{}", self.base_url, remote_id));
        self.authed_send_json(builder, |status| {
            format!("get_remote_detail failed ({status})")
        })
        .await
    }

    /// The repos linked to a remote (the codebase's members).
    pub async fn get_remote_repos(
        &self,
        remote_id: uuid::Uuid,
    ) -> Result<Vec<RemoteRepoRef>, Box<dyn std::error::Error>> {
        Ok(self.get_remote_detail(remote_id).await?.repos)
    }

    /// List all projects. `GET /api/v1/projects`.
    pub async fn list_projects(&self) -> Result<Vec<ProjectListItem>, Box<dyn Error>> {
        let builder = self
            .client
            .get(format!("{}/api/v1/projects", self.base_url));
        self.authed_send_json(builder, |status| {
            format!("Failed to list projects ({status})")
        })
        .await
    }

    /// Full detail for a project. `GET /api/v1/projects/{id}`.
    pub async fn get_project(&self, id: uuid::Uuid) -> Result<ProjectDetail, Box<dyn Error>> {
        let builder = self
            .client
            .get(format!("{}/api/v1/projects/{}", self.base_url, id));
        self.authed_send_json(builder, |status| {
            format!("Failed to get project ({status})")
        })
        .await
    }

    /// Resolve a git URL to its project, distinguishing "no project" (a
    /// genuine domain 404 — see [`is_domain_error_body`]) from "ambiguous,
    /// multiple candidate projects" (409). A bare 404 with no domain-error
    /// body is surfaced as `Err` instead of `None` (see `resolve_remote`'s
    /// doc comment for why). `GET /api/v1/projects/resolve?git_url=`.
    pub async fn resolve_project(
        &self,
        git_url: &str,
    ) -> Result<ResolveProjectOutcome, Box<dyn std::error::Error>> {
        let mut url = Url::parse(&format!("{}/api/v1/projects/resolve", self.base_url))?;
        url.query_pairs_mut().append_pair("git_url", git_url);
        let resp = self.send_authed(self.client.get(url)).await?;
        let status = resp.status();
        if status == reqwest::StatusCode::NOT_FOUND {
            let body = resp.text().await.unwrap_or_default();
            return if is_domain_error_body(&body) {
                Ok(ResolveProjectOutcome::None)
            } else {
                Err(version_skew_404_error("resolve_project"))
            };
        }
        if status == reqwest::StatusCode::CONFLICT {
            return Ok(ResolveProjectOutcome::Ambiguous);
        }
        let parsed: ResolveProjectResponse =
            Self::success_json(resp, |status| format!("resolve_project failed ({status})")).await?;
        Ok(ResolveProjectOutcome::Resolved(parsed.project_id))
    }
}

/// Map an OIDC failure onto [`AuthError`], keeping "the session is dead"
/// distinct from "the refresh attempt itself failed".
fn auth_error(e: crate::oidc::OidcError) -> AuthError {
    match e {
        crate::oidc::OidcError::SessionExpired => AuthError::SessionExpired,
        other => AuthError::Refresh(other.to_string()),
    }
}

/// Classify a `send_authed` failure for the `GetMeError`-returning callers.
/// A dead session becomes `Unauthorized`; everything else (transport, IdP
/// unreachable) becomes `Network`, which callers render as "cannot confirm".
fn get_me_send_error(e: Box<dyn Error>) -> GetMeError {
    match e.downcast::<AuthError>() {
        Ok(auth) => match *auth {
            AuthError::SessionExpired => GetMeError::Unauthorized,
            AuthError::Refresh(m) => GetMeError::Network(m),
        },
        Err(other) => GetMeError::Network(other.to_string()),
    }
}

/// Whether a 404 response body matches the server's JSON error envelope —
/// `{"error": "...", ...}`, emitted by every domain-level `AppError` (see
/// `tracevault-server`'s `error.rs`) — rather than the empty/plain body
/// axum's built-in "no route matched" fallback sends when the server has no
/// handler for the path at all. Used by `resolve_remote`/`resolve_project`
/// to tell a genuine "not tracked"/"no project" 404 apart from a 404 that
/// really means "this server doesn't have this route" (most plausibly a
/// CLI/server version skew).
fn is_domain_error_body(body: &str) -> bool {
    serde_json::from_str::<serde_json::Value>(body)
        .ok()
        .and_then(|v| v.get("error").map(|_| ()))
        .is_some()
}

/// The error for a 404 whose body doesn't match the server's JSON error
/// envelope (see [`is_domain_error_body`]) — surfaced instead of silently
/// treating the call as "not tracked"/"no project", since this shape is the
/// CLI's best signal that the server doesn't recognize `what`'s route at
/// all, rather than a genuine absence of the resource.
fn version_skew_404_error(what: &str) -> Box<dyn std::error::Error> {
    format!(
        "{what} got a 404 with no recognizable error body — this endpoint may not exist on \
         this server yet. This usually means the CLI is newer than the server (a CLI/server \
         version mismatch); confirm the server has been upgraded and retry."
    )
    .into()
}

/// Resolve `project_root`'s credentials (via `resolve_credentials`) into a
/// ready `ApiClient`, or the standard "no server URL configured" error when
/// none of the credential sources yield a server URL. Shared by every
/// command that needs a client from a project root, so this
/// resolve-then-construct shape has exactly one implementation.
pub fn resolve_client(project_root: &Path) -> Result<ApiClient, Box<dyn Error>> {
    let (server_url, credential) = resolve_credentials(project_root)?;
    let server_url = server_url
        .ok_or("no server URL configured: set TRACEVAULT_SERVER_URL or run `tracevault login`")?;
    Ok(ApiClient::with_credential(&server_url, credential))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::credentials::KeycloakSession;
    use crate::test_helpers::{http_json, spawn_seq, spawn_seq_with, RECV_TIMEOUT};
    use std::time::Duration;

    /// Fixed "now" for the refresh-window tests. Using a constant instead of
    /// the wall clock is what makes the boundary assertions deterministic.
    const NOW: i64 = 1_800_000_000;

    fn fixed_now() -> i64 {
        NOW
    }

    /// A fake IdP that answers discovery (self-reporting its own URL as the
    /// issuer, as a real one must) and then one token request. Returns the
    /// issuer URL to put in the session.
    fn spawn_idp(token_response: &'static str) -> (String, std::sync::mpsc::Receiver<String>) {
        spawn_seq_with(move |base| {
            vec![
                http_json(
                    "200 OK",
                    &format!(
                        r#"{{"issuer":"{base}","token_endpoint":"{base}/token","device_authorization_endpoint":"{base}/device","revocation_endpoint":"{base}/revoke"}}"#
                    ),
                ),
                http_json("200 OK", token_response),
            ]
        })
    }

    /// Write a Keycloak credentials file for `server_url`/`issuer` into
    /// `dir`, so a refresh has something to adopt from and persist into.
    ///
    /// `server_url` is explicit because the adopt and the persist are both
    /// scoped to the client's `base_url`: a helper that hardcoded it would
    /// silently disable persistence in tests whose client points elsewhere.
    fn write_keycloak_file(dir: &std::path::Path, server_url: &str, issuer: &str, expires_at: i64) {
        let creds_dir = dir.join("tracevault");
        std::fs::create_dir_all(&creds_dir).unwrap();
        std::fs::write(
            creds_dir.join("credentials.json"),
            format!(
                r#"{{"server_url":"{server_url}","email":"a@b.com","auth":{{"issuer":"{issuer}","client_id":"tracing-cli","refresh_token":"old-rt","access_token":"old-at","access_expires_at":{expires_at}}}}}"#
            ),
        )
        .unwrap();
    }

    fn session(issuer: &str, expires_at: i64) -> KeycloakSession {
        KeycloakSession {
            issuer: issuer.to_string(),
            client_id: "tracing-cli".into(),
            refresh_token: "old-rt".into(),
            access_token: "old-at".into(),
            access_expires_at: expires_at,
        }
    }

    /// An access token inside the 60s window is refreshed BEFORE the request
    /// goes out, and the new tokens are written back to disk so the next
    /// process doesn't repeat the refresh.
    #[tokio::test]
    async fn bearer_refreshes_inside_the_sixty_second_window() {
        let _env_lock = crate::test_helpers::lock_env_mutation().await;
        let dir = tempfile::tempdir().unwrap();
        let mut _guard = crate::test_helpers::EnvVarGuard::new();
        _guard.set("XDG_CONFIG_HOME", dir.path());

        let (issuer, rx) =
            spawn_idp(r#"{"access_token":"fresh-at","refresh_token":"fresh-rt","expires_in":300}"#);
        // 30s of life left — inside the window.
        write_keycloak_file(dir.path(), "https://example.com", &issuer, NOW + 30);

        let client = ApiClient::with_credential(
            "https://example.com",
            Some(Credential::Keycloak(session(&issuer, NOW + 30))),
        )
        .with_now(fixed_now);

        let token = client.bearer().await.unwrap();
        assert_eq!(token.as_deref(), Some("fresh-at"));

        // Discovery, then the refresh_token grant.
        let disc = rx.recv_timeout(RECV_TIMEOUT).expect("no discovery request");
        assert!(disc.contains("/.well-known/openid-configuration"), "{disc}");
        let refresh = rx.recv_timeout(RECV_TIMEOUT).expect("no token request");
        assert!(refresh.contains("grant_type=refresh_token"), "{refresh}");
        assert!(refresh.contains("refresh_token=old-rt"), "{refresh}");
        assert!(
            !refresh.contains("client_secret"),
            "the CLI client is public; no secret may be sent: {refresh}"
        );

        // Persisted, so a git hook running a second later doesn't refresh again.
        let saved = Credentials::load().expect("credentials must still exist");
        let auth = saved.auth.expect("auth block must survive a refresh");
        assert_eq!(auth.access_token, "fresh-at");
        assert_eq!(auth.refresh_token, "fresh-rt");
        assert_eq!(auth.access_expires_at, NOW + 300);
        assert_eq!(saved.email, "a@b.com", "unrelated fields must be preserved");
    }

    /// `otel-headers` needs a token that outlives Claude Code's helper
    /// interval: one with 120s left is fine for `bearer` (outside its 60s
    /// window) but is refreshed for a 240s minimum, and persisted.
    #[tokio::test]
    async fn bearer_valid_for_refreshes_a_token_expiring_within_the_minimum() {
        let _env_lock = crate::test_helpers::lock_env_mutation().await;
        let dir = tempfile::tempdir().unwrap();
        let mut _guard = crate::test_helpers::EnvVarGuard::new();
        _guard.set("XDG_CONFIG_HOME", dir.path());

        let (issuer, rx) =
            spawn_idp(r#"{"access_token":"fresh-at","refresh_token":"fresh-rt","expires_in":300}"#);
        write_keycloak_file(dir.path(), "https://example.com", &issuer, NOW + 120);
        let client = ApiClient::with_credential(
            "https://example.com",
            Some(Credential::Keycloak(session(&issuer, NOW + 120))),
        )
        .with_now(fixed_now);

        let token = client.bearer_valid_for(240).await.unwrap();
        assert_eq!(token.as_deref(), Some("fresh-at"));
        rx.recv_timeout(RECV_TIMEOUT).expect("no discovery request");
        let refresh = rx.recv_timeout(RECV_TIMEOUT).expect("no token request");
        assert!(refresh.contains("refresh_token=old-rt"), "{refresh}");
        let saved = Credentials::load().unwrap().auth.unwrap();
        assert_eq!(saved.access_token, "fresh-at");
    }

    /// Another process left a newer session on disk that is still too short
    /// for the minimum: it is adopted (its refresh token is the live one) and
    /// then refreshed, never handed out as is.
    #[tokio::test]
    async fn bearer_valid_for_refreshes_an_adopted_session_that_is_still_too_short() {
        let _env_lock = crate::test_helpers::lock_env_mutation().await;
        let dir = tempfile::tempdir().unwrap();
        let mut _guard = crate::test_helpers::EnvVarGuard::new();
        _guard.set("XDG_CONFIG_HOME", dir.path());

        let (issuer, rx) =
            spawn_idp(r#"{"access_token":"fresh-at","refresh_token":"fresh-rt","expires_in":300}"#);
        // On disk: newer (150s) than ours (120s), but under 240s.
        write_keycloak_file(dir.path(), "https://example.com", &issuer, NOW + 150);
        let mut held = session(&issuer, NOW + 120);
        held.access_token = "older-at".into();
        let client =
            ApiClient::with_credential("https://example.com", Some(Credential::Keycloak(held)))
                .with_now(fixed_now);

        let token = client.bearer_valid_for(240).await.unwrap();
        assert_eq!(token.as_deref(), Some("fresh-at"));
        rx.recv_timeout(RECV_TIMEOUT).expect("no discovery request");
        let refresh = rx.recv_timeout(RECV_TIMEOUT).expect("no token request");
        assert!(refresh.contains("refresh_token=old-rt"), "{refresh}");
    }

    /// A token valid for longer than the minimum is handed out as is: no IdP
    /// call (the issuer here is unreachable, so one would fail the test).
    #[tokio::test]
    async fn bearer_valid_for_keeps_a_token_valid_long_enough() {
        let client = ApiClient::with_credential(
            "https://example.com",
            Some(Credential::Keycloak(session(
                "http://127.0.0.1:9",
                NOW + 241,
            ))),
        )
        .with_now(fixed_now);
        let token = client.bearer_valid_for(240).await.unwrap();
        assert_eq!(token.as_deref(), Some("old-at"));
    }

    /// A rejected refresh is an error, never the stale token.
    #[tokio::test]
    async fn bearer_valid_for_fails_when_the_refresh_is_rejected() {
        let _env_lock = crate::test_helpers::lock_env_mutation().await;
        let dir = tempfile::tempdir().unwrap();
        let mut _guard = crate::test_helpers::EnvVarGuard::new();
        _guard.set("XDG_CONFIG_HOME", dir.path());

        let (issuer, _rx) = spawn_seq_with(|base| {
            vec![
                http_json(
                    "200 OK",
                    &format!(
                        r#"{{"issuer":"{base}","token_endpoint":"{base}/token","device_authorization_endpoint":"{base}/device"}}"#
                    ),
                ),
                http_json("400 Bad Request", r#"{"error":"invalid_grant"}"#),
            ]
        });
        write_keycloak_file(dir.path(), "https://example.com", &issuer, NOW + 120);
        let client = ApiClient::with_credential(
            "https://example.com",
            Some(Credential::Keycloak(session(&issuer, NOW + 120))),
        )
        .with_now(fixed_now);

        assert!(client.bearer_valid_for(240).await.is_err());
    }

    /// Two git hooks can run at once, and `tracevault status` builds two
    /// clients from one credential. If another process already refreshed, this
    /// one must ADOPT that session rather than present the refresh token that
    /// was just consumed — with refresh-token rotation enabled that would come
    /// back `invalid_grant` and log the user out for no reason.
    ///
    /// The issuer points at a dead port, so any actual refresh attempt would
    /// fail the call: reaching the assertion proves no round trip happened.
    #[tokio::test]
    async fn bearer_adopts_a_newer_session_written_by_another_process() {
        let _env_lock = crate::test_helpers::lock_env_mutation().await;
        let dir = tempfile::tempdir().unwrap();
        let mut _guard = crate::test_helpers::EnvVarGuard::new();
        _guard.set("XDG_CONFIG_HOME", dir.path());

        // On disk: a session refreshed by "another process" — different
        // refresh token, plenty of life left.
        let creds_dir = dir.path().join("tracevault");
        std::fs::create_dir_all(&creds_dir).unwrap();
        std::fs::write(
            creds_dir.join("credentials.json"),
            format!(
                r#"{{"server_url":"https://example.com","email":"a@b.com","auth":{{"issuer":"http://127.0.0.1:1","client_id":"tracing-cli","refresh_token":"rotated-rt","access_token":"other-process-at","access_expires_at":{}}}}}"#,
                NOW + 3600
            ),
        )
        .unwrap();

        // In memory: the stale session this client was built from.
        let client = ApiClient::with_credential(
            "https://example.com",
            Some(Credential::Keycloak(session(
                "http://127.0.0.1:1",
                NOW + 10,
            ))),
        )
        .with_now(fixed_now);

        let token = client
            .bearer()
            .await
            .expect("adopting the on-disk session must not require the IdP");
        assert_eq!(token.as_deref(), Some("other-process-at"));
    }
    /// There is one credentials file but a machine can target several
    /// TraceVault instances. A file belonging to instance B must NOT be adopted
    /// by a client talking to instance A (that would send B's token to A), and
    /// A's refreshed session must NOT overwrite B's file (that would sign the
    /// user out of B).
    ///
    /// Covers BOTH directions of the `same_server` comparison at this call site:
    /// the mismatch above, and — at the end — that a file differing only by a
    /// trailing slash IS still adopted. Without that second half, replacing
    /// `same_server` with `==` here goes unnoticed and quietly disables the
    /// adopt for every user whose stored URL has a trailing slash.
    #[tokio::test]
    async fn a_credentials_file_for_another_server_is_neither_adopted_nor_overwritten() {
        let _env_lock = crate::test_helpers::lock_env_mutation().await;
        let dir = tempfile::tempdir().unwrap();
        let mut _guard = crate::test_helpers::EnvVarGuard::new();
        _guard.set("XDG_CONFIG_HOME", dir.path());

        let (issuer, rx) = spawn_idp(
            r#"{"access_token":"a-fresh-at","refresh_token":"a-fresh-rt","expires_in":300}"#,
        );

        // On disk: instance B's session, freshly written by `tv login` in
        // another terminal. Different refresh token, plenty of life left — so
        // an unscoped adopt WOULD take it.
        let creds_dir = dir.path().join("tracevault");
        std::fs::create_dir_all(&creds_dir).unwrap();
        let b_file = format!(
            r#"{{"server_url":"https://instance-b.example.com","email":"b@b.com","auth":{{"issuer":"{issuer}","client_id":"tracing-cli","refresh_token":"b-rt","access_token":"b-at","access_expires_at":{}}}}}"#,
            NOW + 3600
        );
        std::fs::write(creds_dir.join("credentials.json"), &b_file).unwrap();

        // This client talks to instance A and holds A's own session.
        let client = ApiClient::with_credential(
            "https://instance-a.example.com",
            Some(Credential::Keycloak(session(&issuer, NOW + 10))),
        )
        .with_now(fixed_now);

        let token = client.bearer().await.expect("A's own refresh must succeed");
        assert_eq!(token.as_deref(), "a-fresh-at".into());

        // The refresh used A's OWN in-memory token — B's was never presented.
        let _discovery = rx.recv_timeout(RECV_TIMEOUT).expect("no discovery request");
        let refresh = rx.recv_timeout(RECV_TIMEOUT).expect("no token request");
        assert!(
            refresh.contains("refresh_token=old-rt"),
            "A must refresh with its own token: {refresh}"
        );
        assert!(
            !refresh.contains("b-rt"),
            "another server's refresh token must never be presented: {refresh}"
        );

        // And B's credentials file is untouched: byte-identical to what
        // `tv login` wrote for B.
        let after = std::fs::read_to_string(creds_dir.join("credentials.json")).unwrap();
        assert_eq!(
            after, b_file,
            "instance A's refresh overwrote instance B's credentials"
        );

        // The other direction at this same call site: a file for the SAME
        // instance, written with a trailing slash (as `tv login` stores whatever
        // it was given, while `ApiClient` trims). It must be adopted — so the
        // comparison has to be `same_server`, not `==`.
        std::fs::write(
            creds_dir.join("credentials.json"),
            format!(
                r#"{{"server_url":"https://instance-a.example.com/","email":"a@b.com","auth":{{"issuer":"http://127.0.0.1:1","client_id":"tracing-cli","refresh_token":"adopted-rt","access_token":"adopted-at","access_expires_at":{}}}}}"#,
                NOW + 3600
            ),
        )
        .unwrap();
        // A dead issuer, so an un-adopted session could only fail here.
        let client = ApiClient::with_credential(
            "https://instance-a.example.com",
            Some(Credential::Keycloak(session(
                "http://127.0.0.1:1",
                NOW + 10,
            ))),
        )
        .with_now(fixed_now);
        assert_eq!(
            client
                .bearer()
                .await
                .expect("a trailing slash must not prevent the adopt")
                .as_deref(),
            Some("adopted-at")
        );
    }

    /// The interleaving that makes the adopt unconditional: the on-disk
    /// session has a NEWER refresh token AND its access token is itself inside
    /// the refresh window. A refresh is genuinely needed, so it must be
    /// performed with the ADOPTED refresh token — refreshing with the
    /// in-memory one, which another client already consumed, is the
    /// guaranteed-`invalid_grant` case the adopt exists to prevent.
    #[tokio::test]
    async fn a_refresh_after_adopting_uses_the_disk_refresh_token() {
        let _env_lock = crate::test_helpers::lock_env_mutation().await;
        let dir = tempfile::tempdir().unwrap();
        let mut _guard = crate::test_helpers::EnvVarGuard::new();
        _guard.set("XDG_CONFIG_HOME", dir.path());

        let (issuer, rx) = spawn_idp(
            r#"{"access_token":"newest-at","refresh_token":"newest-rt","expires_in":300}"#,
        );

        // On disk: another client already rotated the refresh token, but its
        // access token is ALSO within 60s of expiry.
        let creds_dir = dir.path().join("tracevault");
        std::fs::create_dir_all(&creds_dir).unwrap();
        std::fs::write(
            creds_dir.join("credentials.json"),
            format!(
                r#"{{"server_url":"https://example.com","email":"a@b.com","auth":{{"issuer":"{issuer}","client_id":"tracing-cli","refresh_token":"rotated-rt","access_token":"rotated-at","access_expires_at":{}}}}}"#,
                NOW + 5
            ),
        )
        .unwrap();

        // In memory: the superseded session, also inside the window.
        let client = ApiClient::with_credential(
            "https://example.com",
            Some(Credential::Keycloak(session(&issuer, NOW + 10))),
        )
        .with_now(fixed_now);

        let token = client.bearer().await.expect("the refresh must succeed");
        assert_eq!(token.as_deref(), Some("newest-at"));

        let _discovery = rx.recv_timeout(RECV_TIMEOUT).expect("no discovery request");
        let refresh = rx.recv_timeout(RECV_TIMEOUT).expect("no token request");
        assert!(
            refresh.contains("refresh_token=rotated-rt"),
            "the refresh must use the adopted on-disk token: {refresh}"
        );
        assert!(
            !refresh.contains("refresh_token=old-rt"),
            "the superseded in-memory token must NOT be presented: {refresh}"
        );
    }

    /// On an IdP that does NOT rotate refresh tokens — RFC 6749 permits omitting
    /// `refresh_token` on a refresh, and `KeycloakSession::apply` keeps the
    /// previous one — every session on disk and in memory carries the SAME
    /// refresh token. A refresh-token comparison therefore never fires, so
    /// `tracevault status` (three clients from one credential) performed three
    /// redundant refreshes, silently. The on-disk access token outliving ours is
    /// the signal that actually works there.
    ///
    /// The issuer points at a dead port, so any refresh attempt would fail the
    /// call: reaching the assertion proves the adopt happened instead.
    #[tokio::test]
    async fn bearer_adopts_a_fresher_session_from_a_non_rotating_idp() {
        let _env_lock = crate::test_helpers::lock_env_mutation().await;
        let dir = tempfile::tempdir().unwrap();
        let mut _guard = crate::test_helpers::EnvVarGuard::new();
        _guard.set("XDG_CONFIG_HOME", dir.path());

        // On disk: another client refreshed and got a new access token, but the
        // SAME refresh token back (no rotation).
        let creds_dir = dir.path().join("tracevault");
        std::fs::create_dir_all(&creds_dir).unwrap();
        std::fs::write(
            creds_dir.join("credentials.json"),
            format!(
                r#"{{"server_url":"https://example.com","email":"a@b.com","auth":{{"issuer":"http://127.0.0.1:1","client_id":"tracing-cli","refresh_token":"old-rt","access_token":"refreshed-by-someone-else","access_expires_at":{}}}}}"#,
                NOW + 3600
            ),
        )
        .unwrap();

        // In memory: the same refresh token, an access token about to expire.
        let client = ApiClient::with_credential(
            "https://example.com",
            Some(Credential::Keycloak(session(
                "http://127.0.0.1:1",
                NOW + 10,
            ))),
        )
        .with_now(fixed_now);

        let token = client
            .bearer()
            .await
            .expect("a fresher on-disk session must be adopted, not re-refreshed");
        assert_eq!(token.as_deref(), Some("refreshed-by-someone-else"));
    }

    /// Outside the window the stored token is used as-is. The issuer points
    /// at a port nothing listens on, so ANY refresh attempt would fail the
    /// call — proving no network round trip happened.
    #[tokio::test]
    async fn bearer_does_not_refresh_outside_the_window() {
        let client = ApiClient::with_credential(
            "https://example.com",
            Some(Credential::Keycloak(session(
                "http://127.0.0.1:1",
                NOW + 3600,
            ))),
        )
        .with_now(fixed_now);

        let token = client
            .bearer()
            .await
            .expect("a still-valid token must not trigger any IdP call");
        assert_eq!(token.as_deref(), Some("old-at"));
    }

    /// The API-key path is a pure passthrough: no clock, no IdP, no refresh.
    #[tokio::test]
    async fn bearer_returns_an_api_key_verbatim() {
        let client = ApiClient::new("https://example.com", Some("tvk_abc"));
        assert_eq!(client.bearer().await.unwrap().as_deref(), Some("tvk_abc"));

        let anonymous = ApiClient::new("https://example.com", None);
        assert_eq!(anonymous.bearer().await.unwrap(), None);
    }

    /// A 401 on an API key is a real rejection: retrying would double every
    /// failure and could re-run a non-idempotent write. Exactly ONE request
    /// must reach the server.
    #[tokio::test]
    async fn a_401_with_an_api_key_does_not_refresh_or_retry() {
        let (base, rx) = spawn_seq(vec![
            http_json("401 Unauthorized", r#"{"error":"invalid token"}"#),
            // A second response is queued precisely to prove it is unused.
            http_json("200 OK", "[]"),
        ]);
        let client = ApiClient::new(&base, Some("tvk_abc"));
        client
            .list_repos()
            .await
            .expect_err("a 401 must surface as an error");

        let first = rx.recv_timeout(RECV_TIMEOUT).expect("no request captured");
        assert!(first.contains("GET /api/v1/repos"), "{first}");
        assert!(
            rx.recv_timeout(Duration::from_millis(300)).is_err(),
            "an API key must never be retried after a 401"
        );
    }

    /// A Keycloak credential that gets an unexpected 401 (server-side session
    /// invalidation, clock skew) force-refreshes and retries ONCE.
    #[tokio::test]
    async fn a_401_with_a_keycloak_credential_refreshes_and_retries_once() {
        let _env_lock = crate::test_helpers::lock_env_mutation().await;
        let dir = tempfile::tempdir().unwrap();
        let mut _guard = crate::test_helpers::EnvVarGuard::new();
        _guard.set("XDG_CONFIG_HOME", dir.path());

        let (issuer, _idp_rx) =
            spawn_idp(r#"{"access_token":"fresh-at","refresh_token":"fresh-rt","expires_in":300}"#);
        let (base, rx) = spawn_seq(vec![
            http_json("401 Unauthorized", r#"{"error":"expired"}"#),
            http_json("200 OK", "[]"),
        ]);
        // The file is for THIS client's server, so the refreshed session is
        // persisted rather than skipped by the same-server guard.
        write_keycloak_file(dir.path(), &base, &issuer, NOW + 3600);

        // Far from expiry: the proactive window must NOT be what triggers the
        // refresh here — the 401 must.
        let client = ApiClient::with_credential(
            &base,
            Some(Credential::Keycloak(session(&issuer, NOW + 3600))),
        )
        .with_now(fixed_now);

        let repos = client
            .list_repos()
            .await
            .expect("the retry after a forced refresh must succeed");
        assert!(repos.is_empty());

        // The point of the retry is that it presents the REFRESHED token; a
        // retry that re-sent the rejected one would be pointless and would
        // still 401 in production.
        let first = rx.recv_timeout(RECV_TIMEOUT).expect("no first request");
        assert!(first.contains("GET /api/v1/repos"), "{first}");
        assert!(
            first.contains("Bearer old-at"),
            "the first attempt must carry the stored token: {first}"
        );
        let second = rx.recv_timeout(RECV_TIMEOUT).expect("no retry request");
        assert!(second.contains("GET /api/v1/repos"), "{second}");
        assert!(
            second.contains("Bearer fresh-at"),
            "the retry must carry the REFRESHED token, not the rejected one: {second}"
        );
        assert!(
            rx.recv_timeout(Duration::from_millis(300)).is_err(),
            "the retry must happen at most once, or a 401-always server would loop"
        );
    }

    /// A 401 that survives the retry must not send the request a third time:
    /// a server answering 401 unconditionally has to terminate.
    #[tokio::test]
    async fn a_persistent_401_stops_after_one_retry() {
        let _env_lock = crate::test_helpers::lock_env_mutation().await;
        let dir = tempfile::tempdir().unwrap();
        let mut _guard = crate::test_helpers::EnvVarGuard::new();
        _guard.set("XDG_CONFIG_HOME", dir.path());

        let (issuer, _idp_rx) =
            spawn_idp(r#"{"access_token":"fresh-at","refresh_token":"fresh-rt","expires_in":300}"#);
        let (base, rx) = spawn_seq(vec![
            http_json("401 Unauthorized", r#"{"error":"nope"}"#),
            http_json("401 Unauthorized", r#"{"error":"nope"}"#),
            http_json("200 OK", "[]"),
        ]);
        write_keycloak_file(dir.path(), &base, &issuer, NOW + 3600);
        let client = ApiClient::with_credential(
            &base,
            Some(Credential::Keycloak(session(&issuer, NOW + 3600))),
        )
        .with_now(fixed_now);

        client
            .list_repos()
            .await
            .expect_err("a persistent 401 must surface as an error");

        assert!(rx.recv_timeout(RECV_TIMEOUT).is_ok());
        assert!(rx.recv_timeout(RECV_TIMEOUT).is_ok());
        assert!(
            rx.recv_timeout(Duration::from_millis(300)).is_err(),
            "a third attempt means the retry can loop"
        );
    }

    /// A dead refresh token must surface as "log in again", not as a bland
    /// 401 or a network error — `tracevault status` renders those differently.
    #[tokio::test]
    async fn get_me_maps_a_dead_refresh_token_to_unauthorized() {
        let _env_lock = crate::test_helpers::lock_env_mutation().await;
        let dir = tempfile::tempdir().unwrap();
        let mut _guard = crate::test_helpers::EnvVarGuard::new();
        _guard.set("XDG_CONFIG_HOME", dir.path());

        let (issuer, _rx) = spawn_seq_with(|base| {
            vec![
                http_json(
                    "200 OK",
                    &format!(r#"{{"issuer":"{base}","token_endpoint":"{base}/token"}}"#),
                ),
                http_json("400 Bad Request", r#"{"error":"invalid_grant"}"#),
            ]
        });
        write_keycloak_file(dir.path(), "http://127.0.0.1:1", &issuer, NOW + 10);

        let client = ApiClient::with_credential(
            "http://127.0.0.1:1",
            // Inside the window, so the (failing) refresh happens before any
            // request to the server is attempted.
            Some(Credential::Keycloak(session(&issuer, NOW + 10))),
        )
        .with_now(fixed_now);

        match client.get_me().await {
            Err(GetMeError::Unauthorized) => {}
            other => panic!("expected Unauthorized for a dead session, got {other:?}"),
        }
    }

    /// An unreachable IdP is NOT a dead session: it must stay distinguishable
    /// so status says "cannot confirm" rather than "you were logged out".
    #[tokio::test]
    async fn get_me_maps_an_unreachable_idp_to_network() {
        // The session is inside the refresh window, so `refresh_locked` calls
        // `Credentials::load()`. Without this redirect that reads the
        // DEVELOPER's real `~/.config/tracevault/credentials.json` — which on a
        // machine logged in with Keycloak means reading a live token, and makes
        // the test's outcome depend on the developer's own login state.
        let _env_lock = crate::test_helpers::lock_env_mutation().await;
        let dir = tempfile::tempdir().unwrap();
        let mut _guard = crate::test_helpers::EnvVarGuard::new();
        _guard.set("XDG_CONFIG_HOME", dir.path());

        let client = ApiClient::with_credential(
            "http://127.0.0.1:1",
            Some(Credential::Keycloak(session(
                "http://127.0.0.1:1",
                NOW + 10,
            ))),
        )
        .with_now(fixed_now);

        match client.get_me().await {
            Err(GetMeError::Network(_)) => {}
            other => panic!("expected Network for an unreachable IdP, got {other:?}"),
        }
    }

    /// A 403 is its own outcome: the token is fine, the account isn't
    /// authorized, and "log in again" would be the wrong advice.
    #[tokio::test]
    async fn get_me_maps_403_to_forbidden() {
        let (base, _rx) = spawn_seq(vec![http_json(
            "403 Forbidden",
            r#"{"error":"missing role"}"#,
        )]);
        let client = ApiClient::new(&base, Some("tvk_abc"));
        match client.get_me().await {
            Err(GetMeError::Forbidden(_)) => {}
            other => panic!("expected Forbidden, got {other:?}"),
        }
    }

    /// `resolve_client` is the funnel the project/repo commands use, so the
    /// guard has to hold through the wrapper too — not only in
    /// `resolve_credentials`, whose own tests now live beside it in
    /// `credentials.rs`.
    #[test]
    fn resolve_client_also_refuses_a_mismatched_server_url() {
        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
        let dir = tempfile::tempdir().unwrap();
        let mut guard = crate::test_helpers::EnvVarGuard::new();
        guard.set("XDG_CONFIG_HOME", dir.path());
        guard.remove("TRACEVAULT_API_KEY");
        guard.set("TRACEVAULT_SERVER_URL", "https://instance-a.example.com");
        write_keycloak_file(
            dir.path(),
            "https://instance-b.example.com",
            "https://idp.test/realms/v",
            NOW + 3600,
        );

        // `ApiClient` deliberately has no `Debug` (it holds a credential), so
        // match instead of `expect_err`.
        let err = match resolve_client(dir.path()) {
            Err(e) => e,
            Ok(_) => panic!("resolve_client must apply the guard"),
        };
        assert!(err.to_string().contains("instance-b.example.com"));
    }
}