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
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
//! `swarmy doctor`: what was found, what is readable, what looks off.

use crate::claude::registry::{self, LiveSession, SessionStatus};
use crate::claude::transcript::ParseStats;
use crate::core::harness::Harness;
use crate::core::period::Period;
use crate::index::query::{Counted, Filter};
use crate::ui::fmt;
use crate::ui::style::Tone;
use crate::ui::table::{Align, Cell, Table};

use crate::app::context::Ctx;
use crate::index::Index;

pub fn run(ctx: &Ctx) -> anyhow::Result<()> {
    let p = &ctx.painter;
    let ok = |s: &str| format!("{} {s}", p.paint("[ OK ]", Tone::Good));
    let warn = |s: &str| format!("{} {s}", p.paint("[WARN]", Tone::Warn));
    let info = |s: &str| format!("{} {s}", p.paint("[ .. ]", Tone::Dim));

    println!("{}", p.paint("SEATS (config/data dirs)", Tone::Header));
    if ctx.seats.is_empty() {
        println!(
            "{}",
            warn(
                "no agent config dir found (looked for ~/.claude*, ~/.gemini/antigravity-cli, ~/.codex*; add [[seat]] to config.toml)"
            )
        );
    }
    // What could not be read: numbers below may be off because of it.
    for problem in &ctx.problems {
        println!("{}", warn(problem));
    }
    let mut agy_cache = crate::agy::live::AgyLiveCache::default();
    let mut codex_cache = crate::codex::live::CodexLiveCache::default();
    let mut live_by_seat: std::collections::HashMap<crate::core::ids::SeatId, Vec<LiveSession>> =
        Default::default();
    for s in &ctx.seats {
        let sessions = match s.harness {
            Harness::Claude => registry::live_sessions(&s.id, &s.sessions_dir(), &ctx.procs),
            Harness::Agy => {
                let locked = agy_cache.locked_conversations(&s.dir);
                agy_cache.resolve_procs(&s.dir, &locked);
                let metas = crate::agy::summaries::read_all(&s.dir);
                crate::agy::live::build_live_sessions(
                    &s.id, &locked, &metas, &agy_cache, &ctx.procs, ctx.now,
                )
            }
            Harness::Codex => {
                let open = codex_cache.open_threads(&s.dir);
                codex_cache.resolve_procs(&s.dir, &open);
                codex_cache.live_sessions(&s.id, &s.dir, &open, ctx.now)
            }
        };
        live_by_seat.insert(s.id.clone(), sessions);
    }
    let mut t = Table::new(&[
        ("SEAT", Align::Left),
        ("HARNESS", Align::Left),
        ("DIR", Align::Left),
        ("ACCOUNT", Align::Left),
        ("PLAN", Align::Left),
        ("LIVE", Align::Right),
        ("FOUND BY", Align::Left),
    ]);
    t.flex_col = 2;
    for (s, si) in ctx.seats.iter().zip(&ctx.seat_info) {
        let live_n = live_by_seat.get(&s.id).map_or(0, Vec::len);
        let acct = si
            .account
            .as_ref()
            .map(|a| ctx.shown_account_name(a.id().as_str()))
            .unwrap_or_else(|| "(not logged in)".into());
        let plan = si
            .account
            .as_ref()
            .and_then(|a| a.plan_label())
            .unwrap_or_default();
        t.row(vec![
            Cell::tone(&s.label, Tone::Bold),
            Cell::tone(s.harness.key(), Tone::Dim),
            Cell::new(ctx.show_path(&s.dir.to_string_lossy())),
            Cell::new(acct),
            Cell::tone(plan, Tone::Dim),
            Cell::new(live_n.to_string()),
            Cell::tone(s.found_by.join(", "), Tone::Dim),
        ]);
    }
    println!("{}", t.render(p));

    // The optional status line: exact limits after every response (Claude Code seats).
    let claude_seats = ctx
        .seats
        .iter()
        .filter(|s| s.harness.supports_statusline())
        .count();
    let with: Vec<&str> = ctx
        .seats
        .iter()
        .filter(|s| {
            s.harness.supports_statusline()
                && matches!(
                    super::setup::seat_status_line(s),
                    super::setup::StatusLine::Swarmy { .. }
                )
        })
        .map(|s| s.label.as_str())
        .collect();
    if claude_seats > 0 {
        println!();
        if with.is_empty() {
            println!(
                "{}",
                p.paint(
                    "limits come from Claude Code's cached readings (≈ between them); optional: `swarmy setup` adds a status line for exact ones",
                    Tone::Dim
                )
            );
        } else {
            println!(
                "{}",
                ok(&format!(
                    "swarmy status line in: {} (exact limits after every response)",
                    with.join(", ")
                ))
            );
        }
    }

    // Accounts shared by several seats share one limit.
    let mut by_acct: std::collections::BTreeMap<String, Vec<&str>> = Default::default();
    for si in &ctx.seat_info {
        if let Some(a) = &si.account {
            by_acct
                .entry(a.id().to_string())
                .or_default()
                .push(&si.label);
        }
    }
    println!();
    println!(
        "{}",
        ok(&format!(
            "{} seats, {} accounts",
            ctx.seats.len(),
            by_acct.len()
        ))
    );
    for (acct, seats) in &by_acct {
        if seats.len() > 1 {
            println!(
                "{}",
                info(&format!(
                    "seats {} are logged into the same account ({}): they share one limit",
                    seats.join(" + "),
                    ctx.shown_account_name(acct)
                ))
            );
        }
    }

    println!();
    println!("{}", p.paint("LIVE SESSIONS", Tone::Header));
    let mut any = false;
    for s in &ctx.seats {
        let sessions = match live_by_seat.get(&s.id) {
            Some(v) => v.as_slice(),
            None => &[],
        };
        for l in sessions {
            any = true;
            let (st, tone) = match &l.status {
                SessionStatus::Busy => ("busy".to_string(), Tone::Good),
                SessionStatus::Idle => ("idle".to_string(), Tone::Dim),
                SessionStatus::Waiting(w) => (format!("NEEDS YOU: {w}"), Tone::Warn),
                SessionStatus::Other(o) => (o.clone(), Tone::Plain),
            };
            let ver = match l.version.as_deref() {
                Some(v) if !v.is_empty() => format!(" · v{v}"),
                Some(_) | None => String::new(),
            };
            let pid_s = if l.pid > 0 {
                format!("pid {} · ", l.pid)
            } else {
                String::new()
            };
            let raw_name = l
                .name
                .clone()
                .unwrap_or_else(|| l.session_id.short().to_string());
            let name = if raw_name.chars().count() > 24 {
                let mut t: String = raw_name.chars().take(23).collect();
                t.push('…');
                t
            } else {
                raw_name
            };
            println!(
                "  {} {:<24} {:<10} {} {}",
                p.paint("●", tone),
                name,
                s.label,
                p.paint(&st, tone),
                p.paint(&format!("{pid_s}{}{ver}", ctx.show_path(&l.cwd)), Tone::Dim)
            );
        }
    }
    if !any {
        println!("  {}", p.paint("none", Tone::Dim));
    }
    let unregistered = ctx
        .procs
        .claude
        .iter()
        .filter(|c| c.config_dir.is_none() && !ctx.seats.iter().any(|s| s.is_default))
        .count();
    if unregistered > 0 {
        println!(
            "{}",
            warn(&format!(
                "{unregistered} claude processes use the default dir, which was not found"
            ))
        );
    }

    println!();
    println!("{}", p.paint("INDEX", Tone::Header));
    let (mut idx, stats) = ctx.index()?;
    println!(
        "{}",
        ok(&format!(
            "{} ({})",
            ctx.show_path(&ctx.dirs.index_file().to_string_lossy()),
            fmt::human_bytes(
                std::fs::metadata(ctx.dirs.index_file())
                    .map(|m| m.len())
                    .unwrap_or(0)
            )
        ))
    );
    println!(
        "{}",
        ok(&format!(
            "{} transcripts · {} requests · {} tool calls · {} sessions · {} agents",
            fmt::count(stats.files_total as u64),
            fmt::count(idx.count(Counted::Requests)?),
            fmt::count(idx.count(Counted::ToolCalls)?),
            fmt::count(idx.count(Counted::Sessions)?),
            fmt::count(idx.count(Counted::Agents)?)
        ))
    );
    println!(
        "{}",
        info(&format!(
            "this run read {} files, {:.1} MB in {:.2}s",
            stats.files_read,
            stats.bytes_read as f64 / 1e6,
            stats.elapsed.as_secs_f64()
        ))
    );
    let (empty_lines, hidden) = empty_seats(ctx, &idx, &live_by_seat)?;
    for line in empty_lines {
        println!("{}", info(&line));
    }
    let mut ps = ParseStats::default();
    for (t, n) in idx.record_types()? {
        if t == crate::claude::transcript::MALFORMED {
            ps.malformed = n;
        } else {
            ps.by_type.insert(t, n);
        }
    }
    if ps.malformed > 0 {
        println!(
            "{}",
            warn(&format!(
                "{} transcript records are damaged (no JSON, or numbers out of range): what they held is not counted",
                fmt::count(ps.malformed)
            ))
        );
    }
    if let Some(n) = idx.meta("rebuild_refused")?.filter(|n| n != "0") {
        println!(
            "{}",
            warn(&format!(
                "a cache rebuild left out {n} kept rows (of transcripts that are gone) the new schema refused; \
                 their spend is missing"
            ))
        );
    }
    for (path, error, since) in idx.unreadable_files()? {
        println!(
            "{}",
            warn(&format!(
                "cannot read {} since {}: {error}; nothing of it is counted until it can be read",
                ctx.show_path(&path),
                crate::index::from_ms(since)
                    .with_timezone(&chrono::Local)
                    .format("%a %d %b %H:%M")
            ))
        );
    }
    let malformed = crate::claude::transcript::MALFORMED;
    let by_harness = idx.record_types_by_harness()?;
    let unknown: Vec<(&str, u64)> = by_harness
        .iter()
        .filter(|(h, t, _)| match h {
            Harness::Claude => !crate::claude::transcript::is_known_type(t),
            Harness::Agy => {
                !crate::agy::transcript::KNOWN_TYPES.contains(&t.as_str()) && t != malformed
            }
            Harness::Codex => {
                !crate::codex::rollout::KNOWN_TYPES.contains(&t.as_str()) && t != malformed
            }
        })
        .map(|(_, t, n)| (t.as_str(), *n))
        .collect();
    if unknown.is_empty() {
        println!("{}", ok("every transcript record type is recognised"));
    } else {
        let list: Vec<String> = unknown.iter().map(|(t, n)| format!("{t} ({n})")).collect();
        println!(
            "{}",
            warn(&format!(
                "unrecognised record types (Claude Code format moved on?): {}",
                list.join(", ")
            ))
        );
    }
    let week = Period::Days(7).span(ctx.now, None);
    let total = idx.total(week, &Filter::default())?;
    if total.unpriced > 0 {
        println!(
            "{}",
            warn(&format!(
                "{} requests in the last 7 days have no price (see `swarmy prices`)",
                total.unpriced
            ))
        );
    }
    let (n, theirs, ours) = idx.cost_crosscheck(week)?;
    if n > 0 && theirs > 0.0 {
        let diff = (ours - theirs) / theirs * 100.0;
        let line = format!(
            "cost cross-check, {n} sessions of the last 7 days: Claude Code counted {}, transcripts give {} ({:+.1}%; background calls such as titles are not in transcripts)",
            fmt::money(theirs),
            fmt::money(ours),
            diff
        );
        println!(
            "{}",
            if diff.abs() <= 5.0 {
                ok(&line)
            } else {
                warn(&line)
            }
        );
    }
    let errs = idx.api_errors(week)?;
    if !errs.is_empty() {
        let list: Vec<String> = errs.iter().map(|(k, n)| format!("{k} ×{n}")).collect();
        println!(
            "{}",
            info(&format!(
                "API errors in the last 7 days: {}",
                list.join(", ")
            ))
        );
    }

    println!();
    println!("{}", p.paint("STORAGE", Tone::Header));
    idx.sample_storage(ctx.now.with_timezone(&chrono::Local).date_naive())?;
    for line in storage(ctx, &mut idx)? {
        println!("{line}");
    }

    println!();
    println!("{}", p.paint("LIMIT READINGS", Tone::Header));
    let readings = ctx.latest_readings(&idx)?;
    if readings.is_empty() && hidden.contains(&Harness::Claude) {
        // A machine without Claude Code in use (its seats are empty): nothing to read.
        println!(
            "{}",
            info("no Claude Code seat in use: no limit readings to show")
        );
    } else if readings.is_empty() {
        println!(
            "{}",
            warn("no cached utilization in any .claude.json (open /usage in Claude Code once)")
        );
    }
    for (acct, rs) in readings {
        for r in rs {
            println!(
                "{}",
                ok(&format!(
                    "{} {} {} · resets {} · reading {} old",
                    ctx.shown_account_name(&acct),
                    r.kind.label(),
                    fmt::pct(r.utilization),
                    r.resets_at
                        .with_timezone(&chrono::Local)
                        .format("%a %d %b %H:%M"),
                    fmt::duration(ctx.now - r.fetched_at)
                ))
            );
        }
    }
    println!();
    println!("{}", p.paint("GUARD", Tone::Header));
    let seats: Vec<GuardSeat> = ctx
        .seats
        .iter()
        .filter(|s| s.harness.supports_statusline())
        .map(|s| GuardSeat {
            label: &s.label,
            guarded: super::setup::seat_has_guard(s),
            status_line: matches!(
                super::setup::seat_status_line(s),
                super::setup::StatusLine::Swarmy { .. }
            ),
        })
        .collect();
    let logins = crate::vault::saved_logins(&ctx.dirs.vault_dir()).unwrap_or_else(|e| {
        crate::diag::log("doctor", &format!("vault unreadable: {e:#}"));
        Vec::new()
    });
    let mut accounts: Vec<crate::core::ids::AccountId> = ctx
        .seat_info
        .iter()
        .filter_map(|si| si.account.as_ref().map(|a| a.id()))
        .chain(
            logins
                .iter()
                .filter(|l| l.harness == Harness::Claude)
                .filter_map(|l| l.account_uuid.as_deref())
                .map(crate::core::ids::AccountId::new),
        )
        .collect();
    accounts.sort();
    accounts.dedup();
    let named: Vec<(crate::core::ids::AccountId, String)> = accounts
        .into_iter()
        .map(|a| {
            let name = ctx.shown_account_name(a.as_str());
            (a, name)
        })
        .collect();
    for line in guard_section(p, &ctx.config, &seats, &named, &logins) {
        println!("{line}");
    }

    println!();
    println!("{}", p.paint("CONFIG", Tone::Header));
    let cfg = ctx.dirs.config_file();
    println!(
        "{}",
        if cfg.exists() {
            ok(&ctx.show_path(&cfg.to_string_lossy()))
        } else {
            info(&format!(
                "{} (not present; defaults in use)",
                ctx.show_path(&cfg.to_string_lossy())
            ))
        }
    );
    Ok(())
}

/// A Claude Code seat as the GUARD section sees it.
struct GuardSeat<'a> {
    label: &'a str,
    guarded: bool,
    status_line: bool,
}

/// The GUARD section: which seats have the guard hook, what keeps it from working, and the line
/// of every account as the hook itself resolves it (`guard::lines_of`), so what doctor says is
/// what the hook does.
fn guard_section(
    p: &crate::ui::style::Painter,
    config: &crate::config::Config,
    seats: &[GuardSeat],
    accounts: &[(crate::core::ids::AccountId, String)],
    logins: &[crate::vault::Login],
) -> Vec<String> {
    use crate::core::limits::WindowKind;
    let ok = |s: &str| format!("{} {s}", p.paint("[ OK ]", Tone::Good));
    let warn = |s: &str| format!("{} {s}", p.paint("[WARN]", Tone::Warn));
    let info = |s: &str| format!("{} {s}", p.paint("[ .. ]", Tone::Dim));
    let mut out = Vec::new();
    let guarded: Vec<&str> = seats
        .iter()
        .filter(|s| s.guarded)
        .map(|s| s.label)
        .collect();
    if guarded.is_empty() {
        out.push(info(if config.guard.is_set() {
            "config.toml has [guard] lines, but no seat has the guard hook (`swarmy setup --guard`)"
        } else {
            "no seat has the guard hook (optional: `swarmy setup --guard` stops agents at a line you set)"
        }));
        if !config.guard.is_set() {
            return out;
        }
    } else {
        out.push(ok(&format!(
            "guard hook in: {} (before every tool call)",
            guarded.join(", ")
        )));
    }
    for s in seats.iter().filter(|s| s.guarded && !s.status_line) {
        out.push(warn(&format!(
            "guard in {} without the swarmy status line: it has no numbers there (`swarmy setup`)",
            s.label
        )));
    }
    if !config.guard.is_set() {
        out.push(warn(
            "no line in config.toml [guard]: the guard lets everything through",
        ));
        return out;
    }
    let mut matched: Vec<&str> = Vec::new();
    for (id, name) in accounts {
        let names = crate::guard::names_of(id, config, logins);
        matched.extend(config.guard.key_for(&names));
        let lines = config.guard.lines_for(&names);
        let parts: Vec<String> = [WindowKind::SevenDay, WindowKind::FiveHour]
            .into_iter()
            .filter_map(|k| {
                let line = lines.line(k)?;
                let word = if k == WindowKind::SevenDay {
                    "week"
                } else {
                    "5-hour"
                };
                let from = lines
                    .wrap_up_at(k)
                    .filter(|w| *w < line)
                    .map_or(String::new(), |w| {
                        format!(", wrap up from {}", fmt::pct(w.get()))
                    });
                Some(format!("{word} {}{from}", fmt::pct(line.get())))
            })
            .collect();
        out.push(if parts.is_empty() {
            info(&format!("{name}: no line"))
        } else {
            ok(&format!("{name}: agents stop at {}", parts.join("; ")))
        });
    }
    for k in config.guard.account.keys() {
        if !matched.contains(&k.as_str()) {
            out.push(warn(&format!(
                "[guard.account.{k}] names no account: use a saved login's label or email, an [accounts] name or the account uuid"
            )));
        }
    }
    out
}

/// The STORAGE section: the index's size, the raw window and the rollups, growth and the
/// 12-month projection against the budget, the seats' transcript retention, the last
/// compaction, and what waits (the one-time VACUUM, rows priced by an old long-context band).
/// One line per empty seat (`core::seat_use`): doctor hides nothing, it says which seats the
/// dashboard and `swarmy accounts` leave out, or why one is kept. Also returns the harnesses
/// the dashboard leaves out.
fn empty_seats(
    ctx: &Ctx,
    idx: &Index,
    live: &std::collections::HashMap<crate::core::ids::SeatId, Vec<LiveSession>>,
) -> anyhow::Result<(Vec<String>, Vec<Harness>)> {
    let vault_seats: Vec<crate::claude::seats::Seat> = ctx
        .seats
        .iter()
        .filter(|s| s.harness.supports_vault())
        .cloned()
        .collect();
    let read = crate::vault::Vault::open(&ctx.dirs.vault_dir())
        .and_then(|v| Ok((v.seat_states(&vault_seats)?, v.logins().to_vec())));
    let (states, logins) = match read {
        Ok(r) => r,
        Err(e) => {
            return Ok((
                vec![format!(
                    "empty seats not checked: the vault cannot be read ({e:#})"
                )],
                Vec::new(),
            ));
        }
    };
    let uses = ctx.seat_uses(idx, &states, |s| live.get(&s.id).map_or(0, Vec::len))?;
    let mut out = Vec::new();
    let mut hidden_harnesses = Vec::new();
    for h in Harness::ALL {
        let of: Vec<(&crate::claude::seats::Seat, bool)> = ctx
            .seats
            .iter()
            .zip(&uses)
            .filter(|(s, _)| s.harness == h)
            .map(|(s, u)| (s, u.is_empty()))
            .collect();
        let saved = logins.iter().filter(|l| l.harness == h).count();
        let empty: Vec<bool> = of.iter().map(|(_, e)| *e).collect();
        let hidden = crate::core::seat_use::hides_harness(&empty, saved);
        if hidden {
            hidden_harnesses.push(h);
        }
        for (s, _) in of.iter().filter(|(_, e)| *e) {
            let what = if hidden {
                "hidden in the dashboard (. shows it) and in swarmy accounts (--all lists it)"
            } else {
                "shown: its harness has other seats in use or saved logins that could go in"
            };
            out.push(format!(
                "seat '{}' ({}): empty (no login, no transcripts): {what}",
                s.label,
                ctx.show_path(&s.dir.to_string_lossy())
            ));
        }
    }
    Ok((out, hidden_harnesses))
}

fn storage(ctx: &Ctx, idx: &mut Index) -> anyhow::Result<Vec<String>> {
    let p = &ctx.painter;
    let ok = |s: &str| format!("{} {s}", p.paint("[ OK ]", Tone::Good));
    let warn = |s: &str| format!("{} {s}", p.paint("[WARN]", Tone::Warn));
    let info = |s: &str| format!("{} {s}", p.paint("[ .. ]", Tone::Dim));
    let hb = fmt::human_bytes;
    let local = |t: i64| crate::index::from_ms(t).with_timezone(&chrono::Local);
    let keep = ctx.keep_raw_days(None)?;
    let st = idx.storage_report()?;
    let mut out = Vec::new();
    out.push(ok(&format!(
        "index {} (+ WAL {}, {} free) · auto-vacuum {}",
        hb(st.file.bytes()),
        hb(st.wal_bytes),
        hb(st.file.free_bytes()),
        if st.file.incremental {
            "incremental"
        } else {
            "off"
        }
    )));
    // Since the last compaction's cutoff, or the oldest request when nothing was rolled up.
    let since = if st.rolled_until > 0 {
        Some(st.rolled_until)
    } else {
        st.oldest_raw
    };
    out.push(info(&format!(
        "detail   since {}: {} requests, {} tool calls ≈ {} · keep_raw_days = {keep}",
        since.map_or("-".into(), |t| local(t).format("%Y-%m-%d").to_string()),
        fmt::count(st.raw_requests),
        fmt::count(st.raw_tool_calls),
        hb(crate::core::storage::raw_bytes(
            st.raw_requests,
            st.raw_tool_calls
        ))
    )));
    out.push(info(&match st.archive_since {
        Some(t) => format!(
            "history  since {} in rollups: {} rows ≈ {}",
            local(t).format("%Y-%m-%d"),
            fmt::count(st.usage_rows + st.tool_rows + st.edit_rows),
            hb(st.rollup_bytes())
        ),
        None => "history  nothing rolled up yet: all of it is per-request detail".into(),
    }));
    let o = st.outlook(ctx.now, keep);
    let budget = ctx.config.storage.budget_mb << 20;
    let pace = if o.from_samples {
        format!("over the last {} days", st.samples.len())
    } else {
        "estimated from the requests a day".into()
    };
    let growth = format!(
        "growth   +{}/day {pace} → ≈ {} in 12 months (budget {} MB)",
        hb(o.per_day as u64),
        hb(o.in_12_months),
        ctx.config.storage.budget_mb
    );
    out.push(if o.in_12_months > budget {
        warn(&growth)
    } else {
        ok(&growth)
    });
    let mut retention: Vec<(u32, bool, usize)> = Vec::new();
    for (_, days, set) in ctx.retention() {
        match retention.iter_mut().find(|r| r.0 == days && r.1 == set) {
            Some(r) => r.2 += 1,
            None => retention.push((days, set, 1)),
        }
    }
    if !retention.is_empty() {
        let parts: Vec<String> = retention
            .iter()
            .map(|(days, set, n)| {
                format!(
                    "after {days} days on {n} seat{} ({})",
                    if *n == 1 { "" } else { "s" },
                    if *set {
                        "cleanupPeriodDays"
                    } else {
                        "cleanupPeriodDays, default"
                    }
                )
            })
            .collect();
        out.push(info(&format!(
            "claude   transcripts are deleted {}: older history exists only in this index",
            parts.join(", ")
        )));
    }
    out.push(info(&match &st.last_compaction {
        Some(c) => {
            let at = local(c.at);
            let day = if at.date_naive() == ctx.now.with_timezone(&chrono::Local).date_naive() {
                "today".to_string()
            } else {
                at.format("%a %d %b").to_string()
            };
            format!(
                "last compaction {day} {}, {} chunks, {} requests, {:.1} s · skipped as already rolled up: {} records",
                at.format("%H:%M"),
                c.chunks,
                fmt::count(c.requests),
                c.ms as f64 / 1000.0,
                fmt::count(st.skipped_records)
            )
        }
        None => "last compaction never: `swarmy compact --dry-run` shows what it would do".into(),
    }));
    if !ctx.config.storage.auto_compact {
        out.push(info(
            "auto_compact = false: the dashboard does not compact; `swarmy compact` does",
        ));
    }
    if let Some(why) = idx.vacuum_skipped()? {
        out.push(warn(&format!(
            "auto-vacuum off: the one-time VACUUM {why}; `swarmy compact --vacuum` runs it now"
        )));
    } else if !st.file.incremental && st.file.free_pages > 0 {
        out.push(info(&format!(
            "auto-vacuum off: {} of free pages stay in the file for new rows; the dashboard (on mains power) or `swarmy compact --vacuum` gives them back once",
            hb(st.file.free_bytes())
        )));
    }
    for d in idx.band_drift(&ctx.prices)? {
        out.push(warn(&format!(
            "{} {}..{}: {} rolled-up rows keep the long-context band of an older price (its threshold changed)",
            d.model,
            d.first,
            d.last,
            fmt::count(d.rows)
        )));
    }
    Ok(out)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::{Config, Dirs};
    use crate::core::pricing::PriceBook;
    use crate::index::archive_scenarios::{NOW, populate, refresh};
    use crate::index::compact::CompactOpts;
    use crate::index::scenarios::{World, at};
    use crate::procs::ProcTable;
    use crate::ui::style::{ColorChoice, Painter};

    #[test]
    fn the_guard_section() {
        use crate::core::ids::AccountId;
        let p = Painter::new(ColorChoice::Never);
        let cfg = |t: &str| -> Config { toml::from_str(t).unwrap() };
        let seat = |label, guarded, status_line| GuardSeat {
            label,
            guarded,
            status_line,
        };
        let accounts = vec![
            (AccountId::new("acc-1/org-1"), "personal".to_string()),
            (AccountId::new("acc-2/org-1"), "work".to_string()),
        ];
        // Nothing set, nothing guarded: one line saying it is there to have.
        let none = guard_section(
            &p,
            &Config::default(),
            &[seat("work", false, true)],
            &accounts,
            &[],
        );
        assert_eq!(none.len(), 1, "{none:?}");
        assert!(none[0].contains("swarmy setup --guard"), "{none:?}");

        // A guarded seat without the status line, and no line in the config.
        let lines = guard_section(
            &p,
            &Config::default(),
            &[seat("lab", true, false)],
            &accounts,
            &[],
        );
        let text = lines.join("\n");
        assert!(text.contains("guard hook in: lab"), "{text}");
        assert!(text.contains("without the swarmy status line"), "{text}");
        assert!(text.contains("lets everything through"), "{text}");

        // Lines per account as the hook resolves them; a key that names nobody is said.
        let c = cfg(
            "[accounts]\n\"acc-1\" = \"personal\"\n[guard]\nweek = 85\n[guard.account.personal]\nweek = 80\nfive_hour = 95\n[guard.account.bobb]\nweek = 50\n",
        );
        let text = guard_section(&p, &c, &[seat("work", true, true)], &accounts, &[]).join("\n");
        assert!(
            text.contains(
                "personal: agents stop at week 80%, wrap up from 75%; 5-hour 95%, wrap up from 90%"
            ),
            "{text}"
        );
        assert!(
            text.contains("work: agents stop at week 85%, wrap up from 80%"),
            "{text}"
        );
        assert!(
            text.contains("[guard.account.bobb] names no account"),
            "{text}"
        );
        assert!(!text.contains("[WARN] [guard.account.personal]"), "{text}");
    }

    #[test]
    fn the_storage_section() {
        let w = World::new(&["work", "home", "lab"]);
        populate(&w);
        std::fs::write(
            w.seats[2].dir.join("settings.json"),
            r#"{"cleanupPeriodDays": 60}"#,
        )
        .unwrap();
        let mut idx = w.index("i.sqlite");
        refresh(&w, &mut idx);
        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: Config::default(),
            seats: w.seats.clone(),
            seat_info: Vec::new(),
            prices: PriceBook::builtin(),
            procs: ProcTable::empty(),
            painter: Painter::new(ColorChoice::Never),
            mask: false,
            now: at(NOW),
            login_labels: Default::default(),
            login_tiers: Default::default(),
            problems: Vec::new(),
        };
        let text = |idx: &mut Index| storage(&ctx, idx).unwrap().join("\n");
        let before = text(&mut idx);
        assert!(before.contains("auto-vacuum off"), "{before}");
        assert!(before.contains("nothing rolled up yet"), "{before}");
        assert!(before.contains("last compaction never"), "{before}");
        assert!(before.contains("keep_raw_days = 14"), "{before}");
        assert!(
            before.contains(
                "transcripts are deleted after 30 days on 2 seats (cleanupPeriodDays, default), after 60 days on 1 seat (cleanupPeriodDays)"
            ),
            "{before}"
        );
        assert!(
            before.contains("estimated from the requests a day")
                && before.contains("(budget 1024 MB)"),
            "{before}"
        );
        idx.compact(&CompactOpts {
            keep_raw_days: 14,
            now: at(NOW),
            prices: &ctx.prices,
            seats: &ctx.seats,
            max_chunks: None,
        })
        .unwrap();
        let after = text(&mut idx);
        assert!(after.contains("history  since 2026-09-2"), "{after}");
        assert!(after.contains(" in rollups: "), "{after}");
        assert!(before.contains("detail   since 2026-09-21: "), "{before}");
        // From rolled_until: at most a chunk before the local midnight 14 days back.
        let until = idx.storage_report().unwrap().rolled_until;
        let since = crate::index::from_ms(until).with_timezone(&chrono::Local);
        assert!(
            after.contains(&format!("detail   since {}: ", since.format("%Y-%m-%d"))),
            "{after}"
        );
        assert!(
            after.contains("chunks") && after.contains("skipped as already rolled up: 0"),
            "{after}"
        );
        assert!(after.contains("[ OK ] growth"), "under the budget: {after}");
        assert!(after.contains("of free pages stay in the file"), "{after}");
        idx.vacuum_to_incremental(true, None, false)
            .unwrap()
            .unwrap_err();
        let waits = text(&mut idx);
        assert!(
            waits.contains("[WARN] auto-vacuum off: the one-time VACUUM waits for mains power"),
            "{waits}"
        );
    }
}