swarmy 0.2.10

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
//! `swarmy compact`: rolls per-request detail older than the raw window up into the archive's
//! quarter-hour rollups and gives the space back (`docs/design/storage.md`). The dashboard does
//! the same on its own; this runs it in the foreground, previews it, or proves it on a copy.

use std::io::{IsTerminal, Write};

use chrono::{DateTime, Local, Utc};
use clap::{Args, ValueEnum};

use crate::app::context::Ctx;
use crate::core::period::Period;
use crate::index::compact::{self, CompactOpts, VacuumSkip};
use crate::index::query::{Dim, Filter, Row};
use crate::index::{Index, from_ms};
use crate::ui::fmt;
use crate::ui::style::Tone;

#[derive(Args, Debug, Clone, Default)]
pub struct CompactArgs {
    /// Show what would be rolled up and how much space it would free; change nothing.
    #[arg(long)]
    pub dry_run: bool,
    /// Days of per-request detail to keep, this once (at least 8).
    #[arg(long, value_name = "DAYS")]
    pub keep_days: Option<i64>,
    /// Also the one-time VACUUM that switches the index to incremental auto-vacuum, so space
    /// freed from now on goes back to the disk (needs twice the index free on disk).
    #[arg(long)]
    pub vacuum: bool,
    /// Compact a scratch copy and check that every total by every grouping stays the same; the
    /// index itself is not changed.
    #[arg(long, conflicts_with_all = ["dry_run", "vacuum"])]
    pub verify: bool,
}

pub fn run(ctx: &Ctx, a: &CompactArgs) -> anyhow::Result<()> {
    // Read what changed first: prices and accounts are settled before anything is rolled up.
    let (mut idx, _) = ctx.index()?;
    run_on(ctx, &mut idx, a, &mut std::io::stdout().lock())
}

/// `swarmy compact` on an open, refreshed index, printing to `out`.
pub fn run_on(
    ctx: &Ctx,
    idx: &mut Index,
    a: &CompactArgs,
    out: &mut dyn Write,
) -> anyhow::Result<()> {
    let keep = ctx.keep_raw_days(a.keep_days)?;
    if a.verify {
        return verify(ctx, idx, keep, out);
    }
    let p = &ctx.painter;
    let when = |t: i64| {
        from_ms(t)
            .with_timezone(&Local)
            .format("%a %d %b %Y %H:%M")
            .to_string()
    };
    let file = idx.file_stats()?;
    writeln!(
        out,
        "index    {} ({} free) · auto-vacuum {}",
        fmt::human_bytes(file.bytes()),
        fmt::human_bytes(file.free_bytes()),
        if file.incremental {
            "incremental"
        } else {
            "off"
        }
    )?;
    if a.dry_run {
        let v = idx.compact_preview(keep, ctx.now)?;
        writeln!(
            out,
            "keep     {keep} days of per-request detail: everything before {} is rolled up",
            when(v.cutoff)
        )?;
        if v.requests + v.tool_calls + v.prompts + v.api_errors == 0 {
            writeln!(out, "{}", p.paint("nothing to roll up", Tone::Good))?;
            return Ok(());
        }
        writeln!(
            out,
            "would roll up {} requests, {} tool calls, {} prompts, {} API errors into ≈ {} rollup rows",
            fmt::count(v.requests),
            fmt::count(v.tool_calls),
            fmt::count(v.prompts),
            fmt::count(v.api_errors),
            fmt::count(v.usage_rows + v.tool_rows)
        )?;
        writeln!(
            out,
            "would free ≈ {} {}",
            fmt::human_bytes(v.bytes),
            if file.incremental {
                "(given back to the disk)"
            } else {
                "(as free pages new rows reuse; `--vacuum` makes the index give space back)"
            }
        )?;
        if v.pending > 0 {
            writeln!(
                out,
                "{}",
                p.paint(
                    &format!(
                        "{} requests are not priced yet: their days wait for the next refresh",
                        fmt::count(v.pending)
                    ),
                    Tone::Warn
                )
            )?;
        }
        return Ok(());
    }
    let started = std::time::Instant::now();
    let tty = std::io::stderr().is_terminal();
    let mut progress = |r: &compact::CompactReport| {
        if tty {
            eprint!(
                "\r\x1b[2K[ .. ] rolled up {} chunks, {} requests",
                r.chunks,
                fmt::count(r.requests)
            );
        }
    };
    let r = idx.compact_with(
        &CompactOpts {
            keep_raw_days: keep,
            now: ctx.now,
            prices: &ctx.prices,
            seats: &ctx.seats,
            max_chunks: None,
        },
        &mut progress,
    )?;
    if tty && r.chunks > 0 {
        eprint!("\r\x1b[2K");
    }
    if r.chunks == 0 {
        writeln!(
            out,
            "{}",
            p.paint(
                &format!("nothing older than {keep} days to roll up"),
                Tone::Good
            )
        )?;
    } else {
        writeln!(
            out,
            "rolled up {} requests, {} tool calls, {} prompts, {} API errors in {} chunks ({:.1}s)",
            fmt::count(r.requests),
            fmt::count(r.tool_calls),
            fmt::count(r.prompts),
            fmt::count(r.api_errors),
            r.chunks,
            started.elapsed().as_secs_f64()
        )?;
    }
    if let Some(w) = r.waiting {
        writeln!(
            out,
            "{}",
            p.paint(
                &format!(
                    "stopped at {}: requests not priced yet (the next refresh prices them)",
                    when(w)
                ),
                Tone::Warn
            )
        )?;
    }
    if r.rolled_until > 0 {
        writeln!(out, "detail kept from {} on", when(r.rolled_until))?;
    }
    if r.freed_bytes > 0 {
        writeln!(out, "freed {}", fmt::human_bytes(r.freed_bytes))?;
    }
    if a.vacuum {
        match idx.vacuum_to_incremental(false, compact::free_disk(&ctx.dirs.data), true)? {
            Ok(shrank) => writeln!(
                out,
                "VACUUM: auto-vacuum is incremental now; the index shrank by {}",
                fmt::human_bytes(shrank)
            )?,
            Err(VacuumSkip::Done) => {}
            Err(skip) => writeln!(
                out,
                "{}",
                p.paint(&format!("VACUUM skipped: {}", skip.describe()), Tone::Warn)
            )?,
        }
    } else if !idx.file_stats()?.incremental && idx.file_stats()?.free_pages > 0 {
        writeln!(
            out,
            "{}",
            p.paint(
                "the freed pages stay inside the index for new rows; `swarmy compact --vacuum` gives them back once",
                Tone::Dim
            )
        )?;
    }
    writeln!(
        out,
        "index    {}",
        fmt::human_bytes(idx.file_stats()?.bytes())
    )?;
    Ok(())
}

/// Every total a report can show, by period, grouping and key.
type Numbers = std::collections::BTreeMap<String, Row>;

/// The periods `--verify` compares: all, rolling ones reaching into the archive or ending at its
/// edge, a calendar month, and today (raw only). Each grouping over all of the index costs
/// about a third of a CPU-second on a month of heavy use, so the list stays short.
fn periods() -> [Period; 5] {
    [
        Period::All,
        Period::Days(30),
        Period::Month,
        Period::Days(14),
        Period::Today,
    ]
}

fn numbers(idx: &Index, now: DateTime<Utc>) -> anyhow::Result<Numbers> {
    let f = Filter::default();
    let mut n = Numbers::new();
    for p in periods() {
        let span = p.span(now, None);
        n.insert(format!("{} · total", p.label()), idx.total(span, &f)?);
        for dim in Dim::value_variants() {
            for row in idx.spend_by(*dim, span, &f)? {
                n.insert(format!("{} · {dim:?} · {}", p.label(), row.key), row);
            }
        }
    }
    Ok(n)
}

/// What differs between two sets of numbers: counts and tokens must be equal, money agree to
/// nine significant digits (sums over other groupings add in another order).
fn differences(before: &Numbers, after: &Numbers) -> Vec<String> {
    let mut out = Vec::new();
    for (k, a) in before {
        let Some(b) = after.get(k) else {
            out.push(format!("{k}: gone"));
            continue;
        };
        let same_money = (a.cost - b.cost).abs() <= 1e-9 * a.cost.abs().max(b.cost.abs()).max(1.0);
        let counts = |r: &Row| (r.requests, r.unpriced, r.pending, r.usage);
        if !same_money || counts(a) != counts(b) {
            out.push(format!(
                "{k}: {} requests {} → {} requests {}",
                a.requests,
                fmt::money(a.cost),
                b.requests,
                fmt::money(b.cost)
            ));
        }
    }
    out.extend(
        after
            .keys()
            .filter(|k| !before.contains_key(*k))
            .map(|k| format!("{k}: new")),
    );
    out
}

/// Compacts a scratch copy of the index (in the data dir) and compares every total by every
/// grouping before and after. The index itself is only read.
fn verify(ctx: &Ctx, idx: &Index, keep: i64, out: &mut dyn Write) -> anyhow::Result<()> {
    let dir = ctx.dirs.data.join("tmp");
    std::fs::create_dir_all(&dir)?;
    // Per run: two `compact --verify` at once never share a copy (review A-L2).
    let scratch = dir.join(format!(
        "verify-{}-{}.sqlite",
        std::process::id(),
        ctx.now.timestamp_millis()
    ));
    let remove = || {
        for ext in ["", "-wal", "-shm"] {
            let p = std::path::PathBuf::from(format!("{}{ext}", scratch.display()));
            if p.exists() {
                std::fs::remove_file(&p)?;
            }
        }
        anyhow::Ok(())
    };
    remove()?;
    idx.copy_to(&scratch)?;
    let tty = std::io::stderr().is_terminal();
    let step = |what: &str| {
        if tty {
            eprint!("\r\x1b[2K[ .. ] verify: {what}");
        }
    };
    let result = (|| {
        let mut copy = Index::open(&scratch)?;
        copy.set_now(ctx.now);
        step("every total before");
        let before = numbers(&copy, ctx.now)?;
        step("compacting the copy");
        let r = copy.compact(&CompactOpts {
            keep_raw_days: keep,
            now: ctx.now,
            prices: &ctx.prices,
            seats: &ctx.seats,
            max_chunks: None,
        })?;
        step("every total after");
        let after = numbers(&copy, ctx.now)?;
        anyhow::Ok((before.len(), r, differences(&before, &after)))
    })();
    if tty {
        eprint!("\r\x1b[2K");
    }
    remove()?;
    let (n, r, diffs) = result?;
    let p = &ctx.painter;
    writeln!(
        out,
        "verify   on a scratch copy (the index is not changed): rolled up {} requests, {} tool calls",
        fmt::count(r.requests),
        fmt::count(r.tool_calls)
    )?;
    let groupings = Dim::value_variants().len();
    if diffs.is_empty() {
        writeln!(
            out,
            "{}",
            p.paint(
                &format!(
                    "every total is the same: {} numbers ({groupings} groupings × {} periods, and totals), 0 differences",
                    fmt::count(n as u64),
                    periods().len()
                ),
                Tone::Good
            )
        )?;
        return Ok(());
    }
    writeln!(
        out,
        "{}",
        p.paint(
            &format!("{} differences in {} numbers:", diffs.len(), n),
            Tone::Bad
        )
    )?;
    for d in diffs.iter().take(20) {
        writeln!(out, "  {d}")?;
    }
    anyhow::bail!("compaction would change numbers; the index was not touched")
}

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

    fn ctx(w: &World) -> 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(),
        }
    }

    fn run(ctx: &Ctx, idx: &mut Index, a: CompactArgs) -> anyhow::Result<String> {
        let mut out = Vec::new();
        run_on(ctx, idx, &a, &mut out)?;
        Ok(String::from_utf8(out).unwrap())
    }

    fn rows(idx: &Index) -> (u64, u64) {
        (
            idx.count(Counted::Requests).unwrap(),
            idx.count(Counted::UsageRollup).unwrap(),
        )
    }

    #[test]
    fn dry_run_verify_then_compact_on_a_temp_index() {
        let w = World::new(&["work", "home", "lab"]);
        populate(&w);
        let mut idx = w.index("i.sqlite");
        refresh(&w, &mut idx);
        readings(&idx);
        let ctx = ctx(&w);
        let raw = rows(&idx);
        assert_eq!(raw.1, 0);

        let out = run(
            &ctx,
            &mut idx,
            CompactArgs {
                dry_run: true,
                ..Default::default()
            },
        )
        .unwrap();
        assert!(
            out.contains("would roll up") && out.contains("would free ≈"),
            "{out}"
        );
        // The local midnight 14 days back, whatever the zone the test runs in.
        let cut = from_ms(compact::cutoff(at(NOW), 14)).with_timezone(&Local);
        assert!(
            out.contains(&format!(
                "everything before {}",
                cut.format("%a %d %b %Y 00:00")
            )),
            "{out}"
        );
        assert_eq!(rows(&idx), raw, "a dry run changes nothing");

        let out = run(
            &ctx,
            &mut idx,
            CompactArgs {
                verify: true,
                ..Default::default()
            },
        )
        .unwrap();
        assert!(out.contains("0 differences"), "{out}");
        assert_eq!(rows(&idx), raw, "verify works on a copy");
        assert_eq!(
            std::fs::read_dir(ctx.dirs.data.join("tmp"))
                .unwrap()
                .count(),
            0,
            "the scratch copy is gone"
        );

        let short = CompactArgs {
            keep_days: Some(7),
            ..Default::default()
        };
        assert!(
            run(&ctx, &mut idx, short).is_err(),
            "the weekly window stays raw"
        );
        // Claude Code keeps these seats' transcripts 30 days: a rebuild must find 28 on disk.
        let long = CompactArgs {
            keep_days: Some(29),
            ..Default::default()
        };
        let e = run(&ctx, &mut idx, long).unwrap_err().to_string();
        assert!(
            e.starts_with("--keep-days: keep_raw_days = 29: at most 28"),
            "{e}"
        );
        let mut strict = super::tests::ctx(&w);
        strict.config.storage.keep_raw_days = Some(40);
        let err = run(&strict, &mut idx, CompactArgs::default()).unwrap_err();
        let e = err.to_string();
        assert!(e.contains("[storage] keep_raw_days = 40"), "{e}");
        // A config error with its code (review B-L10).
        assert!(matches!(
            err.downcast_ref::<crate::errors::ConfigError>(),
            Some(crate::errors::ConfigError::Invalid { .. })
        ));
        assert_eq!(rows(&idx), raw, "refused before anything moved");

        let out = run(
            &ctx,
            &mut idx,
            CompactArgs {
                vacuum: true,
                ..Default::default()
            },
        )
        .unwrap();
        assert!(out.contains("rolled up") && out.contains("chunks"), "{out}");
        assert!(
            out.contains("VACUUM: auto-vacuum is incremental now"),
            "{out}"
        );
        let (left, rolled) = rows(&idx);
        assert!(left < raw.0 && rolled > 0);
        assert!(idx.file_stats().unwrap().incremental);

        let out = run(&ctx, &mut idx, CompactArgs::default()).unwrap();
        assert!(
            out.contains("nothing older than 14 days to roll up"),
            "{out}"
        );
    }
}