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
use std::path::{Path, PathBuf};

use chrono::{DateTime, Duration, TimeZone, Utc};

use super::*;
use crate::claude::seats::Seat;
use crate::statusline::reading::{LiveLimits, VERSION};

struct World {
    _t: tempfile::TempDir,
    dirs: Dirs,
}

fn world() -> World {
    let t = tempfile::tempdir().unwrap();
    let dirs = Dirs {
        data: t.path().join("data"),
        config: t.path().join("cfg"),
        home: t.path().join("home"),
    };
    World { _t: t, dirs }
}

fn now() -> DateTime<Utc> {
    Utc.with_ymd_and_hms(2026, 12, 5, 12, 0, 0).unwrap()
}

fn config(text: &str) -> Config {
    let c: Config = toml::from_str(text).unwrap();
    c.validate().unwrap();
    c
}

fn seat_dir(w: &World, label: &str) -> PathBuf {
    w.dirs.home.join(format!(".claude-{label}"))
}

/// What `swarmy statusline` would have kept for a seat: the week at `week` %, `ago` before now.
fn reading(w: &World, dir: &Path, account: &str, week: f64, ago: Duration) {
    let live = LiveLimits {
        v: VERSION,
        at: now() - ago,
        account: AccountId::new(account),
        config_dir: dir.display().to_string(),
        session_id: Some("s1".into()),
        five_hour: Some((10.0, now() + Duration::hours(2))),
        seven_day: Some((week, now() + Duration::days(2))),
    };
    reading::write(&reading::file_for(&w.dirs.data, dir), &live).unwrap();
}

fn call(w: &World, c: &Config, dir: &Path, session: &str, agent: Option<&str>) -> Answer {
    call_at(w, c, dir, session, agent, now())
}

fn call_at(
    w: &World,
    c: &Config,
    dir: &Path,
    session: &str,
    agent: Option<&str>,
    at: DateTime<Utc>,
) -> Answer {
    let input = match agent {
        Some(a) => format!(r#"{{"session_id":"{session}","agent_id":"{a}"}}"#),
        None => format!(r#"{{"session_id":"{session}"}}"#),
    };
    decide(
        &w.dirs,
        c,
        &crate::claude::seats::seat_id(dir),
        &input::parse(&input),
        at,
    )
}

const LINE_85: &str = "[guard]\nweek = 85\n";

#[test]
fn nothing_is_read_without_a_line_or_with_the_guard_off() {
    let w = world();
    let dir = seat_dir(&w, "work");
    reading(&w, &dir, "a/org-a", 99.0, Duration::minutes(1));
    let input = r#"{"session_id":"s1"}"#;
    assert_eq!(
        run(&w.dirs, &Config::default(), input, now(), false),
        Answer::Go
    );
    assert_eq!(
        run(&w.dirs, &config(LINE_85), input, now(), true),
        Answer::Go,
        "SWARMY_GUARD=off"
    );
}

#[test]
fn below_the_zone_the_call_goes_on() {
    let w = world();
    let dir = seat_dir(&w, "work");
    reading(&w, &dir, "a/org-a", 79.0, Duration::minutes(1));
    assert_eq!(call(&w, &config(LINE_85), &dir, "s1", None), Answer::Go);
    assert!(!w.dirs.data.join("guard").exists(), "no mark for nothing");
}

#[test]
fn each_agent_is_told_to_wrap_up_once() {
    let w = world();
    let dir = seat_dir(&w, "work");
    let c = config(LINE_85);
    reading(&w, &dir, "a/org-a", 81.0, Duration::minutes(1));
    let Answer::WrapUp { context, user } = call(&w, &c, &dir, "s1", None) else {
        panic!("the main thread is told first");
    };
    assert!(context.contains("81% of its week"), "{context}");
    assert!(context.contains("stops agents at 85%"), "{context}");
    assert!(user.contains("week used 81%"), "{user}");
    assert_eq!(call(&w, &c, &dir, "s1", None), Answer::Go, "once");
    // A subagent has a context of its own: it is told too, once.
    assert!(matches!(
        call(&w, &c, &dir, "s1", Some("agent-7")),
        Answer::WrapUp { .. }
    ));
    assert_eq!(call(&w, &c, &dir, "s1", Some("agent-7")), Answer::Go);
    // Another session in the seat as well.
    assert!(matches!(
        call(&w, &c, &dir, "s2", None),
        Answer::WrapUp { .. }
    ));
}

#[test]
fn at_the_line_the_first_call_is_refused_and_the_next_ends_the_turn() {
    let w = world();
    let dir = seat_dir(&w, "work");
    let c = config(LINE_85);
    reading(&w, &dir, "a/org-a", 86.0, Duration::minutes(1));
    let Answer::Refuse { reason } = call(&w, &c, &dir, "s1", None) else {
        panic!("refused first");
    };
    assert!(reason.contains("Do not call any more tools"), "{reason}");
    // A call after the agent read the refusal comes with its next response.
    let later = now() + Duration::seconds(STOP_GRACE_S + 1);
    let Answer::StopTurn { user, .. } = call_at(&w, &c, &dir, "s1", None, later) else {
        panic!("then the turn stops");
    };
    assert!(user.contains("SWARMY_GUARD=off"), "{user}");
    assert!(matches!(
        call_at(&w, &c, &dir, "s1", None, later + Duration::minutes(5)),
        Answer::StopTurn { .. }
    ));
    // A subagent gets its own first refusal, to write where it stopped.
    assert!(matches!(
        call(&w, &c, &dir, "s1", Some("agent-7")),
        Answer::Refuse { .. }
    ));
}

#[test]
fn calls_made_with_the_refused_one_are_refused_too() {
    // A model often calls several tools in one response; the hooks run one after another
    // within a second. Ending the turn there would leave the agent no chance to write where
    // it stopped (seen on Claude Code 2.1.337: three parallel reads, the turn ended silently).
    let w = world();
    let dir = seat_dir(&w, "work");
    let c = config(LINE_85);
    reading(&w, &dir, "a/org-a", 86.0, Duration::minutes(1));
    for ms in [0, 40, 900] {
        let at = now() + Duration::milliseconds(ms);
        let a = call_at(&w, &c, &dir, "s1", None, at);
        assert!(matches!(a, Answer::Refuse { .. }), "at +{ms} ms: {a:?}");
    }
    let next = now() + Duration::seconds(STOP_GRACE_S);
    assert!(matches!(
        call_at(&w, &c, &dir, "s1", None, next),
        Answer::StopTurn { .. }
    ));
}

#[test]
fn a_stop_mark_being_written_counts_as_just_made() {
    // Another call made the mark a moment ago and has not written its time yet.
    let w = world();
    let dir = seat_dir(&w, "work");
    let c = config(LINE_85);
    reading(&w, &dir, "a/org-a", 86.0, Duration::minutes(1));
    assert!(matches!(
        call(&w, &c, &dir, "s1", None),
        Answer::Refuse { .. }
    ));
    let marks = w.dirs.data.join("guard");
    for e in std::fs::read_dir(&marks).unwrap().flatten() {
        std::fs::write(e.path(), "").unwrap();
    }
    let later = now() + Duration::minutes(5);
    assert!(matches!(
        call_at(&w, &c, &dir, "s1", None, later),
        Answer::Refuse { .. }
    ));
}

#[test]
fn a_damaged_input_still_decides_by_the_numbers() {
    // The input only says who is asking; the numbers decide.
    let w = world();
    let dir = seat_dir(&w, "work");
    reading(&w, &dir, "a/org-a", 90.0, Duration::minutes(1));
    let a = decide(
        &w.dirs,
        &config(LINE_85),
        &crate::claude::seats::seat_id(&dir),
        &input::parse("{not json"),
        now(),
    );
    assert!(matches!(a, Answer::Refuse { .. }), "{a:?}");
}

#[test]
fn no_reading_or_an_unreadable_one_lets_the_call_go_on() {
    let w = world();
    let dir = seat_dir(&w, "work");
    let c = config(LINE_85);
    assert_eq!(call(&w, &c, &dir, "s1", None), Answer::Go, "no file yet");
    let file = reading::file_for(&w.dirs.data, &dir);
    std::fs::create_dir_all(file.parent().unwrap()).unwrap();
    std::fs::write(&file, "{damaged").unwrap();
    assert_eq!(call(&w, &c, &dir, "s1", None), Answer::Go, "damaged file");
}

#[test]
fn a_newer_reading_of_the_same_account_in_another_seat_counts() {
    let w = world();
    let (work, lab, other) = (
        seat_dir(&w, "work"),
        seat_dir(&w, "lab"),
        seat_dir(&w, "other"),
    );
    let c = config(LINE_85);
    reading(&w, &work, "a/org-a", 70.0, Duration::minutes(30));
    // Another account at 99%: none of this seat's business.
    reading(&w, &other, "b/org-b", 99.0, Duration::minutes(1));
    assert_eq!(call(&w, &c, &work, "s1", None), Answer::Go);
    // The same account, read later in the lab seat: it has used more since.
    reading(&w, &lab, "a/org-a", 86.0, Duration::minutes(2));
    assert!(matches!(
        call(&w, &c, &work, "s1", None),
        Answer::Refuse { .. }
    ));
}

/// A Claude Code seat with a login of account `acc`, saved in the vault as `acc`.
fn vault_seat(w: &World, label: &str, acc: &str) -> Seat {
    let dir = seat_dir(w, label);
    std::fs::create_dir_all(&dir).unwrap();
    let creds = serde_json::json!({"claudeAiOauth": {"accessToken": format!("at-{acc}"),
        "refreshToken": format!("r-{acc}"), "expiresAt": 1_795_377_583_375_i64}});
    std::fs::write(dir.join(".credentials.json"), creds.to_string()).unwrap();
    let cj = serde_json::json!({"oauthAccount": {"accountUuid": acc,
        "organizationUuid": format!("org-{acc}"), "emailAddress": format!("{acc}@example.com")}});
    std::fs::write(dir.join(".claude.json"), cj.to_string()).unwrap();
    let seat = Seat::new(label, dir.clone(), dir.join(".claude.json"), false);
    let mut v = crate::vault::Vault::open(&w.dirs.vault_dir()).unwrap();
    v.edit(|tx| tx.capture(&seat, Some(acc))).unwrap();
    seat
}

#[test]
fn after_a_switch_the_old_numbers_are_not_the_seats() {
    // The vault dates its switch by the clock: this test keeps to the clock too.
    let w = world();
    let c = config(LINE_85);
    let (work, _spare) = (vault_seat(&w, "work", "a"), vault_seat(&w, "spare", "b"));
    let file = reading::file_for(&w.dirs.data, &work.dir);
    let write = |account: &str, week: f64, at: DateTime<Utc>| {
        let live = LiveLimits {
            v: VERSION,
            at,
            account: AccountId::new(account),
            config_dir: work.dir.display().to_string(),
            session_id: None,
            five_hour: None,
            seven_day: Some((week, at + Duration::days(3))),
        };
        reading::write(&file, &live).unwrap();
    };
    let decide_at = |session: &str, t: DateTime<Utc>| {
        let input = format!(r#"{{"session_id":"{session}"}}"#);
        decide(&w.dirs, &c, &work.id, &input::parse(&input), t)
    };
    let t0 = Utc::now();
    // Account a past its line, read an hour ago: refused.
    write("a/org-a", 90.0, t0 - Duration::hours(1));
    assert!(matches!(decide_at("s1", t0), Answer::Refuse { .. }));
    // The seat now holds b: until the status line reads b's numbers, nothing is known.
    let mut v = crate::vault::Vault::open(&w.dirs.vault_dir()).unwrap();
    v.edit(|tx| tx.switch(&work, "b")).unwrap();
    let switched = crate::vault::last_switch(&w.dirs.vault_dir(), &work.id)
        .unwrap()
        .unwrap()
        .at;
    assert_eq!(decide_at("s2", switched + Duration::minutes(1)), Answer::Go);
    // b's numbers come with the next response, and they count.
    write("b/org-b", 90.0, switched + Duration::seconds(30));
    assert!(matches!(
        decide_at("s2", switched + Duration::minutes(1)),
        Answer::Refuse { .. }
    ));
}

#[test]
fn an_accounts_own_line_is_found_by_its_saved_login_and_named_by_it() {
    let w = world();
    let work = vault_seat(&w, "work", "a");
    // Only alice has a line; she is account a, saved as login "a" with the email below.
    let c = config("[guard.account.\"a@example.com\"]\nweek = 50\n");
    reading(&w, &work.dir, "a/org-a", 60.0, Duration::minutes(1));
    let Answer::Refuse { reason } = call(&w, &c, &work.dir, "s1", None) else {
        panic!("a's own line of 50% holds");
    };
    assert!(
        reason.contains("account a has used 60%"),
        "named by the login's label: {reason}"
    );
    // Another account in the same place has no line.
    let lab = vault_seat(&w, "lab", "b");
    reading(&w, &lab.dir, "b/org-b", 60.0, Duration::minutes(1));
    assert_eq!(call(&w, &c, &lab.dir, "s1", None), Answer::Go);
}

#[test]
fn names_and_labels_of_an_account() {
    let c = config("[accounts]\n\"acc-1\" = \"personal\"\n");
    let id = AccountId::new("acc-1/org-1");
    let names = names_of(&id, &c, &[]);
    for n in ["acc-1/org-1", "acc-1", "org-1", "personal"] {
        assert!(names.contains(&n.to_string()), "{n} in {names:?}");
    }
    assert_eq!(label_of(&id, &c, &[]), "personal");
    let nobody = AccountId::new("0123456789abcdef/org-9");
    assert!(label_of(&nobody, &Config::default(), &[]).starts_with("acct-"));
}

#[test]
fn answers_are_claude_codes_hook_json() {
    let parse =
        |a: Answer| -> serde_json::Value { serde_json::from_str(&a.json().unwrap()).unwrap() };
    assert_eq!(Answer::Go.json(), None, "nothing printed: the call goes on");
    let w = parse(Answer::WrapUp {
        context: "c".into(),
        user: "u".into(),
    });
    assert_eq!(w["hookSpecificOutput"]["hookEventName"], "PreToolUse");
    assert_eq!(w["hookSpecificOutput"]["additionalContext"], "c");
    assert_eq!(w["systemMessage"], "u");
    assert!(
        w["hookSpecificOutput"].get("permissionDecision").is_none(),
        "the usual permission flow: nothing is allowed that was not before"
    );
    let r = parse(Answer::Refuse { reason: "r".into() });
    assert_eq!(r["hookSpecificOutput"]["permissionDecision"], "deny");
    assert_eq!(r["hookSpecificOutput"]["permissionDecisionReason"], "r");
    assert!(r.get("continue").is_none());
    let s = parse(Answer::StopTurn {
        reason: "r".into(),
        user: "u".into(),
    });
    assert_eq!(s["continue"], false);
    assert_eq!(s["stopReason"], "u");
    assert_eq!(
        s["hookSpecificOutput"]["permissionDecision"], "deny",
        "`continue: false` alone does not refuse the call"
    );
}

#[test]
fn old_marks_go_when_a_new_one_is_made() {
    let w = world();
    let dir = seat_dir(&w, "work");
    let c = config(LINE_85);
    let marks = w.dirs.data.join("guard");
    std::fs::create_dir_all(&marks).unwrap();
    let old = marks.join("s0.main.wrap.seven_day.1");
    std::fs::write(&old, "").unwrap();
    let long_ago = std::time::SystemTime::from(now() - Duration::days(9));
    std::fs::File::options()
        .write(true)
        .open(&old)
        .unwrap()
        .set_modified(long_ago)
        .unwrap();
    reading(&w, &dir, "a/org-a", 81.0, Duration::minutes(1));
    assert!(matches!(
        call(&w, &c, &dir, "s1", None),
        Answer::WrapUp { .. }
    ));
    assert!(!old.exists(), "a mark older than the longest window went");
    assert_eq!(std::fs::read_dir(&marks).unwrap().count(), 1);
}

#[test]
fn percents_read_as_on_screen() {
    assert_eq!(pct(Pct::new(85.0)), "85%");
    assert_eq!(pct(Pct::new(84.64)), "84.6%");
}