linesmith-core 0.1.3

Internal core engine for linesmith. No SemVer guarantee for direct dependents — depend on the `linesmith` binary or accept breakage between minor versions.
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
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
use super::*;
use std::cell::{Cell, RefCell};
use std::io;

use jiff::SignedDuration as ChronoDuration;
use tempfile::TempDir;

use crate::data_context::cache::{CacheStore, CachedUsage, Lock, LockStore};
use crate::data_context::credentials::Credentials;
use crate::data_context::error::CredentialError;
use crate::data_context::fetcher::{HttpResponse, UsageTransport};
use crate::data_context::jsonl::{
    FiveHourBlock, JsonlAggregate, SevenDayWindow as JsonlSevenDayWindow, TokenCounts,
};

struct FakeTransport {
    response: RefCell<io::Result<HttpResponse>>,
    calls: Cell<u32>,
}

impl FakeTransport {
    fn ok(status: u16, body: &str, retry_after: Option<&str>) -> Self {
        Self {
            response: RefCell::new(Ok(HttpResponse {
                status,
                body: body.as_bytes().to_vec(),
                retry_after: retry_after.map(String::from),
            })),
            calls: Cell::new(0),
        }
    }

    fn err(kind: io::ErrorKind) -> Self {
        Self {
            response: RefCell::new(Err(io::Error::new(kind, "fake"))),
            calls: Cell::new(0),
        }
    }
}

impl UsageTransport for FakeTransport {
    fn get(&self, _url: &str, _token: &str, _timeout: Duration) -> io::Result<HttpResponse> {
        self.calls.set(self.calls.get() + 1);
        match &*self.response.borrow() {
            Ok(r) => Ok(HttpResponse {
                status: r.status,
                body: r.body.clone(),
                retry_after: r.retry_after.clone(),
            }),
            Err(e) => Err(io::Error::new(e.kind(), e.to_string())),
        }
    }
}

const SAMPLE_BODY: &str = r#"{
    "five_hour":  { "utilization": 42.0, "resets_at": "2026-04-19T05:00:00Z" },
    "seven_day":  { "utilization": 33.0, "resets_at": "2026-04-23T19:00:00Z" }
}"#;

fn sample_response() -> UsageApiResponse {
    serde_json::from_str(SAMPLE_BODY).unwrap()
}

fn config() -> UsageCascadeConfig {
    UsageCascadeConfig::default()
}

fn now_fn() -> impl Fn() -> Timestamp {
    let ts = Timestamp::now();
    move || ts
}

fn ok_creds() -> Arc<Result<Credentials, CredentialError>> {
    Arc::new(Ok(Credentials::for_testing("test-token")))
}

fn no_creds() -> Arc<Result<Credentials, CredentialError>> {
    Arc::new(Err(CredentialError::NoCredentials))
}

fn jsonl_empty() -> Result<JsonlAggregate, JsonlError> {
    Err(JsonlError::NoEntries)
}

/// 7d-only JSONL aggregate. Exercises the case where the cascade
/// falls back to JSONL and the 7d window is populated but no 5h
/// block is active (e.g. the user hasn't coded in the last 5h).
fn jsonl_ok() -> Result<JsonlAggregate, JsonlError> {
    Ok(JsonlAggregate {
        five_hour: None,
        seven_day: JsonlSevenDayWindow {
            window_start: Timestamp::now() - ChronoDuration::from_hours(7 * 24),
            token_counts: TokenCounts::from_parts(1_000_000, 200_000, 0, 0),
        },
        source_paths: Vec::new(),
    })
}

/// JSONL aggregate with an active 5h block. Start is `now - 1h` so
/// the block's `end()` (= start + 5h) lies ~4h in the future, a
/// realistic reset-timer window for the 5h-reset segment tests.
fn jsonl_ok_with_active_block() -> Result<JsonlAggregate, JsonlError> {
    let now = Timestamp::now();
    let start = now - ChronoDuration::from_hours(1);
    Ok(JsonlAggregate {
        five_hour: Some(FiveHourBlock {
            start,
            actual_last_activity: now,
            token_counts: TokenCounts::from_parts(400_000, 20_000, 0, 0),
            models: vec!["claude-opus-4-7".into()],
            usage_limit_reset: None,
        }),
        seven_day: JsonlSevenDayWindow {
            window_start: now - ChronoDuration::from_hours(7 * 24),
            token_counts: TokenCounts::from_parts(1_000_000, 200_000, 0, 0),
        },
        source_paths: Vec::new(),
    })
}

fn stale_cache_entry(age: ChronoDuration) -> CachedUsage {
    let mut entry = CachedUsage::with_data(sample_response());
    entry.cached_at = Timestamp::now() - age;
    entry
}

/// Assert that `data` is the `Jsonl` variant built from the
/// [`jsonl_ok`] fixture (no active 5h block, 7d window
/// populated with `1_000_000 + 200_000` tokens).
///
/// Fallthrough tests use this instead of `matches!(data, UsageData::Jsonl(_))`
/// so that a cascade bug serving `SevenDayWindow::default()` or
/// dropping the window entirely gets caught.
fn assert_jsonl_matches_ok_fixture(data: &UsageData) {
    let UsageData::Jsonl(j) = data else {
        panic!("expected UsageData::Jsonl, got {data:?}");
    };
    assert!(
        j.five_hour.is_none(),
        "jsonl_ok fixture has no active 5h block",
    );
    assert_eq!(
        j.seven_day.tokens.total(),
        1_200_000,
        "7d total must match jsonl_ok fixture (1M input + 200k output)",
    );
}

#[test]
fn fresh_disk_cache_short_circuits_without_reading_credentials() {
    let tmp = TempDir::new().unwrap();
    let cache = CacheStore::new(tmp.path().to_path_buf());
    cache
        .write(&CachedUsage::with_data(sample_response()))
        .unwrap();

    let cred_calls = Cell::new(0u32);
    let jsonl_calls = Cell::new(0u32);
    let credentials = || {
        cred_calls.set(cred_calls.get() + 1);
        ok_creds()
    };
    let jsonl = || {
        jsonl_calls.set(jsonl_calls.get() + 1);
        jsonl_empty()
    };
    let transport = FakeTransport::ok(200, "", None);

    let data = resolve_usage(
        Some(&cache),
        None,
        &transport,
        &credentials,
        &jsonl,
        &now_fn(),
        &config(),
    )
    .expect("ok");

    let UsageData::Endpoint(endpoint) = &data else {
        panic!("expected endpoint variant, got {data:?}");
    };
    assert_eq!(endpoint.five_hour.unwrap().utilization.value(), 42.0);
    assert_eq!(cred_calls.get(), 0, "credentials must not be called");
    assert_eq!(jsonl_calls.get(), 0, "jsonl must not be called");
    assert_eq!(transport.calls.get(), 0, "no HTTP on cache hit");
}

#[test]
fn stale_cache_without_lock_triggers_fetch_and_overwrites() {
    let tmp = TempDir::new().unwrap();
    let cache = CacheStore::new(tmp.path().to_path_buf());
    cache
        .write(&stale_cache_entry(ChronoDuration::from_mins(10)))
        .unwrap();
    let lock = LockStore::new(tmp.path().to_path_buf());

    let transport = FakeTransport::ok(200, SAMPLE_BODY, None);
    let data = resolve_usage(
        Some(&cache),
        Some(&lock),
        &transport,
        &ok_creds,
        &jsonl_empty,
        &now_fn(),
        &config(),
    )
    .expect("ok");

    assert!(matches!(data, UsageData::Endpoint(_)));
    assert_eq!(transport.calls.get(), 1);
    let refreshed = cache.read().unwrap().unwrap();
    let age = Timestamp::now().duration_since(refreshed.cached_at);
    assert!(age.as_secs() < 5, "cache must be re-stamped on success");
}

#[test]
fn stale_cache_with_active_lock_serves_stale_without_credentials() {
    let tmp = TempDir::new().unwrap();
    let cache = CacheStore::new(tmp.path().to_path_buf());
    cache
        .write(&stale_cache_entry(ChronoDuration::from_mins(10)))
        .unwrap();
    let lock = LockStore::new(tmp.path().to_path_buf());
    lock.write(&Lock {
        blocked_until: Timestamp::now().as_second() + 60,
        error: Some("rate-limited".into()),
    })
    .unwrap();

    let cred_calls = Cell::new(0u32);
    let credentials = || {
        cred_calls.set(cred_calls.get() + 1);
        ok_creds()
    };
    let transport = FakeTransport::ok(200, "", None);

    let data = resolve_usage(
        Some(&cache),
        Some(&lock),
        &transport,
        &credentials,
        &jsonl_empty,
        &now_fn(),
        &config(),
    )
    .expect("ok");

    assert!(matches!(data, UsageData::Endpoint(_)));
    assert_eq!(
        cred_calls.get(),
        0,
        "active lock must short-circuit before credentials read",
    );
    assert_eq!(transport.calls.get(), 0, "no HTTP when lock + stale cache");
}

#[test]
fn no_credentials_surfaces_nocredentials_not_timeout() {
    let transport = FakeTransport::err(io::ErrorKind::TimedOut);
    let err = resolve_usage(
        None,
        None,
        &transport,
        &no_creds,
        &jsonl_empty,
        &now_fn(),
        &config(),
    )
    .unwrap_err();
    assert!(matches!(err, UsageError::NoCredentials));
    assert_eq!(transport.calls.get(), 0, "no HTTP when credentials missing",);
}

#[test]
fn no_credentials_falls_through_to_jsonl_when_available() {
    // ADR-0013: JSONL aggregation is the terminal fallback. A
    // user with no OAuth credentials who still has Claude Code
    // transcript history should see their local token totals
    // rather than `[No credentials]`.
    let data = resolve_usage(
        None,
        None,
        &FakeTransport::ok(200, "", None),
        &no_creds,
        &jsonl_ok,
        &now_fn(),
        &config(),
    )
    .expect("ok");
    assert_jsonl_matches_ok_fixture(&data);
}

#[test]
fn no_credentials_with_empty_jsonl_still_surfaces_nocredentials() {
    // JSONL unavailable → original endpoint-path error wins so
    // users on a clean machine see the actionable `[No credentials]`
    // rather than a silent hide.
    let err = resolve_usage(
        None,
        None,
        &FakeTransport::ok(200, "", None),
        &no_creds,
        &jsonl_empty,
        &now_fn(),
        &config(),
    )
    .unwrap_err();
    assert!(matches!(err, UsageError::NoCredentials));
}

#[test]
fn endpoint_200_writes_cache_and_lock() {
    let tmp = TempDir::new().unwrap();
    let cache = CacheStore::new(tmp.path().to_path_buf());
    let lock = LockStore::new(tmp.path().to_path_buf());
    let transport = FakeTransport::ok(200, SAMPLE_BODY, None);

    let data = resolve_usage(
        Some(&cache),
        Some(&lock),
        &transport,
        &ok_creds,
        &jsonl_empty,
        &now_fn(),
        &config(),
    )
    .expect("ok");

    assert!(matches!(data, UsageData::Endpoint(_)));
    assert!(cache.read().unwrap().is_some(), "cache must be populated");
    let persisted_lock = lock.read().unwrap().unwrap();
    let expected_blocked_until =
        Timestamp::now().as_second() + config().cache_duration.as_secs() as i64;
    assert!(
        (persisted_lock.blocked_until - expected_blocked_until).abs() < 5,
        "lock blocked_until = {}, expected near {}",
        persisted_lock.blocked_until,
        expected_blocked_until,
    );
}

#[test]
fn endpoint_401_falls_through_to_jsonl_when_available() {
    // ADR-0013: a revoked/expired token invalidates the endpoint
    // response but not the local transcript. JSONL has to kick in
    // on 401 too, otherwise a user who rotates their token but
    // hasn't re-auth'd sees `[Unauthorized]` instead of real data
    // they could otherwise surface locally.
    let transport = FakeTransport::ok(401, "", None);
    let data = resolve_usage(
        None,
        None,
        &transport,
        &ok_creds,
        &jsonl_ok,
        &now_fn(),
        &config(),
    )
    .expect("ok");
    assert_jsonl_matches_ok_fixture(&data);
    // Endpoint is still hit first — JSONL is a fallback, not a
    // short-circuit. Regression guard against a future refactor
    // that inverts the ordering.
    assert_eq!(transport.calls.get(), 1);
}

#[test]
fn jsonl_fallback_clamps_future_dated_block_start_to_now() {
    // Clock-skew regression (Codex P2, 2026-04-22): a future-dated
    // entry makes `block.start = floor_to_grain(future_timestamp)`,
    // which lies beyond `now`. Without clamping, `FiveHourWindow`
    // would derive an `ends_at` further in the future than 5h,
    // inflating the reset countdown and distorting `rate_limit_5h`
    // tokens. The aggregator keeps the skewed block so mild-skew
    // users don't lose their session; the cascade clamps
    // `block.start` to `floor_to_grain(now)` before surfacing.
    let now = Timestamp::now();
    // Build a skewed block at +2h so `block.start` starts in the
    // future and `ends_at = start + 5h` would land ~7h out.
    let skewed_start = now + ChronoDuration::from_hours(2);
    let skewed: Result<JsonlAggregate, JsonlError> = Ok(JsonlAggregate {
        five_hour: Some(FiveHourBlock {
            start: skewed_start,
            actual_last_activity: now + ChronoDuration::from_mins(30),
            token_counts: TokenCounts::from_parts(100, 0, 0, 0),
            models: vec!["claude-opus-4-7".into()],
            usage_limit_reset: None,
        }),
        seven_day: JsonlSevenDayWindow {
            window_start: now - ChronoDuration::from_hours(7 * 24),
            token_counts: TokenCounts::from_parts(100, 0, 0, 0),
        },
        source_paths: Vec::new(),
    });
    let skewed_closure = || match &skewed {
        Ok(agg) => Ok(agg.clone()),
        Err(_) => Err(JsonlError::NoEntries),
    };
    let now_clock = move || now;
    let data = resolve_usage(
        None,
        None,
        &FakeTransport::err(io::ErrorKind::TimedOut),
        &ok_creds,
        &skewed_closure,
        &now_clock,
        &config(),
    )
    .expect("ok");
    let UsageData::Jsonl(j) = &data else {
        panic!("expected jsonl variant, got {data:?}");
    };
    let window = j
        .five_hour
        .as_ref()
        .expect("active block should populate five_hour window");
    // Clamped: start cannot exceed floor_to_grain(now), so
    // ends_at <= floor_to_grain(now) + 5h <= now + 5h.
    assert!(
        window.ends_at() <= now + ChronoDuration::from_hours(5),
        "ends_at={:?} must be clamped at/before now + 5h ({:?})",
        window.ends_at(),
        now + ChronoDuration::from_hours(5),
    );
}

#[test]
fn jsonl_fallback_surfaces_five_hour_window_with_ends_at() {
    // End-to-end: under endpoint failure + active JSONL block, the
    // cascade wraps `block.end()` as `FiveHourWindow.ends_at` so
    // `rate_limit_5h_reset` can derive its countdown without a
    // tier-aware `resets_at`.
    let data = resolve_usage(
        None,
        None,
        &FakeTransport::err(io::ErrorKind::TimedOut),
        &ok_creds,
        &jsonl_ok_with_active_block,
        &now_fn(),
        &config(),
    )
    .expect("ok");
    let UsageData::Jsonl(j) = &data else {
        panic!("expected jsonl variant, got {data:?}");
    };
    let window = j
        .five_hour
        .as_ref()
        .expect("active block should populate five_hour window");
    let expected_ends_at = Timestamp::now() + ChronoDuration::from_hours(4);
    let drift = window
        .ends_at()
        .duration_since(expected_ends_at)
        .as_secs()
        .abs();
    assert!(
        drift < 5,
        "ends_at={:?} drifted {drift}s from expected",
        window.ends_at(),
    );
    // Total from the active-block fixture (400_000 + 20_000 input+output).
    assert_eq!(window.tokens.total(), 420_000);
}

#[test]
fn endpoint_401_with_empty_jsonl_surfaces_unauthorized() {
    let err = resolve_usage(
        None,
        None,
        &FakeTransport::ok(401, "", None),
        &ok_creds,
        &jsonl_empty,
        &now_fn(),
        &config(),
    )
    .unwrap_err();
    assert!(matches!(err, UsageError::Unauthorized));
}

#[test]
fn endpoint_401_does_not_serve_stale_cache() {
    let tmp = TempDir::new().unwrap();
    let cache = CacheStore::new(tmp.path().to_path_buf());
    cache
        .write(&stale_cache_entry(ChronoDuration::from_mins(10)))
        .unwrap();
    let err = resolve_usage(
        Some(&cache),
        None,
        &FakeTransport::ok(401, "", None),
        &ok_creds,
        &jsonl_empty,
        &now_fn(),
        &config(),
    )
    .unwrap_err();
    assert!(matches!(err, UsageError::Unauthorized));
}

#[test]
fn endpoint_401_clears_cache_so_peers_skip_fresh_short_circuit() {
    // A 401 must remove the cache file so any subsequent invocation
    // (this process or another) reads `None` and falls through to the
    // lock-active 401 guard, rather than short-circuiting on a still-
    // fresh `cached_at`. Without this, the `lock_from_401` guard is
    // dead code for any peer whose cache hasn't expired yet.
    let tmp = TempDir::new().unwrap();
    let cache = CacheStore::new(tmp.path().to_path_buf());
    cache
        .write(&stale_cache_entry(ChronoDuration::from_mins(10)))
        .unwrap();
    let lock = LockStore::new(tmp.path().to_path_buf());
    assert!(
        cache.read().unwrap().is_some(),
        "fixture wrote a cache entry"
    );

    let err = resolve_usage(
        Some(&cache),
        Some(&lock),
        &FakeTransport::ok(401, "", None),
        &ok_creds,
        &jsonl_empty,
        &now_fn(),
        &config(),
    )
    .unwrap_err();
    assert!(matches!(err, UsageError::Unauthorized));
    assert!(
        cache.read().unwrap().is_none(),
        "401 must clear the cache so peers fall through to the lock-active 401 guard",
    );
    let active_lock = lock.read().unwrap().expect("failure lock written");
    assert_eq!(
        active_lock.error.as_deref(),
        Some("Unauthorized"),
        "failure lock still records the 401 reason for the lock-active path",
    );
}

#[test]
fn endpoint_non_401_failure_preserves_cache_for_stale_serve() {
    // Companion guard: only 401 clears the cache. A 429, timeout, or
    // network error leaves the cache file intact so the stale-serve
    // path inside the lock-active branch (and the cache-fall-through
    // for non-Unauthorized lock errors) still has data to return.
    let tmp = TempDir::new().unwrap();
    let cache = CacheStore::new(tmp.path().to_path_buf());
    cache
        .write(&stale_cache_entry(ChronoDuration::from_mins(10)))
        .unwrap();
    let lock = LockStore::new(tmp.path().to_path_buf());

    let data = resolve_usage(
        Some(&cache),
        Some(&lock),
        &FakeTransport::ok(429, "", Some("60")),
        &ok_creds,
        &jsonl_empty,
        &now_fn(),
        &config(),
    )
    .expect("429 with stale cache serves the cached data");
    assert!(
        matches!(data, UsageData::Endpoint(_)),
        "stale-serve path must return the cached endpoint data: got {data:?}",
    );
    assert!(
        cache.read().unwrap().is_some(),
        "429 must NOT clear the cache — the stale-serve path needs the data",
    );
}

#[test]
fn invocation_after_401_does_not_serve_stale_cache_via_lock_active() {
    // A→B sequence: invocation A gets a 401 that clears the cache
    // and writes a failure-lock with error="Unauthorized". Invocation
    // B within the lock TTL reads no cache (A cleared it) and the
    // active Unauthorized lock, so the lock-active branch routes B
    // to JSONL/Unauthorized rather than serving any stale data. The
    // `lock_from_401` guard with a `Some(entry)` value is exercised
    // separately by `active_unauthorized_lock_rejects_stale_cached_data`.
    let tmp = TempDir::new().unwrap();
    let cache = CacheStore::new(tmp.path().to_path_buf());
    cache
        .write(&stale_cache_entry(ChronoDuration::from_mins(10)))
        .unwrap();
    let lock = LockStore::new(tmp.path().to_path_buf());

    // Invocation A: 401.
    let transport_a = FakeTransport::ok(401, "", None);
    let err_a = resolve_usage(
        Some(&cache),
        Some(&lock),
        &transport_a,
        &ok_creds,
        &jsonl_empty,
        &now_fn(),
        &config(),
    )
    .unwrap_err();
    assert!(matches!(err_a, UsageError::Unauthorized));

    // Invocation B: lock active, cache still holds pre-401 data.
    // Transport returns fresh 200 data if hit; we assert it isn't.
    let transport_b = FakeTransport::ok(200, SAMPLE_BODY, None);
    let err_b = resolve_usage(
        Some(&cache),
        Some(&lock),
        &transport_b,
        &ok_creds,
        &jsonl_empty,
        &now_fn(),
        &config(),
    )
    .unwrap_err();
    assert!(matches!(err_b, UsageError::Unauthorized));
    assert_eq!(
        transport_b.calls.get(),
        0,
        "active lock must still gate the endpoint on invocation B",
    );
}

#[test]
fn invocation_after_401_falls_through_to_jsonl_when_available() {
    // ADR-0013 parity for the A→B sequence: when invocation A
    // 401'd and invocation B has JSONL data, B gets local
    // transcript totals instead of either the stale cache or the
    // Unauthorized error.
    let tmp = TempDir::new().unwrap();
    let cache = CacheStore::new(tmp.path().to_path_buf());
    cache
        .write(&stale_cache_entry(ChronoDuration::from_mins(10)))
        .unwrap();
    let lock = LockStore::new(tmp.path().to_path_buf());

    let data_a = resolve_usage(
        Some(&cache),
        Some(&lock),
        &FakeTransport::ok(401, "", None),
        &ok_creds,
        &jsonl_ok,
        &now_fn(),
        &config(),
    )
    .expect("A falls through to JSONL with jsonl_ok");
    assert_jsonl_matches_ok_fixture(&data_a);

    let transport_b = FakeTransport::ok(200, SAMPLE_BODY, None);
    let data_b = resolve_usage(
        Some(&cache),
        Some(&lock),
        &transport_b,
        &ok_creds,
        &jsonl_ok,
        &now_fn(),
        &config(),
    )
    .expect("B returns JSONL on lock-active path");
    assert_jsonl_matches_ok_fixture(&data_b);
    assert_eq!(transport_b.calls.get(), 0);
}

#[test]
fn active_unauthorized_lock_rejects_stale_cached_data() {
    // Isolates the `lock_from_401` guard: seeds `cache.data =
    // Some(stale)` + `lock.error = Some("Unauthorized")` directly,
    // bypassing the A→B integration path. The seeded state is
    // realistic because a different process could have run the
    // 401 (writing the lock) while leaving our cache untouched.
    // Verifies the guard refuses to serve the stale data without
    // depending on the 401 handler's own write ordering.
    let tmp = TempDir::new().unwrap();
    let cache = CacheStore::new(tmp.path().to_path_buf());
    cache
        .write(&stale_cache_entry(ChronoDuration::from_mins(10)))
        .unwrap();
    let lock = LockStore::new(tmp.path().to_path_buf());
    lock.write(&Lock {
        blocked_until: Timestamp::now().as_second() + 30,
        error: Some("Unauthorized".into()),
    })
    .unwrap();

    let transport = FakeTransport::ok(200, SAMPLE_BODY, None);
    let err = resolve_usage(
        Some(&cache),
        Some(&lock),
        &transport,
        &ok_creds,
        &jsonl_empty,
        &now_fn(),
        &config(),
    )
    .unwrap_err();
    assert!(matches!(err, UsageError::Unauthorized));
    assert_eq!(transport.calls.get(), 0);
}

#[test]
fn endpoint_429_writes_lock_with_retry_after_backoff() {
    // Codex P1: without this, every concurrent process re-hits
    // the endpoint during a rate-limit window.
    let tmp = TempDir::new().unwrap();
    let cache = CacheStore::new(tmp.path().to_path_buf());
    let lock = LockStore::new(tmp.path().to_path_buf());

    let _ = resolve_usage(
        Some(&cache),
        Some(&lock),
        &FakeTransport::ok(429, "", Some("120")),
        &ok_creds,
        &jsonl_empty,
        &now_fn(),
        &config(),
    );

    let persisted = lock.read().unwrap().expect("lock must be written");
    let expected = Timestamp::now().as_second() + 120;
    assert!(
        (persisted.blocked_until - expected).abs() < 5,
        "blocked_until={}, expected near {}",
        persisted.blocked_until,
        expected,
    );
    assert_eq!(persisted.error.as_deref(), Some("RateLimited"));
}

#[test]
fn endpoint_timeout_writes_lock_with_error_ttl() {
    let tmp = TempDir::new().unwrap();
    let lock = LockStore::new(tmp.path().to_path_buf());

    let _ = resolve_usage(
        None,
        Some(&lock),
        &FakeTransport::err(io::ErrorKind::TimedOut),
        &ok_creds,
        &jsonl_empty,
        &now_fn(),
        &config(),
    );

    let persisted = lock.read().unwrap().expect("lock must be written");
    let expected = Timestamp::now().as_second() + DEFAULT_ERROR_TTL.as_secs() as i64;
    assert!(
        (persisted.blocked_until - expected).abs() < 5,
        "blocked_until={}, expected near {}",
        persisted.blocked_until,
        expected,
    );
    assert_eq!(persisted.error.as_deref(), Some("Timeout"));
}

#[test]
fn lock_written_on_429_blocks_next_process_from_hitting_endpoint() {
    // End-to-end P1a+P1b: process A gets a 429 and writes the
    // lock; process B observes the lock and skips the endpoint.
    // Without either half of the fix, B stampedes the rate-limited
    // endpoint.
    let tmp = TempDir::new().unwrap();
    let cache = CacheStore::new(tmp.path().to_path_buf());
    let lock = LockStore::new(tmp.path().to_path_buf());

    let transport_a = FakeTransport::ok(429, "", Some("120"));
    let _ = resolve_usage(
        Some(&cache),
        Some(&lock),
        &transport_a,
        &ok_creds,
        &jsonl_empty,
        &now_fn(),
        &config(),
    );

    let transport_b = FakeTransport::ok(200, SAMPLE_BODY, None);
    let result_b = resolve_usage(
        Some(&cache),
        Some(&lock),
        &transport_b,
        &ok_creds,
        &jsonl_empty,
        &now_fn(),
        &config(),
    );
    assert!(matches!(result_b, Err(UsageError::RateLimited { .. })));
    assert_eq!(
        transport_b.calls.get(),
        0,
        "process B must not hit endpoint"
    );
}

#[test]
fn endpoint_401_writes_lock_so_peers_skip_the_stale_token() {
    let tmp = TempDir::new().unwrap();
    let lock = LockStore::new(tmp.path().to_path_buf());

    let _ = resolve_usage(
        None,
        Some(&lock),
        &FakeTransport::ok(401, "", None),
        &ok_creds,
        &jsonl_empty,
        &now_fn(),
        &config(),
    );

    let persisted = lock.read().unwrap().expect("lock must be written");
    assert_eq!(persisted.error.as_deref(), Some("Unauthorized"));
}

#[test]
fn endpoint_429_with_stale_cache_serves_stale() {
    let tmp = TempDir::new().unwrap();
    let cache = CacheStore::new(tmp.path().to_path_buf());
    cache
        .write(&stale_cache_entry(ChronoDuration::from_mins(10)))
        .unwrap();
    let data = resolve_usage(
        Some(&cache),
        None,
        &FakeTransport::ok(429, "", Some("120")),
        &ok_creds,
        &jsonl_empty,
        &now_fn(),
        &config(),
    )
    .expect("ok");
    let UsageData::Endpoint(endpoint) = &data else {
        panic!("expected endpoint variant, got {data:?}");
    };
    assert_eq!(endpoint.five_hour.unwrap().utilization.value(), 42.0);
}

#[test]
fn endpoint_429_with_empty_jsonl_surfaces_ratelimited() {
    // Endpoint + JSONL both empty → original rate-limit error wins
    // so the user sees `[Rate limited]` rather than a silent hide.
    let err = resolve_usage(
        None,
        None,
        &FakeTransport::ok(429, "", None),
        &ok_creds,
        &jsonl_empty,
        &now_fn(),
        &config(),
    )
    .unwrap_err();
    assert!(matches!(err, UsageError::RateLimited { .. }));
}

#[test]
fn endpoint_429_falls_through_to_jsonl_when_available() {
    // ADR-0013: rate-limited users with a local transcript see
    // `~5h: ...` / `~7d: ...` rather than `[Rate limited]`.
    let transport = FakeTransport::ok(429, "", None);
    let data = resolve_usage(
        None,
        None,
        &transport,
        &ok_creds,
        &jsonl_ok,
        &now_fn(),
        &config(),
    )
    .expect("ok");
    assert_jsonl_matches_ok_fixture(&data);
    assert_eq!(transport.calls.get(), 1);
}

#[test]
fn endpoint_timeout_with_stale_cache_serves_stale() {
    let tmp = TempDir::new().unwrap();
    let cache = CacheStore::new(tmp.path().to_path_buf());
    cache
        .write(&stale_cache_entry(ChronoDuration::from_mins(10)))
        .unwrap();
    let data = resolve_usage(
        Some(&cache),
        None,
        &FakeTransport::err(io::ErrorKind::TimedOut),
        &ok_creds,
        &jsonl_empty,
        &now_fn(),
        &config(),
    )
    .expect("ok");
    assert!(matches!(data, UsageData::Endpoint(_)));
}

#[test]
fn endpoint_timeout_without_stale_falls_through_to_jsonl() {
    // ADR-0013: Timeout / NetworkError falls through to JSONL so
    // an offline user still sees their local token totals.
    let transport = FakeTransport::err(io::ErrorKind::TimedOut);
    let data = resolve_usage(
        None,
        None,
        &transport,
        &ok_creds,
        &jsonl_ok,
        &now_fn(),
        &config(),
    )
    .expect("ok");
    assert_jsonl_matches_ok_fixture(&data);
    assert_eq!(
        transport.calls.get(),
        1,
        "endpoint must be attempted before JSONL fallback",
    );
}

#[test]
fn endpoint_timeout_without_stale_or_jsonl_surfaces_original_error() {
    let err = resolve_usage(
        None,
        None,
        &FakeTransport::err(io::ErrorKind::TimedOut),
        &ok_creds,
        &jsonl_empty,
        &now_fn(),
        &config(),
    )
    .unwrap_err();
    assert!(matches!(err, UsageError::Timeout));
}

#[test]
fn endpoint_network_error_falls_through_same_as_timeout() {
    let err = resolve_usage(
        None,
        None,
        &FakeTransport::err(io::ErrorKind::ConnectionRefused),
        &ok_creds,
        &jsonl_empty,
        &now_fn(),
        &config(),
    )
    .unwrap_err();
    assert!(matches!(err, UsageError::NetworkError));
}

#[test]
fn endpoint_malformed_response_falls_through_to_jsonl() {
    let err = resolve_usage(
        None,
        None,
        &FakeTransport::ok(200, "{ not valid", None),
        &ok_creds,
        &jsonl_empty,
        &now_fn(),
        &config(),
    )
    .unwrap_err();
    assert!(matches!(err, UsageError::ParseError));
}

#[test]
fn cascade_tolerates_missing_cache_and_lock_stores() {
    // Mirrors the no-cache-root branch (HOME and XDG both unset):
    // cascade must still reach credentials + endpoint instead of
    // hard-erroring on cache I/O.
    let data = resolve_usage(
        None,
        None,
        &FakeTransport::ok(200, SAMPLE_BODY, None),
        &ok_creds,
        &jsonl_empty,
        &now_fn(),
        &config(),
    )
    .expect("ok");
    assert!(matches!(data, UsageData::Endpoint(_)));
}

#[test]
fn expired_lock_does_not_gate_fetch() {
    let tmp = TempDir::new().unwrap();
    let cache = CacheStore::new(tmp.path().to_path_buf());
    cache
        .write(&stale_cache_entry(ChronoDuration::from_mins(10)))
        .unwrap();
    let lock = LockStore::new(tmp.path().to_path_buf());
    lock.write(&Lock {
        blocked_until: Timestamp::now().as_second() - 60,
        error: None,
    })
    .unwrap();

    let transport = FakeTransport::ok(200, SAMPLE_BODY, None);
    let _ = resolve_usage(
        Some(&cache),
        Some(&lock),
        &transport,
        &ok_creds,
        &jsonl_empty,
        &now_fn(),
        &config(),
    )
    .expect("ok");
    assert_eq!(
        transport.calls.get(),
        1,
        "expired lock must not block fetch"
    );
}

#[test]
fn active_lock_with_no_cached_data_does_not_hit_endpoint() {
    // Cold-cache start during another process's backoff window:
    // the lock must block the fetch even without stale data to
    // serve, else every concurrent statusline invocation stampedes
    // `/api/oauth/usage`. Flagged P1 by Codex.
    let tmp = TempDir::new().unwrap();
    let cache = CacheStore::new(tmp.path().to_path_buf());
    let lock = LockStore::new(tmp.path().to_path_buf());
    lock.write(&Lock {
        blocked_until: Timestamp::now().as_second() + 60,
        error: Some("RateLimited".into()),
    })
    .unwrap();

    let cred_calls = Cell::new(0u32);
    let credentials = || {
        cred_calls.set(cred_calls.get() + 1);
        ok_creds()
    };
    let transport = FakeTransport::ok(200, SAMPLE_BODY, None);
    let err = resolve_usage(
        Some(&cache),
        Some(&lock),
        &transport,
        &credentials,
        &jsonl_empty,
        &now_fn(),
        &config(),
    )
    .unwrap_err();
    assert!(matches!(err, UsageError::RateLimited { .. }));
    assert_eq!(cred_calls.get(), 0, "must not resolve credentials");
    assert_eq!(transport.calls.get(), 0, "must not hit endpoint");
}

#[test]
fn active_lock_falls_through_to_jsonl_when_available() {
    // ADR-0013: even when gated by another process's backoff lock,
    // a populated JSONL aggregate wins over the lock-hint error so
    // rate-limited users with local transcripts see `~5h: ...`.
    // The lock still gates the endpoint — no HTTP call may happen.
    let tmp = TempDir::new().unwrap();
    let cache = CacheStore::new(tmp.path().to_path_buf());
    let lock = LockStore::new(tmp.path().to_path_buf());
    lock.write(&Lock {
        blocked_until: Timestamp::now().as_second() + 60,
        error: Some("RateLimited".into()),
    })
    .unwrap();

    let transport = FakeTransport::ok(200, SAMPLE_BODY, None);
    let data = resolve_usage(
        Some(&cache),
        Some(&lock),
        &transport,
        &ok_creds,
        &jsonl_ok,
        &now_fn(),
        &config(),
    )
    .expect("ok");
    assert_jsonl_matches_ok_fixture(&data);
    assert_eq!(
        transport.calls.get(),
        0,
        "active lock must still gate the endpoint even with JSONL data"
    );
}

#[test]
fn active_lock_serves_cached_error_without_hitting_endpoint() {
    // When the cache carries a specific error tag (e.g. Unauthorized
    // from a prior 401), the lock-active path must surface that
    // code — not the generic lock-hint — so plugins/segments see
    // the real reason.
    let tmp = TempDir::new().unwrap();
    let cache = CacheStore::new(tmp.path().to_path_buf());
    cache
        .write(&CachedUsage::with_error("Unauthorized"))
        .unwrap();
    let lock = LockStore::new(tmp.path().to_path_buf());
    lock.write(&Lock {
        blocked_until: Timestamp::now().as_second() + 60,
        error: Some("RateLimited".into()),
    })
    .unwrap();

    let transport = FakeTransport::ok(200, "", None);
    let err = resolve_usage(
        Some(&cache),
        Some(&lock),
        &transport,
        &ok_creds,
        &jsonl_empty,
        &now_fn(),
        &config(),
    )
    .unwrap_err();
    assert!(matches!(err, UsageError::Unauthorized));
    assert_eq!(transport.calls.get(), 0);
}

#[test]
fn active_lock_with_cached_error_falls_through_to_jsonl_when_available() {
    // ADR-0013 + silent-failure review: when the cache carries a
    // specific error code AND the lock is active AND JSONL has
    // data, the JSONL fallback wins. Otherwise users with a
    // cached `Unauthorized` plus a valid transcript would see
    // `[Unauthorized]` instead of their local totals — the exact
    // failure mode the ADR rejects.
    let tmp = TempDir::new().unwrap();
    let cache = CacheStore::new(tmp.path().to_path_buf());
    cache
        .write(&CachedUsage::with_error("Unauthorized"))
        .unwrap();
    let lock = LockStore::new(tmp.path().to_path_buf());
    lock.write(&Lock {
        blocked_until: Timestamp::now().as_second() + 60,
        error: Some("RateLimited".into()),
    })
    .unwrap();

    let transport = FakeTransport::ok(200, "", None);
    let data = resolve_usage(
        Some(&cache),
        Some(&lock),
        &transport,
        &ok_creds,
        &jsonl_ok,
        &now_fn(),
        &config(),
    )
    .expect("ok");
    assert_jsonl_matches_ok_fixture(&data);
    assert_eq!(transport.calls.get(), 0);
}

#[test]
fn credential_failure_other_than_missing_preserves_variant_tag() {
    // `rate-limit-segments.md` §Error message table distinguishes
    // `[Keychain error]` from `[No credentials]`, so the cascade
    // must preserve the specific CredentialError flavor. Only
    // `NoCredentials` maps to the flat `UsageError::NoCredentials`;
    // everything else wraps.
    let creds_err: Arc<Result<Credentials, CredentialError>> =
        Arc::new(Err(CredentialError::MissingField {
            path: std::path::PathBuf::from("/x"),
        }));
    let credentials = || creds_err.clone();
    let err = resolve_usage(
        None,
        None,
        &FakeTransport::err(io::ErrorKind::TimedOut),
        &credentials,
        &jsonl_empty,
        &now_fn(),
        &config(),
    )
    .unwrap_err();
    assert!(
        matches!(
            err,
            UsageError::Credentials(CredentialError::MissingField { .. })
        ),
        "expected Credentials(MissingField), got {err:?}",
    );
    assert_eq!(err.code(), "MissingField", "variant tag must round-trip");
}

#[test]
fn subprocess_failed_cred_preserves_subprocess_tag() {
    // `SubprocessFailed` carries a non-Clone `io::Error`; the
    // lossy Clone impl on CredentialError must still preserve the
    // variant so segments can render `[Keychain error]`.
    let creds_err: Arc<Result<Credentials, CredentialError>> = Arc::new(Err(
        CredentialError::SubprocessFailed(io::Error::new(io::ErrorKind::PermissionDenied, "x")),
    ));
    let credentials = || creds_err.clone();
    let err = resolve_usage(
        None,
        None,
        &FakeTransport::err(io::ErrorKind::TimedOut),
        &credentials,
        &jsonl_empty,
        &now_fn(),
        &config(),
    )
    .unwrap_err();
    assert_eq!(err.code(), "SubprocessFailed");
}

#[test]
fn credential_variant_falls_through_to_jsonl_when_available() {
    // ADR-0013: non-`NoCredentials` cred failures (broken Keychain,
    // malformed credentials.json) still fall through to JSONL when
    // the transcript is readable, rather than hard-returning the
    // cred error variant. Common degraded-environment scenario.
    let creds_err: Arc<Result<Credentials, CredentialError>> = Arc::new(Err(
        CredentialError::SubprocessFailed(io::Error::new(io::ErrorKind::PermissionDenied, "x")),
    ));
    let credentials = || creds_err.clone();
    let data = resolve_usage(
        None,
        None,
        &FakeTransport::err(io::ErrorKind::TimedOut),
        &credentials,
        &jsonl_ok,
        &now_fn(),
        &config(),
    )
    .expect("ok");
    assert_jsonl_matches_ok_fixture(&data);
}

// Cascade must still return fetched data when persistence breaks.
// The write-side helpers log via `lsm_error!` and continue (the
// cache.rs contract permits per-call failures), so this contract
// is observable in both debug and release builds.
#[test]
fn cache_write_failure_does_not_block_returned_data() {
    let tmp = TempDir::new().unwrap();
    let blocking_file = tmp.path().join("blocked");
    std::fs::write(&blocking_file, "x").unwrap();
    let cache = CacheStore::new(blocking_file.join("nested"));

    let data = resolve_usage(
        Some(&cache),
        None,
        &FakeTransport::ok(200, SAMPLE_BODY, None),
        &ok_creds,
        &jsonl_empty,
        &now_fn(),
        &config(),
    )
    .expect("ok");
    assert!(matches!(data, UsageData::Endpoint(_)));
}

#[test]
fn fresh_cache_is_source_endpoint_not_jsonl() {
    // Regression guard: it would be tempting to tag cached data
    // as `Jsonl` to signal "stale" — but the cache stores the
    // original endpoint payload, so `Endpoint` is correct.
    // Segments decide staleness via TTL, not via the tag.
    let tmp = TempDir::new().unwrap();
    let cache = CacheStore::new(tmp.path().to_path_buf());
    cache
        .write(&CachedUsage::with_data(sample_response()))
        .unwrap();

    let data = resolve_usage(
        Some(&cache),
        None,
        &FakeTransport::ok(200, "", None),
        &ok_creds,
        &jsonl_empty,
        &now_fn(),
        &config(),
    )
    .expect("ok");
    assert!(matches!(data, UsageData::Endpoint(_)));
}

#[test]
fn clock_skew_future_cached_at_treats_entry_as_stale() {
    // `CacheStore::read` already drops entries with `cached_at >
    // now`, so the cascade sees no entry and falls through to the
    // endpoint. Pin the behavior here so a future relaxation of
    // `CacheStore::read` doesn't silently let the cascade serve
    // future-stamped junk.
    let tmp = TempDir::new().unwrap();
    let path = tmp.path().join("usage.json");
    let mut entry = CachedUsage::with_data(sample_response());
    entry.cached_at = Timestamp::now() + ChronoDuration::from_hours(1);
    std::fs::write(&path, serde_json::to_string(&entry).unwrap()).unwrap();
    let cache = CacheStore::new(tmp.path().to_path_buf());

    let transport = FakeTransport::ok(200, SAMPLE_BODY, None);
    let _ = resolve_usage(
        Some(&cache),
        None,
        &transport,
        &ok_creds,
        &jsonl_empty,
        &now_fn(),
        &config(),
    )
    .expect("ok");
    assert_eq!(transport.calls.get(), 1);
}

// --- classify_persist_error contract ---
//
// log_persist_error routes via macros (lsm_debug! / lsm_error!) which
// write to stderr. classify_persist_error is the pure half. A refactor
// that silently dropped EITHER emission path would still pass the
// surviving cache_write_failure_does_not_block_* happy-path test
// (which only asserts the cascade returns endpoint data); these
// tests fail loud on the route + message format so the regression
// can't sneak through.

fn make_io_error(kind: io::ErrorKind) -> CacheError {
    CacheError::Io {
        path: std::path::PathBuf::from("/test/path"),
        cause: io::Error::new(kind, "test"),
    }
}

fn make_persist_error(kind: io::ErrorKind) -> CacheError {
    CacheError::Persist {
        path: std::path::PathBuf::from("/test/path"),
        cause: io::Error::new(kind, "test"),
    }
}

#[test]
fn classify_persist_error_routes_io_failure_to_error() {
    let (class, msg) = classify_persist_error("cache", &make_io_error(io::ErrorKind::NotFound));
    assert_eq!(class, PersistLogClass::Error);
    assert!(
        msg.contains("cascade: cache write failed:"),
        "expected loud-signal prefix, got {msg:?}"
    );
}

#[test]
fn classify_persist_error_routes_lock_kind_into_message() {
    let (class, msg) =
        classify_persist_error("lock", &make_persist_error(io::ErrorKind::OutOfMemory));
    assert_eq!(class, PersistLogClass::Error);
    assert!(
        msg.contains("cascade: lock write failed:"),
        "kind label must thread through, got {msg:?}"
    );
}

#[cfg(unix)]
#[test]
fn classify_persist_error_routes_permission_denied_to_error_on_unix() {
    // PermissionDenied on unix is a real perm bug (EACCES), not a
    // transient race — `is_transient_persist_race` returns false
    // on cfg(not(windows)) so this stays loud.
    let (class, msg) = classify_persist_error(
        "cache",
        &make_persist_error(io::ErrorKind::PermissionDenied),
    );
    assert_eq!(class, PersistLogClass::Error);
    assert!(msg.contains("cascade: cache write failed:"));
}

#[cfg(windows)]
#[test]
fn classify_persist_error_routes_persist_permission_denied_to_debug_on_windows() {
    // The documented MoveFileEx race-loser signature: Persist
    // variant + PermissionDenied cause. Routes to Debug so multi-
    // terminal Windows users don't see stderr noise.
    let (class, msg) = classify_persist_error(
        "cache",
        &make_persist_error(io::ErrorKind::PermissionDenied),
    );
    assert_eq!(class, PersistLogClass::Debug);
    assert!(
        msg.contains("race-loser") && msg.contains("Windows MoveFileEx"),
        "expected race-loser framing, got {msg:?}"
    );
}

#[cfg(windows)]
#[test]
fn classify_persist_error_routes_io_permission_denied_to_error_on_windows() {
    // Even on Windows, PermissionDenied via the Io variant (not
    // Persist) is a real bug — only the Persist+PermissionDenied
    // combination is the MoveFileEx race signature.
    let (class, _msg) =
        classify_persist_error("cache", &make_io_error(io::ErrorKind::PermissionDenied));
    assert_eq!(class, PersistLogClass::Error);
}

// Production `log_persist_error` and these tests share the SAME
// `route_persist_error` match block, so a future arm-swap (Debug
// routing to Error or vice versa) fails loud here.

#[test]
fn route_persist_error_dispatches_debug_class_to_debug_closure_only() {
    let mut debug_calls = 0;
    let mut error_calls = 0;
    route_persist_error(
        PersistLogClass::Debug,
        "msg",
        |_| debug_calls += 1,
        |_| error_calls += 1,
    );
    assert_eq!((debug_calls, error_calls), (1, 0));
}

#[test]
fn route_persist_error_dispatches_error_class_to_error_closure_only() {
    let mut debug_calls = 0;
    let mut error_calls = 0;
    route_persist_error(
        PersistLogClass::Error,
        "msg",
        |_| debug_calls += 1,
        |_| error_calls += 1,
    );
    assert_eq!((debug_calls, error_calls), (0, 1));
}

#[test]
fn route_persist_error_passes_msg_through_unchanged() {
    let mut received: Option<String> = None;
    route_persist_error(
        PersistLogClass::Error,
        "cascade: cache write failed: disk full",
        |_| {},
        |s| received = Some(s.to_string()),
    );
    assert_eq!(
        received.as_deref(),
        Some("cascade: cache write failed: disk full")
    );
}