visdom-cli 1.0.0

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
//! `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=1"), "{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"]);
}

#[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", "1")
        .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()));
}