swarmy 0.2.12

Real-time analytics dashboard for coding agents (Claude Code, Antigravity, Codex): live swarm, history, API-equivalent spend, weekly limits, and a vault for OAuth logins
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
//! `swarmy limits`: where each account's limit went, and when it runs out (the analysis itself
//! lives in `crate::limits`). `--seat current` narrows it to the account of the Claude Code that
//! runs the command, for agents; `--format json` adds, to the analysis, the seats holding each
//! account, its saved logins, each window's level, when it runs out, where it ends at this pace,
//! and the guard's line (`[guard]`).

use chrono::{DateTime, Local, Utc};
use serde::Serialize;

use crate::app::context::Ctx;
use crate::core::guard::{Lines, State};
use crate::core::ids::{AccountId, ProjectKey, SeatId};
use crate::core::limits::{Level, Share};
use crate::core::units::{Pct, Usd};
use crate::limits::{AccountReport, WindowReport, all_reports};
use crate::ui::fmt;
use crate::ui::mask;
use crate::ui::style::Tone;
use crate::ui::table::{Align, Cell, Table};

use super::Format;

/// What `swarmy limits` was asked for.
pub struct LimitsArgs<'a> {
    pub format: Format,
    pub top: usize,
    /// A seat (label, id, dir, or `current`): only the account it holds now.
    pub seat: Option<&'a str>,
    /// An account (uuid, email, saved login label): only it.
    pub account: Option<&'a str>,
}

/// The seat `--seat` names; `current` is the one of the Claude Code that runs us.
fn seat_named<'c>(ctx: &'c Ctx, name: &str) -> anyhow::Result<&'c crate::claude::seats::Seat> {
    if name == "current" {
        let dir = crate::statusline::current_config_dir(&ctx.dirs.home);
        return ctx.resolve_seat(&dir.to_string_lossy());
    }
    ctx.resolve_seat(name)
}

/// The account a seat holds now, as the dashboard knows it.
fn account_in(ctx: &Ctx, seat: &SeatId) -> Option<AccountId> {
    ctx.seats
        .iter()
        .zip(&ctx.seat_info)
        .find(|(s, _)| &s.id == seat)
        .and_then(|(_, si)| si.account.as_ref().map(|a| a.id()))
}

pub fn run(ctx: &Ctx, a: &LimitsArgs) -> anyhow::Result<()> {
    let (idx, _) = ctx.index()?;
    let mut reports = all_reports(&ctx.limits_inputs(&idx)?, &idx)?;
    // Resolved once, here at the edge; a name that fits nothing is an error that says so.
    if let Some(name) = a.seat {
        let seat = seat_named(ctx, name)?;
        let held = account_in(ctx, &seat.id);
        reports.retain(|r| held.as_ref() == Some(&r.account));
    }
    if let Some(name) = a.account {
        let id = ctx.resolve_account(&idx, name)?;
        reports.retain(|r| r.account == id);
    }
    let logins = crate::vault::saved_logins(&ctx.dirs.vault_dir()).unwrap_or_else(|e| {
        crate::diag::log("limits", &format!("vault unreadable: {e:#}"));
        Vec::new()
    });
    let lines: Vec<Lines> = reports
        .iter()
        .map(|r| crate::guard::lines_of(&r.account, &ctx.config, &logins))
        .collect();
    if ctx.mask {
        // The analysis is unmasked; what is printed is masked here. Shares name projects by
        // their dir: the last component only.
        for r in &mut reports {
            r.name = ctx.shown_account_name(r.account.as_str());
            for w in &mut r.windows {
                w.reference = w.reference_id.as_deref().map(|a| ctx.shown_account_name(a));
                for s in &mut w.shares {
                    s.project = ProjectKey::from_stored(ctx.show_path(s.project.as_str()));
                    s.name = ctx.show_path(&s.name);
                }
            }
        }
    }
    match a.format {
        Format::Json => {
            let out: Vec<AccountOut> = reports
                .iter_mut()
                .zip(&lines)
                .map(|(r, l)| account_out(ctx, r, l, &logins, a.top))
                .collect();
            println!("{}", serde_json::to_string_pretty(&out)?);
            return Ok(());
        }
        Format::Csv => {
            print!("{}", csv(ctx, &reports, &lines));
            return Ok(());
        }
        Format::Table => {}
    }
    let p = &ctx.painter;
    if reports.is_empty() {
        let none = if a.seat.is_some() || a.account.is_some() {
            "No limit readings for that account yet."
        } else {
            "No limit readings yet: Claude Code caches them after it shows usage. Run /usage in Claude Code once."
        };
        println!("{}", p.paint(none, Tone::Dim));
        return Ok(());
    }
    for (i, (rep, l)) in reports.iter().zip(&lines).enumerate() {
        if i > 0 {
            println!();
        }
        let email = ctx
            .email(rep.account.as_str())
            .map(|e| format!(" · {e}"))
            .unwrap_or_default();
        let org = match ctx
            .org_name(rep.account.as_str())
            .filter(|o| o != &rep.name)
        {
            Some(o) => format!(" · {o}"),
            None => String::new(),
        };
        let tier = rep
            .tier
            .as_deref()
            .map(|t| format!(" · {}", crate::claude::config_json::format_tier_label(t)))
            .unwrap_or_default();
        println!(
            "{} {}{}",
            p.paint("ACCOUNT", Tone::Header),
            p.paint(&rep.name, Tone::Bold),
            p.paint(&format!("{email}{org}{tier}"), Tone::Dim)
        );
        let guarded = guarded_seats(ctx, &rep.account);
        for w in &rep.windows {
            print_window(ctx, w, a.top);
            print_guard(ctx, w, l, &guarded);
        }
    }
    println!();
    println!(
        "{}",
        p.paint(
            "≈ estimates: limit usage is assumed proportional to API-equivalent cost.",
            Tone::Dim
        )
    );
    Ok(())
}

/// The seats holding an account now.
fn seats_of<'c>(ctx: &'c Ctx, account: &AccountId) -> Vec<&'c crate::claude::seats::Seat> {
    ctx.seats
        .iter()
        .zip(&ctx.seat_info)
        .filter(|(_, si)| si.account.as_ref().is_some_and(|a| &a.id() == account))
        .map(|(s, _)| s)
        .collect()
}

/// The labels of the seats holding an account that have the guard hook.
fn guarded_seats(ctx: &Ctx, account: &AccountId) -> Vec<String> {
    seats_of(ctx, account)
        .into_iter()
        .filter(|s| super::setup::seat_has_guard(s))
        .map(|s| s.label.clone())
        .collect()
}

/// Where the guard stands on a window, from its latest reading (what the hook acts on): none
/// when the window has no line.
fn guard_of(w: &WindowReport, lines: &Lines, now: DateTime<Utc>) -> Option<GuardOut> {
    let line = lines.line(w.reading.kind)?;
    let state = if w.reset_passed {
        State::Go
    } else {
        crate::core::guard::verdict(&[w.reading], lines, now).state
    };
    Some(GuardOut {
        line,
        wrap_up_at: lines.wrap_up_at(w.reading.kind).unwrap_or(line),
        state,
    })
}

fn print_guard(ctx: &Ctx, w: &WindowReport, lines: &Lines, guarded: &[String]) {
    let Some(g) = guard_of(w, lines, ctx.now) else {
        return;
    };
    let p = &ctx.painter;
    let seats = if guarded.is_empty() {
        "in no guarded seat".to_string()
    } else {
        format!("guarded seats: {}", guarded.join(", "))
    };
    let (what, tone) = match g.state {
        State::Go => ("", Tone::Dim),
        State::WrapUp => (" · agents told to wrap up", Tone::Warn),
        State::Stop => (" · agents stopped", Tone::Bad),
    };
    println!(
        "{}{}",
        " ".repeat(16),
        p.paint(
            &format!(
                "guard: wrap up from {}, stop at {} ({seats}){what}",
                fmt::pct(g.wrap_up_at.get()),
                fmt::pct(g.line.get())
            ),
            tone
        )
    );
}

/// An account in `--format json`: the analysis, and what an agent or a script asks next.
#[derive(Serialize)]
struct AccountOut<'a> {
    account_uuid: &'a AccountId,
    name: &'a str,
    tier: Option<&'a str>,
    email: Option<String>,
    org: Option<String>,
    /// The seats holding the account now.
    seats: Vec<SeatOut>,
    /// The labels of its saved logins.
    logins: Vec<String>,
    windows: Vec<WindowOut<'a>>,
}

#[derive(Serialize)]
struct SeatOut {
    id: SeatId,
    label: String,
    guarded: bool,
}

#[derive(Serialize)]
struct WindowOut<'a> {
    #[serde(flatten)]
    report: &'a WindowReport,
    /// `ok` (under 60%), `warn`, `bad` (85% and more), `reached` (100%).
    level: &'static str,
    /// When it runs out at the current pace; none when it lasts until the reset.
    runs_out_at: Option<DateTime<Utc>>,
    /// Where it ends at the reset at the current pace (can pass 100).
    at_reset: Option<Pct>,
    /// Projects past `--top`, left out of `shares`.
    #[serde(skip_serializing_if = "is_zero")]
    shares_left_out: usize,
    /// The guard's line on this window (`[guard]`), when it has one.
    guard: Option<GuardOut>,
}

fn is_zero(n: &usize) -> bool {
    *n == 0
}

#[derive(Serialize)]
struct GuardOut {
    line: Pct,
    wrap_up_at: Pct,
    state: State,
}

fn level_key(l: Level) -> &'static str {
    match l {
        Level::Ok => "ok",
        Level::Warn => "warn",
        Level::Bad => "bad",
        Level::Reached => "reached",
    }
}

fn account_out<'a>(
    ctx: &Ctx,
    r: &'a mut AccountReport,
    lines: &Lines,
    logins: &[crate::vault::Login],
    top: usize,
) -> AccountOut<'a> {
    let left_out: Vec<usize> = r
        .windows
        .iter_mut()
        .map(|w| {
            let n = w.shares.len().saturating_sub(top);
            w.shares.truncate(top);
            n
        })
        .collect();
    let seats = seats_of(ctx, &r.account)
        .into_iter()
        .map(|s| SeatOut {
            id: s.id.clone(),
            label: s.label.clone(),
            guarded: super::setup::seat_has_guard(s),
        })
        .collect();
    let saved = logins
        .iter()
        .filter(|l| l.account_uuid.as_deref().map(AccountId::new).as_ref() == Some(&r.account))
        .map(|l| mask::login_label(&l.label, l.email.as_deref(), ctx.mask))
        .collect();
    let r: &'a AccountReport = r;
    AccountOut {
        account_uuid: &r.account,
        name: &r.name,
        tier: r.tier.as_deref(),
        email: ctx.email(r.account.as_str()),
        org: ctx.org_name(r.account.as_str()),
        seats,
        logins: saved,
        windows: r
            .windows
            .iter()
            .zip(left_out)
            .map(|(w, n)| WindowOut {
                report: w,
                level: level_key(w.level()),
                runs_out_at: w.runs_out_at,
                at_reset: if w.reset_passed {
                    None
                } else {
                    w.projection_at_reset(ctx.now)
                },
                shares_left_out: n,
                guard: guard_of(w, lines, ctx.now),
            })
            .collect(),
    }
}

/// `--format csv`: one row per account and window.
fn csv(ctx: &Ctx, reports: &[AccountReport], lines: &[Lines]) -> String {
    let cell = |s: &str| {
        if s.contains([',', '"', '\n']) {
            format!("\"{}\"", s.replace('"', "\"\""))
        } else {
            s.to_string()
        }
    };
    let time = |t: Option<DateTime<Utc>>| t.map_or(String::new(), |t| t.to_rfc3339());
    let num = |p: Option<Pct>| p.map_or(String::new(), |p| format!("{:.2}", p.get()));
    let mut out = String::from(
        "account_uuid,name,window,reading,reading_at,estimate_now,level,resets_at,runs_out_at,at_reset,cost_in_window_usd,guard_line,guard_state\n",
    );
    for (r, l) in reports.iter().zip(lines) {
        for w in &r.windows {
            let g = guard_of(w, l, ctx.now);
            let state = g.as_ref().map(|g| match g.state {
                State::Go => "go",
                State::WrapUp => "wrap_up",
                State::Stop => "stop",
            });
            out.push_str(&format!(
                "{},{},{},{:.2},{},{:.2},{},{},{},{},{:.6},{},{}\n",
                cell(r.account.as_str()),
                cell(&r.name),
                w.reading.kind.key(),
                w.reading.utilization,
                w.reading.fetched_at.to_rfc3339(),
                w.estimate_now.get(),
                level_key(w.level()),
                w.window.end.to_rfc3339(),
                time(w.runs_out_at),
                num(if w.reset_passed {
                    None
                } else {
                    w.projection_at_reset(ctx.now)
                }),
                w.cost_in_window.get(),
                num(g.as_ref().map(|g| g.line)),
                state.unwrap_or(""),
            ));
        }
    }
    out
}

fn print_window(ctx: &Ctx, w: &WindowReport, top: usize) {
    let p = &ctx.painter;
    let r = &w.reading;
    let shown = w.estimate_now.get();
    let tone = Tone::of_utilization(shown);
    let label = format!("{:<13}", r.kind.label());
    let main = if w.reset_passed {
        format!(
            "{} ≈{} (new window since {}, no reading yet)",
            fmt::gauge(shown / 100.0, 24),
            fmt::pct(shown),
            r.resets_at.with_timezone(&Local).format("%a %H:%M")
        )
    } else {
        format!(
            "{} {}  ≈{} now",
            fmt::gauge(shown / 100.0, 24),
            fmt::pct(r.utilization),
            fmt::pct(shown)
        )
    };
    println!("  {} {}", p.paint(&label, Tone::Bold), p.paint(&main, tone));
    let pad = " ".repeat(16);
    println!(
        "{pad}{}",
        p.paint(
            &format!(
                "resets {} (in {}) · reading {} old",
                w.window.end.with_timezone(&Local).format("%a %H:%M"),
                fmt::duration(w.window.end - ctx.now),
                fmt::duration(ctx.now - r.fetched_at)
            ),
            Tone::Dim
        )
    );
    if let Some(t) = w.manual_reset {
        println!(
            "{pad}{}",
            p.paint(
                &format!(
                    "limit reset by hand ≈{}; counting from there",
                    t.with_timezone(&Local).format("%a %H:%M")
                ),
                Tone::Accent
            )
        );
    }
    let mut burn = format!("burn {}/h", fmt::money(w.burn_usd_per_hour));
    if let Some(pph) = w.points_per_hour {
        burn.push_str(&format!(" ≈ {pph:.1}%/h"));
    }
    match w.eta {
        Some(d) if d.num_seconds() == 0 => burn.push_str(" · LIMIT REACHED"),
        Some(d) => burn.push_str(&format!(
            " → empty {} (in {})",
            (ctx.now + d).with_timezone(&Local).format("%a %H:%M"),
            fmt::duration(d)
        )),
        // No `eta` either because the window lasts, or because the pace is unknown (no usable
        // USD per point yet).
        None if w.points_per_hour.is_some() && w.burn_usd_per_hour > Usd::ZERO => {
            burn.push_str(" · lasts until reset")
        }
        None if w.burn_usd_per_hour > Usd::ZERO => burn.push_str(" · pace unknown"),
        None => {}
    }
    println!(
        "{pad}{}",
        p.paint(
            &burn,
            if w.eta.is_some() {
                Tone::Warn
            } else {
                Tone::Dim
            }
        )
    );
    if let (Some(u), Some(full)) = (w.usd_per_point, w.window_usd) {
        let src = match &w.reference {
            Some(r) => format!(" (reference: {r}, same plan)"),
            None => String::new(),
        };
        println!(
            "{pad}{}",
            p.paint(
                &format!(
                    "≈{}/pt · a full window ≈ {} API-equivalent{src}",
                    fmt::money(u),
                    fmt::money(full)
                ),
                Tone::Dim
            )
        );
    }
    if let (Some(v), Some(o)) = (w.visible_points, w.outside_points)
        && o >= Pct::new(2.0)
    {
        println!(
            "{pad}{}",
            p.paint(&format!("on this machine ≈{v:.1}% · elsewhere (claude.ai, desktop, other computers) ≈{o:.1}%"), Tone::Warn)
        );
    }
    if w.shares.is_empty() {
        return;
    }
    let mut t = Table::new(&[
        ("PROJECT", Align::Left),
        ("COST", Align::Right),
        ("SHARE", Align::Left),
        ("≈ LIMIT", Align::Right),
    ]);
    t.max_width = t.max_width.map(|m| m.saturating_sub(4));
    let max = w.shares.first().map(|s| s.share).unwrap_or(0.0);
    for s in w.shares.iter().take(top) {
        t.row(vec![
            Cell::new(s.name.clone()),
            Cell::new(fmt::money(s.cost)),
            Cell::tone(
                format!(
                    "{:<20} {}",
                    fmt::bar(if max > 0.0 { s.share / max } else { 0.0 }, 20),
                    fmt::pct(s.share * 100.0)
                ),
                Tone::Accent,
            ),
            Cell::tone(format!("≈{:.1}%", s.limit_points), Tone::Bold),
        ]);
    }
    if w.shares.len() > top {
        let rest: Vec<&Share> = w.shares.iter().skip(top).collect();
        t.row(vec![
            Cell::tone(format!("… {} more", rest.len()), Tone::Dim),
            Cell::tone(
                fmt::money(rest.iter().map(|s| s.cost).sum::<Usd>()),
                Tone::Dim,
            ),
            Cell::new(""),
            Cell::tone(
                format!("≈{:.1}%", rest.iter().map(|s| s.limit_points).sum::<Pct>()),
                Tone::Dim,
            ),
        ]);
    }
    if let Some(o) = w.outside_points.filter(|o| *o >= Pct::new(2.0)) {
        t.row(vec![
            Cell::tone("(elsewhere)", Tone::Warn),
            Cell::tone("?", Tone::Dim),
            Cell::new(""),
            Cell::tone(format!("≈{o:.1}%"), Tone::Warn),
        ]);
    }
    for line in t.render(p).lines() {
        println!("    {line}");
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::Dirs;
    use crate::core::pricing::PriceBook;
    use crate::index::SeatInfo;
    use crate::index::scenarios::{World, account, assistant, at, owner, weekly};
    use crate::procs::ProcTable;
    use crate::ui::style::{ColorChoice, Painter};

    /// Two seats: work holds acc-a (week at 82%), lab holds acc-b (week at 30%); the guard stops
    /// agents at 85% of the week, so acc-a is in its wrap-up zone (from 80%).
    fn setup() -> (World, Ctx, Vec<AccountReport>) {
        let w = World::new(&["work", "lab"]);
        let resets = "2026-11-24T00:00:00Z";
        let seat = |label: &str, acc: &str, used: f64| SeatInfo {
            seat: Default::default(),
            label: label.into(),
            account: Some(account(acc, "2026-11-01T00:00:00Z")),
            switched_at: None,
            utilization: Some(weekly(acc, "2026-11-20T00:00:00Z", used, resets)),
        };
        let info = vec![seat("work", "acc-a", 82.0), seat("lab", "acc-b", 30.0)];
        // acc-a spent in two projects this week ($1 per 500 000 input tokens of Sonnet 5.5).
        let req = |id: &str, cwd: &str| {
            assistant(
                id,
                "2026-11-19T06:00:00Z",
                "claude-sonnet-5-5",
                cwd,
                (500_000, 0),
                &[],
            )
        };
        w.append(
            "work",
            "s1",
            &[owner("acc-a"), req("q1", "/w/shop"), req("q2", "/w/blog")],
        );
        let mut idx = w.index("i.sqlite");
        w.refresh(&mut idx, &info, &PriceBook::builtin());
        let ctx = Ctx {
            dirs: Dirs {
                data: w.dir.path().join("data"),
                config: w.dir.path().join("config"),
                home: w.dir.path().to_path_buf(),
            },
            config: toml::from_str("[guard]\nweek = 85\n").unwrap(),
            seats: w.seats.clone(),
            seat_info: info,
            prices: PriceBook::builtin(),
            procs: ProcTable::empty(),
            painter: Painter::new(ColorChoice::Never),
            mask: false,
            now: at("2026-11-20T12:00:00Z"),
            login_labels: Default::default(),
            login_tiers: Default::default(),
            problems: Vec::new(),
        };
        let reports = all_reports(&ctx.limits_inputs(&idx).unwrap(), &idx).unwrap();
        (w, ctx, reports)
    }

    fn lines_for(ctx: &Ctx, reports: &[AccountReport]) -> Vec<Lines> {
        reports
            .iter()
            .map(|r| crate::guard::lines_of(&r.account, &ctx.config, &[]))
            .collect()
    }

    #[test]
    fn a_seat_names_the_account_it_holds() {
        let (_w, ctx, _) = setup();
        let lab = seat_named(&ctx, "lab").unwrap();
        assert_eq!(account_in(&ctx, &lab.id), Some(AccountId::new("acc-b")));
        assert!(
            seat_named(&ctx, "nowhere").is_err(),
            "an unknown seat says so"
        );
    }

    #[test]
    fn json_says_what_an_agent_asks_next() {
        let (_w, ctx, mut reports) = setup();
        let lines = lines_for(&ctx, &reports);
        let out: Vec<AccountOut> = reports
            .iter_mut()
            .zip(&lines)
            .map(|(r, l)| account_out(&ctx, r, l, &[], 8))
            .collect();
        let v = serde_json::to_value(&out).unwrap();
        let a = v
            .as_array()
            .unwrap()
            .iter()
            .find(|a| a["account_uuid"] == "acc-a")
            .unwrap();
        assert_eq!(a["seats"][0]["label"], "work");
        assert_eq!(a["seats"][0]["guarded"], false);
        let week = &a["windows"][0];
        // What was there stays.
        assert_eq!(week["reading"]["utilization"], 82.0);
        assert_eq!(week["estimate_now"], 82.0);
        // What is new.
        assert_eq!(week["level"], "warn");
        assert!(week.get("runs_out_at").is_some(), "{week}");
        assert!(week.get("at_reset").is_some(), "{week}");
        assert_eq!(week["shares"].as_array().unwrap().len(), 2);
        assert!(week.get("shares_left_out").is_none(), "nothing left out");
        assert_eq!(
            week["guard"],
            serde_json::json!({"line": 85.0, "wrap_up_at": 80.0, "state": "wrap_up"})
        );
        let b = v
            .as_array()
            .unwrap()
            .iter()
            .find(|a| a["account_uuid"] == "acc-b")
            .unwrap();
        assert_eq!(b["windows"][0]["guard"]["state"], "go");
    }

    #[test]
    fn top_holds_for_json_too() {
        let (_w, ctx, mut reports) = setup();
        let lines = lines_for(&ctx, &reports);
        let a = reports
            .iter_mut()
            .zip(&lines)
            .find(|(r, _)| r.account.as_str() == "acc-a")
            .unwrap();
        let v = serde_json::to_value(account_out(&ctx, a.0, a.1, &[], 1)).unwrap();
        assert_eq!(v["windows"][0]["shares"].as_array().unwrap().len(), 1);
        assert_eq!(v["windows"][0]["shares_left_out"], 1);
    }

    #[test]
    fn csv_has_one_row_per_account_and_window() {
        let (_w, ctx, reports) = setup();
        let text = csv(&ctx, &reports, &lines_for(&ctx, &reports));
        let rows: Vec<&str> = text.lines().collect();
        assert!(
            rows[0].starts_with("account_uuid,name,window,reading,"),
            "{text}"
        );
        assert_eq!(rows.len(), 3, "{text}");
        let a = rows.iter().find(|r| r.starts_with("acc-a,")).unwrap();
        assert!(a.contains(",seven_day,82.00,"), "{a}");
        assert!(a.ends_with(",85.00,wrap_up"), "{a}");
    }
}