pub mod input;
use std::path::Path;
use chrono::{DateTime, Duration, Local, Utc};
use serde_json::json;
use crate::config::{Config, Dirs};
use crate::core::guard::{Crossing, Lines, State};
use crate::core::ids::{AccountId, SeatId};
use crate::core::limits::{Reading, WindowKind};
use crate::core::units::Pct;
use crate::statusline::reading;
use crate::vault::Login;
use input::HookInput;
const MARKS_KEPT_DAYS: i64 = 8;
const STOP_GRACE_S: i64 = 10;
#[derive(Debug, Clone, PartialEq)]
pub enum Answer {
Go,
WrapUp { context: String, user: String },
Refuse { reason: String },
StopTurn { reason: String, user: String },
}
impl Answer {
pub fn json(&self) -> Option<String> {
let deny = |reason: &str| {
json!({
"hookEventName": "PreToolUse",
"permissionDecision": "deny",
"permissionDecisionReason": reason,
})
};
let v = match self {
Answer::Go => return None,
Answer::WrapUp { context, user } => json!({
"systemMessage": user,
"hookSpecificOutput": {"hookEventName": "PreToolUse", "additionalContext": context},
}),
Answer::Refuse { reason } => json!({"hookSpecificOutput": deny(reason)}),
Answer::StopTurn { reason, user } => json!({
"continue": false,
"stopReason": user,
"hookSpecificOutput": deny(reason),
}),
};
Some(v.to_string())
}
}
pub fn run(dirs: &Dirs, config: &Config, stdin: &str, now: DateTime<Utc>, bypass: bool) -> Answer {
if bypass || !config.guard.is_set() {
return Answer::Go;
}
let seat = crate::claude::seats::seat_id(&crate::statusline::current_config_dir(&dirs.home));
decide(dirs, config, &seat, &input::parse(stdin), now)
}
pub fn decide(
dirs: &Dirs,
config: &Config,
seat: &SeatId,
input: &HookInput,
now: DateTime<Utc>,
) -> Answer {
let Some((account, readings)) = seat_readings(&dirs.data, &dirs.vault_dir(), seat) else {
return Answer::Go;
};
let vault = dirs.vault_dir();
let logins = || {
crate::vault::saved_logins(&vault).unwrap_or_else(|e| {
crate::diag::log("guard", &format!("vault unreadable: {e:#}"));
Vec::new()
})
};
let mut known: Option<Vec<Login>> = None;
let lines = if config.guard.account.is_empty() {
config.guard.lines_for(&[])
} else {
let l = known.get_or_insert_with(&logins);
lines_of(&account, config, l)
};
let v = crate::core::guard::verdict(&readings, &lines, now);
let Some(c) = v.crossing else {
return Answer::Go;
};
let label = label_of(&account, config, known.get_or_insert_with(&logins));
let marks = dirs.data.join("guard");
let who = input.who();
match v.state {
State::Go => Answer::Go,
State::WrapUp => {
if !matches!(mark(&marks, &who, "wrap", &c, now), Mark::New) {
return Answer::Go;
}
Answer::WrapUp {
context: format!(
"swarmy guard: account {label} has used {} of its {}; the user stops agents at {} \
(resets {}). Finish the step you are on, leave the work where someone can \
pick it up, and write down briefly what is done and what is left. Tools stop \
working at {}.",
pct(c.used),
window(c.kind),
pct(c.line),
when(c.resets_at),
pct(c.line),
),
user: format!(
"swarmy guard: {label} {} used {} · agents stop at {}",
window(c.kind),
pct(c.used),
pct(c.line)
),
}
}
State::Stop => {
let reason = format!(
"swarmy guard: account {label} has used {} of its {}, at or past the {} line the \
user set (resets {}). Do not call any more tools. Reply with a short summary: \
what is done, what is left, and where to pick up.",
pct(c.used),
window(c.kind),
pct(c.line),
when(c.resets_at),
);
let just_refused = match mark(&marks, &who, "stop", &c, now) {
Mark::New => true,
Mark::Made(at) => at.is_none_or(|t| now - t < Duration::seconds(STOP_GRACE_S)),
};
if just_refused {
return Answer::Refuse { reason };
}
Answer::StopTurn {
reason,
user: format!(
"swarmy guard: {label} {} used {}, line {} (resets {}). To go on: put another \
login into this seat (S in swarmy, or swarmy accounts switch), raise the line \
in config.toml [guard], or start Claude Code with SWARMY_GUARD=off.",
window(c.kind),
pct(c.used),
pct(c.line),
when(c.resets_at),
),
}
}
}
}
fn seat_readings(data: &Path, vault: &Path, seat: &SeatId) -> Option<(AccountId, Vec<Reading>)> {
let own_file = reading::file_of(data, seat);
let own = reading::read(&own_file)?;
match crate::vault::last_switch(vault, seat) {
Ok(Some(sw)) if sw.at > own.at => return None,
Ok(_) => {}
Err(e) => {
crate::diag::log("guard", &format!("vault unreadable: {e:#}"));
return None;
}
}
let mut all = own.readings();
if let Ok(entries) = std::fs::read_dir(data.join("statusline")) {
for path in entries.flatten().map(|e| e.path()) {
if path == own_file || path.extension().is_none_or(|x| x != "json") {
continue;
}
if let Some(l) = reading::read(&path).filter(|l| l.account == own.account) {
all.extend(l.readings());
}
}
}
Some((own.account, newest_per_kind(all)))
}
fn newest_per_kind(readings: Vec<Reading>) -> Vec<Reading> {
let mut out: Vec<Reading> = Vec::new();
for r in readings {
match out.iter_mut().find(|o| o.kind == r.kind) {
Some(o) if o.fetched_at < r.fetched_at => *o = r,
Some(_) => {}
None => out.push(r),
}
}
out
}
pub fn names_of(id: &AccountId, config: &Config, logins: &[Login]) -> Vec<String> {
let mut names = vec![id.as_str().to_string(), id.user_uuid().to_string()];
names.extend(id.org_uuid().map(str::to_string));
for (uuid, name) in &config.accounts {
if uuid == id.as_str() || uuid == id.user_uuid() {
names.push(name.clone());
}
}
for l in logins.iter().filter(|l| login_of(l, id)) {
names.push(l.label.clone());
names.extend(l.email.clone());
}
names
}
pub fn lines_of(id: &AccountId, config: &Config, logins: &[Login]) -> Lines {
config.guard.lines_for(&names_of(id, config, logins))
}
pub fn label_of(id: &AccountId, config: &Config, logins: &[Login]) -> String {
let configured = config
.accounts
.iter()
.find(|(uuid, _)| *uuid == id.as_str() || *uuid == id.user_uuid())
.map(|(_, name)| name.clone());
let saved = || logins.iter().find(|l| login_of(l, id));
configured
.or_else(|| saved().map(|l| l.label.clone()))
.or_else(|| saved().and_then(|l| l.email.clone()))
.unwrap_or_else(|| format!("acct-{}", crate::core::ids::short_account(id.as_str())))
}
fn login_of(l: &Login, id: &AccountId) -> bool {
l.account_uuid.as_deref().is_some_and(|a| {
let a = AccountId::new(a);
a == *id || (!a.has_org() && a.user_uuid() == id.user_uuid())
})
}
enum Mark {
New,
Made(Option<DateTime<Utc>>),
}
fn mark(dir: &Path, who: &(String, String), what: &str, c: &Crossing, now: DateTime<Utc>) -> Mark {
let name = format!(
"{}.{}.{what}.{}.{}",
who.0,
who.1,
c.kind.key(),
c.resets_at.timestamp()
);
let path = dir.join(name);
if let Err(e) = std::fs::create_dir_all(dir) {
crate::diag::log("guard", &format!("cannot make {}: {e}", dir.display()));
return Mark::New;
}
match std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&path)
{
Ok(mut f) => {
if let Err(e) = std::io::Write::write_all(&mut f, now.to_rfc3339().as_bytes()) {
crate::diag::log("guard", &format!("cannot write {}: {e}", path.display()));
}
prune(dir, now);
Mark::New
}
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Mark::Made(
std::fs::read_to_string(&path)
.ok()
.and_then(|t| DateTime::parse_from_rfc3339(t.trim()).ok())
.map(|t| t.with_timezone(&Utc)),
),
Err(e) => {
crate::diag::log("guard", &format!("cannot write {}: {e}", path.display()));
Mark::New
}
}
}
fn prune(dir: &Path, now: DateTime<Utc>) {
let Ok(entries) = std::fs::read_dir(dir) else {
return;
};
let cutoff = now - Duration::days(MARKS_KEPT_DAYS);
for e in entries.flatten() {
let old = e
.metadata()
.and_then(|m| m.modified())
.is_ok_and(|t| DateTime::<Utc>::from(t) < cutoff);
if old && let Err(err) = std::fs::remove_file(e.path()) {
crate::diag::log("guard", &format!("cannot remove an old mark: {err}"));
}
}
}
fn window(kind: WindowKind) -> &'static str {
match kind {
WindowKind::SevenDay => "week",
WindowKind::FiveHour => "5-hour window",
WindowKind::SevenDayOpus | WindowKind::SevenDaySonnet => kind.label(),
}
}
fn pct(p: Pct) -> String {
let s = format!("{:.1}", p.get());
format!("{}%", s.strip_suffix(".0").unwrap_or(&s))
}
fn when(t: DateTime<Utc>) -> String {
t.with_timezone(&Local).format("%a %H:%M").to_string()
}
#[cfg(test)]
mod tests;