Skip to main content

shep_core/protocol/
request.rs

1//! RPC frames: requests, responses, envelopes, and structured errors
2
3use core::fmt;
4
5use serde::{Deserialize, Deserializer, Serialize};
6
7use crate::config::{AppConfig, DeclaredApp, ResetDepth};
8use crate::status::ProcStatus;
9
10/// Client's opening frame
11// wire format: changing this is a breaking change
12#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
13pub struct Hello {
14    /// Client crate version (semver string)
15    pub client_version: String,
16    /// [`crate::protocol::PROTOCOL_VERSION`] the client speaks
17    pub protocol: u32,
18    /// The name this client was registered under as a dog, when it is one.
19    ///
20    /// `None` is what every other client truthfully is, and what a dog built
21    /// before this field existed sends. The CLI never sets it: a bare
22    /// `Client` has no way to, by construction, so `shep stop` cannot
23    /// impersonate a dog however its environment is set.
24    ///
25    /// The daemon needs it on exactly one path, and it is the path where
26    /// nothing else can supply it. A handshake refused for protocol skew
27    /// never reaches a request, so `Request::DogConfig`'s name — the one
28    /// place a dog otherwise identifies itself — is unreachable precisely
29    /// when the daemon has to know WHICH dog it just refused in order to
30    /// restart it (the handover design's G8). A dog already knows its own
31    /// name: the daemon put it in `$SHEP_DOG_NAME` when it spawned it.
32    ///
33    /// Additive by construction: absent on the wire rather than `null`, and
34    /// ignored by a daemon too old to know it, so
35    /// [`crate::protocol::PROTOCOL_VERSION`] does not move for it. That
36    /// argument deserves more care here than anywhere else, because `Hello`
37    /// IS the version-negotiation frame: a daemon that rejected unknown
38    /// fields would refuse a newer client BEFORE reading `protocol`, and
39    /// that would be a hard break rather than an additive change. It does
40    /// not — this type carries no `#[serde(deny_unknown_fields)]`, and
41    /// `a_hello_without_a_dog_name_still_parses` pins both directions.
42    #[serde(default, skip_serializing_if = "Option::is_none")]
43    pub dog_name: Option<String>,
44}
45
46/// Daemon's handshake answer
47// wire format: changing this is a breaking change
48#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
49pub struct HelloAck {
50    /// Daemon crate version
51    pub daemon_version: String,
52    /// Protocol version the daemon speaks
53    pub protocol: u32,
54    /// Daemon pid
55    pub pid: u32,
56}
57
58/// Serializable selector (mirror of [`crate::selector::ProcessSelector`];
59/// regex travels as its source string)
60// wire format: changing this is a breaking change
61#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
62#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
63pub enum SelectorSpec {
64    /// Every sheep
65    All,
66    /// By id
67    Id(u32),
68    /// By exact name
69    Name(String),
70    /// By regex source
71    Regex(String),
72    /// By fold name
73    Fold(String),
74    // Both field names are part of the wire contract, and the byte shape is
75    // pinned by `request_wire_v2`, so renaming either breaks that snapshot
76    // rather than sliding through unnoticed.
77    /// By app name and instance slot
78    ///
79    /// Added in protocol 2, and the reason that version exists: a daemon
80    /// built against protocol 1 has no such variant and refuses a client
81    /// that sends one at the handshake, rather than failing to decode it
82    /// later. On the wire this is `{"kind":"instance","value":{"name":
83    /// "web","slot":2}}`, following the enum's own `kind`/`value` tagging.
84    Instance {
85        /// The app name
86        name: String,
87        /// The instance slot, counting from 0
88        slot: u32,
89    },
90}
91
92/// A short marker a dog attaches to a sheep for `shep flock` to paint.
93///
94/// shep stores one and prints it. It does not parse it, has no opinion about
95/// what it means, and never will: `▲ main@a1b2c3` is a deploy tool's
96/// sentence, not shep's, and keeping it that way is what makes this a general
97/// mechanism rather than one feature's field.
98///
99/// # The rule
100///
101/// A smit is non-empty once whitespace is discounted, at most
102/// [`Self::MAX_CHARS`] characters, and carries no [`char::is_control`]
103/// character — `\u{1b}` included, which `is_control` already covers and which
104/// is named separately in this doc anyway, because it is the one an attacker
105/// reaches for and a reader should not have to know the classification to see
106/// that it is handled.
107///
108/// Refused, never repaired. The text is stored exactly as it arrived: shep
109/// does not trim it, strip from it, or otherwise hand back something the
110/// publisher did not send. `crate::kv`'s key grammar and value cap set the
111/// same precedent for the same kind of value, and the publisher here is a
112/// program, so a refusal it can see and fix beats mangling it cannot.
113///
114/// # Why the cap counts characters
115///
116/// [`Self::MAX_CHARS`] is a count of `char`s, not of bytes and not of display
117/// columns. Bytes would refuse a legitimate CJK smit at roughly a third of
118/// its apparent length. Display columns are what a table renderer measures,
119/// but they depend on the terminal and on a width table this parser has no
120/// business carrying. Characters are the honest thing a validator can promise
121/// cheaply. 48 is measured against the reference smit `▲ main@a1b2c3` at
122/// thirteen: room for a long branch name, without letting one column swallow
123/// the table.
124///
125/// # Why validation lives here rather than at the renderer
126///
127/// `shep`'s own `output::width::sanitize_cell` deliberately KEEPS a
128/// well-formed CSI sequence, because shep's colouring is made of them, so it
129/// is not a guard against a third party's string. Refusing here means `shep
130/// flock`, `shep describe`, `--format json`, the lookout, the MCP tool schema
131/// and every bus subscriber are safe by construction instead of six places
132/// each remembering.
133///
134/// `Debug` is derived, and that is the deliberate decision (IR-41): a smit
135/// carries no environment and no secret. It is a string a dog asked to have
136/// painted in public, so redacting it would hide the thing an operator is
137/// debugging.
138///
139/// # Example
140/// ```
141/// use shep_core::protocol::Smit;
142///
143/// assert_eq!("▲ main@a1b2c3".parse::<Smit>()?.as_str(), "▲ main@a1b2c3");
144/// assert!("\u{1b}[2Jgone".parse::<Smit>().is_err()); // no escapes
145/// # Ok::<(), shep_core::protocol::SmitError>(())
146/// ```
147// wire format: changing this is a breaking change
148#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
149pub struct Smit(String);
150
151impl Smit {
152    /// The longest a smit may be, in characters. See the type doc for why
153    /// characters rather than bytes or display columns.
154    pub const MAX_CHARS: usize = 48;
155
156    /// The marker as text, exactly as its publisher sent it.
157    #[must_use]
158    pub fn as_str(&self) -> &str {
159        &self.0
160    }
161}
162
163impl fmt::Display for Smit {
164    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
165        f.write_str(&self.0)
166    }
167}
168
169impl core::str::FromStr for Smit {
170    type Err = SmitError;
171
172    /// # Errors
173    /// - [`SmitError::Empty`] — nothing but whitespace.
174    /// - [`SmitError::TooLong`] — over [`Self::MAX_CHARS`] characters.
175    /// - [`SmitError::Unprintable`] — a control character, `\u{1b}` included.
176    fn from_str(text: &str) -> Result<Self, Self::Err> {
177        if text.trim().is_empty() {
178            return Err(SmitError::Empty);
179        }
180        let chars = text.chars().count();
181        if chars > Self::MAX_CHARS {
182            return Err(SmitError::TooLong { chars });
183        }
184        if text.chars().any(char::is_control) {
185            return Err(SmitError::Unprintable);
186        }
187        Ok(Self(text.to_string()))
188    }
189}
190
191/// Hand-written rather than derived, and that is the whole security property.
192///
193/// A derived impl would accept anything a `String` accepts, so a smit
194/// carrying `\u{1b}[2J` would reach the daemon's memory and every listing
195/// built from it. `docs/dogs.md` tells dog authors to speak this wire
196/// directly, so a dog written in another language never runs
197/// [`core::str::FromStr`] — the daemon has to validate what it decodes, not
198/// trust that it was constructed properly.
199impl<'de> Deserialize<'de> for Smit {
200    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
201        // String, not &str: a non-borrowing deserializer cannot always borrow
202        let text = String::deserialize(deserializer)?;
203        text.parse().map_err(serde::de::Error::custom)
204    }
205}
206
207/// Why a string is not a [`Smit`].
208///
209/// `#[non_exhaustive]`: shep-core is a published library and a further
210/// refusal — a grapheme-cluster cap, say, or a bidi-override rule — must not
211/// break an out-of-tree consumer's `match` (IR-20).
212#[non_exhaustive]
213#[derive(Debug, Clone, Copy, PartialEq, Eq)]
214pub enum SmitError {
215    /// Over [`Smit::MAX_CHARS`] characters; carries the count that was sent.
216    TooLong {
217        /// How many characters the string held.
218        chars: usize,
219    },
220    /// A control character, `\u{1b}` included — the sequence that would let a
221    /// third party's string drive an operator's terminal.
222    Unprintable,
223    /// Empty, or nothing but whitespace.
224    Empty,
225}
226
227impl fmt::Display for SmitError {
228    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
229        match self {
230            Self::TooLong { chars } => write!(
231                f,
232                "a smit is at most {} characters; this one is {chars}",
233                Smit::MAX_CHARS
234            ),
235            Self::Unprintable => {
236                f.write_str("a smit may not contain a control character, an escape included")
237            }
238            Self::Empty => f.write_str("a smit may not be empty"),
239        }
240    }
241}
242
243impl core::error::Error for SmitError {}
244
245/// One RPC request
246// wire format: changing existing variants is a breaking change
247#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
248#[serde(tag = "kind", rename_all = "snake_case")]
249#[non_exhaustive]
250pub enum Request {
251    /// Liveness check
252    Ping,
253    /// Full flock listing
254    ListFlock,
255    /// Detailed info for matching sheep
256    Describe {
257        /// Which sheep
258        selector: SelectorSpec,
259    },
260    /// Register + start apps
261    Start {
262        /// App configs — the daemon MUST re-normalize (peer input is
263        /// untrusted); failures return [`RpcErrorCode::InvalidConfig`]
264        apps: Vec<AppConfig>,
265    },
266    /// Ask which of `apps` name a sheep the flock already has under a
267    /// different config
268    ///
269    /// Read-only: nothing is registered, started, or changed. [`Self::Start`]
270    /// on an already-registered name adds instances rather than reconciling
271    /// config, which is what `shep stock` relies on; this is how a caller
272    /// finds out that an edit it just read from a Flockfile is one `Start`
273    /// will not apply, instead of the edit vanishing without a word.
274    ///
275    /// Answers [`Response::Drifted`] with one [`SheepDrift`] per app that is
276    /// both registered and different. An app the flock does not have is
277    /// absent from the answer, not reported as unchanged: `Start` will
278    /// register it, so there is nothing to warn about.
279    ConfigDrift {
280        /// The configs to compare against, exactly as [`Self::Start`] would
281        /// carry them. The daemon MUST re-normalize (peer input is
282        /// untrusted, and an unnormalized config would report every default
283        /// it has not spelled out as a difference); failures return
284        /// [`RpcErrorCode::InvalidConfig`].
285        apps: Vec<AppConfig>,
286    },
287    /// Merge each declared app into the sheep of the same name, applying
288    /// what can be applied and parking the rest for that sheep's next spawn
289    ///
290    /// The acting half of [`Self::ConfigDrift`], which only reports. Nothing
291    /// is registered, nothing is pruned and nothing running is killed: an app
292    /// the flock does not have is refused by name rather than started, and a
293    /// field the running child was spawned from waits for a `shep reload`
294    /// instead of taking one.
295    ///
296    /// Additive by default, which is what `reset` exists to widen. A
297    /// Flockfile arrives from the app's own repository, so a load appends
298    /// what nobody has established and leaves everything an operator set
299    /// since alone.
300    ///
301    /// Answers [`Response::Applied`] with one [`SheepApplied`] per entry in
302    /// `apps`, in the order given, whether or not the app was found and
303    /// whether or not anything changed. One app that cannot be applied does
304    /// not cost the rest of the file its load; its refusal rides in
305    /// [`SheepApplied::refused`].
306    ApplyConfig {
307        /// The apps to merge in, each carrying the keys its document
308        /// literally wrote. The daemon MUST re-normalize the merge result
309        /// (peer input is untrusted) and refuses the whole request with
310        /// [`RpcErrorCode::InvalidConfig`] when two entries share a name:
311        /// the second would be merged against a store the first has not
312        /// written yet, so its record would be the one that survives.
313        apps: Vec<DeclaredApp>,
314        /// How much of what the operator has set since a template last
315        /// loaded this request may overwrite. Default
316        /// [`ResetDepth::None`], which overwrites nothing.
317        reset: ResetDepth,
318    },
319    /// Stop matching sheep (stay registered)
320    Stop {
321        /// Which sheep
322        selector: SelectorSpec,
323    },
324    /// Restart matching sheep
325    Restart {
326        /// Which sheep
327        selector: SelectorSpec,
328    },
329    /// Replace each matching sheep with a fresh instance of the same app, one
330    /// instance of an app at a time, so the app has a window in which it can
331    /// stay reachable across the swap
332    Reload {
333        /// Which sheep. No default anywhere in the stack — a reload replaces
334        /// running processes, so the operator names the target, exactly as
335        /// `stop`/`restart`/`delete` do (see `shep reload`).
336        selector: SelectorSpec,
337    },
338    /// Stop + deregister matching sheep
339    Delete {
340        /// Which sheep
341        selector: SelectorSpec,
342    },
343    /// Set how many instances one app runs (see `shep stock`).
344    ///
345    /// # Why a name and not a selector
346    ///
347    /// Every other verb here takes a [`SelectorSpec`], and this one
348    /// deliberately does not. `instances` is a per-app number and instance
349    /// slots are allocated against the same-name group
350    /// (`shep_daemon::assemble::instance_slots`), so a selector matching two
351    /// apps would have to mean either "four of each" or "four in total", and
352    /// neither reading is more obviously right than the other. A name has one
353    /// meaning.
354    ///
355    /// # Why absolute and not a delta
356    ///
357    /// There is no `+N`/`-N` form and there will not be one. An absolute count
358    /// is idempotent — run it twice, get the same flock — where two operators
359    /// sending `+2` against the same app get a number neither of them asked
360    /// for. This project's own trace notes also record a crash on pm2's
361    /// relative-remove path, and those notes exist so shep does not reproduce
362    /// what they record.
363    Scale {
364        /// The app's name, exactly as its config spells it. Not a selector: no
365        /// `all`, no regex, no `fold:`.
366        name: String,
367        /// How many instances the app has when this returns. `0` is refused
368        /// with [`RpcErrorCode::InvalidConfig`] — `normalize` rejects
369        /// `instances == 0` for every other path into the daemon, and `shep
370        /// delete` is the verb for removing an app.
371        count: u32,
372    },
373    /// Attach a short marker to `sheep` for `shep flock` to paint, or clear
374    /// it with `None`.
375    ///
376    /// By NAME rather than a selector, for [`Self::Scale`]'s reason (see its
377    /// own doc above): a smit belongs to a sheep, not to one of its
378    /// instances, and every instance of that name shows it — including one
379    /// spawned after the smit was painted.
380    ///
381    /// Held in memory and scoped to the connection that sent it. When that
382    /// connection closes, for any reason, the smits it painted go with it. A
383    /// publisher therefore republishes rather than publishing on change.
384    ///
385    /// shep does not parse it and has no opinion about what it means.
386    SetSmit {
387        /// Which sheep.
388        sheep: String,
389        /// The marker, or `None` to clear it.
390        smit: Option<Smit>,
391    },
392    /// Reopen every matched sheep's log files, for an external rotator that
393    /// has renamed them (`create`-mode rotation)
394    Reopen {
395        /// Which sheep
396        selector: SelectorSpec,
397    },
398    /// Empty every matched sheep's log files: flush what is still pending,
399    /// then truncate the recorded paths
400    Flush {
401        /// Which sheep. No default anywhere in the stack — this destroys
402        /// log data, so the operator names the target (see `shep flush`).
403        selector: SelectorSpec,
404    },
405    /// Send a named action to every matched sheep over its shepherd channel
406    /// and report what each app says back (see `shep trigger`).
407    Trigger {
408        /// Which sheep. No default anywhere in the stack, matching
409        /// `stop`/`restart`/`reload`/`delete`/`flush`: an operator names the
410        /// target rather than trigger an action against the whole flock by
411        /// accident.
412        selector: SelectorSpec,
413        /// The action name. Free-form — the daemon never declares, parses,
414        /// or validates it; an app that does not recognize the name is
415        /// expected to say so in its own reply rather than stay silent.
416        action: String,
417        /// Argument text for the action, passed through to the app
418        /// verbatim. One opaque string, not structured data: the daemon
419        /// holds no schema for it, matching the shepherd channel's own
420        /// `action` message this ultimately becomes.
421        params: Option<String>,
422    },
423    /// Deliver one signal to every matched sheep's OWN process — never its
424    /// process group (see `shep signal`).
425    Signal {
426        /// Which sheep. No default anywhere in the stack, matching every
427        /// other verb that reaches a running process: an operator names the
428        /// target rather than signal the whole flock by accident.
429        selector: SelectorSpec,
430        /// The signal's name, as
431        /// [`OperatorSignal`](crate::signals::OperatorSignal) spells it — the
432        /// `SIG` prefix and the case are both optional.
433        ///
434        /// A `String` rather than the enum, for the reason
435        /// [`AppConfig::kill_signal`](crate::config::AppConfig::kill_signal)
436        /// is one: the wire stays plain text a person can read in a capture,
437        /// and the daemon re-validates regardless, because peer input is
438        /// untrusted. A name outside the grammar answers
439        /// [`RpcErrorCode::InvalidConfig`].
440        signal: String,
441    },
442    /// Write one line to every matched sheep's stdin (see `shep whisper`).
443    SendLine {
444        /// Which sheep. No default, matching every other verb that reaches a
445        /// running process.
446        selector: SelectorSpec,
447        /// The line, WITHOUT its terminator — the shepherd appends exactly one
448        /// `\n` when it writes. Carrying the terminator here would leave "did
449        /// the caller include one" as a question every hop has to re-answer,
450        /// and a caller that included two would send an empty line the app
451        /// never asked for.
452        ///
453        /// A line containing an embedded newline is refused
454        /// ([`RpcErrorCode::InvalidConfig`]): it would deliver two commands
455        /// where the operator typed one.
456        line: String,
457    },
458    /// Write the muster roll now, bypassing the snapshot writer's debounce
459    SaveRoll,
460    /// Assemble the flock from the muster roll on disk: start every app the
461    /// roll recorded running, leaving every app the flock already has exactly
462    /// as it stands
463    Muster,
464    /// Ask for one dog's `[dog.<name>]` section, as the dog itself parses it
465    DogConfig {
466        /// The dog's name — the config key, not a selector
467        name: String,
468    },
469    /// Start one dog now, marking it as coming from `source`
470    EnableDog {
471        /// The dog's name
472        name: String,
473        /// Where its binary comes from
474        source: DogSource,
475    },
476    /// Stop and deregister one dog
477    ///
478    /// Answers [`Response::Deleted`], the same reply `Delete` gives: disabling
479    /// deregisters exactly as `Delete` does, so this is the same fact and not
480    /// a coincidence of shape. A variant of its own (`DogDisabled`, say) would
481    /// carry nothing `Deleted` does not.
482    DisableDog {
483        /// The dog's name
484        name: String,
485    },
486    /// Ask which dogs this daemon has given up on, and which it is still
487    /// waiting to hear from (`shep daemon reload`, the handover design's
488    /// G13).
489    ///
490    /// Read-only, and about THIS daemon's own handshakes. A dog's recorded
491    /// crate version describes the process that was running when it
492    /// connected, so it says nothing about a dog that has since been
493    /// replaced; the only thing that knows whether a dog can talk to this
494    /// daemon is whether this daemon accepted its handshake. That is what
495    /// this answers, which is why the reading is worth taking AFTER a
496    /// reload rather than before one.
497    ///
498    /// Answers [`Response::DogStaleness`].
499    ///
500    /// # Why this variant does not move `PROTOCOL_VERSION`
501    ///
502    /// The same argument [`Self::HandoverFitness`] makes above, and the
503    /// same gate enforces it: its only caller is `shep daemon reload`, which
504    /// asks it of the successor it has just proven is running this binary's
505    /// own version. An older daemon is never sent it.
506    DogStaleness,
507    /// Ask whether this daemon could hand its flock to a successor in place,
508    /// rather than stopping it and starting it again (`shep daemon reload`).
509    ///
510    /// Read-only, and nothing here triggers a handover. The trigger is a
511    /// signal and always was: a socket request cannot be the trigger, because
512    /// the case that most needs a reload is the one where the daemon refuses
513    /// the client at the handshake. What travels over the socket is the
514    /// DECISION, for a reason a signal cannot serve (spec H3a) -- a signal
515    /// carries no reply, so a daemon that took one, refused, and fell back to
516    /// its own graceful stop would leave the client polling for a successor
517    /// nobody started, with the flock down and staying down.
518    ///
519    /// Answers [`Response::HandoverFitness`]. Every refusal is a feature the
520    /// running daemon cannot yet carry, not an error: the caller falls back
521    /// to a stop-and-start, which is correct behaviour rather than a degraded
522    /// one, and prints the reason to the operator who asked for the reload.
523    ///
524    /// # Why this variant does not move `PROTOCOL_VERSION`
525    ///
526    /// An older daemon cannot deserialize a variant it has never seen, which
527    /// is normally what a bump is for. It is never sent to one. `daemon
528    /// reload` is an exempt verb, so it connects to a mismatched daemon
529    /// deliberately, learns the daemon's crate version from the handshake,
530    /// and takes the stop arm for anything predating the handover without
531    /// ever asking. shep-cli's `commands::daemon` holds that gate and a test
532    /// of its own pins it.
533    HandoverFitness,
534    /// Graceful daemon shutdown
535    KillDaemon,
536    /// Subscribe this connection to bus topics (glob patterns)
537    Subscribe {
538        /// Topic globs, e.g. `process.*`
539        topics: Vec<String>,
540    },
541}
542
543/// Where a dog came from: this binary, or one an operator adopted.
544///
545/// The one thing an operator wants when a dog misbehaves, which is why it
546/// is a column rather than a detail. Carried on [`ProcessInfo::dog`], so a
547/// listing distinguishes the two populations without a second request.
548///
549/// `#[non_exhaustive]`: a future source — a dog fetched from a registry,
550/// say — must not need a protocol version bump (IR-20).
551// wire format: changing existing variants is a breaking change
552#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
553#[serde(tag = "kind", rename_all = "snake_case")]
554#[non_exhaustive]
555pub enum DogSource {
556    /// An argv branch of the shep binary itself (`shep dog <name>`).
557    BuiltIn,
558    /// A binary an operator adopted, run at the daemon's own trust level.
559    Adopted {
560        /// The binary's path, exactly as the operator gave it to `adopt`.
561        path: String,
562    },
563}
564
565/// One process the OS reports as a descendant of a sheep.
566///
567/// # What this is not
568///
569/// It is **not** the set of processes that die with the sheep, and nothing here
570/// should be read as promising that. The list is built by walking the OS's
571/// parent-pid links; the stop ladder acts on the process GROUP, and the two
572/// units diverge in both directions — a lamb that forks and exits leaves its
573/// own children re-parented to init, out of this list and still in the group,
574/// while a `setsid()` grandchild stays in this list and leaves the group.
575/// shep-daemon's `limits` module doc has the full account, and it is the
576/// authority; this is a pointer to it, not a second copy free to drift.
577///
578/// # Why a name and not a command line
579///
580/// `name` is the executable's name as the OS reports it (`node`, `sh`,
581/// `python3`), never its argument vector. A process's argv routinely carries
582/// credentials — a `--password=` flag, a URL with a token in the query string —
583/// and this field rides in `shep describe --format json`, which is output
584/// people paste into bug reports. A pid alone would be safe too, and was
585/// considered; it was rejected because a tree of bare integers sends the
586/// operator to `ps`, which is the work the tree exists to save.
587///
588/// # Why no memory figure
589///
590/// The sheep's own row already reports its whole tree's resident size
591/// ([`ProcessInfo::memory_bytes`]), and a per-lamb breakdown is a profiler's
592/// job. `deferred.md`'s note on this struct's growth asks for exactly this
593/// restraint.
594///
595/// `#[non_exhaustive]`: shep-core is a published library, this type is new, and
596/// the two obvious next fields (a parent pid, so a deep tree can be nested
597/// rather than flattened; a start time) would otherwise be breaking additions
598/// (IR-20). Build one with [`Self::new`].
599// wire format: changing this is a breaking change
600#[non_exhaustive]
601#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
602pub struct Lamb {
603    /// The lamb's own pid.
604    pub pid: u32,
605    /// The executable's name, as the OS reports it. Never its command line.
606    pub name: String,
607}
608
609impl Lamb {
610    /// One lamb.
611    ///
612    /// A plain constructor rather than a builder, unlike [`ProcessInfo`]: both
613    /// fields are required and neither is optional or derived, which is the
614    /// case a builder buys nothing for.
615    #[must_use]
616    pub fn new(pid: u32, name: impl Into<String>) -> Self {
617        Self {
618            pid,
619            name: name.into(),
620        }
621    }
622}
623
624/// Why a sheep's process most recently stopped existing under this daemon.
625///
626/// Not shep-daemon's own `ExitOutcome` reused directly: that type lives
627/// behind the spawn-runner seam (`ProcessRunner::wait`, in shep-daemon's
628/// `runner` module) and is free to grow with whatever the real runner needs
629/// to observe next without dragging a breaking wire change behind it — this
630/// one only ever grows on its own say-so. The two happen to carry the same
631/// two fields today because the runner's own observation IS the honest exit
632/// outcome; shep-daemon converts one into the other at the point it records
633/// it (`Actor::handle_exited`), rather than this crate depending on
634/// shep-daemon's internals to reuse its type.
635///
636/// A struct, not two flat `Option<i32>` fields on [`ProcessInfo`] directly:
637/// with two flat fields, "this sheep has never exited under this daemon"
638/// and "it exited, killed by a signal this daemon did not name" are both
639/// all-`None`, and a reader cannot tell those apart. Nested behind
640/// [`ProcessInfo::last_exit`]'s own `Option`, that ambiguity moves up a
641/// level where it belongs: `None` there means "never exited"; `Some` means
642/// "exited, and here is what this daemon knows about it" — which itself
643/// mirrors the OS's own exited-normally/killed-by-signal split
644/// (`WIFEXITED`/`WIFSIGNALED`): ordinarily exactly one of `code`/`signal` is
645/// `Some`. A reader must not assume both can never be `None` together,
646/// though — that would still mean "this daemon recorded an exit; it could
647/// not characterize how" rather than "this sheep never exited", and this
648/// type does not forbid it.
649///
650/// No `#[non_exhaustive]`, unlike every other struct on this wire: those
651/// grow because a discriminator does (`ProcessInfo`'s own doc lists its
652/// four so far); `code`/`signal` is already the complete
653/// exited-normally/killed-by-signal split the runner exposes, this crate
654/// has no libc to derive a richer wait-status decomposition from even if it
655/// wanted one, and there is no forecast next field. Adding the attribute
656/// back later is a compatible change the day a real need appears (IR-16
657/// style); carrying it now on nothing but "might grow" is the exact
658/// speculative case IR-20 warns against.
659// wire format: changing this is a breaking change
660#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
661pub struct ExitInfo {
662    /// The process's own exit code, set on a normal exit (`WIFEXITED`).
663    pub code: Option<i32>,
664    /// The raw unix signal number that ended the process, set when it did
665    /// not exit on its own (`WIFSIGNALED`) — an operator's own `shep stop`
666    /// or `shep delete` included: the process still genuinely stopped by a
667    /// signal, and that stays true information even though shep, not a
668    /// crash, is what asked for it. Raw and platform-specific for the same
669    /// reason [`crate::signals::OperatorSignal`] carries no such accessor —
670    /// see that type's own module doc — so rendering this as a name
671    /// (`SIGKILL` rather than `9`) is a job for whichever OS-aware layer
672    /// reads it, never for this crate.
673    pub signal: Option<i32>,
674}
675
676/// Snapshot of one sheep for listings and events
677// wire format: changing this is a breaking change
678//
679// `out_file`/`err_file` are `Option<String>`, and both halves of that are
680// deliberate:
681//
682// String, not PathBuf. Every path already on this wire travels as a string
683// (`AppConfig::script`, `cwd`, `out_file`, `err_file`, all of which ride in
684// `Request::Start`), so this matches the established representation. It is
685// also the safer failure mode: serde's `PathBuf` impl REFUSES a non-UTF-8
686// path, and that refusal is not local — it aborts the whole `Reply`, so one
687// sheep with an odd log path would blank the entire `ListFlock` for every
688// other sheep. Lossy conversion daemon-side degrades exactly one field of
689// one sheep instead.
690//
691// Option, not a bare String. Semantically the daemon always resolves both
692// paths, so a required field is tempting. But the handshake only compares
693// `PROTOCOL_VERSION` (see shep-daemon's `server.rs`), and adding these
694// fields deliberately does NOT bump it — the evolution rule in this
695// module's parent says additive fields keep the version. A daemon built
696// before this field and a client built after it therefore both announce
697// protocol 1 and connect happily, and that daemon's replies carry no
698// `out_file` key at all. A required `String` would fail to deserialize
699// there, so a new client could not list against an old daemon. `None`
700// means precisely "this peer predates the field" — which readers must
701// render as unknown, NOT as "this sheep has no log file".
702//
703// `cpu_percent`/`memory_bytes` are optional for that same skew reason and
704// for one of their own: a sheep that is not running has no resource use to
705// report, and one that has been up for less than a sampling window has no
706// honest CPU figure. All three cases render as unknown, never as zero.
707//
708// No `Eq`, which every other wire struct in this module derives:
709// `cpu_percent` is an `f32` and floats are only partially ordered. Nothing
710// compares a `ProcessInfo` for total equality — `assert_eq!` needs only
711// `PartialEq`, and no listing is keyed on, hashed by, or sorted by a whole
712// row.
713/// `#[non_exhaustive]`: this struct grows fields over time with no hand-edit
714/// sweep needed across OUT-OF-TREE callers — it forbids a struct literal
715/// outside this crate, not inside it. `sample_info()` and
716/// [`ProcessInfoBuilder`] both still name every field and both still need
717/// updating the day a field is added; what the attribute buys is that
718/// nothing downstream does. `deferred.md`'s own `ProcessInfo` entry defers
719/// SPLITTING it into several smaller types, not growing it — this attribute
720/// plus [`ProcessInfo::builder`] is "deliberately the opposite of forcing
721/// the split early," which is what makes a field like `last_exit` cheap to
722/// add for a concrete operator need, not a reason to withhold one. Use
723/// [`ProcessInfo::builder`] to construct one; the fields stay `pub`, so
724/// reading them and assigning to them are both unchanged.
725#[non_exhaustive]
726#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
727pub struct ProcessInfo {
728    /// Stable numeric id
729    pub id: u32,
730    /// Sheep name
731    pub name: String,
732    /// Lifecycle status
733    pub status: ProcStatus,
734    /// OS pid while running
735    pub pid: Option<u32>,
736    /// Restart count since registration
737    pub restarts: u32,
738    /// Milliseconds since last successful start
739    pub uptime_ms: u64,
740    /// Fold membership
741    pub fold: Option<String>,
742    /// Resolved stdout log path: the app's explicit
743    /// [`AppConfig::out_file`] when it set one, else the daemon-derived
744    /// default. `None` only when the peer daemon predates this field.
745    pub out_file: Option<String>,
746    /// Resolved stderr log path, resolved exactly as [`Self::out_file`]
747    pub err_file: Option<String>,
748    /// Tree CPU as a percentage of one core, over the window since the
749    /// daemon's last periodic sample. `None` when the sheep is not running,
750    /// when it has been up for less than one sampling window, or when the
751    /// peer daemon predates this field — all three of which a reader
752    /// renders as unknown, never as zero.
753    ///
754    /// A value over 100 is a tree using more than one core, not a bug.
755    pub cpu_percent: Option<f32>,
756    /// Tree resident set size in bytes, current as of the reply. `None`
757    /// under the same three conditions as [`Self::cpu_percent`], minus the
758    /// window one — memory needs no baseline.
759    pub memory_bytes: Option<u64>,
760    /// Set when this entry is a dog, naming where the dog came from;
761    /// `None` for a sheep.
762    ///
763    /// Unlike [`Self::cpu_percent`], `None` here does not need to enumerate
764    /// three cases. A daemon built before dogs existed has none, so "not a
765    /// dog" is the true answer whether this peer predates the field or the
766    /// entry is genuinely a sheep — there is no resource-usage-style claim
767    /// a stale zero could get wrong. Do not "fix" this into three cases.
768    pub dog: Option<DogSource>,
769    /// The processes the OS reports as descendants of this sheep, or `None`
770    /// when this reply did not walk for them.
771    ///
772    /// `None` covers two cases and is deliberately not a third: this reply is
773    /// not a `Describe` (only `Describe` walks — the walk costs a second pass
774    /// over the machine's process table, and a flock listing is the thing an
775    /// operator leaves running in a loop), or the peer daemon predates the
776    /// field. `Some(vec![])` is the third case, and the one that means what it
777    /// looks like: walked, and this sheep has no children.
778    ///
779    /// Read [`Lamb`]'s own doc before rendering this. The list is a parent-pid
780    /// walk and is NOT the set of processes a stop kills; any output built from
781    /// it has to say so where the operator will see it.
782    pub lambs: Option<Vec<Lamb>>,
783    /// How this sheep's process most recently stopped existing under this
784    /// daemon. `None` while it has never exited under this daemon — either
785    /// it has not been started yet, or it is still on its very first run —
786    /// and also when the peer daemon predates this field, the same skew
787    /// rule [`Self::out_file`] documents for itself.
788    ///
789    /// Sticky across a respawn, deliberately: this is the daemon's answer
790    /// to "why did it last stop", not "is it stopped right now" — `status`
791    /// and `pid` already answer that, and a sheep back `Online` after a
792    /// crash still has a true story to tell about the crash that restarted
793    /// it. It updates only on the next exit, never cleared by one starting
794    /// back up.
795    pub last_exit: Option<ExitInfo>,
796    /// The marker a dog has asked to have painted beside this sheep, or
797    /// `None` when no dog has painted one — which also covers a peer daemon
798    /// that predates the field, the same skew rule [`Self::out_file`]
799    /// documents for itself.
800    ///
801    /// A `String` rather than a [`Smit`], deliberately: a client decoding a
802    /// listing from a daemon that already validated the text should not have
803    /// to re-run the parser, and [`ProcessInfo`] is a report rather than an
804    /// input. The validation that makes this safe to print happened at the
805    /// daemon's ingress — see [`Smit`] for why there and not at the renderer.
806    ///
807    /// Every instance of a name shows the same marker: smits are keyed by
808    /// sheep name, not by instance id.
809    pub smit: Option<String>,
810    /// Which instance slot of its app this sheep occupies, counting from 0.
811    ///
812    /// `None` when the peer daemon predates the field, the same skew rule
813    /// [`Self::out_file`] documents for itself. Deliberately not a bare
814    /// `u32` defaulted to 0: an app stocked to four instances would then
815    /// report four rows all claiming slot 0, which is the silently-wrong
816    /// zero [`Self::dog`] warns against. A reader that finds `None` should
817    /// render exactly what it rendered before this field existed.
818    pub instance: Option<u32>,
819    /// Whether this dog has completed a handshake with the shepherd that is
820    /// reporting it, and not been refused since; `None` for a sheep.
821    ///
822    /// Read [`Self::dog`]'s own doc first — this field follows it rather
823    /// than [`Self::cpu_percent`], and for the same reason. `None` covers a
824    /// sheep and a peer daemon that predates the field, and collapsing the
825    /// two costs nothing: a sheep never handshakes with anything (it has no
826    /// connection to the shepherd at all, only a supervised process), so
827    /// "no handshake fact to report" is the true answer either way, and a
828    /// reader that finds `None` renders exactly what it rendered before
829    /// this field existed. Do not "fix" this into three cases.
830    ///
831    /// `Some(false)` is the one that matters and it is why this exists.
832    /// [`Self::status`] reports whether a PROCESS is alive, which for a
833    /// sheep is the whole truth and for a dog is not: a dog that cannot
834    /// talk to the shepherd is not doing its job, however alive it is. A
835    /// dog running on a protocol this shepherd refuses is exactly that, and
836    /// before this field a listing reported it `online` with zero restarts
837    /// while its own log filled with refusals.
838    ///
839    /// A fact and not a verdict, deliberately: this says whether the
840    /// handshake happened, never what a renderer should print about it. A
841    /// dog that has only just been spawned has not handshaken yet and is
842    /// perfectly healthy, so the decision about which lifecycle states that
843    /// silence is worth overriding belongs to the reader.
844    pub handshook: Option<bool>,
845    /// Whether the reporting shepherd has GIVEN UP on this dog — restarted
846    /// it once for never answering, watched that not help, and stopped
847    /// restarting it; `None` for a sheep.
848    ///
849    /// The same `None` rule [`Self::handshook`] documents, for the same
850    /// reason: a sheep is never given up on because a sheep never had to
851    /// answer anything, so "no verdict to report" is the true answer both
852    /// for a sheep and for a peer daemon that predates this field, and a
853    /// reader that finds `None` renders exactly what it rendered before the
854    /// field existed. Do not "fix" this into three cases.
855    ///
856    /// **Why this is not derivable from [`Self::handshook`], which is the
857    /// whole reason it exists.** `Some(false)` there covers two dogs whose
858    /// rows are otherwise identical: one spawned three seconds ago that has
859    /// simply not dialled back yet, and one this shepherd has permanently
860    /// stopped restarting. The first needs nothing done about it and the
861    /// second is an incident. Before this field the give-up was a latch
862    /// inside the daemon that no listing could see, so every operator-facing
863    /// surface rendered both as the same word.
864    ///
865    /// A fact and not a verdict, again deliberately. It says the shepherd
866    /// stopped, never why — the why is what the shepherd wrote into that
867    /// dog's own log when it gave up, and it is the one place that can name
868    /// the evidence (`shep bleats <dog>`). A renderer that invented a cause
869    /// here would be re-committing the bug this field was added during: a
870    /// shepherd asserting a cause it never observed.
871    pub dog_stale: Option<bool>,
872    /// The [`AppConfig`] field NAMES this sheep's
873    /// spec differs from a load's parked config for, in field-name order.
874    /// `None` when nothing is parked (every sheep outside the window
875    /// between a load that changed a `NeedsRespawn` field and the restart
876    /// that picks it up), and also when the peer daemon predates the field,
877    /// the same skew rule [`Self::out_file`] documents for itself.
878    ///
879    /// Names only, never values, for the same reason [`SheepDrift::fields`]
880    /// carries names only: a differing `env` reports `"env"` and stops
881    /// there (IR-41). `shep reload` is what promotes a parked config.
882    ///
883    /// `#[serde(skip_serializing_if = "Option::is_none")]`: most sheep are
884    /// not mid-parking, so this keeps the ordinary reply free of a key that
885    /// would otherwise be `null` on almost every row.
886    #[serde(default, skip_serializing_if = "Option::is_none")]
887    pub pending: Option<Vec<String>>,
888    /// The [`AppConfig`] field NAMES an operator
889    /// has set on this sheep that its current Flockfile does not declare,
890    /// in field-name order. `None` when there is nothing to report: no
891    /// override on record for this sheep, or a peer daemon that predates
892    /// the field.
893    ///
894    /// Names only, never values, for the reason [`Self::pending`] gives:
895    /// [`crate::overrides::AppOverrides::fields`] can hold an `env` value,
896    /// and nothing in shep sends an app's env to a client (IR-41).
897    ///
898    /// `#[serde(skip_serializing_if = "Option::is_none")]`, for the same
899    /// reason [`Self::pending`] carries it: most sheep carry no override at
900    /// all.
901    #[serde(default, skip_serializing_if = "Option::is_none")]
902    pub overridden: Option<Vec<String>>,
903}
904
905/// Orders one flock listing the way every operator-facing surface presents
906/// one: by name, then by instance slot, then by id.
907///
908/// # Why name first
909///
910/// An id is assigned at registration, so ordering by it sorts the flock by
911/// an accident of history rather than by anything an operator is looking
912/// for. It is not stable either: a `delete all` followed by a fresh start
913/// moved a real thirteen-app flock from ids 0-10 to 11-21 with nothing
914/// about the apps having changed. A name is what an operator scans a long
915/// listing for, and it survives that churn.
916///
917/// # Why id breaks the tie
918///
919/// A name is unique to an APP, not to a sheep: an app stocked to four
920/// instances puts four rows under one name. Name alone is therefore not a
921/// total order, and an unstable sort would let those four shuffle between
922/// refreshes — visible in `shep flock` and worse in `shep lookout`, which
923/// repolls every two seconds. The id keeps its other job unchanged: it is
924/// still how an operator addresses one instance at `shep stop 11`. It stops
925/// being a sort key and stays an addressing key.
926///
927/// This is the ONLY ordering rule in shep, and the daemon's own
928/// `snapshot_all` calls this function rather than restating it. The order is
929/// `(name, instance, id)`: [`ProcessInfo::instance`] now carries the slot a
930/// row occupies, so a reload that hands slot 0 a fresh id no longer moves
931/// that row out of place. A listing whose rows all carry `None` (an older
932/// peer daemon, or a row with no slot to report) collapses to the same
933/// `(name, id)` order this function used before the field existed, because
934/// `None` sorts before every `Some` and every row in that listing shares it.
935pub fn sort_flock(listing: &mut [ProcessInfo]) {
936    listing.sort_unstable_by(|a, b| {
937        (a.name.as_str(), a.instance, a.id).cmp(&(b.name.as_str(), b.instance, b.id))
938    });
939}
940
941impl ProcessInfo {
942    /// Starts a builder for one sheep's row.
943    ///
944    /// The three required arguments are the three fields no row can omit and
945    /// no reader can default: which sheep this is, what it is called, and
946    /// what state it is in. Everything else is optional, derived, or
947    /// meaningfully absent, which is exactly the shape a builder is for —
948    /// a nine-argument `new` would put `Option<String>, Option<String>,
949    /// Option<f32>, Option<u64>` next to each other at every call site and
950    /// invite a silent transposition the type system could not catch.
951    ///
952    /// No `#[must_use]` here: [`ProcessInfoBuilder`] already carries one,
953    /// which clippy's `double_must_use` lint treats as covering this
954    /// function's return too.
955    pub fn builder(id: u32, name: impl Into<String>, status: ProcStatus) -> ProcessInfoBuilder {
956        ProcessInfoBuilder {
957            info: Self {
958                id,
959                name: name.into(),
960                status,
961                pid: None,
962                restarts: 0,
963                uptime_ms: 0,
964                fold: None,
965                out_file: None,
966                err_file: None,
967                cpu_percent: None,
968                memory_bytes: None,
969                dog: None,
970                lambs: None,
971                last_exit: None,
972                smit: None,
973                instance: None,
974                handshook: None,
975                dog_stale: None,
976                pending: None,
977                overridden: None,
978            },
979        }
980    }
981}
982
983/// Builds a [`ProcessInfo`], which is `#[non_exhaustive]` and so cannot be
984/// written as a struct literal outside this crate.
985///
986/// Every setter takes the field's own type, `Option` included, rather than
987/// the unwrapped value. That is deliberate and it is the difference between a
988/// straight port and a rewrite: the daemon already holds `Option<u32>` for a
989/// pid and `Option<f32>` for a CPU reading, so `.pid(entry.pid())` carries
990/// across unchanged where `.pid(u32)` would put an `if let` ladder at every
991/// call site. A setter is skipped, not passed `None`, when a row genuinely
992/// has nothing to say about that field.
993///
994/// Defaults for the skipped fields are the ones a not-yet-running sheep has:
995/// no pid, no uptime, no restarts, no resource reading, not a dog, never
996/// exited.
997#[derive(Debug, Clone)]
998#[must_use = "a builder that is never `build`-ed produces no ProcessInfo"]
999pub struct ProcessInfoBuilder {
1000    info: ProcessInfo,
1001}
1002
1003impl ProcessInfoBuilder {
1004    /// Sets the OS pid; `None` while the sheep is not running.
1005    pub fn pid(mut self, pid: Option<u32>) -> Self {
1006        self.info.pid = pid;
1007        self
1008    }
1009
1010    /// Sets the restart count since registration.
1011    pub fn restarts(mut self, restarts: u32) -> Self {
1012        self.info.restarts = restarts;
1013        self
1014    }
1015
1016    /// Sets milliseconds since the last successful start.
1017    pub fn uptime_ms(mut self, uptime_ms: u64) -> Self {
1018        self.info.uptime_ms = uptime_ms;
1019        self
1020    }
1021
1022    /// Sets fold membership.
1023    pub fn fold(mut self, fold: Option<String>) -> Self {
1024        self.info.fold = fold;
1025        self
1026    }
1027
1028    /// Sets the resolved stdout log path.
1029    pub fn out_file(mut self, out_file: Option<String>) -> Self {
1030        self.info.out_file = out_file;
1031        self
1032    }
1033
1034    /// Sets the resolved stderr log path.
1035    pub fn err_file(mut self, err_file: Option<String>) -> Self {
1036        self.info.err_file = err_file;
1037        self
1038    }
1039
1040    /// Sets tree CPU as a percentage of one core.
1041    pub fn cpu_percent(mut self, cpu_percent: Option<f32>) -> Self {
1042        self.info.cpu_percent = cpu_percent;
1043        self
1044    }
1045
1046    /// Sets tree resident set size in bytes.
1047    pub fn memory_bytes(mut self, memory_bytes: Option<u64>) -> Self {
1048        self.info.memory_bytes = memory_bytes;
1049        self
1050    }
1051
1052    /// Marks this row a dog and names where the dog came from.
1053    pub fn dog(mut self, dog: Option<DogSource>) -> Self {
1054        self.info.dog = dog;
1055        self
1056    }
1057
1058    /// Sets the sheep's lamb list; `None` when this reply did not walk for one.
1059    pub fn lambs(mut self, lambs: Option<Vec<Lamb>>) -> Self {
1060        self.info.lambs = lambs;
1061        self
1062    }
1063
1064    /// Sets how this sheep's process most recently stopped; `None` while it
1065    /// has never exited under this daemon.
1066    pub fn last_exit(mut self, last_exit: Option<ExitInfo>) -> Self {
1067        self.info.last_exit = last_exit;
1068        self
1069    }
1070
1071    /// Sets the marker a dog has painted on this sheep; `None` when none has.
1072    pub fn smit(mut self, smit: Option<String>) -> Self {
1073        self.info.smit = smit;
1074        self
1075    }
1076
1077    /// Sets the instance slot; `None` when the peer daemon predates the field.
1078    pub fn instance(mut self, instance: Option<u32>) -> Self {
1079        self.info.instance = instance;
1080        self
1081    }
1082
1083    /// Sets whether this dog has handshaken with the shepherd; `None` for a
1084    /// sheep, which has no handshake to report.
1085    pub fn handshook(mut self, handshook: Option<bool>) -> Self {
1086        self.info.handshook = handshook;
1087        self
1088    }
1089
1090    /// Sets whether the shepherd has given up restarting this dog; `None`
1091    /// for a sheep, which is never given up on.
1092    pub fn dog_stale(mut self, dog_stale: Option<bool>) -> Self {
1093        self.info.dog_stale = dog_stale;
1094        self
1095    }
1096
1097    /// Sets the field names a load has parked for this sheep's next spawn;
1098    /// `None` when nothing is parked.
1099    pub fn pending(mut self, pending: Option<Vec<String>>) -> Self {
1100        self.info.pending = pending;
1101        self
1102    }
1103
1104    /// Sets the field names an operator has overridden on this sheep;
1105    /// `None` when there is nothing to report.
1106    pub fn overridden(mut self, overridden: Option<Vec<String>>) -> Self {
1107        self.info.overridden = overridden;
1108        self
1109    }
1110
1111    /// Finishes the row.
1112    #[must_use]
1113    pub fn build(self) -> ProcessInfo {
1114        self.info
1115    }
1116}
1117
1118/// What happened when the daemon tried to deliver one sheep's triggered
1119/// action.
1120///
1121/// `#[non_exhaustive]`: a future outcome — distinguishing a malformed reply
1122/// from a well-formed one, say, or a second trigger already in flight for
1123/// the same sheep — must not need a protocol version bump (IR-20).
1124// wire format: changing existing variants is a breaking change
1125#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1126#[serde(tag = "kind", rename_all = "snake_case")]
1127#[non_exhaustive]
1128pub enum ActionOutcome {
1129    /// The app answered on the shepherd channel.
1130    Replied {
1131        /// The reply body, exactly as the app sent it.
1132        body: String,
1133    },
1134    /// The sheep had no reachable shepherd channel for the daemon to
1135    /// deliver the action over.
1136    NoChannel,
1137    /// The sheep is a reload drainee — mid-swap, on its way out — and the
1138    /// daemon skipped it rather than deliver the action to a process
1139    /// already being replaced.
1140    Skipped,
1141    /// The daemon delivered the action, but no reply arrived before the
1142    /// app's configured action timeout elapsed.
1143    TimedOut,
1144}
1145
1146/// One matched sheep's row in a `Trigger` reply.
1147///
1148/// `EmptiedFile` (`crates/shep-cli/src/output/rows.rs`) is the precedent for
1149/// a non-`ProcessInfo` row: a reply body has nowhere to live on
1150/// [`ProcessInfo`], and [`Self::outcome`] is per-row rather than a
1151/// whole-request refusal because spec §9's selector grammar (`all`,
1152/// `/regex/`, `fold:`) makes a mixed flock the normal case — the same reason
1153/// `Reopen`/`Flush` report per-item failure inside a success rather than
1154/// failing the whole request.
1155// wire format: changing this is a breaking change
1156#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1157pub struct ActionReply {
1158    /// The sheep's stable id.
1159    pub id: u32,
1160    /// The sheep's name.
1161    pub name: String,
1162    /// What happened when the daemon tried to deliver the action.
1163    pub outcome: ActionOutcome,
1164}
1165
1166/// What happened when the shepherd tried to deliver one signal.
1167///
1168/// `#[non_exhaustive]`: a future outcome — a sheep refused because it is a dog,
1169/// say, or a delivery held while a stop ladder runs — must not need a protocol
1170/// version bump (IR-20).
1171// wire format: changing existing variants is a breaking change
1172#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1173#[serde(tag = "kind", rename_all = "snake_case")]
1174#[non_exhaustive]
1175pub enum SignalOutcome {
1176    /// The kernel accepted the signal for this sheep's pid.
1177    ///
1178    /// Says the signal was delivered, not that the app did anything with it.
1179    /// A signal the app blocks, ignores, or has no handler for is `Delivered`
1180    /// exactly like one it acts on — there is nothing on this path that could
1181    /// tell the difference, and pretending otherwise would be the dishonest
1182    /// half of an honest report.
1183    Delivered,
1184    /// The sheep is registered but has no live process to signal — stopped,
1185    /// errored, or waiting out a restart backoff.
1186    NotRunning,
1187    /// The kernel refused the delivery; carries its reason (`ESRCH` for a
1188    /// process reaped between the lookup and the syscall, `EPERM` for one this
1189    /// daemon may not signal).
1190    Failed {
1191        /// The refusal, as the OS worded it.
1192        reason: String,
1193    },
1194}
1195
1196/// One matched sheep's row in a `Signal` reply.
1197///
1198/// Shaped exactly like [`ActionReply`] and for the same reason: spec §9's
1199/// selector grammar (`all`, `/regex/`, `fold:`) makes a mixed flock the normal
1200/// case, so a per-row outcome beats a whole-request refusal that would leave
1201/// the operator unable to tell which half was taken.
1202// wire format: changing this is a breaking change
1203#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1204pub struct SignalReply {
1205    /// The sheep's stable id.
1206    pub id: u32,
1207    /// The sheep's name.
1208    pub name: String,
1209    /// What happened when the shepherd tried to deliver the signal.
1210    pub outcome: SignalOutcome,
1211}
1212
1213/// What happened when the shepherd tried to write one line to a sheep's stdin.
1214///
1215/// `#[non_exhaustive]`: a future outcome — a sheep refused because its pipe is
1216/// backed up, say — must not need a protocol version bump (IR-20).
1217// wire format: changing existing variants is a breaking change
1218#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1219#[serde(tag = "kind", rename_all = "snake_case")]
1220#[non_exhaustive]
1221pub enum LineOutcome {
1222    /// The line was written to the pipe and flushed.
1223    ///
1224    /// Says the bytes left the shepherd, not that the app read them. A pipe
1225    /// holds 64 KiB before it blocks, so a short line to an app that never
1226    /// reads its stdin is `Sent` — which is honest, because there is nothing
1227    /// on this path that could tell the difference and a supervisor inventing
1228    /// one would be guessing.
1229    Sent,
1230    /// The sheep has no stdin pipe: its config does not set `stdin = true`, or
1231    /// it is not running.
1232    ///
1233    /// One outcome for two causes, deliberately. The row is read to answer
1234    /// "why did my line not arrive", and both answers are "there is no pipe
1235    /// here"; splitting them would put the operator in front of a distinction
1236    /// with the same fix behind it. A sheep that is not running is visible as
1237    /// such in `shep flock`, which is where that question belongs.
1238    NoStdin,
1239    /// The shepherd had a pipe and did not confirm a write to it; carries
1240    /// why.
1241    ///
1242    /// Three shapes reach it: the write failed (the far end is gone —
1243    /// normally the app exiting between the lookup and the write), the line
1244    /// arrived to find the sheep's queue already full, or the write did not
1245    /// finish inside the shepherd's own bound. The reason names which,
1246    /// because the operator's next move differs.
1247    ///
1248    /// # The last shape does not promise the line was never written
1249    ///
1250    /// "Did not confirm", not "could not write", and the difference is the
1251    /// operator's whole decision about retrying. A write that timed out is a
1252    /// write the shepherd stopped WAITING for: the bytes may be part-written
1253    /// into a pipe the app is not draining, and they land in full the moment
1254    /// it does. There is no way to take them back — abandoning a write
1255    /// halfway would leave a partial line in the pipe, which is worse than a
1256    /// slow one.
1257    ///
1258    /// What the shepherd does do is drop a line still QUEUED behind that one
1259    /// once its caller has given up, so retrying a `sendline` cannot pile
1260    /// duplicates up behind a wedged pipe and deliver them together later.
1261    /// The first line of a retry sequence is the one that can still arrive
1262    /// late; treat a retry as a second command, not a repeat of the first.
1263    NotWritten {
1264        /// What went wrong, in plain English.
1265        reason: String,
1266    },
1267}
1268
1269/// One matched sheep's row in a `SendLine` reply.
1270///
1271/// Same shape and same argument as [`ActionReply`] and [`SignalReply`]: spec
1272/// §9's selector grammar makes a mixed flock the normal case, so an outcome
1273/// per row beats a whole-request refusal.
1274// wire format: changing this is a breaking change
1275#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1276pub struct LineReply {
1277    /// The sheep's stable id.
1278    pub id: u32,
1279    /// The sheep's name.
1280    pub name: String,
1281    /// What happened.
1282    pub outcome: LineOutcome,
1283}
1284
1285/// A dog's `[dog.<name>]` config section, carried as TOML text.
1286///
1287/// This travels over the socket rather than the child's environment for
1288/// exactly one reason: a dog's section routinely holds webhook credentials
1289/// (a Discord or Slack URL with a bearer token embedded), and the socket
1290/// path keeps that out of the process table and out of crash dumps. A
1291/// derived `Debug` on [`Response`] would undo that the moment something
1292/// logs a reply — see the manual `Debug` below, which prints only a length.
1293///
1294/// `#[serde(transparent)]` makes the wire representation identical to a
1295/// bare `String`: this newtype changes nothing about
1296/// [`crate::protocol::PROTOCOL_VERSION`] or the pinned snapshot fixtures.
1297#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
1298#[serde(transparent)]
1299pub struct DogSectionToml(String);
1300
1301impl DogSectionToml {
1302    /// The TOML text, empty when the file has no such section.
1303    #[must_use]
1304    pub fn as_str(&self) -> &str {
1305        &self.0
1306    }
1307}
1308
1309impl From<String> for DogSectionToml {
1310    fn from(toml: String) -> Self {
1311        Self(toml)
1312    }
1313}
1314
1315impl core::ops::Deref for DogSectionToml {
1316    type Target = str;
1317
1318    fn deref(&self) -> &str {
1319        &self.0
1320    }
1321}
1322
1323/// Debug does not print the section body (IR-41) — see the type doc for why.
1324/// Exact-string-tested below (`dog_section_toml_debug_does_not_leak`) so a
1325/// future `#[derive(Debug)]` fails that test instead of silently reopening
1326/// the leak.
1327impl fmt::Debug for DogSectionToml {
1328    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1329        write!(f, "DogSectionToml(<{} bytes>)", self.0.len())
1330    }
1331}
1332
1333/// One registered sheep whose stored config differs from a caller's copy:
1334/// the answer [`Request::ConfigDrift`] is asking for
1335///
1336/// Field NAMES only, never their values. This is built to be printed at an
1337/// operator, and [`AppConfig::env`](crate::config::AppConfig::env) carries
1338/// secrets, so a differing `env` reports `"env"` and nothing more (IR-41).
1339/// `Debug` is derived for that reason: there is nothing here to redact.
1340// wire format: changing field names is a breaking change
1341//
1342// `#[non_exhaustive]`: shep-core is a published library, an out-of-tree
1343// consumer can match or construct this exhaustively today, and a third field
1344// (which side is newer, say) would break them with no version bump to say
1345// so (IR-20). [`SheepDrift::new`] is how the daemon builds one.
1346#[non_exhaustive]
1347#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1348pub struct SheepDrift {
1349    /// The sheep's name. Both configs share it by construction: it is what
1350    /// matched them to each other.
1351    pub name: String,
1352    /// The [`AppConfig`] fields that differ, in
1353    /// field-name order. Never empty: a sheep with nothing to report is left
1354    /// out of the answer entirely.
1355    pub fields: Vec<String>,
1356}
1357
1358impl SheepDrift {
1359    /// Builds one sheep's report.
1360    ///
1361    /// No builder, unlike [`ProcessInfo`]: both fields are required and
1362    /// neither can be defaulted, so there is no optional surface for one to
1363    /// spare a caller.
1364    #[must_use]
1365    pub fn new(name: impl Into<String>, fields: Vec<String>) -> Self {
1366        Self {
1367            name: name.into(),
1368            fields,
1369        }
1370    }
1371}
1372
1373/// What one app's [`Request::ApplyConfig`] did: the answer a load owes the
1374/// operator who ran it
1375///
1376/// One of these per app the request named, whether or not the app was found
1377/// and whether or not anything about it changed. A load that quietly skipped
1378/// an app would leave an operator reading a Flockfile that says one thing and
1379/// a flock doing another, which is the failure this whole verb exists to fix.
1380///
1381/// [`Self::applied`] and [`Self::pending`] carry field NAMES only, never
1382/// their values, exactly as [`SheepDrift`] carries them and for the same
1383/// reason: this is built to be printed at an operator, and
1384/// [`AppConfig::env`](crate::config::AppConfig::env) carries secrets, so an
1385/// applied `env` reports `"env"` and nothing more (IR-41). The merged config
1386/// itself never reaches a client at all -- the daemon keeps it, because a
1387/// config is not something a client needs and `env` is in it.
1388///
1389/// **[`Self::refused`] is prose and is deliberately not held to that**, so
1390/// the rule above is scoped to the two lists rather than stated of the whole
1391/// type. A refusal is a sentence an operator reads, and the useful ones name
1392/// the thing that was refused: the daemon's own instance-count refusal
1393/// quotes the count the file asked for, and a rejected `{{...}}` template
1394/// quotes the offending fragment. Those are values out of the FILE the
1395/// caller just sent, not values out of the flock's stored config, which is
1396/// what makes them safe to echo; see that field's own doc. A refusal that
1397/// needs to name an `env` value is one the daemon must word differently, not
1398/// one this type can prevent.
1399///
1400/// `Debug` is derived on that basis: `refused` holds only what the daemon
1401/// chose to put in front of an operator anyway, so there is nothing here to
1402/// redact that redacting would help.
1403// wire format: changing field names is a breaking change
1404//
1405// `#[non_exhaustive]`: shep-core is a published library, an out-of-tree
1406// consumer can match or construct this exhaustively today, and a fourth
1407// field (which of the pending fields a reload would promote, say) would
1408// break them with no version bump to say so (IR-20). [`SheepApplied::new`]
1409// is how the daemon builds one.
1410#[non_exhaustive]
1411#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1412pub struct SheepApplied {
1413    /// The sheep's name, exactly as the request spelled it.
1414    pub name: String,
1415    /// Fields now in force, in field-name order. Empty when the load changed
1416    /// nothing the daemon could act on immediately.
1417    pub applied: Vec<String>,
1418    /// Fields the app picks up at its next spawn, in field-name order. Empty
1419    /// when nothing is waiting.
1420    ///
1421    /// `shep reload <name>` is what promotes them; a client rendering this
1422    /// list says so, because a pending list with no remedy beside it is a
1423    /// report nobody can act on.
1424    pub pending: Vec<String>,
1425    /// Why some or all of this app's change did not land, in the daemon's own
1426    /// words, or `None` when the whole of it did.
1427    ///
1428    /// Not the same question as the two lists being empty. A refusal raised
1429    /// before anything was touched leaves both empty, and so does a load with
1430    /// nothing to do; a refusal raised after the flock was already reshaped
1431    /// arrives beside lists that carry what did land. The message is what
1432    /// tells them apart, which is why it is a sentence rather than a code.
1433    pub refused: Option<String>,
1434}
1435
1436impl SheepApplied {
1437    /// Builds one app's report.
1438    ///
1439    /// No builder, matching [`SheepDrift::new`]: all four fields are required
1440    /// and none can be defaulted to something honest, so there is no optional
1441    /// surface for one to spare a caller.
1442    #[must_use]
1443    pub fn new(
1444        name: impl Into<String>,
1445        applied: Vec<String>,
1446        pending: Vec<String>,
1447        refused: Option<String>,
1448    ) -> Self {
1449        Self {
1450            name: name.into(),
1451            applied,
1452            pending,
1453            refused,
1454        }
1455    }
1456}
1457
1458/// One RPC response (pairs with [`Request`] variants)
1459///
1460/// Ten variants carry a bare `Vec<ProcessInfo>` (`Flock`, `Described`,
1461/// `Started`, `Stopped`, `Restarted`, `Reloading`, `Scaled`, `Reopened`,
1462/// `Flushed`, `Mustered`), and that repetition is intentional — do not
1463/// collapse them into one. Each names which request it answers, which is what
1464/// lets a variant diverge later without a protocol bump: `Reloading` already
1465/// means an acceptance rather than a result, `Scaled` already means only the
1466/// survivors on a scale-down rather than every matched row, and `Mustered`
1467/// already means "every sheep of every restored app" rather than "what this
1468/// call started". A single `Listing(Vec<ProcessInfo>)` would have to
1469/// relitigate all three as a breaking change.
1470// wire format: changing existing variants is a breaking change
1471//
1472// `large_enum_variant` allowed, not fixed: `DogStarted` holds a whole
1473// `ProcessInfo` inline where every other variant holds a `Vec` of them, and
1474// adding `smit` to that struct is what pushed the spread past the lint's
1475// threshold. Clippy's remedy is to box the payload, which would be a source
1476// break for every `Response::DogStarted(info)` in and out of this workspace
1477// — for nothing: a `Response` is built once per reply and serialized
1478// immediately, so the size it occupies on one stack frame in between is not
1479// a cost anybody pays. The wire shape is identical either way.
1480#[allow(clippy::large_enum_variant)]
1481#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1482#[serde(tag = "kind", content = "data", rename_all = "snake_case")]
1483#[non_exhaustive]
1484pub enum Response {
1485    /// Answer to `Ping`
1486    Pong,
1487    /// Answer to `ListFlock`
1488    Flock(Vec<ProcessInfo>),
1489    /// Answer to `Describe`
1490    Described(Vec<ProcessInfo>),
1491    /// Answer to `Start`
1492    Started(Vec<ProcessInfo>),
1493    /// Answer to `ConfigDrift`: one entry per app that is registered under a
1494    /// config different from the one asked about, and no entry for anything
1495    /// else. An empty vector means every app asked about either matches or
1496    /// is not registered at all.
1497    Drifted(Vec<SheepDrift>),
1498    /// Answer to `ApplyConfig`: one entry per app the request named, in the
1499    /// order it named them, including the apps that were refused and the
1500    /// apps that had nothing to change.
1501    ///
1502    /// Complete where [`Self::Drifted`] is filtered, and the difference is
1503    /// deliberate. A drift report answers "what is different", so a matching
1504    /// app has nothing to say; a load answers "what did you do to each of
1505    /// these", and an app missing from that answer is indistinguishable from
1506    /// an app the daemon silently dropped.
1507    Applied(Vec<SheepApplied>),
1508    /// Answer to `Stop`
1509    Stopped(Vec<ProcessInfo>),
1510    /// Answer to `Restart`
1511    Restarted(Vec<ProcessInfo>),
1512    /// Answer to `Reload` — an ACCEPTANCE, not a result, and the only reply
1513    /// in this enum carrying a flock listing that names one rather than
1514    /// finished work. [`Self::ShuttingDown`] is an acceptance too, sent
1515    /// before the daemon actually goes down, but it carries nothing.
1516    ///
1517    /// One instance costs a readiness wait plus a drain in the worst case, so
1518    /// a clustered app outlasts any deadline a client is allowed to ask for.
1519    /// The daemon therefore answers as soon as the reload is accepted, with
1520    /// the matched sheep as they stood at that moment, and the swaps report
1521    /// themselves on the bus — `process.reload`, `process.reloaded`,
1522    /// `process.reload_abandoned`. A matched sheep with nothing to replace is
1523    /// listed here as the no-op success it is, so this carries the same
1524    /// matches `Describe` would.
1525    Reloading(Vec<ProcessInfo>),
1526    // The order is cited as [`sort_flock`]'s shared rule rather than restated
1527    // as this reply's own, so the two cannot drift apart.
1528    /// Answer to `Scale` — the app's instances that will REMAIN, one row
1529    /// each, by name, then by instance slot, then by id ([`sort_flock`]).
1530    /// Every row shares one name here, so in practice that is slot order,
1531    /// with the id breaking a tie only where two rows report the same slot.
1532    ///
1533    /// Scaling up, these are the instances that exist, the new ones included,
1534    /// and the answer is complete.
1535    ///
1536    /// Scaling down, these are the survivors and the departing instances are
1537    /// deliberately absent, even though they are still running their kill
1538    /// ladders as this reply is written. The operator asked for a number; this
1539    /// is that number of rows. Listing the departing ones as well would answer
1540    /// a `scale web 2` with four rows, which is the one thing the reply must
1541    /// not do. The departures report themselves on the bus as `process.delete`
1542    /// — the same split `Reloading` already makes between an acceptance and
1543    /// the swaps that follow it.
1544    Scaled(Vec<ProcessInfo>),
1545    /// Answer to `SetSmit` — every instance of the named sheep, one row
1546    /// each, each carrying the smit as it now stands.
1547    ///
1548    /// Its own variant rather than one of the ten above, on this enum's own
1549    /// stated terms: each of them names which request it answers so that one
1550    /// can diverge later without a protocol bump. A future `SetSmit` reply
1551    /// that also reported which connection holds the mark would have nowhere
1552    /// to go if this shared `Scaled`.
1553    SmitPainted(Vec<ProcessInfo>),
1554    /// Answer to `Delete` — ids removed
1555    Deleted(Vec<u32>),
1556    /// Answer to `Reopen` — every matched sheep, running or not. A sheep with
1557    /// no live log pump has nothing to reopen and is reported as a success,
1558    /// so this carries the same matches `Describe` would.
1559    Reopened(Vec<ProcessInfo>),
1560    /// Answer to `Flush` — one row per matched sheep, running or not, exactly
1561    /// as [`Self::Reopened`].
1562    ///
1563    /// One row per SHEEP, not per file emptied. Several sheep can share one
1564    /// log path (`merge_logs`, or an explicit `out_file` on a multi-instance
1565    /// app), and the daemon truncates each distinct path once — but the
1566    /// selector names sheep, so the answer names sheep, and the count here
1567    /// matches what `Describe` would return for the same selector.
1568    Flushed(Vec<ProcessInfo>),
1569    /// Answer to `Trigger` — one [`ActionReply`] row per matched sheep,
1570    /// carrying what each one answered rather than a flock listing:
1571    /// `ProcessInfo` has nowhere to hold a reply body.
1572    Triggered(Vec<ActionReply>),
1573    /// Answer to `Signal` — one [`SignalReply`] row per matched sheep.
1574    ///
1575    /// Not a flock listing: what a caller wants back is per-instance delivery,
1576    /// and [`ProcessInfo`] has nowhere to hold it. Same reasoning, and the
1577    /// same row-shaped answer, as [`Self::Triggered`].
1578    Signalled(Vec<SignalReply>),
1579    /// Answer to `SendLine` — one [`LineReply`] row per matched sheep.
1580    SentLine(Vec<LineReply>),
1581    /// Answer to `SaveRoll`
1582    RollSaved {
1583        /// Absolute path of the roll the daemon wrote
1584        path: String,
1585        /// How many apps that roll records
1586        apps: u32,
1587    },
1588    /// Answer to `Muster` — every sheep of every app the roll restored, not
1589    /// only the ones this call spawned.
1590    ///
1591    /// The distinction is the whole point of the reply. Assembling a flock
1592    /// that is already assembled starts nothing, so a listing of what this
1593    /// call spawned would be empty there — indistinguishable from an empty
1594    /// roll, which is the one outcome an operator needs to tell apart.
1595    Mustered(Vec<ProcessInfo>),
1596    /// Answer to `DogConfig` — the dog's own section, rendered back to TOML.
1597    ///
1598    /// `toml` is [`DogSectionToml`], not a bare `String`: this text
1599    /// routinely carries webhook credentials, and the newtype's manual
1600    /// `Debug` keeps them out of a `{:?}`-formatted `Response` — see that
1601    /// type's docs for why the section travels over the socket at all.
1602    DogSection {
1603        /// The `[dog.<name>]` table as TOML text, empty when the file has
1604        /// no such section
1605        toml: DogSectionToml,
1606    },
1607    /// Answer to `EnableDog` — the dog as it stands now
1608    DogStarted(ProcessInfo),
1609    /// Answer to `DogStaleness` — this daemon's own handshake record, split
1610    /// into the dogs it has given up on and the dogs it is still waiting on.
1611    ///
1612    /// Two lists rather than one because they are answers to two different
1613    /// questions, and only one of them is reportable. `stale` is a
1614    /// finding: those dogs were refused, restarted from the binary on disk,
1615    /// and refused again. `pending` is a reason to ask again: those
1616    /// dogs have not finished settling, so a reading taken now would be a
1617    /// guess about them rather than a fact.
1618    ///
1619    /// Names only. What a stale dog's crate version is does not answer the
1620    /// question a caller is asking — two builds differing only in the
1621    /// protocol they speak report the same version — so carrying one here
1622    /// would invite exactly the inference it cannot support.
1623    DogStaleness {
1624        /// Dogs this daemon has refused twice: once on the handshake that
1625        /// bought them a restart from disk, and again after it. It will not
1626        /// restart them a third time (the handover design's G8).
1627        stale: Vec<String>,
1628        /// Dogs this daemon is still waiting to hear a final answer from —
1629        /// one whose restart is in flight, or one it supervises that has
1630        /// not handshook yet. Neither stale nor known healthy.
1631        pending: Vec<String>,
1632    },
1633    /// Answer to `HandoverFitness`: `None` when the whole flock can be
1634    /// carried across a daemon handover, and otherwise the sentence saying
1635    /// which sheep cannot be and why.
1636    ///
1637    /// A rendered sentence rather than a structured reason, deliberately. The
1638    /// set of things a handover cannot yet carry is exactly the set of things
1639    /// that phase has not built, so it changes with every phase that widens
1640    /// it, and a wire enum would make each of those a protocol change for a
1641    /// string the client does nothing with but print. The daemon owns the
1642    /// wording because the daemon owns the gate.
1643    HandoverFitness {
1644        /// Why the flock cannot be handed over in place, or `None` when it
1645        /// can.
1646        refusal: Option<String>,
1647    },
1648    /// Answer to `Subscribe`
1649    Subscribed,
1650    /// Answer to `KillDaemon`
1651    ShuttingDown,
1652}
1653
1654/// A request frame
1655// wire format: changing this is a breaking change
1656#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1657pub struct Envelope {
1658    /// Per-connection request id
1659    pub id: u64,
1660    /// Client-imposed deadline (daemon aborts work past it)
1661    pub deadline_ms: Option<u64>,
1662    /// The request
1663    pub body: Request,
1664}
1665
1666/// A reply frame
1667///
1668/// `result` uses serde's stock `Result` representation — the wire carries
1669/// `{"Ok": ...}` / `{"Err": ...}` (capitalized keys). Deliberate, pinned by
1670/// snapshot: stock serde beats a custom enum the client would convert anyway.
1671// wire format: changing this is a breaking change
1672#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1673pub struct Reply {
1674    /// Echoes [`Envelope::id`]
1675    pub id: u64,
1676    /// The outcome
1677    pub result: Result<Response, RpcError>,
1678}
1679
1680/// Handshake outcome: `HelloAck` or a typed refusal (spec §6 —
1681/// version skew is an error, not silence). Same `Ok`/`Err` wire shape
1682/// as [`Reply::result`]; refusals use [`RpcErrorCode::ProtocolMismatch`].
1683pub type HelloReply = Result<HelloAck, RpcError>;
1684
1685/// Structured RPC failure
1686// wire format: changing this is a breaking change
1687#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1688pub struct RpcError {
1689    /// Machine-readable code
1690    pub code: RpcErrorCode,
1691    /// Human-readable message (plain English, no theme)
1692    pub message: String,
1693    /// The daemon's own crate version, when it chose to name it.
1694    ///
1695    /// Set on a [`RpcErrorCode::ProtocolMismatch`] refusal, where it is the
1696    /// only place a client can learn it: the refusal reports the daemon's
1697    /// PROTOCOL, and [`HelloAck::daemon_version`] never arrives. `shep
1698    /// daemon reload` picks its mechanism by version, and a protocol bump is
1699    /// exactly when that choice matters.
1700    ///
1701    /// `None` on every other error, and on any refusal from a daemon built
1702    /// before this field existed — which no upgrade can change, so a reader
1703    /// must treat `None` as "unknown" and take the conservative path.
1704    ///
1705    /// Additive by construction: absent on the wire rather than `null`, and
1706    /// ignored by a client too old to know it, so
1707    /// [`crate::protocol::PROTOCOL_VERSION`] does not move for it.
1708    #[serde(default, skip_serializing_if = "Option::is_none")]
1709    pub daemon_version: Option<String>,
1710}
1711
1712/// Machine-readable RPC error codes
1713// wire format: changing existing variants is a breaking change
1714#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1715#[serde(rename_all = "snake_case")]
1716#[non_exhaustive]
1717pub enum RpcErrorCode {
1718    /// Selector matched nothing
1719    NotFound,
1720    /// Config failed validation daemon-side
1721    InvalidConfig,
1722    /// Spawn failed (exec error, permissions)
1723    SpawnFailed,
1724    /// Handshake protocol version mismatch
1725    ProtocolMismatch,
1726    /// Unexpected daemon-side failure
1727    Internal,
1728    /// The request's deadline expired before the daemon finished it
1729    DeadlineExceeded,
1730}
1731
1732impl RpcErrorCode {
1733    /// Every variant, for code that needs to iterate them all.
1734    ///
1735    /// `#[non_exhaustive]` forces a `_` arm on any match written outside
1736    /// this crate, which would silently swallow a variant added here and
1737    /// never updated there (shep-cli's exit-code mapping test is the
1738    /// motivating case — see `crates/shep-cli/src/exit.rs`). Downstream
1739    /// crates should iterate `ALL` instead of hand-writing their own list
1740    /// that the compiler can't check.
1741    ///
1742    /// Kept honest by a private `assert_all_lists_every_variant` fn right
1743    /// below: read that doc for how a forgotten variant is caught here,
1744    /// where `#[non_exhaustive]` has no effect.
1745    pub const ALL: [Self; 6] = [
1746        Self::NotFound,
1747        Self::InvalidConfig,
1748        Self::SpawnFailed,
1749        Self::ProtocolMismatch,
1750        Self::Internal,
1751        Self::DeadlineExceeded,
1752    ];
1753
1754    /// Never called; exists purely so this crate fails to build if a
1755    /// variant is added to [`RpcErrorCode`] without also adding it to
1756    /// [`Self::ALL`].
1757    ///
1758    /// `#[non_exhaustive]` only forces a wildcard arm on matches written
1759    /// *outside* this crate — inside the crate that defines the enum, a
1760    /// match with no `_` arm is still checked for exhaustiveness (E0004),
1761    /// so a new variant breaks this build until it gets an arm here. Each
1762    /// arm indexes a fixed literal position into [`Self::ALL`], so growing
1763    /// the enum without growing the array is caught too: rustc denies an
1764    /// out-of-bounds constant array index by default.
1765    #[allow(dead_code)]
1766    const fn assert_all_lists_every_variant(code: Self) -> Self {
1767        match code {
1768            Self::NotFound => Self::ALL[0],
1769            Self::InvalidConfig => Self::ALL[1],
1770            Self::SpawnFailed => Self::ALL[2],
1771            Self::ProtocolMismatch => Self::ALL[3],
1772            Self::Internal => Self::ALL[4],
1773            Self::DeadlineExceeded => Self::ALL[5],
1774        }
1775    }
1776}
1777
1778#[cfg(test)]
1779mod tests {
1780    use super::*;
1781    use crate::config::AppConfig;
1782    use crate::protocol::PROTOCOL_VERSION;
1783    use crate::status::ProcStatus;
1784
1785    fn sample_info() -> ProcessInfo {
1786        ProcessInfo {
1787            id: 3,
1788            name: "web".to_string(),
1789            status: ProcStatus::Online,
1790            pid: Some(4242),
1791            restarts: 1,
1792            uptime_ms: 60_000,
1793            fold: Some("backend".to_string()),
1794            out_file: Some("/home/ada/.shep/logs/web-0-out.log".to_string()),
1795            err_file: Some("/home/ada/.shep/logs/web-0-err.log".to_string()),
1796            // 12.5 rather than a rounder-looking 12.3: an insta JSON
1797            // snapshot is only stable across platforms for a float the
1798            // binary representation holds exactly.
1799            cpu_percent: Some(12.5),
1800            memory_bytes: Some(48 * 1024 * 1024),
1801            dog: None,
1802            lambs: None,
1803            // `restarts: 1` above already says this sheep crashed once and
1804            // came back; a code rather than `None` is the honest exit that
1805            // caused it, not a fact this fixture invents.
1806            last_exit: Some(ExitInfo {
1807                code: Some(1),
1808                signal: None,
1809            }),
1810            smit: None,
1811            instance: None,
1812            handshook: None,
1813            dog_stale: None,
1814            // Left at the builder's own default, like `dog`/`lambs` above
1815            // this fixture: this feeds `reply_wire_snapshots` and
1816            // `bus_event_wire_snapshots`, so a `Some(..)` here would move
1817            // pinned bytes. `every_setter_writes_its_own_field_and_no_other`
1818            // exercises the setter body on its own, the same way it does
1819            // for `dog`, `lambs`, `smit` and `handshook`.
1820            pending: None,
1821            overridden: None,
1822        }
1823    }
1824
1825    /// fails if the builder's defaults drift from what a registered-but-not-yet
1826    /// running sheep actually looks like. A builder that quietly defaulted
1827    /// `uptime_ms` to something non-zero, or `restarts` to 1, would put a wrong
1828    /// number in front of an operator with nothing to compare it against.
1829    #[test]
1830    fn a_builder_with_nothing_set_is_a_sheep_that_has_not_run() {
1831        let info = ProcessInfo::builder(3, "web", ProcStatus::Stopped).build();
1832
1833        assert_eq!(info.id, 3);
1834        assert_eq!(info.name, "web");
1835        assert_eq!(info.status, ProcStatus::Stopped);
1836        assert_eq!(info.pid, None);
1837        assert_eq!(info.restarts, 0);
1838        assert_eq!(info.uptime_ms, 0);
1839        assert_eq!(info.fold, None);
1840        assert_eq!(info.out_file, None);
1841        assert_eq!(info.err_file, None);
1842        assert_eq!(info.cpu_percent, None);
1843        assert_eq!(info.memory_bytes, None);
1844        assert_eq!(info.dog, None);
1845        assert_eq!(info.lambs, None);
1846        assert_eq!(info.last_exit, None);
1847    }
1848
1849    /// fails if any setter writes a field other than its own — the failure a
1850    /// twelve-field builder is most likely to ship, and one no individual
1851    /// round-trip test would catch. Every field is given a value distinct from
1852    /// every other field's default, so a copy-pasted setter body shows up as a
1853    /// mismatch rather than as a coincidence.
1854    #[test]
1855    fn every_setter_writes_its_own_field_and_no_other() {
1856        let built = ProcessInfo::builder(3, "web", ProcStatus::Online)
1857            .pid(Some(4242))
1858            .restarts(1)
1859            .uptime_ms(60_000)
1860            .fold(Some("backend".to_string()))
1861            .out_file(Some("/home/ada/.shep/logs/web-0-out.log".to_string()))
1862            .err_file(Some("/home/ada/.shep/logs/web-0-err.log".to_string()))
1863            .cpu_percent(Some(12.5))
1864            .memory_bytes(Some(48 * 1024 * 1024))
1865            .dog(None)
1866            .last_exit(Some(ExitInfo {
1867                code: Some(1),
1868                signal: None,
1869            }))
1870            .build();
1871
1872        // `sample_info()` is still a struct literal, on purpose: it is the one
1873        // place in the workspace that names every field by hand, so this
1874        // comparison fails the day the struct grows a field the builder cannot
1875        // set. That is the point of comparing against it rather than against
1876        // another builder call.
1877        assert_eq!(built, sample_info());
1878
1879        // `dog` is the one field the comparison above cannot speak for, and it
1880        // is the field the whole dogs subsystem reads. `sample_info()`'s `dog`
1881        // is `None`, which is also the builder's default, so a `dog` setter with
1882        // an EMPTY BODY passes the assert_eq! above and passes it for the wrong
1883        // reason. `sample_info()` cannot be changed to `Some(..)` to fix that —
1884        // it feeds `reply_wire_snapshots` and `bus_event_wire_snapshots`, so
1885        // altering it moves pinned bytes. So the field gets its own line, with a
1886        // value nothing defaults to.
1887        assert_eq!(
1888            ProcessInfo::builder(1, "metrics", ProcStatus::Online)
1889                .dog(Some(DogSource::BuiltIn))
1890                .build()
1891                .dog,
1892            Some(DogSource::BuiltIn),
1893            "an empty `dog` setter body is invisible to the comparison above"
1894        );
1895
1896        // `lambs` is the second field the comparison above cannot speak for,
1897        // for the identical reason `dog` is the first: `sample_info()`'s value
1898        // is `None`, which is also the builder's default, so an EMPTY `lambs`
1899        // setter body passes the `assert_eq!` above. And `sample_info()` still
1900        // cannot be changed to a `Some(..)` — it feeds `reply_wire_snapshots`
1901        // and `bus_event_wire_snapshots`, so altering it moves pinned bytes.
1902        assert_eq!(
1903            ProcessInfo::builder(1, "web", ProcStatus::Online)
1904                .lambs(Some(vec![Lamb::new(4243, "node")]))
1905                .build()
1906                .lambs,
1907            Some(vec![Lamb::new(4243, "node")]),
1908            "an empty `lambs` setter body is invisible to the comparison above"
1909        );
1910
1911        // `smit` is the third, on the same terms, and it is the field a
1912        // third party writes — so an empty setter body here would silently
1913        // drop every dog's mark rather than merely lose a decoration.
1914        assert_eq!(
1915            ProcessInfo::builder(1, "web", ProcStatus::Online)
1916                .smit(Some("\u{25b2} main@a1b2c3".to_string()))
1917                .build()
1918                .smit
1919                .as_deref(),
1920            Some("\u{25b2} main@a1b2c3"),
1921            "an empty `smit` setter body is invisible to the comparison above"
1922        );
1923
1924        // `handshook` is the fourth field, on the same terms as the three
1925        // above: `sample_info()`'s value is `None`, which is also the
1926        // builder's default, so an EMPTY `handshook` setter body would pass
1927        // the `assert_eq!` above. `sample_info()` still cannot be changed to
1928        // a `Some(..)` — it feeds `reply_wire_snapshots` and
1929        // `bus_event_wire_snapshots`, so altering it moves pinned bytes.
1930        assert_eq!(
1931            ProcessInfo::builder(1, "web", ProcStatus::Online)
1932                .handshook(Some(false))
1933                .build()
1934                .handshook,
1935            Some(false),
1936            "an empty `handshook` setter body is invisible to the comparison above"
1937        );
1938
1939        // `dog_stale` is the fifth, and the pairing is the point: it and
1940        // `handshook` are both `None` by default, so a setter that dropped
1941        // this one would leave every dog row saying "silent" and never
1942        // "given up on" -- the exact distinction the field was added to
1943        // carry.
1944        assert_eq!(
1945            ProcessInfo::builder(1, "web", ProcStatus::Online)
1946                .dog_stale(Some(true))
1947                .build()
1948                .dog_stale,
1949            Some(true),
1950            "an empty `dog_stale` setter body is invisible to the comparison above"
1951        );
1952
1953        // `pending` is the sixth field, on the same terms as the five above.
1954        assert_eq!(
1955            ProcessInfo::builder(1, "web", ProcStatus::Online)
1956                .pending(Some(vec!["env".to_string()]))
1957                .build()
1958                .pending,
1959            Some(vec!["env".to_string()]),
1960            "an empty `pending` setter body is invisible to the comparison above"
1961        );
1962
1963        // `overridden` is the seventh and last, on the same terms.
1964        assert_eq!(
1965            ProcessInfo::builder(1, "web", ProcStatus::Online)
1966                .overridden(Some(vec!["cwd".to_string()]))
1967                .build()
1968                .overridden,
1969            Some(vec!["cwd".to_string()]),
1970            "an empty `overridden` setter body is invisible to the comparison above"
1971        );
1972    }
1973
1974    /// fails if `lambs` collapses to a bare `Vec`. The three states are the point:
1975    /// a peer that predates the field and a reply that did not walk the tree are
1976    /// both `None`, and a sheep that really has no children is `Some(vec![])`. A
1977    /// `Vec` would render the first two as "this sheep has no lambs", which is a
1978    /// claim neither of them makes.
1979    #[test]
1980    fn lambs_distinguishes_not_walked_from_walked_and_empty() {
1981        let not_walked = ProcessInfo::builder(1, "web", ProcStatus::Online).build();
1982        assert_eq!(not_walked.lambs, None);
1983
1984        let walked_empty = ProcessInfo::builder(1, "web", ProcStatus::Online)
1985            .lambs(Some(Vec::new()))
1986            .build();
1987        assert_eq!(walked_empty.lambs, Some(Vec::new()));
1988    }
1989
1990    /// fails if a `ProcessInfo` from a daemon that predates the field stops
1991    /// deserializing. That is the whole reason the field is optional and the reason
1992    /// `PROTOCOL_VERSION` does not move for it — an old daemon's reply carries no
1993    /// `lambs` key at all, and a required field there would mean a new client could
1994    /// not list against an old daemon.
1995    #[test]
1996    fn a_process_info_without_a_lambs_key_still_deserializes() {
1997        let fixture = r#"{
1998            "id": 3, "name": "web", "status": "online", "pid": 4242,
1999            "restarts": 0, "uptime_ms": 100, "fold": null,
2000            "out_file": null, "err_file": null,
2001            "cpu_percent": null, "memory_bytes": null, "dog": null
2002        }"#;
2003        let info: ProcessInfo = serde_json::from_str(fixture).unwrap();
2004        assert_eq!(info.lambs, None);
2005    }
2006
2007    /// fails if a lamb stops carrying its name, or starts carrying a command line.
2008    /// The name is `sysinfo`'s executable name, never argv — argv routinely holds
2009    /// credentials (`--password=`, `?token=`) and `shep describe --format json` is
2010    /// output people paste into issues.
2011    #[test]
2012    fn a_lamb_is_a_pid_and_an_executable_name() {
2013        let lamb = Lamb::new(4243, "node");
2014        let json = serde_json::to_string(&lamb).unwrap();
2015        assert_eq!(json, r#"{"pid":4243,"name":"node"}"#);
2016        assert_eq!(serde_json::from_str::<Lamb>(&json).unwrap(), lamb);
2017    }
2018
2019    /// fails if `DogSource` loses its `tag = "kind"` or its snake_case
2020    /// rename, and fails if `Adopted`'s `path` is renamed — any of the three
2021    /// changes one of these two strings while every type-level test in this
2022    /// module keeps passing. The marker is what the CLI splits two tables on
2023    /// and what the metrics dog reports a health gauge from, so a silent
2024    /// rename here is a silently empty dogs table.
2025    #[test]
2026    fn a_dog_source_serializes_snake_case_under_its_kind() {
2027        assert_eq!(
2028            serde_json::to_string(&DogSource::BuiltIn).unwrap(),
2029            r#"{"kind":"built_in"}"#
2030        );
2031        let adopted = DogSource::Adopted {
2032            path: "/usr/local/bin/shep-otel".to_string(),
2033        };
2034        let wire = r#"{"kind":"adopted","path":"/usr/local/bin/shep-otel"}"#;
2035        assert_eq!(serde_json::to_string(&adopted).unwrap(), wire);
2036        assert_eq!(serde_json::from_str::<DogSource>(wire).unwrap(), adopted);
2037    }
2038
2039    /// fails if `dog` stops being optional. A daemon built before dogs
2040    /// sends a reply with no such key and still announces protocol 1, so a
2041    /// required field would make a current client unable to list against it
2042    /// at all — the same skew rule `out_file` and `cpu_percent` are pinned
2043    /// under, and the same committed-byte-fixture proof.
2044    #[test]
2045    fn v1_process_info_without_a_dog_marker_still_deserializes() {
2046        let fixture = r#"{"id":3,"name":"web","status":"online","pid":4242,"restarts":1,"uptime_ms":60000,"fold":"backend","out_file":"/l/o.log","err_file":"/l/e.log","cpu_percent":12.5,"memory_bytes":50331648}"#;
2047        let info: ProcessInfo = serde_json::from_str(fixture).unwrap();
2048        assert_eq!(info.dog, None);
2049    }
2050
2051    /// fails if `last_exit` stops being optional. A daemon built before this
2052    /// field sends a reply with no such key and still announces protocol 1 —
2053    /// the same skew rule every other field added after `Hello`/`HelloAck`
2054    /// were fixed is pinned under.
2055    ///
2056    /// This is also the empirical proof of a subtle point: none of
2057    /// `ProcessInfo`'s fields carry `#[serde(default)]`, and there is
2058    /// no container-level one either, yet the doc comments on `out_file` and
2059    /// `cpu_percent` both claim "`None` only when the peer daemon predates
2060    /// this field" as though one existed. Serde's `Deserialize` derive
2061    /// special-cases a field whose type is syntactically `Option<...>`: a
2062    /// missing key resolves to `None` without `#[serde(default)]` doing
2063    /// anything, because the derive macro recognizes the `Option` wrapper
2064    /// itself and generates that fallback for it. Those doc comments were
2065    /// right; they just named the wrong mechanism, or none. This test pins
2066    /// the real one for `last_exit` specifically — with `dog` and `lambs`
2067    /// present but `last_exit` genuinely absent from the JSON below — rather
2068    /// than leaving it as an inference from `v1_process_info_without_a_dog_
2069    /// marker_still_deserializes` above.
2070    #[test]
2071    fn a_process_info_without_a_last_exit_key_still_deserializes() {
2072        let fixture = r#"{"id":3,"name":"web","status":"online","pid":4242,"restarts":1,"uptime_ms":60000,"fold":"backend","out_file":"/l/o.log","err_file":"/l/e.log","cpu_percent":12.5,"memory_bytes":50331648,"dog":null,"lambs":null}"#;
2073        let info: ProcessInfo = serde_json::from_str(fixture).unwrap();
2074        assert_eq!(info.last_exit, None);
2075    }
2076
2077    /// fails if a `Signal` frame stops carrying the signal name as plain text, or
2078    /// if the outcome rows stop distinguishing their three cases. The name travels
2079    /// as a `String` on purpose (`AppConfig::kill_signal` does the same): the wire
2080    /// stays readable and the daemon re-validates, which it has to do anyway
2081    /// because peer input is untrusted.
2082    #[test]
2083    fn a_signal_request_and_its_reply_round_trip() {
2084        let request = Request::Signal {
2085            selector: SelectorSpec::Name("web".to_string()),
2086            signal: "SIGHUP".to_string(),
2087        };
2088        let json = serde_json::to_string(&request).unwrap();
2089        assert_eq!(serde_json::from_str::<Request>(&json).unwrap(), request);
2090
2091        let reply = Response::Signalled(vec![
2092            SignalReply {
2093                id: 1,
2094                name: "web".to_string(),
2095                outcome: SignalOutcome::Delivered,
2096            },
2097            SignalReply {
2098                id: 2,
2099                name: "web".to_string(),
2100                outcome: SignalOutcome::NotRunning,
2101            },
2102            SignalReply {
2103                id: 3,
2104                name: "api".to_string(),
2105                outcome: SignalOutcome::Failed {
2106                    reason: "no such process".to_string(),
2107                },
2108            },
2109        ]);
2110        let json = serde_json::to_string(&reply).unwrap();
2111        assert_eq!(serde_json::from_str::<Response>(&json).unwrap(), reply);
2112        // The three tags, spelled out: a variant renamed in Rust changes these
2113        // strings mechanically, compiles clean, and breaks a client matching on
2114        // them with nothing to say why.
2115        assert!(json.contains(r#""kind":"delivered""#), "{json}");
2116        assert!(json.contains(r#""kind":"not_running""#), "{json}");
2117        assert!(json.contains(r#""kind":"failed""#), "{json}");
2118    }
2119
2120    /// fails if `Scale` grows a selector. It takes an app NAME, and that is the
2121    /// design: `instances` is a per-app number and instance slots are allocated
2122    /// per name-group, so `shep stock /web.*/ 4` would have to mean either four
2123    /// each or four total and there is no reading of it that is not a guess.
2124    #[test]
2125    fn a_scale_request_names_one_app_and_a_count() {
2126        let request = Request::Scale {
2127            name: "web".to_string(),
2128            count: 4,
2129        };
2130        let json = serde_json::to_string(&request).unwrap();
2131        assert_eq!(serde_json::from_str::<Request>(&json).unwrap(), request);
2132        assert!(json.contains(r#""kind":"scale""#), "{json}");
2133        assert!(json.contains(r#""name":"web""#), "{json}");
2134        // No `selector` key at all — the shape that says this verb is not one of
2135        // the selector-taking family.
2136        assert!(!json.contains("selector"), "{json}");
2137    }
2138
2139    /// fails if `Scaled` stops being distinguishable from the eight other replies
2140    /// carrying a bare `Vec<ProcessInfo>`. Each of those names which request it
2141    /// answers precisely so it can diverge later without a protocol bump — the
2142    /// enum's own doc says not to collapse them, and this is the test that notices.
2143    #[test]
2144    fn a_scaled_reply_carries_its_own_tag() {
2145        let json = serde_json::to_string(&Response::Scaled(vec![])).unwrap();
2146        assert_eq!(json, r#"{"kind":"scaled","data":[]}"#);
2147    }
2148
2149    /// fails if the three outcomes stop being tellable apart on the wire, or if
2150    /// `NotWritten` stops carrying its reason. That reason is the only thing that
2151    /// distinguishes "the app is not reading its stdin" from "the pipe broke", and
2152    /// the operator's next move differs between them.
2153    #[test]
2154    fn a_send_line_request_and_its_reply_round_trip() {
2155        let request = Request::SendLine {
2156            selector: SelectorSpec::Name("repl".to_string()),
2157            line: "reload-config".to_string(),
2158        };
2159        let json = serde_json::to_string(&request).unwrap();
2160        assert_eq!(serde_json::from_str::<Request>(&json).unwrap(), request);
2161
2162        let reply = Response::SentLine(vec![
2163            LineReply {
2164                id: 1,
2165                name: "repl".to_string(),
2166                outcome: LineOutcome::Sent,
2167            },
2168            LineReply {
2169                id: 2,
2170                name: "web".to_string(),
2171                outcome: LineOutcome::NoStdin,
2172            },
2173            LineReply {
2174                id: 3,
2175                name: "stuck".to_string(),
2176                outcome: LineOutcome::NotWritten {
2177                    reason: "the app did not read its stdin within 2s".to_string(),
2178                },
2179            },
2180        ]);
2181        let json = serde_json::to_string(&reply).unwrap();
2182        assert_eq!(serde_json::from_str::<Response>(&json).unwrap(), reply);
2183        assert!(json.contains(r#""kind":"sent""#), "{json}");
2184        assert!(json.contains(r#""kind":"no_stdin""#), "{json}");
2185        assert!(json.contains("did not read its stdin"), "{json}");
2186    }
2187
2188    /// fails if a newline can ride inside the line. The wire carries ONE line and
2189    /// the writer appends the terminator, so an embedded newline would deliver two
2190    /// commands where the operator typed one — the shape that turns a typo into an
2191    /// unintended second instruction to a REPL.
2192    #[test]
2193    fn a_line_carrying_a_newline_is_still_one_field_on_the_wire() {
2194        let request = Request::SendLine {
2195            selector: SelectorSpec::All,
2196            line: "a\nb".to_string(),
2197        };
2198        let json = serde_json::to_string(&request).unwrap();
2199        // Escaped, not literal: the frame stays one JSON object. Rejecting it is
2200        // the daemon's job (see `shep whisper`), not serde's, and this pins that
2201        // the wire itself does not quietly split it.
2202        assert!(json.contains(r#""line":"a\nb""#), "{json}");
2203        assert_eq!(serde_json::from_str::<Request>(&json).unwrap(), request);
2204    }
2205
2206    #[test]
2207    fn request_wire_snapshots() {
2208        let requests = vec![
2209            Envelope {
2210                id: 1,
2211                deadline_ms: Some(5000),
2212                body: Request::Ping,
2213            },
2214            Envelope {
2215                id: 2,
2216                deadline_ms: None,
2217                body: Request::ListFlock,
2218            },
2219            Envelope {
2220                id: 3,
2221                deadline_ms: None,
2222                body: Request::Stop {
2223                    selector: SelectorSpec::Name("web".to_string()),
2224                },
2225            },
2226            Envelope {
2227                id: 4,
2228                deadline_ms: None,
2229                body: Request::Start {
2230                    apps: vec![AppConfig::minimal("web", "./srv")],
2231                },
2232            },
2233            // `All` rather than a named sheep: it is the selector `shep
2234            // reopen` sends when given no argument, and the one a signal can
2235            // ever mean, so it is the row worth pinning.
2236            Envelope {
2237                id: 5,
2238                deadline_ms: None,
2239                body: Request::Reopen {
2240                    selector: SelectorSpec::All,
2241                },
2242            },
2243            // Deliberately the same selector as the row above, so the two
2244            // log-plane rows differ by their `kind` and by nothing else: a
2245            // `Flush` that serialized under `reopen`'s tag — the shape a
2246            // copy-pasted variant takes — shows up here as two identical
2247            // objects rather than as a diff a reader has to compare field by
2248            // field. `shep flush` demands an explicit selector, so `all` is
2249            // not a default here the way it is for `reopen`; it is simply the
2250            // widest thing an operator can type.
2251            Envelope {
2252                id: 6,
2253                deadline_ms: None,
2254                body: Request::Flush {
2255                    selector: SelectorSpec::All,
2256                },
2257            },
2258            // The same selector as the `stop` row above, for the reason the
2259            // pair above share theirs: `reload` is the third verb that
2260            // demands an explicit selector and replaces what it matches, so
2261            // the variant it would be copy-pasted from is `stop`. Serialized
2262            // under `stop`'s tag it shows up here as two identical objects
2263            // rather than as a diff a reader has to compare field by field.
2264            Envelope {
2265                id: 7,
2266                deadline_ms: None,
2267                body: Request::Reload {
2268                    selector: SelectorSpec::Name("web".to_string()),
2269                },
2270            },
2271            // `action`/`params` here match the spec's own §9 example
2272            // (`trigger web set-log-level debug`) and channel.rs's
2273            // with-params fixture verbatim, so a reader tracing a trigger
2274            // from the CLI through the client↔daemon wire to the fd-3 wire
2275            // sees the same two strings at every hop rather than three
2276            // unrelated examples.
2277            Envelope {
2278                id: 8,
2279                deadline_ms: None,
2280                body: Request::Trigger {
2281                    selector: SelectorSpec::Name("web".to_string()),
2282                    action: "set-log-level".to_string(),
2283                    params: Some("debug".to_string()),
2284                },
2285            },
2286            // The first fieldless verb added since `Ping`/`ListFlock`, and
2287            // pinned for that reason: a fieldless variant serializes as a
2288            // bare `{"kind":"..."}` with no `selector` key at all, so a
2289            // reader comparing this row against `stop`'s sees the whole
2290            // difference between the two shapes in one place.
2291            Envelope {
2292                id: 9,
2293                deadline_ms: None,
2294                body: Request::SaveRoll,
2295            },
2296            // Paired with the `save_roll` row above so the two halves of the
2297            // roll — the direction that writes it and the direction that
2298            // assembles from it — sit next to each other, differing by their
2299            // `kind` and by nothing else.
2300            Envelope {
2301                id: 10,
2302                deadline_ms: None,
2303                body: Request::Muster,
2304            },
2305            // The three dog verbs together, in the order an operator meets
2306            // them: ask for a section, start a dog, stop one. Adjacent on
2307            // purpose — `enable_dog` and `disable_dog` differ by their
2308            // `kind` and by `source`, so a `DisableDog` accidentally given
2309            // `EnableDog`'s tag shows up here as two near-identical objects
2310            // rather than as a diff a reader has to compare field by field.
2311            Envelope {
2312                id: 11,
2313                deadline_ms: None,
2314                body: Request::DogConfig {
2315                    name: "bark".to_string(),
2316                },
2317            },
2318            Envelope {
2319                id: 12,
2320                deadline_ms: None,
2321                body: Request::EnableDog {
2322                    name: "metrics".to_string(),
2323                    source: DogSource::BuiltIn,
2324                },
2325            },
2326            Envelope {
2327                id: 13,
2328                deadline_ms: None,
2329                body: Request::DisableDog {
2330                    name: "metrics".to_string(),
2331                },
2332            },
2333            // Grouped and adjacent on purpose: `Id`, `Regex` and `Fold` are
2334            // three newtypes over three different inner types, and the wire
2335            // tells them apart only by their own `kind` tag — a `Fold` that
2336            // serialized under `regex`'s tag is a `shep restart fold:api`
2337            // that silently becomes a regex match, which is a wrong set of
2338            // sheep restarted and not an error anyone sees.
2339            Envelope {
2340                id: 14,
2341                deadline_ms: None,
2342                body: Request::Describe {
2343                    selector: SelectorSpec::Id(7),
2344                },
2345            },
2346            Envelope {
2347                id: 15,
2348                deadline_ms: None,
2349                body: Request::Describe {
2350                    selector: SelectorSpec::Regex("^web-".to_string()),
2351                },
2352            },
2353            Envelope {
2354                id: 16,
2355                deadline_ms: None,
2356                body: Request::Describe {
2357                    selector: SelectorSpec::Fold("api".to_string()),
2358                },
2359            },
2360            // `SIGHUP` rather than `SIGTERM`: TERM is what the stop ladder
2361            // already sends, so a fixture using it could not tell a `signal`
2362            // frame from a stop's. HUP is the signal this verb exists for.
2363            Envelope {
2364                id: 17,
2365                deadline_ms: None,
2366                body: Request::Signal {
2367                    selector: SelectorSpec::Name("web".to_string()),
2368                    signal: "SIGHUP".to_string(),
2369                },
2370            },
2371            // The one verb in this enum whose body has no `selector` key at
2372            // all — a reader comparing this row against `stop`'s sees the
2373            // whole difference in one place.
2374            Envelope {
2375                id: 18,
2376                deadline_ms: None,
2377                body: Request::Scale {
2378                    name: "web".to_string(),
2379                    count: 4,
2380                },
2381            },
2382            // `SelectorSpec::All` rather than a named sheep, mirroring the
2383            // `reopen`/`flush` rows above: it is the widest thing an operator
2384            // can type, and the line carries no terminator on the wire — the
2385            // shepherd appends it — so a fixture with one proves that half of
2386            // the contract too.
2387            Envelope {
2388                id: 19,
2389                deadline_ms: None,
2390                body: Request::SendLine {
2391                    selector: SelectorSpec::All,
2392                    line: "reload-config".to_string(),
2393                },
2394            },
2395            // The second verb here with no `selector` key, and the only one
2396            // whose payload a third party writes. Both halves of its
2397            // `Option` are pinned — a paint and a clear — because a dog
2398            // author reading this fixture needs the clear frame's exact
2399            // shape and would otherwise have to guess `null`.
2400            Envelope {
2401                id: 20,
2402                deadline_ms: None,
2403                body: Request::SetSmit {
2404                    sheep: "web".to_string(),
2405                    smit: Some(
2406                        "\u{25b2} main@a1b2c3"
2407                            .parse()
2408                            .expect("the reference smit is valid"),
2409                    ),
2410                },
2411            },
2412            Envelope {
2413                id: 21,
2414                deadline_ms: None,
2415                body: Request::SetSmit {
2416                    sheep: "web".to_string(),
2417                    smit: None,
2418                },
2419            },
2420            // An EMPTY `apps`, unlike `start`'s row above. The two carry the
2421            // identical payload type, so a second `AppConfig` blob here would
2422            // pin nothing `start`'s blob does not already pin, at fifty lines
2423            // of snapshot. What is genuinely this row's own is the tag and
2424            // the key the list travels under, and an empty list shows both.
2425            Envelope {
2426                id: 22,
2427                deadline_ms: None,
2428                body: Request::ConfigDrift { apps: Vec::new() },
2429            },
2430            // The only STRUCT-shaped `SelectorSpec` variant, and the one
2431            // whose serialized shape moved `PROTOCOL_VERSION` from 1 to 2.
2432            // Every other selector on this wire is a unit or a newtype, both
2433            // already pinned by the rows above, so this row is the only place
2434            // `"kind":"instance"` and the `slot` key are held to anything.
2435            // Without it, renaming the field or flattening the variant turned
2436            // nothing red on the exact type the version bump was for.
2437            Envelope {
2438                id: 23,
2439                deadline_ms: None,
2440                body: Request::Restart {
2441                    selector: SelectorSpec::Instance {
2442                        name: "web".to_string(),
2443                        slot: 2,
2444                    },
2445                },
2446            },
2447            // The one request in this enum that an older daemon must never
2448            // be sent, so the one whose exact tag matters most: shep-cli
2449            // gates it on the daemon's crate version, and a rename here
2450            // would be a variant nothing on either side recognises.
2451            Envelope {
2452                id: 24,
2453                deadline_ms: None,
2454                body: Request::HandoverFitness,
2455            },
2456            // The second request gated on the daemon's crate version, and
2457            // pinned beside the first for that reason: the two are asked by
2458            // the same verb, of the two daemons either side of the same
2459            // handover, and a rename of either is a variant nothing on
2460            // either side recognises.
2461            Envelope {
2462                id: 25,
2463                deadline_ms: None,
2464                body: Request::DogStaleness,
2465            },
2466            // The only request carrying a `DeclaredApp` rather than a bare
2467            // `AppConfig`, and the two key sets beside the config are the
2468            // whole reason it does: a merge keys on what a document CLAIMED,
2469            // so a reader that dropped `declared` would apply every default
2470            // the document never wrote. `declared_env` is pinned non-empty
2471            // for the same reason and one more -- it holds env key NAMES,
2472            // and a fixture is where an out-of-tree reader learns that no
2473            // env VALUE travels under it (IR-41).
2474            //
2475            // `reset` is pinned at its non-default depth. The default
2476            // serializes as `"none"`, which is the one value a reader could
2477            // get right by accident.
2478            Envelope {
2479                id: 26,
2480                deadline_ms: None,
2481                body: Request::ApplyConfig {
2482                    apps: vec![DeclaredApp {
2483                        config: AppConfig::minimal("web", "./srv"),
2484                        declared: ["name", "script"]
2485                            .iter()
2486                            .map(|k| (*k).to_string())
2487                            .collect(),
2488                        declared_env: ["DATABASE_URL"].iter().map(|k| (*k).to_string()).collect(),
2489                    }],
2490                    reset: ResetDepth::Settings,
2491                },
2492            },
2493        ];
2494        insta::assert_json_snapshot!("request_wire_v2", requests);
2495    }
2496
2497    #[test]
2498    fn reply_wire_snapshots() {
2499        let replies = vec![
2500            Reply {
2501                id: 1,
2502                result: Ok(Response::Pong),
2503            },
2504            Reply {
2505                id: 2,
2506                result: Ok(Response::Flock(vec![sample_info()])),
2507            },
2508            Reply {
2509                id: 3,
2510                result: Err(RpcError {
2511                    code: RpcErrorCode::NotFound,
2512                    message: "no sheep matches `web`".to_string(),
2513                    daemon_version: None,
2514                }),
2515            },
2516            // Unlike `Reopened`/`Flushed`/`Reloading` above (all wire-identical
2517            // to `Flock`, just under a different `kind` tag, so pinning `Flock`
2518            // once already covers their shape), `Triggered` carries a genuinely
2519            // different row — `ActionReply` is not a `ProcessInfo` — so it earns
2520            // its own entry. `Replied` is the struct-shaped variant of
2521            // `ActionOutcome`, and so the one worth pinning here: the three
2522            // unit variants serialize as bare `{"kind":"..."}`, a shape already
2523            // proven by every fieldless variant elsewhere on this wire.
2524            Reply {
2525                id: 4,
2526                result: Ok(Response::Triggered(vec![ActionReply {
2527                    id: 3,
2528                    name: "web".to_string(),
2529                    outcome: ActionOutcome::Replied {
2530                        body: "ok".to_string(),
2531                    },
2532                }])),
2533            },
2534            // The only struct-shaped `Response` variant, so the one worth
2535            // pinning here: every other variant on this wire is a newtype
2536            // over a Vec or a unit, both shapes already proven above.
2537            Reply {
2538                id: 5,
2539                result: Ok(Response::RollSaved {
2540                    path: "/home/ada/.shep/flock.json".to_string(),
2541                    apps: 2,
2542                }),
2543            },
2544            // `sample_info()` above pins the absent marker (a sheep's
2545            // `"dog": null`); this row is the only place the present one is
2546            // pinned, and `Adopted` rather than `BuiltIn` because it is the
2547            // variant carrying a payload — the unit variant's shape is
2548            // already proven by every fieldless variant on this wire.
2549            Reply {
2550                id: 6,
2551                result: Ok(Response::Flock(vec![ProcessInfo {
2552                    id: 7,
2553                    name: "otel".to_string(),
2554                    dog: Some(DogSource::Adopted {
2555                        path: "/usr/local/bin/shep-otel".to_string(),
2556                    }),
2557                    ..sample_info()
2558                }])),
2559            },
2560            // The opaque blob, pinned as a blob: the daemon renders a TOML
2561            // table into a string and never a typed structure, so what this
2562            // row proves is that the section crosses the wire as text.
2563            Reply {
2564                id: 7,
2565                result: Ok(Response::DogSection {
2566                    toml: "port = 9615\n".to_string().into(),
2567                }),
2568            },
2569            // The only `Response` variant carrying a BARE `ProcessInfo`
2570            // rather than a `Vec` of them: `enable` starts exactly one dog,
2571            // and a one-element list would invite a reader to wonder when it
2572            // holds two.
2573            Reply {
2574                id: 8,
2575                result: Ok(Response::DogStarted(ProcessInfo {
2576                    id: 4,
2577                    name: "metrics".to_string(),
2578                    dog: Some(DogSource::BuiltIn),
2579                    ..sample_info()
2580                })),
2581            },
2582            // The existing comment on the `Triggered` row is right that pinning
2583            // `Flock` once already proves the `Vec<ProcessInfo>` SHAPE — but
2584            // it does not prove any of these variants' own `kind` tags, and
2585            // three of them are not `Vec<ProcessInfo>`-shaped at all
2586            // (`Deleted` is a `Vec<u32>`, `Subscribed` and `ShuttingDown`
2587            // carry nothing). Each row below therefore carries the smallest
2588            // body that shows its wire shape — empty where empty is legal,
2589            // `Deleted`'s two ids where the shape needs elements: what is
2590            // being pinned here is the tag, and a body repeated eight times
2591            // would bury it.
2592            Reply {
2593                id: 9,
2594                result: Ok(Response::Described(vec![])),
2595            },
2596            Reply {
2597                id: 10,
2598                result: Ok(Response::Started(vec![])),
2599            },
2600            Reply {
2601                id: 11,
2602                result: Ok(Response::Stopped(vec![])),
2603            },
2604            Reply {
2605                id: 12,
2606                result: Ok(Response::Restarted(vec![])),
2607            },
2608            Reply {
2609                id: 13,
2610                result: Ok(Response::Reloading(vec![])),
2611            },
2612            Reply {
2613                id: 14,
2614                result: Ok(Response::Deleted(vec![7, 8])),
2615            },
2616            Reply {
2617                id: 15,
2618                result: Ok(Response::Reopened(vec![])),
2619            },
2620            Reply {
2621                id: 16,
2622                result: Ok(Response::Flushed(vec![])),
2623            },
2624            Reply {
2625                id: 17,
2626                result: Ok(Response::Mustered(vec![])),
2627            },
2628            Reply {
2629                id: 18,
2630                result: Ok(Response::Subscribed),
2631            },
2632            Reply {
2633                id: 19,
2634                result: Ok(Response::ShuttingDown),
2635            },
2636            // `Signalled`, mirroring the `Triggered` row above: three rows,
2637            // one per `SignalOutcome` variant, so a reader sees the whole
2638            // shape of the reply in one pinned fixture rather than one row
2639            // that happens to hit `Delivered` and leaves the other two tags
2640            // unproven.
2641            Reply {
2642                id: 20,
2643                result: Ok(Response::Signalled(vec![
2644                    SignalReply {
2645                        id: 1,
2646                        name: "web".to_string(),
2647                        outcome: SignalOutcome::Delivered,
2648                    },
2649                    SignalReply {
2650                        id: 2,
2651                        name: "web".to_string(),
2652                        outcome: SignalOutcome::NotRunning,
2653                    },
2654                    SignalReply {
2655                        id: 3,
2656                        name: "api".to_string(),
2657                        outcome: SignalOutcome::Failed {
2658                            reason: "no such process".to_string(),
2659                        },
2660                    },
2661                ])),
2662            },
2663            Reply {
2664                id: 21,
2665                result: Ok(Response::Scaled(vec![sample_info()])),
2666            },
2667            // `SentLine`, mirroring the `Signalled` row above: three rows, one
2668            // per `LineOutcome` variant, so a reader sees the whole shape of
2669            // the reply in one pinned fixture rather than one row that
2670            // happens to hit `Sent` and leaves the other two tags unproven.
2671            Reply {
2672                id: 22,
2673                result: Ok(Response::SentLine(vec![
2674                    LineReply {
2675                        id: 1,
2676                        name: "repl".to_string(),
2677                        outcome: LineOutcome::Sent,
2678                    },
2679                    LineReply {
2680                        id: 2,
2681                        name: "web".to_string(),
2682                        outcome: LineOutcome::NoStdin,
2683                    },
2684                    LineReply {
2685                        id: 3,
2686                        name: "stuck".to_string(),
2687                        outcome: LineOutcome::NotWritten {
2688                            reason: "the app did not read its stdin within 2s".to_string(),
2689                        },
2690                    },
2691                ])),
2692            },
2693            // A `Described` row with a real lamb tree. The `null` shape is pinned
2694            // on every other row here; this is the one that pins what a walked
2695            // sheep serializes as, which is the shape a `describe` consumer
2696            // actually parses.
2697            Reply {
2698                id: 23,
2699                result: Ok(Response::Described(vec![
2700                    ProcessInfo::builder(3, "web", ProcStatus::Online)
2701                        .pid(Some(4242))
2702                        .lambs(Some(vec![Lamb::new(4243, "node"), Lamb::new(4244, "sh")]))
2703                        .build(),
2704                ])),
2705            },
2706            // `sample_info()` pins `last_exit`'s "exited normally" shape
2707            // (`code` set, `signal` absent) on every row above; this is the
2708            // only place the other one — killed by a signal, `code` absent
2709            // — is pinned. `SIGTERM`'s raw number (15) rather than a
2710            // symbolic one, because [`ExitInfo::signal`]'s own doc says this
2711            // crate carries no name for it; naming one is a job for
2712            // whichever OS-aware layer renders this field.
2713            Reply {
2714                id: 24,
2715                result: Ok(Response::Flock(vec![
2716                    ProcessInfo::builder(5, "worker", ProcStatus::Stopped)
2717                        .restarts(1)
2718                        .last_exit(Some(ExitInfo {
2719                            code: None,
2720                            signal: Some(15),
2721                        }))
2722                        .build(),
2723                ])),
2724            },
2725            // The one row that pins a smit on the wire. `sample_info()`
2726            // carries none, deliberately (see `every_setter_writes_its_own_
2727            // field_and_no_other` for why it cannot), so without this row
2728            // the field is pinned only in its absent shape — and the absent
2729            // shape is not the one a dog's reader has to parse.
2730            Reply {
2731                id: 25,
2732                result: Ok(Response::SmitPainted(vec![
2733                    ProcessInfo::builder(3, "web", ProcStatus::Online)
2734                        .pid(Some(4242))
2735                        .smit(Some("\u{25b2} main@a1b2c3".to_string()))
2736                        .build(),
2737                ])),
2738            },
2739            // Two entries in one reply, and each is the shape the other is
2740            // not: a sheep drifting in one field and a sheep drifting in
2741            // several. `env` is deliberately one of them, because reporting
2742            // it as a bare NAME is the whole security property of this row
2743            // (IR-41) and a fixture is where an out-of-tree reader learns
2744            // that no value ever travels with it.
2745            Reply {
2746                id: 26,
2747                result: Ok(Response::Drifted(vec![
2748                    SheepDrift::new("web", vec!["cwd".to_string()]),
2749                    SheepDrift::new(
2750                        "api",
2751                        vec!["args".to_string(), "env".to_string(), "script".to_string()],
2752                    ),
2753                ])),
2754            },
2755            // `sample_info()` pins `instance`'s absent shape (`None`, an old
2756            // peer or a single-instance app); every row above reuses it, so
2757            // without this row the present shape (`Some(2)`, a live slot on
2758            // a scaled app) is never on the wire at all.
2759            Reply {
2760                id: 27,
2761                result: Ok(Response::Flock(vec![
2762                    ProcessInfo::builder(9, "web", ProcStatus::Online)
2763                        .pid(Some(5150))
2764                        .instance(Some(2))
2765                        .build(),
2766                ])),
2767            },
2768            // Both shapes of the handover answer, because the difference
2769            // between them is a `null` and a caller that read the key's
2770            // presence rather than its value would pass on one and refuse
2771            // every flock on the other.
2772            Reply {
2773                id: 28,
2774                result: Ok(Response::HandoverFitness { refusal: None }),
2775            },
2776            Reply {
2777                id: 29,
2778                result: Ok(Response::HandoverFitness {
2779                    refusal: Some("sheep 'web' has a shepherd channel".to_string()),
2780                }),
2781            },
2782            // Both lists non-empty and DIFFERENT, because the two carry the
2783            // same wire shape and a reply that filled one from the other
2784            // would be invisible in a fixture that used the same names
2785            // twice. Empty is the shape an ordinary reload sees, and it is
2786            // already proven by every `Vec`-carrying row above.
2787            Reply {
2788                id: 30,
2789                result: Ok(Response::DogStaleness {
2790                    stale: vec!["metrics".to_string()],
2791                    pending: vec!["bark".to_string()],
2792                }),
2793            },
2794            // `sample_info()` pins `handshook`'s absent shape (`None`, a
2795            // sheep or an older peer); every row above reuses it, so
2796            // without this row the shape that actually changes an
2797            // operator's reading — a dog whose process is up and which has
2798            // never answered this shepherd — is never on the wire at all.
2799            //
2800            // `dog_stale: false` is not padding: this is the silence the
2801            // shepherd is still waiting out, and the row below is the one it
2802            // has given up on. The two differ in exactly one byte-level key
2803            // and in what every operator-facing surface must say about them,
2804            // so pinning one without the other would leave the distinction
2805            // untested on the wire it travels over.
2806            Reply {
2807                id: 31,
2808                result: Ok(Response::Flock(vec![
2809                    ProcessInfo::builder(10, "log-rotate", ProcStatus::Online)
2810                        .pid(Some(208_341))
2811                        .dog(Some(DogSource::Adopted {
2812                            path: "/usr/local/bin/shep-log-rotate".to_string(),
2813                        }))
2814                        .handshook(Some(false))
2815                        .dog_stale(Some(false))
2816                        .build(),
2817                ])),
2818            },
2819            Reply {
2820                id: 32,
2821                result: Ok(Response::Flock(vec![
2822                    ProcessInfo::builder(10, "log-rotate", ProcStatus::Online)
2823                        .pid(Some(208_341))
2824                        .dog(Some(DogSource::Adopted {
2825                            path: "/usr/local/bin/shep-log-rotate".to_string(),
2826                        }))
2827                        .handshook(Some(false))
2828                        .dog_stale(Some(true))
2829                        .build(),
2830                ])),
2831            },
2832            // Three entries, because the three shapes a load produces are
2833            // not interchangeable and a reader that saw only one would
2834            // guess wrong about the others: an app that applied cleanly, an
2835            // app whose change is waiting for a respawn, and an app that
2836            // was refused outright. The refusal's `null` twin is pinned by
2837            // the first two rows, so a reader learns the key is always
2838            // present rather than sometimes absent.
2839            //
2840            // `env` is one of the pending names on purpose. Reporting it as
2841            // a bare NAME is this reply's whole security property (IR-41),
2842            // and a fixture is where an out-of-tree reader learns that no
2843            // value ever travels with it.
2844            Reply {
2845                id: 32,
2846                result: Ok(Response::Applied(vec![
2847                    SheepApplied::new("web", vec!["max_memory".to_string()], Vec::new(), None),
2848                    SheepApplied::new(
2849                        "api",
2850                        Vec::new(),
2851                        vec!["args".to_string(), "env".to_string()],
2852                        None,
2853                    ),
2854                    SheepApplied::new(
2855                        "worker",
2856                        Vec::new(),
2857                        Vec::new(),
2858                        Some("worker is not registered".to_string()),
2859                    ),
2860                ])),
2861            },
2862        ];
2863        insta::assert_json_snapshot!("reply_wire_v2", replies);
2864    }
2865
2866    /// fails if `applied` or `pending` ever carries a field's VALUE rather
2867    /// than its name. This reply is printed at an operator and `env` values
2868    /// are secrets, so the wire form of those two lists has to be names
2869    /// alone (IR-41). `refused` is prose and is scoped out of that rule at
2870    /// the type -- see its own doc for why -- so it is left `None` here
2871    /// rather than asserted on.
2872    ///
2873    /// Asserts on the serialized JSON rather than on the struct, because the
2874    /// struct's `Vec<String>` cannot say which of the two a string is: a
2875    /// build that put `DATABASE_URL=postgres://...` in the list would type-
2876    /// check and pass any assertion made on the field's shape.
2877    #[test]
2878    fn a_sheep_applied_carries_names_and_never_values() {
2879        let applied = SheepApplied::new(
2880            "web",
2881            vec!["cwd".to_string()],
2882            vec!["env".to_string()],
2883            None,
2884        );
2885        let json = serde_json::to_string(&applied).unwrap();
2886        assert!(json.contains("\"env\""), "the NAME travels: {json}");
2887        assert!(
2888            !json.contains("DATABASE_URL"),
2889            "and no value ever does: {json}"
2890        );
2891    }
2892
2893    /// fails if `SheepApplied`'s `Debug` grows a value. Derived today because
2894    /// there is nothing here to redact, and that is a property of what the
2895    /// daemon puts IN it rather than of the derive, so it is worth one exact
2896    /// string (IR-41).
2897    #[test]
2898    fn a_sheep_applied_debug_prints_the_names_it_was_given() {
2899        let applied = SheepApplied::new("web", vec!["cwd".to_string()], Vec::new(), None);
2900        assert_eq!(
2901            format!("{applied:?}"),
2902            "SheepApplied { name: \"web\", applied: [\"cwd\"], pending: [], refused: None }"
2903        );
2904    }
2905
2906    /// fails if the new field breaks an older peer, on the same terms as
2907    /// `last_exit` and `lambs` before it. A daemon that predates smits sends
2908    /// no `smit` key, and this decoding to `None` rather than erroring is
2909    /// what keeps `PROTOCOL_VERSION` at 2 rather than needing another bump.
2910    #[test]
2911    fn a_process_info_without_a_smit_key_still_deserializes() {
2912        let fixture = r#"{"id":1,"name":"web","status":"online","pid":42,"restarts":0,"uptime_ms":10,"fold":null,"out_file":null,"err_file":null,"cpu_percent":null,"memory_bytes":null,"dog":null,"lambs":null,"last_exit":null}"#;
2913        let info: ProcessInfo = serde_json::from_str(fixture).unwrap();
2914        assert_eq!(info.smit, None);
2915    }
2916
2917    /// fails if `handshook` breaks an older peer, on the same terms as
2918    /// `smit` and `instance` before it. A daemon that predates the field
2919    /// sends no `handshook` key and still announces protocol 2, so this
2920    /// decoding to `None` rather than erroring is what keeps
2921    /// `PROTOCOL_VERSION` at 2: the evolution rule in this module's parent
2922    /// says an additive optional field keeps the version, and a required
2923    /// one would make a current client unable to list against that daemon
2924    /// at all.
2925    ///
2926    /// The fixture is a DOG's row, deliberately — that is the one row where
2927    /// the missing key changes what a renderer prints, and `None` there has
2928    /// to keep meaning "render this exactly as it rendered before the field
2929    /// existed" rather than "this dog has never handshaken".
2930    #[test]
2931    fn a_process_info_without_a_handshook_key_still_deserializes() {
2932        let fixture = r#"{"id":1,"name":"metrics","status":"online","pid":42,"restarts":0,"uptime_ms":10,"fold":null,"out_file":null,"err_file":null,"cpu_percent":null,"memory_bytes":null,"dog":{"kind":"built_in"},"lambs":null,"last_exit":null,"smit":null,"instance":0}"#;
2933        let info: ProcessInfo = serde_json::from_str(fixture).unwrap();
2934        assert_eq!(info.handshook, None);
2935        assert_eq!(info.dog, Some(DogSource::BuiltIn));
2936    }
2937
2938    /// fails if `dog_stale` breaks an older peer, on the same terms as
2939    /// `handshook` before it -- the same additive-optional rule, the same
2940    /// unchanged `PROTOCOL_VERSION`.
2941    ///
2942    /// The fixture carries `handshook: false`, which is the case that
2943    /// matters. A shepherd old enough to report a dog silent but too old to
2944    /// say whether it gave up on that dog must keep rendering exactly the
2945    /// word it rendered before -- `None` here is "this shepherd has no
2946    /// verdict to report", never "it has not given up".
2947    #[test]
2948    fn a_process_info_without_a_dog_stale_key_still_deserializes() {
2949        let fixture = r#"{"id":1,"name":"metrics","status":"online","pid":42,"restarts":0,"uptime_ms":10,"fold":null,"out_file":null,"err_file":null,"cpu_percent":null,"memory_bytes":null,"dog":{"kind":"built_in"},"lambs":null,"last_exit":null,"smit":null,"instance":0,"handshook":false}"#;
2950        let info: ProcessInfo = serde_json::from_str(fixture).unwrap();
2951        assert_eq!(info.dog_stale, None);
2952        assert_eq!(info.handshook, Some(false));
2953    }
2954
2955    /// fails if the daemon accepts a smit it should refuse. [`Smit`] must
2956    /// validate on the way IN, not only in `FromStr`: `docs/dogs.md` tells
2957    /// dog authors to speak this wire directly, so a dog written in another
2958    /// language never runs our parser.
2959    #[test]
2960    fn a_smit_is_validated_when_it_is_deserialized_not_only_when_parsed() {
2961        for bad in [
2962            r#""\u001b[2Jgone""#.to_string(),                    // an escape
2963            r#""a\nb""#.to_string(),                             // a newline
2964            r#""""#.to_string(),                                 // empty
2965            r#""   ""#.to_string(),                              // whitespace
2966            format!(r#""{}""#, "x".repeat(Smit::MAX_CHARS + 1)), // too long
2967        ] {
2968            assert!(
2969                serde_json::from_str::<Smit>(&bad).is_err(),
2970                "a daemon must refuse this on the wire: {bad}"
2971            );
2972        }
2973        assert!(serde_json::from_str::<Smit>(r#""\u25b2 main@a1b2c3""#).is_ok());
2974    }
2975
2976    /// fails if a smit stops travelling as a bare JSON string. It is a
2977    /// newtype with a hand-written `Deserialize`, and the pair only agrees
2978    /// with itself if the serialize side stays transparent — a `Smit` that
2979    /// serialized as `{"0":"..."}` would round-trip through nothing.
2980    #[test]
2981    fn a_smit_travels_as_a_bare_string() {
2982        let smit: Smit = "\u{25b2} main@a1b2c3".parse().expect("valid");
2983        let json = serde_json::to_string(&smit).unwrap();
2984        assert_eq!(json, "\"\u{25b2} main@a1b2c3\"");
2985        assert_eq!(serde_json::from_str::<Smit>(&json).unwrap(), smit);
2986    }
2987
2988    /// fails if the cap starts counting bytes or display columns. Forty-eight
2989    /// CJK characters are 144 bytes and roughly 96 columns, and all three
2990    /// numbers disagree — a byte cap would refuse this legitimate smit at a
2991    /// third of its apparent length.
2992    #[test]
2993    fn a_smit_is_capped_in_characters_not_bytes() {
2994        let cjk = "\u{7f8a}".repeat(Smit::MAX_CHARS);
2995        assert_eq!(cjk.len(), Smit::MAX_CHARS * 3);
2996        assert!(cjk.parse::<Smit>().is_ok(), "{cjk}");
2997        assert_eq!(
2998            "x".repeat(Smit::MAX_CHARS + 1).parse::<Smit>(),
2999            Err(SmitError::TooLong {
3000                chars: Smit::MAX_CHARS + 1
3001            })
3002        );
3003    }
3004
3005    /// fails if a smit is repaired rather than refused. Trimming or stripping
3006    /// would hand an operator a mark its publisher never sent, and would put
3007    /// shep in the business of editing a string it has agreed not to
3008    /// understand.
3009    #[test]
3010    fn a_smit_is_stored_exactly_as_it_arrived() {
3011        let padded: Smit = "  main@a1b2c3  ".parse().expect("valid");
3012        assert_eq!(padded.as_str(), "  main@a1b2c3  ");
3013        assert_eq!(padded.to_string(), "  main@a1b2c3  ");
3014    }
3015
3016    #[test]
3017    fn v1_fixture_still_deserializes() {
3018        // Committed byte fixture from protocol v1 — if this breaks, bump
3019        // PROTOCOL_VERSION and record it in the CHANGELOG (IR-35).
3020        let fixture = r#"{"id":7,"deadline_ms":null,"body":{"kind":"stop","selector":{"kind":"name","value":"web"}}}"#;
3021        let env: Envelope = serde_json::from_str(fixture).unwrap();
3022        assert_eq!(env.id, 7);
3023        assert!(matches!(
3024            env.body,
3025            Request::Stop { selector: SelectorSpec::Name(ref n) } if n == "web"
3026        ));
3027    }
3028
3029    #[test]
3030    fn hello_handshake_shape() {
3031        let hello = Hello {
3032            client_version: "0.1.0".to_string(),
3033            protocol: PROTOCOL_VERSION,
3034            dog_name: None,
3035        };
3036        let json = serde_json::to_string(&hello).unwrap();
3037        assert_eq!(json, r#"{"client_version":"0.1.0","protocol":2}"#);
3038    }
3039
3040    /// fails if a non-dog client's `Hello` grows a key. The CLI is the
3041    /// overwhelming majority of handshakes and sends `dog_name: None`, so
3042    /// `skip_serializing_if` is what keeps this addition free on the wire
3043    /// for every client that is not a dog — and what makes the bytes above
3044    /// byte-identical to the ones protocol 2 shipped with.
3045    #[test]
3046    fn a_dogs_hello_names_the_dog_and_nothing_elses_does() {
3047        let dog = Hello {
3048            client_version: "0.1.0".to_string(),
3049            protocol: PROTOCOL_VERSION,
3050            dog_name: Some("metrics".to_string()),
3051        };
3052        let json = serde_json::to_string(&dog).unwrap();
3053        assert_eq!(
3054            json,
3055            r#"{"client_version":"0.1.0","protocol":2,"dog_name":"metrics"}"#
3056        );
3057        assert_eq!(serde_json::from_str::<Hello>(&json).unwrap(), dog);
3058    }
3059
3060    /// fails if `Hello` gains `#[serde(deny_unknown_fields)]`, or if
3061    /// `dog_name` stops being optional — the two ways this addition could
3062    /// become a wire break after the fact.
3063    ///
3064    /// `Hello` is the version-negotiation frame, which makes it the one
3065    /// place where rejecting an unknown field would be unrecoverable: the
3066    /// daemon would refuse a newer client BEFORE reading `protocol`, so
3067    /// neither peer could report the skew that caused it. The fixture below
3068    /// is the committed bytes a client built before this field sends
3069    /// (IR-35), and the second half is the same rule in the other
3070    /// direction — an older daemon parsing a newer client's frame.
3071    #[test]
3072    fn a_hello_without_a_dog_name_still_parses() {
3073        let fixture = r#"{"client_version":"0.1.14","protocol":2}"#;
3074        let hello: Hello = serde_json::from_str(fixture).unwrap();
3075        assert_eq!(hello.protocol, 2);
3076        assert_eq!(hello.dog_name, None);
3077
3078        // The other direction: whatever an older daemon does not know, it
3079        // must ignore rather than refuse. `unknown_to_an_older_daemon`
3080        // stands in for `dog_name` as that daemon would see it.
3081        let newer = r#"{"client_version":"9.9.9","protocol":2,"dog_name":"metrics","unknown_to_an_older_daemon":true}"#;
3082        let hello: Hello = serde_json::from_str(newer).unwrap();
3083        assert_eq!(hello.protocol, 2);
3084        assert_eq!(hello.dog_name.as_deref(), Some("metrics"));
3085    }
3086
3087    #[test]
3088    fn hello_reply_carries_typed_skew_error() {
3089        let refusal: HelloReply = Err(RpcError {
3090            code: RpcErrorCode::ProtocolMismatch,
3091            message: "daemon speaks protocol 1, client sent 2".to_string(),
3092            daemon_version: None,
3093        });
3094        let json = serde_json::to_string(&refusal).unwrap();
3095        assert_eq!(
3096            json,
3097            r#"{"Err":{"code":"protocol_mismatch","message":"daemon speaks protocol 1, client sent 2"}}"#
3098        );
3099        let back: HelloReply = serde_json::from_str(&json).unwrap();
3100        assert_eq!(back, refusal);
3101    }
3102
3103    #[test]
3104    fn v1_reply_fixture_still_deserializes() {
3105        // Committed byte fixture, protocol v1 (IR-35).
3106        let ok = r#"{"id":1,"result":{"Ok":{"kind":"pong"}}}"#;
3107        let reply: Reply = serde_json::from_str(ok).unwrap();
3108        assert!(matches!(reply.result, Ok(Response::Pong)));
3109        let err = r#"{"id":2,"result":{"Err":{"code":"not_found","message":"no sheep"}}}"#;
3110        let reply: Reply = serde_json::from_str(err).unwrap();
3111        assert_eq!(reply.result.unwrap_err().code, RpcErrorCode::NotFound);
3112    }
3113
3114    #[test]
3115    fn v1_hello_ack_fixture_still_deserializes() {
3116        let fixture = r#"{"Ok":{"daemon_version":"0.1.0","protocol":1,"pid":4242}}"#;
3117        let ack: HelloReply = serde_json::from_str(fixture).unwrap();
3118        assert_eq!(ack.unwrap().pid, 4242);
3119    }
3120
3121    /// fails if the two fields stop being optional. A daemon built before
3122    /// them sends a reply with no such keys, and both peers still announce
3123    /// protocol 1 — a required field would make a current client unable to
3124    /// list against that daemon at all.
3125    #[test]
3126    fn v1_process_info_without_stats_still_deserializes() {
3127        let fixture = r#"{"id":3,"name":"web","status":"online","pid":4242,"restarts":1,"uptime_ms":60000,"fold":"backend","out_file":"/l/o.log","err_file":"/l/e.log"}"#;
3128        let info: ProcessInfo = serde_json::from_str(fixture).unwrap();
3129        assert_eq!(info.cpu_percent, None);
3130        assert_eq!(info.memory_bytes, None);
3131    }
3132
3133    #[test]
3134    fn v1_process_info_without_log_paths_still_deserializes() {
3135        // Committed byte fixture from before `out_file`/`err_file` existed
3136        // (IR-35). The handshake only compares PROTOCOL_VERSION, which this
3137        // addition deliberately did not bump, so a daemon built at this
3138        // vintage still connects to a current client and sends exactly these
3139        // bytes. Absent keys must land as `None`, not as a decode error.
3140        let fixture = r#"{"id":3,"name":"web","status":"online","pid":4242,"restarts":1,"uptime_ms":60000,"fold":"backend"}"#;
3141        let info: ProcessInfo = serde_json::from_str(fixture).unwrap();
3142        assert_eq!(info.id, 3);
3143        assert_eq!(info.out_file, None);
3144        assert_eq!(info.err_file, None);
3145    }
3146
3147    #[test]
3148    fn an_old_client_still_decodes_a_new_process_info() {
3149        // The other skew direction: a client built before the fields reads a
3150        // current daemon's reply. `ProcessInfo` carries no
3151        // `deny_unknown_fields` (unlike the config types in
3152        // `crate::config`), so the two extra keys are ignored rather than
3153        // refused — which is what makes this addition version-preserving.
3154        #[derive(Deserialize)]
3155        struct V1ProcessInfo {
3156            id: u32,
3157            fold: Option<String>,
3158        }
3159
3160        let current = serde_json::to_string(&sample_info()).unwrap();
3161        let old: V1ProcessInfo = serde_json::from_str(&current).unwrap();
3162        assert_eq!(old.id, 3);
3163        assert_eq!(old.fold.as_deref(), Some("backend"));
3164    }
3165
3166    #[test]
3167    fn an_rpc_error_without_a_daemon_version_serializes_exactly_as_before() {
3168        // `skip_serializing_if` is what makes this addition free: a daemon
3169        // with nothing to say puts the same bytes on the wire it always did,
3170        // not a `"daemon_version":null` key an older client would have to
3171        // ignore. Pinned as an exact string, because "additive" is a claim
3172        // about bytes.
3173        let plain = RpcError {
3174            code: RpcErrorCode::NotFound,
3175            message: "no sheep".to_string(),
3176            daemon_version: None,
3177        };
3178        assert_eq!(
3179            serde_json::to_string(&plain).unwrap(),
3180            r#"{"code":"not_found","message":"no sheep"}"#
3181        );
3182    }
3183
3184    #[test]
3185    fn a_v1_rpc_error_fixture_deserializes_with_no_daemon_version() {
3186        // Committed byte fixture from before this field existed (IR-35): the
3187        // skew direction that matters, a CURRENT client reading an OLD
3188        // daemon's refusal. It must read as `None` rather than failing to
3189        // decode, or the field breaks the upgrade it exists to smooth.
3190        let fixture =
3191            r#"{"code":"protocol_mismatch","message":"daemon speaks protocol 1, client sent 2"}"#;
3192        let err: RpcError = serde_json::from_str(fixture).unwrap();
3193        assert_eq!(err.code, RpcErrorCode::ProtocolMismatch);
3194        assert_eq!(err.daemon_version, None);
3195    }
3196
3197    #[test]
3198    fn an_old_client_ignores_an_rpc_error_field_it_has_never_seen() {
3199        // Step 1 of the handover work: proof that `RpcError` may grow an
3200        // optional field WITHOUT moving `PROTOCOL_VERSION`. Like
3201        // `ProcessInfo` above, `RpcError` carries no `deny_unknown_fields`,
3202        // so a client built before a field decodes a daemon that sends it
3203        // rather than failing the handshake on it.
3204        #[derive(Deserialize)]
3205        struct OldRpcError {
3206            code: RpcErrorCode,
3207            message: String,
3208        }
3209
3210        let current = serde_json::to_string(&RpcError {
3211            code: RpcErrorCode::ProtocolMismatch,
3212            message: "daemon speaks protocol 1, client sent 2".to_string(),
3213            daemon_version: Some("0.1.16".to_string()),
3214        })
3215        .unwrap();
3216        let old: OldRpcError = serde_json::from_str(&current).expect("must tolerate");
3217        assert_eq!(old.code, RpcErrorCode::ProtocolMismatch);
3218        assert_eq!(old.message, "daemon speaks protocol 1, client sent 2");
3219    }
3220
3221    #[test]
3222    fn deadline_exceeded_code_serializes_snake_case() {
3223        // Additive variant (evolution rule): the existing codes keep their
3224        // strings, so v1 byte fixtures above still deserialize unchanged.
3225        assert_eq!(
3226            serde_json::to_string(&RpcErrorCode::DeadlineExceeded).unwrap(),
3227            "\"deadline_exceeded\""
3228        );
3229        assert_eq!(
3230            serde_json::from_str::<RpcErrorCode>("\"deadline_exceeded\"").unwrap(),
3231            RpcErrorCode::DeadlineExceeded
3232        );
3233    }
3234
3235    #[test]
3236    fn action_outcome_kinds_serialize_snake_case_and_round_trip() {
3237        // The shared snapshots above exercise exactly one `ActionOutcome`
3238        // variant (`Replied`, the only struct-shaped one, in
3239        // `reply_wire_snapshots`) — nothing else there would catch a rename
3240        // of `no_channel`, `skipped`, or `timed_out`. Pinned here instead,
3241        // the same way `deadline_exceeded_code_serializes_snake_case` pins a
3242        // lone `RpcErrorCode` variant above.
3243        let cases = [
3244            (
3245                ActionOutcome::Replied {
3246                    body: "pong".to_string(),
3247                },
3248                r#"{"kind":"replied","body":"pong"}"#,
3249            ),
3250            (ActionOutcome::NoChannel, r#"{"kind":"no_channel"}"#),
3251            (ActionOutcome::Skipped, r#"{"kind":"skipped"}"#),
3252            (ActionOutcome::TimedOut, r#"{"kind":"timed_out"}"#),
3253        ];
3254        for (outcome, wire) in cases {
3255            assert_eq!(
3256                serde_json::to_string(&outcome).unwrap(),
3257                wire,
3258                "{outcome:?}"
3259            );
3260            assert_eq!(
3261                serde_json::from_str::<ActionOutcome>(wire).unwrap(),
3262                outcome
3263            );
3264        }
3265    }
3266
3267    /// fails if `SaveRoll` or `RollSaved` is given a `rename`, or if
3268    /// `Response`'s `content = "data"` is dropped — either changes these two
3269    /// strings while every type-level test in this module keeps passing.
3270    #[test]
3271    fn save_roll_serializes_snake_case_with_its_payload_under_data() {
3272        assert_eq!(
3273            serde_json::to_string(&Request::SaveRoll).unwrap(),
3274            r#"{"kind":"save_roll"}"#
3275        );
3276        let reply = Response::RollSaved {
3277            path: "/tmp/flock.json".to_string(),
3278            apps: 3,
3279        };
3280        let wire = r#"{"kind":"roll_saved","data":{"path":"/tmp/flock.json","apps":3}}"#;
3281        assert_eq!(serde_json::to_string(&reply).unwrap(), wire);
3282        assert_eq!(serde_json::from_str::<Response>(wire).unwrap(), reply);
3283    }
3284
3285    /// fails if `Muster` or `Mustered` is given a `rename`, or if `Mustered`
3286    /// is declared fieldless — any of the three changes one of these two
3287    /// strings while every type-level test in this module keeps passing.
3288    ///
3289    /// The listing is empty on purpose. `Mustered` carries the same
3290    /// `Vec<ProcessInfo>` `Flock` does, and `reply_wire_snapshots` already
3291    /// pins that row field by field; what is unpinned until here is this
3292    /// variant's own tag and whether its payload lands under `data` at all.
3293    #[test]
3294    fn muster_serializes_snake_case_with_its_listing_under_data() {
3295        assert_eq!(
3296            serde_json::to_string(&Request::Muster).unwrap(),
3297            r#"{"kind":"muster"}"#
3298        );
3299        let reply = Response::Mustered(Vec::new());
3300        let wire = r#"{"kind":"mustered","data":[]}"#;
3301        assert_eq!(serde_json::to_string(&reply).unwrap(), wire);
3302        assert_eq!(serde_json::from_str::<Response>(wire).unwrap(), reply);
3303    }
3304
3305    /// fails if any of the three verbs or either reply is given a `rename`,
3306    /// or if `Response`'s `content = "data"` is dropped. `disable_dog`'s
3307    /// answer is `Deleted`, which no other test in this module pairs with
3308    /// this verb — a handler wired to answer `Deleted` for `EnableDog` would
3309    /// still round-trip, and this is where the pairing is written down.
3310    #[test]
3311    fn the_dog_verbs_serialize_snake_case_with_their_payloads_under_data() {
3312        assert_eq!(
3313            serde_json::to_string(&Request::DogConfig {
3314                name: "bark".to_string()
3315            })
3316            .unwrap(),
3317            r#"{"kind":"dog_config","name":"bark"}"#
3318        );
3319        assert_eq!(
3320            serde_json::to_string(&Request::DisableDog {
3321                name: "bark".to_string()
3322            })
3323            .unwrap(),
3324            r#"{"kind":"disable_dog","name":"bark"}"#
3325        );
3326        let section = Response::DogSection {
3327            toml: "port = 9615\n".to_string().into(),
3328        };
3329        let wire = r#"{"kind":"dog_section","data":{"toml":"port = 9615\n"}}"#;
3330        assert_eq!(serde_json::to_string(&section).unwrap(), wire);
3331        assert_eq!(serde_json::from_str::<Response>(wire).unwrap(), section);
3332    }
3333
3334    #[test]
3335    fn dog_section_toml_debug_does_not_leak() {
3336        // IR-41: a dog's `[dog.<name>]` section routinely holds webhook
3337        // credentials (a Discord/Slack URL with a bearer token embedded).
3338        // `Response` derives `Debug`, so this is the one thing standing
3339        // between that token and any future `tracing::debug!("{:?}", reply)`.
3340        // Exact string pinned so a lazy `#[derive(Debug)]` refactor on
3341        // `DogSectionToml` fails this test instead of silently reopening
3342        // the leak.
3343        let toml: DogSectionToml =
3344            "webhook_url = \"https://discord.com/api/webhooks/1/super-secret-token\"\n"
3345                .to_string()
3346                .into();
3347        assert_eq!(format!("{toml:?}"), "DogSectionToml(<70 bytes>)");
3348
3349        let response = Response::DogSection { toml };
3350        assert_eq!(
3351            format!("{response:?}"),
3352            "DogSection { toml: DogSectionToml(<70 bytes>) }"
3353        );
3354    }
3355
3356    /// The fixture is built so the two candidate orders CANNOT agree: read
3357    /// by id it is `web/1, api/2, web/0`, read by name it is
3358    /// `api, web, web`. A listing that happened to be alphabetical already,
3359    /// or whose ids happened to ascend with its names, would pass under
3360    /// either rule and prove nothing.
3361    ///
3362    /// The two `web` rows are the tiebreak half, and they are the reason a
3363    /// multi-instance fixture is required: their ids are seeded out of order
3364    /// (1 before 0), so a sort keyed on name alone would leave them as it
3365    /// found them and fail the last assertion while passing the first.
3366    #[test]
3367    fn a_listing_sorts_by_name_then_by_id() {
3368        let mut listing = vec![
3369            ProcessInfo::builder(1, "web", ProcStatus::Online).build(),
3370            ProcessInfo::builder(2, "api", ProcStatus::Online).build(),
3371            ProcessInfo::builder(0, "web", ProcStatus::Online).build(),
3372        ];
3373        sort_flock(&mut listing);
3374
3375        let seen: Vec<(&str, u32)> = listing
3376            .iter()
3377            .map(|info| (info.name.as_str(), info.id))
3378            .collect();
3379        assert_eq!(
3380            seen,
3381            vec![("api", 2), ("web", 0), ("web", 1)],
3382            "name first, then id inside a name"
3383        );
3384    }
3385
3386    #[test]
3387    fn an_instance_slot_survives_a_round_trip_and_defaults_to_absent() {
3388        let with = ProcessInfo::builder(1, "web", ProcStatus::Online)
3389            .instance(Some(2))
3390            .build();
3391        assert_eq!(with.instance, Some(2));
3392
3393        let without = ProcessInfo::builder(1, "web", ProcStatus::Online).build();
3394        assert_eq!(
3395            without.instance, None,
3396            "a row nobody set a slot on says so, rather than claiming slot 0"
3397        );
3398    }
3399
3400    #[test]
3401    fn a_reply_from_a_daemon_without_the_field_deserializes_as_absent() {
3402        // The skew case the Option exists for: an older shepherd's JSON has no
3403        // `instance` key at all.
3404        let json = r#"{"id":1,"name":"web","status":"online","pid":null,
3405            "restarts":0,"uptime_ms":0,"fold":null,"out_file":null,
3406            "err_file":null,"cpu_percent":null,"memory_bytes":null,"dog":null,
3407            "lambs":null,"last_exit":null,"smit":null}"#;
3408        let info: ProcessInfo = serde_json::from_str(json).expect("older reply still parses");
3409        assert_eq!(info.instance, None);
3410    }
3411
3412    #[test]
3413    fn sort_flock_orders_by_slot_before_id() {
3414        // A reload gave slot 0 a fresh, higher id. Slot order must still win.
3415        let mut listing = vec![
3416            ProcessInfo::builder(9, "web", ProcStatus::Online)
3417                .instance(Some(0))
3418                .build(),
3419            ProcessInfo::builder(2, "web", ProcStatus::Online)
3420                .instance(Some(1))
3421                .build(),
3422        ];
3423        sort_flock(&mut listing);
3424        assert_eq!(
3425            listing.iter().map(|i| i.id).collect::<Vec<_>>(),
3426            vec![9, 2],
3427            "slot 0 leads even though its id is higher"
3428        );
3429    }
3430
3431    #[test]
3432    fn sort_flock_falls_back_to_id_when_no_row_carries_a_slot() {
3433        let mut listing = vec![
3434            ProcessInfo::builder(5, "web", ProcStatus::Online).build(),
3435            ProcessInfo::builder(3, "web", ProcStatus::Online).build(),
3436        ];
3437        sort_flock(&mut listing);
3438        assert_eq!(
3439            listing.iter().map(|i| i.id).collect::<Vec<_>>(),
3440            vec![3, 5],
3441            "an older daemon's listing sorts exactly as it does today"
3442        );
3443    }
3444}