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
//! The limit guard's rule: whether an account's limit readings mean its agents should go on,
//! wrap up or stop, against the lines the user set (`[guard]` in config.toml). Pure: `swarmy
//! guard` (Claude Code's PreToolUse hook, `swarmy setup --guard`) and `swarmy limits` both
//! decide with it.

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

use super::limits::{Reading, WindowKind};
use super::units::Pct;

/// Where an account's agents stop, per window, and how many points before that they are told
/// to wrap up. A line at or above 100% stops nothing: Claude Code stops at the limit itself.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct Lines {
    pub week: Option<Pct>,
    pub five_hour: Option<Pct>,
    pub wrap_up: Pct,
}

impl Lines {
    /// A line from here on is no line.
    pub const OFF_AT: f64 = 100.0;
    /// Points before a line at which agents are told to wrap up, when the config says nothing.
    pub const DEFAULT_WRAP_UP: f64 = 5.0;

    /// The line of a window, when one is in force. Per-model weekly windows have none.
    pub fn line(&self, kind: WindowKind) -> Option<Pct> {
        match kind {
            WindowKind::FiveHour => self.five_hour,
            WindowKind::SevenDay => self.week,
            WindowKind::SevenDayOpus | WindowKind::SevenDaySonnet => None,
        }
        .filter(|l| l.get() < Self::OFF_AT)
    }

    pub fn is_set(&self) -> bool {
        self.line(WindowKind::FiveHour).is_some() || self.line(WindowKind::SevenDay).is_some()
    }

    /// Where telling agents to wrap up starts, for a window with a line.
    pub fn wrap_up_at(&self, kind: WindowKind) -> Option<Pct> {
        self.line(kind)
            .map(|l| Pct::new((l.get() - self.wrap_up.get()).max(0.0)))
    }
}

/// What agents on an account do now.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum State {
    /// Below the wrap-up zone, or no line.
    Go,
    /// Within `wrap_up` points of a line: finish the step at hand and write down where it stands.
    WrapUp,
    /// At or past a line: no more tools.
    Stop,
}

/// The window that decided a verdict.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Crossing {
    pub kind: WindowKind,
    pub used: Pct,
    pub line: Pct,
    /// The window's reset, to the minute (`Reading::window_end`): it also names the window.
    pub resets_at: DateTime<Utc>,
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Verdict {
    pub state: State,
    /// None when every window is clear.
    pub crossing: Option<Crossing>,
}

impl Verdict {
    pub const GO: Verdict = Verdict {
        state: State::Go,
        crossing: None,
    };
}

/// One window's state: `used` against its line and the wrap-up zone before it.
pub fn state_of(used: Pct, line: Pct, wrap_up: Pct) -> State {
    if used >= line {
        State::Stop
    } else if wrap_up > Pct::ZERO && used >= line - wrap_up {
        State::WrapUp
    } else {
        State::Go
    }
}

/// The verdict over an account's readings (its newest of each window): the worst window wins,
/// and of two equally bad ones the one further past its line. A window that has reset since its
/// reading counts for nothing until a new reading comes: the new window starts empty.
pub fn verdict(readings: &[Reading], lines: &Lines, now: DateTime<Utc>) -> Verdict {
    let mut best = Verdict::GO;
    let mut best_margin = f64::NEG_INFINITY;
    for r in readings.iter().filter(|r| !r.is_reset(now)) {
        let Some(line) = lines.line(r.kind) else {
            continue;
        };
        let used = Pct::new(r.utilization);
        let state = state_of(used, line, lines.wrap_up);
        if state == State::Go {
            continue;
        }
        let margin = used.get() - line.get();
        if state > best.state || (state == best.state && margin > best_margin) {
            best_margin = margin;
            best = Verdict {
                state,
                crossing: Some(Crossing {
                    kind: r.kind,
                    used,
                    line,
                    resets_at: r.window_end(),
                }),
            };
        }
    }
    best
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::{Duration, TimeZone};

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

    fn reading(kind: WindowKind, used: f64, resets_in_h: i64) -> Reading {
        Reading {
            kind,
            utilization: used,
            resets_at: now() + Duration::hours(resets_in_h),
            fetched_at: now() - Duration::minutes(1),
        }
    }

    fn lines(week: Option<f64>, five_hour: Option<f64>, wrap_up: f64) -> Lines {
        Lines {
            week: week.map(Pct::new),
            five_hour: five_hour.map(Pct::new),
            wrap_up: Pct::new(wrap_up),
        }
    }

    #[test]
    fn states_against_a_line_of_85_with_5_points_to_wrap_up() {
        let l = lines(Some(85.0), None, 5.0);
        let state = |used| verdict(&[reading(WindowKind::SevenDay, used, 48)], &l, now()).state;
        assert_eq!(state(10.0), State::Go);
        assert_eq!(state(79.9), State::Go);
        assert_eq!(state(80.0), State::WrapUp, "85 − 5: the zone starts here");
        assert_eq!(state(84.9), State::WrapUp);
        assert_eq!(state(85.0), State::Stop, "the line itself stops");
        assert_eq!(state(120.0), State::Stop, "extra usage goes past 100");
    }

    #[test]
    fn the_crossing_names_window_used_line_and_reset() {
        let l = lines(Some(85.0), None, 5.0);
        let r = reading(WindowKind::SevenDay, 86.0, 48);
        let v = verdict(&[r], &l, now());
        assert_eq!(
            v.crossing,
            Some(Crossing {
                kind: WindowKind::SevenDay,
                used: Pct::new(86.0),
                line: Pct::new(85.0),
                resets_at: r.window_end(),
            })
        );
    }

    #[test]
    fn a_window_that_has_reset_counts_for_nothing() {
        let l = lines(Some(85.0), None, 5.0);
        // 95% of a week that reset an hour ago: the new week is empty until a reading says more.
        let old = reading(WindowKind::SevenDay, 95.0, -1);
        assert_eq!(verdict(&[old], &l, now()), Verdict::GO);
    }

    #[test]
    fn no_line_or_a_line_of_100_stops_nothing() {
        let r = [reading(WindowKind::SevenDay, 99.0, 48)];
        assert_eq!(verdict(&r, &lines(None, None, 5.0), now()), Verdict::GO);
        let off = lines(Some(100.0), None, 5.0);
        assert!(!off.is_set());
        assert_eq!(verdict(&r, &off, now()), Verdict::GO);
    }

    #[test]
    fn wrap_up_of_zero_goes_straight_to_stop() {
        let l = lines(Some(85.0), None, 0.0);
        let state = |used| verdict(&[reading(WindowKind::SevenDay, used, 48)], &l, now()).state;
        assert_eq!(state(84.9), State::Go);
        assert_eq!(state(85.0), State::Stop);
    }

    #[test]
    fn the_worst_window_decides() {
        // Week in its wrap-up zone, 5 hours past its line: stop, on the 5-hour window.
        let l = lines(Some(85.0), Some(95.0), 5.0);
        let r = [
            reading(WindowKind::SevenDay, 82.0, 48),
            reading(WindowKind::FiveHour, 96.0, 2),
        ];
        let v = verdict(&r, &l, now());
        assert_eq!(v.state, State::Stop);
        assert_eq!(v.crossing.map(|c| c.kind), Some(WindowKind::FiveHour));
        // Both past their lines: the one further past decides.
        let r = [
            reading(WindowKind::SevenDay, 90.0, 48),
            reading(WindowKind::FiveHour, 96.0, 2),
        ];
        assert_eq!(
            verdict(&r, &l, now()).crossing.map(|c| c.kind),
            Some(WindowKind::SevenDay)
        );
    }

    #[test]
    fn per_model_weekly_windows_have_no_line() {
        let l = lines(Some(85.0), Some(85.0), 5.0);
        let r = [reading(WindowKind::SevenDayOpus, 99.0, 48)];
        assert_eq!(verdict(&r, &l, now()), Verdict::GO);
    }

    #[test]
    fn wrap_up_starts_where_it_should() {
        let l = lines(Some(85.0), Some(3.0), 5.0);
        assert_eq!(l.wrap_up_at(WindowKind::SevenDay), Some(Pct::new(80.0)));
        assert_eq!(
            l.wrap_up_at(WindowKind::FiveHour),
            Some(Pct::new(0.0)),
            "never below 0"
        );
        assert_eq!(l.wrap_up_at(WindowKind::SevenDayOpus), None);
    }
}