clauth 0.8.0

Manage multiple Claude Code accounts, monitor 5h/7d usage with configurable auto-switch and delegation with an MCP plugin. CLI + TUI.
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
#![allow(clippy::unwrap_used, clippy::expect_used)]
//! Per-account custom env editor: collision classification + `edit_profile_env`
//! persistence and the strip-removed-keys-on-active behaviour.

use super::*;
use crate::profile::AppState;
use crate::testutil::HomeSandbox;

fn acct_config() -> AppConfig {
    AppConfig {
        state: AppState::default(),
        profiles: vec![Profile::new("acct".to_string(), None, None)],
    }
}

#[test]
fn classify_env_key_flags_managed_keys() {
    let p = Profile::new("acct".to_string(), None, None);
    assert!(matches!(
        classify_env_key(&p, &[], "ANTHROPIC_BASE_URL"),
        Some(EnvKeyCollision::Managed(_))
    ));
    assert!(matches!(
        classify_env_key(&p, &[], "CLAUDE_CODE_SUBAGENT_MODEL"),
        Some(EnvKeyCollision::Managed(_))
    ));
    assert_eq!(classify_env_key(&p, &[], "ANTHROPIC_CUSTOM_FLAG"), None);
}

#[test]
fn classify_env_key_flags_own_field_by_sorted_index() {
    let mut p = Profile::new("acct".to_string(), None, None);
    p.env.insert("ZED".to_string(), "1".to_string());
    p.env.insert("ALPHA".to_string(), "2".to_string());
    // BTreeMap order: ALPHA(0), ZED(1).
    assert_eq!(
        classify_env_key(&p, &[], "ALPHA"),
        Some(EnvKeyCollision::ProfileField(0))
    );
    assert_eq!(
        classify_env_key(&p, &[], "ZED"),
        Some(EnvKeyCollision::ProfileField(1))
    );
}

#[test]
fn classify_env_key_base_settings_only_for_external_keys() {
    let mut p = Profile::new("acct".to_string(), None, None);
    p.env.insert("OWN".to_string(), "1".to_string());
    let base = vec![
        "OWN".to_string(),
        "EXTERNAL".to_string(),
        "ANTHROPIC_BASE_URL".to_string(),
    ];
    // Managed + own-field checks win before the base check, so only a key that is
    // neither (genuinely external) classifies as BaseSettings.
    assert_eq!(
        classify_env_key(&p, &base, "EXTERNAL"),
        Some(EnvKeyCollision::BaseSettings)
    );
    assert_eq!(
        classify_env_key(&p, &base, "OWN"),
        Some(EnvKeyCollision::ProfileField(0))
    );
    assert!(matches!(
        classify_env_key(&p, &base, "ANTHROPIC_BASE_URL"),
        Some(EnvKeyCollision::Managed(_))
    ));
    assert_eq!(classify_env_key(&p, &base, "FRESH"), None);
}

/// macOS reality: `~/.claude/.credentials.json` is a regular-file Keychain mirror
/// of the ACTIVE account (not clauth's symlink). Switching to another profile must
/// succeed — the live file matches the active profile (already captured), so it is
/// safe to replace even though it legitimately differs from the target. Regression
/// for `Error: refusing to replace .credentials.json — live file differs from
/// profile 'xfx'; resolve divergence first` on every `clauth <name>`.
#[test]
fn switch_replaces_active_account_mirror_without_refusing() {
    let _home = HomeSandbox::new();

    let mk = |name: &str, access: &str| {
        let mut p = Profile::new(name.to_string(), None, None);
        p.credentials = Some(crate::profile::ClaudeCredentials {
            claude_ai_oauth: Some(crate::profile::OAuthToken {
                access_token: access.to_string(),
                refresh_token: Some(format!("{access}-refresh")),
                expires_at: None,
                scopes: None,
                subscription_type: None,
            }),
        });
        crate::profile::save_profile(&p).expect("save profile");
        p
    };
    let active = mk("cl-ax", "cl-ax-access");
    let target = mk("xfx", "xfx-access");

    // Live file = a plain regular file whose content matches the ACTIVE profile
    // (exactly what Claude Code mirrors from the Keychain on macOS).
    let live_path = crate::profile::claude_dir()
        .unwrap()
        .join(".credentials.json");
    std::fs::create_dir_all(live_path.parent().unwrap()).unwrap();
    std::fs::write(
        &live_path,
        serde_json::to_vec(active.credentials.as_ref().unwrap()).unwrap(),
    )
    .unwrap();

    let mut config = AppConfig {
        state: AppState::default(),
        profiles: vec![active, target],
    };
    config.state.active_profile = Some("cl-ax".into());

    // Must NOT bail — the live file is the active account's captured mirror.
    switch_profile(&mut config, "xfx").expect("switch replaces the active-account mirror");

    assert!(config.is_active("xfx"));
    assert_eq!(
        classify_credentials_link("xfx").expect("classify"),
        LinkState::LinkedTo,
        "after the switch the live path resolves to xfx's stored creds",
    );
}

#[test]
fn edit_profile_env_persists_to_config_toml() {
    let _home = HomeSandbox::new();
    let mut config = acct_config();
    let mut env = BTreeMap::new();
    env.insert("FOO".to_string(), "bar".to_string());
    edit_profile_env(&mut config, "acct", env).expect("set env");

    assert_eq!(
        config.find("acct").unwrap().env.get("FOO"),
        Some(&"bar".to_string())
    );
    let toml = std::fs::read_to_string(profile_dir("acct").unwrap().join("config.toml"))
        .expect("config.toml written");
    assert!(
        toml.contains("FOO"),
        "custom env key persisted to config.toml"
    );

    // Clearing the map persists too.
    edit_profile_env(&mut config, "acct", BTreeMap::new()).expect("clear env");
    assert!(config.find("acct").unwrap().env.is_empty());
}

#[test]
fn edit_profile_env_strips_removed_keys_from_live_settings_when_active() {
    let _home = HomeSandbox::new();
    let mut config = acct_config();
    config.state.active_profile = Some("acct".into());

    let mut env = BTreeMap::new();
    env.insert("KEEP".to_string(), "1".to_string());
    env.insert("DROP".to_string(), "2".to_string());
    edit_profile_env(&mut config, "acct", env).expect("write both");
    let live = crate::claude::claude_settings_env_keys().expect("read settings");
    assert!(live.contains(&"KEEP".to_string()) && live.contains(&"DROP".to_string()));

    // Removing DROP must strip it from the live settings.json, not leak it.
    let mut env2 = BTreeMap::new();
    env2.insert("KEEP".to_string(), "1".to_string());
    edit_profile_env(&mut config, "acct", env2).expect("drop one");
    let live = crate::claude::claude_settings_env_keys().expect("read settings");
    assert!(live.contains(&"KEEP".to_string()));
    assert!(
        !live.contains(&"DROP".to_string()),
        "a removed key is stripped from the live settings on re-apply"
    );
}

// ── set_profile_default_model (`clauth login --model`, the create-form row) ──
// (the ensure_login_profile tests were dropped with the fn — `clauth login` now
//  mints tokens via the browser flow and captures a profile, rather than
//  pre-creating a blank one; `--model` is applied to the captured profile.)

#[test]
fn set_profile_default_model_persists_to_config_toml() {
    let _home = HomeSandbox::new();
    let mut config = acct_config();
    set_profile_default_model(&mut config, "acct", "opus").expect("set model");

    assert_eq!(
        config.find("acct").unwrap().models.default.as_deref(),
        Some("opus")
    );
    let toml = std::fs::read_to_string(profile_dir("acct").unwrap().join("config.toml"))
        .expect("config.toml written");
    assert!(toml.contains("opus"), "model persisted to config.toml");
}

#[test]
fn set_profile_default_model_preserves_alias_overrides() {
    let _home = HomeSandbox::new();
    let mut config = acct_config();
    edit_profile_model(
        &mut config,
        "acct",
        ModelSettings {
            opus: Some("claude-opus-4-8".to_string()),
            ..ModelSettings::default()
        },
    )
    .expect("seed opus alias");

    set_profile_default_model(&mut config, "acct", "sonnet").expect("set default");

    let profile = config.find("acct").unwrap();
    assert_eq!(profile.models.default.as_deref(), Some("sonnet"));
    assert_eq!(
        profile.models.opus.as_deref(),
        Some("claude-opus-4-8"),
        "setting the default must not clobber an existing alias override"
    );
}

#[test]
fn set_profile_default_model_blank_clears_default() {
    let _home = HomeSandbox::new();
    let mut config = acct_config();
    set_profile_default_model(&mut config, "acct", "opus").expect("set model");
    set_profile_default_model(&mut config, "acct", "   ").expect("clear model");
    assert!(
        config.find("acct").unwrap().models.default.is_none(),
        "blank input clears the default, mirroring the Setup tab's ⏎ commit"
    );
}

#[test]
fn validate_profile_name_accepts_email_rejects_path_chars() {
    for name in [
        "claude@domain.com",
        "user2@domain.com",
        "claude+work@gmail.com",
    ] {
        assert!(
            validate_profile_name(name, &[], None).is_ok(),
            "{name} rejected"
        );
    }
    // path separators / windows-reserved chars stay blocked so the name can't
    // escape its profiles/<name> directory segment.
    for name in ["a/b", "a\\b", "a:b", ".lead", "a b"] {
        assert!(
            validate_profile_name(name, &[], None).is_err(),
            "{name} accepted"
        );
    }
}

// ── capture-name collision overwrite (issue #7) ────────────────────────────

/// Overwriting an existing profile on a capture-name collision must mutate it
/// in place: chain position, env, model/fallback config, and auto_start
/// survive; only credentials/base_url/api_key change; usage_history.jsonl
/// (a persisted log, not a cache) is untouched; the stale per-account fetch
/// caches are dropped since they now describe the wrong credentials.
#[test]
fn overwrite_captured_profile_keeps_config_and_history_swaps_credentials() {
    let _home = HomeSandbox::new();

    // "acme" sits in the MIDDLE of a 3-profile chain — a blind delete+append
    // would move it to the end, so this actually proves position survives an
    // in-place mutation rather than merely proving membership.
    let first = Profile::new("first".to_string(), None, None);
    save_profile(&first).expect("save first");
    let last = Profile::new("last".to_string(), None, None);
    save_profile(&last).expect("save last");

    let mut target = Profile::new("acme".to_string(), None, None);
    target.auto_start = true;
    target.env.insert("FOO".to_string(), "bar".to_string());
    target.fallback_threshold = Some(42.0);
    target.bell_threshold = Some(77.0);
    target.models.opus = Some("claude-opus-4".to_string());
    target.credentials = Some(ClaudeCredentials {
        claude_ai_oauth: Some(crate::profile::OAuthToken {
            access_token: "old-access".to_string(),
            refresh_token: Some("old-refresh".to_string()),
            expires_at: None,
            scopes: None,
            subscription_type: None,
        }),
    });
    save_profile(&target).expect("save target");

    let history_path = profile_dir("acme").unwrap().join("usage_history.jsonl");
    std::fs::write(&history_path, b"{\"ts\":1}\n").expect("seed usage history");

    // Seed the transient fetch-state caches the overwrite must drop.
    for file in [
        crate::profile_cache::USAGE_CACHE_FILE,
        crate::profile_cache::THIRD_PARTY_CACHE_FILE,
        crate::throughput::THROUGHPUT_CACHE_FILE,
    ] {
        crate::profile_cache::write_profile_cache("acme", file, &"stale");
    }

    let mut config = AppConfig {
        state: AppState {
            profiles: vec!["first".into(), "acme".into(), "last".into()],
            fallback_chain: vec!["first".into(), "acme".into(), "last".into()],
            active_profile: Some("first".into()),
            ..AppState::default()
        },
        profiles: vec![first, target, last],
    };

    let snapshot = CaptureSnapshot {
        credentials: Some(ClaudeCredentials {
            claude_ai_oauth: Some(crate::profile::OAuthToken {
                access_token: "new-access".to_string(),
                refresh_token: Some("new-refresh".to_string()),
                expires_at: None,
                scopes: None,
                subscription_type: None,
            }),
        }),
        base_url: Some("https://api.example.com".to_string()),
        api_key: Some("new-api-key".to_string()),
    };

    overwrite_captured_profile(&mut config, "acme", snapshot).expect("overwrite in place");

    assert_eq!(
        config.profiles.len(),
        3,
        "no duplicate entry from a blind append"
    );
    let acme = config
        .find("acme")
        .expect("profile still present under the same name");
    assert_eq!(
        acme.access_token(),
        Some("new-access"),
        "credentials replaced"
    );
    assert_eq!(
        acme.base_url.as_deref(),
        Some("https://api.example.com"),
        "base_url replaced"
    );
    assert_eq!(
        acme.api_key.as_deref(),
        Some("new-api-key"),
        "api_key replaced"
    );
    assert!(acme.auto_start, "auto_start config preserved");
    assert_eq!(
        acme.env.get("FOO"),
        Some(&"bar".to_string()),
        "env map preserved"
    );
    assert_eq!(
        acme.fallback_threshold,
        Some(42.0),
        "fallback_threshold preserved"
    );
    assert_eq!(acme.bell_threshold, Some(77.0), "bell_threshold preserved");
    assert_eq!(
        acme.models.opus.as_deref(),
        Some("claude-opus-4"),
        "model settings preserved"
    );
    assert!(
        acme.usage.is_none() && acme.fetch_status.is_none() && acme.third_party_usage.is_none(),
        "transient fetch state cleared"
    );

    assert_eq!(
        config.state.fallback_chain,
        vec![
            crate::profile::ProfileName::from("first"),
            crate::profile::ProfileName::from("acme"),
            crate::profile::ProfileName::from("last"),
        ],
        "chain position must survive an in-place overwrite, not delete+append"
    );

    assert_eq!(
        std::fs::read_to_string(&history_path).unwrap(),
        "{\"ts\":1}\n",
        "usage_history.jsonl is the persisted log, not a cache — must survive"
    );

    for file in [
        crate::profile_cache::USAGE_CACHE_FILE,
        crate::profile_cache::THIRD_PARTY_CACHE_FILE,
        crate::throughput::THROUGHPUT_CACHE_FILE,
    ] {
        let path = crate::profile_cache::profile_cache_path("acme", file).unwrap();
        assert!(
            !path.exists(),
            "{file} must be dropped — it describes the old account"
        );
    }
}

/// Overwriting the ACTIVE profile must re-apply to live `~/.claude` state —
/// mirrors `edit_profile_endpoint`'s active-case handling. Without this a
/// running `claude` keeps reading the OLD endpoint/token until the next
/// explicit switch, and dropping OAuth creds on an active profile (a
/// third-party recapture) would leave `.credentials.json` a dangling
/// symlink instead of a clean absence.
#[test]
fn overwrite_captured_profile_reapplies_live_state_when_active() {
    let _home = HomeSandbox::new();

    let mut acme = Profile::new("acme".to_string(), None, None);
    acme.credentials = Some(ClaudeCredentials {
        claude_ai_oauth: Some(crate::profile::OAuthToken {
            access_token: "old-access".to_string(),
            refresh_token: Some("old-refresh".to_string()),
            expires_at: None,
            scopes: None,
            subscription_type: None,
        }),
    });
    save_profile(&acme).expect("save acme");
    crate::claude::link_profile_credentials("acme").expect("link acme live");

    let mut config = AppConfig {
        state: AppState {
            profiles: vec!["acme".into()],
            fallback_chain: vec!["acme".into()],
            active_profile: Some("acme".into()),
            ..AppState::default()
        },
        profiles: vec![acme],
    };

    // Overwrite the active profile with a third-party (no-OAuth) snapshot.
    let snapshot = CaptureSnapshot {
        credentials: None,
        base_url: Some("https://api.example.com".to_string()),
        api_key: Some("new-api-key".to_string()),
    };
    overwrite_captured_profile(&mut config, "acme", snapshot).expect("overwrite active profile");

    let live_endpoint = crate::claude::read_claude_endpoint_config().expect("read live endpoint");
    assert_eq!(
        live_endpoint.base_url.as_deref(),
        Some("https://api.example.com"),
        "live settings.json must pick up the new base_url immediately, not on next switch"
    );
    assert_eq!(
        live_endpoint.api_key.as_deref(),
        Some("new-api-key"),
        "live settings.json must pick up the new api_key immediately, not on next switch"
    );

    let live_path = crate::profile::claude_dir()
        .unwrap()
        .join(".credentials.json");
    assert!(
        live_path.symlink_metadata().is_err(),
        "no dangling .credentials.json symlink after credentials go to None while active"
    );
}

/// Blanking an active profile drops its credentials + per-account fetch caches
/// and clears the live link + `active_profile`, while name/env/model survive.
#[test]
fn clear_profile_credentials_blanks_active_profile_keeping_shell() {
    let _home = HomeSandbox::new();

    let mut acct = Profile::new("acct".to_string(), None, None);
    acct.auto_start = true;
    acct.env.insert("FOO".to_string(), "bar".to_string());
    acct.models.opus = Some("claude-opus-4".to_string());
    acct.credentials = Some(ClaudeCredentials {
        claude_ai_oauth: Some(crate::profile::OAuthToken {
            access_token: "acc".to_string(),
            refresh_token: Some("ref".to_string()),
            expires_at: None,
            scopes: None,
            subscription_type: None,
        }),
    });
    save_profile(&acct).expect("save acct");
    crate::claude::link_profile_credentials("acct").expect("link acct live");

    for file in [
        crate::profile_cache::USAGE_CACHE_FILE,
        crate::profile_cache::THIRD_PARTY_CACHE_FILE,
        crate::throughput::THROUGHPUT_CACHE_FILE,
    ] {
        crate::profile_cache::write_profile_cache("acct", file, &"stale");
    }

    let mut config = AppConfig {
        state: AppState {
            profiles: vec!["acct".into()],
            fallback_chain: vec!["acct".into()],
            active_profile: Some("acct".into()),
            ..AppState::default()
        },
        profiles: vec![acct],
    };

    clear_profile_credentials(&mut config, "acct").expect("clear credentials");

    let profile = config.find("acct").expect("profile still present");
    assert!(profile.credentials.is_none(), "credentials dropped");
    assert!(profile.auto_start, "shell preserved: auto_start");
    assert_eq!(
        profile.env.get("FOO"),
        Some(&"bar".to_string()),
        "shell preserved: env"
    );
    assert_eq!(
        profile.models.opus.as_deref(),
        Some("claude-opus-4"),
        "shell preserved: model"
    );
    assert!(
        config.state.active_profile.is_none(),
        "active profile deactivated"
    );

    let cred_path = profile_dir("acct").unwrap().join("credentials.json");
    assert!(!cred_path.exists(), "credentials.json removed");

    for file in [
        crate::profile_cache::USAGE_CACHE_FILE,
        crate::profile_cache::THIRD_PARTY_CACHE_FILE,
        crate::throughput::THROUGHPUT_CACHE_FILE,
    ] {
        let path = crate::profile_cache::profile_cache_path("acct", file).unwrap();
        assert!(!path.exists(), "{file} must be dropped");
    }

    let live_path = crate::profile::claude_dir()
        .unwrap()
        .join(".credentials.json");
    assert!(
        live_path.symlink_metadata().is_err(),
        "live .credentials.json link cleared on blanking the active profile"
    );
}

/// Blanking a NON-active profile must not touch the active link / `active_profile`,
/// and a lingering rotation sidecar must not resurrect the deleted login on the
/// next disk load (`recover_pending_credentials` treats a missing credentials.json
/// as a failed commit and adopts the sidecar).
#[test]
fn clear_profile_credentials_non_active_and_no_sidecar_resurrection() {
    let _home = HomeSandbox::new();

    let creds = || ClaudeCredentials {
        claude_ai_oauth: Some(crate::profile::OAuthToken {
            access_token: "acc".to_string(),
            refresh_token: Some("ref".to_string()),
            expires_at: None,
            scopes: None,
            subscription_type: None,
        }),
    };

    let mut acct = Profile::new("acct".to_string(), None, None);
    acct.credentials = Some(creds());
    save_profile(&acct).expect("save acct");
    // A rotation sidecar that never committed — the resurrection vector.
    crate::profile::stage_rotated_credentials("acct", &creds()).expect("stage sidecar");

    let mut other = Profile::new("other".to_string(), None, None);
    other.credentials = Some(creds());
    save_profile(&other).expect("save other");
    crate::claude::link_profile_credentials("other").expect("link other live");

    let mut config = AppConfig {
        state: AppState {
            profiles: vec!["acct".into(), "other".into()],
            fallback_chain: vec!["acct".into(), "other".into()],
            active_profile: Some("other".into()),
            ..AppState::default()
        },
        profiles: vec![acct, other],
    };

    // Persist the profile list so `load_config` below can find both by name.
    crate::profile::save_app_state(&config.state).expect("persist state");

    clear_profile_credentials(&mut config, "acct").expect("clear credentials");

    // The active profile and its live link are untouched — only "acct" changed.
    assert_eq!(
        config.state.active_profile.as_deref(),
        Some("other"),
        "blanking a non-active profile leaves the active one set"
    );
    let live_path = crate::profile::claude_dir()
        .unwrap()
        .join(".credentials.json");
    assert!(
        live_path.symlink_metadata().is_ok(),
        "the active profile's live link survives a non-active blank"
    );

    // Reload from disk: the sidecar must be gone, so the login stays deleted.
    let reloaded = crate::profile::load_config().expect("reload config");
    let acct = reloaded.find("acct").expect("acct still present");
    assert!(
        acct.credentials.is_none(),
        "a lingering sidecar must not resurrect the blanked login"
    );
    let cred_path = profile_dir("acct").unwrap().join("credentials.json");
    assert!(
        !cred_path.exists(),
        "credentials.json stays gone after reload (sidecar not adopted)"
    );
}

// ── issue #17: stale oauthAccount deleted on every switch path ────────────

fn home_claude_json_path() -> std::path::PathBuf {
    crate::profile::home_dir().unwrap().join(".claude.json")
}

fn write_home_claude_json_with_identity() {
    std::fs::write(
        home_claude_json_path(),
        serde_json::to_vec_pretty(&serde_json::json!({
            "oauthAccount": {"emailAddress": "stale@x"},
            "numStartups": 7,
        }))
        .unwrap(),
    )
    .expect("write home .claude.json");
}

/// `finish_switch` is the shared convergence point for the manual CLI, TUI,
/// MCP `switch`, and fallback switch paths (all four route through
/// `switch_profile`/`switch_profile_reconciled`/`switch_profile_discard`,
/// which call it under the state lock) — asserting on it directly pins the
/// behaviour for all of them at once.
#[test]
fn finish_switch_deletes_stale_oauth_account_block() {
    let _home = HomeSandbox::new();
    write_home_claude_json_with_identity();

    let mut config = acct_config();
    finish_switch(&mut config, "acct").expect("finish_switch");

    let after: serde_json::Value =
        serde_json::from_slice(&std::fs::read(home_claude_json_path()).unwrap()).unwrap();
    assert!(
        after.get("oauthAccount").is_none(),
        "the outgoing account's identity block must be gone after a switch"
    );
    assert_eq!(
        after["numStartups"],
        serde_json::json!(7),
        "unrelated keys must survive the switch untouched"
    );
}

/// `switch_off` (chain-exhausted / manual "turn off") clears live credentials
/// without going through `finish_switch` — a stale identity block is just as
/// wrong once creds are gone, so it needs its own coverage rather than relying
/// on the shared path.
#[test]
fn switch_off_also_deletes_stale_oauth_account_block() {
    let _home = HomeSandbox::new();
    write_home_claude_json_with_identity();

    let profile = Profile::new("acct".to_string(), None, None);
    save_profile(&profile).expect("save profile");
    crate::claude::link_profile_credentials("acct").expect("link acct live");

    let mut config = AppConfig {
        state: AppState {
            profiles: vec!["acct".into()],
            active_profile: Some("acct".into()),
            ..AppState::default()
        },
        profiles: vec![profile],
    };

    switch_off(&mut config).expect("switch_off");

    assert!(config.state.active_profile.is_none());
    let after: serde_json::Value =
        serde_json::from_slice(&std::fs::read(home_claude_json_path()).unwrap()).unwrap();
    assert!(
        after.get("oauthAccount").is_none(),
        "no active account remains, so the stale identity block must be gone too"
    );
    assert_eq!(after["numStartups"], serde_json::json!(7));
}