shep-daemon 0.22.0

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
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
//! [`TokioRunner`] and [`TokioProc`]: [`crate::runner::ProcessRunner`] and
//! [`crate::runner::RunningProcess`] over real child processes.
//!
//! A spawn puts the child in its own process group, so
//! [`RunningProcess::signal`] and [`RunningProcess::kill_tree`] reach the
//! whole group without touching the daemon's own. A sandboxed sheep's
//! `signal` is the exception: it reaches the leader alone
//! ([`SpawnSpec::leader_only_stop`]). It optionally wires an
//! fd-3 socketpair as the shepherd channel and hands it to
//! [`super::pump::spawn_channel_pumps`].

use std::fs;
use std::io;
#[cfg(unix)]
use std::os::fd::{AsRawFd, OwnedFd, RawFd};
#[cfg(unix)]
use std::os::unix::process::ExitStatusExt as _;
use std::path::Path;
use std::process::Stdio;
#[cfg(unix)]
use std::sync::Arc;
use std::sync::{Mutex, PoisonError};

#[cfg(unix)]
use command_fds::{CommandFdExt, FdMapping};
#[cfg(unix)]
use nix::sys::signal::{self, Signal};
#[cfg(unix)]
use nix::unistd::Pid;
use shep_core::signals::OperatorSignal;
#[cfg(unix)]
use tokio::net::UnixStream;
use tokio::process::{Child, Command};
use tokio::sync::mpsc;

use crate::channel::CHANNEL_VERSION;
#[cfg(unix)]
use crate::runner::{AdoptSpec, AdoptedReaper};
use crate::runner::{
    DogLink, ExitOutcome, Preflight, ProcIo, ProcessRunner, RunnerError, RunningProcess, SpawnSpec,
    StopSignal,
};
#[cfg(windows)]
use shep_core::dogs::DOG_LINK_PIPE_VAR;
#[cfg(unix)]
use shep_core::dogs::{DOG_LINK_FD, DOG_LINK_FD_VAR};

use super::CHANNEL_CAPACITY;
#[cfg(unix)]
use super::dog_link;
#[cfg(unix)]
use super::log_file::carried_sink;
use super::log_file::{LogSink, PipeFds};
use super::pump::{spawn_channel_pumps, spawn_log_pump, spawn_stdin_pump};
#[cfg(windows)]
use super::windows_pipe;

/// Real [`crate::runner::ProcessRunner`] over actual OS processes.
#[derive(Debug)]
pub struct TokioRunner {
    /// Where each dog's connection goes once its child has a pid.
    links: mpsc::UnboundedSender<DogLink>,
    /// The other end of `links`, until [`ProcessRunner::dog_links`] takes it.
    links_rx: Mutex<Option<mpsc::UnboundedReceiver<DogLink>>>,
}

impl Default for TokioRunner {
    fn default() -> Self {
        Self::new()
    }
}

/// The exit code [`TokioProc::kill_tree`] terminates a job with.
///
/// Windows exits carry no signal number, so this is all a reader of
/// `ProcessInfo::last_exit` sees for a sheep the daemon killed. `137` is
/// `128 + 9`, what `commands::reap::classify` reads on unix for "killed by
/// SIGKILL".
#[cfg(windows)]
const KILL_TREE_EXIT_CODE: u32 = 137;

impl TokioRunner {
    /// Builds a runner that spawns real OS child processes.
    #[must_use]
    pub fn new() -> Self {
        let (links, links_rx) = mpsc::unbounded_channel();
        Self {
            links,
            links_rx: Mutex::new(Some(links_rx)),
        }
    }
}

/// A live real OS child, produced by [`TokioRunner`]'s
/// [`crate::runner::ProcessRunner::spawn`].
#[derive(Debug)]
pub struct TokioProc {
    /// Captured at spawn: `Child::id` reports `None` once the child has been
    /// waited, and a kill ladder may still need the pid then. It is also the
    /// whole of an adopted sheep's identity.
    pid: u32,
    proc: Supervised,
    /// Stop signals go to `pid` alone, as [`SpawnSpec::leader_only_stop`]
    /// says. Windows refuses every stop signal, so only unix reads this.
    #[cfg(unix)]
    leader_only_stop: bool,
    /// The job object this sheep and everything it spawns belong to: Windows'
    /// stand-in for the unix process group, and what
    /// [`RunningProcess::kill_tree`] terminates.
    ///
    /// Held for the proc's whole life: the handle is the group, so dropping it
    /// leaves nothing to address the tree by.
    #[cfg(windows)]
    job: shep_tree::job::Job,
}

/// Where this proc's exit comes from: tokio, or a targeted `waitpid`.
///
/// An adopted sheep crossed an `execve` into a successor that has no `Child`
/// for it and no way to make one, so [`AdoptedReaper`] collects its exit.
/// Only the wait differs: `signal`, `signal_process` and `kill_tree` all
/// address the pid.
#[derive(Debug)]
enum Supervised {
    /// Started by this daemon, and waited by tokio.
    Spawned(Child),
    /// Inherited across a handover, and waited by the successor's reaper.
    #[cfg(unix)]
    Adopted(Arc<AdoptedReaper>),
}

impl RunningProcess for TokioProc {
    fn pid(&self) -> u32 {
        self.pid
    }

    async fn wait(&mut self) -> ExitOutcome {
        let child = match &mut self.proc {
            Supervised::Spawned(child) => child,
            // Cancel-safe: the reaper remembers and replays a status it has
            // taken. Its error means something else reaped the pid, which
            // lands on the same degenerate outcome as the arm below.
            #[cfg(unix)]
            Supervised::Adopted(reaper) => {
                return match reaper.wait(self.pid).await {
                    Ok(outcome) => outcome,
                    Err(error) => {
                        tracing::error!(pid = self.pid, %error, "adopted process wait failed");
                        ExitOutcome {
                            code: None,
                            signal: None,
                        }
                    }
                };
            }
        };
        // Cancel-safe: `Child::wait` replays its cached result rather than
        // restarting.
        match child.wait().await {
            Ok(status) => ExitOutcome {
                code: status.code(),
                // Nothing kills a Windows process by signal, so there is no
                // number for an exit to carry; see `KILL_TREE_EXIT_CODE`.
                #[cfg(windows)]
                signal: None,
                #[cfg(unix)]
                signal: status.signal(),
            },
            Err(error) => {
                // The `wait4()` itself failed, e.g. something else reaped the
                // pid. `wait` has no error variant, so report a terminal one.
                tracing::error!(pid = self.pid, %error, "process wait() failed");
                ExitOutcome {
                    code: None,
                    signal: None,
                }
            }
        }
    }

    #[cfg(unix)]
    fn signal(&mut self, sig: StopSignal) -> Result<(), RunnerError> {
        if self.leader_only_stop {
            return signal_leader(self.pid, to_nix_signal(sig));
        }
        signal_group(self.pid, to_nix_signal(sig))
    }

    /// Refuses every signal: Windows has no way to deliver anything
    /// SIGTERM-shaped to an arbitrary process.
    ///
    /// `GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, group)` reaches only console
    /// processes sharing a console with the caller, and a detached shepherd
    /// shares one with nothing. An `Ok(())` would tell the ladder a polite stop
    /// was delivered. An app on the shepherd channel never reaches this.
    #[cfg(windows)]
    fn signal(&mut self, sig: StopSignal) -> Result<(), RunnerError> {
        Err(RunnerError::SignalFailed(format!(
            "Windows cannot deliver {sig:?} to another process; \
             an app that needs a graceful stop must opt into the shepherd \
             channel (shutdown_with_message), otherwise the stop escalates \
             to a forced termination after kill_timeout"
        )))
    }

    #[cfg(unix)]
    fn kill_tree(&mut self) -> Result<(), RunnerError> {
        signal_group(self.pid, Signal::SIGKILL)
    }

    /// Terminates the sheep's whole job: every process it spawned, however
    /// deeply nested.
    ///
    /// Stronger than the unix rung, which a grandchild escapes by calling
    /// `setsid` and leaves to the lamb sweep. A job member cannot leave its
    /// job or spawn outside it, since `shep_tree::job::Job::create` grants no
    /// breakaway.
    #[cfg(windows)]
    fn kill_tree(&mut self) -> Result<(), RunnerError> {
        self.job
            .terminate(KILL_TREE_EXIT_CODE)
            .map_err(|error| RunnerError::SignalFailed(error.to_string()))
    }

    /// `SIGKILL` is delivered; the other eight names are refused by name.
    ///
    /// Per-signal rather than per-verb, so `shep signal <sheep> SIGKILL` keeps
    /// working while `SIGHUP` says what it cannot do. Seven of the nine have
    /// no delivery mechanism to a foreign Windows process at all. `Int` is
    /// refused as a judgement: Ctrl+C is disabled by default under
    /// `CREATE_NEW_PROCESS_GROUP`, which is how every sheep is spawned.
    #[cfg(windows)]
    fn signal_process(&mut self, sig: OperatorSignal) -> Result<(), RunnerError> {
        let Supervised::Spawned(child) = &mut self.proc;
        match sig {
            OperatorSignal::Kill => child
                .start_kill()
                .map_err(|error| RunnerError::SignalFailed(error.to_string())),
            other => Err(refused_on_windows(other)),
        }
    }

    #[cfg(unix)]
    fn signal_process(&mut self, sig: OperatorSignal) -> Result<(), RunnerError> {
        // Positive pid, unlike `signal_group`'s negative one: this reaches the
        // sheep alone, that one reaches its whole group.
        signal_pid(self.pid, sig)
    }
}

/// Sends `sig` to the one process `pid`, never its group.
///
/// # Errors
///
/// [`RunnerError::SignalFailed`] if `pid` is 0 or above `i32::MAX`, or the
/// `kill(2)` failed (typically `ESRCH`, or `EPERM` for another user's process).
#[cfg(unix)]
pub(crate) fn signal_pid(pid: u32, sig: OperatorSignal) -> Result<(), RunnerError> {
    let pid = signallable_pid(pid)?;
    signal::kill(Pid::from_raw(pid), to_nix_operator_signal(sig))
        .map_err(|error| RunnerError::SignalFailed(error.to_string()))
}

/// Sends `sig` to the one process `pid`: `SIGKILL` is delivered and the other
/// eight names are refused, as [`TokioProc`]'s own `signal_process` does.
///
/// # Errors
///
/// [`RunnerError::SignalFailed`] for any signal but `SIGKILL`, or if the OS
/// refused to end the process.
#[cfg(windows)]
pub(crate) fn signal_pid(pid: u32, sig: OperatorSignal) -> Result<(), RunnerError> {
    match sig {
        OperatorSignal::Kill => crate::sys_windows::terminate_process(pid, KILL_TREE_EXIT_CODE)
            .map_err(|error| RunnerError::SignalFailed(error.to_string())),
        other => Err(refused_on_windows(other)),
    }
}

#[cfg(windows)]
fn refused_on_windows(sig: OperatorSignal) -> RunnerError {
    RunnerError::SignalFailed(format!(
        "Windows has no way to deliver {sig:?} to another process; only SIGKILL is available here"
    ))
}

/// Narrows a spawn's pid to the `i32` form `kill(2)` takes, refusing one it
/// cannot take.
///
/// A zero pid must never reach the syscall: `-0` is `0`, and `kill(0, ..)`
/// signals the daemon's own group. A pid above `i32::MAX` has no `i32` form.
///
/// # Errors
///
/// [`RunnerError::SignalFailed`] if `pid` is 0 or above `i32::MAX`.
#[cfg(unix)]
pub(super) fn signallable_pid(pid: u32) -> Result<i32, RunnerError> {
    i32::try_from(pid)
        .ok()
        .filter(|pid| *pid > 0)
        .ok_or_else(|| {
            RunnerError::SignalFailed(format!("pid {pid} is not a signallable process id"))
        })
}

// Group-wide for an unsandboxed sheep's stop rungs and the exec prober's
// timeout path (`probes/os.rs`, why this is `pub(crate)`): a wrapper script
// that forks leaves its child in the group, and a leader-only signal would
// orphan it. A sandboxed sheep's first rung is `signal_leader`.
/// Sends `sig` to the whole process group led by `pid`, through
/// [`shep_tree::group::signal_group`].
///
/// `-pid` names the group `spawn`'s `process_group(0)` establishes. A
/// descendant that calls `setsid` lands in its own session, which this
/// misses. A sheep's lamb sweep ends it after the leader exits; a probe's
/// child has no sweep.
///
/// # Errors
///
/// [`RunnerError::SignalFailed`] if `pid` is not a signallable process id,
/// `sig` is not one `shep-tree` sends, or the `kill(2)` itself failed
/// (typically `ESRCH`: no group led by `pid`).
#[cfg(unix)]
pub(crate) fn signal_group(pid: u32, sig: Signal) -> Result<(), RunnerError> {
    // Before the signal is looked at, so a pid that must never reach
    // `kill(2)` is refused whatever it is asked to carry.
    signallable_pid(pid)?;
    shep_tree::group::signal_group(pid, to_tree_signal(sig)?)
        .map_err(|error| RunnerError::SignalFailed(error.to_string()))
}

/// Sends `sig` to the process `pid` and not its group.
///
/// For a sandboxed sheep, whose leader passes the signal on: a group signal
/// would reach the wrapped command twice on macOS.
///
/// # Errors
///
/// [`RunnerError::SignalFailed`] if `pid` is not a signallable process id, or
/// the `kill(2)` failed (typically `ESRCH`).
#[cfg(unix)]
fn signal_leader(pid: u32, sig: Signal) -> Result<(), RunnerError> {
    let pid = signallable_pid(pid)?;
    signal::kill(Pid::from_raw(pid), sig)
        .map_err(|error| RunnerError::SignalFailed(error.to_string()))
}

/// Maps a nix [`Signal`] to the [`shep_tree::Signal`] that names it.
///
/// # Errors
///
/// [`RunnerError::SignalFailed`] for a signal the ladder never sends to a
/// group, which `shep-tree` has no name for.
#[cfg(unix)]
fn to_tree_signal(sig: Signal) -> Result<shep_tree::Signal, RunnerError> {
    match sig {
        Signal::SIGTERM => Ok(shep_tree::Signal::Term),
        Signal::SIGINT => Ok(shep_tree::Signal::Int),
        Signal::SIGQUIT => Ok(shep_tree::Signal::Quit),
        Signal::SIGUSR2 => Ok(shep_tree::Signal::Usr2),
        Signal::SIGKILL => Ok(shep_tree::Signal::Kill),
        other => Err(RunnerError::SignalFailed(format!(
            "{other} cannot be sent to a process group"
        ))),
    }
}

/// Maps [`StopSignal`] to the nix [`Signal`] it names.
///
/// An explicit match, not `Signal::try_from(sig.as_raw())`, so an unmapped
/// variant is a compile error rather than a runtime one.
#[cfg(unix)]
fn to_nix_signal(sig: StopSignal) -> Signal {
    match sig {
        StopSignal::Term => Signal::SIGTERM,
        StopSignal::Int => Signal::SIGINT,
        StopSignal::Quit => Signal::SIGQUIT,
        StopSignal::Usr2 => Signal::SIGUSR2,
        StopSignal::Kill => Signal::SIGKILL,
    }
}

/// Maps [`OperatorSignal`] to the nix [`Signal`] it names.
///
/// shep-core holds no raw signal numbers, since they differ by platform
/// (`SIGUSR1` is 10 on Linux and 30 on macOS), so the two vocabularies meet
/// here.
#[cfg(unix)]
fn to_nix_operator_signal(sig: OperatorSignal) -> Signal {
    match sig {
        OperatorSignal::Hup => Signal::SIGHUP,
        OperatorSignal::Int => Signal::SIGINT,
        OperatorSignal::Quit => Signal::SIGQUIT,
        OperatorSignal::Term => Signal::SIGTERM,
        OperatorSignal::Usr1 => Signal::SIGUSR1,
        OperatorSignal::Usr2 => Signal::SIGUSR2,
        OperatorSignal::Winch => Signal::SIGWINCH,
        OperatorSignal::Cont => Signal::SIGCONT,
        OperatorSignal::Kill => Signal::SIGKILL,
    }
}

/// What exec will make of `spec.program`, before anything is spawned.
///
/// A `/` makes it a path, absolute or relative to `spec.cwd`, whose absence is
/// [`Preflight::Impossible`] and refuses the caller's whole batch. Without one
/// it is a bare command resolved through `spec.env`'s own `PATH`, at most
/// [`Preflight::Doubtful`]: a `shep startup` unit's `PATH` is not the
/// operator's shell's. Read through [`definitely_absent`], not [`Path::exists`].
pub(super) fn what_exec_will_find(spec: &SpawnSpec) -> Preflight {
    if spec.program.is_empty() {
        return Preflight::Unknown;
    }
    let program = Path::new(&spec.program);
    // A `/` is the claim that this is a path; Windows spells it `\`. Missing
    // that claim costs only the clear refusal: the fall-through looks the
    // program up on PATH, misses, and the spawn proceeds anyway.
    if spec.program.contains('/') || spec.program.contains(std::path::MAIN_SEPARATOR) {
        let full = if program.is_absolute() {
            program.to_path_buf()
        } else {
            match &spec.cwd {
                Some(cwd) => cwd.join(program),
                None => return Preflight::Unknown,
            }
        };
        if !definitely_absent(&full) {
            return Preflight::Unknown;
        }
        return Preflight::Impossible(format!("no such file: {}", full.display()));
    }
    let Some(path) = spec.env.get("PATH").filter(|value| !value.is_empty()) else {
        return Preflight::Unknown;
    };
    // Absent only if every entry answers a plain `NotFound`: one unreadable
    // directory means exec may still find the program there. `split_paths`
    // rather than a separator of our own, since a Windows entry carries a `:`
    // of its own and may be quoted.
    for dir in std::env::split_paths(path).filter(|dir| !dir.as_os_str().is_empty()) {
        match fs::metadata(dir.join(program)) {
            Ok(_) => return Preflight::Unknown,
            Err(err) if err.kind() == io::ErrorKind::NotFound => {}
            Err(_) => return Preflight::Unknown,
        }
    }
    Preflight::Doubtful(format!(
        "`{}` is not on the shepherd's PATH ({})",
        spec.program,
        summarise_path(path)
    ))
}

/// How many `PATH` entries a preflight message names before summarising the
/// rest.
///
/// Four: `assemble::environment_inheritance::inherited_env`'s fallback for a
/// startup unit with no `PATH` is three entries, so the case an operator hits
/// prints in full with one to spare. What gets cut off is an interactive
/// shell's `PATH`, which is unreadable in a terminal error.
const PATH_ENTRIES_IN_MESSAGE: usize = 4;

/// What separates one `PATH` entry from the next.
///
/// Display only: the lookup in `what_exec_will_find` goes through
/// `std::env::split_paths`, which also understands quoting.
pub(super) const PATH_LIST_SEPARATOR: char = if cfg!(windows) { ';' } else { ':' };

/// `path` as a message should print it: in full when short, and otherwise its
/// first [`PATH_ENTRIES_IN_MESSAGE`] entries with a count of the rest.
pub(super) fn summarise_path(path: &str) -> String {
    let entries: Vec<&str> = path
        .split(PATH_LIST_SEPARATOR)
        .filter(|dir| !dir.is_empty())
        .collect();
    if entries.len() <= PATH_ENTRIES_IN_MESSAGE {
        return path.to_string();
    }
    format!(
        "{} and {} more entries",
        entries[..PATH_ENTRIES_IN_MESSAGE].join(&PATH_LIST_SEPARATOR.to_string()),
        entries.len() - PATH_ENTRIES_IN_MESSAGE,
    )
}

/// Whether the filesystem says, without qualification, that `path` is not
/// there. `NotFound` and nothing else.
///
/// [`Path::exists`] returns `false` on any [`fs::metadata`] error, so a
/// permission error or an unsettled mount would read as absent and have
/// `what_exec_will_find` refuse a whole batch over a filesystem that was
/// unavailable for a moment. Follows symlinks, as exec does.
fn definitely_absent(path: &Path) -> bool {
    matches!(fs::metadata(path), Err(err) if err.kind() == io::ErrorKind::NotFound)
}

impl ProcessRunner for TokioRunner {
    type Proc = TokioProc;

    /// Reports a `program` that provably is not there, and nothing else.
    ///
    /// `program` is what `assemble` resolved `script` and `interpreter` down
    /// to, so an app running `npx next start` is checked at `npx` and `next`
    /// is npx's business. See `what_exec_will_find`.
    fn preflight(&self, spec: &SpawnSpec) -> Preflight {
        what_exec_will_find(spec)
    }

    /// Takes a sheep this image inherited rather than started.
    ///
    /// Nothing is spawned, opened or signalled. The carried pipe read ends go
    /// to the same log pump a spawn feeds, the carried log handles are written
    /// through rather than reopened, and the pid is the one the sheep has been
    /// running under all along. A blob naming neither a stdin nor a channel
    /// gets both closed here rather than left dangling.
    #[cfg(unix)]
    fn adopt(&self, spec: AdoptSpec) -> Result<(Self::Proc, ProcIo), RunnerError> {
        let AdoptSpec {
            name,
            pid,
            out_file,
            err_file,
            out_pipe,
            err_pipe,
            out_log,
            err_log,
            log_timestamps,
            leader_only_stop,
            stdin_pipe,
            channel,
            dog_link,
            dog_topics,
            reaper,
        } = spec;

        let (logs_tx, logs_rx) = mpsc::channel(CHANNEL_CAPACITY);
        let (log_ctl_tx, log_ctl_rx) = mpsc::channel(CHANNEL_CAPACITY);
        // Read before the handles move into their pumps: these are the
        // numbers the next handover carries.
        let pipes = PipeFds {
            out: out_pipe.as_ref().map(AsRawFd::as_raw_fd),
            err: err_pipe.as_ref().map(AsRawFd::as_raw_fd),
            stdin: stdin_pipe.as_ref().map(AsRawFd::as_raw_fd),
            channel: channel.as_ref().map(AsRawFd::as_raw_fd),
        };
        spawn_log_pump(
            out_pipe,
            err_pipe,
            carried_sink(out_file, out_log),
            carried_sink(err_file, err_log),
            log_timestamps,
            logs_tx,
            log_ctl_rx,
            pipes,
        );

        // Served by the same task that served it before the exec, which is
        // not this runner's to start: it is handed over, and a send that fails
        // means nothing is serving links, as at a spawn.
        if let Some(stream) = dog_link {
            let _ = self.links.send(DogLink {
                name,
                pid,
                stream,
                resumed: dog_topics,
            });
        }

        let (from_child_tx, from_child) = mpsc::channel(CHANNEL_CAPACITY);
        let (to_child, to_child_rx) = mpsc::channel(CHANNEL_CAPACITY);
        if let Some(channel) = channel {
            spawn_channel_pumps(channel, from_child_tx, to_child_rx);
        } else {
            drop(from_child_tx);
            drop(to_child_rx);
        }
        let (to_stdin, to_stdin_rx) = mpsc::channel(CHANNEL_CAPACITY);
        if let Some(stdin_pipe) = stdin_pipe {
            spawn_stdin_pump(Some(stdin_pipe), to_stdin_rx);
        } else {
            drop(to_stdin_rx);
        }

        Ok((
            TokioProc {
                pid,
                proc: Supervised::Adopted(reaper),
                leader_only_stop,
            },
            ProcIo {
                logs: logs_rx,
                from_child,
                to_child,
                log_ctl: log_ctl_tx,
                to_stdin,
            },
        ))
    }

    fn dog_links(&self) -> Option<mpsc::UnboundedReceiver<DogLink>> {
        self.links_rx
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .take()
    }

    fn spawn(&self, spec: &SpawnSpec) -> Result<(Self::Proc, ProcIo), RunnerError> {
        let mut command = Command::new(&spec.program);
        command.args(&spec.args);
        if let Some(cwd) = &spec.cwd {
            command.current_dir(cwd);
        }
        // Collected here and applied once, after every variable below is
        // known: `SpawnSpec::env` promises no daemon-env leakage beyond this
        // map, and a listen sheep's block must be the only thing that sets
        // the child's environment (see `crate::sys::ListenEnv`).
        let mut env = spec.env.clone();
        // `/dev/null` unless the app asked for a pipe: many programs decide
        // they are non-interactive from a closed fd 0. See `AppConfig::stdin`.
        command.stdin(if spec.stdin {
            Stdio::piped()
        } else {
            Stdio::null()
        });
        command.stdout(Stdio::piped());
        command.stderr(Stdio::piped());
        // New process group rooted at the child, so `kill_tree`'s
        // negative-pid `SIGKILL` cannot reach the daemon's own group.
        #[cfg(unix)]
        command.process_group(0);

        // Containment itself happens after `spawn()`: a process joins a job
        // only once it exists. These flags make that assignment meaningful by
        // keeping a Ctrl+C in the shepherd's console off the flock, and a
        // console child from flashing up a window nobody can draw.
        #[cfg(windows)]
        {
            /// Roots a new console process group at the child.
            const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
            /// Runs a console application without allocating a console window.
            const CREATE_NO_WINDOW: u32 = 0x0800_0000;
            command.creation_flags(CREATE_NEW_PROCESS_GROUP | CREATE_NO_WINDOW);
        }

        #[cfg(unix)]
        if let Some(creds) = spec.credentials {
            // std sets the gid before the uid, which is the order a privilege
            // drop requires. `CommandExt::groups` is unstable and unused, and
            // std still calls `setgroups(0, NULL)` before `setuid()` whenever
            // `.uid()` is set, so the child gets no supplementary groups.
            if let Some(gid) = creds.gid {
                command.gid(gid);
            }
            command.uid(creds.uid);
        }

        // `privilege::resolve` refuses `user`/`group` on Windows long before
        // a spawn, so this is an assertion rather than an error path: real
        // privilege drop there needs a plaintext password or an LSA logon
        // session, and a partial version would be worse than the refusal.
        #[cfg(windows)]
        debug_assert!(
            spec.credentials.is_none(),
            "privilege::resolve must refuse user/group on Windows before a spawn is reached"
        );

        let (from_child_tx, from_child_rx) = mpsc::channel(CHANNEL_CAPACITY);
        let (to_child_tx, to_child_rx) = mpsc::channel(CHANNEL_CAPACITY);

        // A named pipe the child opens by name, since `command-fds` is
        // unix-only and `cmd.exe` has no fd-3 redirection. Same wire format;
        // only the handle moves. `SHEP_CHANNEL_PIPE` is exported and
        // `SHEP_CHANNEL_FD` is not, so an app branches on the variable.
        #[cfg(windows)]
        if spec.channel {
            // Unique per spawn, so two instances cannot share a channel. The
            // pipe admits only the shepherd's own user: the namespace lists to
            // any local account and the `accept` below authenticates nobody,
            // so the descriptor is what refuses a second account (#350).
            let (pipe, mut listener) = windows_pipe::bind("channel", "shepherd channel pipe")?;
            env.insert("SHEP_CHANNEL_PIPE".to_string(), pipe.display().to_string());
            env.insert(
                "SHEP_CHANNEL_VERSION".to_string(),
                CHANNEL_VERSION.to_string(),
            );

            // On a task, since `spawn` is synchronous and the child cannot
            // connect until it is started below. The `closed()` arm bounds
            // it: an app that never opens the pipe would otherwise hold the
            // listener and a sender for the daemon's life. Both are cancel-safe.
            let from_child_tx = from_child_tx.clone();
            tokio::spawn(async move {
                let watcher = from_child_tx.clone();
                tokio::select! {
                    accepted = listener.accept() => match accepted {
                        Ok(daemon_end) => {
                            spawn_channel_pumps(daemon_end, from_child_tx, to_child_rx);
                        }
                        Err(error) => {
                            tracing::warn!(%error, "shepherd channel accept failed");
                        }
                    },
                    () = watcher.closed() => {}
                }
            });
        } else {
            drop(to_child_rx);
        }

        // The dog's own connection on Windows: a pipe the dog opens by the name
        // in its environment, as the channel's is. Served once it has a pid.
        #[cfg(windows)]
        let mut dog_pipe = None;
        #[cfg(windows)]
        if spec.dog_link {
            let (pipe, listener) = windows_pipe::bind("dog", "dog connection pipe")?;
            env.insert(DOG_LINK_PIPE_VAR.to_string(), pipe.display().to_string());
            dog_pipe = Some(listener);
        }

        // The block below moves `daemon_end` into its pumps, and `PipeFds` is
        // assembled after the spawn: the number is in reach only here.
        #[cfg(unix)]
        let mut channel_fd: Option<RawFd> = None;
        // `fd_mappings` installs a pre-exec hook each call, and its own docs
        // warn against calling it twice on one command.
        #[cfg(unix)]
        let mut mappings: Vec<FdMapping> = Vec::new();
        // Systemd's layout: the listeners take fd 3 upward in name order and
        // the channel follows them, so a sheep with none keeps the channel on
        // fd 3.
        #[cfg(unix)]
        let mut channel_child_fd: RawFd = 3;
        #[cfg(unix)]
        let listening = match &spec.listen {
            Some(sockets) if !sockets.is_empty() => Some(sockets),
            _ => None,
        };
        #[cfg(unix)]
        if let Some(sockets) = listening {
            if spec.dog_link {
                return Err(RunnerError::SpawnFailed(
                    "a dog's connection and listen sockets both claim fd 4".to_string(),
                ));
            }
            let duplicates = sockets.duplicates().map_err(|error| {
                RunnerError::SpawnFailed(format!("listen socket duplicate: {error}"))
            })?;
            for parent_fd in duplicates {
                mappings.push(FdMapping {
                    parent_fd,
                    child_fd: channel_child_fd,
                });
                channel_child_fd += 1;
            }
            // Ours, not the operator's: a stale `LISTEN_*` in the sheep's own
            // env would name descriptors this layout does not have.
            env.insert("LISTEN_FDS".to_string(), sockets.len().to_string());
            env.insert(
                "LISTEN_FDNAMES".to_string(),
                sockets.names().collect::<Vec<_>>().join(":"),
            );
        }
        #[cfg(unix)]
        if spec.channel {
            env.insert("SHEP_CHANNEL_FD".to_string(), channel_child_fd.to_string());
            // Not negotiation: an app cannot be asked what it speaks, but one
            // that wants to be defensive can check what it is given.
            env.insert(
                "SHEP_CHANNEL_VERSION".to_string(),
                CHANNEL_VERSION.to_string(),
            );
            let (daemon_end, child_end) = UnixStream::pair().map_err(|error| {
                RunnerError::SpawnFailed(format!("shepherd channel socketpair: {error}"))
            })?;
            let std_child_end = child_end.into_std().map_err(|error| {
                RunnerError::SpawnFailed(format!("shepherd channel into_std: {error}"))
            })?;
            // `UnixStream::pair()` sets `O_NONBLOCK` on both ends for tokio's
            // half, and the child inherits it across the exec: a plain
            // `read <&3` would get `EAGAIN` rather than parking. The daemon's
            // own end is a separate descriptor and stays non-blocking.
            std_child_end.set_nonblocking(false).map_err(|error| {
                RunnerError::SpawnFailed(format!("shepherd channel set_nonblocking: {error}"))
            })?;
            let child_fd = OwnedFd::from(std_child_end);
            mappings.push(FdMapping {
                parent_fd: child_fd,
                child_fd: channel_child_fd,
            });
            channel_fd = Some(daemon_end.as_raw_fd());
            spawn_channel_pumps(daemon_end, from_child_tx, to_child_rx);
        } else {
            // No channel: closed rather than dangling, so `from_child.recv()`
            // reports closed at once and a stray send fails fast.
            drop(from_child_tx);
            drop(to_child_rx);
        }

        // Held until the child has a pid: the server that serves it records
        // contact by that pid.
        #[cfg(unix)]
        let mut dog_end = None;
        #[cfg(unix)]
        if spec.dog_link {
            let (daemon_end, mapping) = dog_link::pair()?;
            env.insert(DOG_LINK_FD_VAR.to_string(), DOG_LINK_FD.to_string());
            mappings.push(mapping);
            dog_end = Some(daemon_end);
        }
        #[cfg(unix)]
        if !mappings.is_empty() {
            command
                .as_std_mut()
                .fd_mappings(mappings)
                .map_err(|error| RunnerError::SpawnFailed(format!("fd mapping: {error}")))?;
        }

        #[cfg(unix)]
        if listening.is_some() {
            // `LISTEN_PID` is the child's own pid, which only the child can
            // write, after the fork. The block replaces `environ` there, so
            // the command's own env must stay untouched.
            let block = crate::sys::ListenEnv::new(&env)
                .map_err(|error| RunnerError::SpawnFailed(format!("environment: {error}")))?;
            crate::sys::set_listen_env(command.as_std_mut(), block);
        } else {
            command.env_clear();
            command.envs(&env);
        }
        #[cfg(windows)]
        {
            command.env_clear();
            command.envs(&env);
        }

        let mut child = command
            .spawn()
            .map_err(|error| RunnerError::SpawnFailed(error.to_string()))?;
        // Closes the parent's copy of the fd-3 socketpair end here rather
        // than at the end of the scope, so the daemon's end sees a clean EOF.
        drop(command);

        let pid = child.id().ok_or_else(|| {
            RunnerError::SpawnFailed("child exited before its pid could be read".to_string())
        })?;
        // A send that fails means nothing is serving links, and the dog falls
        // back to the control socket.
        #[cfg(unix)]
        if let Some(stream) = dog_end {
            let _ = self.links.send(DogLink {
                name: spec.name.clone(),
                pid,
                stream,
                resumed: None,
            });
        }

        // As early as containment can happen: the child exists and everything
        // it spawns from here inherits the job. Fatal on failure, because a
        // sheep outside its job is one `kill_tree` cannot reach and `shep
        // stop` would report success over a running process.
        #[cfg(windows)]
        let job = {
            let job = shep_tree::job::Job::create().map_err(|error| {
                RunnerError::SpawnFailed(format!("job object for {}: {error}", spec.name))
            })?;
            let handle = child.raw_handle().ok_or_else(|| {
                RunnerError::SpawnFailed("child exited before it could be contained".to_string())
            })?;
            if let Err(error) = job.assign(handle) {
                // Running and in no job: nothing could stop its descendants
                // afterwards, so it must not be left behind.
                let _ = child.start_kill();
                return Err(RunnerError::SpawnFailed(format!(
                    "could not contain {} in a job object: {error}",
                    spec.name
                )));
            }
            job
        };

        let (logs_tx, logs_rx) = mpsc::channel(CHANNEL_CAPACITY);
        let (log_ctl_tx, log_ctl_rx) = mpsc::channel(CHANNEL_CAPACITY);
        // After the job, which can still fail the spawn: a dog nothing is
        // contained for must not leave a listener behind. Bounded by the log
        // pump, which ends with the dog.
        #[cfg(windows)]
        if let Some(listener) = dog_pipe {
            windows_pipe::serve_dog_link(
                listener,
                spec.name.clone(),
                pid,
                self.links.clone(),
                log_ctl_tx.clone(),
            );
        }
        // Before the `take`s below move the handles: the only place the
        // numbers a handover carries are known.
        #[cfg(unix)]
        let pipes = PipeFds {
            out: child.stdout.as_ref().map(AsRawFd::as_raw_fd),
            err: child.stderr.as_ref().map(AsRawFd::as_raw_fd),
            stdin: child.stdin.as_ref().map(AsRawFd::as_raw_fd),
            // Read further up, before the daemon end moved into its pumps.
            // Nothing on `child` names it: the child's side is fd 3.
            channel: channel_fd,
        };
        #[cfg(not(unix))]
        let pipes = PipeFds;
        spawn_log_pump(
            child.stdout.take(),
            child.stderr.take(),
            LogSink::Path(spec.out_file.clone()),
            LogSink::Path(spec.err_file.clone()),
            spec.log_timestamps,
            logs_tx,
            log_ctl_rx,
            pipes,
        );

        let (to_stdin_tx, to_stdin_rx) = mpsc::channel(CHANNEL_CAPACITY);
        if spec.stdin {
            spawn_stdin_pump(child.stdin.take(), to_stdin_rx);
        } else {
            // Dropped rather than dangling, so a caller's `is_closed()` says
            // "no pipe here" at once.
            drop(to_stdin_rx);
        }

        let io = ProcIo {
            logs: logs_rx,
            from_child: from_child_rx,
            to_child: to_child_tx,
            log_ctl: log_ctl_tx,
            to_stdin: to_stdin_tx,
        };
        Ok((
            TokioProc {
                pid,
                proc: Supervised::Spawned(child),
                #[cfg(unix)]
                leader_only_stop: spec.leader_only_stop,
                #[cfg(windows)]
                job,
            },
            io,
        ))
    }
}