shep 0.24.0

The shep binary: a process manager that keeps a flock of long-running processes alive on macOS, Linux and Windows, with logs, watch and cron restarts, and webhook alerts
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
//! Rendering the five init-system units shep can start at boot: systemd,
//! launchd, openrc, and the FreeBSD and OpenBSD `rc.d` scripts.
//!
//! Every renderer is pure `format!` over a [`UnitSpec`]: no filesystem
//! access, no environment reads, nothing that could fail. Resolving a real
//! `UnitSpec` and writing the result to disk is the parent module's job.
//!
//! Every unit's argv is `<exec> daemon --foreground`, never `shep muster`:
//! an init system supervises the process it starts, and `muster` is a client
//! that exits immediately. The daemon restores the roll at boot on its own.

use std::ffi::OsString;
use std::path::PathBuf;

use super::shell_quote;
use crate::commands::startup_shared::xml_text;
use crate::exit::ExitCode;

/// Everything a generated init unit carries.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct UnitSpec {
    /// The user the daemon runs as.
    pub user: String,
    /// This binary's own resolved path.
    pub exec: PathBuf,
    /// `$SHEP_HOME` the daemon is given.
    pub home: PathBuf,
    /// `PATH` captured from the invoking environment, so an interpreter under
    /// `~/.bun` or `~/.cargo` is still findable after a reboot.
    pub path: OsString,
    /// The daemon's working directory.
    pub working_dir: PathBuf,
}

/// Renders the systemd unit, `Type=notify`.
///
/// No `TimeoutStartSec`: systemd's default applies, and the shepherd sends
/// `EXTEND_TIMEOUT_USEC` around each muster-restore stage, so the deadline
/// follows the walk. `RestartPreventExitStatus` is [`ExitCode::DaemonAlreadyRunning`]:
/// a hand-started shepherd holds the home lock. `Delegate=memory cpu pids` chowns
/// the service cgroup to `User=` with only those controllers; `yes` grants all.
pub(crate) fn systemd_unit(spec: &UnitSpec) -> String {
    let home = systemd_environment_value(&spec.home.display().to_string());
    let path = systemd_environment_value(&spec.path.to_string_lossy());
    format!(
        "[Unit]\n\
         Description=shep process manager for {user}\n\
         After=network.target\n\
         \n\
         [Service]\n\
         Type=notify\n\
         NotifyAccess=main\n\
         User={user}\n\
         WorkingDirectory={working_dir}\n\
         Environment=\"SHEP_HOME={home}\"\n\
         Environment=\"PATH={path}\"\n\
         ExecStart={exec} daemon --foreground\n\
         ExecReload={exec} reload all\n\
         ExecStop={exec} kill\n\
         Restart=on-failure\n\
         RestartSec=5\n\
         RestartPreventExitStatus={already_running}\n\
         Delegate=memory cpu pids\n\
         \n\
         [Install]\n\
         WantedBy=multi-user.target\n",
        user = spec.user,
        working_dir = spec.working_dir.display(),
        exec = spec.exec.display(),
        already_running = ExitCode::DaemonAlreadyRunning as u8,
    )
}

/// Renders the launchd plist. `KeepAlive`/`SuccessfulExit=false` is
/// launchd's `Restart=on-failure`; launchd has no `ExecReload` equivalent,
/// so a reload goes through `shep reload all` same as any other client.
pub(crate) fn launchd_plist(spec: &UnitSpec) -> String {
    let label = xml_text(&launchd_label(&spec.user));
    let exec = xml_text(&spec.exec.display().to_string());
    let user = xml_text(&spec.user);
    let working_dir = xml_text(&spec.working_dir.display().to_string());
    let home = xml_text(&spec.home.display().to_string());
    let path = xml_text(&spec.path.to_string_lossy());
    format!(
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\
         <!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n\
         <plist version=\"1.0\">\n\
         <dict>\n\
         \t<key>Label</key><string>{label}</string>\n\
         \t<key>ProgramArguments</key>\n\
         \t<array>\n\
         \t\t<string>{exec}</string>\n\
         \t\t<string>daemon</string>\n\
         \t\t<string>--foreground</string>\n\
         \t</array>\n\
         \t<key>UserName</key><string>{user}</string>\n\
         \t<key>WorkingDirectory</key><string>{working_dir}</string>\n\
         \t<key>EnvironmentVariables</key>\n\
         \t<dict>\n\
         \t\t<key>SHEP_HOME</key><string>{home}</string>\n\
         \t\t<key>PATH</key><string>{path}</string>\n\
         \t</dict>\n\
         \t<key>RunAtLoad</key><true/>\n\
         \t<key>KeepAlive</key>\n\
         \t<dict><key>SuccessfulExit</key><false/></dict>\n\
         \t<key>StandardOutPath</key><string>{home}/logs/shepd.out.log</string>\n\
         \t<key>StandardErrorPath</key><string>{home}/logs/shepd.err.log</string>\n\
         </dict>\n\
         </plist>\n"
    )
}

/// `/etc/systemd/system/shep-<user>.service`.
pub(crate) fn systemd_unit_path(user: &str) -> PathBuf {
    PathBuf::from(format!("/etc/systemd/system/shep-{user}.service"))
}

/// `io.github.turtiesocks.shep.<user>`: the launchd label, the plist's own
/// filename stem, and what `launchctl bootout system/<label>` names.
pub(crate) fn launchd_label(user: &str) -> String {
    format!("io.github.turtiesocks.shep.{user}")
}

/// `/Library/LaunchDaemons/<label>.plist`.
pub(crate) fn launchd_plist_path(user: &str) -> PathBuf {
    PathBuf::from(format!(
        "/Library/LaunchDaemons/{}.plist",
        launchd_label(user)
    ))
}

/// Escapes one systemd `Environment=` value: doubles every `%`, which systemd
/// otherwise expands silently as a specifier (`%h`, `%t`, ...).
///
/// The caller wraps the whole `KEY=value` in `"..."`, so a value containing a
/// space needs nothing further here.
fn systemd_environment_value(value: &str) -> String {
    value.replace('%', "%%")
}

/// Renders the openrc init script.
///
/// `supervise-daemon` (openrc >= 0.21) supervises the foreground process
/// like systemd, instead of tracking a pidfile. openrc has no `sd_notify`
/// analogue, so `start_post` polls `shep flock`, which never spawns a
/// shepherd of its own. Every interpolated value goes through
/// [`sh_double_quoted`]: these land in a script that runs as root at boot.
pub(crate) fn openrc_script(spec: &UnitSpec) -> String {
    let user = sh_double_quoted(&spec.user);
    let exec = sh_double_quoted(&spec.exec.display().to_string());
    let home = sh_double_quoted(&spec.home.display().to_string());
    let path = sh_double_quoted(&spec.path.to_string_lossy());
    let working_dir = sh_double_quoted(&spec.working_dir.display().to_string());
    format!(
        "#!/sbin/openrc-run\n\
         # shep process manager for {user}\n\
         #\n\
         # openrc has no sd_notify analogue, so the readiness gap systemd's\n\
         # Type=notify closes is closed here by start_post asking the shepherd\n\
         # itself. The first answered request proves the muster restore finished:\n\
         # shep binds its control socket before the restore but does not accept on\n\
         # it until after.\n\
         \n\
         name=\"shep-{user}\"\n\
         description=\"shep process manager for {user}\"\n\
         supervisor=\"supervise-daemon\"\n\
         command=\"{exec}\"\n\
         command_args=\"daemon --foreground\"\n\
         command_user=\"{user}\"\n\
         directory=\"{working_dir}\"\n\
         pidfile=\"/run/shep-{user}.pid\"\n\
         respawn_delay=5\n\
         output_log=\"{home}/logs/shepd.out.log\"\n\
         error_log=\"{home}/logs/shepd.err.log\"\n\
         \n\
         export SHEP_HOME=\"{home}\"\n\
         export PATH=\"{path}\"\n\
         \n\
         depend() {{\n\
         \tneed net\n\
         }}\n\
         \n\
         # start_post runs as root, and the control socket lives in a 0700 $SHEP_HOME\n\
         # owned by {user}. Root bypasses that, so the poll works; it looks like a\n\
         # permission bug only until you have thought it through.\n\
         start_post() {{\n\
         \tlocal waited=0\n\
         \twhile [ \"${{waited}}\" -lt 60 ]; do\n\
         \t\tif \"{exec}\" --home \"{home}\" flock >/dev/null 2>&1; then\n\
         \t\t\treturn 0\n\
         \t\tfi\n\
         \t\tsleep 1\n\
         \t\twaited=$((waited + 1))\n\
         \tdone\n\
         \teerror \"shep did not answer on its control socket within 60s\"\n\
         \treturn 1\n\
         }}\n"
    )
}

/// Renders the FreeBSD `rc.d` script, `/usr/local/etc/rc.d/shep_<user>`.
///
/// `start_postcmd` polls the shepherd's control socket, since `daemon(8)`
/// reports the service started as soon as it forks. `spec.user` must pass
/// [`super::privilege_check::is_rc_safe_user`]: it is interpolated raw into
/// shell identifiers. A value a second shell re-reads, in `${name}_env` and
/// `command_args`, is `sh_double_quoted(shell_quote(value))` instead.
pub(crate) fn freebsd_rc_script(spec: &UnitSpec) -> String {
    let user = &spec.user;
    let exec = sh_double_quoted(&spec.exec.display().to_string());
    let exec_arg = sh_double_quoted(&shell_quote(&spec.exec.display().to_string()));
    let home = sh_double_quoted(&spec.home.display().to_string());
    let working_dir = sh_double_quoted(&spec.working_dir.display().to_string());
    let home_env = sh_double_quoted(&shell_quote(&spec.home.display().to_string()));
    let path_env = sh_double_quoted(&shell_quote(&spec.path.to_string_lossy()));
    format!(
        "#!/bin/sh\n\
         #\n\
         # PROVIDE: shep_{user}\n\
         # REQUIRE: LOGIN NETWORKING\n\
         # KEYWORD: shutdown\n\
         #\n\
         # Enable with: sysrc shep_{user}_enable=YES\n\
         \n\
         . /etc/rc.subr\n\
         \n\
         name=\"shep_{user}\"\n\
         rcvar=\"shep_{user}_enable\"\n\
         : ${{shep_{user}_enable:=\"NO\"}}\n\
         \n\
         shep_{user}_user=\"{user}\"\n\
         shep_{user}_chdir=\"{working_dir}\"\n\
         shep_{user}_env=\"SHEP_HOME={home_env} PATH={path_env}\"\n\
         \n\
         pidfile=\"/var/run/shep_{user}.pid\"\n\
         command=\"/usr/sbin/daemon\"\n\
         command_args=\"-P ${{pidfile}} -r -f {exec_arg} daemon --foreground\"\n\
         \n\
         start_postcmd=\"shep_{user}_poststart\"\n\
         \n\
         # rc.subr reports the service started as soon as daemon(8) has forked, which\n\
         # is before the shepherd has finished restoring the muster roll. This waits\n\
         # for the shepherd to answer on its own control socket, which is the same\n\
         # milestone systemd's READY=1 reports.\n\
         shep_{user}_poststart()\n\
         {{\n\
         \t_waited=0\n\
         \twhile [ ${{_waited}} -lt 60 ]; do\n\
         \t\tif \"{exec}\" --home \"{home}\" flock >/dev/null 2>&1; then\n\
         \t\t\treturn 0\n\
         \t\tfi\n\
         \t\tsleep 1\n\
         \t\t_waited=$((_waited + 1))\n\
         \tdone\n\
         \techo \"shep did not answer on its control socket within 60s\" >&2\n\
         \treturn 1\n\
         }}\n\
         \n\
         load_rc_config $name\n\
         run_rc_command \"$1\"\n"
    )
}

/// Renders the OpenBSD `rc.d` script, `/etc/rc.d/shep_<user>`.
///
/// Like [`freebsd_rc_script`], `spec.user` must pass
/// [`super::privilege_check::is_rc_safe_user`] and is interpolated raw as an identifier.
/// `rc.subr(8)` has no post-start hook, so `shep --home <home> flock` is
/// the readiness check. The environment travels as `VAR=value` prefixes
/// inside the `su -fl ... -c "..."` string: `su -l` discards the rest.
pub(crate) fn openbsd_rc_script(spec: &UnitSpec) -> String {
    let user = &spec.user;
    let exec = sh_double_quoted(&shell_quote(&spec.exec.display().to_string()));
    let working_dir = sh_double_quoted(&spec.working_dir.display().to_string());
    let home_display = spec.home.display();
    let home_env = sh_double_quoted(&shell_quote(&spec.home.display().to_string()));
    let path_env = sh_double_quoted(&shell_quote(&spec.path.to_string_lossy()));
    format!(
        "#!/bin/ksh\n\
         #\n\
         # shep process manager for {user}\n\
         #\n\
         # Enable with: rcctl enable shep_{user} && rcctl start shep_{user}\n\
         #\n\
         # OpenBSD's rc.subr has no post-start hook: rc_pre runs before the daemon\n\
         # starts and rc_post runs after it stops. So this script reports the service\n\
         # started as soon as the shepherd process is spawned, which is BEFORE the\n\
         # muster restore has finished: the flock may still be coming back. There is\n\
         # no readiness protocol here and this script does not pretend to one. Check\n\
         # with: shep --home {home_display} flock\n\
         \n\
         daemon=\"{exec}\"\n\
         daemon_flags=\"daemon --foreground\"\n\
         daemon_user=\"{user}\"\n\
         daemon_execdir=\"{working_dir}\"\n\
         \n\
         . /etc/rc.d/rc.subr\n\
         \n\
         rc_bg=YES\n\
         rc_reload=NO\n\
         \n\
         # su(1)'s -l flag, which rc_exec always passes, discards the environment\n\
         # rc.subr itself ran in, so exporting SHEP_HOME/PATH above would never reach\n\
         # the daemon. Prefixing them onto the string rc_exec hands to su is the only\n\
         # way they survive. Single-quoted for the shell that evaluates that string,\n\
         # then escaped again for the double-quoted context here.\n\
         rc_start() {{\n\
         \trc_exec \"SHEP_HOME={home_env} PATH={path_env} ${{daemon}} ${{daemon_flags}}\"\n\
         }}\n\
         \n\
         rc_cmd $1\n"
    )
}

/// Escapes a value that lands inside a double-quoted shell assignment:
/// `"`, `$`, `` ` `` and `\` get a backslash.
///
/// Distinct from [`super::shell_quote`]: that produces a standalone
/// single-quoted word for a human to paste, this escapes content already
/// inside double quotes. A value a second shell re-evaluates composes the
/// two, innermost first: `sh_double_quoted(shell_quote(value))`.
fn sh_double_quoted(value: &str) -> String {
    let mut escaped = String::with_capacity(value.len());
    for ch in value.chars() {
        if matches!(ch, '"' | '$' | '`' | '\\') {
            escaped.push('\\');
        }
        escaped.push(ch);
    }
    escaped
}

#[cfg(test)]
mod tests {
    use std::path::Path;

    use super::*;
    use crate::cli::Init;
    use crate::commands::startup::unit_path_for;

    fn spec() -> UnitSpec {
        UnitSpec {
            user: "deploy".to_string(),
            exec: PathBuf::from("/usr/local/bin/shep"),
            home: PathBuf::from("/home/deploy/.shep"),
            path: OsString::from("/home/deploy/.bun/bin:/usr/local/bin:/usr/bin:/bin"),
            working_dir: PathBuf::from("/home/deploy"),
        }
    }

    /// Byte for byte, not `.contains`: a substring match can't catch a
    /// stray line, wrong section order, or a missing blank line between
    /// sections. Every value here round-trips with no escaping needed, so
    /// this also pins the unescaped happy path.
    #[test]
    fn the_systemd_unit_matches_the_spec_exactly() {
        let unit = systemd_unit(&spec());
        assert_eq!(
            unit,
            "[Unit]\n\
             Description=shep process manager for deploy\n\
             After=network.target\n\
             \n\
             [Service]\n\
             Type=notify\n\
             NotifyAccess=main\n\
             User=deploy\n\
             WorkingDirectory=/home/deploy\n\
             Environment=\"SHEP_HOME=/home/deploy/.shep\"\n\
             Environment=\"PATH=/home/deploy/.bun/bin:/usr/local/bin:/usr/bin:/bin\"\n\
             ExecStart=/usr/local/bin/shep daemon --foreground\n\
             ExecReload=/usr/local/bin/shep reload all\n\
             ExecStop=/usr/local/bin/shep kill\n\
             Restart=on-failure\n\
             RestartSec=5\n\
             RestartPreventExitStatus=10\n\
             Delegate=memory cpu pids\n\
             \n\
             [Install]\n\
             WantedBy=multi-user.target\n",
            "{unit}"
        );
    }

    /// Byte for byte, same rationale as the systemd exact-match test above:
    /// `.contains` cannot see a swapped tag order or a missing sibling key.
    #[test]
    fn the_launchd_plist_matches_the_spec_exactly() {
        let plist = launchd_plist(&spec());
        assert_eq!(
            plist,
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\
             <!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n\
             <plist version=\"1.0\">\n\
             <dict>\n\
             \t<key>Label</key><string>io.github.turtiesocks.shep.deploy</string>\n\
             \t<key>ProgramArguments</key>\n\
             \t<array>\n\
             \t\t<string>/usr/local/bin/shep</string>\n\
             \t\t<string>daemon</string>\n\
             \t\t<string>--foreground</string>\n\
             \t</array>\n\
             \t<key>UserName</key><string>deploy</string>\n\
             \t<key>WorkingDirectory</key><string>/home/deploy</string>\n\
             \t<key>EnvironmentVariables</key>\n\
             \t<dict>\n\
             \t\t<key>SHEP_HOME</key><string>/home/deploy/.shep</string>\n\
             \t\t<key>PATH</key><string>/home/deploy/.bun/bin:/usr/local/bin:/usr/bin:/bin</string>\n\
             \t</dict>\n\
             \t<key>RunAtLoad</key><true/>\n\
             \t<key>KeepAlive</key>\n\
             \t<dict><key>SuccessfulExit</key><false/></dict>\n\
             \t<key>StandardOutPath</key><string>/home/deploy/.shep/logs/shepd.out.log</string>\n\
             \t<key>StandardErrorPath</key><string>/home/deploy/.shep/logs/shepd.err.log</string>\n\
             </dict>\n\
             </plist>\n",
            "{plist}"
        );
    }

    /// fails if any of the four ExecStart/Reload/Stop/Type lines drifts.
    /// Each is load-bearing: Type=notify is what makes the unit go green on
    /// a restored flock, and an ExecStart naming `muster` would have systemd
    /// supervising a client that exits immediately.
    #[test]
    fn the_systemd_unit_carries_the_four_lines_that_matter() {
        let unit = systemd_unit(&spec());
        assert!(unit.contains("Type=notify"), "{unit}");
        assert!(
            unit.contains("ExecStart=/usr/local/bin/shep daemon --foreground"),
            "{unit}"
        );
        assert!(
            unit.contains("ExecReload=/usr/local/bin/shep reload all"),
            "{unit}"
        );
        assert!(unit.contains("ExecStop=/usr/local/bin/shep kill"), "{unit}");
        assert!(unit.contains("WantedBy=multi-user.target"), "{unit}");
    }

    /// fails if the unit stops delegating, or widens to `Delegate=yes`. The
    /// shepherd runs as `User=`, so it can write its own cgroup subtree only
    /// once systemd chowns it; the three controllers are all it uses.
    #[test]
    fn the_unit_delegates_memory_cpu_and_pids() {
        let unit = systemd_unit(&spec());
        let service = unit
            .split("[Service]\n")
            .nth(1)
            .and_then(|rest| rest.split("\n[").next())
            .unwrap_or_default();
        assert!(
            service.lines().any(|l| l == "Delegate=memory cpu pids"),
            "{unit}"
        );
    }

    /// fails if an Environment value stops being quoted, or a `%` stops
    /// being escaped. A PATH with a space silently truncates at the space;
    /// a `%` is a systemd specifier and expands to something else entirely.
    /// Both are reachable from a real captured PATH, and neither is visible
    /// until an interpreter is not found after a reboot.
    #[test]
    fn environment_values_are_quoted_and_specifier_escaped() {
        let mut spec = spec();
        spec.path = OsString::from("/opt/my tools/bin:/usr/bin:/pct%dir/bin");
        let unit = systemd_unit(&spec);
        assert!(
            unit.contains(r#"Environment="PATH=/opt/my tools/bin:/usr/bin:/pct%%dir/bin""#),
            "{unit}"
        );
    }

    /// fails if plist values stop being XML-escaped. A `&` in a path makes
    /// the whole plist unparseable, and launchd's refusal names the file
    /// rather than the character.
    #[test]
    fn plist_values_are_xml_escaped() {
        let mut spec = spec();
        spec.home = PathBuf::from("/home/r&d/.shep");
        let plist = launchd_plist(&spec);
        assert!(
            plist.contains("<string>/home/r&amp;d/.shep</string>"),
            "{plist}"
        );
        assert!(
            !plist.contains("r&d"),
            "a raw ampersand makes the plist unparseable"
        );
    }

    /// `systemd_unit_path`/`launchd_label`/`launchd_plist_path` are simple
    /// format strings, but `systemctl enable` and `launchctl bootout`
    /// address a unit by exactly these, so they get the same exact-match
    /// treatment as the two renderers above.
    #[test]
    fn the_install_paths_and_label_match_the_spec_exactly() {
        assert_eq!(
            systemd_unit_path("deploy"),
            PathBuf::from("/etc/systemd/system/shep-deploy.service")
        );
        assert_eq!(launchd_label("deploy"), "io.github.turtiesocks.shep.deploy");
        assert_eq!(
            launchd_plist_path("deploy"),
            PathBuf::from("/Library/LaunchDaemons/io.github.turtiesocks.shep.deploy.plist")
        );
    }

    /// Probes `systemd-analyze`'s two conventional install paths with
    /// `Path::exists` rather than shelling out to `which`: one fewer
    /// process, no dependence on the test's own `$PATH`.
    fn which_systemd_analyze() -> Result<PathBuf, ()> {
        for candidate in ["/usr/bin/systemd-analyze", "/bin/systemd-analyze"] {
            let path = Path::new(candidate);
            if path.exists() {
                return Ok(path.to_path_buf());
            }
        }
        Err(())
    }

    /// systemd's own parser is the only thing that can say the generated
    /// unit is well-formed; every assertion above is our opinion of it.
    /// Skips, loudly, when the tool is absent, as on macOS.
    ///
    /// Builds its own spec rather than [`spec`]'s: `verify` resolves
    /// `ExecStart`/`ExecReload`/`ExecStop` against the real filesystem, so
    /// this process's own executable stands in for `spec()`'s fixture path.
    #[test]
    fn systemd_analyze_accepts_the_generated_unit() {
        let Ok(analyze) = which_systemd_analyze() else {
            eprintln!("skipping: systemd-analyze is not on this machine");
            return;
        };
        let mut unit_spec = spec();
        unit_spec.exec = std::env::current_exe().unwrap();

        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("shep-deploy.service");
        std::fs::write(&path, systemd_unit(&unit_spec)).unwrap();
        let out = std::process::Command::new(analyze)
            .arg("verify")
            .arg(&path)
            .output()
            .unwrap();
        assert!(
            out.status.success(),
            "systemd-analyze verify rejected the unit:\n{}",
            String::from_utf8_lossy(&out.stderr)
        );
    }

    /// fails if the readiness poll is ever dropped or unbounded. openrc's
    /// only honest answer to Type=notify.
    #[test]
    fn the_openrc_script_polls_for_readiness_and_bounds_the_wait() {
        let rendered = openrc_script(&spec());
        assert!(rendered.contains("start_post()"));
        assert!(rendered.contains("-lt 60"), "the poll must be bounded");
        assert!(rendered.contains("flock >/dev/null"));
        assert!(
            rendered.contains("return 1"),
            "a timeout must fail the service"
        );
    }

    /// Guards the rendered script's own explanation of why polling stands
    /// in for `READY=1`: prose in a generated artefact can go stale
    /// silently otherwise.
    #[test]
    fn the_openrc_script_says_why_it_polls() {
        let rendered = openrc_script(&spec());
        assert!(rendered.contains("openrc has no sd_notify analogue"));
        assert!(rendered.contains("binds its control socket before the restore"));
    }

    /// A `home` carrying every character [`sh_double_quoted`] escapes.
    const SHELL_METACHARACTER_HOME: &str = r#"/tmp/we"ird/$HOME/`x`/back\slash"#;

    /// Asserts a script built from [`SHELL_METACHARACTER_HOME`] escaped all
    /// four, so a fifth character added to the escape set is pinned here
    /// rather than in each rc flavour's test.
    fn assert_double_quoted_escapes(rendered: &str) {
        assert!(
            rendered.contains(r#"we\"ird"#),
            "a quote must be escaped: {rendered}"
        );
        assert!(
            rendered.contains(r"\$HOME"),
            "a dollar must be escaped: {rendered}"
        );
        assert!(
            rendered.contains(r"\`x\`"),
            "a backtick must be escaped: {rendered}"
        );
        assert!(
            rendered.contains(r"back\\slash"),
            "a backslash must be escaped: {rendered}"
        );
    }

    /// fails if a metacharacter in a path escapes the double quotes.
    #[test]
    fn the_openrc_script_quotes_shell_metacharacters() {
        let mut s = spec();
        s.home = PathBuf::from(SHELL_METACHARACTER_HOME);
        let rendered = openrc_script(&s);
        assert_double_quoted_escapes(&rendered);
    }

    /// openrc derives defaults from `name`/`RC_SVCNAME`; a constant `name`
    /// would make two users on one host collide.
    #[test]
    fn the_openrc_name_is_per_user_and_matches_the_file() {
        let rendered = openrc_script(&spec());
        assert!(rendered.contains(r#"name="shep-deploy""#), "{rendered}");
        assert_eq!(
            unit_path_for(Init::Openrc, "deploy"),
            PathBuf::from("/etc/init.d/shep-deploy")
        );
    }

    #[test]
    fn the_openrc_script_is_the_same_entry_point_as_the_other_two() {
        let rendered = openrc_script(&spec());
        assert!(rendered.contains(r#"command_args="daemon --foreground""#));
    }

    /// The two must agree, or `sysrc shep_<user>_enable=YES` sets a
    /// variable nothing reads, and the service never starts at boot.
    #[test]
    fn the_freebsd_rcvar_matches_the_script_name() {
        let rendered = freebsd_rc_script(&spec());
        assert!(rendered.contains(r#"name="shep_deploy""#), "{rendered}");
        assert!(
            rendered.contains(r#"rcvar="shep_deploy_enable""#),
            "{rendered}"
        );
        assert!(rendered.contains("PROVIDE: shep_deploy"), "{rendered}");
        assert_eq!(
            unit_path_for(Init::FreebsdRc, "deploy"),
            PathBuf::from("/usr/local/etc/rc.d/shep_deploy")
        );
    }

    /// OpenBSD's `rc.subr` has no post-start hook.
    #[test]
    fn the_openbsd_script_admits_it_has_no_readiness_gate() {
        let rendered = openbsd_rc_script(&spec());
        assert!(rendered.contains("no post-start hook"), "{rendered}");
        assert!(rendered.contains("BEFORE the"), "{rendered}");
        assert!(
            !rendered.contains("start_post"),
            "OpenBSD has no such hook: {rendered}"
        );
        assert!(
            !rendered.contains("READY=1"),
            "that is systemd's, not this: {rendered}"
        );
    }

    /// A shepherd started without `SHEP_HOME` falls back to root's
    /// `~/.shep` and restores nothing.
    #[test]
    fn both_bsd_scripts_carry_shep_home_and_path() {
        for rendered in [freebsd_rc_script(&spec()), openbsd_rc_script(&spec())] {
            assert!(rendered.contains("SHEP_HOME="), "{rendered}");
            assert!(rendered.contains("PATH="), "{rendered}");
        }
    }

    /// fails if a metacharacter in `home` escapes the quoting in the
    /// FreeBSD script. Same class as the openrc test above; this one is
    /// worse in the `${name}_env` line, where `rc.subr` word-splits the
    /// result into arguments for `env(1)`.
    #[test]
    fn the_freebsd_script_quotes_shell_metacharacters() {
        let mut s = spec();
        s.home = PathBuf::from(SHELL_METACHARACTER_HOME);
        let rendered = freebsd_rc_script(&s);
        assert_double_quoted_escapes(&rendered);
    }

    /// fails if a metacharacter in `home` escapes the quoting in the
    /// OpenBSD script. Worse than the openrc case: OpenBSD hands its whole
    /// interpolated string to a shell for evaluation via `su -c`.
    #[test]
    fn the_openbsd_script_quotes_shell_metacharacters() {
        let mut s = spec();
        s.home = PathBuf::from(SHELL_METACHARACTER_HOME);
        let rendered = openbsd_rc_script(&s);
        assert_double_quoted_escapes(&rendered);
    }

    /// fails if a `PATH` containing a space becomes two environment entries.
    /// `${name}_env` is a space-separated list rc.subr word-splits into
    /// arguments for `env(1)`, and capturing a real `PATH` is the whole
    /// reason that field exists.
    #[test]
    fn a_path_with_a_space_stays_one_freebsd_env_entry() {
        let mut s = spec();
        s.path = OsString::from("/opt/my tools/bin:/usr/bin");
        let rendered = freebsd_rc_script(&s);
        assert!(
            rendered.contains("PATH='/opt/my tools/bin:/usr/bin'"),
            "the space must stay inside the single-quoted word: {rendered}"
        );
    }

    /// fails if an `exec` path containing a space splits into two argv
    /// elements when `rc.subr` later expands `$command_args` unquoted into
    /// `daemon(8)`'s argv. Without the two-context escape, `daemon(8)`
    /// would be handed `/opt/my` and `tools/shep` as separate arguments and
    /// would exec the wrong (nonexistent) file at the next reboot.
    #[test]
    fn a_path_with_a_space_stays_one_freebsd_command_args_word() {
        let mut s = spec();
        s.exec = PathBuf::from("/opt/my tools/shep");
        let rendered = freebsd_rc_script(&s);
        assert!(
            rendered.contains("-f '/opt/my tools/shep' daemon --foreground"),
            "the space must stay inside the single-quoted word: {rendered}"
        );
        assert!(
            rendered.contains("if \"/opt/my tools/shep\" --home"),
            "start_postcmd's own direct invocation stays single-escaped: {rendered}"
        );
    }

    /// fails if an `exec` path containing a space splits into two words once
    /// `${daemon}` is interpolated unquoted into the string `rc_exec` hands
    /// to `su -c`, which spawns a second shell that word-splits it.
    #[test]
    fn a_path_with_a_space_stays_one_openbsd_daemon_word() {
        let mut s = spec();
        s.exec = PathBuf::from("/opt/my tools/shep");
        let rendered = openbsd_rc_script(&s);
        assert!(
            rendered.contains("daemon=\"'/opt/my tools/shep'\""),
            "the space must stay inside the single-quoted word: {rendered}"
        );
    }

    /// Byte-for-byte, the same tier `the_systemd_unit_matches_the_spec_exactly`
    /// and `the_launchd_plist_matches_the_spec_exactly` already set. The
    /// `.contains` tests above each guard one claim; this one guards the
    /// whole artefact, which is the only kind of test a file nobody can run
    /// on its own OS can have.
    #[test]
    fn the_openbsd_script_matches_the_spec_exactly() {
        let rendered = openbsd_rc_script(&spec());
        assert_eq!(
            rendered,
            "#!/bin/ksh\n\
             #\n\
             # shep process manager for deploy\n\
             #\n\
             # Enable with: rcctl enable shep_deploy && rcctl start shep_deploy\n\
             #\n\
             # OpenBSD's rc.subr has no post-start hook: rc_pre runs before the daemon\n\
             # starts and rc_post runs after it stops. So this script reports the service\n\
             # started as soon as the shepherd process is spawned, which is BEFORE the\n\
             # muster restore has finished: the flock may still be coming back. There is\n\
             # no readiness protocol here and this script does not pretend to one. Check\n\
             # with: shep --home /home/deploy/.shep flock\n\
             \n\
             daemon=\"/usr/local/bin/shep\"\n\
             daemon_flags=\"daemon --foreground\"\n\
             daemon_user=\"deploy\"\n\
             daemon_execdir=\"/home/deploy\"\n\
             \n\
             . /etc/rc.d/rc.subr\n\
             \n\
             rc_bg=YES\n\
             rc_reload=NO\n\
             \n\
             # su(1)'s -l flag, which rc_exec always passes, discards the environment\n\
             # rc.subr itself ran in, so exporting SHEP_HOME/PATH above would never reach\n\
             # the daemon. Prefixing them onto the string rc_exec hands to su is the only\n\
             # way they survive. Single-quoted for the shell that evaluates that string,\n\
             # then escaped again for the double-quoted context here.\n\
             rc_start() {\n\
             \trc_exec \"SHEP_HOME=/home/deploy/.shep PATH=/home/deploy/.bun/bin:/usr/local/bin:/usr/bin:/bin ${daemon} ${daemon_flags}\"\n\
             }\n\
             \n\
             rc_cmd $1\n",
            "{rendered}"
        );
    }
}