shep 0.4.4

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
//! The settings screen's own reader and writer: the one place `shep.toml`'s
//! raw text meets [`DaemonConfig`]'s opinion about whether a value is legal.
//!
//! Validation lives in [`apply_setting`], the only function that puts a
//! mutated [`ShepToml`] and a real [`DaemonConfig::load`] in one place.
//!
//! [`load_settings`] reads the document, never a loaded [`DaemonConfig`]:
//! every `[daemon]` and `[whistle]` section is `#[serde(default)]`, so a
//! loaded config cannot tell a key written at its own default from a key
//! nobody wrote, which is the distinction this screen exists to show.

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

use shep_core::config::daemon::{DaemonSection, WhistleSection};
use shep_core::config::{DaemonConfig, DaemonConfigError, parse_daemon_bool};
use shep_core::values::UpDuration;

use crate::commands::shep_toml::{ShepToml, ShepTomlError};
use crate::dog::BUILT_IN_DOGS;
use crate::style::{StyleLevel, StyleSource};

// `crate::style::StyleSource` is reused for "which layer decided". Only
// `style_level` ever reads as `Flag` or `Env`: the shepherd's own env and
// flags are invisible here, so a `[daemon]` field is `Config` or `Default`.
// `Config` says the key is in the file, not that the shepherd is using it.

/// One scalar as the screen shows it
///
/// `Debug` is derived, not redacted: a rendered string and a layer name.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ScalarView {
    /// Already rendered for display, defaults resolved.
    pub value: String,
    /// Which layer this value came from.
    pub source: StyleSource,
}

/// Which scalar an edit names
///
/// `Debug` is derived, not redacted: a bare field name.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SettingField {
    /// `[daemon] log_level`.
    LogLevel,
    /// `[daemon] log_json`.
    LogJson,
    /// `[daemon] socket`.
    Socket,
    /// `[daemon] max_cron_sleep`.
    MaxCronSleep,
    /// `[whistle] allow_control`.
    AllowControl,
    /// `[style] level`.
    StyleLevel,
}

impl SettingField {
    /// The TOML key, which is also what a [`crate::lookout::field::Field::key`]
    /// carries for the same scalar.
    #[must_use]
    pub const fn key(self) -> &'static str {
        match self {
            Self::LogLevel => "log_level",
            Self::LogJson => "log_json",
            Self::Socket => "socket",
            Self::MaxCronSleep => "max_cron_sleep",
            Self::AllowControl => "allow_control",
            Self::StyleLevel => "level",
        }
    }

    /// The inverse of [`Self::key`]. `None` for a key no scalar has.
    #[must_use]
    pub fn from_key(key: &str) -> Option<Self> {
        Some(match key {
            "log_level" => Self::LogLevel,
            "log_json" => Self::LogJson,
            "socket" => Self::Socket,
            "max_cron_sleep" => Self::MaxCronSleep,
            "allow_control" => Self::AllowControl,
            "level" => Self::StyleLevel,
            _ => return None,
        })
    }
}

/// The six scalars as a [`crate::lookout::field::FieldSet`], in the order
/// the screen has always shown them, grouped by their section.
///
/// Hand-built rather than read off a schema, because `shep.toml` has none.
/// That is the point of the model: it is the common shape, not the schema.
/// The choices for `log_level` and `level` are the ladders
/// `Settings::next_candidate` already cycles: `LOG_LEVEL_ORDER` and
/// `STYLE_LEVEL_ORDER` in `lookout::app`, mapped through each enum's own
/// string form.
#[must_use]
pub fn settings_field_set() -> crate::lookout::field::FieldSet {
    use crate::lookout::app::{LOG_LEVEL_ORDER, STYLE_LEVEL_ORDER};
    use crate::lookout::field::{Field, FieldKind, FieldSet};

    let f = |field: SettingField, group: &str, kind: FieldKind| Field {
        key: field.key().to_owned(),
        help: field.key().to_owned(),
        group: Some(group.to_owned()),
        kind,
        value_kind: None,
        default: None,
        secret: false,
        editable: true,
    };
    let log_levels = FieldKind::Choice(
        LOG_LEVEL_ORDER
            .iter()
            .map(|l| l.as_str().to_owned())
            .collect(),
    );
    let style_levels =
        FieldKind::Choice(STYLE_LEVEL_ORDER.iter().map(ToString::to_string).collect());
    FieldSet::from_fields(
        vec![
            f(SettingField::LogLevel, "[daemon]", log_levels),
            f(SettingField::LogJson, "[daemon]", FieldKind::Bool),
            f(SettingField::Socket, "[daemon]", FieldKind::Text),
            f(SettingField::MaxCronSleep, "[daemon]", FieldKind::Text),
            f(SettingField::AllowControl, "[whistle]", FieldKind::Bool),
            f(SettingField::StyleLevel, "[style]", style_levels),
        ],
        &["[daemon]", "[whistle]", "[style]"],
    )
}

/// One edit, ready to apply
///
/// `Debug` is derived, not redacted: none of the six scalars this reaches
/// is a secret.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SettingEdit {
    /// Write `field` to `value`.
    Set {
        /// Which scalar.
        field: SettingField,
        /// The text as typed or chosen, unparsed until [`apply_setting`]
        /// validates it.
        value: String,
    },
    /// Remove `field`'s key, returning it to the compiled default.
    ///
    /// Only [`SettingField::Socket`] and [`SettingField::MaxCronSleep`]
    /// reach this; the other four have no unset form.
    Unset {
        /// Which scalar.
        field: SettingField,
    },
}

/// Everything the screen reads off disk in one go
///
/// `Debug` is derived, not redacted: a dog's own webhook token lives in
/// `dogs.toml`, which this type never reads.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SettingsSnapshot {
    /// `[daemon] log_level`.
    pub log_level: ScalarView,
    /// `[daemon] log_json`.
    pub log_json: ScalarView,
    /// `[daemon] socket`.
    pub socket: ScalarView,
    /// `[daemon] max_cron_sleep`.
    pub max_cron_sleep: ScalarView,
    /// `[whistle] allow_control`.
    pub allow_control: ScalarView,
    /// `[style] level`, resolved.
    pub style_level: ScalarView,
    /// What `[style] level` says in the document, or `None` when the
    /// document never wrote it.
    ///
    /// The one field needing both halves: `--style` and `$SHEP_STYLE` are
    /// lookout's own, so `style_level` is the level in force and this is
    /// the level on disk. Cycling from the resolved one would propose a
    /// no-op write under `$SHEP_STYLE=bare` over a file saying `full`.
    pub style_level_in_file: Option<String>,
    /// Every candidate dog: [`BUILT_IN_DOGS`] plus every `adopted_dogs`
    /// key, sorted, deduplicated.
    pub dogs: Vec<DogView>,
}

/// One row of the dogs table
///
/// `Debug` is derived, not redacted: a name, a bool and a binary's path.
/// The dog's own config, which can hold a secret, lives in `dogs.toml`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DogView {
    /// The dog's name.
    pub name: String,
    /// Whether `[daemon] enabled_dogs` names it.
    pub enabled: bool,
    /// `None` for a built-in dog; the adopted binary's path otherwise.
    pub adopted_path: Option<PathBuf>,
}

/// What [`apply_setting`] can fail with
///
/// `Debug` is derived, not redacted: [`Self::Config`] forwards to
/// [`ShepTomlError`]'s own redacted `Debug`, and [`Self::Invalid`] carries
/// a refusal message naming a key and a rule, never a value from the file.
#[derive(Debug)]
pub enum SettingError {
    /// [`ShepToml::try_edit`]'s setup or write failed: the lock, the read,
    /// or the rename.
    Config(ShepTomlError),
    /// [`DaemonConfig::load`] refused the document this edit would have
    /// written, or the value is not legal for its field. Carries the
    /// refusal message, so the operator is told which key and why.
    Invalid(String),
}

impl std::fmt::Display for SettingError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Config(err) => write!(f, "{err}"),
            Self::Invalid(message) => write!(f, "{message}"),
        }
    }
}

impl core::error::Error for SettingError {
    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
        match self {
            Self::Config(err) => Some(err),
            Self::Invalid(_) => None,
        }
    }
}

impl From<ShepTomlError> for SettingError {
    fn from(err: ShepTomlError) -> Self {
        Self::Config(err)
    }
}

/// Reads the snapshot, taking no lock: see [`ShepToml::read_only`]
///
/// `socket_default` is the socket this lookout is connected over, so an
/// absent `[daemon] socket` shows the live answer rather than a guess.
/// `style` is `resolve_style`'s already-resolved pair.
///
/// # Errors
/// [`ShepTomlError::Io`] if `path` exists and could not be read.
/// [`ShepTomlError::Parse`] if `path` exists and is not valid TOML.
pub fn load_settings(
    path: &Path,
    socket_default: &Path,
    style: (StyleLevel, StyleSource),
) -> Result<SettingsSnapshot, ShepTomlError> {
    let doc = ShepToml::read_only(path)?;
    let daemon_default = DaemonSection::default();
    let whistle_default = WhistleSection::default();

    let log_level = match doc.daemon_log_level() {
        Some(value) => ScalarView {
            value,
            source: StyleSource::Config,
        },
        None => ScalarView {
            value: daemon_default.log_level.as_str().to_string(),
            source: StyleSource::Default,
        },
    };
    let log_json = match doc.daemon_log_json() {
        Some(value) => ScalarView {
            value: value.to_string(),
            source: StyleSource::Config,
        },
        None => ScalarView {
            value: daemon_default.log_json.to_string(),
            source: StyleSource::Default,
        },
    };
    let socket = match doc.daemon_socket() {
        Some(value) => ScalarView {
            value: value.display().to_string(),
            source: StyleSource::Config,
        },
        None => ScalarView {
            value: socket_default.display().to_string(),
            source: StyleSource::Default,
        },
    };
    let max_cron_sleep = match doc.daemon_max_cron_sleep() {
        Some(value) => ScalarView {
            value,
            source: StyleSource::Config,
        },
        None => ScalarView {
            value: render_compiled_max_cron_sleep(daemon_default.max_cron_sleep),
            source: StyleSource::Default,
        },
    };
    let allow_control = match doc.whistle_allow_control() {
        Some(value) => ScalarView {
            value: value.to_string(),
            source: StyleSource::Config,
        },
        None => ScalarView {
            value: whistle_default.allow_control.to_string(),
            source: StyleSource::Default,
        },
    };
    let (level, source) = style;
    let style_level = ScalarView {
        value: level.to_string(),
        source,
    };
    let style_level_in_file = doc.style_level();

    Ok(SettingsSnapshot {
        log_level,
        log_json,
        socket,
        max_cron_sleep,
        allow_control,
        style_level,
        style_level_in_file,
        dogs: dog_candidates(&doc),
    })
}

/// [`DaemonSection::default`]'s own `max_cron_sleep`, rendered for the
/// screen's default row
///
/// A `None` default renders as "not set": the daemon's own fallback lives
/// in `shep-daemon` and is unreachable from here, so naming a duration
/// would be a guess.
fn render_compiled_max_cron_sleep(default: Option<UpDuration>) -> String {
    default.map_or_else(|| "not set".to_string(), |value| value.to_string())
}

/// Every candidate dog: [`BUILT_IN_DOGS`] plus every adopted name, sorted
/// and deduplicated, each paired with whether it is enabled and its path.
fn dog_candidates(doc: &ShepToml) -> Vec<DogView> {
    let enabled = doc.enabled_dog_names();
    let mut names: BTreeSet<String> = BUILT_IN_DOGS
        .iter()
        .map(|name| (*name).to_string())
        .collect();
    names.extend(doc.adopted_dog_names());
    names
        .into_iter()
        .map(|name| {
            let adopted_path = doc.adopted_dog_path(&name);
            let is_enabled = enabled.contains(&name);
            DogView {
                name,
                enabled: is_enabled,
                adopted_path,
            }
        })
        .collect()
}

/// Applies one edit under the config lock, validating before it saves
///
/// The mutated document is loaded with `&|_| None` in place of an env
/// layer: this process's environment is not the shepherd's. A loader `Err`
/// returns before [`ShepToml::try_edit`] saves, leaving the file untouched
/// down to its inode.
///
/// # Errors
/// [`SettingError::Config`] if the lock, the read or the write failed, or
/// the document holds the key as a shape the setter cannot write into.
/// [`SettingError::Invalid`] if the value is not legal for its field, or
/// [`SettingEdit::Unset`] named a field with no unset form.
pub fn apply_setting(path: &Path, edit: &SettingEdit) -> Result<(), SettingError> {
    ShepToml::try_edit(path, |doc| -> Result<(), SettingError> {
        match edit {
            SettingEdit::Set { field, value } => set_field(doc, *field, value)?,
            SettingEdit::Unset { field } => unset_field(doc, *field)?,
        }
        let rendered = doc.rendered();
        DaemonConfig::load(Some(&rendered), &|_| None)
            .map_err(|err: DaemonConfigError| SettingError::Invalid(err.to_string()))?;
        Ok(())
    })
}

/// The `Set` half of [`apply_setting`]'s match, one field per arm.
fn set_field(doc: &mut ShepToml, field: SettingField, value: &str) -> Result<(), SettingError> {
    match field {
        SettingField::LogLevel => doc.set_daemon_log_level(value)?,
        SettingField::LogJson => doc.set_daemon_log_json(parse_bool_field(value)?)?,
        SettingField::Socket => doc.set_daemon_socket(Path::new(value))?,
        SettingField::MaxCronSleep => doc.set_daemon_max_cron_sleep(value)?,
        SettingField::AllowControl => doc.set_whistle_allow_control(parse_bool_field(value)?)?,
        SettingField::StyleLevel => {
            let level = StyleLevel::parse(value).ok_or_else(|| {
                SettingError::Invalid(format!("{value} does not name a style level"))
            })?;
            doc.set_style_level(level)?;
        }
    }
    Ok(())
}

/// The `Unset` half of [`apply_setting`]'s match. Only
/// [`SettingField::Socket`] and [`SettingField::MaxCronSleep`] have an
/// unsetter; every other field refuses.
fn unset_field(doc: &mut ShepToml, field: SettingField) -> Result<(), SettingError> {
    match field {
        SettingField::Socket => doc.unset_daemon_socket(),
        SettingField::MaxCronSleep => doc.unset_daemon_max_cron_sleep(),
        _ => {
            return Err(SettingError::Invalid(
                "this field has no unset form".to_string(),
            ));
        }
    }
    Ok(())
}

/// Delegates to [`parse_daemon_bool`] so the screen's grammar and
/// `SHEP_LOG_JSON`'s cannot disagree: typing `1` here must work too.
fn parse_bool_field(value: &str) -> Result<bool, SettingError> {
    parse_daemon_bool(value)
        .ok_or_else(|| SettingError::Invalid(format!("{value} is not a valid boolean")))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::lookout::field::FieldKind;

    /// The style pair every test that does not care about `[style]` uses.
    fn style_fixture() -> (StyleLevel, StyleSource) {
        (StyleLevel::Full, StyleSource::Config)
    }

    #[test]
    fn every_setting_field_round_trips_through_its_key() {
        for field in [
            SettingField::LogLevel,
            SettingField::LogJson,
            SettingField::Socket,
            SettingField::MaxCronSleep,
            SettingField::AllowControl,
            SettingField::StyleLevel,
        ] {
            assert_eq!(SettingField::from_key(field.key()), Some(field));
        }
        assert_eq!(SettingField::from_key("no_such_key"), None);
    }

    #[test]
    fn the_settings_field_set_lists_the_six_scalars_in_the_screens_fixed_order() {
        let set = settings_field_set();
        let keys: Vec<&str> = set.fields().iter().map(|f| f.key.as_str()).collect();
        assert_eq!(
            keys,
            [
                "log_level",
                "log_json",
                "socket",
                "max_cron_sleep",
                "allow_control",
                "level"
            ]
        );
        let mut groups: Vec<&str> = Vec::new();
        for field in set.fields() {
            let group = field
                .group
                .as_deref()
                .expect("every scalar names a section");
            if groups.last() != Some(&group) {
                groups.push(group);
            }
        }
        assert_eq!(groups, ["[daemon]", "[whistle]", "[style]"]);
    }

    #[test]
    fn the_cycled_scalars_are_choices_and_the_typed_ones_are_text() {
        let set = settings_field_set();
        assert!(matches!(
            set.by_key("log_level").unwrap().kind,
            FieldKind::Choice(_)
        ));
        assert_eq!(set.by_key("log_json").unwrap().kind, FieldKind::Bool);
        assert_eq!(set.by_key("socket").unwrap().kind, FieldKind::Text);
        assert_eq!(set.by_key("max_cron_sleep").unwrap().kind, FieldKind::Text);
    }

    fn socket_default_fixture() -> PathBuf {
        PathBuf::from("/var/run/shep-settings-fixture.sock")
    }

    #[test]
    fn a_fresh_home_reads_every_scalar_as_the_default() {
        // What `scaffold_first_run_interpreters` leaves behind.
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("shep.toml");
        ShepToml::edit(&path, ShepToml::write_starter_interpreters).unwrap();

        let snap = load_settings(&path, &socket_default_fixture(), style_fixture()).unwrap();
        assert_eq!(snap.log_level.source, StyleSource::Default);
        assert_eq!(snap.log_level.value, "warn");
        assert_eq!(snap.log_json.source, StyleSource::Default);
        assert_eq!(snap.allow_control.source, StyleSource::Default);
        assert_eq!(snap.max_cron_sleep.source, StyleSource::Default);
        assert_eq!(
            snap.style_level_in_file, None,
            "a fresh home has never written [style], so the reader must say so"
        );
    }

    #[test]
    fn a_declared_scalar_reads_as_config_even_at_its_default_value() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("shep.toml");
        std::fs::write(
            &path,
            "[daemon]\nlog_level = \"warn\"\n\n[style]\nlevel = \"bare\"\n",
        )
        .unwrap();

        let snap = load_settings(&path, &socket_default_fixture(), style_fixture()).unwrap();
        assert_eq!(snap.log_level.value, "warn");
        assert_eq!(
            snap.log_level.source,
            StyleSource::Config,
            "a key written to its own default is still a key someone wrote"
        );
        assert_eq!(
            snap.style_level_in_file,
            Some("bare".to_string()),
            "load_settings must read [style] level off the real document, \
             not just carry the resolved level `style_fixture` supplies"
        );
    }

    // `.ino()` needs `std::os::unix::fs::MetadataExt`, so unix only.
    #[cfg(unix)]
    #[test]
    fn a_value_the_loader_refuses_leaves_the_file_byte_identical() {
        use std::os::unix::fs::MetadataExt as _;

        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("shep.toml");
        let before = "# mine\n[daemon]\nlog_level = \"debug\"\n";
        std::fs::write(&path, before).unwrap();
        let inode_before = std::fs::metadata(&path).unwrap().ino();

        let refusal = apply_setting(
            &path,
            &SettingEdit::Set {
                field: SettingField::MaxCronSleep,
                value: "500ms".into(),
            },
        );

        assert!(matches!(refusal, Err(SettingError::Invalid(_))));
        assert_eq!(std::fs::read_to_string(&path).unwrap(), before);
        assert_eq!(
            std::fs::metadata(&path).unwrap().ino(),
            inode_before,
            "a refusal must not stage and rename, which is what try_edit buys"
        );
    }

    #[test]
    fn the_refusal_carries_the_loaders_own_message() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("shep.toml");
        std::fs::write(&path, "").unwrap();

        let Err(SettingError::Invalid(message)) = apply_setting(
            &path,
            &SettingEdit::Set {
                field: SettingField::MaxCronSleep,
                value: "500ms".into(),
            },
        ) else {
            panic!("a value under the floor must be refused");
        };
        assert!(
            message.contains("max_cron_sleep"),
            "the operator has to be told which key: {message}"
        );
    }

    #[test]
    fn unsetting_an_optional_field_returns_it_to_the_default() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("shep.toml");
        std::fs::write(&path, "[daemon]\nmax_cron_sleep = \"30s\"\n").unwrap();

        apply_setting(
            &path,
            &SettingEdit::Unset {
                field: SettingField::MaxCronSleep,
            },
        )
        .unwrap();

        let snap = load_settings(&path, &socket_default_fixture(), style_fixture()).unwrap();
        assert_eq!(snap.max_cron_sleep.source, StyleSource::Default);
    }

    #[test]
    fn every_built_in_dog_is_a_candidate_even_when_nothing_is_enabled() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("shep.toml");
        std::fs::write(&path, "").unwrap();

        let snap = load_settings(&path, &socket_default_fixture(), style_fixture()).unwrap();
        let names: Vec<&str> = snap.dogs.iter().map(|d| d.name.as_str()).collect();
        assert_eq!(names, vec!["bark", "metrics"]);
        assert!(snap.dogs.iter().all(|d| !d.enabled));
    }

    #[test]
    fn an_adopted_dog_joins_the_candidates_and_carries_its_path() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("shep.toml");
        std::fs::write(
            &path,
            "[daemon]\nenabled_dogs = [\"otel\"]\n\n[daemon.adopted_dogs]\notel = \"/usr/local/bin/shep-otel\"\n",
        )
        .unwrap();

        let snap = load_settings(&path, &socket_default_fixture(), style_fixture()).unwrap();
        let otel = snap.dogs.iter().find(|d| d.name == "otel").unwrap();
        assert!(otel.enabled);
        assert_eq!(
            otel.adopted_path.as_deref(),
            Some(Path::new("/usr/local/bin/shep-otel"))
        );
        let metrics = snap.dogs.iter().find(|d| d.name == "metrics").unwrap();
        assert_eq!(metrics.adopted_path, None, "a built-in dog has no path");
    }
}