swapdex 0.167.16

Switch between multiple Claude Code, Codex, Gemini, and Antigravity login accounts, locally and safely.
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
//! Last-known usage per account, so a busy endpoint does not blank the display.
//!
//! Reading several accounts in a row rate-limits the usage endpoint, and an
//! account that could not be read this minute is not an account with no quota.
//! Keeping the last successful reading (with its age, so it is never mistaken for
//! live) means the picture degrades instead of disappearing.

use crate::paths::Paths;
use fs2::FileExt;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::os::unix::fs::OpenOptionsExt;

#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
pub struct Entry {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub five_h: Option<f64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub five_h_reset: Option<i64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub seven_d: Option<f64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub seven_d_reset: Option<i64>,
    /// Unix seconds when this reading was taken.
    pub at: i64,
    /// The account keeps serving past a full window, billed to extra usage.
    /// Remembered with the numbers: without it a cached full window flips the
    /// row back to "spent" between live reads.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub on_credits: bool,
    /// Why the account is refusing, in the API's own words, when the reading
    /// carried a reason. Kept with the numbers because it arrived with them:
    /// Codex states `rate_limit_reached_type` on the same response as the
    /// windows, and dropping it left the row saying an account was refusing
    /// with no way to say what would clear it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub refused: Option<String>,
    /// Unix seconds of the last live read the account's OWN TOKEN was rejected
    /// for. Distinct from `refused`, which is an endpoint that recognises the
    /// account and is declining to serve it: that clears when the window
    /// resets, this one clears when somebody signs in again.
    ///
    /// Displays that read only the cache could say how OLD a number was and
    /// not that it had stopped arriving, so an account whose reading can never
    /// update again looked exactly like one running a little late.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub token_rejected_at: Option<i64>,
}

/// A BTreeMap so the file is stable across writes - a cache that reorders itself
/// every save is noise in any diff and in any backup.
pub type Cache = BTreeMap<String, Entry>;

fn file(paths: &Paths) -> std::path::PathBuf {
    file_for(paths, "claude-code")
}

/// One file per tool. Slot names are unique only WITHIN a tool, so a single
/// flat cache lets a Codex `work` overwrite a Claude `work` and show one
/// account's windows under the other's name. Claude keeps the original
/// filename so an upgrading install does not lose its history.
fn file_for(paths: &Paths, tool: &str) -> std::path::PathBuf {
    let name = match tool {
        "claude-code" => "quota-cache.json".to_string(),
        t => format!("{t}-quota-cache.json"),
    };
    paths.store_dir().join(name)
}

struct CacheLock(std::fs::File);

impl Drop for CacheLock {
    fn drop(&mut self) {
        let _ = FileExt::unlock(&self.0);
    }
}

/// One lock per tool cache, held from read through atomic replacement.
///
/// Atomic rename keeps readers from seeing partial JSON, but it cannot merge
/// two snapshots that were read at the same time. A distinct lock from the
/// profile store avoids lock nesting with account rename/removal callers, and
/// a blocking lock lets every writer apply its change instead of dropping a
/// contending observation.
fn lock_for(paths: &Paths, tool: &str) -> Option<CacheLock> {
    std::fs::create_dir_all(paths.store_dir()).ok()?;
    let cache = file_for(paths, tool);
    let name = cache.file_name()?.to_string_lossy();
    let path = paths.store_dir().join(format!(".{name}.lock"));
    let file = std::fs::OpenOptions::new()
        .write(true)
        .create(true)
        .truncate(false)
        .mode(0o600)
        .open(path)
        .ok()?;
    FileExt::lock_exclusive(&file).ok()?;
    Some(CacheLock(file))
}

/// Read the cache. Anything unreadable yields an empty one: a stale-value cache
/// is a convenience, never a reason to fail a command.
pub fn load(paths: &Paths) -> Cache {
    load_at(paths, now_secs())
}

/// Every account's reset times, INCLUDING accounts pinned at 100%.
///
/// `load` drops a clamped entry, because a reading stuck at the ceiling is not
/// a measurement. But its reset time is still a fact, and it is the only fact a
/// "wait for the wall to lift" decision can use - so dropping it made the data
/// vanish precisely when it was needed. A window whose reset has already passed
/// is still dropped: that one says nothing about the future.
pub fn resets_for(paths: &Paths, tool: &str) -> Vec<Option<i64>> {
    load_file_at(&file_for(paths, tool), now_secs(), false)
        .values()
        .map(|e| match (e.five_h_reset, e.seven_d_reset) {
            (Some(a), Some(b)) => Some(a.min(b)),
            (a, b) => a.or(b),
        })
        .collect()
}

/// The same, for one tool.
pub fn load_for(paths: &Paths, tool: &str) -> Cache {
    load_file_at(&file_for(paths, tool), now_secs(), drops_clamped(tool))
}

/// Whether this tool's cache should discard readings pinned at the ceiling.
///
/// The rule exists for one Claude-era bug: `utilization` was read as a
/// fraction, so every account above 1% clamped to exactly 100 and the wrong
/// numbers were remembered for hours. Codex never had that bug, and applying
/// the rule there throws away the reading that matters most - a spent account's
/// - leaving its row blank instead of saying it is out.
fn drops_clamped(tool: &str) -> bool {
    tool == "claude-code"
}

/// Unix seconds, taken once per load so every window is judged against the same
/// instant.
fn now_secs() -> i64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs() as i64)
        .unwrap_or(0)
}

/// Drop the windows a remembered reading no longer describes.
///
/// A reading is about a WINDOW, and a window ends. Past its reset the number is
/// not merely stale, it is wrong: the account has a fresh allowance while the
/// bar goes on drawing the spent one. Found on a real machine showing "0% left"
/// ten minutes after the window had turned over. The two windows lapse
/// separately, so each is judged on its own.
fn expire_windows(mut e: Entry, now: i64) -> Entry {
    if e.five_h_reset.is_some_and(|r| now >= r) {
        e.five_h = None;
        e.five_h_reset = None;
    }
    if e.seven_d_reset.is_some_and(|r| now >= r) {
        e.seven_d = None;
        e.seven_d_reset = None;
    }
    e
}

/// `load`, against a given instant, so the expiry is testable.
fn load_at(paths: &Paths, now: i64) -> Cache {
    load_file_at(&file(paths), now, true)
}

fn load_file_at(path: &std::path::Path, now: i64, drop_clamped: bool) -> Cache {
    let mut c: Cache = std::fs::read(path)
        .ok()
        .and_then(|b| serde_json::from_slice(&b).ok())
        .unwrap_or_default();
    for e in c.values_mut() {
        *e = expire_windows(std::mem::take(e), now);
    }
    // An entry with nothing left to say is not an entry. A future reset is still
    // actionable without a usage reading, and a rejected token is the reason no
    // number is arriving, so either keeps the entry alive on its own. Expired
    // resets were cleared above and cannot resurrect an otherwise empty entry.
    c.retain(|_, e| {
        e.five_h.is_some()
            || e.five_h_reset.is_some()
            || e.seven_d.is_some()
            || e.seven_d_reset.is_some()
            || e.token_rejected_at.is_some()
    });
    // Readings taken while `utilization` was misread as a fraction are all
    // exactly 100 - every account above 1% clamped there - and remembering them
    // would keep showing accounts as spent long after the reading was fixed.
    // A genuine 100 is re-read within minutes, so dropping it costs nothing.
    if drop_clamped {
        c.retain(|_, e| !was_clamped(e));
    }
    c
}

/// A reading that carries only the clamp value in both windows: not a
/// measurement, an artefact of the misread.
fn was_clamped(e: &Entry) -> bool {
    let at_ceiling = |v: Option<f64>| v.is_none_or(|p| p >= 100.0);
    at_ceiling(e.five_h) && at_ceiling(e.seven_d) && (e.five_h.is_some() || e.seven_d.is_some())
}

/// Merge fresh readings in and save. Only accounts that were actually read are
/// touched, so one account's throttled request cannot erase another's history.
pub fn update(paths: &Paths, fresh: &[(String, Entry)]) {
    update_for(paths, "claude-code", fresh);
}

/// The same, for one tool.
pub fn update_for(paths: &Paths, tool: &str, fresh: &[(String, Entry)]) {
    if fresh.is_empty() {
        return;
    }
    let Some(_lock) = lock_for(paths, tool) else {
        return;
    };
    let path = file_for(paths, tool);
    let mut c = load_file_at(&path, now_secs(), drops_clamped(tool));
    for (name, e) in fresh {
        let mut e = e.clone();
        if let Some(old) = c.get(name) {
            // A response-carried reset is independent of a usage reading. Some
            // usage endpoints omit it, so absence in the fresh reading must
            // not erase a future reset learned from served traffic.
            e.five_h_reset = e.five_h_reset.or(old.five_h_reset);
            e.seven_d_reset = e.seven_d_reset.or(old.seven_d_reset);
        }
        c.insert(name.clone(), e);
    }
    if let Ok(bytes) = serde_json::to_vec_pretty(&c) {
        let _ = std::fs::create_dir_all(paths.store_dir());
        let _ = crate::atomic::write_secret(&path, &bytes);
    }
}

/// Merge the resets a served response reported onto what is remembered.
///
/// The numbers come from the usage endpoint; the RESETS also ride on every
/// response the user's own traffic earns. An account whose endpoint reports no
/// window of its own - a team seat, whose consumption is accounted elsewhere -
/// therefore had a bar with no reset time on it, while the response that just
/// came back said exactly when the window turns over. Merged, never replacing:
/// a reset is not a reading, and must not erase one.
pub fn note_resets(
    paths: &Paths,
    tool: &str,
    name: &str,
    five_h: Option<i64>,
    seven_d: Option<i64>,
) {
    if five_h.is_none() && seven_d.is_none() {
        return;
    }
    let Some(_lock) = lock_for(paths, tool) else {
        return;
    };
    let path = file_for(paths, tool);
    let mut c = load_file_at(&path, now_secs(), drops_clamped(tool));
    // This runs on every served response; rewriting the file to store what it
    // already says would be a write per turn for nothing.
    if let Some(e) = c.get(name) {
        let same = |cur: Option<i64>, new: Option<i64>| new.is_none() || cur == new;
        if same(e.five_h_reset, five_h) && same(e.seven_d_reset, seven_d) {
            return;
        }
    }
    let e = c.entry(name.to_string()).or_insert_with(|| Entry {
        at: now_secs(),
        ..Default::default()
    });
    if let Some(r) = five_h {
        e.five_h_reset = Some(r);
    }
    if let Some(r) = seven_d {
        e.seven_d_reset = Some(r);
    }
    if let Ok(bytes) = serde_json::to_vec_pretty(&c) {
        let _ = std::fs::create_dir_all(paths.store_dir());
        let _ = crate::atomic::write_secret(&path, &bytes);
    }
}

/// Record that a live read of `name` was rejected by the account's own token.
///
/// Merged onto whatever is remembered rather than replacing it: the numbers
/// were true when they were taken, and the caller wants to say "this stopped
/// arriving", not "there was never anything here". An account with nothing
/// remembered gets an entry carrying only the stamp, because "its token is
/// being rejected" is worth saying about an account that has never read.
pub fn note_token_rejected(paths: &Paths, tool: &str, name: &str, at: i64) {
    let Some(_lock) = lock_for(paths, tool) else {
        return;
    };
    let path = file_for(paths, tool);
    let mut c = load_file_at(&path, now_secs(), drops_clamped(tool));
    let e = c.entry(name.to_string()).or_default();
    e.token_rejected_at = Some(at);
    if let Ok(bytes) = serde_json::to_vec_pretty(&c) {
        let _ = std::fs::create_dir_all(paths.store_dir());
        let _ = crate::atomic::write_secret(&path, &bytes);
    }
}

/// Carry an account's remembered readings to its new name, in EVERY tool's
/// file - the cache is sharded per tool, and an account can hold a slot under
/// more than one.
///
/// The readings are keyed by name and every display looks them up by exact
/// name, so a rename that leaves them behind draws a row for a name no account
/// answers to and shows the renamed account as never read.
///
/// Read and written raw: the filters `load` applies decide what to SHOW, and a
/// rename must not be the thing that discards another account's history.
pub fn rename_account(paths: &Paths, old: &str, new: &str) {
    for tool in crate::adapters::names() {
        let Some(_lock) = lock_for(paths, tool) else {
            continue;
        };
        let path = file_for(paths, tool);
        let mut c = read_raw(&path);
        if let Some(e) = c.remove(old) {
            c.insert(new.to_string(), e);
            write_raw(&path, &c);
        }
    }
}

/// Drop an account's remembered readings. They outlive the account otherwise,
/// and the next account registered under that name inherits its percentages,
/// its credit status and its rejected token - every one of them a statement
/// about somebody else.
pub fn forget_account(paths: &Paths, name: &str) {
    for tool in crate::adapters::names() {
        let Some(_lock) = lock_for(paths, tool) else {
            continue;
        };
        let path = file_for(paths, tool);
        let mut c = read_raw(&path);
        if c.remove(name).is_some() {
            write_raw(&path, &c);
        }
    }
}

fn read_raw(path: &std::path::Path) -> Cache {
    std::fs::read(path)
        .ok()
        .and_then(|b| serde_json::from_slice(&b).ok())
        .unwrap_or_default()
}

fn write_raw(path: &std::path::Path, c: &Cache) {
    if let Ok(bytes) = serde_json::to_vec_pretty(c) {
        let _ = crate::atomic::write_secret(path, &bytes);
    }
}

#[cfg(test)]
mod tests {
    /// A reset that arrives on traffic must reach the bar without erasing the
    /// numbers that came from the endpoint.
    ///
    /// On a team seat the usage endpoint answers `utilization 0, resets_at null`
    /// for the account's own windows - consumption is accounted elsewhere - so
    /// the 5h gauge had no reset time on it while every served response carried
    /// one. Merged, because a reset is not a reading.
    #[test]
    fn a_reset_from_traffic_lands_without_erasing_the_reading() {
        let dir = tempfile::tempdir().unwrap();
        let paths = crate::paths::Paths::rooted(dir.path());
        super::update(
            &paths,
            &[(
                "work".to_string(),
                super::Entry {
                    five_h: Some(22.0),
                    seven_d: Some(21.0),
                    at: 1_000,
                    ..Default::default()
                },
            )],
        );

        super::note_resets(&paths, "claude-code", "work", Some(9_000_000_000), None);

        let c = super::load_for(&paths, "claude-code");
        let e = c.get("work").expect("the account is still there");
        assert_eq!(e.five_h, Some(22.0), "the reading survives");
        assert_eq!(e.five_h_reset, Some(9_000_000_000), "and the reset landed");
        assert_eq!(e.seven_d, Some(21.0), "the other window is untouched");
        assert_eq!(e.seven_d_reset, None, "nothing invented for it");
    }

    use super::*;

    fn entry(pct: f64, at: i64) -> Entry {
        Entry {
            five_h: Some(pct),
            at,
            ..Default::default()
        }
    }

    /// The clamp rule belongs to Claude, where the misread happened. Applied to
    /// Codex it discards a genuinely spent account's reading and leaves its row
    /// blank - the one row you most need to see.
    #[test]
    fn a_spent_codex_account_is_still_remembered() {
        let root = tempfile::tempdir().unwrap();
        let paths = Paths::rooted(root.path());
        let full = Entry {
            seven_d: Some(100.0),
            at: 1,
            ..Default::default()
        };
        update_for(&paths, "codex", &[("spent".into(), full.clone())]);
        update_for(&paths, "claude-code", &[("spent".into(), full)]);

        assert_eq!(load_for(&paths, "codex")["spent"].seven_d, Some(100.0));
        // Claude keeps the rule it needs, unchanged.
        assert!(!load_for(&paths, "claude-code").contains_key("spent"));
    }

    /// Codex accounts are remembered in their own file. Slot names are only
    /// unique within a tool, so one flat cache lets a Codex account named
    /// `work` overwrite a Claude account named `work` - and the display would
    /// show one account's windows under the other's name.
    #[test]
    fn each_tool_remembers_its_accounts_separately() {
        let root = tempfile::tempdir().unwrap();
        let paths = Paths::rooted(root.path());
        update_for(&paths, "claude-code", &[("work".into(), entry(10.0, 1))]);
        update_for(&paths, "codex", &[("work".into(), entry(90.0, 1))]);

        assert_eq!(load_for(&paths, "claude-code")["work"].five_h, Some(10.0));
        assert_eq!(load_for(&paths, "codex")["work"].five_h, Some(90.0));
        // The Claude file keeps the name it has always had, so an install that
        // upgrades does not lose its history.
        assert!(root
            .path()
            .join(".local/share/swapdex/quota-cache.json")
            .exists());
    }

    #[test]
    fn readings_persist_and_merge_without_erasing_others() {
        let root = tempfile::tempdir().unwrap();
        let paths = Paths::rooted(root.path());
        assert!(load(&paths).is_empty());

        update(&paths, &[("a".into(), entry(10.0, 100))]);
        update(&paths, &[("b".into(), entry(20.0, 200))]);
        let c = load(&paths);
        assert_eq!(c.len(), 2, "a later write keeps the earlier account");
        assert_eq!(c["a"].five_h, Some(10.0));

        // A fresh reading for one account replaces only that one.
        update(&paths, &[("a".into(), entry(55.0, 300))]);
        let c = load(&paths);
        assert_eq!(c["a"].five_h, Some(55.0));
        assert_eq!(c["b"].five_h, Some(20.0), "b is untouched");
    }

    // Every reading taken while utilization was misread is exactly 100, and
    // keeping them would show accounts as spent long after the reading was fixed.
    #[test]
    fn readings_pinned_at_the_clamp_are_not_remembered() {
        let root = tempfile::tempdir().unwrap();
        let paths = Paths::rooted(root.path());
        let full = Entry {
            five_h: Some(100.0),
            seven_d: Some(100.0),
            at: 1,
            ..Default::default()
        };
        let real = Entry {
            five_h: Some(4.0),
            seven_d: Some(59.0),
            at: 2,
            ..Default::default()
        };
        // A real 100% in ONE window beside a measured other window is a genuine
        // reading and must survive - only the all-at-the-ceiling shape is dropped.
        let one_full = Entry {
            five_h: Some(100.0),
            seven_d: Some(59.0),
            at: 3,
            ..Default::default()
        };
        update(
            &paths,
            &[
                ("clamped".into(), full),
                ("measured".into(), real),
                ("half".into(), one_full),
            ],
        );
        let c = load(&paths);
        assert!(!c.contains_key("clamped"), "the artefact is dropped");
        assert_eq!(c["measured"].five_h, Some(4.0));
        assert_eq!(c["half"].five_h, Some(100.0), "a real 100 survives");
    }

    #[test]
    fn an_unreadable_cache_is_empty_not_an_error() {
        let root = tempfile::tempdir().unwrap();
        let paths = Paths::rooted(root.path());
        std::fs::create_dir_all(paths.store_dir()).unwrap();
        std::fs::write(super::file(&paths), b"{ not json").unwrap();
        assert!(load(&paths).is_empty());
        // And it can be written over.
        update(&paths, &[("a".into(), entry(1.0, 1))]);
        assert_eq!(load(&paths).len(), 1);
    }

    #[test]
    fn a_rejected_token_is_remembered_beside_the_numbers_and_cleared_by_a_reading() {
        let root = tempfile::tempdir().unwrap();
        let paths = crate::paths::Paths::rooted(root.path());
        update_for(&paths, "codex", &[("work".into(), entry(5.0, now_secs()))]);

        note_token_rejected(&paths, "codex", "work", 1_788_737_118);
        let e = load_file_at(&file_for(&paths, "codex"), now_secs(), false)["work"].clone();
        assert_eq!(e.token_rejected_at, Some(1_788_737_118));
        assert_eq!(
            e.five_h,
            Some(5.0),
            "the numbers it had are not thrown away"
        );

        // An account nothing is remembered for still gets the fact.
        note_token_rejected(&paths, "codex", "never-read", 42);
        let c = load_file_at(&file_for(&paths, "codex"), now_secs(), false);
        assert_eq!(c["never-read"].token_rejected_at, Some(42));

        // A reading is proof the token works, so it clears.
        update_for(&paths, "codex", &[("work".into(), entry(9.0, now_secs()))]);
        let e = load_file_at(&file_for(&paths, "codex"), now_secs(), false)["work"].clone();
        assert_eq!(e.token_rejected_at, None);
    }
}

#[cfg(test)]
mod expiry_tests {
    use super::*;

    /// A remembered reading describes a WINDOW, and a window ends. Once its reset
    /// has passed the number is not stale, it is wrong: the account has a fresh
    /// allowance and the bar was still drawing the spent one. Found on a real
    /// machine reading "0% left" ten minutes after the window had turned over.
    #[test]
    fn a_window_whose_reset_has_passed_is_dropped_not_shown() {
        let e = Entry {
            five_h: Some(100.0),
            five_h_reset: Some(1_000),
            seven_d: Some(41.0),
            seven_d_reset: Some(9_000),
            at: 900,
            ..Default::default()
        };
        let before = expire_windows(e.clone(), 999);
        assert_eq!(before.five_h, Some(100.0), "inside the window it stands");

        let after = expire_windows(e.clone(), 1_001);
        assert_eq!(after.five_h, None, "past the reset it is gone");
        assert_eq!(after.five_h_reset, None, "and so is the reset it described");
        assert_eq!(
            after.seven_d,
            Some(41.0),
            "the other window is untouched - they turn over separately"
        );
    }

    /// A reading with no reset time says nothing about when it lapses, so it is
    /// left alone; its age is already shown beside it.
    #[test]
    fn a_reading_with_no_reset_is_left_alone() {
        let e = Entry {
            five_h: Some(30.0),
            five_h_reset: None,
            seven_d: None,
            seven_d_reset: None,
            at: 900,
            ..Default::default()
        };
        assert_eq!(expire_windows(e.clone(), 9_999_999), e);
    }

    #[test]
    fn an_entry_left_with_nothing_is_not_kept() {
        let root = tempfile::tempdir().unwrap();
        let paths = Paths::rooted(root.path());
        update(
            &paths,
            &[(
                "spent".to_string(),
                // Not 100: a reading pinned at the ceiling in every window is
                // dropped as an artefact of the old misread, which would hide
                // the behaviour under test.
                Entry {
                    five_h: Some(80.0),
                    five_h_reset: Some(1_000),
                    at: 900,
                    ..Default::default()
                },
            )],
        );
        assert!(
            !load_at(&paths, 2_000).contains_key("spent"),
            "nothing left to say about it"
        );
        assert!(
            load_at(&paths, 999).contains_key("spent"),
            "and it was there while the window ran"
        );
    }
}

#[cfg(test)]
mod resets_survive_tests {
    use super::*;

    #[test]
    fn a_reset_only_traffic_note_survives_until_its_windows_expire() {
        let root = tempfile::tempdir().unwrap();
        let paths = Paths::rooted(root.path());
        let five_h = 9_000_000_000;
        let seven_d = 9_000_010_000;

        note_resets(&paths, "codex", "reset-only", Some(five_h), Some(seven_d));

        assert_eq!(
            resets_for(&paths, "codex"),
            vec![Some(five_h)],
            "a served response's future reset disappeared without a usage reading"
        );
        let path = file_for(&paths, "codex");
        let before = load_file_at(&path, five_h - 1, false);
        assert_eq!(before["reset-only"].five_h_reset, Some(five_h));
        assert_eq!(before["reset-only"].seven_d_reset, Some(seven_d));

        let after_five_h = load_file_at(&path, five_h, false);
        assert_eq!(after_five_h["reset-only"].five_h_reset, None);
        assert_eq!(
            after_five_h["reset-only"].seven_d_reset,
            Some(seven_d),
            "one expired window must not discard the other future reset"
        );
        assert!(
            load_file_at(&path, seven_d, false).is_empty(),
            "an entry with no future reset or reading must expire"
        );
    }

    /// The reset time of a SPENT account is exactly what a hold needs.
    ///
    /// `load` drops entries pinned at 100% - they read as clamped, and a
    /// clamped reading is not a measurement. But the reset time on such an
    /// entry is still a fact, and it is the only fact a "wait for the wall to
    /// lift" decision can use. Dropping it meant the data vanished precisely
    /// when it was needed.
    #[test]
    fn a_spent_account_still_reports_when_it_reopens() {
        let d = tempfile::tempdir().unwrap();
        let f = d.path().join("q.json");
        std::fs::write(
            &f,
            serde_json::to_vec(&serde_json::json!({"acct": {
                "five_h": 100.0, "five_h_reset": 5_000,
                "seven_d": 100.0, "seven_d_reset": 9_000, "at": 1}}))
            .unwrap(),
        )
        .unwrap();

        // The ordinary read hides it: a clamped reading is not a measurement.
        assert!(load_file_at(&f, 1_000, true).is_empty());
        // The reset-only read keeps it, because the reset is still a fact.
        let keep = load_file_at(&f, 1_000, false);
        assert_eq!(keep["acct"].five_h_reset, Some(5_000));
        // A window whose reset has PASSED is still dropped either way: that one
        // is not a fact about the future.
        let gone = load_file_at(&f, 6_000, false);
        assert_eq!(gone["acct"].five_h_reset, None);
        assert_eq!(gone["acct"].seven_d_reset, Some(9_000));
    }
}

#[cfg(test)]
mod name_change_tests {
    use super::*;

    fn entry(pct: f64, at: i64) -> Entry {
        Entry {
            five_h: Some(pct),
            at,
            ..Default::default()
        }
    }

    /// The remembered readings are keyed by account name, so a rename has to
    /// carry them - in EVERY tool's file, because the cache is sharded per tool
    /// and an account can hold a slot in more than one.
    #[test]
    fn a_rename_carries_the_remembered_readings_of_every_tool() {
        let root = tempfile::tempdir().unwrap();
        let paths = Paths::rooted(root.path());
        update_for(&paths, "claude-code", &[("work".into(), entry(10.0, 1))]);
        update_for(&paths, "codex", &[("work".into(), entry(90.0, 1))]);
        update_for(&paths, "codex", &[("other".into(), entry(30.0, 1))]);

        rename_account(&paths, "work", "work2");

        let claude = load_for(&paths, "claude-code");
        assert!(!claude.contains_key("work"), "the old name is gone");
        assert_eq!(claude["work2"].five_h, Some(10.0), "the reading followed");
        let codex = load_for(&paths, "codex");
        assert!(!codex.contains_key("work"), "and in the second tool's file");
        assert_eq!(codex["work2"].five_h, Some(90.0));
        assert_eq!(codex["other"].five_h, Some(30.0), "others are untouched");
    }

    /// Without this the numbers outlive the account and are shown under its
    /// name - and then handed to whatever account is registered under that name
    /// next.
    #[test]
    fn forgetting_an_account_drops_its_remembered_readings() {
        let root = tempfile::tempdir().unwrap();
        let paths = Paths::rooted(root.path());
        update_for(&paths, "claude-code", &[("work".into(), entry(10.0, 1))]);
        update_for(&paths, "codex", &[("work".into(), entry(90.0, 1))]);
        update_for(&paths, "codex", &[("keep".into(), entry(30.0, 1))]);

        forget_account(&paths, "work");

        assert!(load_for(&paths, "claude-code").is_empty());
        let codex = load_for(&paths, "codex");
        assert!(!codex.contains_key("work"), "gone from every tool's file");
        assert_eq!(codex["keep"].five_h, Some(30.0), "others are untouched");
    }
}