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
//! Boot and lifecycle: config load, the log subscriber, [`boot_supervisor`]
//! and [`run_daemon`], and the exit-code mapping for both.

use std::collections::BTreeMap;
use std::ffi::OsStr;
use std::io::IsTerminal;

use shep_core::config::{DaemonConfig, DaemonConfigError, DaemonOverrides};
use shep_core::paths::ShepPaths;
use shep_core::protocol::DogSource;
use shep_core::values::UpDuration;
use shep_daemon::boot::{BootError, BootOptions, RunningDaemon, boot};
use shep_daemon::dogs::DogSpec;
#[cfg(unix)]
use shep_daemon::notify::NOTIFY_SOCKET_ENV;
use shep_daemon::tokio_runner::TokioRunner;
use tracing_subscriber::EnvFilter;

use crate::cli::DaemonArgs;
use crate::commands::dog_migration::{self, DogMigrationError};
use crate::commands::dogs::{upgrade_grants, upgrade_notice};
use crate::exit::ExitCode;

/// Everything [`run_daemon`] can fail with.
///
/// [`Self::Boot`] and [`Self::Run`] both wrap a [`BootError`] and stay
/// distinct: `Run` means the supervisor came up and served.
#[derive(Debug)]
pub enum DaemonRunError {
    /// `shep.toml` was unreadable as config.
    Config(DaemonConfigError),
    /// The supervisor failed to come up, before it ever served a request.
    Boot(BootError),
    /// The supervisor came up and served, then failed during its run loop
    /// or teardown.
    Run(BootError),
    /// `[dog.<name>]` sections could not be moved into `dogs.toml`. Raised
    /// before the supervisor comes up, so no dog has read a section from
    /// either file yet.
    DogMigration(DogMigrationError),
}

impl core::fmt::Display for DaemonRunError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::Config(err) => write!(f, "invalid daemon configuration: {err}"),
            Self::Boot(err) => write!(f, "the daemon failed to boot: {err}"),
            Self::Run(err) => write!(f, "the daemon failed while running: {err}"),
            Self::DogMigration(err) => write!(f, "invalid dog configuration: {err}"),
        }
    }
}

impl core::error::Error for DaemonRunError {
    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
        match self {
            Self::Config(err) => Some(err),
            Self::Boot(err) | Self::Run(err) => Some(err),
            Self::DogMigration(err) => Some(err),
        }
    }
}

impl From<DaemonConfigError> for DaemonRunError {
    fn from(source: DaemonConfigError) -> Self {
        Self::Config(source)
    }
}

// No `impl From<BootError>`: both `Boot` and `Run` wrap one, so each call
// site picks with an explicit `map_err`.

/// Loads `paths.daemon_config`'s raw source, `None` for a missing file.
///
/// Only `NotFound` is swallowed: any other IO failure is a fault on a real
/// path, and is reported through [`DaemonRunError::Boot`].
pub(super) fn read_daemon_config_source(
    paths: &ShepPaths,
) -> Result<Option<String>, DaemonRunError> {
    match std::fs::read_to_string(&paths.daemon_config) {
        Ok(src) => Ok(Some(src)),
        Err(source) if source.kind() == std::io::ErrorKind::NotFound => Ok(None),
        Err(source) => Err(DaemonRunError::Boot(BootError::Io {
            path: paths.daemon_config.clone(),
            source,
        })),
    }
}

/// Installs the subscriber that renders the daemon's own records.
///
/// The sink is stderr, which `launch.rs` has already redirected into
/// `$SHEP_HOME/logs/shepd.err.log` for a re-exec'd daemon.
///
/// Records are written from tokio worker threads, so `main::run`'s `daemon`
/// arm must not hold a `stderr().lock()` guard while this process runs.
fn install_log_subscriber(config: &DaemonConfig) {
    let builder = tracing_subscriber::fmt()
        .with_env_filter(EnvFilter::new(config.daemon.log_level.as_str()))
        .with_writer(std::io::stderr);
    let installed = if config.daemon.log_json {
        builder.json().try_init()
    } else {
        builder
            .with_ansi(ansi_enabled(
                std::io::stderr().is_terminal(),
                std::env::var_os("NO_COLOR").as_deref(),
            ))
            .try_init()
    };
    if let Err(err) = installed {
        eprintln!("shep: the daemon's own logs are not being rendered: {err}");
    }
}

/// Whether ANSI colour belongs on the daemon's own records: only when stderr
/// is a terminal, and only when `NO_COLOR` is unset or empty.
///
/// `RUST_LOG` is ignored; `[daemon] log_level` and `SHEP_LOG_LEVEL` are the
/// only level knobs. An empty `NO_COLOR` is an unset one, per the convention.
fn ansi_enabled(stderr_is_terminal: bool, no_color: Option<&OsStr>) -> bool {
    stderr_is_terminal && no_color.is_none_or(OsStr::is_empty)
}

/// Loads config, installs the log subscriber, and boots the supervisor:
/// everything [`run_daemon`] does except serve.
///
/// Separate from [`run_daemon`] so `commands::foreground` can hold the booted
/// daemon rather than block until shutdown. The log subscriber is global, so
/// it is installed here rather than in `shep_daemon::boot`, which one test
/// binary calls many times.
///
/// # Errors
/// - [`DaemonRunError::Config`]: `shep.toml` or a `SHEP_*` override is invalid.
/// - [`DaemonRunError::Boot`]: the config file was unreadable, or the boot failed.
/// - [`DaemonRunError::DogMigration`]: `[dog]` sections could not be moved.
pub async fn boot_supervisor(
    paths: ShepPaths,
    args: &DaemonArgs,
    delete_flock_on_shutdown: bool,
) -> Result<RunningDaemon, DaemonRunError> {
    // Before the config load and before the supervisor: `dog_section` reads
    // the new file from the first request onward, and a dog can connect as
    // soon as the socket is up. Idempotent, and takes both files' locks in
    // this crate's one order, shep.toml outer, dogs.toml inner.
    let moved =
        dog_migration::migrate_dog_sections(&paths).map_err(DaemonRunError::DogMigration)?;
    if !moved.is_empty() {
        // Not `tracing`: `install_log_subscriber` runs below, so a record
        // written here would be dropped.
        eprintln!(
            "shep: moved dog config out of shep.toml and into dogs.toml: {}",
            moved.join(", ")
        );
    }
    // Before the config load, for the same reason: the boot reads each dog's
    // grants from the file, so a list this writes is the one it enforces. A
    // refusal here is not a boot failure. The dogs keep the grants they hold,
    // and `shep enable` looks again.
    match upgrade_grants(&paths) {
        Ok(changed) if changed.is_empty() => {}
        Ok(changed) => eprintln!("shep: {}", upgrade_notice(&changed)),
        Err(err) => eprintln!("shep: could not update the grants recorded for dogs: {err}"),
    }
    let env = |key: &str| std::env::var(key).ok();
    let file_source = read_daemon_config_source(&paths)?;
    let overrides = daemon_overrides(args);
    let config = DaemonConfig::load_layered(file_source.as_deref(), &env, &overrides)?;
    install_log_subscriber(&config);
    // The one read of `$NOTIFY_SOCKET` in the workspace. Unix only: it is
    // systemd's readiness protocol, and the field stays on `BootOptions` for
    // both platforms.
    #[cfg(unix)]
    let notify_socket = std::env::var_os(NOTIFY_SOCKET_ENV);
    #[cfg(windows)]
    let notify_socket: Option<std::ffi::OsString> = None;
    let mut options = boot_options(&config, args, notify_socket.as_deref());
    options.delete_flock_on_shutdown = delete_flock_on_shutdown;
    let daemon = boot(TokioRunner::new(), paths, options)
        .await
        .map_err(DaemonRunError::Boot)?;
    // The one publisher of `config.dog.<name>`: the migration above ran
    // before `boot`, when there was no bus to publish onto.
    daemon.context().announce_dog_config(&moved);
    Ok(daemon)
}

/// Runs the supervisor in this process until a signal or `KillDaemon`.
///
/// [`boot_supervisor`] plus `.run()`.
///
/// # Errors
/// - [`DaemonRunError::Config`]: `shep.toml` or a `SHEP_*` override is invalid.
/// - [`DaemonRunError::Boot`]: the config file was unreadable, or the boot failed.
/// - [`DaemonRunError::Run`]: the supervisor served, then failed in its run
///   loop or teardown.
/// - [`DaemonRunError::DogMigration`]: `[dog]` sections could not be moved.
pub async fn run_daemon(paths: ShepPaths, args: &DaemonArgs) -> Result<(), DaemonRunError> {
    // A production daemon always keeps its final roll: `shep muster` after a
    // reboot reads it.
    boot_supervisor(paths, args, false)
        .await?
        .run()
        .await
        .map_err(DaemonRunError::Run)
}

/// Builds the CLI-flag layer of `file < env < flags` from the `daemon`
/// subcommand's own arguments.
#[must_use]
pub fn daemon_overrides(args: &DaemonArgs) -> DaemonOverrides {
    DaemonOverrides::new()
        .log_json(args.log_json)
        .log_level(args.log_level)
        .socket(args.socket.clone())
        .max_cron_sleep(args.max_cron_sleep)
}

/// Builds [`BootOptions`] from `config`, the daemon flags, and `$NOTIFY_SOCKET`.
///
/// `ready_fd` stays `None`: readiness is a completed handshake, and this crate
/// forbids unsafe code. `notify_socket` is a parameter, since
/// `std::env::set_var` is `unsafe` in edition 2024.
///
/// `[daemon] enabled_dogs` names each dog to start, in the order written.
#[must_use]
pub fn boot_options(
    config: &DaemonConfig,
    args: &DaemonArgs,
    notify_socket: Option<&OsStr>,
) -> BootOptions {
    let mut seen = std::collections::BTreeSet::new();
    BootOptions {
        socket: config.daemon.socket.clone(),
        ready_fd: None,
        restore: !args.no_restore,
        environment: Some(config.daemon.environment.clone()),
        max_cron_sleep: config.daemon.max_cron_sleep.map(UpDuration::as_duration),
        notify_socket: notify_socket
            .filter(|_| args.foreground)
            .map(OsStr::to_os_string),
        dogs: config
            .daemon
            .enabled_dogs
            .iter()
            .map(|name| dog_spec(config, name))
            .collect(),
        // Every dog that exists, not the spawn order above: the shepherd
        // lists each at rest, and `Request::SetDogConfig` is guarded on
        // this one, because the dog most in need of configuring is one that
        // is disabled or has never started.
        known_dogs: crate::dog::BUILT_IN_DOGS
            .iter()
            .map(|built_in| (*built_in).to_string())
            .chain(config.daemon.adopted_dogs.keys().cloned())
            .chain(config.daemon.enabled_dogs.iter().cloned())
            .filter(|name| seen.insert(name.clone()))
            .map(|name| dog_spec(config, &name))
            .collect(),
        boot_first_dogs: config.daemon.boot_first_dogs.clone(),
        // Overwritten by `boot_supervisor`, the only caller that ever wants
        // `true`.
        delete_flock_on_shutdown: false,
        // This process is the shep binary, which is what the field asserts, so
        // an init system's SIGHUP reaches the handover `shep daemon reload` does.
        handover: true,
    }
}

/// The dog `name` is: adopted from the entry `shep.toml` records, or built
/// in, with the grants and the `env` `shep.toml` records for it.
pub(crate) fn dog_spec(config: &DaemonConfig, name: &str) -> DogSpec {
    let grants = config
        .daemon
        .dog_grants
        .get(name)
        .map(|section| section.granted.clone());
    let events = config
        .daemon
        .dog_grants
        .get(name)
        .map(|section| section.events.clone())
        .unwrap_or_default();
    let (source, env) = match config.daemon.adopted_dogs.get(name) {
        Some(entry) => (
            DogSource::Adopted {
                grants,
                path: entry.path.display().to_string(),
                channel: config.daemon.channel_dogs.iter().any(|dog| dog == name),
                events,
            },
            entry.env.clone(),
        ),
        None => (DogSource::BuiltIn { grants, events }, BTreeMap::new()),
    };
    DogSpec {
        name: name.to_string(),
        source,
        env,
    }
}

/// Maps a boot or run failure to the process exit status the parent will read.
///
/// [`BootError`] is `#[non_exhaustive]`, so the [`DaemonRunError::Boot`] arm
/// carries a wildcard and only [`BootError::AlreadyRunning`] gets its own
/// code. [`DaemonRunError::Run`] is always [`ExitCode::Failure`], since
/// `RunningDaemon::run()` names only `BootError::Io`.
#[must_use]
pub fn daemon_exit_code(err: &DaemonRunError) -> ExitCode {
    match err {
        DaemonRunError::Config(_) => ExitCode::InvalidConfig,
        DaemonRunError::Boot(boot_err) => match boot_err {
            BootError::AlreadyRunning { .. } => ExitCode::DaemonAlreadyRunning,
            // `Io`/`Snapshot`/`ReadyWrite` today, plus any future variant
            // `#[non_exhaustive]` makes room for.
            _ => ExitCode::Failure,
        },
        DaemonRunError::Run(_) => ExitCode::Failure,
        // Every refusal this variant carries, I/O faults included, is a
        // shep.toml or dogs.toml an operator has to edit.
        DaemonRunError::DogMigration(_) => ExitCode::InvalidConfig,
    }
}

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

    /// An all-default [`DaemonArgs`]: no subcommand, both flags off, every
    /// option `None`, so the `shep.toml` a test hands [`boot_options`] is the
    /// only thing deciding what it gets. A test that needs one field set names
    /// that field over `..args()`.
    fn args() -> DaemonArgs {
        DaemonArgs {
            cmd: None,
            no_restore: false,
            foreground: false,
            log_json: None,
            log_level: None,
            socket: None,
            max_cron_sleep: None,
        }
    }

    #[test]
    fn every_daemon_flag_reaches_the_config() {
        let args = DaemonArgs {
            cmd: None,
            no_restore: false,
            foreground: false,
            log_json: Some(true),
            log_level: Some(LogLevel::Trace),
            socket: Some(std::path::PathBuf::from("/tmp/flag.sock")),
            max_cron_sleep: Some(UpDuration::from_millis(120_000)),
        };
        let cfg = DaemonConfig::load_layered(
            Some(
                "[daemon]\nlog_json = false\nlog_level = \"error\"\nsocket = \"/tmp/file.sock\"\n",
            ),
            &|_| None,
            &daemon_overrides(&args),
        )
        .unwrap();
        assert!(cfg.daemon.log_json);
        assert_eq!(cfg.daemon.log_level, LogLevel::Trace);
        assert_eq!(
            cfg.daemon.socket,
            Some(std::path::PathBuf::from("/tmp/flag.sock"))
        );
        assert_eq!(
            cfg.daemon.max_cron_sleep,
            Some(UpDuration::from_millis(120_000))
        );
    }

    #[test]
    fn a_dog_spec_carries_the_event_kinds_recorded_beside_its_grants() {
        let config = DaemonConfig::load_layered(
            Some(
                "[daemon.adopted_dogs]\notel = \"/bin/shep-otel\"\n\n\
                 [daemon.dog_grants.otel]\ngranted = []\nevents = [\"exported\"]\n",
            ),
            &|_| None,
            &daemon_overrides(&args()),
        )
        .unwrap();

        let spec = dog_spec(&config, "otel");

        assert_eq!(spec.source.events(), ["exported".to_string()]);
        assert_eq!(
            dog_spec(&config, "bark").source.events(),
            Vec::<String>::new()
        );
    }

    #[test]
    fn colour_needs_a_terminal_and_no_no_color() {
        assert!(ansi_enabled(true, None));
        assert!(!ansi_enabled(false, None), "a file never gets escape codes");
        assert!(!ansi_enabled(true, Some(OsStr::new("1"))));
        assert!(
            ansi_enabled(true, Some(OsStr::new(""))),
            "an empty NO_COLOR is an unset NO_COLOR"
        );
        assert!(
            !ansi_enabled(false, Some(OsStr::new("1"))),
            "the two reasons to suppress colour must not cancel out"
        );
    }

    #[test]
    fn boot_options_pass_ready_fd_none_and_the_configured_socket() {
        let config =
            DaemonConfig::load(Some("[daemon]\nsocket = \"/tmp/custom.sock\"\n"), &|_| None)
                .unwrap();
        let opts = boot_options(&config, &args(), None);
        assert!(
            opts.ready_fd.is_none(),
            "readiness is a handshake in this phase"
        );
        assert_eq!(
            opts.socket.as_deref(),
            Some(std::path::Path::new("/tmp/custom.sock"))
        );
        assert!(opts.restore, "the default is to restore the muster roll");
    }

    /// `metrics` in `channel_dogs` is a hand edit: a built-in never takes
    /// the channel, whatever the file says.
    #[test]
    fn boot_options_carry_every_enabled_dog_with_the_source_the_file_names() {
        let src = r#"
[daemon]
enabled_dogs = ["metrics", "otel", "jobs"]
channel_dogs = ["jobs", "metrics"]

[daemon.adopted_dogs]
otel = "/usr/local/bin/shep-otel"
jobs = "/usr/local/bin/shep-jobs"
"#;
        let config = DaemonConfig::load(Some(src), &|_| None).unwrap();
        let opts = boot_options(&config, &args(), None);
        assert_eq!(
            opts.dogs,
            vec![
                DogSpec {
                    name: "metrics".into(),
                    source: DogSource::BuiltIn {
                        grants: None,
                        events: Vec::new()
                    },
                    env: BTreeMap::new(),
                },
                DogSpec {
                    name: "otel".into(),
                    source: DogSource::Adopted {
                        grants: None,
                        path: "/usr/local/bin/shep-otel".into(),
                        channel: false,
                        events: Vec::new(),
                    },
                    env: BTreeMap::new(),
                },
                DogSpec {
                    name: "jobs".into(),
                    source: DogSource::Adopted {
                        grants: None,
                        path: "/usr/local/bin/shep-jobs".into(),
                        channel: true,
                        events: Vec::new(),
                    },
                    env: BTreeMap::new(),
                },
            ]
        );
    }

    // fails if the key parses but never reaches the daemon, which would
    // leave log-rotate starting after the flock it exists to serve
    #[test]
    fn boot_options_carries_the_promoted_dogs() {
        let src = r#"
[daemon]
enabled_dogs = ["metrics", "log-rotate"]
boot_first_dogs = ["log-rotate"]
"#;
        let config = DaemonConfig::load(Some(src), &|_| None).unwrap();
        let opts = boot_options(&config, &args(), None);
        assert_eq!(opts.boot_first_dogs, vec!["log-rotate".to_string()]);
    }

    #[test]
    fn boot_options_know_every_dog_that_exists_and_not_only_the_enabled_ones() {
        let src = r#"
[daemon]
enabled_dogs = ["metrics"]

[daemon.adopted_dogs]
otel = "/usr/local/bin/shep-otel"
"#;
        let config = DaemonConfig::load(Some(src), &|_| None).unwrap();
        let opts = boot_options(&config, &args(), None);

        assert_eq!(
            opts.known_dogs,
            vec![
                DogSpec {
                    name: "metrics".into(),
                    source: DogSource::BuiltIn {
                        grants: None,
                        events: Vec::new()
                    },
                    env: BTreeMap::new(),
                },
                DogSpec {
                    name: "bark".into(),
                    source: DogSource::BuiltIn {
                        grants: None,
                        events: Vec::new()
                    },
                    env: BTreeMap::new(),
                },
                DogSpec {
                    name: "otel".into(),
                    source: DogSource::Adopted {
                        grants: None,
                        path: "/usr/local/bin/shep-otel".into(),
                        channel: false,
                        events: Vec::new(),
                    },
                    env: BTreeMap::new(),
                },
            ],
            "adopted-and-disabled is the case this field exists for"
        );
    }

    #[test]
    fn boot_options_carry_the_configured_max_cron_sleep_and_invent_none() {
        let configured =
            DaemonConfig::load(Some("[daemon]\nmax_cron_sleep = \"5m\"\n"), &|_| None).unwrap();
        assert_eq!(
            boot_options(&configured, &args(), None).max_cron_sleep,
            Some(core::time::Duration::from_secs(300))
        );

        let unset = DaemonConfig::load(None, &|_| None).unwrap();
        assert_eq!(
            boot_options(&unset, &args(), None).max_cron_sleep,
            None,
            "an unset knob must stay None: the daemon owns the default"
        );
    }

    #[test]
    fn boot_options_carry_the_configured_environment_and_default_to_production() {
        // The host default every sheep naming no `environment` of its own
        // resolves its `{{secret:...}}` references in, so an unset file
        // reaching the supervisor as anything but `production` would move
        // every such sheep to a different slot of the store.
        let configured =
            DaemonConfig::load(Some("[daemon]\nenvironment = \"staging\"\n"), &|_| None).unwrap();
        assert_eq!(
            boot_options(&configured, &args(), None).environment,
            Some("staging".to_string())
        );

        let unset = DaemonConfig::load(None, &|_| None).unwrap();
        assert_eq!(
            boot_options(&unset, &args(), None).environment,
            Some("production".to_string())
        );
    }

    #[test]
    fn no_restore_boots_without_the_muster_roll() {
        let config = DaemonConfig::load(None, &|_| None).unwrap();
        let opts = boot_options(
            &config,
            &DaemonArgs {
                no_restore: true,
                ..args()
            },
            None,
        );
        assert!(!opts.restore);
    }

    #[test]
    fn the_foreground_flag_reaches_the_boot_options() {
        let config = DaemonConfig::load(None, &|_| None).unwrap();
        let bare = boot_options(&config, &args(), None);
        assert!(
            bare.notify_socket.is_none(),
            "an autostarted daemon reports to nobody"
        );

        let supervised = boot_options(
            &config,
            &DaemonArgs {
                foreground: true,
                ..args()
            },
            Some(OsStr::new("/run/systemd/notify")),
        );
        assert_eq!(
            supervised.notify_socket.as_deref(),
            Some(OsStr::new("/run/systemd/notify"))
        );

        // Without the flag the address is ignored, so a shep autostarted
        // inside another notify-type service cannot report readiness by accident.
        let unflagged = boot_options(
            &config,
            &DaemonArgs {
                foreground: true,
                ..args()
            },
            None,
        );
        assert!(unflagged.notify_socket.is_none());

        let inherited = boot_options(&config, &args(), Some(OsStr::new("/run/systemd/notify")));
        assert!(inherited.notify_socket.is_none());
    }

    #[test]
    fn foreground_and_no_restore_are_independent() {
        let config = DaemonConfig::load(None, &|_| None).unwrap();
        let opts = boot_options(
            &config,
            &DaemonArgs {
                foreground: true,
                ..args()
            },
            Some(OsStr::new("/run/systemd/notify")),
        );
        assert!(opts.restore, "a supervised daemon still musters its roll");
    }

    #[test]
    fn already_running_gets_its_own_exit_code_and_everything_else_is_failure() {
        use DaemonRunError::{Boot, Config, Run};
        assert_eq!(
            daemon_exit_code(&Boot(BootError::AlreadyRunning { pid: Some(7) })),
            ExitCode::DaemonAlreadyRunning
        );
        assert_eq!(
            daemon_exit_code(&Boot(BootError::AlreadyRunning { pid: None })),
            ExitCode::DaemonAlreadyRunning
        );
        assert_eq!(
            daemon_exit_code(&Boot(BootError::Io {
                path: "/x".into(),
                source: std::io::Error::other("x"),
            })),
            ExitCode::Failure
        );
        assert_eq!(
            daemon_exit_code(&Run(BootError::Io {
                path: "/x".into(),
                source: std::io::Error::other("x"),
            })),
            ExitCode::Failure
        );
        assert_eq!(
            daemon_exit_code(&Config(DaemonConfigError::Toml("expected `=`".into()))),
            ExitCode::InvalidConfig
        );
        assert_eq!(
            daemon_exit_code(&Config(DaemonConfigError::BadEnvValue(
                "SHEP_LOG_JSON",
                "maybe".into()
            ))),
            ExitCode::InvalidConfig
        );
        assert_eq!(
            daemon_exit_code(&DaemonRunError::DogMigration(
                DogMigrationError::WouldOverwrite {
                    name: "metrics".to_string(),
                    holds_env: false,
                }
            )),
            ExitCode::InvalidConfig
        );
    }

    #[test]
    fn boot_and_run_report_different_phases_for_the_same_underlying_error() {
        use DaemonRunError::{Boot, Run};
        let io_err = || BootError::Io {
            path: "/x".into(),
            source: std::io::Error::other("x"),
        };
        let boot_msg = Boot(io_err()).to_string();
        let run_msg = Run(io_err()).to_string();
        assert_ne!(boot_msg, run_msg);
        assert!(boot_msg.starts_with("the daemon failed to boot"));
        assert!(
            !run_msg.starts_with("the daemon failed to boot"),
            "a run-phase failure must not still claim to be a boot failure: {run_msg:?}"
        );
        assert!(run_msg.starts_with("the daemon failed while running"));
    }
}