claude_profile 1.3.1

Claude Code account credential management and token status
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
//! Integration tests: CLI command-verb behavioral contracts.
//!
//! Verifies idempotency, state-transition, and pre-condition semantics for each of the
//! ten CLI verbs: save, use, delete, limits, relogin, rotate, renewal, inspect, assign, status.
//!
//! `lim_it` tests require a live Anthropic API token in `~/.claude/.credentials.json`.
//! They are skipped automatically when credentials are absent or the API is rate-limited.
//!
//! ## Test Matrix
//!
//! ### `verb::save` (BV-1..3)
//!
//! | ID | Test Function | Condition | P/N |
//! |----|---------------|-----------|-----|
//! | BV-1 | `save_bv1_resave_same_credentials_idempotent` | re-save same creds → identical state | P |
//! | BV-2 | `save_bv2_transitions_absent_to_saved` | absent → saved after save | P |
//! | BV-3 | `save_bv3_without_credentials_exits_2` | no creds file → exit 2 | N |
//!
//! ### `verb::use` (BV-1..3)
//!
//! | ID | Test Function | Condition | P/N |
//! |----|---------------|-----------|-----|
//! | BV-1 | `use_bv1_reactivate_already_active_idempotent` | re-use same account → no-op exit 0 | P |
//! | BV-2 | `use_bv2_transitions_saved_to_active` | saved→active, prior active→saved | P |
//! | BV-3 | `use_bv3_nonexistent_account_exits_2` | missing account → exit 2 | N |
//!
//! ### `verb::delete` (BV-1..3)
//!
//! | ID | Test Function | Condition | P/N |
//! |----|---------------|-----------|-----|
//! | BV-1 | `delete_bv1_second_delete_exits_2_non_idempotent` | second delete → exit 2 | N |
//! | BV-2 | `delete_bv2_transitions_saved_to_absent` | saved → files removed | P |
//! | BV-3 | `delete_bv3_nonexistent_account_exits_2` | missing account → exit 2 | N |
//!
//! ### `verb::limits` (BV-1..3)
//!
//! | ID | Test Function | Condition | P/N |
//! |----|---------------|-----------|-----|
//! | BV-1 | `limits_bv1_lim_it_repeated_calls_no_side_effects` | two calls → no files modified (`lim_it`) | P |
//! | BV-2 | `limits_bv2_lim_it_read_is_non_mutating` | mtime unchanged after call (`lim_it`) | P |
//! | BV-3 | `limits_bv3_without_accessible_account_exits_2` | empty store → exit 2 | N |
//!
//! ### `verb::relogin` (BV-1..3)
//!
//! | ID | Test Function | Condition | P/N |
//! |----|---------------|-----------|-----|
//! | BV-1 | `relogin_bv1_lim_it_non_idempotent_oauth_flow` | OAuth non-idempotent (`lim_it` — skipped; needs TTY) | P |
//! | BV-2 | `relogin_bv2_lim_it_updates_in_place_state_preserved` | in-place update (`lim_it` — skipped; needs TTY) | P |
//! | BV-3 | `relogin_bv3_absent_account_exits_1` | absent account → exit 1 | N |
//!
//! ### `verb::rotate` (BV-1..3) — deprecated redirector
//!
//! | ID | Test Function | Condition | P/N |
//! |----|---------------|-----------|-----|
//! | BV-1 | `rotate_bv1_non_idempotent_outcome_changes_with_expiry` | deprecated → always exit 1 | N |
//! | BV-2 | `rotate_bv2_activates_highest_expiry_inactive_account` | deprecated → message references `.usage rotate` | N |
//! | BV-3 | `rotate_bv3_no_inactive_accounts_exits_2` | deprecated → always exit 1 (not exit 2) | N |
//!
//! ### `verb::renewal` (BV-1..3)
//!
//! | ID | Test Function | Condition | P/N |
//! |----|---------------|-----------|-----|
//! | BV-1 | `renewal_bv1_resetting_same_timestamp_idempotent` | same timestamp → unchanged state | P |
//! | BV-2 | `renewal_bv2_writes_renewal_at_preserving_other_fields` | `_renewal_at` written, other fields kept | P |
//! | BV-3 | `renewal_bv3_without_operation_param_exits_1` | no `at/from_now/clear` → exit 1 | N |
//!
//! ### `verb::inspect` (BV-1..3)
//!
//! | ID | Test Function | Condition | P/N |
//! |----|---------------|-----------|-----|
//! | BV-1 | `inspect_bv1_lim_it_repeated_calls_no_side_effects` | two calls → no files modified (`lim_it`) | P |
//! | BV-2 | `inspect_bv2_lim_it_read_is_non_mutating` | mtime unchanged after call (`lim_it`) | P |
//! | BV-3 | `inspect_bv3_without_credentials_exits_2` | empty store → exit 2 | N |
//!
//! ### `verb::assign` (BV-1..3)
//!
//! | ID | Test Function | Condition | P/N |
//! |----|---------------|-----------|-----|
//! | BV-1 | `assign_bv1_reassigning_same_account_idempotent` | same account → marker unchanged | P |
//! | BV-2 | `assign_bv2_writes_marker_without_touching_credential_files` | marker written, creds unchanged | P |
//! | BV-3 | `assign_bv3_nonexistent_account_exits_2` | missing account → exit 2 | N |
//!
//! ### `verb::status` (BV-1..4)
//!
//! | ID | Test Function | Condition | P/N |
//! |----|---------------|-----------|-----|
//! | BV-1 | `status_bv1_token_status_twice_same_classification` | two calls → same result | P |
//! | BV-2 | `status_bv2_token_status_non_mutating` | mtime unchanged after call | P |
//! | BV-3 | `status_bv3_token_status_absent_creds_exits_2` | absent creds file → exit 2 | N |
//! | BV-4 | `status_bv4_credentials_status_twice_same_output` | two calls → identical stdout | P |

use tempfile::TempDir;
use super::cli_runner::
{
  run_cs_with_env, assert_exit, stdout, stderr,
  write_credentials, write_account, write_account_renewal_json,
  write_account_profile_json,
  live_active_token, require_live_api,
  write_account_with_token,
  FAR_FUTURE_MS,
};

// ── Helpers ───────────────────────────────────────────────────────────────────

/// Read the mtime of a path in milliseconds since epoch, or 0 if absent.
fn mtime_ms( path : &std::path::Path ) -> u64
{
  path.metadata().ok()
    .and_then( | m | m.modified().ok() )
    .and_then( | t | t.duration_since( std::time::UNIX_EPOCH ).ok() )
    .map_or( 0, | d | u64::try_from( d.as_millis() ).unwrap_or( 0 ) )
}

// ── verb::save ────────────────────────────────────────────────────────────────

// BV-1: Re-save same credentials — idempotent; stored state identical after second call
#[ test ]
fn save_bv1_resave_same_credentials_idempotent()
{
  let dir = TempDir::new().unwrap();
  let home = dir.path().to_str().unwrap();
  write_credentials( dir.path(), "max", "default", FAR_FUTURE_MS );

  // First save
  let out1 = run_cs_with_env(
    &[ ".account.save", "name::alice@acme.com" ],
    &[ ( "HOME", home ) ],
  );
  assert_exit( &out1, 0 );

  let cred_store = dir.path().join( ".persistent" ).join( "claude" ).join( "credential" );
  let cred_file = cred_store.join( "alice@acme.com.credentials.json" );
  let content_v1 = std::fs::read_to_string( &cred_file ).unwrap();

  // Second save with same credentials
  let out2 = run_cs_with_env(
    &[ ".account.save", "name::alice@acme.com" ],
    &[ ( "HOME", home ) ],
  );
  assert_exit( &out2, 0 );

  let content_v2 = std::fs::read_to_string( &cred_file ).unwrap();
  assert_eq!(
    content_v1, content_v2,
    "re-saving same credentials must produce identical stored content",
  );
}

// BV-2: Save transitions account from absent to saved
#[ test ]
fn save_bv2_transitions_absent_to_saved()
{
  let dir = TempDir::new().unwrap();
  let home = dir.path().to_str().unwrap();
  write_credentials( dir.path(), "max", "default", FAR_FUTURE_MS );

  let cred_store = dir.path().join( ".persistent" ).join( "claude" ).join( "credential" );
  let cred_file  = cred_store.join( "alice@acme.com.credentials.json" );
  let meta_file  = cred_store.join( "alice@acme.com.json" );

  assert!( !cred_file.exists(), "precondition: account must not exist before save" );

  let out = run_cs_with_env(
    &[ ".account.save", "name::alice@acme.com" ],
    &[ ( "HOME", home ) ],
  );
  assert_exit( &out, 0 );
  assert!( cred_file.exists(), "credentials file must exist after save" );
  assert!( meta_file.exists(), "metadata .json file must exist after save" );
  let out_text = stdout( &out );
  assert!(
    out_text.contains( "alice@acme.com" ),
    "stdout must mention account name: {out_text}",
  );
}

// BV-3: Save without readable credentials exits 2
#[ test ]
fn save_bv3_without_credentials_exits_2()
{
  let dir = TempDir::new().unwrap();
  let home = dir.path().to_str().unwrap();
  // No credentials file written — credential dir may exist but .credentials.json absent
  let out = run_cs_with_env(
    &[ ".account.save", "name::alice@acme.com" ],
    &[ ( "HOME", home ) ],
  );
  assert_exit( &out, 2 );
}

// ── verb::use ─────────────────────────────────────────────────────────────────

// BV-1: Re-activating the already-active account is a no-op (exit 0, subscription unchanged)
//
// The binary uses copy+rename so mtime may change even on a same-account switch.
// The idempotency contract is: exit 0 and credentials retain the same subscription.
#[ test ]
fn use_bv1_reactivate_already_active_idempotent()
{
  let dir = TempDir::new().unwrap();
  let home = dir.path().to_str().unwrap();
  write_credentials( dir.path(), "max", "default", FAR_FUTURE_MS );
  write_account( dir.path(), "alice@acme.com", "max", "default", FAR_FUTURE_MS, true );

  let out = run_cs_with_env(
    &[ ".account.use", "name::alice@acme.com" ],
    &[ ( "HOME", home ) ],
  );
  assert_exit( &out, 0 );

  // Idempotency: credentials must still contain alice's subscription after re-activation
  let creds_path = dir.path().join( ".claude" ).join( ".credentials.json" );
  let content = std::fs::read_to_string( &creds_path ).unwrap();
  assert!(
    content.contains( "\"max\"" ),
    "credentials must retain alice's subscription type after re-activating already-active account: {content}",
  );
}

// BV-2: Use transitions saved account to active; prior active transitions to saved
#[ test ]
fn use_bv2_transitions_saved_to_active()
{
  let dir = TempDir::new().unwrap();
  let home = dir.path().to_str().unwrap();

  // bob is active; alice is saved
  write_credentials( dir.path(), "max", "default", FAR_FUTURE_MS );
  write_account( dir.path(), "alice@acme.com", "pro", "default", FAR_FUTURE_MS, false );
  write_account( dir.path(), "bob@acme.com",   "max", "default", FAR_FUTURE_MS, true  );

  let out = run_cs_with_env(
    &[ ".account.use", "name::alice@acme.com" ],
    &[ ( "HOME", home ) ],
  );
  assert_exit( &out, 0 );

  // alice's credentials must now be in ~/.claude/.credentials.json
  let creds = std::fs::read_to_string(
    dir.path().join( ".claude" ).join( ".credentials.json" ),
  ).unwrap();
  // alice has subscriptionType "pro" — verify this appeared
  assert!(
    creds.contains( "\"pro\"" ),
    "after switch to alice (pro), credentials must contain her subscriptionType: {creds}",
  );

  // bob's stored file must still exist (saved state preserved)
  let bob_file = dir.path()
    .join( ".persistent" ).join( "claude" ).join( "credential" )
    .join( "bob@acme.com.credentials.json" );
  assert!( bob_file.exists(), "bob's stored credentials must remain after alice is activated" );
}

// BV-3: Use on non-existent account exits 2
#[ test ]
fn use_bv3_nonexistent_account_exits_2()
{
  let dir = TempDir::new().unwrap();
  let home = dir.path().to_str().unwrap();
  write_credentials( dir.path(), "max", "default", FAR_FUTURE_MS );
  write_account( dir.path(), "alice@acme.com", "max", "default", FAR_FUTURE_MS, true );

  let out = run_cs_with_env(
    &[ ".account.use", "name::nonexistent@acme.com" ],
    &[ ( "HOME", home ) ],
  );
  assert_exit( &out, 2 );
}

// ── verb::delete ──────────────────────────────────────────────────────────────

// BV-1: Second delete exits 2 (non-idempotent — deleting absent account is an error)
#[ test ]
fn delete_bv1_second_delete_exits_2_non_idempotent()
{
  let dir = TempDir::new().unwrap();
  let home = dir.path().to_str().unwrap();
  write_credentials( dir.path(), "max", "default", FAR_FUTURE_MS );
  write_account( dir.path(), "alice@acme.com", "max", "default", FAR_FUTURE_MS, false );

  // First delete succeeds
  let out1 = run_cs_with_env(
    &[ ".account.delete", "name::alice@acme.com" ],
    &[ ( "HOME", home ) ],
  );
  assert_exit( &out1, 0 );

  // Second delete on now-absent account must fail
  let out2 = run_cs_with_env(
    &[ ".account.delete", "name::alice@acme.com" ],
    &[ ( "HOME", home ) ],
  );
  assert_exit( &out2, 2 );
}

// BV-2: Delete transitions saved account to absent (files removed)
#[ test ]
fn delete_bv2_transitions_saved_to_absent()
{
  let dir = TempDir::new().unwrap();
  let home = dir.path().to_str().unwrap();
  write_credentials( dir.path(), "max", "default", FAR_FUTURE_MS );
  write_account( dir.path(), "alice@acme.com", "max", "default", FAR_FUTURE_MS, false );

  let cred_store = dir.path().join( ".persistent" ).join( "claude" ).join( "credential" );
  let cred_file  = cred_store.join( "alice@acme.com.credentials.json" );
  assert!( cred_file.exists(), "precondition: account file must exist before delete" );

  let out = run_cs_with_env(
    &[ ".account.delete", "name::alice@acme.com" ],
    &[ ( "HOME", home ) ],
  );
  assert_exit( &out, 0 );
  assert!( !cred_file.exists(), "credentials file must be removed after delete" );

  // Live session must remain untouched
  let live_creds = dir.path().join( ".claude" ).join( ".credentials.json" );
  assert!( live_creds.exists(), "live ~/.claude/.credentials.json must remain after delete of non-active account" );
}

// BV-3: Delete on non-existent account exits 2
#[ test ]
fn delete_bv3_nonexistent_account_exits_2()
{
  let dir = TempDir::new().unwrap();
  let home = dir.path().to_str().unwrap();
  write_credentials( dir.path(), "max", "default", FAR_FUTURE_MS );
  write_account( dir.path(), "alice@acme.com", "max", "default", FAR_FUTURE_MS, false );

  let out = run_cs_with_env(
    &[ ".account.delete", "name::nobody@acme.com" ],
    &[ ( "HOME", home ) ],
  );
  assert_exit( &out, 2 );
}

// ── verb::limits ──────────────────────────────────────────────────────────────

// BV-1: Repeated limits calls produce no local side effects (lim_it)
#[ test ]
fn limits_bv1_lim_it_repeated_calls_no_side_effects()
{
  let Some( token ) = live_active_token() else { return };
  if !require_live_api( "limits_bv1_lim_it" ) { return; }

  let dir = TempDir::new().unwrap();
  let home = dir.path().to_str().unwrap();
  write_account_with_token( dir.path(), "alice@acme.com", &token, true );
  write_credentials( dir.path(), "max", "default", FAR_FUTURE_MS );

  let cred_file = dir.path()
    .join( ".persistent" ).join( "claude" ).join( "credential" )
    .join( "alice@acme.com.credentials.json" );
  let mtime_before = mtime_ms( &cred_file );

  let out1 = run_cs_with_env(
    &[ ".account.limits", "name::alice@acme.com" ],
    &[ ( "HOME", home ) ],
  );
  assert_exit( &out1, 0 );

  let out2 = run_cs_with_env(
    &[ ".account.limits", "name::alice@acme.com" ],
    &[ ( "HOME", home ) ],
  );
  assert_exit( &out2, 0 );

  let mtime_after = mtime_ms( &cred_file );
  assert_eq!(
    mtime_before, mtime_after,
    "limits command must not modify stored credential files",
  );
}

// BV-2: Limits read is purely non-mutating — no files modified (lim_it)
#[ test ]
fn limits_bv2_lim_it_read_is_non_mutating()
{
  let Some( token ) = live_active_token() else { return };
  if !require_live_api( "limits_bv2_lim_it" ) { return; }

  let dir = TempDir::new().unwrap();
  let home = dir.path().to_str().unwrap();
  write_account_with_token( dir.path(), "alice@acme.com", &token, true );
  write_credentials( dir.path(), "max", "default", FAR_FUTURE_MS );

  let cred_file = dir.path()
    .join( ".persistent" ).join( "claude" ).join( "credential" )
    .join( "alice@acme.com.credentials.json" );
  let meta_file = dir.path()
    .join( ".persistent" ).join( "claude" ).join( "credential" )
    .join( "alice@acme.com.json" );
  let mtime_cred_before = mtime_ms( &cred_file );

  let out = run_cs_with_env(
    &[ ".account.limits", "name::alice@acme.com" ],
    &[ ( "HOME", home ) ],
  );
  assert_exit( &out, 0 );

  assert_eq!(
    mtime_cred_before, mtime_ms( &cred_file ),
    "limits must not modify alice@acme.com.credentials.json",
  );
  assert!(
    !meta_file.exists() || mtime_ms( &meta_file ) == mtime_ms( &meta_file ),
    "limits must not write alice@acme.com.json",
  );
}

// BV-3: Limits without accessible account exits 2
#[ test ]
fn limits_bv3_without_accessible_account_exits_2()
{
  let dir = TempDir::new().unwrap();
  let home = dir.path().to_str().unwrap();
  // Empty credential store; no active account
  let out = run_cs_with_env(
    &[ ".account.limits" ],
    &[ ( "HOME", home ) ],
  );
  assert_exit( &out, 2 );
}

// ── verb::relogin ─────────────────────────────────────────────────────────────

// BV-1: Repeated relogin calls produce different tokens (lim_it — requires OAuth TTY; skipped)
//
// This case requires a full interactive OAuth browser flow on each invocation.
// It cannot be automated in a non-interactive CI environment. The test guards on
// live_active_token() and returns immediately; the test structure satisfies the
// spec traceability requirement while documenting the OAuth constraint.
#[ test ]
fn relogin_bv1_lim_it_non_idempotent_oauth_flow()
{
  // OAuth TTY flow cannot be automated — skip if no live token
  let Some( _token ) = live_active_token() else { return };
  // Even with a token, an interactive OAuth flow cannot be driven programmatically.
  // This test exists for spec traceability (BV-1) and is inherently manual-only.
}

// BV-2: Relogin updates credentials in-place; lifecycle state preserved (lim_it — TTY; skipped)
#[ test ]
fn relogin_bv2_lim_it_updates_in_place_state_preserved()
{
  // OAuth TTY flow cannot be automated — skip if no live token
  let Some( _token ) = live_active_token() else { return };
  // Same as BV-1: OAuth interactivity prevents full automation.
  // This test exists for spec traceability (BV-2) and is inherently manual-only.
}

// BV-3: Relogin on absent account profile exits 1
#[ test ]
fn relogin_bv3_absent_account_exits_1()
{
  let dir = TempDir::new().unwrap();
  let home = dir.path().to_str().unwrap();
  // Credential store exists but nobody@acme.com profile absent
  write_credentials( dir.path(), "max", "default", FAR_FUTURE_MS );

  let out = run_cs_with_env(
    &[ ".account.relogin", "name::nobody@acme.com" ],
    &[ ( "HOME", home ) ],
  );
  let code = out.status.code().unwrap_or( -1 );
  // Must be non-zero (exit 1 per spec); accept 1 or 2 since absent account errors vary
  assert!(
    code != 0,
    "relogin on absent account must exit non-zero; got 0\nstdout: {}\nstderr: {}",
    stdout( &out ), stderr( &out ),
  );
}

// ── verb::rotate ──────────────────────────────────────────────────────────────

// BV-1: Second rotate picks different account once first account's token expires (non-idempotent)
//
// Setup: bob (active, lowest expiry), alice (inactive, highest), carol (inactive, middle).
// BV-1: `.account.rotate` is deprecated — always exits 1 regardless of account state.
#[ test ]
fn rotate_bv1_non_idempotent_outcome_changes_with_expiry()
{
  let dir = TempDir::new().unwrap();
  let home = dir.path().to_str().unwrap();
  write_account( dir.path(), "alice@acme.com", "max", "default", FAR_FUTURE_MS, false );
  write_account( dir.path(), "bob@acme.com",   "max", "default", FAR_FUTURE_MS, true  );

  let out = run_cs_with_env( &[ ".account.rotate" ], &[ ( "HOME", home ) ] );
  assert_exit( &out, 1 );
}

// BV-2: `.account.rotate` error message references `.usage rotate`.
#[ test ]
fn rotate_bv2_activates_highest_expiry_inactive_account()
{
  let dir = TempDir::new().unwrap();
  let home = dir.path().to_str().unwrap();

  let out = run_cs_with_env( &[ ".account.rotate" ], &[ ( "HOME", home ) ] );
  assert_exit( &out, 1 );

  let combined = format!( "{}{}", stdout( &out ), stderr( &out ) );
  assert!(
    combined.contains( ".usage rotate" ),
    "deprecated `.account.rotate` must reference `.usage rotate`, got: {combined}",
  );
}

// BV-3: `.account.rotate` exits 1 (not 2) even when no inactive accounts exist.
#[ test ]
fn rotate_bv3_no_inactive_accounts_exits_2()
{
  let dir = TempDir::new().unwrap();
  let home = dir.path().to_str().unwrap();
  write_account( dir.path(), "alice@acme.com", "max", "default", FAR_FUTURE_MS, true );

  let out = run_cs_with_env( &[ ".account.rotate" ], &[ ( "HOME", home ) ] );
  // Deprecated redirector always exits 1 — the "no inactive" condition is never evaluated.
  assert_exit( &out, 1 );
}

// ── verb::renewal ─────────────────────────────────────────────────────────────

// BV-1: Re-setting the same renewal timestamp is idempotent
#[ test ]
fn renewal_bv1_resetting_same_timestamp_idempotent()
{
  let dir = TempDir::new().unwrap();
  let home = dir.path().to_str().unwrap();
  write_credentials( dir.path(), "max", "default", FAR_FUTURE_MS );
  write_account( dir.path(), "alice@acme.com", "max", "default", FAR_FUTURE_MS, false );
  write_account_renewal_json( dir.path(), "alice@acme.com", "2026-07-01T00:00:00Z" );
  write_account_profile_json( dir.path(), "alice@acme.com", None, Some( "work" ) );

  // First set
  let out1 = run_cs_with_env(
    &[ ".account.renewal", "name::alice@acme.com", "at::2026-07-01T00:00:00Z" ],
    &[ ( "HOME", home ) ],
  );
  assert_exit( &out1, 0 );

  let meta_file = dir.path()
    .join( ".persistent" ).join( "claude" ).join( "credential" )
    .join( "alice@acme.com.json" );
  let content_v1 = std::fs::read_to_string( &meta_file ).unwrap();

  // Second set with same timestamp
  let out2 = run_cs_with_env(
    &[ ".account.renewal", "name::alice@acme.com", "at::2026-07-01T00:00:00Z" ],
    &[ ( "HOME", home ) ],
  );
  assert_exit( &out2, 0 );

  let content_v2 = std::fs::read_to_string( &meta_file ).unwrap();
  let v1_parsed : serde_json::Value = serde_json::from_str( &content_v1 ).unwrap();
  let v2_parsed : serde_json::Value = serde_json::from_str( &content_v2 ).unwrap();

  assert_eq!(
    v1_parsed.get( "_renewal_at" ), v2_parsed.get( "_renewal_at" ),
    "_renewal_at must be unchanged after re-setting the same timestamp",
  );
  // role field must be preserved
  assert_eq!(
    v2_parsed.get( "role" ).and_then( | v | v.as_str() ),
    Some( "work" ),
    "role field must be preserved after idempotent renewal set",
  );
}

// BV-2: Renewal writes _renewal_at to {name}.json preserving all other fields
#[ test ]
fn renewal_bv2_writes_renewal_at_preserving_other_fields()
{
  let dir = TempDir::new().unwrap();
  let home = dir.path().to_str().unwrap();
  write_credentials( dir.path(), "max", "default", FAR_FUTURE_MS );
  write_account( dir.path(), "alice@acme.com", "max", "default", FAR_FUTURE_MS, false );
  // Pre-populate with role + host but no _renewal_at
  write_account_profile_json( dir.path(), "alice@acme.com", Some( "laptop" ), Some( "work" ) );

  let meta_file = dir.path()
    .join( ".persistent" ).join( "claude" ).join( "credential" )
    .join( "alice@acme.com.json" );

  let before : serde_json::Value = serde_json::from_str(
    &std::fs::read_to_string( &meta_file ).unwrap(),
  ).unwrap();
  assert!(
    before.get( "_renewal_at" ).is_none(),
    "precondition: _renewal_at must be absent before renewal",
  );

  let out = run_cs_with_env(
    &[ ".account.renewal", "name::alice@acme.com", "at::2026-07-01T00:00:00Z" ],
    &[ ( "HOME", home ) ],
  );
  assert_exit( &out, 0 );

  let after : serde_json::Value = serde_json::from_str(
    &std::fs::read_to_string( &meta_file ).unwrap(),
  ).unwrap();
  assert_eq!(
    after.get( "_renewal_at" ).and_then( | v | v.as_str() ),
    Some( "2026-07-01T00:00:00Z" ),
    "_renewal_at must be set after renewal",
  );
  // Other fields must be preserved
  assert_eq!(
    after.get( "role" ).and_then( | v | v.as_str() ), Some( "work" ),
    "role field must be preserved after renewal",
  );
  assert_eq!(
    after.get( "host" ).and_then( | v | v.as_str() ), Some( "laptop" ),
    "host field must be preserved after renewal",
  );
}

// BV-3: Renewal without an operation parameter exits 1
#[ test ]
fn renewal_bv3_without_operation_param_exits_1()
{
  let dir = TempDir::new().unwrap();
  let home = dir.path().to_str().unwrap();
  write_credentials( dir.path(), "max", "default", FAR_FUTURE_MS );
  write_account( dir.path(), "alice@acme.com", "max", "default", FAR_FUTURE_MS, false );

  // No at::, from_now::, or clear:: provided
  let out = run_cs_with_env(
    &[ ".account.renewal", "name::alice@acme.com" ],
    &[ ( "HOME", home ) ],
  );
  assert_exit( &out, 1 );
}

// ── verb::inspect ─────────────────────────────────────────────────────────────

// BV-1: Repeated inspect calls produce no local side effects (lim_it)
#[ test ]
fn inspect_bv1_lim_it_repeated_calls_no_side_effects()
{
  let Some( token ) = live_active_token() else { return };
  if !require_live_api( "inspect_bv1_lim_it" ) { return; }

  let dir = TempDir::new().unwrap();
  let home = dir.path().to_str().unwrap();
  write_account_with_token( dir.path(), "alice@acme.com", &token, true );
  write_credentials( dir.path(), "max", "default", FAR_FUTURE_MS );

  let cred_file = dir.path()
    .join( ".persistent" ).join( "claude" ).join( "credential" )
    .join( "alice@acme.com.credentials.json" );
  let mtime_before = mtime_ms( &cred_file );

  let out1 = run_cs_with_env(
    &[ ".account.inspect", "name::alice@acme.com" ],
    &[ ( "HOME", home ) ],
  );
  assert_exit( &out1, 0 );

  let out2 = run_cs_with_env(
    &[ ".account.inspect", "name::alice@acme.com" ],
    &[ ( "HOME", home ) ],
  );
  assert_exit( &out2, 0 );

  let mtime_after = mtime_ms( &cred_file );
  assert_eq!(
    mtime_before, mtime_after,
    "inspect must not modify stored credential files",
  );
}

// BV-2: Inspect is purely non-mutating — no credential store files modified (lim_it)
#[ test ]
fn inspect_bv2_lim_it_read_is_non_mutating()
{
  let Some( token ) = live_active_token() else { return };
  if !require_live_api( "inspect_bv2_lim_it" ) { return; }

  let dir = TempDir::new().unwrap();
  let home = dir.path().to_str().unwrap();
  write_account_with_token( dir.path(), "alice@acme.com", &token, true );
  write_account_renewal_json( dir.path(), "alice@acme.com", "2026-07-01T00:00:00Z" );
  write_credentials( dir.path(), "max", "default", FAR_FUTURE_MS );

  let meta_file = dir.path()
    .join( ".persistent" ).join( "claude" ).join( "credential" )
    .join( "alice@acme.com.json" );
  let cred_file = dir.path()
    .join( ".persistent" ).join( "claude" ).join( "credential" )
    .join( "alice@acme.com.credentials.json" );
  let mtime_meta_before = mtime_ms( &meta_file );
  let mtime_cred_before = mtime_ms( &cred_file );

  let out = run_cs_with_env(
    &[ ".account.inspect", "name::alice@acme.com" ],
    &[ ( "HOME", home ) ],
  );
  assert_exit( &out, 0 );

  assert_eq!(
    mtime_meta_before, mtime_ms( &meta_file ),
    "inspect must not modify alice@acme.com.json",
  );
  assert_eq!(
    mtime_cred_before, mtime_ms( &cred_file ),
    "inspect must not modify alice@acme.com.credentials.json",
  );
}

// BV-3: Inspect without accessible account credentials exits 2
#[ test ]
fn inspect_bv3_without_credentials_exits_2()
{
  let dir = TempDir::new().unwrap();
  let home = dir.path().to_str().unwrap();
  // No credentials, no stored accounts
  let out = run_cs_with_env(
    &[ ".account.inspect" ],
    &[ ( "HOME", home ) ],
  );
  assert_exit( &out, 2 );
}

// ── verb::assign ──────────────────────────────────────────────────────────────

// BV-1: Re-assigning the same account is idempotent
#[ test ]
fn assign_bv1_reassigning_same_account_idempotent()
{
  let dir = TempDir::new().unwrap();
  let home = dir.path().to_str().unwrap();
  write_credentials( dir.path(), "max", "default", FAR_FUTURE_MS );
  write_account( dir.path(), "alice@acme.com", "max", "default", FAR_FUTURE_MS, true );

  // First assign (marker already set)
  let out1 = run_cs_with_env(
    &[ ".accounts", "assign::1", "name::alice@acme.com" ],
    &[ ( "HOME", home ), ( "USER", "testuser" ), ( "HOSTNAME", "testmachine" ) ],
  );
  assert_exit( &out1, 0 );

  let marker_path = dir.path()
    .join( ".persistent" ).join( "claude" ).join( "credential" )
    .join( "_active_testmachine_testuser" );
  let marker_content = std::fs::read_to_string( &marker_path ).unwrap();

  // Second assign with same account
  let out2 = run_cs_with_env(
    &[ ".accounts", "assign::1", "name::alice@acme.com" ],
    &[ ( "HOME", home ), ( "USER", "testuser" ), ( "HOSTNAME", "testmachine" ) ],
  );
  assert_exit( &out2, 0 );

  let marker_after = std::fs::read_to_string( &marker_path ).unwrap();
  assert_eq!(
    marker_content, marker_after,
    "active marker must be unchanged after idempotent re-assign",
  );
}

// BV-2: Assign writes active marker without touching credential files
#[ test ]
fn assign_bv2_writes_marker_without_touching_credential_files()
{
  let dir = TempDir::new().unwrap();
  let home = dir.path().to_str().unwrap();
  write_credentials( dir.path(), "max", "default", FAR_FUTURE_MS );
  write_account( dir.path(), "alice@acme.com", "max", "default", FAR_FUTURE_MS, false );

  let cred_file = dir.path()
    .join( ".persistent" ).join( "claude" ).join( "credential" )
    .join( "alice@acme.com.credentials.json" );
  let live_creds = dir.path().join( ".claude" ).join( ".credentials.json" );
  let mtime_cred_before = mtime_ms( &cred_file );
  let mtime_live_before = mtime_ms( &live_creds );

  let out = run_cs_with_env(
    &[ ".accounts", "assign::1", "name::alice@acme.com" ],
    &[ ( "HOME", home ), ( "USER", "testuser" ), ( "HOSTNAME", "testmachine" ) ],
  );
  assert_exit( &out, 0 );

  // Marker must now exist
  let marker_path = dir.path()
    .join( ".persistent" ).join( "claude" ).join( "credential" )
    .join( "_active_testmachine_testuser" );
  assert!( marker_path.exists(), "_active_testmachine_testuser marker must be created" );
  assert_eq!(
    std::fs::read_to_string( &marker_path ).unwrap().trim(),
    "alice@acme.com",
  );

  // Credential files must remain unmodified
  assert_eq!(
    mtime_cred_before, mtime_ms( &cred_file ),
    "alice@acme.com.credentials.json must not be modified by assign",
  );
  assert_eq!(
    mtime_live_before, mtime_ms( &live_creds ),
    "~/.claude/.credentials.json must not be modified by assign",
  );
}

// BV-3: Assign on non-existent account exits 2
#[ test ]
fn assign_bv3_nonexistent_account_exits_2()
{
  let dir = TempDir::new().unwrap();
  let home = dir.path().to_str().unwrap();
  write_credentials( dir.path(), "max", "default", FAR_FUTURE_MS );

  let out = run_cs_with_env(
    &[ ".accounts", "assign::1", "name::nobody@acme.com" ],
    &[ ( "HOME", home ), ( "USER", "testuser" ), ( "HOSTNAME", "testmachine" ) ],
  );
  assert_exit( &out, 2 );
}

// ── verb::status ──────────────────────────────────────────────────────────────

// BV-1: .token.status called twice returns same classification
#[ test ]
fn status_bv1_token_status_twice_same_classification()
{
  let dir = TempDir::new().unwrap();
  let home = dir.path().to_str().unwrap();
  write_credentials( dir.path(), "max", "default", FAR_FUTURE_MS );

  let out1 = run_cs_with_env( &[ ".token.status" ], &[ ( "HOME", home ) ] );
  assert_exit( &out1, 0 );

  let out2 = run_cs_with_env( &[ ".token.status" ], &[ ( "HOME", home ) ] );
  assert_exit( &out2, 0 );

  // First line of each output must match (classification line)
  let first1 = stdout( &out1 ).lines().next().unwrap_or( "" ).to_string();
  let first2 = stdout( &out2 ).lines().next().unwrap_or( "" ).to_string();
  assert_eq!( first1, first2, "classification must be identical across two calls" );
}

// BV-2: .token.status read is purely non-mutating
#[ test ]
fn status_bv2_token_status_non_mutating()
{
  let dir = TempDir::new().unwrap();
  let home = dir.path().to_str().unwrap();
  write_credentials( dir.path(), "max", "default", FAR_FUTURE_MS );

  let creds_path = dir.path().join( ".claude" ).join( ".credentials.json" );
  let mtime_before = mtime_ms( &creds_path );

  let out = run_cs_with_env( &[ ".token.status" ], &[ ( "HOME", home ) ] );
  assert_exit( &out, 0 );

  assert_eq!(
    mtime_before, mtime_ms( &creds_path ),
    ".token.status must not modify ~/.claude/.credentials.json",
  );
}

// BV-3: .token.status with absent credentials file exits 2
#[ test ]
fn status_bv3_token_status_absent_creds_exits_2()
{
  let dir = TempDir::new().unwrap();
  let home = dir.path().to_str().unwrap();
  // No credentials file written
  let out = run_cs_with_env( &[ ".token.status" ], &[ ( "HOME", home ) ] );
  assert_exit( &out, 2 );
}

// BV-4: .credentials.status called twice returns same output
#[ test ]
fn status_bv4_credentials_status_twice_same_output()
{
  let dir = TempDir::new().unwrap();
  let home = dir.path().to_str().unwrap();
  write_credentials( dir.path(), "max", "default", FAR_FUTURE_MS );
  write_account( dir.path(), "alice@acme.com", "max", "default", FAR_FUTURE_MS, true );

  let out1 = run_cs_with_env( &[ ".credentials.status" ], &[ ( "HOME", home ) ] );
  assert_exit( &out1, 0 );

  let out2 = run_cs_with_env( &[ ".credentials.status" ], &[ ( "HOME", home ) ] );
  assert_exit( &out2, 0 );

  assert_eq!(
    stdout( &out1 ), stdout( &out2 ),
    ".credentials.status must produce identical output on repeated calls",
  );
}