hennery 0.3.0

Self-hosted cockpit for ACP coding agents
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
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
//! `hennery service install|uninstall|status` (distribution spec ยง6): a
//! per-user service for one role, a launchd user agent on macOS and a
//! systemd user unit on Linux. Everything that touches the machine goes
//! through a `Context`: its directories, its environment and, above all,
//! the service manager, which the tests replace with a fake.

pub mod path;
pub mod unit;

use crate::supervisor;
use anyhow::{Context as _, Result, bail};
use clap::{Args, Subcommand};
use std::collections::BTreeMap;
use std::io::Write;
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use std::time::{Duration, Instant};
use unit::Role;

#[derive(Args)]
pub struct ServiceArgs {
    #[command(subcommand)]
    command: ServiceCommand,
}

#[derive(Subcommand)]
enum ServiceCommand {
    /// Write and start the service for a role: a launchd user agent
    /// (macOS) or a systemd user unit (Linux). One role per machine.
    Install {
        #[arg(long, value_enum, default_value_t = Role::Up)]
        role: Role,
        /// The data directory the service runs on; by default
        /// `~/Library/Application Support/hennery` (macOS) or
        /// `$XDG_DATA_HOME/hennery` (Linux). For `--role host`, the one
        /// `hennery host join` paired.
        #[arg(long)]
        data_dir: Option<PathBuf>,
        /// The login shell whose PATH the service gets; by default the
        /// account's shell.
        #[arg(long)]
        shell: Option<PathBuf>,
    },
    /// Stop and remove the service; its data directory and logs are kept.
    Uninstall {
        /// By default, whichever role is installed.
        #[arg(long, value_enum)]
        role: Option<Role>,
    },
    /// Show the installed service: what it runs, whether it runs, and, for
    /// `up`, its children. Exits 1 unless it is installed and running, with
    /// no child given up on or revoked.
    Status {
        /// By default, whichever role is installed.
        #[arg(long, value_enum)]
        role: Option<Role>,
    },
}

pub fn run(args: ServiceArgs) -> Result<ExitCode> {
    let system = System;
    let cx = Context::from_process(&system)?;
    let mut out = std::io::stdout();
    match args.command {
        ServiceCommand::Install { role, data_dir, shell } => {
            install(&cx, role, data_dir.as_deref(), shell.as_deref(), &mut out)?;
            Ok(ExitCode::SUCCESS)
        }
        ServiceCommand::Uninstall { role } => {
            uninstall(&cx, role, &mut out)?;
            Ok(ExitCode::SUCCESS)
        }
        ServiceCommand::Status { role } => status(&cx, role, &mut out),
    }
}

/// The outcome of one service-manager command.
#[derive(Debug, Clone, Default)]
pub struct Ran {
    pub ok: bool,
    pub stdout: String,
    pub stderr: String,
}

/// Runs `launchctl`, `systemctl` and `loginctl`.
pub trait Manager {
    fn run(&self, program: &str, args: &[&str]) -> Result<Ran>;
}

/// The machine's own service manager.
pub(crate) struct System;

impl Manager for System {
    fn run(&self, program: &str, args: &[&str]) -> Result<Ran> {
        let out = std::process::Command::new(program)
            .args(args)
            .stdin(std::process::Stdio::null())
            .output()
            .with_context(|| format!("run {program}"))?;
        Ok(Ran {
            ok: out.status.success(),
            stdout: String::from_utf8_lossy(&out.stdout).into_owned(),
            stderr: String::from_utf8_lossy(&out.stderr).into_owned(),
        })
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Platform {
    MacOs,
    Linux,
}

/// The machine as the service commands see it.
pub struct Context<'a> {
    pub platform: Platform,
    pub home: PathBuf,
    /// This process's environment.
    pub env: BTreeMap<String, String>,
    pub uid: u32,
    pub user: String,
    /// The login shell (the account's, else `$SHELL`, else `/bin/sh`).
    pub shell: PathBuf,
    /// This binary, as the service will run it.
    pub exe: PathBuf,
    /// Where `/run` and `/proc` are (`/`, but for the tests).
    pub root: PathBuf,
    pub manager: &'a dyn Manager,
}

impl<'a> Context<'a> {
    pub(crate) fn from_process(manager: &'a dyn Manager) -> Result<Self> {
        let platform = if cfg!(target_os = "macos") {
            Platform::MacOs
        } else if cfg!(target_os = "linux") {
            Platform::Linux
        } else {
            bail!("`hennery service` supports macOS (launchd) and Linux (systemd) only");
        };
        let env: BTreeMap<String, String> = std::env::vars().collect();
        // SAFETY: getuid(2) cannot fail.
        let uid = unsafe { libc::getuid() };
        let account = account(uid);
        let home = env
            .get("HOME")
            .map(PathBuf::from)
            .filter(|h| h.is_absolute())
            .or_else(|| account.as_ref().map(|a| a.home.clone()))
            .context("no home directory: set HOME")?;
        let user = env
            .get("USER")
            .cloned()
            .or_else(|| account.as_ref().map(|a| a.name.clone()))
            .unwrap_or_else(|| uid.to_string());
        let shell = account
            .as_ref()
            .map(|a| a.shell.clone())
            .filter(|s| s.is_absolute())
            .or_else(|| env.get("SHELL").map(PathBuf::from).filter(|s| s.is_absolute()))
            .unwrap_or_else(|| PathBuf::from("/bin/sh"));
        Ok(Self {
            platform,
            home,
            uid,
            user,
            shell,
            exe: invoked_exe(&env)?,
            root: PathBuf::from("/"),
            manager,
            env,
        })
    }

    /// `$XDG_<name>_HOME` when set to an absolute path, else `home/fallback`.
    fn xdg(&self, name: &str, fallback: &str) -> PathBuf {
        self.env
            .get(&format!("XDG_{name}_HOME"))
            .map(PathBuf::from)
            .filter(|p| p.is_absolute())
            .unwrap_or_else(|| self.home.join(fallback))
    }

    /// Distribution spec ยง8: the data directory by default.
    pub fn default_data_dir(&self) -> PathBuf {
        match self.platform {
            Platform::MacOs => self.home.join("Library/Application Support/hennery"),
            Platform::Linux => self.xdg("DATA", ".local/share").join("hennery"),
        }
    }

    /// Where `role`'s service file is.
    pub fn service_file(&self, role: Role) -> PathBuf {
        match self.platform {
            Platform::MacOs => self
                .home
                .join("Library/LaunchAgents")
                .join(format!("{}.plist", role.label())),
            Platform::Linux => self.xdg("CONFIG", ".config").join("systemd/user").join(role.unit()),
        }
    }

    /// The systemd unit's environment file (distribution spec ยง8).
    pub(crate) fn env_file(&self) -> PathBuf {
        self.xdg("CONFIG", ".config").join("hennery/service.env")
    }

    /// Where launchd writes `role`'s output (distribution spec ยง8).
    fn log_file(&self, role: Role) -> PathBuf {
        self.home
            .join("Library/Logs/hennery")
            .join(format!("{}.log", role.name()))
    }

    /// The roles whose service file is there.
    pub(crate) fn installed(&self) -> Vec<Role> {
        Role::ALL
            .into_iter()
            .filter(|&role| self.service_file(role).exists())
            .collect()
    }

    fn run(&self, program: &str, args: &[&str]) -> Result<Ran> {
        self.manager.run(program, args)
    }

    fn launchd_domain(&self) -> String {
        format!("gui/{}", self.uid)
    }

    fn launchd_target(&self, role: Role) -> String {
        format!("gui/{}/{}", self.uid, role.label())
    }
}

/// The account's entry in the user database.
struct Account {
    name: String,
    home: PathBuf,
    shell: PathBuf,
}

fn account(uid: u32) -> Option<Account> {
    use std::ffi::CStr;
    use std::os::unix::ffi::OsStrExt;
    let mut buf = vec![0 as libc::c_char; 16 * 1024];
    // SAFETY: all-zero bytes are a valid `passwd`; getpwuid_r(3) fills it
    // with pointers into `buf`, which outlives every use below.
    let mut pwd: libc::passwd = unsafe { std::mem::zeroed() };
    let mut found: *mut libc::passwd = std::ptr::null_mut();
    let rc = unsafe { libc::getpwuid_r(uid, &mut pwd, buf.as_mut_ptr(), buf.len(), &mut found) };
    if rc != 0 || found.is_null() {
        return None;
    }
    // SAFETY: on success each field is a NUL-terminated string in `buf`.
    let text = |p: *const libc::c_char| unsafe { CStr::from_ptr(p) }.to_bytes().to_vec();
    Some(Account {
        name: String::from_utf8_lossy(&text(pwd.pw_name)).into_owned(),
        home: PathBuf::from(std::ffi::OsStr::from_bytes(&text(pwd.pw_dir))),
        shell: PathBuf::from(std::ffi::OsStr::from_bytes(&text(pwd.pw_shell))),
    })
}

/// This binary as it was started: the path on PATH (or given) that leads
/// to it, not where that resolves to. A package manager's link
/// (`/opt/homebrew/bin/hennery`, `~/.nix-profile/bin/hennery`) survives an
/// upgrade; the versioned file it points at does not.
fn invoked_exe(env: &BTreeMap<String, String>) -> Result<PathBuf> {
    let real = std::env::current_exe()?;
    let canonical = real.canonicalize().unwrap_or_else(|_| real.clone());
    let same = |candidate: &Path| candidate.canonicalize().is_ok_and(|c| c == canonical);
    if let Some(arg0) = std::env::args_os().next().map(PathBuf::from) {
        if arg0.components().count() > 1 {
            if let Ok(abs) = std::path::absolute(&arg0)
                && same(&abs)
            {
                return Ok(abs);
            }
        } else if let Some(path) = env.get("PATH") {
            for dir in std::env::split_paths(path).filter(|d| d.is_absolute()) {
                let candidate = dir.join(&arg0);
                if same(&candidate) {
                    return Ok(candidate);
                }
            }
        }
    }
    Ok(real)
}

/// Write `text` to `path` whole or not at all, with `mode`.
fn write_file(path: &Path, text: &str, mode: u32) -> Result<()> {
    let tmp = path.with_extension("hennery-tmp");
    let mut file = std::fs::OpenOptions::new()
        .write(true)
        .create(true)
        .truncate(true)
        .mode(mode)
        .open(&tmp)
        .with_context(|| format!("write {}", tmp.display()))?;
    file.write_all(text.as_bytes())?;
    file.sync_all()?;
    drop(file);
    std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(mode))?;
    std::fs::rename(&tmp, path).with_context(|| format!("write {}", path.display()))
}

fn create_dir(dir: &Path, mode: u32) -> Result<()> {
    use std::os::unix::fs::DirBuilderExt;
    std::fs::DirBuilder::new()
        .recursive(true)
        .mode(mode)
        .create(dir)
        .with_context(|| format!("create {}", dir.display()))
}

/// Whether `dir` holds a host's pairing, looked at without `Paired::load`,
/// which would roll an interrupted pairing forward (renames, the outbox
/// moved aside) without the host's lock (decision 8).
fn host_pairing(dir: &Path) -> Result<()> {
    match crate::pairing_in(dir) {
        crate::Pairing::Whole => Ok(()),
        crate::Pairing::Interrupted => bail!(
            "{} holds a pairing that was interrupted: run `hennery host run --data-dir {}` once to finish it, then install",
            dir.display(),
            dir.display()
        ),
        crate::Pairing::None => bail!(
            "{} holds no pairing: run `hennery host join <url> --data-dir {}` first",
            dir.display(),
            dir.display()
        ),
    }
}

/// Why there is no systemd user manager to install into, if there is none.
fn no_systemd(cx: &Context) -> Option<String> {
    if cx.root.join("run/systemd/system").is_dir() {
        return None;
    }
    let wsl = cx.env.contains_key("WSL_DISTRO_NAME")
        || std::fs::read_to_string(cx.root.join("proc/sys/kernel/osrelease"))
            .is_ok_and(|release| release.to_ascii_lowercase().contains("microsoft"));
    Some(if wsl {
        "this WSL distribution does not run systemd: add `[boot]` and `systemd=true` to /etc/wsl.conf, run \
         `wsl --shutdown` from Windows, start the distribution again, and retry"
            .to_string()
    } else {
        "systemd is not running here (no /run/systemd/system), and `hennery service` installs systemd user units; \
         run `hennery up` or `hennery host run` under your own supervisor instead"
            .to_string()
    })
}

/// `hennery service install` (distribution spec ยง6).
pub fn install(
    cx: &Context,
    role: Role,
    data_dir: Option<&Path>,
    shell: Option<&Path>,
    out: &mut dyn Write,
) -> Result<()> {
    if let Some(other) = cx.installed().into_iter().find(|&r| r != role) {
        bail!(
            "the {other} service is installed ({}); one role per machine: run `hennery service uninstall --role {other}` first",
            cx.service_file(other).display()
        );
    }
    let data_dir = match data_dir {
        Some(dir) => std::path::absolute(dir)?,
        None => cx.default_data_dir(),
    };
    if role == Role::Host {
        host_pairing(&data_dir)?;
    }
    if cx.platform == Platform::Linux
        && let Some(why) = no_systemd(cx)
    {
        bail!(why);
    }
    let argv = unit::command_line(role, &cx.exe, &data_dir)?;
    let shell = shell.unwrap_or(&cx.shell);
    // Recorded beside the PATH, so doctor runs the same shell again.
    let shell_text = unit::plain(shell)
        .with_context(|| format!("the login shell {} (pick another with --shell)", shell.display()))?;
    let macos = cx.platform == Platform::MacOs;
    let env = path::shell_environment(&cx.env, shell, macos);
    let captured = path::login_environment(shell, &env, path::CAPTURE_TIMEOUT).with_context(|| {
        format!(
            "capture the PATH of the login shell {} (pick another with --shell)",
            shell.display()
        )
    })?;
    let service_path = path::service_path(&captured, &cx.home, macos)?;
    let file = cx.service_file(role);
    let restarted = match cx.platform {
        Platform::MacOs => install_launchd(cx, role, &argv, &service_path.path, &shell_text, &file)?,
        Platform::Linux => install_systemd(cx, role, &argv, &service_path.path, &shell_text, &file)?,
    };
    writeln!(out, "installed the {role} service: {}", file.display())?;
    writeln!(out, "  runs: {}", argv.join(" "))?;
    match cx.platform {
        Platform::MacOs => writeln!(out, "  PATH (in the plist): {}", service_path.path)?,
        Platform::Linux => writeln!(out, "  PATH (in {}): {}", cx.env_file().display(), service_path.path)?,
    }
    writeln!(out, "  from the login shell: {shell_text}")?;
    for note in &service_path.notes {
        writeln!(out, "  note: {note}")?;
    }
    if restarted {
        writeln!(
            out,
            "  it was running and has been restarted: its sessions are parked, and resumable"
        )?;
    }
    if macos {
        writeln!(out, "  output: {}", cx.log_file(role).display())?;
        writeln!(
            out,
            "  it runs while you are logged in to the Mac's screen (the login keychain holds the agents' credentials)"
        )?;
    } else {
        linger(cx, out)?;
    }
    // A service has no terminal: the setup link is only in a file.
    if role != Role::Host {
        writeln!(
            out,
            "  not set up yet? `hennery admin --data-dir {} setup-url` prints the setup link",
            data_dir.display()
        )?;
    }
    Ok(())
}

/// How long `bootout` may take: the plist's `ExitTimeOut`, and a little.
const BOOTOUT_WAIT: Duration = Duration::from_secs(35);

fn loaded(cx: &Context, role: Role) -> Result<bool> {
    Ok(cx.run("launchctl", &["print", &cx.launchd_target(role)])?.ok)
}

/// Unload `role`'s agent if it is loaded, and wait until launchd has let it
/// go: `bootstrap` fails while the old job is still stopping. `true` if it
/// was loaded.
fn bootout(cx: &Context, role: Role) -> Result<bool> {
    if !loaded(cx, role)? {
        return Ok(false);
    }
    let target = cx.launchd_target(role);
    let ran = cx.run("launchctl", &["bootout", &target])?;
    let deadline = Instant::now() + BOOTOUT_WAIT;
    while loaded(cx, role)? {
        if Instant::now() >= deadline {
            bail!("launchctl bootout {target} did not finish: {}", ran.stderr.trim());
        }
        std::thread::sleep(Duration::from_millis(200));
    }
    Ok(true)
}

fn install_launchd(cx: &Context, role: Role, argv: &[String], path: &str, shell: &str, file: &Path) -> Result<bool> {
    // Private: the log is the service's whole output.
    let log = cx.log_file(role);
    create_dir(log.parent().expect("a log directory"), 0o700)?;
    std::fs::OpenOptions::new()
        .append(true)
        .create(true)
        .mode(0o600)
        .open(&log)
        .with_context(|| format!("create {}", log.display()))?;
    create_dir(file.parent().expect("LaunchAgents"), 0o755)?;
    let restarted = bootout(cx, role)?;
    write_file(file, &unit::plist(role, argv, path, shell, &unit::plain(&log)?), 0o644)?;
    let plist = unit::plain(file)?;
    let ran = cx.run("launchctl", &["bootstrap", &cx.launchd_domain(), &plist])?;
    if !ran.ok {
        bail!(
            "launchctl bootstrap {} {plist} failed: {}. A launchd user agent loads only in a GUI login session \
             (log in on the Mac's screen, not only over SSH); then run `hennery service install` again. \
             The agent that ran before, if any, has been stopped",
            cx.launchd_domain(),
            ran.stderr.trim()
        );
    }
    Ok(restarted)
}

/// `systemctl --user โ€ฆ`, failing with its error output.
fn systemctl(cx: &Context, args: &[&str]) -> Result<Ran> {
    let mut all = vec!["--user"];
    all.extend_from_slice(args);
    let ran = cx.run("systemctl", &all)?;
    if !ran.ok {
        bail!("systemctl {} failed: {}", all.join(" "), ran.stderr.trim());
    }
    Ok(ran)
}

fn install_systemd(cx: &Context, role: Role, argv: &[String], path: &str, shell: &str, file: &Path) -> Result<bool> {
    let env_file = cx.env_file();
    create_dir(env_file.parent().expect("a config directory"), 0o700)?;
    write_file(&env_file, &unit::env_file(path, shell), 0o600)?;
    create_dir(file.parent().expect("systemd/user"), 0o755)?;
    let restarted = cx
        .run("systemctl", &["--user", "is-active", "--quiet", role.unit()])?
        .ok;
    write_file(file, &unit::systemd_unit(role, argv, &unit::plain(&env_file)?)?, 0o644)?;
    systemctl(cx, &["daemon-reload"])?;
    systemctl(cx, &["enable", role.unit()])?;
    // A unit that hit its start limit refuses a plain restart.
    let _ = cx.run("systemctl", &["--user", "reset-failed", role.unit()]);
    systemctl(cx, &["restart", role.unit()])?;
    Ok(restarted)
}

/// Whether `loginctl` says linger is on for this user.
pub(crate) fn linger_on(cx: &Context) -> bool {
    let uid = cx.uid.to_string();
    cx.run("loginctl", &["show-user", &uid, "-p", "Linger"])
        .is_ok_and(|ran| ran.ok && ran.stdout.trim() == "Linger=yes")
}

/// Distribution spec ยง6.3: without linger the service stops at logout and
/// does not start at boot. Said, never changed: enabling it may need
/// privileges.
fn linger(cx: &Context, out: &mut dyn Write) -> Result<()> {
    if !linger_on(cx) {
        writeln!(
            out,
            "  linger is off: the service stops when you log out and does not start at boot. To keep it running, run:\n    loginctl enable-linger {}",
            cx.user
        )?;
    }
    Ok(())
}

/// `hennery service uninstall`.
pub fn uninstall(cx: &Context, role: Option<Role>, out: &mut dyn Write) -> Result<()> {
    let roles = match role {
        Some(role) if !cx.service_file(role).exists() => {
            writeln!(out, "the {role} service is not installed")?;
            return Ok(());
        }
        Some(role) => vec![role],
        None => cx.installed(),
    };
    if roles.is_empty() {
        writeln!(out, "no hennery service is installed")?;
        return Ok(());
    }
    for role in roles {
        let file = cx.service_file(role);
        let data = read_command_line(cx, role).and_then(|argv| data_dir_of(&argv));
        match cx.platform {
            Platform::MacOs => {
                bootout(cx, role)?;
                std::fs::remove_file(&file).with_context(|| format!("remove {}", file.display()))?;
            }
            Platform::Linux => {
                if let Err(err) = systemctl(cx, &["disable", "--now", role.unit()]) {
                    writeln!(out, "  warning: {err:#}")?;
                }
                std::fs::remove_file(&file).with_context(|| format!("remove {}", file.display()))?;
                // Every role's unit names it: kept while one is left.
                if cx.installed().is_empty() {
                    let _ = std::fs::remove_file(cx.env_file());
                }
                if let Err(err) = systemctl(cx, &["daemon-reload"]) {
                    writeln!(out, "  warning: {err:#}")?;
                }
            }
        }
        writeln!(out, "removed the {role} service: {}", file.display())?;
        if let Some(data) = data {
            writeln!(out, "  its data directory is kept: {}", data.display())?;
        }
        if cx.platform == Platform::MacOs {
            writeln!(out, "  its log is kept: {}", cx.log_file(role).display())?;
        }
    }
    Ok(())
}

pub(crate) fn read_command_line(cx: &Context, role: Role) -> Option<Vec<String>> {
    let text = std::fs::read_to_string(cx.service_file(role)).ok()?;
    match cx.platform {
        Platform::MacOs => unit::plist_command_line(&text),
        Platform::Linux => unit::systemd_command_line(&text),
    }
}

pub(crate) fn data_dir_of(argv: &[String]) -> Option<PathBuf> {
    let at = argv.iter().position(|a| a == "--data-dir")?;
    argv.get(at + 1).map(PathBuf::from)
}

/// `hennery service status`: exit 0 when the service is installed and
/// running, its binary exists, and no child of `up` was given up on or
/// revoked; 1 otherwise. A binary other than this one is only named.
pub fn status(cx: &Context, role: Option<Role>, out: &mut dyn Write) -> Result<ExitCode> {
    let roles = match role {
        Some(role) => vec![role],
        None => cx.installed(),
    };
    if roles.is_empty() {
        writeln!(out, "no hennery service is installed")?;
        return Ok(ExitCode::FAILURE);
    }
    if roles.len() > 1 {
        writeln!(
            out,
            "warning: more than one role is installed; keep one (`hennery service uninstall --role โ€ฆ`)"
        )?;
    }
    let mut healthy = roles.len() == 1;
    for role in roles {
        healthy &= status_of(cx, role, out)?;
    }
    Ok(if healthy { ExitCode::SUCCESS } else { ExitCode::FAILURE })
}

fn status_of(cx: &Context, role: Role, out: &mut dyn Write) -> Result<bool> {
    let file = cx.service_file(role);
    if !file.exists() {
        writeln!(out, "the {role} service is not installed ({})", file.display())?;
        return Ok(false);
    }
    writeln!(out, "the {role} service: {}", file.display())?;
    let mut healthy = true;
    let argv = read_command_line(cx, role).unwrap_or_default();
    match argv.first().map(PathBuf::from) {
        None => {
            writeln!(
                out,
                "  runs: unreadable; run `hennery service install --role {role}` again"
            )?;
            healthy = false;
        }
        Some(exe) => {
            writeln!(out, "  runs: {}", argv.join(" "))?;
            let canonical = |p: &Path| p.canonicalize().ok();
            if !exe.exists() {
                writeln!(
                    out,
                    "  its binary is missing; run `hennery service install --role {role}` again"
                )?;
                healthy = false;
            } else if canonical(&exe) != canonical(&cx.exe) {
                writeln!(
                    out,
                    "  its binary is not this one ({}); run `hennery service install --role {role}` with the one to use",
                    cx.exe.display()
                )?;
            }
        }
    }
    // A revoked host stays down (spec ยง5.2): under launchd its exit code no
    // longer says why, so its record does; said first, as the manager may
    // not even be reachable.
    if role == Role::Host
        && let Some(data) = data_dir_of(&argv)
    {
        match crate::revoked::current(&data) {
            Ok(Some(revoked)) => {
                let (why, fix) = revoked.said(&start_command(cx, role));
                writeln!(out, "  {why}; {fix}")?;
                healthy = false;
            }
            Ok(None) => {}
            Err(err) => {
                writeln!(out, "  whether it was revoked is unknown: {err:#}")?;
                healthy = false;
            }
        }
    }
    // Whether it runs, and as which process, as the service manager says.
    let Some(managed) = managed(cx, role)? else {
        writeln!(out, "  systemd: unavailable (`systemctl --user` cannot be run)")?;
        return Ok(false);
    };
    writeln!(out, "  {}", managed.said)?;
    if cx.platform == Platform::Linux {
        linger(cx, out)?;
    }
    healthy &= managed.running;
    if role == Role::Up
        && let Some(data) = data_dir_of(&argv)
    {
        healthy &= children(&data, managed.pid, out)?;
    }
    Ok(healthy)
}

/// How `role`'s service is started (again) by hand.
pub(crate) fn start_command(cx: &Context, role: Role) -> String {
    match cx.platform {
        Platform::MacOs => format!("launchctl kickstart -k gui/{}/{}", cx.uid, role.label()),
        Platform::Linux => format!("systemctl --user restart {}", role.unit()),
    }
}

/// What the service manager says of a service: parsed fields only, never
/// its raw output (`launchctl print` lists the job's environment).
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Managed {
    /// As `status` prints it, e.g. `launchd: running, pid 42`.
    pub said: String,
    pub running: bool,
    /// Its process, when the manager names one.
    pub pid: Option<u32>,
}

/// Ask the service manager about `role`'s service: `None` when `systemctl
/// --user` cannot be run at all.
pub(crate) fn managed(cx: &Context, role: Role) -> Result<Option<Managed>> {
    match cx.platform {
        Platform::MacOs => {
            let ran = cx.run("launchctl", &["print", &cx.launchd_target(role)])?;
            if !ran.ok {
                return Ok(Some(Managed {
                    said: "launchd: not loaded (it loads at your next GUI login)".to_string(),
                    running: false,
                    pid: None,
                }));
            }
            let field = |name: &str| {
                ran.stdout
                    .lines()
                    .find_map(|l| l.trim().strip_prefix(name)?.trim().strip_prefix('=').map(str::trim))
            };
            let state = field("state").unwrap_or("unknown");
            let pid = field("pid").and_then(|pid| pid.parse::<u32>().ok());
            let said = match pid {
                Some(pid) => format!("launchd: {state}, pid {pid}"),
                None => format!("launchd: {state}"),
            };
            Ok(Some(Managed {
                said,
                running: state == "running",
                pid,
            }))
        }
        Platform::Linux => {
            let (Ok(active), Ok(enabled)) = (
                cx.run("systemctl", &["--user", "is-active", role.unit()]),
                cx.run("systemctl", &["--user", "is-enabled", role.unit()]),
            ) else {
                return Ok(None);
            };
            let pid = cx
                .run(
                    "systemctl",
                    &["--user", "show", "-p", "MainPID", "--value", role.unit()],
                )?
                .stdout
                .trim()
                .parse::<u32>()
                .ok()
                .filter(|&pid| pid != 0);
            Ok(Some(Managed {
                said: format!("systemd: {}, {}", active.stdout.trim(), enabled.stdout.trim()),
                running: active.stdout.trim() == "active",
                pid,
            }))
        }
    }
}

/// Whether process `pid` exists.
pub(crate) fn alive(pid: u32) -> bool {
    let Ok(pid) = libc::pid_t::try_from(pid) else {
        return false;
    };
    // SAFETY: kill(2) with signal 0 sends nothing; it only checks.
    unsafe { libc::kill(pid, 0) == 0 || std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM) }
}

/// `up`'s report of its children (`supervisor.json`), as `status` and
/// `doctor` both judge it.
#[derive(Debug)]
pub(crate) enum Report {
    /// `up` has written none yet.
    None,
    /// It cannot be read: why.
    Unreadable(String),
    /// From a process that is gone, or that is not the one the service
    /// manager runs: that process's pid.
    Stale(u32),
    Current(supervisor::State),
}

/// `up`'s report in `data`. A report from a process that is gone, or that
/// is not the one the service manager runs (`pid`, when it says), is stale
/// and judged by nothing: an `up` killed outright leaves one behind, and so
/// does an `up` run by hand on the same data directory.
pub(crate) fn report(data: &Path, pid: Option<u32>) -> Report {
    match supervisor::read_state(data) {
        Ok(None) => Report::None,
        Err(err) => Report::Unreadable(format!("{err:#}")),
        Ok(Some(state)) if !alive(state.pid) || pid.is_some_and(|pid| pid != state.pid) => Report::Stale(state.pid),
        Ok(Some(state)) => Report::Current(state),
    }
}

/// One child's state in words, and whether it is healthy: one given up on,
/// or revoked, is not.
pub(crate) fn child_state(child: &supervisor::ChildReport) -> (String, bool) {
    match child.state {
        supervisor::ChildState::Running => ("running".to_string(), true),
        supervisor::ChildState::Restarting => ("crashed; starting again".to_string(), true),
        supervisor::ChildState::Stopped => ("stopped".to_string(), true),
        supervisor::ChildState::Revoked => (
            "revoked by the collector; pair it again (see `hennery up`'s log)".to_string(),
            false,
        ),
        supervisor::ChildState::GaveUp => (
            format!(
                "given up on after {} crashes; restart the service once the cause is fixed",
                child.crashes_in_window
            ),
            false,
        ),
    }
}

/// `up`'s report of its children, printed: `false` when one was given up
/// on or revoked, or the report cannot be read.
fn children(data: &Path, pid: Option<u32>, out: &mut dyn Write) -> Result<bool> {
    let state = match report(data, pid) {
        Report::None => {
            writeln!(out, "  children: no report yet in {}", data.display())?;
            return Ok(true);
        }
        Report::Unreadable(err) => {
            writeln!(out, "  children: the report cannot be read ({err})")?;
            return Ok(false);
        }
        Report::Stale(pid) => {
            writeln!(
                out,
                "  children: the last report is stale (from pid {pid}, which is not the service's process)"
            )?;
            return Ok(true);
        }
        Report::Current(state) => state,
    };
    let mut healthy = true;
    for (name, child) in [("collector", &state.collector), ("host", &state.host)] {
        let last = child
            .last_exit
            .as_deref()
            .map(|e| format!(", last exit: {e}"))
            .unwrap_or_default();
        let (what, ok) = child_state(child);
        healthy &= ok;
        writeln!(out, "  {name}: {what} ({} restarts{last})", child.restarts)?;
    }
    writeln!(out, "  (reported by pid {})", state.pid)?;
    Ok(healthy)
}

#[cfg(test)]
mod tests;