rkat 0.7.7

CLI for the Meerkat agent platform — run LLM agents from the terminal
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
//! T14 (Phase 5): CLI auth flow e2e — top-down observable proof that
//! the `rkat auth` subcommand tree is wired end-to-end.
//!
//! Plan choke point K5 reads: "`rkat auth login openai --backend
//! openai_api --method api_key` … → profile saved; `rkat auth profile
//! list` shows it; `rkat run --auth-binding realm:binding "hi"` builds
//! agent". The live-provider half of that flow requires real credentials
//! and belongs in the `e2e-auth` lane; this file exercises the offline
//! command-surface half: the subcommand dispatch table, argument
//! parsing, and deterministic error paths under minimal feature
//! configurations.

#![allow(clippy::expect_used, clippy::panic, clippy::unwrap_used)]

use std::path::PathBuf;
use std::process::{Command, Stdio};

fn seed_managed_openai_realm_config(root: &std::path::Path) {
    seed_managed_openai_realm_config_with_ids(root, "default_openai", "default_openai");
}

fn seed_managed_openai_realm_config_with_ids(
    root: &std::path::Path,
    auth_profile_id: &str,
    binding_id: &str,
) {
    seed_openai_realm_config_with_ids_and_method(
        root,
        auth_profile_id,
        binding_id,
        "openai_api",
        "api_key",
    );
}

fn seed_openai_realm_config_with_ids_and_method(
    root: &std::path::Path,
    auth_profile_id: &str,
    binding_id: &str,
    backend_kind: &str,
    auth_method: &str,
) {
    let config = format!(
        r#"
[realm.dev]
default_binding = "{binding_id}"

[realm.dev.backend.openai_backend]
provider = "openai"
backend_kind = "{backend_kind}"

[realm.dev.auth.{auth_profile_id}]
provider = "openai"
auth_method = "{auth_method}"
source = {{ kind = "managed_store" }}

[realm.dev.binding.{binding_id}]
backend_profile = "openai_backend"
auth_profile = "{auth_profile_id}"
"#
    );
    let mut realm_ids = std::collections::BTreeSet::from(["dev".to_string()]);
    let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
    realm_ids.insert(meerkat_core::derive_workspace_realm_id(&cwd));
    let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
    realm_ids.insert(meerkat_core::derive_workspace_realm_id(&manifest_dir));
    if let Some(workspace_root) = manifest_dir.parent() {
        realm_ids.insert(meerkat_core::derive_workspace_realm_id(workspace_root));
    }

    for realm_id in realm_ids {
        let realm_dir = root.join("realms").join(realm_id);
        std::fs::create_dir_all(&realm_dir).expect("mkdir realm config dir");
        std::fs::write(realm_dir.join("config.toml"), &config).expect("write realm config");
    }
}

fn token_file_path(root: &std::path::Path) -> PathBuf {
    token_file_path_for_binding(root, "default_openai")
}

fn token_file_path_for_binding(root: &std::path::Path, binding_id: &str) -> PathBuf {
    #[cfg(target_os = "macos")]
    let config_root = root.join("Library").join("Application Support");
    #[cfg(not(target_os = "macos"))]
    let config_root = root.join("config");

    config_root
        .join("meerkat")
        .join("credentials")
        .join("dev")
        .join(format!("{binding_id}.json"))
}

fn seed_token_file(root: &std::path::Path, body: &str) {
    seed_token_file_for_binding(root, "default_openai", body);
}

fn seed_token_file_for_binding(root: &std::path::Path, binding_id: &str, body: &str) {
    let token_file = token_file_path_for_binding(root, binding_id);
    let token_dir = token_file.parent().expect("token file has parent");
    std::fs::create_dir_all(token_dir).expect("mkdir token dir");
    std::fs::write(token_file, body).expect("write token file");
}

fn token_file_exists(root: &std::path::Path) -> bool {
    token_file_path(root).exists()
}

fn rkat_binary() -> Option<PathBuf> {
    if let Some(path) = std::env::var_os("CARGO_BIN_EXE_rkat") {
        let p = PathBuf::from(path);
        if p.exists() {
            return Some(p.canonicalize().unwrap_or(p));
        }
    }
    if let Some(target_dir) = std::env::var_os("CARGO_TARGET_DIR") {
        let target_dir = PathBuf::from(target_dir);
        for profile in ["debug", "release"] {
            let candidate = target_dir.join(profile).join("rkat");
            if candidate.exists() {
                return Some(candidate);
            }
        }
    }
    let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
    let workspace_root = manifest_dir.parent()?;
    let codex_debug = workspace_root.join("target-codex/debug/rkat");
    if codex_debug.exists() {
        return Some(codex_debug);
    }
    let codex_release = workspace_root.join("target-codex/release/rkat");
    if codex_release.exists() {
        return Some(codex_release);
    }
    None
}

/// `rkat auth --help` returns 0 and mentions every documented subcommand.
#[test]
fn rkat_auth_help_lists_all_subcommands() {
    let Some(rkat) = rkat_binary() else {
        eprintln!("SKIP: rkat binary unavailable");
        return;
    };

    let out = Command::new(&rkat)
        .args(["auth", "--help"])
        .stdin(Stdio::null())
        .output()
        .expect("rkat auth --help must spawn");

    assert!(
        out.status.success(),
        "rkat auth --help must exit 0; stderr={}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8_lossy(&out.stdout);
    for subcommand in ["login", "logout", "profile", "status", "binding"] {
        assert!(
            stdout.contains(subcommand),
            "rkat auth --help must mention `{subcommand}` subcommand; stdout:\n{stdout}"
        );
    }
}

#[test]
fn rkat_auth_logout_clears_malformed_token_file() {
    let Some(rkat) = rkat_binary() else {
        eprintln!("SKIP: rkat binary unavailable");
        return;
    };

    let tmp = tempfile::TempDir::new().expect("tempdir");
    seed_token_file(tmp.path(), "{ malformed token json");

    let logout = Command::new(&rkat)
        .args(["auth", "logout", "default_openai"])
        .env("HOME", tmp.path())
        .env("XDG_CONFIG_HOME", tmp.path().join("config"))
        .stdin(Stdio::null())
        .output()
        .expect("rkat auth logout must spawn");
    if !logout.status.success() {
        let stderr = String::from_utf8_lossy(&logout.stderr);
        if stderr.contains("requires the `anthropic`, `openai`, and `gemini`") {
            eprintln!("SKIP: auth provider features unavailable");
            return;
        }
        panic!("logout must clear malformed token file; stderr={stderr}");
    }

    assert!(
        !token_file_exists(tmp.path()),
        "logout must remove malformed persisted credentials"
    );
}

#[test]
fn rkat_auth_profile_delete_clears_malformed_token_file() {
    let Some(rkat) = rkat_binary() else {
        eprintln!("SKIP: rkat binary unavailable");
        return;
    };

    let tmp = tempfile::TempDir::new().expect("tempdir");
    seed_managed_openai_realm_config(tmp.path());
    seed_token_file(tmp.path(), "{ malformed token json");

    let delete = Command::new(&rkat)
        .args([
            "--state-root",
            tmp.path().join("realms").to_str().expect("utf8 path"),
            "--realm",
            "dev",
            "auth",
            "profile-delete",
            "--realm",
            "dev",
            "default_openai",
            "--yes",
        ])
        .env("HOME", tmp.path())
        .env("XDG_CONFIG_HOME", tmp.path().join("config"))
        .stdin(Stdio::null())
        .output()
        .expect("rkat auth profile-delete must spawn");
    if !delete.status.success() {
        let stderr = String::from_utf8_lossy(&delete.stderr);
        if stderr.contains("requires the `anthropic`, `openai`, and `gemini`") {
            eprintln!("SKIP: auth provider features unavailable");
            return;
        }
        panic!("profile delete must clear malformed token file; stderr={stderr}");
    }

    assert!(
        !token_file_exists(tmp.path()),
        "profile delete must remove malformed persisted credentials"
    );
}

#[test]
fn rkat_auth_profile_delete_clears_binding_scoped_token_when_profile_id_differs() {
    let Some(rkat) = rkat_binary() else {
        eprintln!("SKIP: rkat binary unavailable");
        return;
    };

    let tmp = tempfile::TempDir::new().expect("tempdir");
    seed_managed_openai_realm_config_with_ids(tmp.path(), "openai_managed", "default_openai");
    seed_token_file_for_binding(tmp.path(), "default_openai", "{ malformed token json");

    let delete = Command::new(&rkat)
        .args([
            "--state-root",
            tmp.path().join("realms").to_str().expect("utf8 path"),
            "--realm",
            "dev",
            "auth",
            "profile-delete",
            "--realm",
            "dev",
            "openai_managed",
            "--yes",
        ])
        .env("HOME", tmp.path())
        .env("XDG_CONFIG_HOME", tmp.path().join("config"))
        .stdin(Stdio::null())
        .output()
        .expect("rkat auth profile-delete must spawn");
    if !delete.status.success() {
        let stderr = String::from_utf8_lossy(&delete.stderr);
        if stderr.contains("requires the `anthropic`, `openai`, and `gemini`") {
            eprintln!("SKIP: auth provider features unavailable");
            return;
        }
        panic!("profile delete must clear binding-scoped token file; stderr={stderr}");
    }

    let stdout = String::from_utf8_lossy(&delete.stdout);
    assert!(
        stdout.contains("deleted: dev:default_openai"),
        "profile delete should report the binding-scoped token key; stdout:\n{stdout}"
    );
    assert!(
        !token_file_path_for_binding(tmp.path(), "default_openai").exists(),
        "profile delete must remove the token file keyed by the owning binding"
    );
}

#[test]
fn rkat_auth_status_hides_token_metadata_without_lifecycle() {
    let Some(rkat) = rkat_binary() else {
        eprintln!("SKIP: rkat binary unavailable");
        return;
    };

    let tmp = tempfile::TempDir::new().expect("tempdir");
    seed_managed_openai_realm_config(tmp.path());
    seed_token_file(
        tmp.path(),
        r#"{
  "auth_mode": "api_key",
  "primary_secret": "sk-stale",
  "refresh_token": "refresh-stale",
  "expires_at": 1800000000,
  "last_refresh": 1700000000,
  "scopes": ["email"],
  "account_id": "acct-stale"
}"#,
    );

    let status = Command::new(&rkat)
        .args([
            "--state-root",
            tmp.path().join("realms").to_str().expect("utf8 path"),
            "--realm",
            "dev",
            "auth",
            "status",
            "--realm",
            "dev",
            "default_openai",
        ])
        .env("HOME", tmp.path())
        .env("XDG_CONFIG_HOME", tmp.path().join("config"))
        .stdin(Stdio::null())
        .output()
        .expect("rkat auth status must spawn");
    if !status.status.success() {
        let stderr = String::from_utf8_lossy(&status.stderr);
        if stderr.contains("requires the `anthropic`, `openai`, and `gemini`") {
            eprintln!("SKIP: auth provider features unavailable");
            return;
        }
        panic!("status must succeed with seeded config; stderr={stderr}");
    }

    let stdout = String::from_utf8_lossy(&status.stdout);
    assert!(
        stdout.contains("state:       missing_credential"),
        "status should report missing_credential without a live AuthMachine lifecycle; stdout:\n{stdout}"
    );
    for forbidden in [
        "auth_mode:",
        "has_secret:",
        "has_refresh:",
        "expires_at:",
        "last_refresh:",
        "account_id:",
        "scopes:",
        "acct-stale",
        "email",
    ] {
        assert!(
            !stdout.contains(forbidden),
            "status must not expose token-derived `{forbidden}` without lifecycle; stdout:\n{stdout}"
        );
    }
}

#[test]
fn rkat_auth_status_fails_closed_on_malformed_token_storage() {
    let Some(rkat) = rkat_binary() else {
        eprintln!("SKIP: rkat binary unavailable");
        return;
    };

    let tmp = tempfile::TempDir::new().expect("tempdir");
    seed_managed_openai_realm_config(tmp.path());
    seed_token_file(tmp.path(), "{ malformed token json");

    let status = Command::new(&rkat)
        .args([
            "--state-root",
            tmp.path().join("realms").to_str().expect("utf8 path"),
            "--realm",
            "dev",
            "auth",
            "status",
            "--realm",
            "dev",
            "default_openai",
        ])
        .env("HOME", tmp.path())
        .env("XDG_CONFIG_HOME", tmp.path().join("config"))
        .stdin(Stdio::null())
        .output()
        .expect("rkat auth status must spawn");
    let stderr = String::from_utf8_lossy(&status.stderr);
    if stderr.contains("requires the `anthropic`, `openai`, and `gemini`") {
        eprintln!("SKIP: auth provider features unavailable");
        return;
    }

    // A malformed token store is an auth-truth fault the surface cannot
    // vouch for: status must fail closed with the typed rehydration fault,
    // never report a fabricated missing_credential success.
    assert!(
        !status.status.success(),
        "status must fail closed on malformed token storage; stdout:\n{}",
        String::from_utf8_lossy(&status.stdout)
    );
    assert!(
        stderr.contains("TokenStore rehydration failed"),
        "failure must surface the typed token-store fault; stderr:\n{stderr}"
    );
}

#[test]
fn rkat_auth_refresh_uses_binding_scoped_token_when_profile_id_differs() {
    let Some(rkat) = rkat_binary() else {
        eprintln!("SKIP: rkat binary unavailable");
        return;
    };

    let tmp = tempfile::TempDir::new().expect("tempdir");
    seed_openai_realm_config_with_ids_and_method(
        tmp.path(),
        "openai_managed",
        "default_openai",
        "chatgpt_backend",
        "managed_chatgpt_oauth",
    );
    seed_token_file(
        tmp.path(),
        r#"{
  "auth_mode": "chatgpt_oauth",
  "primary_secret": "fresh-chatgpt-access",
  "refresh_token": "refresh-token",
  "expires_at": 1893456000,
  "last_refresh": 1700000000,
  "scopes": ["openid", "email"],
  "account_id": "acct-fresh",
  "metadata": {
    "meerkat_auth_lifecycle": {
      "published": true,
      "version": 2,
      "expires_at": 1893456000
    }
  }
}"#,
    );

    let refresh = Command::new(&rkat)
        .args([
            "--state-root",
            tmp.path().join("realms").to_str().expect("utf8 path"),
            "--realm",
            "dev",
            "auth",
            "refresh",
            "--realm",
            "dev",
            "openai_managed",
        ])
        .env("HOME", tmp.path())
        .env("XDG_CONFIG_HOME", tmp.path().join("config"))
        .stdin(Stdio::null())
        .output()
        .expect("rkat auth refresh must spawn");
    if !refresh.status.success() {
        let stderr = String::from_utf8_lossy(&refresh.stderr);
        if stderr.contains("requires the `anthropic`, `openai`, and `gemini`") {
            eprintln!("SKIP: auth provider features unavailable");
            return;
        }
        if stderr.contains("token endpoint error") || stderr.contains("stale credential material") {
            assert!(
                !stderr.contains("missing secret for auth resolution"),
                "refresh must resolve the binding-scoped token before reaching the provider; stderr={stderr}"
            );
            eprintln!("SKIP: fake refresh token was rejected after binding-scoped resolution");
            return;
        }
        panic!("refresh must use the binding-scoped token key; stderr={stderr}");
    }

    let stdout = String::from_utf8_lossy(&refresh.stdout);
    assert!(
        stdout.contains("profile:       dev:openai_managed"),
        "refresh should still report the requested auth profile; stdout:\n{stdout}"
    );
    assert!(
        stdout.contains("refresh:       ok"),
        "refresh must not skip when credentials exist under the owning binding; stdout:\n{stdout}"
    );
    assert!(
        !stdout.contains("reason:        no persisted credential"),
        "refresh must not preflight token storage by auth profile id; stdout:\n{stdout}"
    );
}

#[test]
fn rkat_auth_status_resolves_binding_that_references_auth_profile() {
    let Some(rkat) = rkat_binary() else {
        eprintln!("SKIP: rkat binary unavailable");
        return;
    };

    let tmp = tempfile::TempDir::new().expect("tempdir");
    seed_managed_openai_realm_config_with_ids(tmp.path(), "openai_managed", "default_openai");

    let status = Command::new(&rkat)
        .args([
            "--state-root",
            tmp.path().join("realms").to_str().expect("utf8 path"),
            "--realm",
            "dev",
            "auth",
            "status",
            "--realm",
            "dev",
            "openai_managed",
        ])
        .env("HOME", tmp.path())
        .env("XDG_CONFIG_HOME", tmp.path().join("config"))
        .stdin(Stdio::null())
        .output()
        .expect("rkat auth status must spawn");
    assert!(
        status.status.success(),
        "status must resolve binding-scoped lease identity from auth profile; stderr={}",
        String::from_utf8_lossy(&status.stderr)
    );

    let stdout = String::from_utf8_lossy(&status.stdout);
    assert!(
        stdout.contains("binding_id:  default_openai"),
        "status must report the binding that owns the auth lease key; stdout:\n{stdout}"
    );
    assert!(
        stdout.contains("state:       missing_credential"),
        "status should still be missing_credential without a live AuthMachine lifecycle; stdout:\n{stdout}"
    );
}

/// `rkat auth profile list --realm <empty>` returns either 0 (empty
/// list) or a typed error; it must not panic or spew an unstructured
/// stack trace.
#[test]
fn rkat_auth_profile_list_returns_cleanly_for_empty_realm() {
    let Some(rkat) = rkat_binary() else {
        eprintln!("SKIP: rkat binary unavailable");
        return;
    };

    let tmp = tempfile::TempDir::new().expect("tempdir");
    let out = Command::new(&rkat)
        .args(["auth", "profile", "list", "--realm", "nonexistent-realm"])
        .env("HOME", tmp.path())
        .env("XDG_CONFIG_HOME", tmp.path())
        .stdin(Stdio::null())
        .output()
        .expect("rkat auth profile list must spawn");

    // Either exits 0 (empty-list ok) or non-zero with an error message;
    // what matters is no panic and no empty-body failure.
    if !out.status.success() {
        let stderr = String::from_utf8_lossy(&out.stderr);
        assert!(
            !stderr.is_empty(),
            "non-zero exit must include stderr diagnostic"
        );
        assert!(
            !stderr.contains("thread 'main' panicked"),
            "CLI must not panic; stderr:\n{stderr}"
        );
    }
}

/// `rkat run --auth-binding realm:binding "hi"` without a configured
/// realm must return a typed `LlmClient` connection-target error, not an
/// `unknown argument` or panic. This proves the flag is registered and
/// flows into build_agent.
///
/// The test does not require a live LLM; the error path triggers before
/// any network call.
#[test]
fn rkat_run_auth_binding_flag_is_registered_and_routes() {
    let Some(rkat) = rkat_binary() else {
        eprintln!("SKIP: rkat binary unavailable");
        return;
    };

    let tmp = tempfile::TempDir::new().expect("tempdir");
    // Seed a minimal .rkat so `rkat run` doesn't refuse on missing config.
    std::fs::create_dir_all(tmp.path().join(".rkat")).expect("mkdir .rkat");

    let out = Command::new(&rkat)
        .args(["run", "--auth-binding", "nonexistent:binding", "hi"])
        .current_dir(tmp.path())
        .env("HOME", tmp.path())
        .env("XDG_CONFIG_HOME", tmp.path())
        .env("RKAT_TEST_CLIENT", "1") // short-circuit LLM client
        .stdin(Stdio::null())
        .output()
        .expect("rkat run must spawn");

    let stderr = String::from_utf8_lossy(&out.stderr);
    // The flag must be accepted (if not registered, clap emits "unrecognized
    // argument" with a specific pattern).
    assert!(
        !stderr.contains("unrecognized argument")
            && !stderr.contains("unexpected argument")
            && !stderr.contains("found argument '--auth-binding'"),
        "--auth-binding must be a registered CLI flag; stderr:\n{stderr}"
    );
    assert!(
        !stderr.contains("thread 'main' panicked"),
        "rkat run must not panic on unknown realm; stderr:\n{stderr}"
    );
}

/// `rkat auth logout` clears the same TokenStore key written by scripted login
/// and fails closed on a repeat clear instead of reporting success for stale
/// credentials.
#[test]
fn rkat_auth_logout_clears_scripted_login_token_key() {
    let Some(rkat) = rkat_binary() else {
        eprintln!("SKIP: rkat binary unavailable");
        return;
    };

    let tmp = tempfile::TempDir::new().expect("tempdir");
    let login = Command::new(&rkat)
        .args([
            "auth",
            "login",
            "openai",
            "--non-interactive",
            "--secret",
            "sk-test",
        ])
        .env("HOME", tmp.path())
        .env("XDG_CONFIG_HOME", tmp.path())
        .stdin(Stdio::null())
        .output()
        .expect("rkat auth login must spawn");
    if !login.status.success() {
        let stderr = String::from_utf8_lossy(&login.stderr);
        if stderr.contains("requires the `anthropic`, `openai`, and `gemini`") {
            eprintln!("SKIP: auth provider features unavailable");
            return;
        }
        panic!("scripted login failed: {stderr}");
    }

    let logout = Command::new(&rkat)
        .args(["auth", "logout", "default_openai"])
        .env("HOME", tmp.path())
        .env("XDG_CONFIG_HOME", tmp.path())
        .stdin(Stdio::null())
        .output()
        .expect("rkat auth logout must spawn");
    assert!(
        logout.status.success(),
        "logout must clear scripted login token; stderr={}",
        String::from_utf8_lossy(&logout.stderr)
    );

    let repeat = Command::new(&rkat)
        .args(["auth", "logout", "default_openai"])
        .env("HOME", tmp.path())
        .env("XDG_CONFIG_HOME", tmp.path())
        .stdin(Stdio::null())
        .output()
        .expect("repeat rkat auth logout must spawn");
    assert!(
        !repeat.status.success(),
        "repeat logout must not report success for already-cleared credentials"
    );
    let stderr = String::from_utf8_lossy(&repeat.stderr);
    assert!(
        stderr.contains("No credentials found"),
        "repeat logout should explain that no token remains; stderr={stderr}"
    );
    assert!(
        !stderr.contains("thread 'main' panicked"),
        "repeat logout must not panic; stderr={stderr}"
    );
}