use std::path::{Path, PathBuf};
use anyhow::Context;
use chrono::NaiveDate;
use serde::{Deserialize, Serialize};
use crate::core::guard::Lines;
use crate::core::harness::Harness;
use crate::core::pricing::{PriceBook, RateOverrides, Rates};
use crate::core::units::Pct;
use crate::errors::ConfigError;
use crate::model::project::Alias;
#[derive(Debug, Clone)]
pub struct Dirs {
pub data: PathBuf,
pub config: PathBuf,
pub home: PathBuf,
}
impl Dirs {
pub fn resolve() -> anyhow::Result<Dirs> {
let base = directories::BaseDirs::new().context("cannot determine the home directory")?;
let home = base.home_dir().to_path_buf();
let pd = directories::ProjectDirs::from("", "", "swarmy")
.context("cannot determine data directories")?;
let data = std::env::var_os("SWARMY_DATA_DIR")
.map(PathBuf::from)
.unwrap_or_else(|| pd.data_dir().to_path_buf());
let config = std::env::var_os("SWARMY_CONFIG_DIR")
.map(PathBuf::from)
.unwrap_or_else(|| pd.config_dir().to_path_buf());
if let Some(old) = directories::ProjectDirs::from("", "", "agentmana")
&& (old.data_dir().exists() || old.config_dir().exists())
&& !old_program_running()
{
for (from, to) in [(old.data_dir(), &data), (old.config_dir(), &config)] {
migrate_dir(from, to);
}
}
Ok(Dirs { data, config, home })
}
pub fn config_file(&self) -> PathBuf {
self.config.join("config.toml")
}
pub fn index_file(&self) -> PathBuf {
self.data.join("index.sqlite")
}
pub fn vault_dir(&self) -> PathBuf {
self.data.join("vault")
}
}
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct Config {
pub seat: Vec<SeatConf>,
pub project: Vec<Alias>,
pub price: Vec<PriceConf>,
pub accounts: std::collections::BTreeMap<String, String>,
pub statusline: StatuslineConf,
pub subscription: std::collections::BTreeMap<String, f64>,
pub stall_minutes: Option<u64>,
pub theme: Option<ThemeName>,
pub storage: StorageConf,
pub guard: GuardConf,
pub disabled_harnesses: Vec<Harness>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum ThemeName {
#[default]
Ops,
Phosphor,
Amber,
Plain,
}
impl ThemeName {
pub const ALL: [ThemeName; 4] = [
ThemeName::Ops,
ThemeName::Phosphor,
ThemeName::Amber,
ThemeName::Plain,
];
pub fn as_str(self) -> &'static str {
match self {
ThemeName::Ops => "ops",
ThemeName::Phosphor => "phosphor",
ThemeName::Amber => "amber",
ThemeName::Plain => "plain",
}
}
pub fn next(self) -> ThemeName {
let i = Self::ALL
.iter()
.position(|t| *t == self)
.map_or(0, |i| i + 1);
Self::ALL[i % Self::ALL.len()]
}
}
impl std::str::FromStr for ThemeName {
type Err = String;
fn from_str(s: &str) -> Result<ThemeName, String> {
Self::ALL
.into_iter()
.find(|t| t.as_str() == s)
.ok_or_else(|| {
let names: Vec<&str> = Self::ALL.iter().map(|t| t.as_str()).collect();
format!("unknown theme '{s}' (themes: {})", names.join(", "))
})
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct StorageConf {
pub keep_raw_days: Option<i64>,
pub budget_mb: u64,
pub auto_compact: bool,
}
impl Default for StorageConf {
fn default() -> Self {
StorageConf {
keep_raw_days: None,
budget_mb: crate::core::storage::DEFAULT_BUDGET_MB,
auto_compact: true,
}
}
}
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct GuardConf {
pub week: Option<f64>,
pub five_hour: Option<f64>,
pub wrap_up: Option<f64>,
pub account: std::collections::BTreeMap<String, GuardLine>,
}
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct GuardLine {
pub week: Option<f64>,
pub five_hour: Option<f64>,
pub wrap_up: Option<f64>,
}
impl GuardConf {
pub fn is_set(&self) -> bool {
let on = |l: Option<f64>| l.is_some_and(|l| l < Lines::OFF_AT);
on(self.week)
|| on(self.five_hour)
|| self.account.values().any(|a| on(a.week) || on(a.five_hour))
}
pub fn key_for<'a>(&'a self, names: &[String]) -> Option<&'a str> {
self.account
.keys()
.find(|k| names.iter().any(|n| n.eq_ignore_ascii_case(k.trim())))
.map(String::as_str)
}
pub fn lines_for(&self, names: &[String]) -> Lines {
let own = self.key_for(names).and_then(|k| self.account.get(k));
let pick = |own: Option<f64>, all: Option<f64>| own.or(all).map(Pct::new);
Lines {
week: pick(own.and_then(|a| a.week), self.week),
five_hour: pick(own.and_then(|a| a.five_hour), self.five_hour),
wrap_up: pick(own.and_then(|a| a.wrap_up), self.wrap_up)
.unwrap_or(Pct::new(Lines::DEFAULT_WRAP_UP)),
}
}
fn validate(&self) -> Result<(), String> {
let check = |at: &str, l: &GuardLine| -> Result<(), String> {
for (name, v) in [("week", l.week), ("five_hour", l.five_hour)] {
if let Some(v) = v
&& !(v.is_finite() && v > 0.0 && v <= Lines::OFF_AT)
{
return Err(format!("{at} {name}: a % above 0, at most 100 (got {v})"));
}
}
if let Some(w) = l.wrap_up
&& !(w.is_finite() && (0.0..50.0).contains(&w))
{
return Err(format!("{at} wrap_up: points from 0 to under 50 (got {w})"));
}
Ok(())
};
check(
"[guard]",
&GuardLine {
week: self.week,
five_hour: self.five_hour,
wrap_up: self.wrap_up,
},
)?;
for (k, l) in &self.account {
check(&format!("[guard.account.{k}]"), l)?;
}
Ok(())
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct SeatConf {
pub path: String,
pub label: Option<String>,
#[serde(default)]
pub harness: Option<Harness>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PriceConf {
pub model: String,
pub from: Option<NaiveDate>,
pub input: f64,
pub output: f64,
pub cache_write_5m: Option<f64>,
pub cache_write_1h: Option<f64>,
pub cache_read: Option<f64>,
pub web_search: Option<f64>,
pub fast_multiplier: Option<f64>,
}
impl Config {
pub fn load(dirs: &Dirs) -> anyhow::Result<Config> {
let p = dirs.config_file();
let invalid = |message: String| ConfigError::Invalid {
path: p.clone(),
message,
};
match std::fs::read_to_string(&p) {
Ok(text) => {
let c: Config = toml::from_str(&text).map_err(|e| invalid(e.to_string()))?;
c.validate().map_err(invalid)?;
Ok(c)
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Config::default()),
Err(source) => Err(ConfigError::Unreadable { path: p, source }.into()),
}
}
pub fn stall_minutes(&self) -> u64 {
self.stall_minutes.unwrap_or(20)
}
pub fn seat_paths(&self, home: &Path) -> Vec<(PathBuf, Option<String>)> {
self.seat
.iter()
.filter(|s| s.harness.is_none_or(|h| h == Harness::Claude))
.map(|s| (expand_home(&s.path, home), s.label.clone()))
.collect()
}
pub fn seat_entries(&self, home: &Path) -> Vec<(PathBuf, Option<String>, Option<Harness>)> {
self.seat
.iter()
.map(|s| (expand_home(&s.path, home), s.label.clone(), s.harness))
.collect()
}
pub fn seats_of(&self, home: &Path, h: Harness) -> Vec<(PathBuf, Option<String>)> {
self.seat_entries(home)
.into_iter()
.filter(|(path, _, explicit)| {
explicit.unwrap_or_else(|| detect_harness(path).unwrap_or(Harness::Claude)) == h
})
.map(|(path, label, _)| (path, label))
.collect()
}
pub fn harness_enabled(&self, h: Harness) -> bool {
!self.disabled_harnesses.contains(&h)
}
pub fn validate(&self) -> Result<(), String> {
self.guard.validate()?;
for (account, usd) in &self.subscription {
if !(usd.is_finite() && *usd > 0.0) {
return Err(format!(
"[subscription] {account}: a monthly price above 0 (got {usd})"
));
}
}
for p in &self.price {
let rates = Rates::derive(p.input, p.output, &p.overrides(), None);
rates
.validate()
.map_err(|e| format!("[[price]] {}: {e}", p.model))?;
if rates.web_search > crate::core::pricing::MAX_WEB_SEARCH_USD {
return Err(format!(
"[[price]] {}: web_search is USD per request (got {}; $10 per 1000 searches is 0.01)",
p.model, rates.web_search
));
}
}
Ok(())
}
pub fn apply_prices(&self, book: &mut PriceBook, today: NaiveDate) -> anyhow::Result<()> {
for p in &self.price {
book.push_override(&p.model, p.from, p.input, p.output, &p.overrides(), today)
.map_err(|e| anyhow::anyhow!("[[price]] {}: {e}", p.model))?;
}
Ok(())
}
}
impl PriceConf {
fn overrides(&self) -> RateOverrides {
RateOverrides {
cache_write_5m: self.cache_write_5m,
cache_write_1h: self.cache_write_1h,
cache_read: self.cache_read,
web_search: self.web_search,
fast_multiplier: self.fast_multiplier,
}
}
}
pub fn expand_home(p: &str, home: &Path) -> PathBuf {
if p == "~" {
home.to_path_buf()
} else if let Some(rest) = p.strip_prefix("~/") {
home.join(rest)
} else {
PathBuf::from(p)
}
}
pub fn detect_harness(dir: &Path) -> Result<Harness, Vec<Harness>> {
Harness::detect(|f| dir.join(f).exists())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn segments_and_subscriptions_are_checked() {
assert!(toml::from_str::<Config>("[statusline]\nsegments = [\"wek\"]\n").is_err());
let ok: Config =
toml::from_str("[statusline]\nsegments = [\"week\", \"five_hour\"]\n").unwrap();
assert_eq!(
ok.statusline.segments,
[StatusSegment::Week, StatusSegment::FiveHour]
);
let bad: Config = toml::from_str("[subscription]\nwork = -20\n").unwrap();
assert!(bad.validate().is_err());
let good: Config = toml::from_str("[subscription]\nwork = 200\n").unwrap();
assert!(good.validate().is_ok());
}
#[test]
fn a_web_search_price_per_thousand_is_refused() {
let c: Config = toml::from_str(
"[[price]]\nmodel = \"claude-opus-5-5\"\ninput = 4\noutput = 20\nweb_search = 10\n",
)
.unwrap();
let e = c.validate().unwrap_err();
assert!(e.contains("USD per request"), "{e}");
let ok: Config = toml::from_str(
"[[price]]\nmodel = \"claude-opus-5-5\"\ninput = 4\noutput = 20\nweb_search = 0.01\n",
)
.unwrap();
assert!(ok.validate().is_ok());
}
#[test]
fn themes_are_checked() {
let c: Config = toml::from_str("theme = \"amber\"").unwrap();
assert_eq!(c.theme, Some(ThemeName::Amber));
let e = toml::from_str::<Config>("theme = \"ambr\"")
.unwrap_err()
.to_string();
assert!(e.contains("ambr") && e.contains("phosphor"), "{e}");
assert_eq!("plain".parse::<ThemeName>(), Ok(ThemeName::Plain));
assert!(
"Ops"
.parse::<ThemeName>()
.unwrap_err()
.contains("ops, phosphor, amber, plain")
);
let mut t = ThemeName::default();
for _ in 0..ThemeName::ALL.len() {
t = t.next();
}
assert_eq!(t, ThemeName::Ops, "the cycle visits every theme");
let d = tempfile::tempdir().unwrap();
let dirs = Dirs {
data: d.path().join("data"),
config: d.path().to_path_buf(),
home: d.path().to_path_buf(),
};
std::fs::write(dirs.config_file(), "theme = \"ambr\"\n").unwrap();
let e = Config::load(&dirs).unwrap_err();
assert_eq!(crate::errors::code_of(&e), Some("config-invalid"));
}
#[test]
fn parses_a_full_config() {
let c: Config = toml::from_str(
r#"
stall_minutes = 30
[[seat]]
path = "~/cc-work"
label = "work"
[[project]]
match = "/home/user/work/old"
name = "shop"
[[price]]
model = "claude-opus-5-5"
from = "2026-12-01"
input = 3
output = 15
[accounts]
"acc-1" = "personal"
[subscription]
personal = 200
[storage]
keep_raw_days = 21
auto_compact = false
[guard]
week = 85
[guard.account.personal]
five_hour = 95
"#,
)
.unwrap();
assert_eq!(c.stall_minutes(), 30);
assert!(c.guard.is_set());
assert_eq!(c.guard.account["personal"].five_hour, Some(95.0));
assert_eq!(c.storage.keep_raw_days, Some(21));
assert!(!c.storage.auto_compact);
assert_eq!(
c.storage.budget_mb, 1024,
"what is left out keeps its default"
);
assert!(Config::default().storage.auto_compact);
assert_eq!(
c.seat_paths(Path::new("/h"))[0].0,
PathBuf::from("/h/cc-work")
);
let mut b = PriceBook::default();
c.apply_prices(&mut b, NaiveDate::from_ymd_opt(2026, 11, 22).unwrap())
.unwrap();
assert_eq!(b.entries()[0].rates.cache_write_1h, 6.0);
let bad: Config =
toml::from_str("[[price]]\nmodel = \"claude-opus-5-5\"\ninput = -3\noutput = nan\n")
.unwrap();
let e = bad.validate().unwrap_err();
assert!(e.contains("claude-opus-5-5") && e.contains("input"), "{e}");
assert!(
toml::from_str::<Config>("bogus = 1").is_err(),
"typos are reported"
);
}
fn names(v: &[&str]) -> Vec<String> {
v.iter().map(|s| s.to_string()).collect()
}
#[test]
fn guard_lines_come_from_the_account_entry_over_the_defaults() {
let c: Config = toml::from_str(
r#"
[guard]
week = 85
wrap_up = 4
[guard.account.bob]
week = 100
[guard.account."alice@example.com"]
five_hour = 90
"#,
)
.unwrap();
let g = &c.guard;
let other = g.lines_for(&names(&["acc-3/org-1", "acc-3"]));
assert_eq!(other.week, Some(Pct::new(85.0)));
assert_eq!(other.five_hour, None);
assert_eq!(other.wrap_up, Pct::new(4.0));
let bob = g.lines_for(&names(&["acc-2/org-1", "bob"]));
assert_eq!(bob.week, Some(Pct::new(100.0)));
assert!(!bob.is_set());
let alice = g.lines_for(&names(&["acc-1/org-1", "Alice@Example.com"]));
assert_eq!(alice.week, Some(Pct::new(85.0)));
assert_eq!(alice.five_hour, Some(Pct::new(90.0)));
assert_eq!(
g.key_for(&names(&["ALICE@example.com"])),
Some("alice@example.com")
);
assert_eq!(
GuardConf::default().lines_for(&[]).wrap_up,
Pct::new(Lines::DEFAULT_WRAP_UP)
);
}
#[test]
fn guard_is_set_only_by_a_line_below_100() {
assert!(!GuardConf::default().is_set());
let off: Config = toml::from_str("[guard]\nweek = 100\nwrap_up = 3\n").unwrap();
assert!(!off.guard.is_set());
let one: Config = toml::from_str("[guard.account.bob]\nfive_hour = 90\n").unwrap();
assert!(one.guard.is_set());
}
#[test]
fn guard_lines_outside_their_range_are_config_errors() {
for (text, says) in [
("[guard]\nweek = 0\n", "[guard] week"),
("[guard]\nweek = 120\n", "[guard] week"),
("[guard]\nwrap_up = 50\n", "[guard] wrap_up"),
(
"[guard.account.bob]\nfive_hour = -1\n",
"[guard.account.bob] five_hour",
),
] {
let c: Config = toml::from_str(text).unwrap();
let e = c.validate().unwrap_err();
assert!(e.contains(says), "{text}: {e}");
}
let ok: Config = toml::from_str("[guard]\nweek = 100\nwrap_up = 0\n").unwrap();
assert!(ok.validate().is_ok());
assert!(
toml::from_str::<Config>("[guard]\nweeks = 85\n").is_err(),
"unknown keys are errors"
);
}
}
fn old_program_running() -> bool {
let Ok(mut sys) = sysinfo::System::new() else {
return true;
};
sys.refresh_processes(sysinfo::ProcessesToUpdate::All, true);
sys.processes()
.values()
.any(|p| p.name().to_string_lossy().starts_with("agentmana"))
}
fn migrate_dir(from: &std::path::Path, to: &std::path::Path) {
if !from.is_dir() || from == to {
return;
}
let _ = std::fs::create_dir_all(to);
if let Ok(entries) = std::fs::read_dir(from) {
for e in entries.flatten() {
let dest = to.join(e.file_name());
if dest.exists() {
if e.path().is_dir() && dest.is_dir() {
migrate_dir(&e.path(), &dest);
}
continue;
}
let _ = std::fs::rename(e.path(), &dest);
}
}
let _ = std::fs::remove_dir(from);
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum StatusSegment {
Attention,
Agents,
Week,
FiveHour,
Context,
Cost,
Burn,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct StatuslineConf {
pub segments: Vec<StatusSegment>,
pub lines: u8,
pub refresh_seconds: u32,
pub fresh_seconds: u32,
pub reserve: u16,
pub mask: bool,
}
impl Default for StatuslineConf {
fn default() -> Self {
StatuslineConf {
segments: vec![
StatusSegment::Attention,
StatusSegment::Agents,
StatusSegment::Week,
StatusSegment::FiveHour,
StatusSegment::Context,
StatusSegment::Cost,
StatusSegment::Burn,
],
lines: 1,
refresh_seconds: 10,
fresh_seconds: 15,
reserve: 0,
mask: false,
}
}
}