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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
//! `config.toml` and the tool's own directories.
//!
//! Everything is optional: with no config file the tool discovers seats on its own.

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 {
    /// Index database, vault metadata, backups.
    pub data: PathBuf,
    /// `config.toml`.
    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());
        // The tool was called agentmana before: move its data and config (index, vault of saved
        // logins, config.toml) over once. Never while the old program runs (it would recreate
        // and write its dirs), and never over anything already in the new place.
        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 {
    /// Extra config dirs: `[[seat]] path = "~/claude-work"  label = "work"`.
    pub seat: Vec<SeatConf>,
    /// Project aliases: `[[project]] match = "/old/path"  name = "shop"`.
    pub project: Vec<Alias>,
    /// Price overrides: `[[price]] model = "claude-opus-5-5"  from = "2026-12-01"  input = 4 …`.
    pub price: Vec<PriceConf>,
    /// Display names for accounts: `[accounts] "<account uuid>" = "work"`.
    pub accounts: std::collections::BTreeMap<String, String>,
    /// The Claude Code status line (`swarmy statusline`).
    pub statusline: StatuslineConf,
    /// Monthly subscription price per account label or uuid, for the payback figure.
    pub subscription: std::collections::BTreeMap<String, f64>,
    /// Minutes without transcript activity after which an unfinished agent counts as stalled.
    pub stall_minutes: Option<u64>,
    /// The dashboard's colours; a name not in [`ThemeName`] is a config error (review L3).
    pub theme: Option<ThemeName>,
    /// How long per-request detail is kept, and the size the index may grow to.
    pub storage: StorageConf,
    /// Where agents in guarded seats stop (`swarmy setup --guard`, `swarmy guard`).
    pub guard: GuardConf,
    /// Harnesses to skip during auto-discovery (e.g. `disabled_harnesses = ["agy"]`).
    pub disabled_harnesses: Vec<Harness>,
}

/// The dashboard's colour themes, by the name `config.toml` and `:theme` use.
#[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",
        }
    }

    /// The theme after this one, for the key that cycles them.
    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(", "))
            })
    }
}

/// `[storage]` in config.toml (`docs/design/storage.md` §5).
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct StorageConf {
    /// Days of per-request and per-tool-call detail; older detail is kept as quarter-hour
    /// rollups for good. 8 ..= the shortest transcript retention of the seats − 2
    /// (`core::storage::keep_raw_days`); unset: 14, less when a seat keeps transcripts shorter.
    pub keep_raw_days: Option<i64>,
    /// `doctor` and SYSTEM warn when the 12-month projection goes over this (MB); nothing is
    /// ever deleted because of it.
    pub budget_mb: u64,
    /// The dashboard compacts on its own; `swarmy compact` works either way.
    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,
        }
    }
}

/// `[guard]` in config.toml: the limit lines at which agents in guarded seats (`swarmy setup
/// --guard`) are told to wrap up and then stop. Nothing is set by default: no line, no stop.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct GuardConf {
    /// % of the week at which agents stop, on every account.
    pub week: Option<f64>,
    /// % of the 5-hour window at which agents stop, on every account.
    pub five_hour: Option<f64>,
    /// Points before a line at which agents are told once to wrap up (unset: 5; 0: never).
    pub wrap_up: Option<f64>,
    /// Lines of one account, keyed by a saved login's label or email, its `[accounts]` name or
    /// its uuid (what `swarmy guard` knows without the index); what an entry leaves out comes
    /// from the lines above.
    pub account: std::collections::BTreeMap<String, GuardLine>,
}

/// `[guard.account.<name>]`: one account's own lines.
#[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 {
    /// Some line below 100% anywhere: otherwise `swarmy guard` reads nothing at all.
    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))
    }

    /// The `[guard.account.*]` key that names the account known by `names` (its id, uuids,
    /// labels, emails), compared without case; the first in key order when several do.
    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)
    }

    /// The lines of the account known by `names`: its own entry over the lines for every account.
    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>,
    /// Optional harness (`claude`, `agy`, `codex`); auto-detected from the directory shape when omitted.
    #[serde(default)]
    pub harness: Option<Harness>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PriceConf {
    /// Exact id or a prefix ending in `*`.
    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()
    }

    /// Configured seats with their explicit harness (when set).
    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()
    }

    /// The `[[seat]]` paths and labels of harness `h`: those that say so, and those without
    /// `harness` whose files are `h`'s ([`detect_harness`]; a dir whose files fit several is read
    /// as Claude Code's). Every front end finds configured seats through this (reviews A-M3,
    /// B-M19: the status line and `jump` had their own scans, which missed them).
    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)
    }

    /// Rules TOML cannot express: prices are finite and not negative; a subscription costs a
    /// finite amount above zero (review A-M5: a negative or NaN price gave a payback figure).
    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))?;
            // USD per request, unlike the rest (per million tokens): a price per 1000 searches
            // would price each one 1000 times too high (review B-L11).
            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(())
    }

    /// Adds the `[[price]]` overrides to `book`; what an override leaves out is derived from the
    /// entry it overrides (`PriceBook::push_override`).
    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)
    }
}

/// The harness of a config dir, by the files in it (`Harness::detect`); `Err` names the
/// harnesses whose files are all there.
pub fn detect_harness(dir: &Path) -> Result<Harness, Vec<Harness>> {
    Harness::detect(|f| dir.join(f).exists())
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Review A-M5: a typo in `segments` or a nonsense subscription price fails the config,
    /// instead of a segment silently missing or a payback from a negative price.
    #[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());
    }

    /// First review L3: a misspelt theme is an error naming the themes, not a silent default.
    #[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");
        // Loaded from a file, the error names the file and has a code.
        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;
        // An account named by nothing in the config: the lines for every account.
        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));
        // bob turns the week off; what his entry leaves out comes from above.
        let bob = g.lines_for(&names(&["acc-2/org-1", "bob"]));
        assert_eq!(bob.week, Some(Pct::new(100.0)));
        assert!(!bob.is_set());
        // Matched by email, without case.
        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")
        );
        // No `wrap_up` anywhere: 5 points.
        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 {
        // Cannot tell: assume it runs, and migrate another time.
        return true;
    };
    sys.refresh_processes(sysinfo::ProcessesToUpdate::All, true);
    sys.processes()
        .values()
        .any(|p| p.name().to_string_lossy().starts_with("agentmana"))
}

/// Moves `from` into `to` entry by entry; entries that already exist in `to` stay where they are.
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);
        }
    }
    // Remove the old dir only when everything moved.
    let _ = std::fs::remove_dir(from);
}

/// A piece of the status line (`[statusline] segments`). A name it does not know fails
/// `config.toml` when it is read, instead of a segment silently missing (review A-M5).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum StatusSegment {
    Attention,
    Agents,
    Week,
    FiveHour,
    Context,
    Cost,
    Burn,
}

/// `[statusline]` in config.toml.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct StatuslineConf {
    /// Segments in display order: attention, agents, week, five_hour, context, cost, burn.
    pub segments: Vec<StatusSegment>,
    /// 1, or 2 for a second line with the model, effort, branch and session name.
    pub lines: u8,
    /// Seconds between refreshes of an idle session's line (`swarmy setup` writes it into
    /// Claude Code's `refreshInterval`); 0 = only on Claude Code's own events.
    pub refresh_seconds: u32,
    /// The dashboard's summary counts while it is younger than this.
    pub fresh_seconds: u32,
    /// Columns left free on the right for Claude Code's own notifications.
    pub reserve: u16,
    /// Hide session and project names (also `SWARMY_MASK=1`).
    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,
        }
    }
}