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
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
//! `swarmy setup`: a short wizard for a new machine.
//!
//! 1. Lists the Claude Code config dirs ("seats") it found.
//! 2. Offers the swarmy status line in each seat's `settings.json`: Claude Code then shows week and
//!    5-hour use under the prompt, and swarmy gets exact limit readings after every response. A
//!    status line the user already has is kept and shown first (`swarmy statusline --then …`).
//!    The old file is backed up next to it; `swarmy setup --remove` puts things back.
//! 3. Offers to save the logins the seats hold in the vault, so they can be switched later.
//!
//! `swarmy setup --guard` instead offers the limit guard, seat by seat: a `PreToolUse` hook
//! (`swarmy guard`) in `settings.json` that tells agents to wrap up, then stops them, at the
//! lines of `[guard]` in config.toml. Only seats with the swarmy status line can have it: the
//! status line brings the numbers the guard acts on.
//!
//! The only files it writes in a config dir are `settings.json` (and its backup), and only after a
//! yes (or `--yes`).

use std::io::{BufRead, IsTerminal, Write};
use std::path::{Path, PathBuf};

use anyhow::Context as _;
use clap::Args;
use serde_json::{Map, Value, json};

use crate::app::context::Ctx;
use crate::claude::seats::Seat;
use crate::core::harness::Harness;
use crate::ui::style::Tone;

#[derive(Args, Debug, Clone)]
pub struct SetupArgs {
    /// Answer yes to every question.
    #[arg(long, short)]
    pub yes: bool,
    /// Take swarmy out of every seat: the status line (restoring the one it wrapped) and the
    /// guard hook. With --guard: only the guard hook.
    #[arg(long)]
    pub remove: bool,
    /// Do not offer to save logins in the vault.
    #[arg(long)]
    pub no_vault: bool,
    /// Offer the limit guard, seat by seat: before each tool call Claude Code asks `swarmy guard`,
    /// which tells agents to wrap up and then stops them at the lines of `[guard]` in config.toml.
    #[arg(long)]
    pub guard: bool,
}

/// What a seat's `settings.json` has as its status line.
#[derive(Debug, Clone, PartialEq)]
pub enum StatusLine {
    None,
    Swarmy { wraps: Option<String> },
    Other(String),
}

pub fn settings_file(seat: &Seat) -> PathBuf {
    seat.dir.join("settings.json")
}

fn read_settings(path: &Path) -> anyhow::Result<Map<String, Value>> {
    match std::fs::read_to_string(path) {
        Ok(t) if t.trim().is_empty() => Ok(Map::new()),
        Ok(t) => match serde_json::from_str::<Value>(&t) {
            Ok(Value::Object(m)) => Ok(m),
            Ok(_) | Err(_) => {
                Err(crate::errors::SetupError::SettingsDamaged(path.to_path_buf()).into())
            }
        },
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Map::new()),
        Err(e) => Err(e).with_context(|| format!("cannot read {}", path.display())),
    }
}

pub fn status_line_of(settings: &Map<String, Value>) -> StatusLine {
    let Some(cmd) = settings
        .get("statusLine")
        .and_then(|s| s.get("command"))
        .and_then(Value::as_str)
    else {
        return StatusLine::None;
    };
    match cmd.find(" statusline") {
        Some(_) if cmd.contains("swarmy") => StatusLine::Swarmy {
            wraps: wrapped(cmd),
        },
        _ => StatusLine::Other(cmd.to_string()),
    }
}

pub fn seat_status_line(seat: &Seat) -> StatusLine {
    read_settings(&settings_file(seat))
        .map(|s| status_line_of(&s))
        .unwrap_or(StatusLine::None)
}

/// POSIX single quotes: `it's` → `'it'\''s'`.
fn sh_quote(s: &str) -> String {
    format!("'{}'", s.replace('\'', r"'\''"))
}

/// The command a `--then '…'` argument wraps, undoing `sh_quote`.
fn wrapped(cmd: &str) -> Option<String> {
    let rest = cmd.split_once("--then ")?.1.trim();
    let inner = rest.strip_prefix('\'')?.strip_suffix('\'')?;
    Some(inner.replace(r"'\''", "'"))
}

/// This binary as a command's first word: quoted when its path has a space.
fn exe_word(exe: &Path) -> String {
    let exe = exe.to_string_lossy();
    if exe.contains(' ') {
        format!("\"{exe}\"")
    } else {
        exe.into_owned()
    }
}

/// The status-line command for this binary, wrapping `previous` when there is one.
pub fn command_for(exe: &Path, previous: Option<&str>) -> String {
    let exe = exe_word(exe);
    match previous {
        Some(p) => format!("{exe} statusline --then {}", sh_quote(p)),
        None => format!("{exe} statusline"),
    }
}

/// The new `settings.json` content, or `None` when nothing changes.
pub fn with_status_line(
    mut settings: Map<String, Value>,
    exe: &Path,
    remove: bool,
    refresh: u32,
) -> Option<Map<String, Value>> {
    let current_refresh = settings
        .get("statusLine")
        .and_then(|s| s.get("refreshInterval"))
        .and_then(Value::as_u64);
    match (status_line_of(&settings), remove) {
        // Ours already: only the refresh timer may need adding.
        (StatusLine::Swarmy { .. }, false) => {
            if refresh == 0 || current_refresh.is_some() {
                return None;
            }
            settings["statusLine"]["refreshInterval"] = json!(refresh);
            Some(settings)
        }
        (StatusLine::None | StatusLine::Other(_), true) => None,
        (StatusLine::None, false) => {
            let mut sl = json!({"type": "command", "command": command_for(exe, None)});
            if refresh > 0 {
                // Idle sessions re-run it on this timer, so "needs you" elsewhere shows up.
                sl["refreshInterval"] = json!(refresh);
            }
            settings.insert("statusLine".into(), sl);
            Some(settings)
        }
        (StatusLine::Other(prev), false) => {
            let mut sl = settings
                .get("statusLine")
                .cloned()
                .unwrap_or_else(|| json!({}));
            sl["command"] = Value::String(command_for(exe, Some(&prev)));
            if refresh > 0 && sl.get("refreshInterval").is_none() {
                sl["refreshInterval"] = json!(refresh);
            }
            settings.insert("statusLine".into(), sl);
            Some(settings)
        }
        (StatusLine::Swarmy { wraps }, true) => {
            match wraps {
                Some(prev) => {
                    let mut sl = settings
                        .get("statusLine")
                        .cloned()
                        .unwrap_or_else(|| json!({}));
                    sl["command"] = Value::String(prev);
                    if let Some(o) = sl.as_object_mut() {
                        o.remove("refreshInterval");
                    }
                    settings.insert("statusLine".into(), sl);
                }
                None => {
                    settings.remove("statusLine");
                }
            }
            Some(settings)
        }
    }
}

/// Seconds Claude Code gives the guard before going on without it (a hook that times out does
/// not refuse the call); the guard takes milliseconds.
const GUARD_TIMEOUT_S: u64 = 5;

/// Whether a hook command is the guard's (`<path>/swarmy guard`).
pub fn is_guard_command(cmd: &str) -> bool {
    cmd.contains("swarmy") && cmd.trim_end().ends_with(" guard")
}

/// The guard's hook command for this binary.
pub fn guard_command(exe: &Path) -> String {
    format!("{} guard", exe_word(exe))
}

/// The commands of a settings file's `PreToolUse` hooks.
fn pre_tool_commands(settings: &Map<String, Value>) -> Vec<&str> {
    settings
        .get("hooks")
        .and_then(|h| h.get("PreToolUse"))
        .and_then(Value::as_array)
        .into_iter()
        .flatten()
        .filter_map(|group| group.get("hooks").and_then(Value::as_array))
        .flatten()
        .filter_map(|h| h.get("command").and_then(Value::as_str))
        .collect()
}

/// Whether a settings file has the guard hook.
pub fn has_guard(settings: &Map<String, Value>) -> bool {
    pre_tool_commands(settings)
        .into_iter()
        .any(is_guard_command)
}

/// Whether a seat has the guard hook (`swarmy doctor`).
pub fn seat_has_guard(seat: &Seat) -> bool {
    read_settings(&settings_file(seat)).is_ok_and(|s| has_guard(&s))
}

/// The new `settings.json` content with the guard hook added (or taken out), or `None` when
/// nothing changes. Other hooks stay as they are; containers left empty by a removal go. A
/// `hooks` of a shape Claude Code would not read either is not touched: an error says so.
pub fn with_guard_hook(
    mut settings: Map<String, Value>,
    exe: &Path,
    remove: bool,
) -> Result<Option<Map<String, Value>>, String> {
    let shape = "its \"hooks\" is not the shape Claude Code reads; left as it is";
    if remove {
        if !has_guard(&settings) {
            return Ok(None);
        }
        let Some(hooks) = settings.get_mut("hooks").and_then(Value::as_object_mut) else {
            return Err(shape.into());
        };
        let Some(groups) = hooks.get_mut("PreToolUse").and_then(Value::as_array_mut) else {
            return Err(shape.into());
        };
        for g in groups.iter_mut() {
            if let Some(list) = g.get_mut("hooks").and_then(Value::as_array_mut) {
                list.retain(|h| {
                    !h.get("command")
                        .and_then(Value::as_str)
                        .is_some_and(is_guard_command)
                });
            }
        }
        groups.retain(|g| {
            g.get("hooks")
                .and_then(Value::as_array)
                .is_none_or(|l| !l.is_empty())
        });
        if groups.is_empty() {
            hooks.remove("PreToolUse");
        }
        if hooks.is_empty() {
            settings.remove("hooks");
        }
        return Ok(Some(settings));
    }
    if has_guard(&settings) {
        return Ok(None);
    }
    let hooks = settings
        .entry("hooks")
        .or_insert_with(|| json!({}))
        .as_object_mut()
        .ok_or(shape)?;
    let groups = hooks
        .entry("PreToolUse")
        .or_insert_with(|| json!([]))
        .as_array_mut()
        .ok_or(shape)?;
    groups.push(json!({
        "matcher": "*",
        "hooks": [{"type": "command", "command": guard_command(exe), "timeout": GUARD_TIMEOUT_S}],
    }));
    Ok(Some(settings))
}

/// Backs up the old file (when there is one) and writes the new one atomically.
fn write_settings(path: &Path, settings: &Map<String, Value>) -> anyhow::Result<Option<PathBuf>> {
    let backup = if path.exists() {
        // Never over an older backup: two runs within a second must both keep theirs.
        let stamp = chrono::Local::now().format("%Y%m%d-%H%M%S");
        let mut b = path.with_extension(format!("json.swarmy-{stamp}.bak"));
        let mut n = 1;
        while b.exists() {
            b = path.with_extension(format!("json.swarmy-{stamp}-{n}.bak"));
            n += 1;
        }
        std::fs::copy(path, &b).with_context(|| format!("cannot back up {}", path.display()))?;
        Some(b)
    } else {
        None
    };
    let mut text = serde_json::to_string_pretty(&Value::Object(settings.clone()))?;
    text.push('\n');
    // Claude Code's file: it keeps its mode.
    crate::fsutil::atomic_write(path, text.as_bytes(), crate::fsutil::Mode::KeepExisting)
        .with_context(|| format!("cannot write {}", path.display()))?;
    Ok(backup)
}

fn ask(question: &str, yes: bool) -> bool {
    if yes {
        println!("{question} [Y/n] y");
        return true;
    }
    print!("{question} [Y/n] ");
    let _ = std::io::stdout().flush();
    let mut line = String::new();
    if std::io::stdin().lock().read_line(&mut line).is_err() {
        return false;
    }
    !matches!(line.trim().to_lowercase().as_str(), "n" | "no")
}

pub fn run(ctx: &Ctx, a: &SetupArgs) -> anyhow::Result<()> {
    let p = &ctx.painter;
    if !a.yes && !std::io::stdin().is_terminal() {
        anyhow::bail!("setup asks questions: run it in a terminal, or with --yes");
    }
    let home = &ctx.dirs.home;
    let show = |path: &Path| match path.strip_prefix(home) {
        Ok(rest) => format!("~/{}", rest.display()),
        Err(_) => path.display().to_string(),
    };
    println!("{}", p.paint("swarmy setup", Tone::Header));
    let claude_seats: Vec<&Seat> = ctx
        .seats
        .iter()
        .filter(|s| s.harness.supports_statusline())
        .collect();
    if a.guard {
        return guard_step(ctx, a, &claude_seats, &show);
    }
    // The status line is Claude Code's; a machine with only agy or Codex seats still gets the
    // saved-logins step below (review A-L2).
    'statusline: {
        if claude_seats.is_empty() {
            println!("No Claude Code config dir found: no status line to install.");
            break 'statusline;
        }
        println!("\nClaude Code config dirs (seats) found:");
        for s in &claude_seats {
            let state = match seat_status_line(s) {
                StatusLine::None => p.paint("no status line", Tone::Dim),
                StatusLine::Swarmy { .. } => p.paint("swarmy status line ✓", Tone::Good),
                StatusLine::Other(_) => p.paint("has its own status line", Tone::Dim),
            };
            println!("  {:<12} {:<34} {state}", s.label, show(&s.dir));
        }
        let exe = std::env::current_exe().context("cannot find the swarmy binary")?;
        let exe = crate::fsutil::canonical(&exe).unwrap_or(exe);

        // 1. The status line.
        let todo: Vec<&Seat> = claude_seats
            .iter()
            .copied()
            .filter(|s| match read_settings(&settings_file(s)) {
                Ok(settings) => with_status_line(
                    settings,
                    &exe,
                    a.remove,
                    ctx.config.statusline.refresh_seconds,
                )
                .is_some(),
                // Never taken for an empty file: that seat is left out, and says why.
                Err(e) => {
                    println!("  {} {e:#}", p.paint("skipped:", Tone::Warn));
                    false
                }
            })
            .collect();
        println!();
        if todo.is_empty() {
            println!(
                "{}",
                if a.remove {
                    "No seat has the swarmy status line."
                } else {
                    "Every seat already has the swarmy status line."
                }
            );
        } else {
            let q = if a.remove {
                format!("Take the swarmy status line out of {} seat(s)?", todo.len())
            } else {
                println!(
                    "The swarmy status line shows week and 5-hour use under Claude Code's prompt, and"
                );
                println!(
                    "gives swarmy the exact limits after every response (no network, nothing else changes)."
                );
                println!("A status line you already have stays and is shown first.");
                let fresh = todo
                    .iter()
                    .filter(|s| !matches!(seat_status_line(s), StatusLine::Swarmy { .. }))
                    .count();
                if fresh == 0 {
                    format!(
                        "Update the swarmy status line in {} seat(s) (refresh every {} s)?",
                        todo.len(),
                        ctx.config.statusline.refresh_seconds
                    )
                } else {
                    format!("Add it to {} seat(s)?", todo.len())
                }
            };
            if ask(&q, a.yes) {
                for s in todo {
                    let path = settings_file(s);
                    let settings = read_settings(&path)?;
                    if let Some(new) = with_status_line(
                        settings,
                        &exe,
                        a.remove,
                        ctx.config.statusline.refresh_seconds,
                    ) {
                        let backup = write_settings(&path, &new)?;
                        println!(
                            "  {} {}{}",
                            p.paint("✓", Tone::Good),
                            show(&path),
                            backup
                                .map(|b| format!(" (backup: {})", show(&b)))
                                .unwrap_or_default()
                        );
                    }
                }
                if !a.remove {
                    println!("  Claude Code shows it with the next response (or after a restart).");
                }
            }
        }
    }

    // `--remove` takes the guard out too: without the status line it has no numbers.
    if a.remove && !claude_seats.is_empty() {
        guard_step(ctx, a, &claude_seats, &show)?;
    }

    // 2. Saved logins.
    // Claude Code on macOS keeps its login in the Keychain: say so instead of offering nothing.
    if !a.remove
        && !a.no_vault
        && ctx.seats.iter().any(|s| s.harness == Harness::Claude)
        && let Some(e) = crate::vault::unavailable(Harness::Claude)
    {
        println!(
            "{}",
            ctx.painter.paint(&format!("Saved logins: {e}."), Tone::Dim)
        );
    }
    if !a.remove && !a.no_vault {
        let mut v = crate::vault::Vault::open(&ctx.dirs.vault_dir())?;
        let vault_seats: Vec<Seat> = ctx
            .seats
            .iter()
            .filter(|s| s.harness.supports_vault())
            .cloned()
            .collect();
        let states = v.edit(|tx| tx.seat_states(&vault_seats))?;
        let unsaved: Vec<&Seat> = ctx
            .seats
            .iter()
            .filter(|s| {
                s.harness.supports_vault()
                    && states
                        .get(&s.id)
                        .is_some_and(|st| st.fingerprint.is_some() && st.saved_as.is_none())
            })
            .collect();
        if !unsaved.is_empty() {
            println!();
            println!(
                "Saving a seat's login lets you put another account into it when a limit runs out,"
            );
            println!(
                "and switch back later (dashboard: panel 2, Enter; or `swarmy accounts switch`)."
            );
            for s in unsaved {
                if ask(
                    &format!("Save the login of seat '{}' in the vault?", s.label),
                    a.yes,
                ) {
                    match v.edit(|tx| tx.capture(s, None))? {
                        Some(id) => println!(
                            "  {} saved as '{}'",
                            p.paint("✓", Tone::Good),
                            v.logins()
                                .iter()
                                .find(|l| l.id == id)
                                .map(|l| l.label.as_str())
                                .unwrap_or("?")
                        ),
                        None => println!("  no login in this seat"),
                    }
                }
            }
        }
    }
    println!(
        "\nDone. Run {} for the dashboard, {} for keys and a legend.",
        p.paint("swarmy", Tone::Accent),
        p.paint("?", Tone::Accent)
    );
    Ok(())
}

/// `swarmy setup --guard`: the guard hook, seat by seat; with `--remove`, out of every seat.
fn guard_step(
    ctx: &Ctx,
    a: &SetupArgs,
    seats: &[&Seat],
    show: &dyn Fn(&Path) -> String,
) -> anyhow::Result<()> {
    let p = &ctx.painter;
    if seats.is_empty() {
        println!("No Claude Code config dir found: no seat to guard.");
        return Ok(());
    }
    let exe = std::env::current_exe().context("cannot find the swarmy binary")?;
    let exe = crate::fsutil::canonical(&exe).unwrap_or(exe);
    let mut readable: Vec<(&Seat, Map<String, Value>)> = Vec::new();
    for s in seats {
        match read_settings(&settings_file(s)) {
            Ok(st) => readable.push((s, st)),
            // Never taken for an empty file: that seat is left out, and says why.
            Err(e) => println!("  {} {e:#}", p.paint("skipped:", Tone::Warn)),
        }
    }
    if a.remove {
        let todo: Vec<&Seat> = readable
            .iter()
            .filter(|(_, st)| has_guard(st))
            .map(|(s, _)| *s)
            .collect();
        if todo.is_empty() {
            println!("No seat has the guard hook.");
        } else if ask(
            &format!("Take the guard hook out of {} seat(s)?", todo.len()),
            a.yes,
        ) {
            for s in todo {
                apply_guard(ctx, s, &exe, true, show)?;
            }
        }
        return Ok(());
    }
    println!();
    println!("The limit guard: before every tool call in a guarded seat, Claude Code asks swarmy");
    println!(
        "whether the account has reached the line set in config.toml [guard]. Agents are told"
    );
    println!(
        "once to wrap up a few points before it, and stop at it. A seat without the guard keeps"
    );
    println!("working, so the rest of the limit stays yours there.");
    println!();
    for (s, st) in &readable {
        let row = format!("  {:<12} {:<34}", s.label, show(&s.dir));
        if has_guard(st) {
            println!("{row} {}", p.paint("guarded ✓", Tone::Good));
        } else if !matches!(status_line_of(st), StatusLine::Swarmy { .. }) {
            println!(
                "{row} {}",
                p.paint(
                    "needs the swarmy status line first (swarmy setup)",
                    Tone::Dim
                )
            );
        } else if ask(&format!("{row} guard it?"), a.yes) {
            apply_guard(ctx, s, &exe, false, show)?;
        }
    }
    if ctx.config.guard.is_set() {
        println!("  New Claude Code sessions use it; restart the running ones.");
        println!("  `swarmy doctor` shows the line of every account.");
    } else {
        println!(
            "\nNo line is set yet: the guard lets everything through. Add one to {}:",
            show(&ctx.dirs.config_file())
        );
        println!("  [guard]");
        println!("  week = 85                  # agents stop at 85% of the week, on every account");
        println!("  # wrap_up = 5              # and are told to wrap up 5 points before");
        println!(
            "  # [guard.account.personal] # one account's line: saved login label or email, or uuid"
        );
        println!("  # week = 80");
    }
    Ok(())
}

/// Adds the guard hook to a seat's `settings.json` (or takes it out), with a backup.
fn apply_guard(
    ctx: &Ctx,
    s: &Seat,
    exe: &Path,
    remove: bool,
    show: &dyn Fn(&Path) -> String,
) -> anyhow::Result<()> {
    let p = &ctx.painter;
    let path = settings_file(s);
    match with_guard_hook(read_settings(&path)?, exe, remove) {
        Ok(Some(new)) => {
            let backup = write_settings(&path, &new)?;
            println!(
                "  {} {}{}",
                p.paint("✓", Tone::Good),
                show(&path),
                backup.map_or(String::new(), |b| format!(" (backup: {})", show(&b)))
            );
        }
        Ok(None) => {}
        Err(why) => println!(
            "  {} {}: {why}",
            p.paint("skipped:", Tone::Warn),
            show(&path)
        ),
    }
    Ok(())
}

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

    fn obj(v: Value) -> Map<String, Value> {
        v.as_object().unwrap().clone()
    }

    #[test]
    fn adds_wraps_and_removes_the_status_line() {
        let exe = Path::new("/opt/bin/swarmy");
        // None → ours; other keys stay.
        let s = with_status_line(obj(json!({"model": "opus"})), exe, false, 0).unwrap();
        assert_eq!(s["statusLine"]["command"], "/opt/bin/swarmy statusline");
        assert_eq!(s["model"], "opus");
        assert_eq!(
            with_status_line(s.clone(), exe, false, 0),
            None,
            "already there"
        );
        // The refresh timer is added to ours when asked for.
        let timed = with_status_line(s.clone(), exe, false, 10).unwrap();
        assert_eq!(timed["statusLine"]["refreshInterval"], 10);

        // Someone else's → wrapped, with quotes kept intact, and restored on removal.
        let theirs = r#"bash -c 'echo it'"'"'s me'"#;
        let s = obj(json!({"statusLine": {"type": "command", "command": theirs, "padding": 1}}));
        let w = with_status_line(s, exe, false, 0).unwrap();
        let cmd = w["statusLine"]["command"].as_str().unwrap();
        assert!(
            cmd.starts_with("/opt/bin/swarmy statusline --then '"),
            "{cmd}"
        );
        assert_eq!(w["statusLine"]["padding"], 1);
        assert_eq!(
            status_line_of(&w),
            StatusLine::Swarmy {
                wraps: Some(theirs.to_string())
            }
        );
        let back = with_status_line(w, exe, true, 0).unwrap();
        assert_eq!(back["statusLine"]["command"], theirs);

        // Ours alone → the key goes away.
        let mine = with_status_line(obj(json!({})), exe, false, 10).unwrap();
        assert!(
            !with_status_line(mine, exe, true, 10)
                .unwrap()
                .contains_key("statusLine")
        );
    }

    #[test]
    fn adds_and_removes_the_guard_hook_beside_other_hooks() {
        let exe = Path::new("/opt/bin/swarmy");
        // Nothing yet → ours, as Claude Code reads it; other keys stay.
        let s = with_guard_hook(obj(json!({"model": "opus"})), exe, false)
            .unwrap()
            .unwrap();
        assert_eq!(s["model"], "opus");
        let group = &s["hooks"]["PreToolUse"][0];
        assert_eq!(group["matcher"], "*");
        assert_eq!(group["hooks"][0]["type"], "command");
        assert_eq!(group["hooks"][0]["command"], "/opt/bin/swarmy guard");
        assert_eq!(group["hooks"][0]["timeout"], GUARD_TIMEOUT_S);
        assert!(has_guard(&s));
        assert_eq!(
            with_guard_hook(s.clone(), exe, false),
            Ok(None),
            "already there"
        );
        // Taken out alone: the containers it made go too.
        let back = with_guard_hook(s, exe, true).unwrap().unwrap();
        assert!(!back.contains_key("hooks"), "{back:?}");
        assert_eq!(
            with_guard_hook(back, exe, true),
            Ok(None),
            "nothing to take out"
        );

        // Beside someone else's hooks: theirs stay, in and out.
        let theirs = obj(json!({"hooks": {
            "PreToolUse": [{"matcher": "Bash", "hooks": [{"type": "command", "command": "check.sh"}]}],
            "Stop": [{"hooks": [{"type": "command", "command": "notify.sh"}]}]
        }}));
        let with = with_guard_hook(theirs.clone(), exe, false)
            .unwrap()
            .unwrap();
        assert_eq!(with["hooks"]["PreToolUse"].as_array().unwrap().len(), 2);
        assert_eq!(with["hooks"]["PreToolUse"][0]["matcher"], "Bash");
        let without = with_guard_hook(with, exe, true).unwrap().unwrap();
        assert_eq!(without, theirs, "exactly what was there before");

        // Ours in a group someone else shares: only our entry goes.
        let shared = obj(json!({"hooks": {"PreToolUse": [{"matcher": "*", "hooks": [
            {"type": "command", "command": "check.sh"},
            {"type": "command", "command": "/usr/local/bin/swarmy guard"}
        ]}]}}));
        let left = with_guard_hook(shared, exe, true).unwrap().unwrap();
        assert_eq!(
            left["hooks"]["PreToolUse"][0]["hooks"],
            json!([{"type": "command", "command": "check.sh"}])
        );
    }

    #[test]
    fn a_hooks_of_another_shape_is_left_alone() {
        let exe = Path::new("/opt/bin/swarmy");
        for odd in [json!({"hooks": "x"}), json!({"hooks": {"PreToolUse": {}}})] {
            assert!(with_guard_hook(obj(odd), exe, false).is_err());
        }
    }

    #[test]
    fn the_guard_command_is_told_from_others() {
        assert!(is_guard_command("/opt/bin/swarmy guard"));
        assert!(is_guard_command("\"/opt/my tools/swarmy\" guard"));
        assert!(!is_guard_command("/opt/bin/swarmy statusline"));
        assert!(!is_guard_command("/usr/bin/guard"));
        assert_eq!(
            guard_command(Path::new("/opt/my tools/swarmy")),
            "\"/opt/my tools/swarmy\" guard"
        );
    }
}