shep-daemon 0.25.2

The supervision engine behind shep: process spawning, restart policy, the log plane, watch and cron restarts, and the RPC server
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
//! The verb-routing `match`: one arm per [`Request`] variant, wrapped by
//! [`budget`] so no reply outlives its deadline.
//!
//! `run` is the whole dispatch table; [`dispatch`] and `with_deadline`
//! are the timeout wrapper around it.

use core::future::Future;
use core::time::Duration;

use std::collections::{BTreeMap, BTreeSet, HashSet};

use shep_core::config::{NormalizeError, ResolvedApp, normalize_all};
use shep_core::dogs::is_reserved_action;
use shep_core::protocol::{
    Envelope, PROTOCOL_VERSION, Reply, Request, Response, RpcError, RpcErrorCode, SheepApplied,
};

use crate::bus::TopicFilter;
use crate::dogs::DogSpec;
use crate::supervisor::{BatchPolicy, ConnId, SheepDogRead, SupervisorError};

use super::PtyStream;
use super::batch::{duplicate_name, persists, staged_plan};
use super::context::{Outcome, RpcContext, budget};
use super::dog_events::publish_dog_event;
use super::dog_secrets::{resolved_section, resolved_sheep_table};
#[cfg(feature = "vcs")]
use super::enrichment::with_vcs;
use super::enrichment::{
    dog_staleness, handover_refusal, with_dog_contact, with_lambs, with_live_stats,
};
use super::error::{forbidden, invalid_config, no_sheep, rpc_error};
use super::gate::{Link, check, check_launch, pin_grants};
use super::selector_verbs::{
    matching_rows, not_found, selector_call, selector_of, signal_request, trigger,
};
use super::walk::{reload_request, restart_request};

/// Dispatches one request envelope against `ctx`, returning the connection's next step.
///
/// `link` is the connection a dog or a launched sheep was spawned holding,
/// which bounds what it may send. `None` is the control socket.
///
/// The deadline [`budget`] bounds the reply, not the actor's work: a
/// `DeadlineExceeded` to `Start` does not mean nothing happened.
pub(crate) async fn dispatch(
    envelope: Envelope,
    conn: ConnId,
    link: Option<Link<'_>>,
    ctx: &RpcContext,
) -> Outcome {
    let id = envelope.id;
    let work = async {
        let mut body = envelope.body;
        let refusal = match link {
            None => None,
            Some(Link::Dog(dog)) => {
                let refusal = check(ctx, dog, &body).await.err();
                body = pin_grants(ctx, body);
                refusal
            }
            Some(Link::Launch { dog, sheep }) => check_launch(dog, sheep, &body).err(),
        };
        if let Some(err) = refusal {
            return Outcome::Reply(Reply {
                id,
                result: Err(err),
            });
        }
        run(id, conn, link, body, ctx).await
    };
    with_deadline(id, budget(envelope.deadline_ms), work).await
}

// `+ Send`: awaited inside the per-connection `tokio::spawn`, so the bound is
// stated rather than inferred.
pub(super) async fn with_deadline<F: Future<Output = Outcome> + Send>(
    id: u64,
    budget: Duration,
    work: F,
) -> Outcome {
    match tokio::time::timeout(budget, work).await {
        Ok(outcome) => outcome,
        Err(_) => Outcome::Reply(Reply {
            id,
            result: Err(RpcError {
                code: RpcErrorCode::DeadlineExceeded,
                message: format!(
                    "the request deadline of {} ms expired before the daemon finished",
                    budget.as_millis()
                ),
                daemon_version: None,
            }),
        }),
    }
}

async fn run(
    id: u64,
    conn: ConnId,
    link: Option<Link<'_>>,
    request: Request,
    ctx: &RpcContext,
) -> Outcome {
    let reply = |result| Outcome::Reply(Reply { id, result });
    match request {
        Request::Ping => reply(Ok(Response::Pong)),
        // One of the two verbs that pays for a live reading; `with_live_stats`
        // says why every lifecycle verb below goes without.
        Request::ListFlock => match ctx.supervisor.list_checked().await {
            Ok(infos) => reply(Ok(Response::Flock(with_dog_contact(
                &ctx.dog_refusals,
                with_live_stats(&ctx.stats, infos).await,
            )))),
            Err(err) => reply(Err(rpc_error(&err))),
        },
        // Free, unlike the two below it: the reading was taken on this
        // daemon's own tick and this arm hands back what is already in
        // memory. Sampling here would divide a near-zero delta by a
        // near-zero window; `crate::host` is the argument.
        Request::HostUsage => reply(Ok(Response::HostUsage(ctx.host.latest()))),
        // The other one. Sampled after the selector has narrowed the
        // listing, so the join below runs over the matched rows alone.
        Request::Describe { selector } => match selector_of(selector) {
            Err(err) => reply(Err(err)),
            Ok(selector) => match ctx.supervisor.list_checked().await {
                Err(err) => reply(Err(rpc_error(&err))),
                Ok(infos) => {
                    let hits = matching_rows(infos, &selector);
                    if hits.is_empty() {
                        reply(Err(not_found()))
                    } else {
                        let hits = with_live_stats(&ctx.stats, hits).await;
                        let hits = with_lambs(&ctx.stats, hits).await;
                        #[cfg(feature = "vcs")]
                        let hits = with_vcs(&ctx.supervisor, hits).await;
                        reply(Ok(Response::Described(with_dog_contact(
                            &ctx.dog_refusals,
                            hits,
                        ))))
                    }
                }
            },
        },
        // Peer input is untrusted: re-normalize before anything is registered.
        //
        // `AllOrNothing` no longer means the whole request is atomic: a refusal
        // in stage 1 leaves stage 0 running and nothing rolls it back.
        Request::Start { apps } => match normalize_all(apps) {
            Err(err) => reply(Err(invalid_config(err))),
            Ok(resolved) => match staged_plan(ctx, &resolved) {
                Err(err) => reply(Err(err)),
                Ok(plan) => {
                    ctx.registry.record(&resolved);
                    match crate::boot_order::start_in_stages(
                        &plan,
                        &resolved,
                        &ctx.supervisor,
                        &ctx.events,
                        BatchPolicy::AllOrNothing,
                        None,
                    )
                    .await
                    {
                        Ok(infos) => reply(Ok(Response::Started(infos))),
                        Err(err) => reply(Err(rpc_error(&err))),
                    }
                }
            },
        },
        // The membership half of `Start` with none of the spawning, and the
        // same untrusted-peer rule. Recorded in the registry as `Start` is:
        // an added app is a flock member that happens to be stopped, so a
        // `shep save` after a `shep add` has to write it.
        Request::Add { apps } => match normalize_all(apps) {
            Err(err) => reply(Err(invalid_config(err))),
            Ok(resolved) => match staged_plan(ctx, &resolved) {
                Err(err) => reply(Err(err)),
                Ok(_) => {
                    ctx.registry.record(&resolved);
                    match ctx
                        .supervisor
                        .register_at_rest(resolved, BTreeSet::new())
                        .await
                    {
                        Ok(infos) => reply(Ok(Response::Added(infos))),
                        Err(err) => reply(Err(rpc_error(&err))),
                    }
                }
            },
        },
        // Re-normalized for the reason `Start` is, plus one of its own: an
        // unnormalized config would report every default it did not spell out
        // as a difference. Nothing is recorded, since this answers a question
        // and must not change what the next `shep save` writes.
        Request::ConfigDrift { apps } => match normalize_all(apps) {
            Err(err) => reply(Err(invalid_config(err))),
            Ok(resolved) => match ctx.supervisor.config_drift(resolved).await {
                Ok(drifted) => reply(Ok(Response::Drifted(drifted))),
                Err(err) => reply(Err(rpc_error(&err))),
            },
        },
        Request::Stop { selector } => {
            selector_call(id, selector, |s| ctx.supervisor.stop(s), Response::Stopped).await
        }
        Request::Disable { selector } => {
            let outcome = selector_call(
                id,
                selector,
                |s| ctx.supervisor.disable(s),
                Response::Disabled,
            )
            .await;
            // The mark is part of the roll and moves no process on an app
            // that is already stopped, so the bus cannot be what wakes the
            // writer.
            ctx.registry.touch();
            outcome
        }
        Request::Enable { selector } => {
            let outcome = selector_call(
                id,
                selector,
                |s| ctx.supervisor.enable(s),
                Response::Enabled,
            )
            .await;
            ctx.registry.touch();
            outcome
        }
        // Forward, dependencies first, when the selector matches more than
        // one sheep. Not reverse-stop then forward-start: the rolling version
        // puts the whole fold down at once in the middle, and forward-only
        // never does.
        Request::Restart { selector } => restart_request(id, selector, ctx).await,
        // Staged like `Restart` above and for its reason. Which of the two
        // reloads an app gets is still `ReloadMode::of`'s call: ordering
        // decides when a stage begins and nothing about the swap inside it.
        // A walk of several stages holds the reply until the swaps it waits on land.
        Request::Reload { selector } => reload_request(id, selector, ctx).await,
        Request::Reopen { selector } => {
            selector_call(
                id,
                selector,
                |s| ctx.supervisor.reopen(s),
                Response::Reopened,
            )
            .await
        }
        Request::Flush { selector } => {
            selector_call(id, selector, |s| ctx.supervisor.flush(s), Response::Flushed).await
        }
        Request::Reset { selector } => {
            selector_call(id, selector, |s| ctx.supervisor.reset(s), Response::Reset).await
        }
        Request::TailLog {
            id: sheep,
            stream,
            lines,
        } => reply(super::log_tail::answer(sheep, stream, lines, ctx).await),
        Request::PublishEvent { event, payload } => {
            reply(publish_dog_event(link, &event, payload, ctx))
        }
        Request::Trigger {
            selector,
            action,
            params,
        } => {
            // Named only from a dog's own connection: the shepherd vouches
            // for the name, since the connection is the dog's identity.
            let caller = match link {
                Some(Link::Dog(dog)) => {
                    // A dog may not send one of these: a `shep.validate` from
                    // a dog reads to the callee as the operator's own settings
                    // ask, and a `shep.pane` as lookout asking.
                    if is_reserved_action(&action) {
                        return reply(Err(forbidden(format!(
                            "dog `{dog}` may not trigger `{action}`: a `shep.` action is one \
                             shep sends itself, as the operator"
                        ))));
                    }
                    Some(dog.to_owned())
                }
                // The control socket acts as the operator, and the operator is
                // who sends these names.
                Some(Link::Launch { .. }) | None => None,
            };
            trigger(id, selector, action, params, caller, ctx).await
        }
        Request::Signal {
            selector,
            signal,
            lamb,
        } => signal_request(id, selector, signal, lamb, ctx).await,
        Request::SendLine { selector, line } => {
            // Refused here, not silently split by the writer: a line
            // carrying a newline would be delivered as two commands where the
            // operator typed one. `\r` too, since CRLF reaches a shell as a
            // command with a stray carriage return in it.
            if line.contains(['\n', '\r']) {
                return reply(Err(invalid_config(
                    "a line may not contain a newline or a carriage return; \
                     send one line per request",
                )));
            }
            match selector_of(selector) {
                Ok(selector) => match ctx.supervisor.send_line(selector, line).await {
                    Ok(rows) => reply(Ok(Response::SentLine(rows))),
                    Err(err) => reply(Err(rpc_error(&err))),
                },
                Err(err) => reply(Err(err)),
            }
        }
        Request::Delete { selector } => match selector_of(selector) {
            Err(err) => reply(Err(err)),
            Ok(selector) => match ctx.supervisor.delete(selector).await {
                Ok(ids) => reply(Ok(Response::Deleted(ids))),
                Err(err) => reply(Err(rpc_error(&err))),
            },
        },
        Request::Scale { name, count } => match ctx.supervisor.scale(&name, count).await {
            Ok(scaled) => {
                // Recorded unconditionally: without it `shep stock web 4`
                // then `shep save` writes `instances = 2` and the next reboot
                // undoes the scale. Unconditionally, since a partial scale-up
                // leaves real instances the roll has to know about too.
                let achieved = scaled.achieved();
                let requested = scaled.requested;
                ctx.registry.record(&[scaled.app]);
                match scaled.shortfall {
                    None => reply(Ok(Response::Scaled(scaled.instances))),
                    // Non-zero exit: the operator asked for four and has
                    // three. The sentence names both numbers, so a reader can
                    // tell a scale that achieved nothing from one that nearly
                    // finished.
                    Some(message) => reply(Err(RpcError {
                        code: RpcErrorCode::SpawnFailed,
                        message: format!(
                            "scaled {name} to {achieved} of {requested} requested; \
                             the next instance would not spawn: {message}"
                        ),
                        daemon_version: None,
                    })),
                }
            }
            Err(err) => reply(Err(rpc_error(&err))),
        },
        // Scoped to `conn`, which is what makes a smit ephemeral: the
        // connection layer forgets this one's marks in its own tail. `smit`
        // arrives already validated by `Smit`'s hand-written `Deserialize`,
        // so the only refusal left here is a name nothing holds.
        Request::SetSmit { sheep, smit } => {
            match ctx.supervisor.set_smit(conn, &sheep, smit).await {
                Ok(infos) => reply(Ok(Response::SmitPainted(infos))),
                Err(err) => reply(Err(rpc_error(&err))),
            }
        }
        Request::SaveRoll => match ctx.save_roll_now().await {
            Ok(Some(saved)) => reply(Ok(Response::RollSaved {
                // Lossy, as `to_info` treats log paths: a non-UTF-8 roll
                // path degrades one field rather than the whole reply.
                path: saved.path.to_string_lossy().into_owned(),
                apps: saved.apps,
            })),
            Ok(None) => reply(Err(RpcError {
                code: RpcErrorCode::Internal,
                message: "the supervisor engine has stopped; no roll was written".to_string(),
                daemon_version: None,
            })),
            Err(err) => reply(Err(RpcError {
                code: RpcErrorCode::Internal,
                message: err.to_string(),
                daemon_version: None,
            })),
        },
        // The same restore `boot` runs, called the same way
        // (`crate::snapshot::muster`).
        Request::Muster => {
            match crate::snapshot::muster(
                &ctx.snapshot_path,
                &ctx.registry,
                &ctx.supervisor,
                &ctx.events,
                &ctx.dog_names,
                &ctx.boot_first_dogs,
                None,
            )
            .await
            {
                Err(err) => reply(Err(RpcError {
                    code: RpcErrorCode::Internal,
                    message: err.to_string(),
                    daemon_version: None,
                })),
                Ok(names) => {
                    // One pass to build the set, one lookup per row:
                    // `contains` on the vec is flock times restored
                    // string comparisons on every Muster.
                    let restored: HashSet<&str> = names.iter().map(String::as_str).collect();
                    match ctx.supervisor.list_checked().await {
                        Err(err) => reply(Err(rpc_error(&err))),
                        // Every sheep of every app the roll restored, not only
                        // the ones this call spawned (`Response::Mustered`).
                        Ok(infos) => reply(Ok(Response::Mustered(
                            infos
                                .into_iter()
                                .filter(|info| restored.contains(info.name.as_str()))
                                .collect(),
                        ))),
                    }
                }
            }
        }
        // Re-read per request, never cached: `shep disable X && shep enable
        // X` bounces a dog to reload its configuration, and a copy taken at
        // boot would answer with the section as it was. A dog subscribed to
        // `config.dog.<name>` reaches this same arm without going down.
        Request::DogConfig { name } => match crate::dogs::dog_section(&ctx.dogs_config, &name) {
            Ok(toml) => reply(Ok(Response::DogSection { toml: toml.into() })),
            Err(err) => reply(Err(invalid_config(err))),
        },
        Request::DogConfigResolved { name } => match resolved_section(ctx, &name) {
            Ok(toml) => reply(Ok(Response::DogSection { toml })),
            Err(err) => reply(Err(err)),
        },
        Request::SheepDogSettingsResolved { name, dog } => {
            match ctx
                .supervisor
                .sheep_dog_read(name.clone(), dog.clone())
                .await
            {
                Ok(Some(SheepDogRead {
                    table: Some(table),
                    environment,
                })) => match resolved_sheep_table(ctx, &name, &dog, &environment, &table) {
                    Ok(table) => reply(Ok(Response::SheepDogTable { table: Some(table) })),
                    Err(err) => reply(Err(err)),
                },
                Ok(Some(SheepDogRead { table: None, .. })) => {
                    reply(Ok(Response::SheepDogTable { table: None }))
                }
                Ok(None) => reply(Err(no_sheep(&name))),
                Err(err) => reply(Err(rpc_error(&err))),
            }
        }
        Request::EnableDog { name, source, env } => {
            let spec = DogSpec {
                name,
                source,
                env: env
                    .into_iter()
                    .map(|(key, value)| (key, value.into_string()))
                    .collect(),
            };
            let grants = spec.source.grants().cloned();
            let events = spec.source.events().to_vec();
            match crate::dogs::dog_app(&spec, &ctx.paths) {
                Err(err) => reply(Err(invalid_config(err))),
                Ok(app) => {
                    // Read before `start_dog` takes the app. An operator
                    // reading the dog's log during an upgrade is usually
                    // asking which file the spawn resolved to.
                    let script = app.config().script.clone();
                    // Recorded before the start is queued, not after it
                    // answers. The supervisor starts the dog whether or not
                    // this dispatch outlives its deadline, and a dog with no
                    // entry is undeclared, with full access.
                    let held = ctx.known_dogs.replace(&spec.name, grants, events);
                    match ctx.supervisor.start_dog(app, spec.source).await {
                        // `start_dog` is idempotent by name for anything not
                        // at rest, so what comes back is whatever already
                        // holds it. An unmarked entry means a sheep holds it:
                        // nothing was spawned, so the refusal has nothing to undo.
                        Ok(info) if info.dog.is_none() => {
                            ctx.known_dogs.restore(&spec.name, held);
                            reply(Err(invalid_config(format!(
                                "a sheep is already registered as `{}`; rename it or give the dog another name",
                                spec.name
                            ))))
                        }
                        Ok(info) => {
                            // The one place this daemon learns of a dog it was
                            // not told about at boot. `shep adopt` and
                            // `shep enable` both arrive here, and both have
                            // just written the name into `shep.toml`.
                            crate::dogs::narrate(
                                &ctx.events,
                                &info,
                                &format!(
                                    "shep has this dog enabled, running the binary at {script}"
                                ),
                            )
                            .await;
                            reply(Ok(Response::DogStarted(info)))
                        }
                        // A spawn that fails still registers the dog, as
                        // `Errored`, and a restart or the restart policy
                        // brings it up: its grants stay recorded, or its link
                        // would find none and run unchecked.
                        Err(err) => {
                            if !matches!(err, SupervisorError::SpawnFailed(_)) {
                                ctx.known_dogs.restore(&spec.name, held);
                            }
                            reply(Err(rpc_error(&err)))
                        }
                    }
                }
            }
        }
        // Stops the dog and leaves it registered, marked disabled, so the
        // flock still lists it. Answers `Deleted` all the same: it is the
        // only reply an older CLI accepts for this request.
        Request::DisableDog { name } => match ctx.supervisor.disable_dog(name).await {
            Ok(ids) => reply(Ok(Response::Deleted(ids))),
            Err(err) => reply(Err(rpc_error(&err))),
        },
        Request::Subscribe { topics } => match TopicFilter::new(&topics) {
            Ok(filter) => Outcome::Subscribe {
                reply: Reply {
                    id,
                    result: Ok(Response::Subscribed),
                },
                filter,
            },
            Err(err) => reply(Err(invalid_config(err))),
        },
        // The shepherd subscribes, then resizes the same terminal, so the
        // redraw is heard and both name one instance.
        Request::Attach { name, rows, cols } => {
            match ctx.supervisor.pty_attach(name.clone(), rows, cols).await {
                Ok(attached) => Outcome::Attach {
                    reply: Reply {
                        id,
                        result: Ok(Response::Attached {
                            id: attached.id,
                            name: name.clone(),
                        }),
                    },
                    output: PtyStream::new(name, attached.output),
                },
                Err(err) => reply(Err(rpc_error(&err))),
            }
        }
        // Answered with `Attached`, the one reply that names an instance:
        // the wire has no bare acknowledgement.
        Request::PtyInput { name, data } => {
            match ctx.supervisor.pty_input(name.clone(), data).await {
                Ok(id) => reply(Ok(Response::Attached { id, name })),
                Err(err) => reply(Err(rpc_error(&err))),
            }
        }
        Request::PtyResize { name, rows, cols } => {
            match ctx.supervisor.pty_resize(name.clone(), rows, cols).await {
                Ok(id) => reply(Ok(Response::Attached { id, name })),
                Err(err) => reply(Err(rpc_error(&err))),
            }
        }
        Request::DogStaleness => {
            let (stale, pending) = dog_staleness(ctx).await;
            reply(Ok(Response::DogStaleness { stale, pending }))
        }
        Request::HandoverFitness => reply(Ok(Response::HandoverFitness {
            refusal: handover_refusal(ctx).await,
        })),
        Request::KillDaemon => Outcome::Shutdown(Reply {
            id,
            result: Ok(Response::ShuttingDown),
        }),
        // The acting half of `ConfigDrift` above, and the one arm here that
        // changes a running flock's config without replacing anything.
        Request::ApplyConfig { apps, reset } => match duplicate_name(&apps) {
            Some(name) => reply(Err(invalid_config(NormalizeError::DuplicateName(name)))),
            None => match ctx.supervisor.apply_config(apps, reset).await {
                Ok(applied) => {
                    // Recorded unconditionally, as the `Scale` arm above is:
                    // an apply that reached the stored spec must reach the
                    // roll too. An app whose merge produced no honest config
                    // carries `None` and is skipped rather than invented.
                    let recorded: Vec<ResolvedApp> =
                        applied.iter().filter_map(|a| a.app.clone()).collect();
                    ctx.registry.record(&recorded);
                    reply(Ok(Response::Applied(
                        applied.into_iter().map(SheepApplied::from).collect(),
                    )))
                }
                Err(err) => reply(Err(rpc_error(&err))),
            },
        },
        // The two config-pane reads and writes. Neither takes a selector:
        // a pane edits one sheep, so an unknown name is `NotFound` here
        // rather than an empty match.
        Request::SheepConfig { name } => match ctx.supervisor.sheep_config(&name).await {
            Ok(Some(view)) => reply(Ok(Response::SheepConfig(Box::new(view)))),
            Ok(None) => reply(Err(no_sheep(&name))),
            Err(err) => reply(Err(rpc_error(&err))),
        },
        Request::SetSheepEnv { name, key, value } => {
            match ctx.supervisor.set_sheep_env(&name, &key, value).await {
                // Recorded exactly as `Start`, `Add`, `Scale` and
                // `ApplyConfig` record theirs, and for the reason `Scale`'s
                // arm gives: the muster roll is written from the registry and
                // nothing on the restore path reads the override store.
                Ok(Some(app)) => {
                    ctx.registry.record(&[app]);
                    reply(Ok(Response::SheepEnvSet { name, key }))
                }
                Ok(None) => reply(Err(no_sheep(&name))),
                Err(err) => reply(Err(rpc_error(&err))),
            }
        }
        Request::SetSheepEnvBatch {
            name,
            entries,
            force,
            dry_run,
        } => {
            let values: BTreeMap<String, String> = entries
                .iter()
                .map(|(key, value)| (key.clone(), value.as_str().to_string()))
                .collect();
            match ctx
                .supervisor
                .set_sheep_env_batch(&name, values, force, dry_run)
                .await
            {
                // Recorded for `SetSheepEnv`'s reason: the muster roll is
                // written from the registry and nothing on the restore path
                // reads the override store. `app` is `None` for a dry run,
                // for a refused collision, and for a batch that wrote nothing.
                Ok(Some(batch)) => {
                    if let Some(app) = batch.app {
                        ctx.registry.record(&[app]);
                    }
                    reply(Ok(Response::SheepEnvBatch {
                        name,
                        set: batch.set,
                        unchanged: batch.unchanged,
                        collisions: batch.collisions,
                    }))
                }
                Ok(None) => reply(Err(no_sheep(&name))),
                Err(err) => reply(Err(rpc_error(&err))),
            }
        }
        Request::CopySheepEnv {
            from,
            to,
            replace,
            except,
            dry_run,
            expect,
        } => match ctx
            .supervisor
            .copy_sheep_env(&from, &to, replace, except, dry_run, expect)
            .await
        {
            // Recorded for `SetSheepEnv`'s reason. `app` is `None` for a dry
            // run and for a copy with nothing to change.
            Ok(copy) => {
                if let Some(app) = copy.app {
                    ctx.registry.record(&[app]);
                }
                reply(Ok(Response::SheepEnvCopied {
                    from,
                    to,
                    changes: copy.changes,
                }))
            }
            Err(err) => reply(Err(rpc_error(&err))),
        },
        Request::SetSheepField { name, key, value } => {
            match ctx.supervisor.set_sheep_field(&name, &key, value).await {
                // Recorded exactly as `SetSheepEnv` records its own, and for
                // that arm's reason: the muster roll is written from the
                // registry and nothing on the restore path reads the override
                // store, so a field edit that skipped this would vanish on a cold restart.
                Ok(Some(set)) => {
                    let pending = set.pending;
                    let warning = set.warning;
                    ctx.registry.record(&[set.app]);
                    reply(Ok(Response::SheepFieldSet {
                        name,
                        key,
                        pending,
                        warning,
                    }))
                }
                Ok(None) => reply(Err(no_sheep(&name))),
                Err(err) => reply(Err(rpc_error(&err))),
            }
        }
        Request::ResetSheepField { name, key } => {
            match ctx.supervisor.reset_sheep_field(&name, &key).await {
                // Recorded for `SetSheepField`'s reason: nothing on the
                // restore path reads the override store.
                Ok(Some(set)) => {
                    let (pending, warning, value) = (set.pending, set.warning, set.value);
                    ctx.registry.record(&[set.app]);
                    reply(Ok(Response::SheepFieldReset {
                        name,
                        key,
                        value,
                        pending,
                        warning,
                    }))
                }
                Ok(None) => reply(Err(no_sheep(&name))),
                Err(err) => reply(Err(rpc_error(&err))),
            }
        }
        Request::DogSheepSettings { dog } => match ctx.supervisor.dog_sheep_settings(dog).await {
            Ok(tables) => reply(Ok(Response::DogSheepSettings { tables })),
            Err(err) => reply(Err(rpc_error(&err))),
        },
        Request::SetSheepDogSettings { name, dog, table } => {
            match ctx
                .supervisor
                .set_sheep_dog_settings(name.clone(), dog.clone(), table)
                .await
            {
                // Recorded for `SetSheepField`'s reason: nothing on the
                // restore path reads the override store.
                Ok(Some(set)) => {
                    ctx.registry.record(&[set.app]);
                    reply(Ok(Response::SheepDogSettingsSet { name, dog }))
                }
                Ok(None) => reply(Err(no_sheep(&name))),
                Err(err) => reply(Err(rpc_error(&err))),
            }
        }
        // The inverse of every other config door's guard: `dogs.toml` holds
        // dogs' sections and nothing else, so what this one refuses is a
        // sheep's name. Guarded on `known_dogs`, not on the running flock: a
        // guard on the flock would refuse the dog most in need of configuring.
        Request::SetDogConfig { name, toml } => {
            // A stopped engine runs no dogs, so "not running" is the honest
            // answer and `known_dogs` is left carrying the guard alone.
            let running_dog = || async {
                ctx.supervisor
                    .list_checked()
                    .await
                    .unwrap_or_default()
                    .iter()
                    .any(|info| info.name == name && info.dog.is_some())
            };
            if !ctx.known_dogs.contains(&name) && !running_dog().await {
                return reply(Err(RpcError {
                    code: RpcErrorCode::NotFound,
                    message: format!(
                        "no dog named {name}; `shep adopt` or `shep enable` makes one known \
                         to this shepherd"
                    ),
                    daemon_version: None,
                }));
            }
            match crate::dogs::set_dog_section(&ctx.dogs_config, &name, toml.as_str()) {
                Ok(()) => {
                    crate::bus::publish_dog_config_changed(
                        &ctx.events,
                        std::slice::from_ref(&name),
                    );
                    reply(Ok(Response::DogConfigSet { name }))
                }
                Err(err) => reply(Err(invalid_config(err))),
            }
        }
        // A provider dog's push. Unguarded by design, for the reason the
        // variant's own doc gives. Both NAMES and every entry KEY are checked
        // against the store's own grammar: one outside it is a name no
        // `{{secret:...}}` reference could reach. Values are capped too.
        Request::PutSecrets {
            namespace,
            environment,
            entries,
        } => {
            let refused = [
                ("namespace", namespace.as_str()),
                ("environment", environment.as_str()),
            ]
            .into_iter()
            .chain(entries.keys().map(|key| ("key", key.as_str())))
            .find(|(_, value)| !shep_core::secrets::is_name(value));
            if let Some((field, value)) = refused {
                return reply(Err(invalid_config(format!(
                    "`{value}` is not a valid {field}: a name is 1 to \
                     {max} bytes of `[A-Za-z0-9._-]` and may not start with `.`",
                    max = shep_core::secrets::MAX_KEY_BYTES
                ))));
            }
            // The key, never the value: an error message is the one place a
            // pushed value must not turn up (IR-41).
            let oversized = entries
                .iter()
                .map(|(key, value)| (key, value.as_str().len()))
                .find(|(_, len)| *len > shep_core::secrets::MAX_VALUE_BYTES);
            if let Some((key, len)) = oversized {
                return reply(Err(invalid_config(format!(
                    "the value for `{key}` is {len} bytes, over the {max}-byte limit",
                    max = shep_core::secrets::MAX_VALUE_BYTES
                ))));
            }
            // The entries arrive owned, so the values map takes the
            // `String` out of each rather than copying what `as_str`
            // borrows.
            let values = entries
                .into_iter()
                .map(|(key, value)| (key, value.into_string()))
                .collect();
            // Asked before the push so a namespace nobody names costs one
            // file read and nothing else.
            let named = crate::dogs::dogs_referencing(&ctx.dogs_config, Some(&namespace));
            let pushed = ctx.provider_secrets.put(
                &ctx.host_environment,
                &namespace,
                &environment,
                values,
                persists(&ctx.dogs_config, &namespace),
            );
            let (changed, cache) = match pushed {
                Ok(pushed) => (pushed.changed, Ok(pushed.accepted)),
                Err(failed) => (failed.changed, Err(failed.source)),
            };
            // Before the cache result is looked at: the values are live in
            // memory either way, and a dog told nothing keeps the secret
            // that was just rotated away.
            let affected: Vec<String> = named
                .into_iter()
                .filter(|(_, keys)| !keys.is_disjoint(&changed))
                .map(|(dog, _)| dog)
                .collect();
            crate::bus::publish_dog_config_changed(&ctx.events, &affected);
            match cache {
                Ok(accepted) => reply(Ok(Response::SecretsPut { accepted })),
                // The values are already in memory and already resolvable;
                // what failed is only their surviving a restart. Reported
                // rather than swallowed, so a dog whose operator asked for
                // a cache learns it is not getting one.
                Err(err) => reply(Err(RpcError {
                    code: RpcErrorCode::Internal,
                    message: format!(
                        "{namespace}/{environment} is stored, but the cache could not be \
                         written: {err}"
                    ),
                    daemon_version: None,
                })),
            }
        }
        // The catch-all `#[serde(other)]` lands on the wire, not a panic: a
        // client newer than this daemon gets a named refusal instead of a
        // dropped connection. `daemon_version` stays `None` here, since this
        // reply follows a handshake that already delivered it.
        Request::Unrecognized => reply(Err(RpcError {
            code: RpcErrorCode::Unsupported,
            message: format!(
                "this shepherd speaks protocol {PROTOCOL_VERSION} and does not \
                 implement the request the client sent"
            ),
            daemon_version: None,
        })),
        // A `Request` variant this crate added but this match forgot to wire
        // up: `Request::Unrecognized` above already answers a verb this
        // daemon has never heard of, so reaching this arm is our own bug,
        // not a hostile or newer client (IR-47).
        _ => reply(Err(RpcError {
            code: RpcErrorCode::Internal,
            message: "this daemon does not implement that request".to_string(),
            daemon_version: None,
        })),
    }
}