visdom-cli 1.1.1

Visdom developer CLI: checks a project's Visdom wiring and launches the coding agent
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
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
//! `visdom` starting an agent through the AI Gateway, against local stand-ins
//! for the tracing server, Control Plane and the gateway (one server plays
//! all three) and a script standing in for the agent.
#![cfg(target_os = "linux")]

mod common;

use std::os::unix::fs::PermissionsExt;
use std::path::Path;

use common::http::MockServer;
use common::{stderr, stdout, Sandbox};

const PERSON_TOKEN: &str = "person-access-token";
const VARIABLES: [&str; 8] = [
    "VISDOM_GATEWAY_SESSION",
    "CLAUDE_CODE_USE_BEDROCK",
    "VISDOM_TRACING_MODE",
    "ANTHROPIC_BASE_URL",
    "ANTHROPIC_API_KEY",
    "ANTHROPIC_MODEL",
    "ANTHROPIC_CUSTOM_HEADERS",
    "CLAUDE_CODE_API_KEY_HELPER_TTL_MS",
];

const SUITE: (&str, u16, &str) = (
    "GET /api/v1/auth/public-config",
    200,
    r#"{"oidc_enabled":true,"control_plane_url":"{URL}","ai_gateway_url":"{URL}"}"#,
);
const SETTINGS: (&str, u16, &str) = (
    "GET /api/settings",
    200,
    r#"{"llmGatewayUrl":"{URL}","mcpGatewayUrl":"{URL}","suite":[],"controlPlaneUrl":"{URL}"}"#,
);
const ONE_PROJECT: (&str, u16, &str) = (
    "GET /api/me/keys",
    200,
    r#"{"hours":24,"projects":[{"id":"p-1","slug":"alpha","name":"Alpha","budget":null}],"keys":[]}"#,
);
const NO_PROJECT: (&str, u16, &str) = (
    "GET /api/me/keys",
    200,
    r#"{"hours":24,"projects":[],"keys":[]}"#,
);
const ISSUE: (&str, u16, &str) = (
    "POST /api/me/keys",
    201,
    r#"{"secret":"sk-personal","id":"h","name":"personal-dev-1","expiresAt":"2099-01-01T00:00:00Z"}"#,
);
const MODELS: (&str, u16, &str) = (
    "GET /v1/models",
    200,
    r#"{"object":"list","data":[{"id":"gpt-general"},{"id":"claude-sonnet"}]}"#,
);

fn policy(name: &str) -> String {
    format!(r#"{{"timezone":"UTC","ai_traffic_policy":"{name}"}}"#)
}

/// A sandbox logged in to `server`, whose Claude Code is a recording script.
fn sandbox(server: &MockServer) -> (Sandbox, std::path::PathBuf) {
    let sb = Sandbox::new();
    sb.log_in(&server.url, PERSON_TOKEN);
    let (agent, log) = sb.recording_agent(&VARIABLES);
    sb.write_user_config(&format!(
        "[agents]\nclaude_code = \"{}\"\n",
        agent.display()
    ));
    (sb, log)
}

fn lines(log: &Path) -> Vec<String> {
    std::fs::read_to_string(log)
        .unwrap_or_default()
        .lines()
        .map(String::from)
        .collect()
}

fn args(log: &Path) -> Vec<String> {
    lines(log)
        .iter()
        .filter_map(|l| l.strip_prefix("arg:").map(String::from))
        .collect()
}

#[test]
fn a_chosen_gateway_session_gets_a_key_a_model_and_its_ids() {
    let settings = policy("per_agent");
    let server = MockServer::start(&[
        SUITE,
        ("GET /api/v1/workspace/settings", 200, &settings),
        SETTINGS,
        ONE_PROJECT,
        ISSUE,
        MODELS,
    ]);
    let (sb, log) = sandbox(&server);
    let output = sb
        .visdom(sb.repo.path())
        .args(["--mode", "gateway", "--", "--verbose"])
        // Left over from working with another provider.
        .env("CLAUDE_CODE_USE_BEDROCK", "1")
        .output()
        .unwrap();
    assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));

    let recorded = lines(&log);
    let has = |line: &str| recorded.iter().any(|l| l == line);
    assert!(has("VISDOM_TRACING_MODE=gateway"), "{recorded:?}");
    assert!(has("VISDOM_GATEWAY_SESSION=claude-code"), "{recorded:?}");
    assert!(has("CLAUDE_CODE_USE_BEDROCK unset"), "{recorded:?}");
    assert!(
        has(&format!("ANTHROPIC_BASE_URL={}", server.url)),
        "{recorded:?}"
    );
    assert!(has("ANTHROPIC_API_KEY unset"), "{recorded:?}");
    assert!(has("ANTHROPIC_MODEL=claude-sonnet"), "{recorded:?}");
    assert!(
        has("CLAUDE_CODE_API_KEY_HELPER_TTL_MS=300000"),
        "{recorded:?}"
    );
    assert!(
        recorded
            .iter()
            .any(|l| l == "ANTHROPIC_CUSTOM_HEADERS=x-tracevault-agent: claude-code"),
        "{recorded:?}"
    );

    let args = args(&log);
    assert_eq!(args[0], "--settings");
    let helper = serde_json::from_str::<serde_json::Value>(&args[1]).unwrap()["apiKeyHelper"]
        .as_str()
        .unwrap()
        .to_string();
    assert!(helper.contains("gateway-key"), "{helper}");
    assert_eq!(args[2], "--session-id");
    assert_eq!(args[4], "--verbose");
    // The key reaches the agent through the helper only.
    assert!(
        !recorded.iter().any(|l| l.contains("sk-personal")),
        "{recorded:?}"
    );

    // Control Plane and the gateway were asked as the person.
    for asked in server.requests() {
        if asked.route != "GET /api/v1/auth/public-config" && asked.route != "GET /v1/models" {
            assert_eq!(
                asked.authorization.as_deref(),
                Some("Bearer person-access-token"),
                "{}",
                asked.route
            );
        }
    }
    assert_eq!(
        server
            .routes()
            .iter()
            .filter(|r| *r == "POST /api/me/keys")
            .count(),
        1
    );

    // The key is kept, for the user alone, and the helper prints it without
    // asking anybody again.
    let store = sb.home.path().join(".config/visdom/gateway-keys.json");
    let mode = std::fs::metadata(&store).unwrap().permissions().mode();
    assert_eq!(mode & 0o777, 0o600);
    let before = server.routes().len();
    let helper_run = std::process::Command::new("sh")
        .arg("-c")
        .arg(&helper)
        .current_dir(sb.repo.path())
        .env("HOME", sb.home.path())
        .env("XDG_CONFIG_HOME", sb.home.path().join(".config"))
        .output()
        .unwrap();
    assert_eq!(
        stdout(&helper_run),
        "sk-personal\n",
        "{}",
        stderr(&helper_run)
    );
    assert_eq!(server.routes().len(), before, "answered from the kept key");
}

#[test]
fn a_second_session_shares_the_kept_key() {
    let settings = policy("per_agent");
    let server = MockServer::start(&[
        SUITE,
        ("GET /api/v1/workspace/settings", 200, &settings),
        SETTINGS,
        ONE_PROJECT,
        ISSUE,
        MODELS,
    ]);
    let (sb, log) = sandbox(&server);
    for _ in 0..2 {
        let output = sb
            .visdom(sb.repo.path())
            .args(["--mode", "gateway"])
            .output()
            .unwrap();
        assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
    }
    let issued = server
        .routes()
        .iter()
        .filter(|r| *r == "POST /api/me/keys")
        .count();
    assert_eq!(issued, 1, "a new key would revoke the first session's");
    let sessions: Vec<String> = args(&log)
        .windows(2)
        .filter(|w| w[0] == "--session-id")
        .map(|w| w[1].clone())
        .collect();
    assert_eq!(sessions.len(), 2);
    assert_ne!(sessions[0], sessions[1], "each session has its own id");
}

#[test]
fn an_enforcing_workspace_puts_every_session_through_the_gateway() {
    let settings = policy("enforced");
    let server = MockServer::start(&[
        SUITE,
        ("GET /api/v1/workspace/settings", 200, &settings),
        SETTINGS,
        ONE_PROJECT,
        ISSUE,
        MODELS,
    ]);
    let (sb, log) = sandbox(&server);
    // Nothing chosen, and then hooks chosen: the gateway either way.
    for chosen in [vec![], vec!["--mode", "hooks"]] {
        let output = sb.visdom(sb.repo.path()).args(&chosen).output().unwrap();
        assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
        if !chosen.is_empty() {
            assert!(
                stderr(&output).contains("`enforced`"),
                "{}",
                stderr(&output)
            );
        }
    }
    let modes: Vec<String> = lines(&log)
        .into_iter()
        .filter(|l| l.starts_with("VISDOM_TRACING_MODE"))
        .collect();
    assert_eq!(
        modes,
        ["VISDOM_TRACING_MODE=gateway", "VISDOM_TRACING_MODE=gateway"]
    );
}

#[test]
fn an_enforcing_workspace_does_not_start_an_agent_it_cannot_route() {
    let settings = policy("enforced");
    let server = MockServer::start(&[
        SUITE,
        ("GET /api/v1/workspace/settings", 200, &settings),
        SETTINGS,
        NO_PROJECT,
    ]);
    let (sb, log) = sandbox(&server);
    let output = sb.visdom(sb.repo.path()).output().unwrap();
    assert_eq!(output.status.code(), Some(1), "{}", stderr(&output));
    let said = stderr(&output);
    assert!(said.contains("personal keys on"), "{said}");
    assert!(said.contains("the agent is not started"), "{said}");
    assert!(lines(&log).is_empty(), "the agent must not have run");
}

#[test]
fn a_chosen_gateway_that_is_not_ready_falls_back_to_hooks() {
    let settings = policy("per_agent");
    let server = MockServer::start(&[
        SUITE,
        ("GET /api/v1/workspace/settings", 200, &settings),
        SETTINGS,
        NO_PROJECT,
    ]);
    let (sb, log) = sandbox(&server);
    let output = sb
        .visdom(sb.repo.path())
        .args(["--mode", "gateway", "--", "--verbose"])
        .output()
        .unwrap();
    assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
    assert!(
        stderr(&output).contains("with hooks tracing instead"),
        "{}",
        stderr(&output)
    );
    let recorded = lines(&log);
    assert!(
        recorded.contains(&"VISDOM_TRACING_MODE=hooks".to_string()),
        "{recorded:?}"
    );
    assert!(
        recorded.contains(&"ANTHROPIC_BASE_URL unset".to_string()),
        "{recorded:?}"
    );
    assert_eq!(args(&log), ["--verbose"]);
}

/// A workspace that keeps sessions on hooks, so nothing of the gateway's is
/// needed to start an agent.
fn hooks_workspace() -> MockServer {
    let settings = policy("direct");
    MockServer::start(&[SUITE, ("GET /api/v1/workspace/settings", 200, &settings)])
}

/// The agent's hooks, installed for the whole machine: what binds a session
/// to its repository.
fn install_hooks(sb: &Sandbox, file: &str) {
    let path = sb.home.path().join(file);
    std::fs::create_dir_all(path.parent().unwrap()).unwrap();
    std::fs::write(
        path,
        r#"{"hooks":{"SessionStart":[{"hooks":[{"type":"command","command":"visdom trace session-start"}]}]}}"#,
    )
    .unwrap();
}

const CLAUDE_HOOKS: &str = ".claude/settings.json";
const CODEX_HOOKS: &str = ".codex/hooks.json";

#[test]
fn a_session_with_hooks_is_told_how_to_ask_for_its_policies() {
    let server = hooks_workspace();
    let (sb, log) = sandbox(&server);
    install_hooks(&sb, CLAUDE_HOOKS);
    let output = sb
        .visdom(sb.repo.path())
        .args(["--", "--verbose"])
        .output()
        .unwrap();
    assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
    assert_eq!(
        args(&log),
        ["--append-system-prompt", "# Visdom", "--verbose"]
    );
    let told = std::fs::read_to_string(&log).unwrap();
    assert!(told.contains("visdom trace agent-policies"), "{told}");
    assert!(told.contains("visdom trace repo switch <path>"), "{told}");
    assert!(told.contains("visdom trace check"), "{told}");
    assert!(!told.contains("## AI Gateway"), "{told}");
    // Nothing is registered for this agent.
    assert!(!told.contains("Bazaar"), "{told}");
}

#[test]
fn a_session_through_the_gateway_is_told_to_leave_the_provider_alone() {
    let settings = policy("per_agent");
    let server = MockServer::start(&[
        SUITE,
        ("GET /api/v1/workspace/settings", 200, &settings),
        SETTINGS,
        ONE_PROJECT,
        ISSUE,
        MODELS,
    ]);
    let (sb, log) = sandbox(&server);
    install_hooks(&sb, CLAUDE_HOOKS);
    let output = sb
        .visdom(sb.repo.path())
        .args(["--mode", "gateway", "--", "--verbose"])
        .output()
        .unwrap();
    assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
    let args = args(&log);
    // After what routes the session, ahead of the caller's options.
    assert_eq!(args[0], "--settings");
    assert_eq!(args[2], "--session-id");
    assert_eq!(
        args[4..],
        ["--append-system-prompt", "# Visdom", "--verbose"]
    );
    let told = std::fs::read_to_string(&log).unwrap();
    assert!(told.contains("## AI Gateway"), "{told}");
    assert!(told.contains("visdom trace repo switch <path>"), "{told}");
    // A check made by the hooks, which record nothing of this session.
    assert!(!told.contains("visdom trace check"), "{told}");
}

#[test]
fn an_agent_is_told_about_the_bazaar_it_has_under_the_name_it_has_it() {
    const BAZAAR: &str = "https://ctx.example.com/mcp/remote";
    let server = hooks_workspace();
    let (sb, log) = sandbox(&server);
    std::fs::write(
        sb.home.path().join(".claude.json"),
        format!(r#"{{"mcpServers":{{"org-context":{{"type":"http","url":"{BAZAAR}"}}}}}}"#),
    )
    .unwrap();
    let run = |agent_args: &[&str]| {
        let _ = std::fs::remove_file(&log);
        let output = sb
            .visdom(sb.repo.path())
            .env("VISDOM_BAZAAR_URL", BAZAAR)
            .arg("--")
            .args(agent_args)
            .output()
            .unwrap();
        assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
        (args(&log), std::fs::read_to_string(&log).unwrap())
    };

    // The caller's own addition stays, after visdom's.
    let (args, told) = run(&["--append-system-prompt", "Answer in Polish.", "-p", "hi"]);
    assert_eq!(args[0], "--append-system-prompt");
    assert_eq!(args[args.len() - 2..], ["-p", "hi"], "{args:?}");
    assert_eq!(
        args.iter()
            .filter(|a| *a == "--append-system-prompt")
            .count(),
        1,
        "{args:?}"
    );
    assert!(
        told.contains("## Bazaar: the `org-context` MCP server"),
        "{told}"
    );
    // Without the hooks no session is bound: nothing is said of policies.
    assert!(!told.contains("visdom trace"), "{told}");
    let (ours, theirs) = (
        told.find("visdom doctor").unwrap(),
        told.find("Answer in Polish.").unwrap(),
    );
    assert!(ours < theirs, "{told}");

    // Started without its registered servers, it has no bazaar to be told
    // of, and then nothing at all.
    let (args, _) = run(&["--strict-mcp-config", "-p", "hi"]);
    assert_eq!(args, ["--strict-mcp-config", "-p", "hi"]);
}

#[test]
fn an_agent_is_told_nothing_when_that_is_asked_for() {
    let server = hooks_workspace();
    let (sb, log) = sandbox(&server);
    install_hooks(&sb, CLAUDE_HOOKS);
    let output = sb
        .visdom(sb.repo.path())
        .args(["--no-instructions", "--", "--verbose"])
        .output()
        .unwrap();
    assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
    assert_eq!(args(&log), ["--verbose"]);

    // A Claude Code that runs no hooks has no bound session to be told of.
    std::fs::remove_file(&log).unwrap();
    let output = sb
        .visdom(sb.repo.path())
        .args(["--", "--bare", "-p", "hi"])
        .output()
        .unwrap();
    assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
    assert_eq!(args(&log), ["--bare", "-p", "hi"]);

    std::fs::remove_file(&log).unwrap();
    let config = std::fs::read_to_string(sb.user_config()).unwrap();
    sb.write_user_config(&format!("agent_instructions = false\n{config}"));
    let output = sb
        .visdom(sb.repo.path())
        .args(["--", "--verbose"])
        .output()
        .unwrap();
    assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
    assert_eq!(args(&log), ["--verbose"]);
}

#[test]
fn codex_is_told_in_its_developer_instructions_ahead_of_the_developers_own() {
    let server = hooks_workspace();
    let sb = Sandbox::new();
    sb.log_in(&server.url, PERSON_TOKEN);
    let (agent, log) = sb.recording_agent(&VARIABLES);
    sb.write_user_config(&format!("[agents]\ncodex = \"{}\"\n", agent.display()));
    install_hooks(&sb, CODEX_HOOKS);
    std::fs::write(
        sb.home.path().join(".codex/config.toml"),
        "developer_instructions = \"Keep answers short.\"\n",
    )
    .unwrap();
    let run = || {
        let _ = std::fs::remove_file(&log);
        let output = sb
            .visdom(sb.repo.path())
            .args(["--agent", "codex", "--", "exec", "say hi"])
            .output()
            .unwrap();
        assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
        (args(&log), stderr(&output))
    };

    let (args, said) = run();
    assert_eq!(args[0], "-c");
    assert_eq!(args[2..], ["exec", "say hi"], "{args:?}");
    // One line, a TOML string: read back as Codex reads it.
    let setting: toml::Table = toml::from_str(&args[1]).unwrap();
    let told = setting["developer_instructions"].as_str().unwrap();
    assert!(told.starts_with("# Visdom\n"), "{told}");
    assert!(told.contains("visdom trace agent-policies"), "{told}");
    assert!(told.ends_with("\n\nKeep answers short."), "{told}");
    assert!(!said.contains("developer instructions"), "{said}");

    // A project's own are Codex's to read or not (its trust): they are
    // neither replaced nor made into an option, and the developer is told.
    let project = sb.repo.path().join(".codex/config.toml");
    std::fs::create_dir_all(project.parent().unwrap()).unwrap();
    std::fs::write(&project, "developer_instructions = \"Project rules.\"\n").unwrap();
    let (args, said) = run();
    assert_eq!(args, ["exec", "say hi"]);
    assert!(
        said.contains(".codex/config.toml sets Codex's developer instructions"),
        "{said}"
    );
    assert!(said.contains("visdom instructions"), "{said}");
    assert_eq!(said.matches("developer instructions").count(), 1, "{said}");
}

/// What is added for the agent takes nothing from the routing: Codex goes
/// through the gateway with the instructions, the caller's own kept, and an
/// option that would take it elsewhere still stops the launch.
#[test]
fn codex_through_the_gateway_is_told_and_still_cannot_be_sent_elsewhere() {
    let settings = policy("enforced");
    let server = MockServer::start(&[
        SUITE,
        ("GET /api/v1/workspace/settings", 200, &settings),
        SETTINGS,
        ONE_PROJECT,
        ISSUE,
        MODELS,
    ]);
    let sb = Sandbox::new();
    sb.log_in(&server.url, PERSON_TOKEN);
    let (agent, log) = sb.recording_agent(&VARIABLES);
    sb.write_user_config(&format!("[agents]\ncodex = \"{}\"\n", agent.display()));
    install_hooks(&sb, CODEX_HOOKS);

    let output = sb
        .visdom(sb.repo.path())
        .args(["--agent", "codex", "--"])
        .args([
            "-c",
            "developer_instructions=Mine",
            "-c",
            "model_provider=openai",
        ])
        .output()
        .unwrap();
    assert_eq!(output.status.code(), Some(1), "{}", stderr(&output));
    assert!(
        stderr(&output).contains("`-c model_provider=openai`"),
        "{}",
        stderr(&output)
    );
    assert!(lines(&log).is_empty(), "the agent must not have run");

    let output = sb
        .visdom(sb.repo.path())
        .args(["--agent", "codex", "--"])
        .args(["-c", "developer_instructions=Mine", "exec", "hi"])
        .output()
        .unwrap();
    assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
    assert_eq!(modes(&log), ["VISDOM_TRACING_MODE=gateway"]);
    let args = args(&log);
    assert!(args.contains(&r#"model_provider="visdom-gateway""#.to_string()));
    assert_eq!(args[args.len() - 2..], ["exec", "hi"], "{args:?}");
    let told: Vec<&String> = args
        .iter()
        .filter(|a| a.starts_with("developer_instructions="))
        .collect();
    assert_eq!(told.len(), 1, "{args:?}");
    let setting: toml::Table = toml::from_str(told[0]).unwrap();
    let told = setting["developer_instructions"].as_str().unwrap();
    assert!(told.contains("## AI Gateway"), "{told}");
    assert!(told.ends_with("\n\nMine"), "{told}");
}

#[test]
fn instructions_prints_what_an_agent_would_be_told() {
    let server = hooks_workspace();
    let (sb, log) = sandbox(&server);
    let print = || {
        let output = sb
            .visdom(sb.repo.path())
            .arg("instructions")
            .output()
            .unwrap();
        assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
        stdout(&output)
    };
    // Logged in, but no hook binds a session here: nothing to tell.
    assert_eq!(print(), "");

    install_hooks(&sb, CLAUDE_HOOKS);
    let told = print();
    assert!(told.starts_with("# Visdom\n"), "{told}");
    assert!(told.contains("visdom trace repo switch <path>"), "{told}");
    assert!(lines(&log).is_empty(), "no agent is started");
}

#[test]
fn a_direct_workspace_keeps_sessions_on_hooks() {
    let settings = policy("direct");
    let server = MockServer::start(&[SUITE, ("GET /api/v1/workspace/settings", 200, &settings)]);
    let (sb, log) = sandbox(&server);
    let output = sb
        .visdom(sb.repo.path())
        .args(["--mode", "gateway"])
        // What is left in the environment (of a gateway session's shell,
        // say) must not switch the hooks' capture off either.
        .env("VISDOM_TRACING_MODE", "gateway")
        .env("VISDOM_GATEWAY_SESSION", "claude-code")
        .output()
        .unwrap();
    assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
    assert!(stderr(&output).contains("`direct`"), "{}", stderr(&output));
    let recorded = lines(&log);
    assert!(
        recorded.contains(&"VISDOM_TRACING_MODE=hooks".to_string()),
        "{recorded:?}"
    );
    assert!(
        recorded.contains(&"VISDOM_GATEWAY_SESSION unset".to_string()),
        "{recorded:?}"
    );
    assert!(
        !server.routes().iter().any(|r| r.contains("/api/me/keys")),
        "the gateway is not asked for anything"
    );
}

#[test]
fn an_api_key_is_never_sent_beyond_the_tracing_server() {
    let settings = policy("per_agent");
    let server = MockServer::start(&[
        SUITE,
        ("GET /api/v1/workspace/settings", 200, &settings),
        SETTINGS,
        ONE_PROJECT,
        ISSUE,
    ]);
    let sb = Sandbox::new();
    let (agent, log) = sb.recording_agent(&VARIABLES);
    sb.write_user_config(&format!(
        "[agents]\nclaude_code = \"{}\"\n",
        agent.display()
    ));
    let output = sb
        .visdom(sb.repo.path())
        .args(["--mode", "gateway"])
        .env("VISDOM_API_KEY", "tvk_secret")
        .env("VISDOM_SERVER_URL", &server.url)
        .output()
        .unwrap();
    assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
    assert!(
        stderr(&output).contains("Visdom account login"),
        "{}",
        stderr(&output)
    );
    for asked in server.requests() {
        assert_eq!(asked.authorization, None, "{}", asked.route);
    }
    assert!(lines(&log).contains(&"VISDOM_TRACING_MODE=hooks".to_string()));
}

#[test]
fn doctor_reports_the_mode_without_issuing_a_key() {
    let settings = policy("per_agent");
    let server = MockServer::start(&[
        SUITE,
        ("GET /api/v1/workspace/settings", 200, &settings),
        SETTINGS,
        ONE_PROJECT,
        ISSUE,
    ]);
    let (sb, _log) = sandbox(&server);
    let output = sb
        .visdom(sb.repo.path())
        .args(["doctor", "--json", "--mode", "gateway"])
        .output()
        .unwrap();
    let json: serde_json::Value = serde_json::from_str(&stdout(&output)).unwrap();
    let find = |id: &str| {
        json["findings"]
            .as_array()
            .unwrap()
            .iter()
            .find(|f| f["id"] == id)
            .cloned()
            .unwrap_or_else(|| panic!("no {id} in {json}"))
    };
    assert_eq!(find("gateway.mode")["severity"], "ok");
    assert!(find("gateway.project")["message"]
        .as_str()
        .unwrap()
        .contains("`alpha`"));
    assert!(
        !server.routes().iter().any(|r| r == "POST /api/me/keys"),
        "a check issues nothing: a new key would revoke the one in use"
    );
}

fn count(server: &MockServer, route: &str) -> usize {
    server.routes().iter().filter(|r| *r == route).count()
}

fn modes(log: &Path) -> Vec<String> {
    lines(log)
        .into_iter()
        .filter(|l| l.starts_with("VISDOM_TRACING_MODE"))
        .collect()
}

/// The tracing server names Control Plane. While it is away, a workspace
/// that requires the gateway still does: what the server said last holds.
#[test]
fn an_enforcing_workspace_still_enforces_while_the_tracing_server_is_away() {
    let settings = policy("enforced");
    let server = MockServer::start(&[
        SUITE,
        ("GET /api/v1/auth/public-config", 503, "{}"),
        ("GET /api/v1/workspace/settings", 200, &settings),
        SETTINGS,
        ONE_PROJECT,
        ISSUE,
        MODELS,
    ]);
    let (sb, log) = sandbox(&server);
    for _ in 0..2 {
        let output = sb.visdom(sb.repo.path()).output().unwrap();
        assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
    }
    assert_eq!(count(&server, "GET /api/v1/auth/public-config"), 2);
    assert_eq!(
        modes(&log),
        ["VISDOM_TRACING_MODE=gateway", "VISDOM_TRACING_MODE=gateway"],
        "the second session must not fall to hooks"
    );
}

#[test]
fn a_chosen_gateway_whose_llm_endpoint_fails_falls_back_to_hooks() {
    let settings = policy("per_agent");
    let server = MockServer::start(&[
        SUITE,
        ("GET /api/v1/workspace/settings", 200, &settings),
        SETTINGS,
        ONE_PROJECT,
        ISSUE,
        ("GET /v1/models", 502, "{}"),
    ]);
    let (sb, log) = sandbox(&server);
    let output = sb
        .visdom(sb.repo.path())
        .args(["--mode", "gateway"])
        .output()
        .unwrap();
    assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
    let said = stderr(&output);
    assert!(
        said.contains("cannot list the AI Gateway's models"),
        "{said}"
    );
    assert!(said.contains("with hooks tracing instead"), "{said}");
    assert_eq!(modes(&log), ["VISDOM_TRACING_MODE=hooks"]);
    assert!(lines(&log).contains(&"ANTHROPIC_BASE_URL unset".to_string()));
}

#[test]
fn an_enforcing_workspace_does_not_start_an_agent_whose_llm_endpoint_fails() {
    let settings = policy("enforced");
    let server = MockServer::start(&[
        SUITE,
        ("GET /api/v1/workspace/settings", 200, &settings),
        SETTINGS,
        ONE_PROJECT,
        ISSUE,
        ("GET /v1/models", 502, "{}"),
    ]);
    let (sb, log) = sandbox(&server);
    let output = sb.visdom(sb.repo.path()).output().unwrap();
    assert_eq!(output.status.code(), Some(1), "{}", stderr(&output));
    let said = stderr(&output);
    assert!(
        said.contains("cannot list the AI Gateway's models"),
        "{said}"
    );
    assert!(said.contains("the agent is not started"), "{said}");
    assert!(lines(&log).is_empty(), "the agent must not have run");
}

/// A key issued elsewhere (the console) revokes the kept one: the gateway
/// refuses it, and the session gets a new key instead of a dead one.
#[test]
fn a_kept_key_the_gateway_refuses_is_replaced() {
    let settings = policy("per_agent");
    let server = MockServer::start(&[
        SUITE,
        ("GET /api/v1/workspace/settings", 200, &settings),
        SETTINGS,
        ONE_PROJECT,
        ISSUE,
        (
            "POST /api/me/keys",
            201,
            r#"{"secret":"sk-second","id":"h2","name":"personal-dev-2","expiresAt":"2099-01-01T00:00:00Z"}"#,
        ),
        MODELS,
        ("GET /v1/models", 401, r#"{"error":"revoked"}"#),
        MODELS,
    ]);
    let (sb, log) = sandbox(&server);
    for _ in 0..2 {
        let output = sb
            .visdom(sb.repo.path())
            .args(["--mode", "gateway"])
            .output()
            .unwrap();
        assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
    }
    assert_eq!(count(&server, "POST /api/me/keys"), 2);
    assert_eq!(count(&server, "GET /v1/models"), 3);
    let asked: Vec<Option<String>> = server
        .requests()
        .into_iter()
        .filter(|r| r.route == "GET /v1/models")
        .map(|r| r.authorization)
        .collect();
    assert_eq!(
        asked,
        ["sk-personal", "sk-personal", "sk-second"].map(|k| Some(format!("Bearer {k}")))
    );
    assert_eq!(modes(&log), ["VISDOM_TRACING_MODE=gateway"; 2]);
    let kept =
        std::fs::read_to_string(sb.home.path().join(".config/visdom/gateway-keys.json")).unwrap();
    assert!(
        kept.contains("sk-second") && !kept.contains("sk-personal"),
        "{kept}"
    );
}

fn key_helper(sb: &Sandbox, server: &MockServer) -> std::process::Output {
    sb.visdom(sb.repo.path())
        .args(["gateway-key", "--console", &server.url, "--project", "p-1"])
        .output()
        .unwrap()
}

/// What Claude Code runs during a long session: a key about to expire is
/// renewed with the stored login, kept, and nothing but the key is printed.
#[test]
fn the_key_helper_renews_an_expiring_key() {
    let server = MockServer::start(&[ISSUE]);
    let (sb, _log) = sandbox(&server);
    let store = sb.home.path().join(".config/visdom/gateway-keys.json");
    let soon = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_secs()
        + 60;
    std::fs::write(
        &store,
        serde_json::json!([{
            "console_url": server.url, "project_id": "p-1", "account": "",
            "secret": "sk-expiring", "expires_at": soon,
        }])
        .to_string(),
    )
    .unwrap();

    let output = key_helper(&sb, &server);
    assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
    assert_eq!(stdout(&output), "sk-personal\n");
    let asked = server.requests();
    assert_eq!(asked.len(), 1);
    assert_eq!(asked[0].route, "POST /api/me/keys");
    assert_eq!(
        asked[0].authorization.as_deref(),
        Some("Bearer person-access-token")
    );
    let kept = std::fs::read_to_string(&store).unwrap();
    assert!(
        kept.contains("sk-personal") && !kept.contains("sk-expiring"),
        "{kept}"
    );
    assert_eq!(
        std::fs::metadata(&store).unwrap().permissions().mode() & 0o777,
        0o600
    );
    // And from then on it is answered from the store.
    assert_eq!(stdout(&key_helper(&sb, &server)), "sk-personal\n");
    assert_eq!(server.requests().len(), 1);
}

#[test]
fn a_key_helper_that_cannot_renew_fails_without_printing_anything() {
    let server = MockServer::start(&[(
        "POST /api/me/keys",
        403,
        r#"{"error":"Alpha does not allow personal keys"}"#,
    )]);
    let (sb, _log) = sandbox(&server);
    let output = key_helper(&sb, &server);
    assert_eq!(output.status.code(), Some(1));
    assert_eq!(stdout(&output), "", "stdout is the key, or nothing");
    let said = stderr(&output);
    assert!(said.contains("does not allow personal keys"), "{said}");
    assert!(!said.contains(PERSON_TOKEN), "{said}");

    // Without a login there is nobody to renew it for.
    let anonymous = Sandbox::new();
    let output = key_helper(&anonymous, &server);
    assert_eq!(output.status.code(), Some(1));
    assert_eq!(stdout(&output), "");
    assert!(
        stderr(&output).contains("visdom login"),
        "{}",
        stderr(&output)
    );
    assert_eq!(
        server.requests().len(),
        1,
        "nothing was asked without a login"
    );
}

#[test]
fn logging_out_forgets_the_kept_keys() {
    let server = MockServer::start(&[ISSUE]);
    let (sb, _log) = sandbox(&server);
    assert_eq!(stdout(&key_helper(&sb, &server)), "sk-personal\n");
    let store = sb.home.path().join(".config/visdom/gateway-keys.json");
    assert!(store.exists());
    // Whether or not the identity provider can be told.
    let _ = sb.visdom(sb.repo.path()).arg("logout").output().unwrap();
    assert!(!store.exists(), "the keys go with the login");
}

/// Codex takes the caller's `-c` overrides after visdom's: one that names
/// another provider would take the session past a gateway the workspace
/// requires, so nothing is started.
#[test]
fn an_enforcing_workspace_does_not_start_codex_told_to_use_another_provider() {
    let settings = policy("enforced");
    let server = MockServer::start(&[
        SUITE,
        ("GET /api/v1/workspace/settings", 200, &settings),
        SETTINGS,
        ONE_PROJECT,
        ISSUE,
        MODELS,
    ]);
    let sb = Sandbox::new();
    sb.log_in(&server.url, PERSON_TOKEN);
    let (agent, log) = sb.recording_agent(&VARIABLES);
    sb.write_user_config(&format!("[agents]\ncodex = \"{}\"\n", agent.display()));
    let output = sb
        .visdom(sb.repo.path())
        .args(["--agent", "codex", "--", "-c", "model_provider=openai"])
        .output()
        .unwrap();
    assert_eq!(output.status.code(), Some(1), "{}", stderr(&output));
    let said = stderr(&output);
    assert!(said.contains("`-c model_provider=openai`"), "{said}");
    assert!(said.contains("the agent is not started"), "{said}");
    assert!(lines(&log).is_empty(), "the agent must not have run");

    // Without it, Codex starts on the gateway's provider.
    let output = sb
        .visdom(sb.repo.path())
        .args(["--agent", "codex"])
        .output()
        .unwrap();
    assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
    assert_eq!(modes(&log), ["VISDOM_TRACING_MODE=gateway"]);
    assert!(args(&log).contains(&r#"model_provider="visdom-gateway""#.to_string()));
}

const TWO_PROJECTS: (&str, u16, &str) = (
    "GET /api/me/keys",
    200,
    r#"{"hours":24,"projects":[{"id":"p-1","slug":"alpha","name":"Alpha","budget":null},{"id":"p-2","slug":"beta","name":"Beta","budget":null}],"keys":[]}"#,
);

/// Run `script` (the output of `visdom env`) in a shell of the sandbox, then
/// `command` in the same shell.
fn sourced(sb: &Sandbox, script: &str, command: &str) -> std::process::Output {
    // The sandbox's own environment, as `visdom` is given it.
    let shell = sb.visdom(sb.repo.path());
    let mut cmd = std::process::Command::new("sh");
    cmd.arg("-c")
        .arg(format!("{script}\n{command}"))
        .current_dir(sb.repo.path());
    for (name, value) in shell.get_envs() {
        match value {
            Some(value) => cmd.env(name, value),
            None => cmd.env_remove(name),
        };
    }
    // `visdom` in the script is named by its full path.
    cmd.output().unwrap()
}

/// `visdom env`: what makes a Claude Code started by hand go through the
/// gateway. The key is not in it — only the command that gets it.
#[test]
fn env_sends_a_claude_started_without_visdom_through_the_gateway() {
    let settings = policy("per_agent");
    let server = MockServer::start(&[
        SUITE,
        ("GET /api/v1/workspace/settings", 200, &settings),
        SETTINGS,
        ONE_PROJECT,
        ISSUE,
        MODELS,
    ]);
    let sb = Sandbox::new();
    sb.log_in(&server.url, PERSON_TOKEN);
    let (agent, log) = sb.recording_agent(&[
        "ANTHROPIC_BASE_URL",
        "ANTHROPIC_AUTH_TOKEN",
        "ANTHROPIC_API_KEY",
        "ANTHROPIC_MODEL",
        "ANTHROPIC_CUSTOM_HEADERS",
        "VISDOM_GATEWAY_SESSION",
        "CLAUDE_CODE_USE_BEDROCK",
    ]);
    // Hooks at rest: asking for the variables is asking for the gateway.
    let output = sb.visdom(sb.repo.path()).arg("env").output().unwrap();
    assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
    let script = stdout(&output);
    assert!(!script.contains("sk-personal"), "{script}");
    assert!(script.contains("gateway-key --console"), "{script}");
    assert!(script.contains("project `alpha`"), "{script}");

    let run = sourced(
        &sb,
        &format!("export ANTHROPIC_API_KEY=sk-mine CLAUDE_CODE_USE_BEDROCK=1\n{script}"),
        &format!("'{}' --verbose", agent.display()),
    );
    assert!(run.status.success(), "{}", stderr(&run));
    let recorded = lines(&log);
    let has = |line: &str| recorded.iter().any(|l| l == line);
    assert!(
        has(&format!("ANTHROPIC_BASE_URL={}", server.url)),
        "{recorded:?}"
    );
    assert!(has("ANTHROPIC_AUTH_TOKEN=sk-personal"), "{recorded:?}");
    assert!(has("ANTHROPIC_API_KEY unset"), "{recorded:?}");
    assert!(has("ANTHROPIC_MODEL=claude-sonnet"), "{recorded:?}");
    assert!(has("VISDOM_GATEWAY_SESSION=claude-code"), "{recorded:?}");
    assert!(has("CLAUDE_CODE_USE_BEDROCK unset"), "{recorded:?}");
    assert!(
        has("ANTHROPIC_CUSTOM_HEADERS=x-tracevault-agent: claude-code"),
        "{recorded:?}"
    );
    assert_eq!(args(&log), ["--verbose"]);
}

/// Codex takes its provider as options, so the script defines a `codex`
/// function that adds them to whatever it is called with.
#[test]
fn env_gives_codex_a_function_that_adds_the_gateway() {
    let settings = policy("enforced");
    let server = MockServer::start(&[
        SUITE,
        ("GET /api/v1/workspace/settings", 200, &settings),
        SETTINGS,
        ONE_PROJECT,
        ISSUE,
        MODELS,
    ]);
    let sb = Sandbox::new();
    sb.log_in(&server.url, PERSON_TOKEN);
    let (agent, log) = sb.recording_agent(&["VISDOM_GATEWAY_API_KEY", "VISDOM_GATEWAY_SESSION"]);
    sb.write_user_config(&format!("[agents]\ncodex = \"{}\"\n", agent.display()));
    let output = sb
        .visdom(sb.repo.path())
        .args(["env", "--agent", "codex"])
        .output()
        .unwrap();
    assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
    let script = stdout(&output);
    assert!(!script.contains("sk-personal"), "{script}");

    let run = sourced(&sb, &script, "codex exec 'say hi'");
    assert!(run.status.success(), "{}", stderr(&run));
    let recorded = lines(&log);
    assert!(
        recorded.contains(&"VISDOM_GATEWAY_API_KEY=sk-personal".to_string()),
        "{recorded:?}"
    );
    assert!(
        recorded.contains(&"VISDOM_GATEWAY_SESSION=codex".to_string()),
        "{recorded:?}"
    );
    let args = args(&log);
    assert!(
        args.contains(&"model_provider=\"visdom-gateway\"".to_string()),
        "{args:?}"
    );
    assert!(
        args.iter().any(|a| a
            == &format!(
                "model_providers.visdom-gateway.base_url=\"{}/v1\"",
                server.url
            )),
        "{args:?}"
    );
    assert_eq!(&args[args.len() - 2..], ["exec", "say hi"], "{args:?}");
}

/// Where the workspace keeps sessions off the gateway there is nothing to
/// set, and nothing is printed for a shell to run.
#[test]
fn env_prints_nothing_where_the_workspace_keeps_sessions_on_hooks() {
    let settings = policy("direct");
    let server = MockServer::start(&[SUITE, ("GET /api/v1/workspace/settings", 200, &settings)]);
    let sb = Sandbox::new();
    sb.log_in(&server.url, PERSON_TOKEN);
    let output = sb.visdom(sb.repo.path()).arg("env").output().unwrap();
    assert_eq!(output.status.code(), Some(1));
    assert_eq!(stdout(&output), "");
    assert!(
        stderr(&output).contains("AI traffic policy"),
        "{}",
        stderr(&output)
    );
}

/// A setting left out of the config is taken from the environment: the
/// project among several, and the model alias.
#[test]
fn the_project_and_the_model_can_come_from_the_environment() {
    let settings = policy("per_agent");
    let server = MockServer::start(&[
        SUITE,
        ("GET /api/v1/workspace/settings", 200, &settings),
        SETTINGS,
        TWO_PROJECTS,
        ISSUE,
        MODELS,
    ]);
    let (sb, log) = sandbox(&server);
    // Several projects and nobody said which: no gateway session.
    let output = sb
        .visdom(sb.repo.path())
        .args(["--mode", "gateway"])
        .output()
        .unwrap();
    assert!(
        stderr(&output).contains("VISDOM_GATEWAY_PROJECT"),
        "{}",
        stderr(&output)
    );
    assert!(lines(&log).contains(&"VISDOM_GATEWAY_SESSION unset".to_string()));
    std::fs::remove_file(&log).unwrap();

    let output = sb
        .visdom(sb.repo.path())
        .args(["--mode", "gateway"])
        .env("VISDOM_GATEWAY_PROJECT", "beta")
        .env("VISDOM_GATEWAY_MODEL", "gpt-general")
        .output()
        .unwrap();
    assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
    let recorded = lines(&log);
    assert!(
        recorded.contains(&"ANTHROPIC_MODEL=gpt-general".to_string()),
        "{recorded:?}"
    );
    assert!(
        recorded.contains(&"VISDOM_GATEWAY_SESSION=claude-code".to_string()),
        "{recorded:?}"
    );
}

/// `visdom init` leaves the gateway ready: the mode asked for is kept, the
/// model alias is written down, a key is issued and tried, and what was set
/// up is shown with where each setting comes from.
#[test]
fn init_leaves_the_gateway_ready_and_says_where_its_settings_are() {
    let settings = policy("per_agent");
    let server = MockServer::start(&[
        SUITE,
        ("GET /api/v1/workspace/settings", 200, &settings),
        SETTINGS,
        ONE_PROJECT,
        ISSUE,
        MODELS,
    ]);
    let sb = Sandbox::new();
    sb.log_in(&server.url, PERSON_TOKEN);
    let output = sb
        .visdom(sb.repo.path())
        .args(["--mode", "gateway", "init"])
        .output()
        .unwrap();
    assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
    let said = stdout(&output);
    assert!(said.contains("AI Gateway ready for Claude Code"), "{said}");
    for line in [
        "published by the tracing server",
        "project under [gateway]",
        "claude_code_model under [gateway]",
        "VISDOM_GATEWAY_PROJECT",
        "source <(visdom env)",
    ] {
        assert!(said.contains(line), "{line}: {said}");
    }
    assert!(!said.contains("sk-personal"), "{said}");
    // What was settled is in the config: the next `visdom` needs no option.
    let config = std::fs::read_to_string(sb.user_config()).unwrap();
    assert!(config.contains("tracing_mode = \"gateway\""), "{config}");
    // The only project open today too: one more opened later changes nothing.
    assert!(config.contains("project = \"alpha\""), "{config}");
    assert!(
        config.contains("claude_code_model = \"claude-sonnet\""),
        "{config}"
    );
    assert_eq!(count(&server, "POST /api/me/keys"), 1);
    assert_eq!(count(&server, "GET /v1/models"), 1);

    let (agent, log) = sb.recording_agent(&VARIABLES);
    let mut config = std::fs::read_to_string(sb.user_config()).unwrap();
    config.push_str(&format!(
        "\n[agents]\nclaude_code = \"{}\"\n",
        agent.display()
    ));
    sb.write_user_config(&config);
    let output = sb.visdom(sb.repo.path()).output().unwrap();
    assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
    let recorded = lines(&log);
    assert!(
        recorded.contains(&"VISDOM_GATEWAY_SESSION=claude-code".to_string()),
        "{recorded:?}"
    );
    // The key issued by init is the one used.
    assert_eq!(count(&server, "POST /api/me/keys"), 1);
}

/// A gateway that cannot be made ready fails init, with what to set and
/// where: init does not end "done" on a setup whose first start would fail.
#[test]
fn init_fails_when_the_gateway_cannot_be_made_ready() {
    let settings = policy("enforced");
    let server = MockServer::start(&[
        SUITE,
        ("GET /api/v1/workspace/settings", 200, &settings),
        SETTINGS,
        TWO_PROJECTS,
    ]);
    let sb = Sandbox::new();
    sb.log_in(&server.url, PERSON_TOKEN);
    // Nobody to ask which of the two projects.
    let output = sb.visdom(sb.repo.path()).arg("init").output().unwrap();
    assert_eq!(output.status.code(), Some(1), "{}", stdout(&output));
    let said = stderr(&output);
    assert!(said.contains("the AI Gateway is not ready"), "{said}");
    assert!(said.contains("alpha, beta"), "{said}");
    assert!(said.contains("`project`"), "{said}");
    assert!(said.contains("VISDOM_GATEWAY_PROJECT"), "{said}");
    assert!(!stdout(&output).contains("AI Gateway ready"));

    // Said in the environment, it is set up.
    let server = MockServer::start(&[
        SUITE,
        ("GET /api/v1/workspace/settings", 200, &settings),
        SETTINGS,
        TWO_PROJECTS,
        ISSUE,
        MODELS,
    ]);
    sb.log_in(&server.url, PERSON_TOKEN);
    let output = sb
        .visdom(sb.repo.path())
        .arg("init")
        .env("VISDOM_GATEWAY_PROJECT", "beta")
        .output()
        .unwrap();
    assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
    let said = stdout(&output);
    assert!(
        said.contains("VISDOM_GATEWAY_PROJECT in the environment"),
        "{said}"
    );
    assert!(said.contains("required by the workspace"), "{said}");
}

const CUSTOM_MODELS: (&str, u16, &str) = (
    "GET /v1/models",
    200,
    r#"{"object":"list","data":[{"id":"team-assistant"},{"id":"team-fast"}]}"#,
);

/// A gateway whose aliases say nothing about the agent, and nobody to ask
/// which to use: the agent would ask for its own default, which the project
/// does not have. That is not a gateway left ready, nor one to hand out
/// variables for.
#[test]
fn init_and_env_fail_without_a_model_alias_to_ask_for() {
    let settings = policy("per_agent");
    let routes = [
        SUITE,
        ("GET /api/v1/workspace/settings", 200, settings.as_str()),
        SETTINGS,
        ONE_PROJECT,
        ISSUE,
        CUSTOM_MODELS,
    ];
    let server = MockServer::start(&routes);
    let sb = Sandbox::new();
    sb.log_in(&server.url, PERSON_TOKEN);
    let output = sb
        .visdom(sb.repo.path())
        .args(["--mode", "gateway", "init"])
        .output()
        .unwrap();
    assert_eq!(output.status.code(), Some(1), "{}", stdout(&output));
    let said = stderr(&output);
    assert!(said.contains("the AI Gateway is not ready"), "{said}");
    assert!(said.contains("team-assistant, team-fast"), "{said}");
    assert!(said.contains("claude_code_model"), "{said}");
    assert!(said.contains("VISDOM_GATEWAY_MODEL"), "{said}");
    assert!(!stdout(&output).contains("AI Gateway ready"));

    let output = sb.visdom(sb.repo.path()).arg("env").output().unwrap();
    assert_eq!(output.status.code(), Some(1));
    assert_eq!(stdout(&output), "");
    assert!(
        stderr(&output).contains("team-assistant"),
        "{}",
        stderr(&output)
    );

    // An alias the project does not have is no better than none.
    for command in ["init", "env"] {
        let output = sb
            .visdom(sb.repo.path())
            .args(["--mode", "gateway", command])
            .env("VISDOM_GATEWAY_MODEL", "claude-sonnet")
            .output()
            .unwrap();
        assert_eq!(
            output.status.code(),
            Some(1),
            "{command}: {}",
            stdout(&output)
        );
        let said = stderr(&output);
        assert!(said.contains("`claude-sonnet`"), "{command}: {said}");
        assert!(
            said.contains("VISDOM_GATEWAY_MODEL in the environment"),
            "{said}"
        );
        assert!(said.contains("team-assistant, team-fast"), "{said}");
        assert!(!stdout(&output).contains("ready"), "{command}");
    }

    // Named, it is ready.
    let output = sb
        .visdom(sb.repo.path())
        .arg("init")
        .env("VISDOM_GATEWAY_MODEL", "team-assistant")
        .output()
        .unwrap();
    assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
    assert!(
        stdout(&output).contains("VISDOM_GATEWAY_MODEL in the environment"),
        "{}",
        stdout(&output)
    );
}

/// What init settles has to be found by the next `visdom`: a config that
/// cannot be written is a failed init, not a summary of a setup that is gone
/// when the command ends.
#[cfg(unix)]
#[test]
fn init_fails_when_what_it_settled_cannot_be_saved() {
    use std::os::unix::fs::PermissionsExt;
    let settings = policy("enforced");
    let server = MockServer::start(&[
        SUITE,
        ("GET /api/v1/workspace/settings", 200, &settings),
        SETTINGS,
        ONE_PROJECT,
        ISSUE,
        MODELS,
    ]);
    let sb = Sandbox::new();
    sb.log_in(&server.url, PERSON_TOKEN);
    sb.write_user_config("agent = \"claude-code\"\n");
    let config = sb.user_config();
    let read_only = std::fs::Permissions::from_mode(0o444);
    std::fs::set_permissions(&config, read_only).unwrap();
    let output = sb.visdom(sb.repo.path()).arg("init").output().unwrap();
    std::fs::set_permissions(&config, std::fs::Permissions::from_mode(0o644)).unwrap();
    if std::fs::read_to_string(&config)
        .unwrap()
        .contains("[gateway]")
    {
        // Running as root: nothing is read-only.
        return;
    }
    assert_eq!(output.status.code(), Some(1), "{}", stdout(&output));
    let said = stderr(&output);
    assert!(said.contains("could not be saved"), "{said}");
    assert!(said.contains("VISDOM_GATEWAY_PROJECT"), "{said}");
    assert!(!stdout(&output).contains("AI Gateway ready"));

    // The mode asked for is such a setting too.
    sb.write_user_config("[gateway]\nproject = \"alpha\"\nclaude_code_model = \"claude-sonnet\"\n");
    let settings = policy("per_agent");
    let server = MockServer::start(&[
        SUITE,
        ("GET /api/v1/workspace/settings", 200, &settings),
        SETTINGS,
        ONE_PROJECT,
        ISSUE,
        MODELS,
    ]);
    sb.log_in(&server.url, PERSON_TOKEN);
    std::fs::set_permissions(&config, std::fs::Permissions::from_mode(0o444)).unwrap();
    let output = sb
        .visdom(sb.repo.path())
        .args(["--mode", "gateway", "init"])
        .output()
        .unwrap();
    std::fs::set_permissions(&config, std::fs::Permissions::from_mode(0o644)).unwrap();
    assert_eq!(output.status.code(), Some(1), "{}", stdout(&output));
    let said = stderr(&output);
    assert!(said.contains("tracing mode could not be saved"), "{said}");
    assert!(said.contains("VISDOM_TRACING_MODE=gateway"), "{said}");
    assert!(!stdout(&output).contains("AI Gateway ready"));
}

/// A variable that is set wins over the files: the project over the
/// repository's and the user's, the model over the user's.
#[test]
fn the_environment_wins_over_the_config_files() {
    let settings = policy("per_agent");
    let server = MockServer::start(&[
        SUITE,
        ("GET /api/v1/workspace/settings", 200, &settings),
        SETTINGS,
        TWO_PROJECTS,
        ISSUE,
        MODELS,
    ]);
    let (sb, log) = sandbox(&server);
    let mut config = std::fs::read_to_string(sb.user_config()).unwrap();
    config.push_str("\n[gateway]\nproject = \"alpha\"\nclaude_code_model = \"claude-sonnet\"\n");
    sb.write_user_config(&config);
    std::fs::create_dir_all(sb.repo.path().join(".visdom")).unwrap();
    std::fs::write(
        sb.repo.path().join(".visdom/config.toml"),
        "[gateway]\nproject = \"alpha\"\n",
    )
    .unwrap();
    let output = sb
        .visdom(sb.repo.path())
        .args(["--mode", "gateway"])
        .env("VISDOM_GATEWAY_PROJECT", "beta")
        .env("VISDOM_GATEWAY_MODEL", "gpt-general")
        .output()
        .unwrap();
    assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
    let recorded = lines(&log);
    assert!(
        recorded.contains(&"ANTHROPIC_MODEL=gpt-general".to_string()),
        "{recorded:?}"
    );
    assert!(
        server
            .requests()
            .iter()
            .any(|r| r.route == "POST /api/me/keys" && r.body.contains("p-2")),
        "{:?}",
        server.routes()
    );
}

/// A model alias the project no longer has does not stop a launch — the
/// gateway refuses the request, and the developer was told why.
#[test]
fn a_launch_warns_about_a_model_alias_the_project_does_not_have() {
    let settings = policy("per_agent");
    let server = MockServer::start(&[
        SUITE,
        ("GET /api/v1/workspace/settings", 200, &settings),
        SETTINGS,
        ONE_PROJECT,
        ISSUE,
        MODELS,
    ]);
    let (sb, log) = sandbox(&server);
    let output = sb
        .visdom(sb.repo.path())
        .args(["--mode", "gateway"])
        .env("VISDOM_GATEWAY_MODEL", "removed-alias")
        .output()
        .unwrap();
    assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
    let said = stderr(&output);
    assert!(said.contains("`removed-alias` is not among"), "{said}");
    assert!(said.contains("gpt-general, claude-sonnet"), "{said}");
    let recorded = lines(&log);
    assert!(
        recorded.contains(&"ANTHROPIC_MODEL=removed-alias".to_string()),
        "{recorded:?}"
    );
}

/// `visdom --mode gateway init` keeps the mode in the user config. Where the
/// repository's config (or the environment) says otherwise, that wins at the
/// next `visdom`: init says so instead of calling the setup done.
#[test]
fn init_fails_when_the_mode_it_saves_would_be_overruled() {
    let settings = policy("per_agent");
    let server = MockServer::start(&[
        SUITE,
        ("GET /api/v1/workspace/settings", 200, &settings),
        SETTINGS,
        ONE_PROJECT,
        ISSUE,
        MODELS,
    ]);
    let sb = Sandbox::new();
    sb.log_in(&server.url, PERSON_TOKEN);
    std::fs::create_dir_all(sb.repo.path().join(".visdom")).unwrap();
    std::fs::write(
        sb.repo.path().join(".visdom/config.toml"),
        "tracing_mode = \"hooks\"\n",
    )
    .unwrap();
    let output = sb
        .visdom(sb.repo.path())
        .args(["--mode", "gateway", "init"])
        .output()
        .unwrap();
    assert_eq!(output.status.code(), Some(1), "{}", stdout(&output));
    let said = stderr(&output);
    assert!(said.contains(".visdom/config.toml"), "{said}");
    assert!(said.contains("hooks"), "{said}");
    assert!(!stdout(&output).contains("AI Gateway ready"));
}

/// `visdom init --global` is the whole setup too, for the machine: bazaar is
/// registered for all of the user's projects, and the gateway is left ready.
#[test]
fn a_machine_wide_init_sets_up_bazaar_and_the_gateway_too() {
    let settings = policy("enforced");
    let server = MockServer::start(&[
        SUITE,
        ("GET /api/v1/workspace/settings", 200, &settings),
        SETTINGS,
        ONE_PROJECT,
        ISSUE,
        MODELS,
    ]);
    let sb = Sandbox::new();
    sb.log_in(&server.url, PERSON_TOKEN);
    let (agent, log) = sb.recording_agent(&[]);
    sb.write_user_config(&format!(
        "bazaar_url = \"https://context.example.com/mcp/remote\"\n\n[agents]\nclaude_code = \"{}\"\n",
        agent.display()
    ));
    // Not in a repository: a machine-wide setup needs none.
    let elsewhere = tempfile::tempdir().unwrap();
    let output = sb
        .visdom(elsewhere.path())
        .args(["init", "--global"])
        .output()
        .unwrap();
    assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
    let said = stdout(&output);
    assert!(said.contains("AI Gateway ready for Claude Code"), "{said}");
    let args = args(&log);
    let scope = args.iter().position(|a| a == "--scope").expect("mcp add");
    assert_eq!(args[scope + 1], "user", "{args:?}");
}

/// A folder of checkouts set up as a workspace keeps its gateway project in
/// its own `.visdom/config.toml`, which applies in it and below it although
/// it is no git checkout.
#[test]
fn a_workspace_folder_names_its_own_gateway_project() {
    let settings = policy("per_agent");
    let server = MockServer::start(&[
        SUITE,
        ("GET /api/v1/workspace/settings", 200, &settings),
        SETTINGS,
        TWO_PROJECTS,
        ISSUE,
        MODELS,
    ]);
    let (sb, log) = sandbox(&server);
    let workspace = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(workspace.path().join(".visdom")).unwrap();
    std::fs::write(
        workspace.path().join(".visdom/config.toml"),
        "tracing_mode = \"gateway\"\n\n[gateway]\nproject = \"beta\"\n",
    )
    .unwrap();
    let below = workspace.path().join("notes");
    std::fs::create_dir_all(&below).unwrap();
    let output = sb.visdom(&below).output().unwrap();
    assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
    let recorded = lines(&log);
    assert!(
        recorded.contains(&"VISDOM_GATEWAY_SESSION=claude-code".to_string()),
        "{recorded:?} {}",
        stderr(&output)
    );
    // The key is the workspace's project's.
    assert!(
        server
            .requests()
            .iter()
            .any(|r| r.route == "POST /api/me/keys" && r.body.contains("p-2")),
        "{:?}",
        server.routes()
    );
}

/// `visdom init --workspace` binds the folder to its project and then goes
/// on with the rest of the setup, like any other init.
#[test]
fn a_workspace_init_binds_the_folder_and_sets_up_the_gateway() {
    let settings = policy("enforced");
    let server = MockServer::start(&[
        SUITE,
        ("GET /api/v1/workspace/settings", 200, &settings),
        (
            "GET /api/v1/projects",
            200,
            r#"[{"id":"11111111-2222-3333-4444-555555555555","name":"my-platform"}]"#,
        ),
        SETTINGS,
        ONE_PROJECT,
        ISSUE,
        MODELS,
    ]);
    let sb = Sandbox::new();
    sb.log_in(&server.url, PERSON_TOKEN);
    // The developer's own default, from an earlier setup.
    sb.write_user_config("[gateway]\nproject = \"alpha\"\n");
    let folder = tempfile::tempdir().unwrap();
    let output = sb
        .visdom(folder.path())
        .args(["init", "--workspace", "--project", "my-platform"])
        .output()
        .unwrap();
    assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
    // The folder keeps its gateway project itself: a later change of the
    // developer's default does not move it.
    let own = std::fs::read_to_string(folder.path().join(".visdom/config.toml")).unwrap();
    assert!(own.contains("project = \"alpha\""), "{own}");
    assert!(
        stdout(&output).contains(".visdom/config.toml"),
        "{}",
        stdout(&output)
    );
    let bound = std::fs::read_to_string(folder.path().join(".visdom/tracing.toml")).unwrap();
    assert!(
        bound.contains("11111111-2222-3333-4444-555555555555"),
        "{bound}"
    );
    let said = stdout(&output);
    assert!(said.contains("AI Gateway ready for Claude Code"), "{said}");
    // Said with the flag, it is `tracevault init --workspace` as it is: the
    // machine-wide hooks are not installed behind the developer's back.
    let hooks =
        std::fs::read_to_string(sb.home.path().join(".claude/settings.json")).unwrap_or_default();
    assert!(!hooks.contains(" stream --event"), "{hooks}");
}

const PROJECTS: (&str, u16, &str) = (
    "GET /api/v1/projects",
    200,
    r#"[{"id":"11111111-2222-3333-4444-555555555555","name":"my-platform"}]"#,
);

/// A workspace may be a checkout's top level: its gateway project is kept in
/// that checkout's `.visdom/config.toml` — the inherited one written down,
/// one already named there (an empty value is none) left as it is.
#[test]
fn a_workspace_at_a_checkouts_top_level_keeps_its_gateway_project_there() {
    let settings = policy("enforced");
    let routes = [
        SUITE,
        ("GET /api/v1/workspace/settings", 200, settings.as_str()),
        PROJECTS,
        SETTINGS,
        TWO_PROJECTS,
        ISSUE,
        MODELS,
    ];
    let init = |sb: &Sandbox| {
        sb.visdom(sb.repo.path())
            .args(["init", "--workspace", "--project", "my-platform"])
            .output()
            .unwrap()
    };
    let own =
        |sb: &Sandbox| std::fs::read_to_string(sb.repo.path().join(".visdom/config.toml")).unwrap();

    for before in [None, Some("[gateway]\nproject = \"  \"\n")] {
        let server = MockServer::start(&routes);
        let sb = Sandbox::new();
        sb.log_in(&server.url, PERSON_TOKEN);
        sb.write_user_config("[gateway]\nproject = \"alpha\"\n");
        if let Some(before) = before {
            std::fs::create_dir_all(sb.repo.path().join(".visdom")).unwrap();
            std::fs::write(sb.repo.path().join(".visdom/config.toml"), before).unwrap();
        }
        let output = init(&sb);
        assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
        assert!(
            own(&sb).contains("project = \"alpha\""),
            "{before:?}: {}",
            own(&sb)
        );
    }

    let server = MockServer::start(&routes);
    let sb = Sandbox::new();
    sb.log_in(&server.url, PERSON_TOKEN);
    sb.write_user_config("[gateway]\nproject = \"alpha\"\n");
    std::fs::create_dir_all(sb.repo.path().join(".visdom")).unwrap();
    std::fs::write(
        sb.repo.path().join(".visdom/config.toml"),
        "[gateway]\nproject = \"beta\"\n",
    )
    .unwrap();
    let output = init(&sb);
    assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
    assert!(own(&sb).contains("project = \"beta\""), "{}", own(&sb));
    assert!(!own(&sb).contains("alpha"), "{}", own(&sb));
}

/// A folder's new config comes before one further up. Where that one chose
/// the gateway, the choice is carried into the new file, so that the folder
/// does not fall back to hooks after an init that called the gateway ready.
#[test]
fn a_workspaces_new_config_keeps_the_mode_chosen_further_up() {
    let settings = policy("per_agent");
    let server = MockServer::start(&[
        SUITE,
        ("GET /api/v1/workspace/settings", 200, &settings),
        PROJECTS,
        SETTINGS,
        ONE_PROJECT,
        ISSUE,
        MODELS,
    ]);
    let (sb, log) = sandbox(&server);
    let above = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(above.path().join(".visdom")).unwrap();
    std::fs::write(
        above.path().join(".visdom/config.toml"),
        "tracing_mode = \"gateway\"\n",
    )
    .unwrap();
    let folder = above.path().join("platform");
    std::fs::create_dir_all(&folder).unwrap();
    let output = sb
        .visdom(&folder)
        .args(["init", "--workspace", "--project", "my-platform"])
        .output()
        .unwrap();
    assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
    assert!(
        stdout(&output).contains("AI Gateway ready"),
        "{}",
        stdout(&output)
    );
    let own = std::fs::read_to_string(folder.join(".visdom/config.toml")).unwrap();
    assert!(own.contains("tracing_mode = \"gateway\""), "{own}");
    assert!(own.contains("project = \"alpha\""), "{own}");

    let output = sb.visdom(&folder).output().unwrap();
    assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
    assert!(
        lines(&log).contains(&"VISDOM_GATEWAY_SESSION=claude-code".to_string()),
        "{:?}",
        lines(&log)
    );
}