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}"))
}
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");
assert!(matches!(
call(&w, &c, &dir, "s1", Some("agent-7")),
Answer::WrapUp { .. }
));
assert_eq!(call(&w, &c, &dir, "s1", Some("agent-7")), Answer::Go);
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}");
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 { .. }
));
assert!(matches!(
call(&w, &c, &dir, "s1", Some("agent-7")),
Answer::Refuse { .. }
));
}
#[test]
fn calls_made_with_the_refused_one_are_refused_too() {
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() {
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() {
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));
reading(&w, &other, "b/org-b", 99.0, Duration::minutes(1));
assert_eq!(call(&w, &c, &work, "s1", None), Answer::Go);
reading(&w, &lab, "a/org-a", 86.0, Duration::minutes(2));
assert!(matches!(
call(&w, &c, &work, "s1", None),
Answer::Refuse { .. }
));
}
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() {
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();
write("a/org-a", 90.0, t0 - Duration::hours(1));
assert!(matches!(decide_at("s1", t0), Answer::Refuse { .. }));
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);
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");
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}"
);
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%");
}