shep-daemon 0.8.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
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
//! Spawn seam between the daemon engine and the OS
//!
//! [`ProcessRunner`] spawns a child; the [`RunningProcess`] it returns owns
//! that one live child. Spawn also hands back a [`ProcIo`] bundle of
//! channels, so the sheep task pumps stdout/stderr and shepherd-channel
//! messages without the runner blocking on delivery.
//!
//! Also owns the log plane's vocabulary ([`LogCtl`] and its two errors) and
//! this crate's only opener of a sheep's log file, `open_log_path`, with the
//! ancestry guard that runs ahead of it. The log pump and `shep flush` both
//! go through the pair, so neither can drift on what it will open. The
//! `#[cfg(unix)]` items are the handover's; Windows has no `execve`.

use core::fmt;
use std::collections::BTreeMap;
use std::io;
use std::path::{Path, PathBuf};

use tokio::sync::{mpsc, oneshot};

use shep_core::signals::OperatorSignal;

use crate::channel::{ChildMessage, ShepherdMessage};
use crate::privilege::Credentials;

/// Re-exported so [`AdoptSpec`]'s public signature can name it: the reaper
/// itself lives in the crate-private `handover` module.
#[cfg(unix)]
pub use crate::handover::reap::AdoptedReaper;

/// One exit observation
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ExitOutcome {
    /// Exit code on normal exit
    pub code: Option<i32>,
    /// Raw unix signal number when killed (`SIGTERM`=15, `SIGKILL`=9, ...)
    pub signal: Option<i32>,
}

/// Typed stop signal
///
/// [`StopSignal::as_raw`] gives the unix number so fake and real runners
/// record identical [`ExitOutcome`]s.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StopSignal {
    /// `SIGTERM`: graceful stop request
    Term,
    /// `SIGINT`: interrupt
    Int,
    /// `SIGQUIT`: quit, core-dumping by default
    Quit,
    /// `SIGUSR2`: user-defined signal 2
    Usr2,
    /// `SIGKILL`: unblockable, immediate
    Kill,
}

impl StopSignal {
    /// The raw unix signal number
    #[must_use]
    pub fn as_raw(self) -> i32 {
        match self {
            Self::Term => 15,
            Self::Int => 2,
            Self::Quit => 3,
            Self::Usr2 => 12,
            Self::Kill => 9,
        }
    }
}

/// One stdout/stderr line from a child
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LogLine {
    /// True = stderr, false = stdout
    pub err: bool,
    /// The line, no trailing newline
    pub line: String,
}

/// What the supervisor can ask a log pump to do mid-flight.
///
/// The [`oneshot`] on each variant is what makes it usable as a barrier:
/// once it resolves, every live pump has done the thing. A logrotate
/// `postrotate` stanza needs that of [`Self::Reopen`] before it compresses
/// what it renamed; `shep flush` needs it of [`Self::Flush`] before it
/// truncates.
///
/// `#[non_exhaustive]`: this crate is published, and an out-of-tree
/// `ProcessRunner` matching exhaustively would break on the next variant.
#[derive(Debug)]
#[non_exhaustive]
pub enum LogCtl {
    /// Drop the current handle and open the path again, then acknowledge.
    /// Sent when an external rotator has renamed the file.
    Reopen {
        /// Fires once the pump has finished acting on this request.
        ///
        /// `Ok` says both old handles were flushed and closed and both paths
        /// were opened again. [`ReopenError`] says at least one path could
        /// not be opened: the old handle is closed either way, so the rename
        /// is safe to act on, but that stream's lines are dropped until
        /// something reopens it.
        ///
        /// The channel buffers, so a request that was accepted is not one
        /// that will be served: a pump that ends first drops this sender and
        /// the caller's `await` resolves [`Err`](oneshot::error::RecvError).
        /// Treat that as the stopped-sheep no-op a failed send means.
        done: oneshot::Sender<Result<(), ReopenError>>,
    },
    /// Write out whatever the pump has buffered, wait for it to reach the
    /// file, keep the handle, then acknowledge. Sent as the first half of
    /// `shep flush`, immediately before the recorded paths are truncated.
    Flush {
        /// Fires once both handles have nothing buffered and no write in
        /// flight.
        ///
        /// The barrier the truncate that follows is ordered against:
        /// `write_all` on a [`tokio::fs::File`] returns as soon as the real
        /// `write(2)` is queued, so a line already dispatched could otherwise
        /// land at offset 0 after the file was emptied.
        ///
        /// [`FlushError`] says at least one stream's owed bytes never reached
        /// its file. It does not hold up the truncate: `poll_flush` drives
        /// the in-flight write to completion either way. A pump that ends
        /// first drops this sender, as [`Self::Reopen`]'s does.
        done: oneshot::Sender<Result<(), FlushError>>,
    },
    /// Write out whatever the pump has buffered, wait for it to reach the
    /// files, then acknowledge with the descriptor numbers a blob is to
    /// name for this sheep. Sent while assembling a daemon handover.
    ///
    /// Flush and report are one request: bytes still buffered behind a
    /// descriptor the blob already claims die with the image at the `execve`,
    /// and the successor cannot repair a gap it never saw.
    ///
    /// Unix only: it answers with raw descriptor numbers, and Windows has no
    /// `execve` and no handover.
    #[cfg(unix)]
    ReportFds {
        /// Fires once both handles have nothing buffered and no write in
        /// flight, carrying the descriptors the blob is to name.
        ///
        /// `CarriedFds::none` is the honest answer for a pump holding
        /// nothing, never an error: a number that names nothing is what the
        /// successor must not be handed. A pump that ends first drops this
        /// sender, as [`Self::Reopen`]'s does.
        ///
        /// `CarriedFds` is crate-private, so an out-of-tree runner can drop
        /// this sender but cannot answer it.
        done: oneshot::Sender<crate::handover::CarriedFds>,
    },
    /// Read the sheep's streams again after a [`Self::ReportFds`] that no
    /// exec followed. Sent when a handover is abandoned.
    ///
    /// A report parks the pump, since a snapshot only stays true while
    /// nothing moves behind it, and normally the exec ends the park by
    /// replacing the image. Every other way out leaves this daemon with a
    /// pump that has stopped reading for the rest of its life, so an
    /// abandoned handover owes every pump it reported one of these.
    ///
    /// No acknowledgement: nobody is ordered against it, and sending one to
    /// a pump that was never parked is a no-op, so it is safe to send widely
    /// rather than exactly. Unix only, as [`Self::ReportFds`] is.
    #[cfg(unix)]
    Resume,
}

/// A [`LogCtl::Reopen`] that could not open one or both of a sheep's log
/// files again.
///
/// Carries a rendered message rather than the `io::Error`s behind it, as
/// [`RunnerError`] does: it crosses a channel and every layer between only
/// prints it, and a `String` is what keeps this `Clone`/`Eq`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReopenError {
    /// Every log file the reopen could not open again, as
    /// `"<path>: <what the open reported>"`, joined by `", "` when both
    /// streams failed. Never empty: a reopen that opened both answers `Ok`.
    ///
    /// `", "` and not `"; "` because this list nests:
    /// [`SupervisorError::ReopenFailed`] joins one of these per sheep with
    /// `"; "`, and one separator at both levels would punctuate one sheep
    /// that failed on both streams like two sheep that failed on one each.
    ///
    /// [`SupervisorError::ReopenFailed`]: crate::supervisor::SupervisorError::ReopenFailed
    pub message: String,
}

impl fmt::Display for ReopenError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "could not reopen {}", self.message)
    }
}

impl core::error::Error for ReopenError {}

/// A `shep flush` that could not empty a log file, from either half of that
/// verb: a pump whose pending writes would not reach the file
/// ([`LogCtl::Flush`]), or a path that could not be truncated once they had.
///
/// What the two leave behind differs: a truncate that failed leaves its file
/// as it was, while a failed flush does not hold up the truncate, so that
/// file ends up empty with the lines it held gone unwritten. Carries a
/// rendered message for the reasons [`ReopenError`] gives.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FlushError {
    /// Every log file the flush could not empty, as
    /// `"<path>: <what the failing call reported>"`, joined by `", "` when
    /// both of a pump's streams did. Never empty: a flush that emptied every
    /// file answers `Ok`.
    ///
    /// `", "` for the reason [`ReopenError::message`] gives about its own
    /// separator.
    ///
    /// Keyed by path and never by sheep: several sheep can share one log
    /// path (`merge_logs`, or an explicit `out_file` on a multi-instance
    /// app), so naming one of them would be arbitrary.
    pub message: String,
}

impl fmt::Display for FlushError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "could not flush {}", self.message)
    }
}

impl core::error::Error for FlushError {}

/// What an operator is told when a log path turns out to be a symlink.
///
/// One owner for the sentence, cited by [`open_log_path`] and by both
/// openers' tests, so the operator reads a remedy rather than a bare
/// `ELOOP`. The path is not in here: every caller already prefixes one.
#[cfg_attr(windows, allow(dead_code))]
pub(crate) const SYMLINK_REFUSED: &str = "refusing to follow a symlink at this log path; shep \
     opens log files with O_NOFOLLOW, so point out_file/err_file at the real file";

/// Opens `path` through `options`, refusing a symlink at the path itself
///
/// The one opener of a log file in this crate: the pump's append handle and
/// `shep flush`'s truncating one both come through here.
/// [`check_log_ancestry`] runs before it at both call sites, ahead of
/// `open_append`'s `mkdir`. `O_NOFOLLOW` guards only the final component, so
/// a symlinked parent still resolves; only that check covers it.
///
/// # Errors
///
/// Whatever the open reported, with `ELOOP` relabelled to
/// [`SYMLINK_REFUSED`]: `NotFound` passes through untouched.
pub(crate) async fn open_log_path(
    options: &mut tokio::fs::OpenOptions,
    path: &Path,
) -> io::Result<tokio::fs::File> {
    #[cfg(unix)]
    options.custom_flags(nix::libc::O_NOFOLLOW);
    options.open(path).await.map_err(name_the_symlink)
}

/// Relabels the `ELOOP` an `O_NOFOLLOW` open answers with, leaving every
/// other error exactly as the OS reported it.
///
/// One errno covers both supported platforms: POSIX specifies `ELOOP` and
/// Darwin's `open(2)` matches. The kind is carried over; only the message
/// changes.
#[cfg(unix)]
fn name_the_symlink(error: io::Error) -> io::Error {
    if error.raw_os_error() == Some(nix::libc::ELOOP) {
        io::Error::new(error.kind(), SYMLINK_REFUSED)
    } else {
        error
    }
}

/// The non-unix arm of [`name_the_symlink`]: no `O_NOFOLLOW`, so no refusal
/// to relabel.
#[cfg(not(unix))]
fn name_the_symlink(error: io::Error) -> io::Error {
    error
}

/// Refuses a log path another local user could redirect, under root only
///
/// [`open_log_path`]'s other half, run before it (and before any `mkdir`)
/// at both call sites. A loose ancestry escalates only under a privileged
/// daemon, so root refuses and everyone else is warned once per path.
/// [`loose_ancestor`] defines loose, and the window between the check and
/// the open stays open (`docs/specs/deferred.md`).
///
/// # Errors
///
/// [`io::ErrorKind::PermissionDenied`] naming the loose ancestor, when the
/// daemon's effective uid is root. The message carries no path of its own.
pub(crate) fn check_log_ancestry(path: &Path) -> io::Result<()> {
    #[cfg(unix)]
    {
        check_log_ancestry_as(path, crate::server::daemon_uid())
    }
    // Windows has neither the uid model this reads nor the `shep flush`
    // surface that reaches it, so there is nothing to check.
    #[cfg(not(unix))]
    {
        let _ = path;
        Ok(())
    }
}

/// The effective uid a shepherd has to be running as for a loose ancestor to
/// be an escalation rather than a footgun.
#[cfg(unix)]
const ROOT_UID: u32 = 0;

/// The permission bit that lets every local user create entries in a
/// directory. Narrower than `boot`'s socket-directory check (`0o022`, group
/// or world): a group-writable log directory names accounts an operator
/// chose, while this bit names everyone.
#[cfg(unix)]
const WORLD_WRITABLE: u32 = 0o002;

/// Log paths whose loose ancestry has already been reported, so an
/// unprivileged shepherd says it once rather than on every open.
///
/// Keyed by the log path, not by the offending ancestor: that is what an
/// operator asking which of their apps this is about is asking. Bounded by
/// the number of distinct log paths in the flock.
#[cfg(unix)]
static WARNED_LOOSE_LOG_PATHS: std::sync::LazyLock<
    std::sync::Mutex<std::collections::HashSet<PathBuf>>,
> = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashSet::new()));

/// [`check_log_ancestry`] with the daemon's effective uid supplied, so the
/// privileged arm is reachable from a test that is not running as root.
///
/// # Errors
///
/// [`check_log_ancestry`]'s.
#[cfg(unix)]
fn check_log_ancestry_as(path: &Path, daemon_uid: u32) -> io::Result<()> {
    let Some(loose) = loose_ancestor(path, daemon_uid) else {
        return Ok(());
    };
    if daemon_uid == ROOT_UID {
        return Err(io::Error::new(
            io::ErrorKind::PermissionDenied,
            format!(
                "refusing to open a log file below {}, which {}; a shepherd running as root \
                 writes only below directories its own user owns",
                loose.path.display(),
                loose.reason,
            ),
        ));
    }
    let first_time = WARNED_LOOSE_LOG_PATHS
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .insert(path.to_path_buf());
    if first_time {
        tracing::warn!(
            path = %path.display(),
            ancestor = %loose.path.display(),
            reason = %loose.reason,
            "log path sits below a directory another local user could redirect; a shepherd \
             running as root would refuse to open it"
        );
    }
    Ok(())
}

/// An ancestor of a log path that another local user could use to redirect
/// where that path lands.
#[cfg(unix)]
#[derive(Debug, Clone, PartialEq, Eq)]
struct LooseAncestor {
    /// The offending component, as it appears in the log path.
    path: PathBuf,
    /// Why it offends: reads as the predicate in `"<path> <reason>"`.
    reason: LooseReason,
}

/// Why an ancestor of a log path counts as loose.
#[cfg(unix)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum LooseReason {
    /// Owned by a uid that is neither the daemon's own nor root's, so its
    /// owner can replace or redirect it under the daemon (carries that uid).
    /// Also how a symlinked component is caught: the link's own owner is the
    /// user who planted it.
    ForeignOwner(u32),
    /// A directory every local user can create entries in, so anyone can put
    /// a symlink where the next component is about to be resolved.
    WorldWritable,
}

#[cfg(unix)]
impl fmt::Display for LooseReason {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::ForeignOwner(uid) => write!(f, "is owned by uid {uid}"),
            Self::WorldWritable => f.write_str("is world-writable"),
        }
    }
}

/// The nearest ancestor of `path` another local user could redirect it
/// through, or `None` when every one is the daemon's to trust.
///
/// Walks the path's own textual components upwards from its parent and stops
/// at the first offender. `symlink_metadata`, never `metadata`: a symlinked
/// component must be read as the link it is, owned by whoever planted it. An
/// ancestor that does not exist, or cannot be stat'd, is skipped, since
/// `open_append` is about to create it at `boot::DIR_MODE` as the daemon.
///
/// One `lstat(2)` per component per log-file open, 7.8 µs for a
/// nine-component path on macOS, so it runs inline rather than paying a
/// `spawn_blocking` hop.
#[cfg(unix)]
fn loose_ancestor(path: &Path, daemon_uid: u32) -> Option<LooseAncestor> {
    use std::os::unix::fs::MetadataExt as _;

    path.parent()?
        .ancestors()
        .filter_map(|ancestor| Some((ancestor, std::fs::symlink_metadata(ancestor).ok()?)))
        .find_map(|(ancestor, meta)| {
            let reason = if meta.uid() != daemon_uid && meta.uid() != ROOT_UID {
                LooseReason::ForeignOwner(meta.uid())
            } else if meta.is_dir() && meta.mode() & WORLD_WRITABLE != 0 {
                LooseReason::WorldWritable
            } else {
                return None;
            };
            Some(LooseAncestor {
                path: ancestor.to_path_buf(),
                reason,
            })
        })
}

/// IO endpoints handed back by spawn; the runner pumps internally.
///
/// The sheep task owns this and must drain every receiver: an undrained
/// `from_child` back-pressures a metric-emitting child until it stalls on
/// its own fd-3 write.
#[derive(Debug)]
pub struct ProcIo {
    /// stdout+stderr lines
    pub logs: mpsc::Receiver<LogLine>,
    /// Parsed child→daemon shepherd-channel messages
    pub from_child: mpsc::Receiver<ChildMessage>,
    /// daemon→child shepherd-channel sender
    pub to_child: mpsc::Sender<ShepherdMessage>,
    /// Control channel into this sheep's log pump
    ///
    /// The pump is the only reader of the child's stdout and stderr, and it
    /// ends when the last of these senders drops, so hold this while the
    /// child is alive: ending the pump drops the read ends of both pipes and
    /// the child's next write gets `EPIPE`/`SIGPIPE`. The supervisor clones
    /// it (`SheepSlot::log_ctl`); what keeps a clone from stretching a
    /// pump's life is the pump's own exit on the `logs` receiver going away.
    ///
    /// A send that fails means the pump is already gone, which makes a
    /// reopen a no-op rather than an error.
    pub log_ctl: mpsc::Sender<LogCtl>,
    /// The shepherd's writing end of this sheep's stdin.
    ///
    /// Always present, and closed rather than absent when the app asked for
    /// no pipe: the runner drops the receiving end, so `is_closed()` is the
    /// one question a caller asks, the same shape [`Self::to_child`] uses.
    ///
    /// Hold it only for as long as the child is alive: the task on the far
    /// end parks on `recv()`, so a sender kept past the child's exit parks
    /// that task and holds the pipe's write end with it.
    pub to_stdin: mpsc::Sender<StdinWrite>,
}

/// One line to write to a sheep's stdin, and where the answer goes.
///
/// The acknowledgement is the point, as on [`LogCtl`]: an `mpsc::send` only
/// proves the message was queued, and the line may still be sitting behind a
/// pipe the app has stopped reading. The `oneshot` fires after the bytes are
/// written and flushed.
#[derive(Debug)]
pub struct StdinWrite {
    /// The line, without its terminator: the writer appends one `\n`.
    pub line: String,
    /// Fires once the line has landed, or with why it could not.
    ///
    /// A dropped sender means the writer task ended before serving this
    /// request, which happens when the child's stdin closed; the caller reads
    /// that as the pipe being gone.
    pub done: oneshot::Sender<Result<(), RunnerError>>,
}

/// A live child.
pub trait RunningProcess: Send + 'static {
    /// The OS process id
    fn pid(&self) -> u32;

    /// Resolves exactly once with the exit outcome
    ///
    /// # Cancellation safety
    ///
    /// Dropping the returned future and calling `wait` again neither
    /// restarts the wait nor loses progress toward it, as
    /// [`tokio::process::Child::wait`] guarantees; the scripted fake mirrors
    /// it by fixing its exit deadline once, at spawn.
    ///
    /// The future is `Send` (RPITIT) because the sheep task that owns the
    /// proc is `tokio::spawn`'ed.
    fn wait(&mut self) -> impl core::future::Future<Output = ExitOutcome> + Send;

    /// Sends a signal to the sheep's whole process group
    ///
    /// Group-wide, not leader-only: a `thing & wait` wrapper's forked child
    /// stays in its own group, and a leader-only signal would leave it
    /// running and untracked. Implementors must spawn each child as the
    /// leader of a fresh group; this and [`Self::kill_tree`] address it by
    /// [`Self::pid`], so a child that escapes with `setsid` is beyond both.
    ///
    /// # Errors
    ///
    /// - [`RunnerError::SignalFailed`] if delivery failed (already reaped,
    ///   `EPERM`).
    fn signal(&mut self, sig: StopSignal) -> Result<(), RunnerError>;

    /// Sends `sig` to this sheep's own process, never its process group.
    ///
    /// Not group-wide, unlike [`Self::signal`]: this exists for a
    /// conversation between an operator and one application, and a `SIGHUP`
    /// broadcast to the group would reach whatever `sh` and runtime children
    /// are in it. The default refuses rather than widening to the group.
    ///
    /// # Errors
    ///
    /// - [`RunnerError::SignalFailed`] if delivery failed (`ESRCH`, `EPERM`)
    ///   or this implementation has no per-process delivery at all.
    fn signal_process(&mut self, sig: OperatorSignal) -> Result<(), RunnerError> {
        let _ = sig;
        Err(RunnerError::SignalFailed(
            "this runner cannot signal a single process".to_string(),
        ))
    }

    /// SIGKILLs the whole process group/tree
    ///
    /// The escalation rung above [`Self::signal`]: same group, same
    /// process-group assumption, but a signal nothing can catch or ignore.
    ///
    /// # Errors
    ///
    /// - [`RunnerError::SignalFailed`] if delivery failed (already reaped,
    ///   `EPERM`).
    fn kill_tree(&mut self) -> Result<(), RunnerError>;
}

/// Spawn seam between engine and OS
pub trait ProcessRunner: Send + Sync + 'static {
    /// The live-child type this runner produces
    type Proc: RunningProcess;

    /// Spawns per the spec, returning the proc + its IO bundle
    ///
    /// Must be called from within a Tokio runtime context: both
    /// implementations spawn background tasks internally to pump IO.
    ///
    /// # Errors
    ///
    /// - [`RunnerError::SpawnFailed`] on an exec failure, bad permissions or
    ///   a missing binary.
    fn spawn(&self, spec: &SpawnSpec) -> Result<(Self::Proc, ProcIo), RunnerError>;

    /// What is knowable about `spec` before anything is spawned
    ///
    /// Lets a caller refuse a whole batch before registering any of it,
    /// rather than registering the apps ahead of the one that cannot spawn.
    /// See [`Preflight`] for which verdicts a caller may refuse a batch over.
    /// The default answers [`Preflight::Unknown`], which is also the honest
    /// answer for a runner that never touches the filesystem.
    #[must_use]
    fn preflight(&self, spec: &SpawnSpec) -> Preflight {
        let _ = spec;
        Preflight::Unknown
    }

    /// Rebuilds a proc around a sheep this process inherited, not started
    ///
    /// The successor half of a handover, unix only as the handover is. Every
    /// handle in `spec` crossed an `execve` with its `FD_CLOEXEC` cleared, so
    /// the sheep never noticed: same pid, same pipes, same open file
    /// description on each log. Nothing here spawns or signals.
    ///
    /// # Errors
    ///
    /// - [`RunnerError::AdoptFailed`] if this runner cannot take a process it
    ///   did not spawn (what the default answers), or if the carried handles
    ///   could not be wired to a pump.
    #[cfg(unix)]
    fn adopt(&self, spec: AdoptSpec) -> Result<(Self::Proc, ProcIo), RunnerError> {
        let _ = spec;
        Err(RunnerError::AdoptFailed(
            "this runner cannot adopt a process it did not spawn".to_string(),
        ))
    }
}

/// One inherited sheep, and everything a runner needs to supervise it again.
///
/// Produced by the successor's `handover::adopt` and consumed by
/// [`ProcessRunner::adopt`]. The handles are owned, since adopting is taking
/// ownership of them; `None` on a pair means the predecessor had no handle
/// to carry.
///
/// `Debug` is derived: descriptor numbers, a pid and two log paths are all in
/// `shep flock` already, and no env value reaches this type.
#[cfg(unix)]
#[derive(Debug)]
pub struct AdoptSpec {
    /// The pid the sheep has been running under all along, unchanged by the
    /// handover.
    pub pid: u32,
    /// Where its stdout is logged, kept so a later rotation can reopen it.
    pub out_file: PathBuf,
    /// Where its stderr is logged, kept for the same reason.
    pub err_file: PathBuf,
    /// The read end of its stdout pipe, still the one the child writes into.
    pub out_pipe: Option<tokio::net::unix::pipe::Receiver>,
    /// The read end of its stderr pipe, likewise.
    pub err_pipe: Option<tokio::net::unix::pipe::Receiver>,
    /// The appending handle on its stdout log, written through rather than
    /// reopened so `O_APPEND` survives.
    pub out_log: Option<tokio::fs::File>,
    /// The appending handle on its stderr log, likewise.
    pub err_log: Option<tokio::fs::File>,
    /// The write end of its stdin pipe, still the one the child reads from,
    /// for a sheep whose app asked for one.
    ///
    /// The one handle here the daemon writes to. `None` is the commoner
    /// sheep, which has `/dev/null` on fd 0.
    pub stdin_pipe: Option<tokio::net::unix::pipe::Sender>,
    /// The daemon's end of its shepherd-channel socketpair, still the one
    /// whose other end is the child's fd 3.
    ///
    /// Goes both ways, so an adoption puts both pumps back on it. `None` for
    /// a sheep whose app asked for no channel, and for one whose child has
    /// closed fd 3.
    pub channel: Option<tokio::net::UnixStream>,
    /// The one reaper this successor waits every adopted pid through.
    ///
    /// Shared rather than owned per sheep: a status can be collected once,
    /// so two reapers racing on one pid would leave one meeting `ECHILD`.
    pub reaper: std::sync::Arc<AdoptedReaper>,
}

/// What a [`ProcessRunner`] can tell about a [`SpawnSpec`] before anything is
/// spawned
///
/// The line that matters runs between [`Self::Impossible`] and
/// [`Self::Doubtful`], and it separates two kinds of claim. A path with a
/// `/` is a claim about the filesystem, which the daemon can check. A bare
/// command is a claim about the daemon's own environment, which is not the
/// shell the operator tested in: `node` from homebrew or nvm resolves in a
/// terminal and under no `shep startup` unit. Refusing a batch on the second
/// would keep twelve apps down over one interpreter.
// `#[non_exhaustive]`: an out-of-tree consumer can match this exhaustively,
// and a fourth verdict would break them with no version bump.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Preflight {
    /// Nothing is knowable in advance.
    ///
    /// Not "this will work": every form an implementation declines to decide
    /// arrives here alongside every form it decided is fine. A caller may
    /// only act on the other two variants.
    Unknown,
    /// The spawn cannot succeed, as a certainty. Carries one reason, no
    /// trailing punctuation, ready to be printed after a sheep's name.
    ///
    /// A caller registering a batch should refuse the whole batch and
    /// register none of it.
    Impossible(String),
    /// The spawn looks like it will fail, and a caller must not refuse a
    /// batch over it. Carries a reason on the same terms as
    /// [`Self::Impossible`]. Report it and carry on: the spawn then fails for
    /// that one sheep as it would have anyway.
    Doubtful(String),
}

/// Everything a spawn needs, pre-assembled by the assembler (a later task)
#[derive(Clone, PartialEq, Eq)]
pub struct SpawnSpec {
    /// Sheep name (for logging/tracing, not passed to the child)
    pub name: String,
    /// Executable path or name (resolved via `PATH` if bare)
    pub program: String,
    /// Argument vector, `argv[1..]`
    pub args: Vec<String>,
    /// Working directory; `None` inherits the daemon's
    pub cwd: Option<PathBuf>,
    /// Environment variables, fully resolved (no daemon-env leakage beyond this map)
    pub env: BTreeMap<String, String>,
    /// File stdout is appended to
    pub out_file: PathBuf,
    /// File stderr is appended to
    pub err_file: PathBuf,
    /// Open the shepherd channel (fd 3 socketpair)
    pub channel: bool,
    /// Pipe the child's stdin, so `shep whisper` can write to it. `false`
    /// gives the child `/dev/null` on fd 0, which is what every sheep gets
    /// unless its config sets `stdin = true`.
    pub stdin: bool,
    /// Unix uid/gid to drop to before exec (`None` inherits the daemon's own
    /// identity). Resolved once per `Start` by `crate::privilege::resolve`;
    /// see that module for how `user`/`group` config names become this.
    pub credentials: Option<Credentials>,
}

/// Redacted: `env` and `args` both carry whatever the operator configured,
/// a resolved `{{secret:...}}` included, and this type is the one handed to
/// `Command::envs` at exec.
impl fmt::Debug for SpawnSpec {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SpawnSpec")
            .field("name", &self.name)
            .field("program", &self.program)
            .field("args", &format_args!("<{} args>", self.args.len()))
            .field("cwd", &self.cwd)
            .field("env", &format_args!("<{} vars>", self.env.len()))
            .finish_non_exhaustive()
    }
}

/// Whether `path` exists as a directory, in the one word a config-edit
/// warning appends after printing the path — but only when the filesystem
/// gives a definite answer.
///
/// [`cwd_advisory`] and [`log_path_advisory`] share this rather than each
/// re-deriving the same three-way match: a `cwd` has to be a directory
/// itself, and a log file's parent merely has to be one to hold it, so both
/// checks are this same question asked of a different path.
///
/// Only [`io::ErrorKind::NotFound`] and "exists but is a file" are
/// conclusive enough to report. A permission error or an unsettled mount
/// answers `None` rather than a guess, the same posture
/// `tokio_runner`'s `definitely_absent` documents for the identical
/// tradeoff: a false "missing" reads worse than the one real gap this
/// misses.
fn missing_directory(path: &Path) -> Option<&'static str> {
    match std::fs::metadata(path) {
        Ok(meta) if meta.is_dir() => None,
        Ok(_) => Some("exists but is not a directory"),
        Err(err) if err.kind() == io::ErrorKind::NotFound => Some("does not exist yet"),
        Err(_) => None,
    }
}

/// An operator-facing note that a `cwd` looks wrong on disk, checked when
/// the field is written rather than left to surface as the OS's own `No
/// such file or directory` at the next respawn.
///
/// Advisory, never a refusal: unlike a log file, `normalize` cannot
/// substitute an empty `cwd` for a bad one, and a directory a deploy script
/// has not created yet is a legitimate config this call cannot tell apart
/// from a typo. The check and the spawn it warns about are not atomic —
/// `check_log_ancestry`'s own doc comment names the identical window for
/// its check, and this one inherits the same gap (`docs/specs/deferred.md`).
#[must_use]
pub(crate) fn cwd_advisory(cwd: &Path) -> Option<String> {
    #[cfg(windows)]
    {
        if let Some(reason) = windows_name_advisory(cwd) {
            return Some(format!("{} {reason}", cwd.display()));
        }
    }
    let reason = missing_directory(cwd)?;
    Some(format!("{} {reason}", cwd.display()))
}

/// [`cwd_advisory`]'s counterpart for a log file rather than a working
/// directory: `out_file`/`err_file` are opened with `O_CREAT`, so the file
/// coming and going is normal and only its parent has to already be a
/// directory.
///
/// Also catches the file's own path already being a directory — a `cwd`
/// can never be that confusion in the other direction, since nothing
/// expects a file to sit there.
#[must_use]
pub(crate) fn log_path_advisory(path: &Path) -> Option<String> {
    #[cfg(windows)]
    {
        if let Some(reason) = windows_name_advisory(path) {
            return Some(format!("{} {reason}", path.display()));
        }
    }
    if matches!(std::fs::metadata(path), Ok(meta) if meta.is_dir()) {
        return Some(format!("{} is a directory, not a log file", path.display()));
    }
    let parent = path.parent().filter(|p| !p.as_os_str().is_empty())?;
    let reason = missing_directory(parent)?;
    Some(format!("{} {reason}", parent.display()))
}

/// Windows path restrictions no unix filesystem enforces, so nothing in
/// this crate checked them anywhere before this: a reserved device name, a
/// character the filesystem refuses in a path, or a full path at or over
/// the classic per-path limit.
///
/// Returns the reason alone, the same shape [`missing_directory`] returns,
/// so [`cwd_advisory`] and [`log_path_advisory`] can prefix either with the
/// path in one place rather than each formatting its own sentence.
///
/// `#[cfg(windows)]` only. Warning an operator on macOS or Linux that `CON`
/// is a reserved name would be noise: the restriction only exists where the
/// daemon evaluating it will actually resolve the path.
#[cfg(windows)]
#[must_use]
fn windows_name_advisory(path: &Path) -> Option<String> {
    use std::os::windows::ffi::OsStrExt as _;

    /// Characters no Windows filesystem accepts anywhere in a path.
    ///
    /// The printable half of the set. Windows refuses every control
    /// character below U+0020 too, which is handled separately because
    /// naming one in an advisory means printing its code point rather than
    /// the character.
    const ILLEGAL: &[char] = &['<', '>', ':', '"', '|', '?', '*'];
    /// Device names Windows reserves regardless of extension, compared
    /// case-insensitively against each path component's stem.
    const RESERVED: &[&str] = &[
        "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8",
        "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
    ];
    /// The classic `MAX_PATH` every Windows install still enforces unless an
    /// operator has opted into the long-path policy. That opt-in only
    /// widens what passes; it never refuses something this check accepts.
    ///
    /// `>=` rather than `>`, because the 260 counts the terminating null: a
    /// fully qualified path may be 259 units, so 260 is already over.
    /// Not measurable on the reference Windows host, which has
    /// `LongPathsEnabled` set to 1, so paths of 258 through 261 all wrote a
    /// file there. Anyone re-checking this on that box will get four passes
    /// and learn nothing about the boundary.
    const MAX_PATH: usize = 260;

    // `encode_wide`, not `OsStr::len`. Windows counts this limit in UTF-16
    // units and `len` returns WTF-8 bytes, which are only equal for ASCII.
    // `é` is two bytes and one unit, and an emoji is four bytes and two, so
    // `len` warns about paths Windows accepts: a 259-unit path of emoji
    // measures 518 by bytes and would be refused an advisory it never
    // earned.
    let length = path.as_os_str().encode_wide().count();
    if length >= MAX_PATH {
        return Some(format!(
            "is {length} characters, at or over Windows' {MAX_PATH}-character default limit"
        ));
    }
    for component in path.components() {
        let std::path::Component::Normal(part) = component else {
            // `Prefix` (`C:`) and the rest name no file of their own; only
            // a `Normal` segment can be `CON.txt` or carry a stray `?`.
            continue;
        };
        let Some(name) = part.to_str() else {
            continue;
        };
        if let Some(bad) = name.chars().find(|c| ILLEGAL.contains(c)) {
            return Some(format!("contains `{bad}`, which Windows refuses in a path"));
        }
        // Below U+0020 only, which is the range Windows documents. Not
        // `char::is_control`, which also matches U+007F and the C1 block
        // U+0080 to U+009F: those are legal in a Windows file name, so
        // warning about them would refuse a path the filesystem accepts,
        // the same way counting bytes did above.
        //
        // Named by code point, not printed. A tab or a newline reaching an
        // advisory would otherwise rearrange the operator's line rather
        // than appear in it, and a NUL would truncate it.
        if let Some(control) = name.chars().find(|&c| (c as u32) < 0x20) {
            return Some(format!(
                "contains U+{:04X}, a control character Windows refuses in a path",
                control as u32
            ));
        }
        // Up to the LAST dot, not the first. Measured on Windows 2026-09-12
        // by creating each name and asking whether a file appeared:
        // `CON.txt` did not (the device took it), `CON.my.txt` did, and so
        // did `NUL.my.log`. Splitting on the first dot would warn about
        // `CON.my.txt`, which is an ordinary file.
        let stem = name.rsplit_once('.').map_or(name, |(stem, _)| stem);
        if RESERVED
            .iter()
            .any(|reserved| reserved.eq_ignore_ascii_case(stem))
        {
            return Some(format!("names `{name}`, a reserved Windows device name"));
        }
    }
    None
}

/// Error type returned from spawn and process control
///
/// `#[non_exhaustive]`: a future process-control primitive, a cgroup freeze
/// or a Windows job-object failure, would need its own variant rather than
/// stretching one of these, and an out-of-tree matcher should not break.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RunnerError {
    /// The OS refused the spawn (exec failure, permissions, missing binary)
    SpawnFailed(String),
    /// Signal delivery failed (already reaped, `EPERM`)
    SignalFailed(String),
    /// A write to a child's stdin failed (carries the OS message, or the
    /// shepherd's own bound when the app was not reading).
    WriteFailed(String),
    /// A sheep inherited across a handover could not be taken back under
    /// supervision: this runner does not adopt at all, or the carried
    /// handles could not be wired to a pump.
    AdoptFailed(String),
}

impl fmt::Display for RunnerError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::SpawnFailed(msg) => write!(f, "process spawn failed: {msg}"),
            Self::SignalFailed(msg) => write!(f, "signal delivery failed: {msg}"),
            Self::WriteFailed(msg) => write!(f, "stdin write failed: {msg}"),
            Self::AdoptFailed(msg) => write!(f, "process adoption failed: {msg}"),
        }
    }
}

impl core::error::Error for RunnerError {}

// Every case here is `#[cfg(unix)]`, as is everything they exercise: the uid
// model `loose_ancestor` reads, the mode bits it tests, and
// `std::os::unix::fs::symlink`.
#[cfg(all(test, unix))]
mod tests {
    use std::os::unix::fs::PermissionsExt as _;

    use super::*;
    use crate::testing::capture_logs;

    /// A uid no fixture in this module creates anything as. Only reached on
    /// a root test runner, where everything created is root-owned and root is
    /// exempt by construction.
    const FOREIGN_UID: u32 = 65_432;

    /// This process's effective uid: what every fixture directory is owned
    /// by, and what the cases move the daemon's uid relative to.
    fn me() -> u32 {
        nix::unistd::geteuid().as_raw()
    }

    /// A log path two components below `dir`, with its parent created and
    /// left at `mode`.
    fn log_path_under(dir: &tempfile::TempDir, mode: u32) -> (PathBuf, PathBuf) {
        let parent = dir.path().join("logs");
        std::fs::create_dir(&parent).unwrap();
        std::fs::set_permissions(&parent, std::fs::Permissions::from_mode(mode)).unwrap();
        let log = parent.join("web-0-out.log");
        (parent, log)
    }

    /// Also the only case pinning the world-writable arm on its own: drop
    /// that arm and this reddens with `None` while the ownership cases below
    /// stay green.
    #[test]
    fn the_nearest_loose_ancestor_is_the_one_reported() {
        let dir = tempfile::tempdir().unwrap();
        let (parent, log) = log_path_under(&dir, 0o777);

        assert_eq!(
            loose_ancestor(&log, me()),
            Some(LooseAncestor {
                path: parent,
                reason: LooseReason::WorldWritable,
            })
        );
    }

    /// The parent is `0700`, so a write-bit-only check waves it through,
    /// while its owner can still replace it under a root shepherd.
    #[test]
    fn an_ancestor_owned_by_another_user_is_loose_however_tight_its_mode() {
        let dir = tempfile::tempdir().unwrap();
        let (parent, log) = log_path_under(&dir, 0o700);

        // The predicate is symmetric in the two uids, so an unprivileged
        // runner moves the daemon's rather than the directory's; it cannot
        // chown. A root runner must move the directory's: root is exempt
        // whatever the daemon's uid is.
        let (daemon_uid, owner) = if me() == ROOT_UID {
            std::os::unix::fs::chown(&parent, Some(FOREIGN_UID), None).unwrap();
            (ROOT_UID, FOREIGN_UID)
        } else {
            (me() + 1, me())
        };

        assert_eq!(
            loose_ancestor(&log, daemon_uid),
            Some(LooseAncestor {
                path: parent,
                reason: LooseReason::ForeignOwner(owner),
            })
        );
    }

    /// The link is owned by this user and points at a root-owned, tight
    /// directory, so following it blames the tempdir instead. Only the path
    /// in the answer tells the two apart. This is the case `O_NOFOLLOW`
    /// cannot cover: the redirect is one level up.
    #[test]
    fn a_symlinked_component_is_judged_as_the_link_not_as_its_target() {
        let dir = tempfile::tempdir().unwrap();
        let link = dir.path().join("logs");
        // `/usr` exists and is root-owned `0755` on both tier-1 platforms,
        // an ancestor the walk would wave through if it followed the link.
        std::os::unix::fs::symlink("/usr", &link).unwrap();
        let log = link.join("web-0-out.log");

        let loose = loose_ancestor(&log, me() + 1).expect("a foreign-owned component is loose");
        assert_eq!(
            loose.path,
            link,
            "the link itself must be judged, not what it resolves to: blaming {} means the \
             walk followed it",
            loose.path.display()
        );
    }

    /// Refusing everywhere would break a developer logging to `/tmp` as
    /// themselves; warning everywhere would leave the root case exiting zero.
    ///
    /// The warn-once half rides along because it is the same call: a count of
    /// two means the dedup set is gone.
    #[test]
    fn a_root_shepherd_refuses_where_an_unprivileged_one_warns_once() {
        let dir = tempfile::tempdir().unwrap();
        let (parent, log) = log_path_under(&dir, 0o777);

        let refused = check_log_ancestry_as(&log, ROOT_UID)
            .expect_err("a root shepherd must not open a log below a loose ancestor");
        assert_eq!(refused.kind(), io::ErrorKind::PermissionDenied);
        assert!(
            refused.to_string().contains(&parent.display().to_string()),
            "the refusal must name the ancestor an operator has to fix: {refused}"
        );

        // Never `me()`: a root test runner would take the arm above.
        // `me() + 1` is non-root by construction and owns nothing here.
        let unprivileged = me() + 1;
        let rendered = capture_logs(|| {
            assert_eq!(check_log_ancestry_as(&log, unprivileged).ok(), Some(()));
            assert_eq!(check_log_ancestry_as(&log, unprivileged).ok(), Some(()));
        });
        assert_eq!(
            rendered.matches("log path sits below").count(),
            1,
            "an unprivileged shepherd warns once per path, not once per open: {rendered}"
        );
    }

    /// This type sits on the exec boundary, so a `tracing` call that
    /// formatted it would put every configured secret in the daemon's log.
    /// `args` counts as much as `env` now that a `{{secret:...}}` resolves
    /// into it: `--token=<value>` on an argv is a value the same way
    /// `TOKEN=<value>` on an environment is. Exact string pinned so a
    /// `derive(Debug)` refactor fails here (IR-41).
    #[test]
    fn debug_redacts_env_values_and_args() {
        let mut spec = SpawnSpec {
            name: "web".to_string(),
            program: "./srv".to_string(),
            args: vec!["--token=sk-live-abc".to_string(), "--port=8080".to_string()],
            cwd: None,
            env: BTreeMap::new(),
            out_file: PathBuf::from("/tmp/web-out.log"),
            err_file: PathBuf::from("/tmp/web-err.log"),
            channel: false,
            stdin: false,
            credentials: None,
        };
        spec.env.insert(
            "DATABASE_URL".to_string(),
            "postgres://user:hunter2@db".to_string(),
        );
        spec.env
            .insert("API_KEY".to_string(), "sk-live-abc".to_string());

        assert_eq!(
            format!("{spec:?}"),
            "SpawnSpec { name: \"web\", program: \"./srv\", args: <2 args>, cwd: None, \
             env: <2 vars>, .. }"
        );
    }
}

/// Unlike the module above, these run on every platform this crate ships
/// on: `cwd_advisory` and `log_path_advisory` read nothing platform-specific
/// except through `windows_name_advisory`, which gets its own module below.
#[cfg(test)]
mod path_advisory_tests {
    use super::*;

    #[test]
    fn a_cwd_that_exists_gets_no_warning() {
        let dir = tempfile::tempdir().unwrap();
        assert_eq!(cwd_advisory(dir.path()), None);
    }

    #[test]
    fn a_cwd_that_does_not_exist_yet_is_named() {
        let dir = tempfile::tempdir().unwrap();
        let missing = dir.path().join("not-created-yet");
        let warning = cwd_advisory(&missing).expect("a missing cwd warns");
        assert!(warning.contains("does not exist"), "{warning}");
        assert!(
            warning.contains(&missing.display().to_string()),
            "names the path: {warning}"
        );
    }

    #[test]
    fn a_cwd_that_is_a_file_is_named() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("not-a-dir");
        std::fs::write(&file, b"").unwrap();
        let warning = cwd_advisory(&file).expect("a file where a directory is meant warns");
        assert!(warning.contains("is not a directory"), "{warning}");
    }

    #[test]
    fn a_log_path_whose_parent_exists_gets_no_warning() {
        let dir = tempfile::tempdir().unwrap();
        let log = dir.path().join("web-out.log");
        assert_eq!(
            log_path_advisory(&log),
            None,
            "the file itself need not exist yet; `open_log_path` creates it"
        );
    }

    #[test]
    fn a_log_path_whose_parent_does_not_exist_yet_is_named() {
        let dir = tempfile::tempdir().unwrap();
        let log = dir.path().join("not-created-yet").join("web-out.log");
        let warning = log_path_advisory(&log).expect("a missing parent warns");
        assert!(warning.contains("does not exist"), "{warning}");
    }

    /// The `Ok(_)` arm of [`missing_directory`], reached through the parent
    /// rather than through the path itself. A sibling test covers the path
    /// BEING a directory; this covers its parent being an ordinary file,
    /// which is the likelier misconfiguration: an operator points `out_file`
    /// at `<something>/web.log` where `<something>` is already a file.
    #[test]
    fn a_log_path_whose_parent_is_a_file_is_named() {
        let dir = tempfile::tempdir().unwrap();
        let parent = dir.path().join("not-a-directory");
        std::fs::write(&parent, b"").unwrap();
        let warning =
            log_path_advisory(&parent.join("web-out.log")).expect("a parent that is a file warns");
        assert!(
            warning.contains("exists but is not a directory"),
            "{warning}"
        );
    }

    #[test]
    fn a_log_path_that_is_already_a_directory_is_named() {
        let dir = tempfile::tempdir().unwrap();
        let warning =
            log_path_advisory(dir.path()).expect("a directory where a file is meant warns");
        assert!(
            warning.contains("is a directory, not a log file"),
            "{warning}"
        );
    }
}

/// `windows_name_advisory` only compiles under `cfg(windows)`, so its tests
/// only run on the `windows-latest` leg of the test matrix — the one place
/// the restrictions it checks are real.
#[cfg(all(test, windows))]
mod windows_advisory_tests {
    use super::*;

    #[test]
    fn a_reserved_device_name_is_named_regardless_of_extension() {
        let warning = windows_name_advisory(Path::new(r"C:\logs\CON.log"))
            .expect("CON is reserved regardless of extension");
        assert!(
            warning.contains("reserved Windows device name"),
            "{warning}"
        );
    }

    /// fails if the stem is taken up to the first dot again. Measured on
    /// Windows 2026-09-12: writing `CON.txt` created no file, the device
    /// swallowed it, while `CON.my.txt` and `NUL.my.log` both created
    /// ordinary files. So a second dot takes the name back out of the
    /// reserved set, and warning about it would be a false alarm on a path
    /// that works.
    #[test]
    fn a_second_dot_takes_a_name_back_out_of_the_reserved_set() {
        assert_eq!(
            windows_name_advisory(Path::new(r"C:\logs\CON.my.txt")),
            None,
            "CON.my is not a device name"
        );
        assert_eq!(
            windows_name_advisory(Path::new(r"C:\logs\NUL.my.log")),
            None,
            "NUL.my is not a device name"
        );
        assert!(
            windows_name_advisory(Path::new(r"C:\logs\CON.txt")).is_some(),
            "one dot still leaves CON reserved"
        );
    }

    /// fails if the length is taken in bytes again. Windows counts this
    /// limit in UTF-16 units and the two agree only for ASCII, so a
    /// non-BMP path sits either side of the limit depending on which is
    /// counted.
    #[test]
    fn the_path_limit_counts_utf16_units_not_bytes() {
        let under = format!(r"C:\logs\{}.log", "\u{1f411}".repeat(120));
        assert_eq!(
            windows_name_advisory(Path::new(&under)),
            None,
            "252 units is under the limit, though the same path is 492 bytes"
        );

        let over = format!(r"C:\logs\{}.log", "\u{1f411}".repeat(130));
        let warning = windows_name_advisory(Path::new(&over)).expect("260 units is at the limit");
        assert!(warning.contains("260-character"), "{warning}");
    }

    /// fails if the control range widens to `char::is_control`. A tab is
    /// refused by Windows and U+0085 is not, so a check that cannot tell
    /// them apart refuses a path the filesystem accepts.
    #[test]
    fn a_control_character_is_named_by_code_point_and_c1_is_not() {
        let warning = windows_name_advisory(Path::new("C:\\logs\\web\tout.log"))
            .expect("a tab is refused anywhere in a Windows path");
        assert!(warning.contains("U+0009"), "{warning}");
        // Printed as a code point, or the advisory would carry the tab
        // itself and rearrange the operator's line.
        assert!(!warning.contains('\t'), "{warning}");

        assert_eq!(
            windows_name_advisory(Path::new("C:\\logs\\web\u{85}out.log")),
            None,
            "U+0085 is a C1 control that Windows accepts in a file name"
        );
    }

    #[test]
    fn an_ordinary_path_gets_no_warning() {
        assert_eq!(
            windows_name_advisory(Path::new(r"C:\logs\web-out.log")),
            None
        );
    }

    #[test]
    fn an_illegal_character_is_named() {
        let warning = windows_name_advisory(Path::new(r"C:\logs\web?out.log"))
            .expect("`?` is refused anywhere in a Windows path");
        assert!(warning.contains('?'), "{warning}");
    }

    #[test]
    fn an_over_length_path_is_named() {
        let long = format!(r"C:\{}", "a".repeat(300));
        let warning =
            windows_name_advisory(Path::new(&long)).expect("300 characters is over MAX_PATH");
        assert!(warning.contains("260-character"), "{warning}");
    }
}