claude_profile 1.2.0

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
// Path-referenced test module for api.rs — compiled as `mod tests` via `#[path]`.
// Lives in src/usage/ (not tests/) to access pub(crate) pre_switch_touch_ctx,
// apply_model_override, apply_post_switch_touch, and TouchCtx
// without widening their visibility. See src/usage/readme.md § Inline Test Exception.

use super::{ pre_switch_touch_ctx, apply_model_override, apply_post_switch_touch, PreSwitchOutcome, TouchCtx };
use tempfile::TempDir;

/// Structural test: `pre_switch_touch_ctx` with an invalid credential file (no accessToken).
///
/// # Root Cause (BUG-210)
/// `pre_switch_touch_ctx()` returned `None` in the already-active branch without emitting
/// `model:` + `effort:` trace lines. Model/effort resolution lived in `apply_post_switch_touch`
/// only, which is never called on the skip path.
///
/// # Why Not Caught
/// No test called `pre_switch_touch_ctx` directly with a failing credential read; the only
/// coverage was via the live `aw29` integration test (`lim_it`, excluded from CI).
///
/// # Fix Applied
/// Extended `pre_switch_touch_ctx` to accept `imodel_str` and `effort_str` parameters;
/// added model/effort resolution and trace emission in the already-active branch.
///
/// # Prevention
/// This test acts as a compile-time guard: if the function reverts to 3 params, this
/// call (with 5 args) causes a compile error. Also verifies that the fetch-failed path does
/// NOT emit `model:` lines — the model/effort emission belongs only to quota-fetch-OK paths.
///
/// # Pitfall
/// The fetch-failed path must NOT emit `model:` even after the BUG-210 fix — model/effort
/// resolution requires quota data, which is unavailable when fetch fails.
#[ doc = "bug_reproducer(BUG-210)" ]
#[ test ]
fn test_pre_switch_touch_ctx_model_effort_absent_on_fetch_failure()
{
  let store = TempDir::new().unwrap();

  // Write a credential file with no accessToken — quota fetch will fail.
  std::fs::write(
    store.path().join( "noaccess@example.com.credentials.json" ),
    r#"{"subscriptionType":"pro"}"#,
  ).unwrap();

  // 5-arg signature — compile error before BUG-210 fix extends the function.
  let result = pre_switch_touch_ctx(
    "noaccess@example.com",
    store.path(),
    true,
    "auto",
    "auto",
  );

  // Fetch-failed path must return Unavailable (credential read OK but accessToken absent).
  assert!(
    matches!( result, PreSwitchOutcome::Unavailable ),
    "fetch-failed path must return Unavailable, got {result:?}",
  );
}

/// `mre_bug238` — `apply_model_override()` writes opus when 7d(Son) consumed > 80%.
///
/// # Root Cause
/// `pre_switch_touch_ctx()` originally returned `PreSwitchOutcome::AlreadyActive` for
/// accounts with an active 5h window, and `apply_post_switch_touch()` skipped
/// `apply_model_override()` in that branch — the model override never fired for
/// already-active accounts.
///
/// # Why Not Caught
/// No unit test for `apply_model_override()` existed. Full CLI path requires a live OAuth
/// token to fetch quota, which is impractical in CI.
///
/// # Fix Applied
/// BUG-238 fix: wired `apply_model_override` into the `AlreadyActive` branch.
/// BUG-285 follow-up: the `AlreadyActive` variant was subsequently removed entirely —
///   `pre_switch_touch_ctx` now always returns `NeedTouch` when the quota fetch succeeds
///   (the subprocess is idempotent). `apply_model_override` fires unconditionally for all
///   fetch-succeeded outcomes.
///
/// # Prevention
/// Test `apply_model_override` directly to stay independent of CLI plumbing. Any future
/// `PreSwitchOutcome` variant that carries `OauthUsageData` must wire in `apply_model_override`.
///
/// # Pitfall
/// `apply_model_override` only fires when `sonnet_left < 15.0`. Test input must push
/// `utilization` to > 85.0 (leaving < 15%). Also: the `.claude/` parent dir must exist
/// before the write or `override_session_model_to_opus` silently no-ops.
#[ doc = "bug_reproducer(BUG-238)" ]
#[ test ]
fn mre_bug238_model_override_fires_for_active_account()
{
  use claude_quota::{ OauthUsageData, PeriodUsage };
  let dir   = TempDir::new().unwrap();
  let paths = crate::ClaudePaths::with_home( dir.path() );
  // Create ~/.claude/ so override_session_model_to_opus can write settings.json.
  std::fs::create_dir_all( paths.base() ).unwrap();

  let quota = OauthUsageData
  {
    five_hour        : None,
    seven_day        : None,
    seven_day_sonnet : Some( PeriodUsage { utilization : 90.0, resets_at : None } ),
  };
  apply_model_override( &quota, &paths, false, "account.use", "test-account" );

  let content = std::fs::read_to_string( paths.settings_file() ).unwrap();
  assert!(
    content.contains( "\"opus\"" ) && !content.contains( "claude-opus-4-6" ),
    "apply_model_override must write opus shorthand to settings.json when 7d(Son) is 90% consumed (10% left), got: {content}",
  );
}

/// `mre_bug286` — full model ID `"claude-opus-4-6"` in settings.json must be
/// normalized to shorthand `"opus"` by `apply_model_override`.
///
/// # Root Cause
/// BUG-257 fix added `contains("sonnet")` for sonnet alias coverage, but did not
/// add the analogous full-ID opus → shorthand normalization path. When settings.json
/// contained `"claude-opus-4-6"` (written by a prior `set_session_model`), the gate
/// `contains("sonnet") || is_empty()` was false — override never fired.
///
/// # Why Not Caught
/// No test wrote a full-ID opus value to settings.json before calling
/// `apply_model_override`. All existing tests started from empty or shorthand values.
///
/// # Fix Applied
/// Added `current == "claude-opus-4-6"` arm to the gate condition in
/// `override_session_model_to_opus`.
///
/// # Prevention
/// This test pre-writes the full opus ID and asserts normalization to shorthand.
///
/// # Pitfall
/// Any path that writes model to settings.json must write Claude Code shorthand
/// ("opus"/"sonnet"), never full IDs ("claude-opus-4-6").
#[ doc = "bug_reproducer(BUG-286)" ]
#[ test ]
fn mre_bug286_full_opus_id_normalized_to_shorthand()
{
  use claude_quota::{ OauthUsageData, PeriodUsage };
  let dir   = TempDir::new().unwrap();
  let paths = crate::ClaudePaths::with_home( dir.path() );
  std::fs::create_dir_all( paths.base() ).unwrap();
  // Pre-write full opus ID — as stored in {name}.json snapshots from older convention.
  std::fs::write( paths.settings_file(), r#"{"model":"claude-opus-4-6"}"# ).unwrap();
  let quota = OauthUsageData
  {
    five_hour        : None,
    seven_day        : None,
    seven_day_sonnet : Some( PeriodUsage { utilization : 90.0, resets_at : None } ),
  };
  apply_model_override( &quota, &paths, false, "account.use", "test-account" );
  let content = std::fs::read_to_string( paths.settings_file() ).unwrap();
  assert!(
    content.contains( "\"opus\"" ) && !content.contains( "claude-opus-4-6" ),
    "BUG-286: full-ID opus must be normalized to shorthand 'opus', got: {content}",
  );
}

/// `mre_bug300` — `apply_model_override()` fires unconditionally when `seven_day_sonnet = None`.
///
/// # Root Cause
/// `apply_model_override()` at `src/usage/api.rs:267` uses
/// `quota.seven_day_sonnet.as_ref().map_or(0.0, |p| 100.0 - p.utilization)`.
/// When `seven_day_sonnet = None`, `map_or` returns `0.0`. `0.0 < 20.0` is always true,
/// so the Opus override fires unconditionally for every account without a Sonnet tier.
///
/// # Why Not Caught
/// All existing tests supply `seven_day_sonnet: Some(PeriodUsage { utilization: 90.0, ... })`.
/// No test used `None` as input. The buggy `map_or(0.0, ...)` path was invisible in CI.
///
/// # Fix Applied
/// Replace `map_or(0.0, ...)` with `if let Some( ref sonnet ) = quota.seven_day_sonnet { ... }`.
/// When `None`, the entire override block is skipped.
/// `None` = "tier absent/unknown", not "quota fully exhausted".
///
/// # Prevention
/// This test catches any regression to `map_or(0.0, ...)` or other "treat None as 0%"
/// patterns. Observable contract: `settings.json` must NOT be created when `seven_day_sonnet`
/// is absent, regardless of any threshold comparison.
///
/// # Pitfall
/// `map_or(0.0, ...)` is correct for display (show 0% when tier absent) but WRONG for
/// conditional gates. `None` = "tier absent/unknown". Always use `if let Some(...)` for
/// quota-exhaustion logic — never treat absence as exhaustion.
#[ doc = "bug_reproducer(BUG-300)" ]
#[ test ]
fn mre_bug300_model_override_absent_sonnet_no_override()
{
  use claude_quota::OauthUsageData;
  let dir   = TempDir::new().unwrap();
  let paths = crate::ClaudePaths::with_home( dir.path() );
  std::fs::create_dir_all( paths.base() ).unwrap();
  // seven_day_sonnet = None: Sonnet tier absent — override must NOT fire.
  let quota = OauthUsageData { five_hour : None, seven_day : None, seven_day_sonnet : None };
  apply_model_override( &quota, &paths, false, "usage", "test-account" );
  assert!(
    !paths.settings_file().exists(),
    "BUG-300: settings.json must NOT be written when seven_day_sonnet is None \
     (absent tier is unknown, not exhausted)",
  );
}

// ── BUG-244 tests: label param + usage_routine wiring ─────────────────────

#[ test ]
fn t01_model_override_fires_when_sonnet_below_threshold()
{
  use claude_quota::{ OauthUsageData, PeriodUsage };
  let dir   = TempDir::new().unwrap();
  let paths = crate::ClaudePaths::with_home( dir.path() );
  std::fs::create_dir_all( paths.base() ).unwrap();
  let quota = OauthUsageData
  {
    five_hour        : None,
    seven_day        : None,
    seven_day_sonnet : Some( PeriodUsage { utilization : 90.0, resets_at : None } ),
  };
  apply_model_override( &quota, &paths, false, "usage", "test-account" );
  let content = std::fs::read_to_string( paths.settings_file() ).unwrap();
  assert!(
    content.contains( "\"opus\"" ) && !content.contains( "claude-opus-4-6" ),
    "must write opus shorthand when 7d(Son) utilization=90% (10% left), got: {content}",
  );
}

#[ test ]
fn t02_model_override_skips_when_sonnet_above_threshold()
{
  use claude_quota::{ OauthUsageData, PeriodUsage };
  let dir   = TempDir::new().unwrap();
  let paths = crate::ClaudePaths::with_home( dir.path() );
  std::fs::create_dir_all( paths.base() ).unwrap();
  let quota = OauthUsageData
  {
    five_hour        : None,
    seven_day        : None,
    seven_day_sonnet : Some( PeriodUsage { utilization : 70.0, resets_at : None } ),
  };
  apply_model_override( &quota, &paths, false, "usage", "test-account" );
  assert!(
    !paths.settings_file().exists(),
    "must NOT write settings.json when 7d(Son) utilization=70% (30% left)",
  );
}

#[ test ]
fn t03_model_override_skips_when_already_opus()
{
  use claude_quota::{ OauthUsageData, PeriodUsage };
  let dir   = TempDir::new().unwrap();
  let paths = crate::ClaudePaths::with_home( dir.path() );
  std::fs::create_dir_all( paths.base() ).unwrap();
  // Pre-write settings.json with opus shorthand already set (production convention).
  std::fs::write( paths.settings_file(), r#"{"model":"opus"}"# ).unwrap();
  let quota = OauthUsageData
  {
    five_hour        : None,
    seven_day        : None,
    seven_day_sonnet : Some( PeriodUsage { utilization : 90.0, resets_at : None } ),
  };
  apply_model_override( &quota, &paths, false, "usage", "test-account" );
  let content = std::fs::read_to_string( paths.settings_file() ).unwrap();
  assert!(
    content.contains( "\"opus\"" ),
    "settings.json must still contain opus after call when already opus, got: {content}",
  );
  assert!(
    !content.contains( "sonnet" ),
    "must not downgrade to sonnet, got: {content}",
  );
}

#[ test ]
fn t04_model_override_skips_on_error_result()
{
  // Guard test: usage_routine must guard apply_model_override with result.is_ok(),
  // since OauthUsageData is unavailable for Err accounts.
  let src      = include_str!( "api.rs" );
  let fn_start = src.find( "pub fn usage_routine" ).expect( "usage_routine not found" );
  let call_rel = src[ fn_start.. ]
    .find( "apply_model_override(" )
    .expect( "BUG-244: apply_model_override must be called in usage_routine" );
  // before_call: from fn_start to call site — ASCII boundaries, no multibyte risk.
  let before_call = &src[ fn_start .. fn_start + call_rel ];
  assert!(
    before_call.contains( "is_ok()" ) || before_call.contains( "Ok( ref " ),
    "apply_model_override call in usage_routine must be guarded by result.is_ok()",
  );
}

#[ test ]
fn t05_apply_model_override_absent_from_usage_routine_before_fix()
{
  let src      = include_str!( "api.rs" );
  let fn_start = src.find( "pub fn usage_routine" ).expect( "usage_routine not found" );
  let body_end = {
    let after = &src[ fn_start + 1.. ];
    let a     = after.find( "\npub fn " ).unwrap_or( after.len() );
    let b     = after.find( "\n#[ cfg( t" ).unwrap_or( after.len() );
    let c     = after.find( "\n#[cfg(t" ).unwrap_or( after.len() );
    fn_start + 1 + a.min( b ).min( c )
  };
  let body       = &src[ fn_start..body_end ];
  let call_count = body.matches( "apply_model_override(" ).count();
  // BUG-244 fix: one call for the current-account usage path (guarded by is_current).
  // Feature 062 (AC-05): one call for the rotation-winner path (after switch_account).
  assert_eq!(
    call_count, 2,
    "apply_model_override must be called exactly twice in usage_routine body: \
    once for current-account (BUG-244) and once for rotation-winner (Feature 062 AC-05)",
  );
}

#[ test ]
fn t06_model_override_skips_for_non_current_account()
{
  // Guard test: usage_routine must only call apply_model_override for is_current accounts.
  let src      = include_str!( "api.rs" );
  let fn_start = src.find( "pub fn usage_routine" ).expect( "usage_routine not found" );
  let call_rel = src[ fn_start.. ]
    .find( "apply_model_override(" )
    .expect( "BUG-244: apply_model_override must be called in usage_routine" );
  // before_call: from fn_start to call site — ASCII boundaries, no multibyte risk.
  let before_call = &src[ fn_start .. fn_start + call_rel ];
  assert!(
    before_call.contains( "is_current" ),
    "apply_model_override call in usage_routine must be guarded by is_current check",
  );
}

#[ test ]
fn t07_model_override_skips_at_and_above_15pct_boundary()
{
  use claude_quota::{ OauthUsageData, PeriodUsage };
  let dir   = TempDir::new().unwrap();
  let paths = crate::ClaudePaths::with_home( dir.path() );
  std::fs::create_dir_all( paths.base() ).unwrap();
  // utilization=85.0 → sonnet_left = 100.0 - 85.0 = 15.0; 15.0 < 15.0 == false.
  let quota = OauthUsageData
  {
    five_hour        : None,
    seven_day        : None,
    seven_day_sonnet : Some( PeriodUsage { utilization : 85.0, resets_at : None } ),
  };
  apply_model_override( &quota, &paths, false, "usage", "test-account" );
  assert!(
    !paths.settings_file().exists(),
    "must NOT write at exact 15% boundary (utilization=85.0)",
  );
}

#[ test ]
fn t08_model_override_trace_label_is_usage()
{
  use claude_quota::{ OauthUsageData, PeriodUsage };
  use std::io::Read;
  let dir   = TempDir::new().unwrap();
  let paths = crate::ClaudePaths::with_home( dir.path() );
  std::fs::create_dir_all( paths.base() ).unwrap();
  let quota = OauthUsageData
  {
    five_hour        : None,
    seven_day        : None,
    seven_day_sonnet : Some( PeriodUsage { utilization : 90.0, resets_at : None } ),
  };
  let _stderr_guard = crate::usage::test_support::STDERR_LOCK.lock().unwrap_or_else( std::sync::PoisonError::into_inner );
  let mut buf = gag::BufferRedirect::stderr().unwrap();
  apply_model_override( &quota, &paths, true, "usage", "test-account" );
  let mut output = String::new();
  buf.read_to_string( &mut output ).unwrap();
  assert!(
    output.contains( "[trace] usage" ),
    "trace output must contain '[trace] usage' when label='usage', got: {output}",
  );
  assert!(
    !output.contains( "[trace] account.use" ),
    "trace output must NOT contain '[trace] account.use' when label='usage', got: {output}",
  );
}

/// # MRE: BUG-245 + BUG-246 — `only_active` retain fires after HTTP fetch
///
/// ## Root Cause
/// `usage_routine()` placed `accounts.retain( |aq| aq.is_active )` at ~line 490,
/// after `fetch_all_quota` (~line 430). With N saved accounts and `only_active::1`,
/// all N accounts were HTTP-fetched before the row filter reduced output to 1 row.
///
/// ## Why Not Caught
/// No structural test enforced ordering of the pre-filter vs. the HTTP fetch call.
/// Output was correct (1 row shown) but N unnecessary HTTP round trips occurred.
///
/// ## Fix Applied
/// Pre-filter via `account::list()` (filesystem marker, no HTTP) in `usage_routine()`
/// before the HTTP fetch. When `only_active::1`, only the active account is passed to
/// `fetch_quota_for_list()` — exactly 1 HTTP call per invocation. BUG-246 (touch loop)
/// is fixed simultaneously: `apply_touch` iterates the pre-filtered 1-entry slice.
///
/// ## Prevention
/// This structural test: assert that `retain( |aq| aq.is_active )` appears in
/// `usage_routine` source BEFORE `fetch_quota_for_list(` — maintains the ordering invariant.
///
/// ## Pitfall
/// The pre-filter uses `Vec<Account>` (from `account::list()`), not `Vec<AccountQuota>`.
/// Both types have `is_active: bool` — the retain closure `|aq| aq.is_active` works on either.
#[ doc = "bug_reproducer(BUG-245)" ]
#[ doc = "bug_reproducer(BUG-246)" ]
#[ test ]
fn mre_bug245_only_active_retain_fires_before_http_fetch()
{
  let src      = include_str!( "api.rs" );
  let fn_start = src.find( "pub fn usage_routine" ).expect( "usage_routine not found" );
  let body_end = {
    let after = &src[ fn_start + 1.. ];
    let a     = after.find( "\npub fn " ).unwrap_or( after.len() );
    let b     = after.find( "\n#[ cfg( t" ).unwrap_or( after.len() );
    let c     = after.find( "\n#[cfg(t" ).unwrap_or( after.len() );
    fn_start + 1 + a.min( b ).min( c )
  };
  let body       = &src[ fn_start..body_end ];
  let retain_pos = body.find( "retain( |aq| aq.is_active )" )
    .expect( "BUG-245: retain( |aq| aq.is_active ) must exist in usage_routine body" );
  let fetch_pos  = body.find( "fetch_quota_for_list(" )
    .expect( "BUG-245: fetch_quota_for_list call must exist in usage_routine body" );
  assert!(
    retain_pos < fetch_pos,
    "BUG-245/246: retain must fire BEFORE fetch_quota_for_list — \
    retain at ~{retain_pos}, fetch at ~{fetch_pos}",
  );
}

/// # MRE: BUG-244 — `usage_routine` never called `apply_model_override`
///
/// ## Root Cause
/// `usage_routine()` in `src/usage/api.rs` had no call to `apply_model_override()`.
/// The function existed and worked (called from `.account.use` path) but was never
/// invoked from the `.usage` command path.
///
/// ## Why Not Caught
/// No test exercised the full `usage_routine()` → `apply_model_override()` wiring.
/// Unit tests for `apply_model_override` passed trivially (calling it directly).
///
/// ## Fix Applied
/// Added `apply_model_override( data, claude_paths, params.trace, "usage", &current.name )`
/// in `usage_routine()` after the touch loop, before the row-filter pipeline,
/// guarded by `aq.is_current && aq.result.is_ok()`.
/// Also added `label: &str` parameter to `apply_model_override` (was hardcoded "account.use").
///
/// ## Prevention
/// T05 structural test: grep of `usage_routine` body must contain exactly one call.
///
/// ## Pitfall
/// Insert the call BEFORE the row-filter pipeline (`only_next`/`only_active`/etc.) — those
/// filters can remove the `is_current` entry from the slice, causing a silent no-op.
#[ doc = "bug_reproducer(BUG-244)" ]
#[ test ]
fn mre_bug244_usage_routine_never_calls_apply_model_override()
{
  let src      = include_str!( "api.rs" );
  let fn_start = src.find( "pub fn usage_routine" ).expect( "usage_routine not found" );
  let body_end = {
    let after = &src[ fn_start + 1.. ];
    let a     = after.find( "\npub fn " ).unwrap_or( after.len() );
    let b     = after.find( "\n#[ cfg( t" ).unwrap_or( after.len() );
    let c     = after.find( "\n#[cfg(t" ).unwrap_or( after.len() );
    fn_start + 1 + a.min( b ).min( c )
  };
  let body = &src[ fn_start..body_end ];
  assert!(
    body.contains( "apply_model_override(" ),
    "BUG-244: apply_model_override must be called from usage_routine — was absent before fix",
  );
}

/// # MRE: BUG-285 — idle check used server-side `resets_at` as local subprocess oracle
///
/// ## Root Cause
/// `pre_switch_touch_ctx()` computed `is_idle` from `quota.five_hour.resets_at.is_none()`.
/// `resets_at` is set server-side by Anthropic's API for any session on any machine —
/// it is NOT a local subprocess identity indicator. An account with `resets_at=Some`
/// (set by a session on another machine) returned `AlreadyActive` and skipped the
/// subprocess touch, even though no local subprocess was running.
///
/// ## Why Not Caught
/// The `is_idle` check appeared logically sound in single-machine setups: if the 5h window
/// is counting down, a subprocess must have started it. This reasoning fails for accounts
/// used across multiple machines where any machine can advance the server-side state.
///
/// ## Fix Applied
/// Removed `is_idle` check entirely from `pre_switch_touch_ctx`. Function now always
/// returns `NeedTouch` when quota is successfully fetched. `AlreadyActive` variant
/// removed from `PreSwitchOutcome`. `trace_already_active()` deleted as dead code.
///
/// ## Prevention
/// This structural test asserts that `let is_idle` assignment and `AlreadyActive` return
/// no longer appear in `pre_switch_touch_ctx` — any reintroduction of the oracle pattern
/// fails the test.
///
/// ## Pitfall
/// `resets_at` presence does NOT mean a local subprocess is active. Server-side state
/// reflects global account state; local subprocess identity requires local process
/// introspection, not quota API responses.
#[ doc = "bug_reproducer(BUG-285)" ]
#[ test ]
fn mre_bug285_idle_check_uses_resets_at_as_wrong_oracle()
{
  let src      = include_str!( "api.rs" );
  let fn_start = src
    .find( "pub( crate ) fn pre_switch_touch_ctx(" )
    .expect( "pre_switch_touch_ctx not found in api.rs" );
  let fn_end   = src[ fn_start + 1.. ]
    .find( "\npub( crate ) fn " )
    .map_or( src.len(), |rel| fn_start + 1 + rel );
  let fn_body  = &src[ fn_start..fn_end ];

  assert!(
    !fn_body.contains( "let is_idle" ),
    "BUG-285 regression: `let is_idle` variable must not exist in pre_switch_touch_ctx body\n\
    resets_at is server-side state and cannot proxy local subprocess identity",
  );
  assert!(
    !fn_body.contains( "AlreadyActive" ),
    "BUG-285 regression: AlreadyActive must not be returned from pre_switch_touch_ctx",
  );
}

/// `mre_bug288` — `apply_post_switch_touch` re-fetch is non-aborting when the credentials
/// file has no `accessToken`; pre-re-fetch cache writes succeed regardless.
///
/// # Root Cause
/// `apply_post_switch_touch` discarded the `run_isolated` result with `let _ = ...` and
/// performed no post-subprocess quota re-fetch. A subsequent `.usage touch` call then saw
/// stale `resets_at = None` and spawned a redundant second subprocess (double-subprocess race).
///
/// # Why Not Caught
/// No unit test exercised `apply_post_switch_touch` directly. The only coverage was via
/// `lim_it` CLI integration tests requiring live OAuth credentials (`aw27`, `aw28`, `aw29`).
///
/// # Fix Applied
/// Added post-subprocess quota re-fetch block (AC-21) to `apply_post_switch_touch`, mirroring
/// `apply_touch`'s AC-03 pattern. Reads credentials fresh from disk (not from
/// `ctx.credentials_json`) to capture any post-subprocess token rotation. On `Ok(new_data)`:
/// calls `write_quota_cache(paths.base(), name, ...)` to persist the updated quota. On
/// failure: silently skips — non-aborting per AC-21.
///
/// # Prevention
/// This test verifies the non-aborting invariant: when `accessToken` is absent from the
/// credentials file, the re-fetch is silently skipped and the function returns normally.
/// Also verifies that `last_touch_at` and `touch_idle` (written before the re-fetch block)
/// are committed to disk even when the re-fetch is skipped.
///
/// # Pitfall
/// `apply_post_switch_touch` is `pub(crate)` — only testable inline in `src/usage/api.rs`.
/// The re-fetch block reads credentials from `paths.base()/{name}.credentials.json` (fresh
/// disk read), NOT from `ctx.credentials_json` — tests must write the credential file at
/// that path, not just supply a non-empty string in the `TouchCtx`.
#[ doc = "bug_reproducer(BUG-288)" ]
#[ test ]
fn mre_bug288_post_switch_touch_refetch_updates_quota()
{
  use claude_quota::OauthUsageData;

  // ── Success path (structural): write_quota_cache is called when re-fetch succeeds ──
  // Verifies Fix(BUG-288) is present: apply_post_switch_touch must call write_quota_cache
  // on a successful fetch_oauth_usage result so subsequent .usage sees the updated resets_at.
  {
    let src      = include_str!( "api.rs" );
    let fn_start = src
      .find( "pub( crate ) fn apply_post_switch_touch(" )
      .expect( "apply_post_switch_touch not found in api.rs" );
    let fn_end   = src[ fn_start + 1.. ]
      .find( "\n// ── Main routine" )
      .map( |rel| fn_start + 1 + rel )
      .expect( "anchor '// ── Main routine' must follow apply_post_switch_touch — update structural test if section was renamed" );
    let fn_body  = &src[ fn_start..fn_end ];
    assert!(
      fn_body.contains( "fetch_oauth_usage" ),
      "BUG-288: apply_post_switch_touch must call fetch_oauth_usage for AC-21 re-fetch",
    );
    assert!(
      fn_body.contains( "write_quota_cache" ),
      "BUG-288: apply_post_switch_touch must call write_quota_cache on successful re-fetch \
      so subsequent .usage sees the updated resets_at (no double-subprocess race)",
    );
  }

  // ── Failure path (runtime): no accessToken → re-fetch silently skipped ──────────────
  let dir   = TempDir::new().unwrap();
  let paths = crate::ClaudePaths::with_home( dir.path() );
  std::fs::create_dir_all( paths.base() ).unwrap();
  let name = "test@example.com";

  // Failure path: credentials file has no `accessToken` field.
  // `parse_string_field` returns None → re-fetch skipped → non-aborting.
  std::fs::write(
    paths.base().join( format!( "{name}.credentials.json" ) ),
    r#"{"subscriptionType":"pro","expiresAt":9999999999999}"#,
  ).unwrap();

  let ctx = TouchCtx::for_test(
    r#"{"subscriptionType":"pro"}"#.to_string(),
    OauthUsageData { five_hour : None, seven_day : None, seven_day_sonnet : None },
  );

  // Must not panic: run_isolated fails silently (let _ = ...); re-fetch skipped.
  apply_post_switch_touch( name, ctx, "auto", "auto", false, &paths );

  // Observable 1: pre-re-fetch cache writes (last_touch_at, touch_idle) must succeed
  // even when the re-fetch block is skipped — they are written unconditionally before it.
  let cache_path = paths.base().join( format!( "{name}.json" ) );
  let cache = std::fs::read_to_string( &cache_path )
    .expect( "BUG-288: cache file must exist after apply_post_switch_touch" );
  assert!(
    cache.contains( "last_touch_at" ),
    "BUG-288: last_touch_at must be written to cache even when re-fetch is skipped, got: {cache}",
  );
  assert!(
    cache.contains( "touch_idle" ),
    "BUG-288: touch_idle must be written to cache even when re-fetch is skipped, got: {cache}",
  );

  // Observable 2: quota re-fetch must have been skipped — `resets_at` must not appear.
  // If the re-fetch had fired with a live token and written new quota data, this would fail,
  // making it both an absence-check for the failure path and an implicit sentinel that the
  // test fixture did not accidentally provide a live credential.
  assert!(
    !cache.contains( "resets_at" ),
    "BUG-288: resets_at must not be written when accessToken is absent (re-fetch skipped), got: {cache}",
  );
}

/// Corner case: credentials file absent → outer `read_to_string` guard fails →
/// entire re-fetch block skipped; `last_touch_at` and `touch_idle` still written; no panic.
///
/// # Root Cause
/// The AC-21 re-fetch block uses three nested `if let` guards:
///   1. `if let Ok(fresh_json) = read_to_string(&cred_path)` — outer: file I/O
///   2. `if let Some(token) = parse_string_field(...)` — inner: JSON field
///   3. `if let Ok(new_data) = fetch_oauth_usage(...)` — innermost: HTTP
///
/// `mre_bug288_post_switch_touch_refetch_updates_quota` covers guard 2 (file present,
/// no `accessToken`). This test covers guard 1 (file absent entirely).
///
/// # Why Not Caught
/// The file-absent path was not covered because the existing MRE test always writes a
/// credential file (albeit without `accessToken`). The outer guard is a distinct code
/// path even though observables are identical to the inner-guard failure path.
///
/// # Fix Applied
/// No fix required — `if let Ok` on `read_to_string` already handles this correctly.
/// This test verifies the non-aborting invariant for the outer guard specifically.
///
/// # Prevention
/// Nested `if let` re-fetch blocks must have unit tests per guard layer: outer I/O
/// guard and inner parse guard are independent failure modes requiring separate coverage.
///
/// # Pitfall
/// File-absent and file-present-no-token produce identical observables (`last_touch_at`
/// written, no `resets_at`) but exercise different branches. Both must be tested to
/// confirm the non-aborting invariant holds at each layer of the nested guard chain.
#[ test ]
fn it_apply_post_switch_touch_cred_file_absent_skips_refetch()
{
  use claude_quota::OauthUsageData;

  let dir   = TempDir::new().unwrap();
  let paths = crate::ClaudePaths::with_home( dir.path() );
  std::fs::create_dir_all( paths.base() ).unwrap();
  let name = "absent@example.com";

  // No credentials file written — `read_to_string` returns Err.
  // Outer `if let Ok` guard fires → entire re-fetch block bypassed.

  let ctx = TouchCtx::for_test(
    r#"{"subscriptionType":"pro"}"#.to_string(),
    OauthUsageData { five_hour : None, seven_day : None, seven_day_sonnet : None },
  );

  // Must not panic: run_isolated discards result; outer re-fetch guard skips silently.
  apply_post_switch_touch( name, ctx, "auto", "auto", false, &paths );

  // Observable 1: last_touch_at and touch_idle written unconditionally (before re-fetch block).
  let cache_path = paths.base().join( format!( "{name}.json" ) );
  let cache = std::fs::read_to_string( &cache_path )
    .expect( "cache file must exist even when credential file is absent" );
  assert!(
    cache.contains( "last_touch_at" ),
    "last_touch_at must be written even when credential file is absent; got: {cache}",
  );
  assert!(
    cache.contains( "touch_idle" ),
    "touch_idle must be written even when credential file is absent; got: {cache}",
  );

  // Observable 2: re-fetch outer guard fired → no resets_at in cache.
  assert!(
    !cache.contains( "resets_at" ),
    "resets_at must not appear when credential file is absent (outer guard bypassed); got: {cache}",
  );
}

/// `ft11` — Rotation dispatcher calls `apply_model_override` for the winner (AC-05, Feature 062).
///
/// # Root Cause
/// Before Feature 062, the rotation dispatch block in `usage_routine` called `switch_account` and
/// `apply_touch` but never `apply_model_override` for the winner — the winner's session model
/// remained at whatever was set by the previous current account.
///
/// # Why Not Caught
/// No structural test asserted the call site exists inside the rotation block.
///
/// # Fix Applied
/// Added `apply_model_override( winner_data, &claude_paths, ... )` inside the rotation dispatch
/// block, guarded by `if let Ok( ref winner_data ) = accounts[ winner_idx ].result`.
///
/// # Prevention
/// Structural grep: rotation dispatch block must contain `apply_model_override(`.
///
/// # Pitfall
/// Must insert AFTER `switch_account` succeeds — before that point, `claude_paths` is
/// conditionally set and `winner_idx` may not be resolved.
#[ test ]
fn ft11_rotation_dispatcher_calls_apply_model_override_for_winner()
{
  let src      = include_str!( "api.rs" );
  // Locate rotation dispatch block: starts at "Rotation dispatch" comment.
  let block_start = src
    .find( "Rotation dispatch (Feature 038" )
    .expect( "rotation dispatch block not found in api.rs" );
  // Ends at the closing `}` of `if params.rotate { ... }` — after the final `return Ok`.
  let block_end   = src[ block_start.. ]
    .find( "\n  Ok( OutputData::new( content" )
    .map_or( src.len(), |rel| block_start + rel );
  let block = &src[ block_start..block_end ];

  assert!(
    block.contains( "apply_model_override(" ),
    "AC-05: apply_model_override must be called in the rotation dispatch block (Feature 062)\n\
    block:\n{block}",
  );
}

/// `ft12` — Rotation dispatcher calls `set_session_effort` to carry forward effort (AC-06).
///
/// # Root Cause
/// Before Feature 062, `effortLevel` was never written during rotation — the user's effort
/// preference would vanish from settings.json after switching accounts.
///
/// # Why Not Caught
/// No structural test asserted the call site exists inside the rotation block.
///
/// # Fix Applied
/// Added `set_session_effort( &claude_paths, se )` inside the rotation dispatch block,
/// guarded by `if let Some( se ) = session_effort`.
///
/// # Prevention
/// Structural grep: rotation dispatch block must contain `set_session_effort(`.
///
/// # Pitfall
/// `session_effort` is read from the PRE-rotation settings.json and carried forward — it
/// represents the user's persistent effort preference, not the winner account's data.
#[ test ]
fn ft12_rotation_dispatcher_calls_set_session_effort_for_carry_forward()
{
  let src         = include_str!( "api.rs" );
  let block_start = src
    .find( "Rotation dispatch (Feature 038" )
    .expect( "rotation dispatch block not found in api.rs" );
  let block_end   = src[ block_start.. ]
    .find( "\n  Ok( OutputData::new( content" )
    .map_or( src.len(), |rel| block_start + rel );
  let block = &src[ block_start..block_end ];

  assert!(
    block.contains( "set_session_effort(" ),
    "AC-06: set_session_effort must be called in the rotation dispatch block (Feature 062)\n\
    block:\n{block}",
  );
}

/// `ft13` — `set_session_effort` is only called when `session_effort` is `Some` (AC-07).
///
/// # Root Cause
/// AC-07 forbids injecting a default effort when none is configured. If `set_session_effort`
/// were called unconditionally (or with a hardcoded default), users without an effort preference
/// would have one silently injected after rotation.
///
/// # Why Not Caught
/// No structural test asserted the `Some(se)` guard wraps the call.
///
/// # Fix Applied
/// `set_session_effort` is called inside `if let Some( se ) = session_effort { ... }` — only
/// fires when the pre-rotation settings.json contained an `effortLevel` value.
///
/// # Prevention
/// Structural grep: `set_session_effort` call must be preceded by `if let Some( se ) = session_effort`.
///
/// # Pitfall
/// The guard checks `session_effort` (the `Option<&str>` extracted from settings.json before
/// render), not `params.effort` (the CLI param). These are distinct: params.effort governs
/// the subprocess model; `session_effort` governs the settings.json effortLevel field.
#[ test ]
fn ft13_rotation_set_session_effort_guarded_by_some_not_injected()
{
  let src         = include_str!( "api.rs" );
  let block_start = src
    .find( "Rotation dispatch (Feature 038" )
    .expect( "rotation dispatch block not found in api.rs" );
  let block_end   = src[ block_start.. ]
    .find( "\n  Ok( OutputData::new( content" )
    .map_or( src.len(), |rel| block_start + rel );
  let block = &src[ block_start..block_end ];

  assert!(
    block.contains( "if let Some( se ) = session_effort" ),
    "AC-07: set_session_effort must be guarded by `if let Some( se ) = session_effort` \
    to prevent effort injection when none is configured (Feature 062)\n\
    block:\n{block}",
  );
}