Skip to main content

caixa_core/
supervisor.rs

1//! OTP-shaped supervisor trees, encoded as a typed `:kind Supervisor`
2//! caixa with a strategy + restart-policy children list.
3//!
4//! See `theory/INSPIRATIONS.md` §II.2 + §III.2 for the prior-art frame
5//! (Erlang OTP supervisor + Lunatic supervisor strategies as Rust types).
6//!
7//! ```lisp
8//! (defcaixa
9//!   :nome           "my-app-root"
10//!   :versao         "0.1.0"
11//!   :kind           Supervisor
12//!   :estrategia     OneForOne
13//!   :max-restarts   5
14//!   :restart-window "60s"
15//!   :children       ((:caixa "worker"       :versao "^0.1" :restart Permanent)
16//!                    (:caixa "cache-server" :versao "^0.1" :restart Transient)
17//!                    (:caixa "scratch-job"  :versao "^0.1" :restart Temporary)))
18//! ```
19//!
20//! wasm-operator (M3) walks the tree, materializes one ComputeUnit per
21//! child, and applies the strategy on child failure. The Rust types
22//! here are the typed contract; the runtime owns lifecycle.
23
24use std::time::Duration;
25
26use serde::{Deserialize, Serialize};
27use thiserror::Error;
28
29/// One of the four canonical Erlang/OTP restart strategies.
30///
31/// The strategy decides what happens to *sibling* children when one
32/// child dies. Per-child behaviour is governed by [`RestartPolicy`].
33#[derive(
34    Serialize,
35    Deserialize,
36    Debug,
37    Clone,
38    Copy,
39    PartialEq,
40    Eq,
41    Hash,
42    gen_platform::TypedDispatcher,
43    gen_platform::Discriminant,
44    gen_platform::IsVariant,
45    gen_platform::FromStrKind,
46)]
47pub enum RestartStrategy {
48    /// On child failure, restart only that child. Default; matches
49    /// most "tree of independent workers" use cases.
50    OneForOne,
51    /// On child failure, restart every child. Used when children
52    /// share state and must be in sync.
53    OneForAll,
54    /// On child failure, restart the failed child and every child
55    /// started *after* it (preserving startup order). Used when later
56    /// children depend on earlier ones.
57    RestForOne,
58    /// Dynamic children of the same shape, started on demand. The
59    /// supervisor doesn't know its children at boot; they're added as
60    /// they're needed (e.g. one child per session).
61    SimpleOneForOne,
62}
63
64impl Default for RestartStrategy {
65    fn default() -> Self {
66        // Route the [`Default for RestartStrategy`] impl through the
67        // substrate-canonical [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed
68        // `pub const` rather than a raw `Self::OneForOne` arm — one
69        // source of truth for the Erlang/OTP `one_for_one` half of Learn
70        // You Some Erlang's `{one_for_one, intensity, 5, 60}` worker-
71        // supervisor canonical default, paired with the sibling
72        // `SUPERVISOR_MAX_RESTARTS_DEFAULT` `MaxIntensity` half (b698ec0)
73        // and `SUPERVISOR_RESTART_WINDOW_DEFAULT` `Period` half (f7dcd0e).
74        // Pinned by `restart_strategy_default_routes_through_lifted_default`.
75        SUPERVISOR_ESTRATEGIA_DEFAULT
76    }
77}
78
79impl RestartStrategy {
80    /// Exhaustive iteration surface for every consumer that walks the
81    /// closed four-arm [`RestartStrategy`] discriminator set (the future
82    /// M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
83    /// admission-webhook rejection body naming the accepted-`:estrategia`
84    /// list, a future `feira supervisor --estrategia …` CLI arg-parse's
85    /// "did you mean" hint via a [`Self::from_wire`]-scan over the slice,
86    /// the future `feira app graph` per-supervisor `:estrategia` column,
87    /// any future round-trip fuzz harness that sweeps every arm). A
88    /// future arm addition (an OTP-`rest_for_all` arm the theory
89    /// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
90    /// might reach for once the four canonical OTP strategies stop
91    /// covering the substrate's discovered load-shape) extends this
92    /// slice as one edit and every consumer picks up the new entry by
93    /// construction; the compiler-checked exhaustiveness on the sibling
94    /// method `match` arms ([`Self::as_str`] / [`Self::from_wire`]) is
95    /// the build-time guarantee that no arm forgets to grow.
96    ///
97    /// Peer of the sibling closed-set typed enums'
98    /// [`crate::CaixaKind::ALL`] (6b1f4fb) /
99    /// [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
100    /// [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
101    /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
102    /// surfaces — the fifth (and the first M2 OTP-shape) closed-set
103    /// typed enum on the caixa surface to converge onto the same
104    /// one-canonical-arm-list-per-enum discipline.
105    pub const ALL: &'static [Self] = &[
106        Self::OneForOne,
107        Self::OneForAll,
108        Self::RestForOne,
109        Self::SimpleOneForOne,
110    ];
111
112    /// Substrate-canonical exhaustive accept-set on the
113    /// [`RestartStrategy`] `PascalCase` wire byte-string axis — the
114    /// closed four-arm roster of every byte-string [`Self::as_str`]
115    /// returns, routed byte-for-byte through the paired
116    /// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
117    /// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
118    /// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
119    /// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
120    /// lifted `pub const` roster the [`Self::as_str`] emitter (and the
121    /// [`std::fmt::Display`] / [`AsRef<str>`] /
122    /// `From<{Self,&Self}> for {&'static str, String, Cow<'static, str>,
123    /// Box<str>, Arc<str>}` trait triple + quintuple routed through it)
124    /// walks — and byte-for-byte the same four strings the un-`rename`d
125    /// `Serialize` derive emits under the paired
126    /// [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`] tag key on every
127    /// JSON / YAML CR round-trip.
128    ///
129    /// Peer of the sibling [`crate::CaixaKind::WIRE_NAMES`] (bd708bd)
130    /// roster on the top-level typed-kind discriminator's `PascalCase`
131    /// wire byte-string axis, and of the sibling
132    /// [`crate::upgrade::UpgradeInstruction::WIRE_FORMS`] (cc42c0e) /
133    /// [`crate::upgrade::UpgradeInstruction::LISP_FORMS`] (1898d77)
134    /// rosters on the OTP-appup discriminator's two-axis roster split —
135    /// the same closed-set exhaustive-accept-set roster discipline
136    /// extended here onto the first M2 OTP-shape sibling-restart
137    /// closed-set typed enum. The sibling
138    /// [`crate::aplicacao::PlacementStrategy`] M3 mesh-shape distribution
139    /// strategy enum is the next natural peer on the same axis, still
140    /// carrying only [`crate::aplicacao::PlacementStrategy::ALL`].
141    ///
142    /// Downstream consumers of the closed accepted-wire-form set — a
143    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR admission-webhook
144    /// rejection body enumerating the accepted JSON `:estrategia` values
145    /// verbatim (as distinct from the kebab-case dispatcher-catalog
146    /// enumeration [`Self::discriminant`] serves, whose per-arm form
147    /// `"one-for-one"` / `"one-for-all"` / `"rest-for-one"` /
148    /// `"simple-one-for-one"` structurally disagrees with the wire byte-
149    /// string these `PascalCase` entries carry), a future `feira
150    /// supervisor --estrategia …` CLI-side "did you mean" hint whose
151    /// candidate-list must byte-match the wire form the operator's
152    /// per-strategy dispatch keys off (rather than the kebab
153    /// dispatcher-catalog identity), a future `feira app graph`
154    /// per-supervisor `:estrategia`-histogram column that renders
155    /// zero-count arms, a future wasm-operator per-reconcile-step
156    /// diagnostic log line enumerating accepted wire forms on an
157    /// unknown-strategy rejection, a future
158    /// `tracing::field::valuable::Value::List` structured-log accepted-
159    /// wire-form emit — now reach for one lifted substrate-primitive
160    /// roster rather than open-coding a four-string array-literal
161    /// (`["OneForOne", "OneForAll", "RestForOne", "SimpleOneForOne"]`)
162    /// whose arm-set has no compile-time link back to the typed
163    /// [`RestartStrategy`] enum. A future arm addition (an OTP-`rest_for_all`
164    /// arm the theory
165    /// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
166    /// might reach for once the four canonical OTP strategies stop
167    /// covering the substrate's discovered load-shape) extends this
168    /// roster as a single edit — paired with the [`Self::as_str`]
169    /// match's compiler-checked exhaustiveness on the new arm — and
170    /// every consumer picks up the new wire form by construction rather
171    /// than a coordinated array-literal rewrite across every downstream
172    /// site.
173    ///
174    /// Length is pinned load-bearing at `RestartStrategy::ALL.len()`
175    /// (four) by
176    /// [`tests::restart_strategy_wire_names_covers_every_arm`], every
177    /// variant's [`Self::as_str`] projection is pinned to a member of
178    /// the roster so a silent skew between the emitter's arm-set and
179    /// this const's arm-set trips at caixa-core test time rather than
180    /// at a downstream consumer's accepted-set enumeration miss, and
181    /// every entry is further pinned to open with an ASCII uppercase
182    /// byte so a silent collapse of the wire-form axis with the peer
183    /// kebab-case dispatcher-catalog axis (an entry byte-identical to a
184    /// sibling [`Self::discriminant`] kebab byte-string that would let
185    /// a wire-axis consumer accept the dispatcher-catalog vocabulary)
186    /// trips here rather than at a downstream K8s-CR round-trip miss.
187    pub const WIRE_NAMES: &'static [&'static str] = &[
188        crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
189        crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
190        crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
191        crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
192    ];
193
194    /// Canonical PascalCase discriminator scalar this variant serializes
195    /// as under [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`]. The four arms
196    /// return the paired [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`]
197    /// / [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
198    /// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
199    /// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] lifted
200    /// constants so every substrate consumer that dispatches on the
201    /// per-supervisor sibling-restart strategy (the future
202    /// wasm-operator's per-supervisor sibling-restart branch, the future
203    /// M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
204    /// admission-time enum-arm bind, the `caixa-operator`'s hierarchical
205    /// reconciliation scheduler's per-strategy fan-out) reads the same
206    /// byte-string the `Serialize` derive emits — the pin test in
207    /// [`tests::restart_strategy_variants_serialize_to_lifted_scalar_values`]
208    /// asserts the two paths agree, peer of the M3
209    /// `PlacementStrategy::as_str` (cc8f749) on the sibling per-Aplicacao
210    /// distribution-strategy axis.
211    #[must_use]
212    pub const fn as_str(self) -> &'static str {
213        match self {
214            Self::OneForOne => crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
215            Self::OneForAll => crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
216            Self::RestForOne => crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
217            Self::SimpleOneForOne => crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
218        }
219    }
220
221    /// Substrate-canonical reverse projection on the `:supervisor
222    /// :estrategia` closed-set axis — parses the `PascalCase`
223    /// discriminator scalar back to the typed variant, or `None` when
224    /// `s` is outside
225    /// the closed-set arm-string set [`Self::as_str`] emits. Dispatches
226    /// on the same lifted
227    /// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
228    /// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
229    /// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
230    /// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
231    /// constants the [`Self::as_str`] emitter walks, so the parse and
232    /// emit halves of the round-trip migrate through one caixa-core
233    /// edit on any future arm addition.
234    ///
235    /// Prior to this lift the substrate carried only the forward
236    /// `Self → &str` projection on the OTP sibling-restart axis (the
237    /// [`Self::as_str`] emitter, the [`std::fmt::Display`] impl routed
238    /// through it, the `Serialize` derive that emits the same
239    /// byte-string under [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`])
240    /// plus the kebab-case dispatcher-catalog identity via
241    /// [`Self::discriminant`] — every non-serde consumer that wanted to
242    /// parse a wire-form `PascalCase` strategy scalar had to re-inline
243    /// a four-arm `match s { "OneForOne" => …, "OneForAll" => …,
244    /// "RestForOne" => …, "SimpleOneForOne" => …, _ => … }` cascade
245    /// that expressed no compile-time link back to the typed variant's
246    /// canonical lifted constant. A future variant rename or per-arm
247    /// serde-attribute drift would silently split the wire byte-string
248    /// one non-serde consumer parsed from the one the emitter wrote,
249    /// with the failure surfacing at parse time far from the rebrand
250    /// commit.
251    ///
252    /// Distinct axis from the [`std::str::FromStr`] impl the
253    /// [`gen_platform::FromStrKind`] derive already installs on this
254    /// enum by design, not by drift: `FromStr` parses the *kebab-case*
255    /// dispatcher-catalog identity (`"one-for-one"` / `"one-for-all"` /
256    /// `"rest-for-one"` / `"simple-one-for-one"` — the inverse of
257    /// [`Self::discriminant`]), while this method inverts the
258    /// `PascalCase` wire byte-string [`Self::as_str`] emits. The
259    /// two-axis split lets the dispatcher-catalog identity live in
260    /// kebab-case
261    /// (where every peer catalog identifier already lives) without
262    /// forcing a wire-format rename on the tatara-lisp author surface
263    /// (`:estrategia OneForOne`, `PascalCase`) — the same two-axis
264    /// distinction the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
265    /// / [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
266    /// carry on their peer closed-set typed-enum wire round-trips.
267    ///
268    /// Same closed-set-reverse-projection discipline the sibling
269    /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
270    /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342) /
271    /// [`crate::aplicacao::RateLimitUnit::from_suffix`] typed enums
272    /// carry on the peer wire-side `str → Self` axes — extended onto
273    /// the M2 OTP-shape sibling-restart-strategy closed-set axis, the
274    /// fifth substrate-side closed-set typed enum to converge on the
275    /// two-way `str ↔ Self` round-trip. Method-named `from_wire` (not
276    /// `from_str`) to match the peer [`crate::CaixaKind::from_wire`]
277    /// shape verbatim and side-step the [`std::str::FromStr`] impl the
278    /// derive already installs on the sibling kebab-case axis. Returns
279    /// `Option<Self>` (rather than `Result<Self, _>`) to match the peer
280    /// shapes: the caller picks the diagnostic form appropriate for
281    /// its use site.
282    #[must_use]
283    pub fn from_wire(s: &str) -> Option<Self> {
284        match s {
285            crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE => Some(Self::OneForOne),
286            crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL => Some(Self::OneForAll),
287            crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE => Some(Self::RestForOne),
288            crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE => Some(Self::SimpleOneForOne),
289            _ => None,
290        }
291    }
292}
293
294/// [`std::fmt::Display`] routed through [`RestartStrategy::as_str`], so the
295/// pretty-printed byte-string every consumer that formats the strategy as
296/// user-facing text lands on (the future wasm-operator's per-supervisor
297/// sibling-restart-strategy diagnostic line, the future `feira app graph`
298/// per-supervisor strategy line, the future M4
299/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission-webhook
300/// rejection body) reaches for the same lifted
301/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
302/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
303/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
304/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const the
305/// wire-format `Serialize` derive already emits under
306/// [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`] and the
307/// [`RestartStrategy::as_str`] helper already returns.
308///
309/// Pre-convergence the two paths structurally disagreed — the
310/// `#[derive(gen_platform::Discriminant)]` + `#[discriminant(also_display)]`
311/// route (now retired here) sent [`std::fmt::Display`] through the
312/// gen-platform discriminant catalog string, which arrives kebab-case as
313/// `"one-for-one"` / `"one-for-all"` / `"rest-for-one"` /
314/// `"simple-one-for-one"`, while the wire format ran as `PascalCase`
315/// `"OneForOne"` / `"OneForAll"` / `"RestForOne"` / `"SimpleOneForOne"`
316/// through the un-`rename`d serde derive. Every consumer that formatted
317/// the strategy for a diagnostic line, a graph, or a rejection body under
318/// `format!("{v}")` therefore landed under a different byte-string than
319/// the wire format the operator's per-strategy dispatch keyed off — a
320/// silent split whose apply-time symptom (a `format!("{v}")`-carrying
321/// diagnostic quoting `"one-for-one"` while the wire scalar the operator
322/// probed was `"OneForOne"`) surfaced as a confused correlate at
323/// operator-log time far from the two-declaration site.
324///
325/// Routing `Display` through [`RestartStrategy::as_str`] closes the third
326/// path: every `format!("{v}")` call reaches the same lifted
327/// [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const the wire format and
328/// the [`RestartStrategy::as_str`] helper route through — `Debug` (the
329/// compiler-derived variant name), `Display` (via `as_str`), and `Serialize`
330/// (via the un-`rename`d derive) all resolve to the same `PascalCase`
331/// byte-string per variant. A future variant rename or
332/// `#[serde(rename_all = "kebab-case")]` attribute reaches every path at
333/// exactly one place, structurally.
334///
335/// The dispatcher-catalog identity remains kebab-case — [`Self::discriminant`]
336/// (from `#[derive(gen_platform::Discriminant)]`) still returns
337/// `"one-for-one"` / etc., and the fleet-wide
338/// [`gen_platform::register_dispatcher!("caixa.restart-strategy", …)`]
339/// registration keys the catalog off the same kebab identity. The two
340/// naming worlds now live on separate typed methods (`Display` /
341/// `as_str` for the wire byte-string, `discriminant` for the catalog
342/// identity) rather than sharing one `Display` route that structurally
343/// disagrees with the wire format.
344///
345/// Pin tests
346/// [`tests::restart_strategy_display_routes_through_as_str_helper`]
347/// and
348/// [`tests::restart_strategy_display_matches_serialized_wire_byte_string`]
349/// assert the three paths agree byte-for-byte on every variant, so a
350/// future variant rename or per-arm serde attribute drift is a build
351/// error visible at caixa-core test time, not a silent per-consumer
352/// dispatch miss at apply / reconcile time.
353///
354/// Mirrors the M3 [`crate::aplicacao::PlacementStrategy`] `Display` impl
355/// (aplicacao.rs:2306) on the sibling per-Aplicacao distribution-strategy
356/// axis — same three-path-convergence discipline, extended to close the
357/// second of three OTP-shaped closed-enum discriminator axes on the
358/// caixa typed surface.
359impl std::fmt::Display for RestartStrategy {
360    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
361        f.write_str(self.as_str())
362    }
363}
364
365/// Substrate-canonical [`AsRef<str>`] projection on the M2
366/// per-supervisor sibling-restart [`RestartStrategy`] closed-set typed
367/// enum — routes through the same [`RestartStrategy::as_str`]
368/// `pub const fn` scalar accessor the paired [`std::fmt::Display`]
369/// impl and the un-`rename`d [`serde::Serialize`] derive already key
370/// off, so any future consumer that binds a [`RestartStrategy`]
371/// through the standard-library `impl AsRef<str>` bound (a future
372/// [`caixa-feira`] `feira supervisor --estrategia <arm>` verb that
373/// composes the emitted `PascalCase` wire scalar into a
374/// [`std::process::Command::arg`] shell-out of the future
375/// wasm-operator's admission gate, a per-supervisor structured-log
376/// recorder on the future `caixa-operator`'s hierarchical
377/// reconciliation surface that accepts `impl AsRef<str>` at the
378/// `tracing::field::Value` `Str`-arm, a [`std::collections::HashMap`]
379/// lookup keyed on the estrategia wire byte through
380/// `map.get::<str>(strategy.as_ref())` on a future per-strategy
381/// dispatch table) reaches the paired [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`]
382/// / [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
383/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
384/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
385/// lifted-const through one substrate-primitive dispatch rather
386/// than an open-coded `.as_str()` projection at every wire-up.
387///
388/// Peer of the sibling [`std::fmt::Display`] impl on the same
389/// primitive — both delegate to the shared
390/// [`RestartStrategy::as_str`] `pub const fn` accessor, so
391/// [`format!("{s}")`], `s.as_str()`, and
392/// `<RestartStrategy as AsRef<str>>::as_ref(&s)` resolve to the same
393/// byte-string per instance by construction. A future variant rename
394/// or `#[serde(rename_all = "kebab-case")]` attribute-drift on the
395/// enum reaches every one of the three paths (plus the wire-format
396/// `Serialize` derive that already routes through the same lifted
397/// const) through exactly one caixa-core edit.
398///
399/// Same "route the trait impl through the substrate-primitive
400/// accessor" discipline the sibling [`crate::CaixaVersion`]
401/// [`AsRef<str>`] impl (16d5c7e) carries on the paired top-level
402/// `:versao` typed newtype — extends it onto the second `AsRef<str>`
403/// axis on the caixa typed surface (the first M2 OTP-shape
404/// closed-set typed enum to converge onto the standard-library
405/// [`AsRef<str>`] projection). Rust-side newtype/typed-enum
406/// convention pairs [`AsRef<str>`] and [`fmt::Display`] on the same
407/// primitive so a caller who has one has both; before this lift,
408/// [`RestartStrategy`] carried [`fmt::Display`] but not the paired
409/// [`AsRef<str>`] impl the convention names.
410///
411/// Pinned load-bearing by
412/// [`tests::restart_strategy_as_ref_str_routes_through_as_str_accessor`]
413/// (byte-parity pin against [`RestartStrategy::as_str`] across the
414/// four-arm closed set) — any future silent detour that routes the
415/// impl through a divergent projection (a per-arm inline
416/// `match self { … }` re-inlining that opens a compile-time link to
417/// the un-lifted arm-literal, a swap onto the kebab-case
418/// [`gen_platform::Discriminant`] catalog identity that would collide
419/// the wire axis with the dispatcher-catalog axis) trips at
420/// caixa-core test time under `assert_eq!` rather than at a
421/// downstream `impl AsRef<str>`-bound consumer's silent split.
422impl AsRef<str> for RestartStrategy {
423    fn as_ref(&self) -> &str {
424        self.as_str()
425    }
426}
427
428/// Trait-idiomatic reverse projection on the M2-OTP-shape sibling-restart
429/// [`RestartStrategy`] closed-set typed enum — routes byte-for-byte through
430/// the paired substrate-primitive [`RestartStrategy::from_wire`]
431/// `Option<Self>` accessor so every future consumer that binds a
432/// `PascalCase` `:supervisor :estrategia` wire byte-string through the
433/// standard-library `.try_into()` / [`TryFrom`] axis (a future
434/// [`caixa-feira`] `feira supervisor --estrategia <OneForOne|OneForAll|
435/// RestForOne|SimpleOneForOne>` CLI arg-parse that composes into
436/// `let estrategia: RestartStrategy = s.try_into()?`, a future
437/// `mesh.pleme.io/v1alpha1/Supervisor` CR admission-webhook that folds a
438/// `spec.estrategia: String` field through
439/// `RestartStrategy::try_from(&s)?`, a generic
440/// `<T: TryFrom<&str>>`-bound loader over any of the substrate's closed-
441/// set typed enums) reaches the same four-arm accept-set the sibling
442/// [`RestartStrategy::from_wire`] resolver parses through and the sibling
443/// [`RestartStrategy::as_str`] emits, rather than an open-coded per-arm
444/// `match s { "OneForOne" => …, "OneForAll" => …, "RestForOne" => …,
445/// "SimpleOneForOne" => …, _ => … }` cascade whose arm-set has no
446/// compile-time link back to the substrate primitive.
447///
448/// Complements the pre-existing forward-projection triple
449/// ([`std::fmt::Display`], [`AsRef<str>`], [`RestartStrategy::as_str`])
450/// with the paired trait-idiomatic reverse-projection axis: Rust-side
451/// newtype/typed-enum convention pairs [`AsRef<str>`] with either
452/// [`std::str::FromStr`] or [`TryFrom<&str>`] on the same primitive so a
453/// caller who can project *out to* a `&str` can also project *in from*
454/// one. The [`TryFrom<&str>`] axis is deliberately chosen over
455/// [`std::str::FromStr`] to sidestep the `clippy::should_implement_trait`
456/// lint the sibling method-named [`RestartStrategy::from_wire`] would
457/// trigger under a `FromStr` impl and to avoid colliding with the
458/// [`std::str::FromStr`] impl the [`gen_platform::FromStrKind`] derive
459/// already installs on the paired *kebab-case dispatcher-catalog* axis
460/// (which parses `"one-for-one"` / `"one-for-all"` / `"rest-for-one"` /
461/// `"simple-one-for-one"`, the inverse of [`Self::discriminant`]) — this
462/// impl closes the trait-idiomatic reverse axis on the *`PascalCase` wire*
463/// half without disturbing either the method-named `from_wire` shape every
464/// sibling closed-set typed enum on the substrate already carries or the
465/// pre-existing `FromStr` on the dispatcher-catalog half, keeping the
466/// two-axis split the sibling [`Self::from_wire`] doc block motivates.
467///
468/// `type Error = ()` matches the sibling [`RestartStrategy::from_wire`]'s
469/// `Option<Self>` return-shape's deliberate deferral of error typing: the
470/// caller picks the diagnostic form appropriate for its use site (a future
471/// `feira supervisor --estrategia` arg-parse composes its own per-verb
472/// "unknown strategy: <arg> — accepted: {…}" message enumerating
473/// [`RestartStrategy::ALL`], a future M4 admission-webhook rejection body
474/// wraps the `Err(())` outcome with the accepted-set enumeration for
475/// operator diagnostics, a `Result::map_err` at the call site lifts the
476/// unit-error to a per-verb error type). Same shape the peer
477/// [`crate::CaixaKind`] (3c83606), [`crate::CaixaDialeto`] (bf33136),
478/// [`crate::aplicacao::PlacementStrategy`] (6fd00cd), and
479/// [`crate::provedor::ferrite::FerriteRuntime::from_wire`] blocks motivate
480/// on their peer closed-set typed enums' reverse projections.
481///
482/// The paired [`TryFrom<&str>`] impl reaches the same four-arm accept-set
483/// the [`RestartStrategy::from_wire`] resolver dispatches through, so any
484/// future arm addition (an OTP-`rest_for_all` fifth arm the theory
485/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
486/// might reach for once the four canonical OTP strategies stop covering
487/// the substrate's discovered load-shape) grows the trait-idiomatic axis
488/// by construction — one caixa-core edit on
489/// [`RestartStrategy::from_wire`] extends both the method-named reverse
490/// projection every existing consumer keys off and the trait-idiomatic
491/// reverse projection this impl exposes, without a coordinated rewrite
492/// across every future `TryFrom<&str>`-bound consumer's arm-set.
493///
494/// Extends the substrate-wide closed-set-enum reverse-projection family
495/// ([`crate::CaixaKind`] via 3c83606, [`crate::CaixaDialeto`] via bf33136,
496/// [`crate::aplicacao::PlacementStrategy`] via 6fd00cd) onto the first
497/// M2-OTP-shape closed-set typed enum on the caixa surface — the
498/// `:supervisor :estrategia` closed set the future wasm-operator's
499/// hierarchical reconciliation scheduler keys off end-to-end.
500///
501/// Pinned load-bearing by
502/// [`tests::restart_strategy_try_from_str_routes_through_from_wire_accessor`]
503/// (byte-parity pin against [`RestartStrategy::from_wire`] across the
504/// four-arm accept-set) and
505/// [`tests::restart_strategy_try_from_str_rejects_unknown_byte_strings`]
506/// (rejection witness against silent accept-set widening).
507impl TryFrom<&str> for RestartStrategy {
508    type Error = ();
509
510    fn try_from(s: &str) -> Result<Self, Self::Error> {
511        Self::from_wire(s).ok_or(())
512    }
513}
514
515/// Trait-idiomatic *forward* projection on the M2-OTP-shape sibling-restart
516/// [`RestartStrategy`] closed-set typed enum onto the `&'static str` axis —
517/// routes byte-for-byte through the paired substrate-primitive
518/// [`RestartStrategy::as_str`] `pub const fn` accessor so every future
519/// consumer that binds a [`RestartStrategy`] through the standard-library
520/// `.into()` / [`From<Self> for &'static str`] (equivalently
521/// [`Into<&'static str>`]) axis (a future
522/// `tracing::field::valuable::Value::Str(strategy.into())` structured-log
523/// recorder where the `Str` arm typing demands `&'static str` and the
524/// sibling [`AsRef<str>`] impl's borrowed `&str` return-type does not
525/// satisfy the bound, a future `Cow::Borrowed::<'static, str>(strategy.into())`
526/// composer on the future M4 admission-webhook rejection body where the
527/// `Cow<'static, str>` typing rules out the sibling [`AsRef<str>`] borrowed
528/// return, a generic `<T: Into<&'static str>>`-bound serializer on a
529/// per-strategy diagnostic column) reaches the same lifted
530/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
531/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
532/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
533/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const the
534/// paired [`std::fmt::Display`], [`AsRef<str>`], and
535/// [`RestartStrategy::as_str`] surfaces already return, rather than an
536/// open-coded per-arm `match s { OneForOne => "OneForOne", … }` cascade
537/// whose arm-set has no compile-time link back to the substrate primitive.
538///
539/// Complements the pre-existing quadruple
540/// ([`std::fmt::Display`], [`AsRef<str>`], [`RestartStrategy::as_str`],
541/// [`TryFrom<&str>`] via 5b828ed) with the paired trait-idiomatic
542/// forward-projection axis: Rust-side newtype/typed-enum convention pairs
543/// [`TryFrom<&str>`] (trait-idiomatic reverse) with [`From<Self> for
544/// &'static str`] (trait-idiomatic forward) on the same primitive so a
545/// caller who can project *in from* a `&str` via the trait axis can also
546/// project *out to* one — mirroring the `strum::IntoStaticStr` /
547/// `serde::Serialize`-shape idiom where both projection halves share one
548/// trait-driven vocabulary. Before this lift the substrate carried a
549/// `&str`-returning [`AsRef<str>`] but not the paired `&'static str`-
550/// returning [`From<Self> for &'static str`] axis every downstream
551/// generic that specifically needs `'static` byte-string bytes reaches for.
552///
553/// The paired [`RestartStrategy::as_str`] returns `&'static str` by
554/// construction (each `match` arm resolves to a
555/// [`crate::render::SUPERVISOR_ESTRATEGIA_*`] `pub const &str` with static
556/// lifetime), so the trait's return-type promise is upheld structurally.
557/// Any future silent detour that routes the impl through a non-static
558/// projection (a per-arm inline `String::from("OneForOne")`-shaped
559/// re-inlining that would `.leak()`-cast for the `'static` bound, a
560/// hypothetical rebrand of one arm's [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
561/// const to a non-`const &str`) is a caixa-core-build-time failure through
562/// the `pub const fn as_str` signature the trait routes through.
563///
564/// The paired impl reaches the same four-arm emit-set the
565/// [`RestartStrategy::as_str`] accessor dispatches through, so any future
566/// arm addition (an OTP-`rest_for_all` fifth arm the theory
567/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
568/// might reach for once the four canonical OTP strategies stop covering
569/// the substrate's discovered load-shape) grows the trait-idiomatic
570/// forward axis by construction — one caixa-core edit on
571/// [`RestartStrategy::as_str`] extends every one of the five sibling
572/// forward-projection paths ([`std::fmt::Display`], [`AsRef<str>`],
573/// [`RestartStrategy::as_str`] itself, this [`From<Self> for &'static str`],
574/// and the un-`rename`d [`serde::Serialize`] derive that also emits
575/// [`Self::as_str`]'s bytes) without a coordinated rewrite across every
576/// future `Into<&'static str>`-bound consumer's arm-set.
577///
578/// Opens the substrate-wide trait-idiomatic *forward*-projection family on
579/// closed-set fieldless typed enums — the mirror of the recently-closed
580/// trait-idiomatic *reverse*-projection family ([`crate::CaixaKind`] via
581/// 3c83606, [`crate::CaixaDialeto`] via bf33136,
582/// [`crate::aplicacao::PlacementStrategy`] via 6fd00cd, this enum via
583/// 5b828ed, [`crate::supervisor::RestartPolicy`] via 6fdd0d9,
584/// [`crate::aplicacao::WitShape`] via 5472902,
585/// [`crate::aplicacao::RateLimitUnit`] via bf78400,
586/// [`crate::render::PathShapeViolation`] via e67e48a, and the four
587/// downstream-crate peers — [`caixa_arch::InvariantKind`] via e21a857,
588/// [`caixa_arch::ArchVerdict`] via 0a4cc45, [`caixa_lint::Severity`] via
589/// a7bf74c, [`caixa_lint::FixSafety`] via df86c94,
590/// [`caixa_theme::Semantic`] via bd7da69, and
591/// [`caixa_provedor::ferrite::FerriteRuntime`] via 42ab951). This lift
592/// picks [`RestartStrategy`] as the first-mover on the forward-projection
593/// family because its wire byte-string (`PascalCase`) and diagnostic
594/// byte-string ([`as_str`] return) coincide by construction — the sibling
595/// [`crate::CaixaKind`] two-axis split (lowercase Portuguese diagnostic
596/// vs `PascalCase` wire) would leave a first-mover peer arbitrarily
597/// picking one axis; on [`RestartStrategy`] the choice is unambiguous.
598///
599/// Pinned load-bearing by
600/// [`tests::restart_strategy_from_into_static_str_routes_through_as_str_accessor`]
601/// (byte-parity pin against [`RestartStrategy::as_str`] across the
602/// four-arm emit-set, plus a `const`-context materialization witness for
603/// the `&'static str` lifetime promise) and
604/// [`tests::restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
605/// (partition pin asserting `<&'static str as From<RestartStrategy>>::from`
606/// and [`RestartStrategy::as_str`] agree on every arm, so no future
607/// silent bifurcation of the two forward-projection paths can land
608/// silently).
609impl From<RestartStrategy> for &'static str {
610    fn from(strategy: RestartStrategy) -> &'static str {
611        strategy.as_str()
612    }
613}
614
615/// Trait-idiomatic *forward* projection on [`RestartStrategy`] from a
616/// *borrowed* input onto the `&'static str` axis — the borrowed-input
617/// companion to the paired owned-input [`From<RestartStrategy> for
618/// &'static str`] impl immediately above. Routes byte-for-byte through
619/// the same substrate-primitive [`RestartStrategy::as_str`] `pub const
620/// fn` accessor so every consumer that binds a `&RestartStrategy`
621/// through the standard-library `.into()` / [`From<&Self> for &'static
622/// str`] axis (a `RestartStrategy::ALL.iter().map(<&'static
623/// str>::from).collect::<Vec<_>>()` per-arm accept-set materializer —
624/// whose iterator over `&'static [RestartStrategy]` yields
625/// `&RestartStrategy`, not `RestartStrategy`, so the owned-input
626/// [`From<RestartStrategy>`] axis alone forces every call site through
627/// an explicit `.copied()` / dereference / [`Copy`]-bound restatement
628/// rather than the direct trait-idiomatic projection; a future generic
629/// `<T: Copy + for<'a> Into<&'static str>>`-bound diagnostic column
630/// that walks the `iter().map(Into::into)` shape verbatim across every
631/// substrate-wide closed-set typed enum; the future wasm-operator's
632/// per-supervisor sibling-restart-strategy diagnostic line that
633/// composes the accepted-set enumeration from an iterated
634/// `RestartStrategy::ALL.iter().map(|s| s.into())` pipe rather than a
635/// per-arm `match s { … }` cascade; a future
636/// `HashMap::<&'static str, RestartStrategy>::from_iter(
637///     RestartStrategy::ALL.iter().map(|s| (s.into(), *s)))`-style
638/// per-strategy reverse-lookup table the sibling [`TryFrom<&str>`]
639/// impl cannot compose without this borrowed-input axis in place)
640/// reaches the same four-arm lifted
641/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
642/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
643/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
644/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const
645/// the paired owned-input [`From<RestartStrategy> for &'static str`],
646/// the sibling [`std::fmt::Display`], [`AsRef<str>`], and
647/// [`RestartStrategy::as_str`] surfaces already return.
648///
649/// Fourth peer on the substrate-wide trait-idiomatic *borrowed-input*
650/// forward-projection family opened on [`crate::dep::DepList`]
651/// (64aa742) and extended onto [`crate::CaixaKind`] (5ab993a) and
652/// [`crate::CaixaDialeto`] (807b0b5). Rust's `From` trait does not
653/// auto-derive the `From<&Self>` sibling from a `From<Self>` impl (the
654/// blanket `impl<T, U> From<&T> for U where T: Copy, U: From<T>` does
655/// not exist in `core`), so every closed-set typed enum that carries
656/// the owned-input axis but not the borrowed-input axis forces every
657/// borrowed-input call site through a `.copied()` /
658/// `<&'static str>::from(*strategy)` / `strategy.as_str()` detour whose
659/// type bounds have no compile-time link to the substrate primitive.
660/// [`RestartStrategy`] is the first M2 OTP-shape peer to converge onto
661/// this campaign (mirroring the first-mover role it played on the
662/// owned-input axis in 523157d); the remaining eleven substrate-wide
663/// closed-set fieldless typed enum peers (`RestartPolicy`, `WitShape`,
664/// `RateLimitUnit`, `PlacementStrategy`, `PathShapeViolation`,
665/// `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`,
666/// `FerriteRuntime`) are the future targets of this campaign.
667///
668/// Unlike the peer [`crate::CaixaKind`] axis pair (whose forward
669/// [`From<Self> for &'static str`] emits the lowercase Portuguese
670/// [`Self::as_str`] diagnostic vocabulary while the reverse
671/// [`TryFrom<&str>`] parses the `PascalCase` [`Self::wire_name`]
672/// author-surface vocabulary, forcing the round-trip through an
673/// intermediate wire-vocab hop), [`RestartStrategy`]'s
674/// [`Self::as_str`] emit and [`Self::from_wire`] parse share the same
675/// `PascalCase` vocabulary by construction, so the borrowed-input
676/// forward axis and the reverse axis compose directly — the round-trip
677/// witness pin below locks this direct composition without the
678/// intermediate hop the peer axis requires.
679///
680/// Pinned load-bearing by
681/// [`tests::restart_strategy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
682/// (byte-parity pin against [`RestartStrategy::as_str`] across the
683/// four-arm emit-set via a borrowed input, plus a `const`-context
684/// materialization witness for the `&'static str` lifetime promise,
685/// plus a blanket `.into()` shape) and
686/// [`tests::restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
687/// (cross-axis partition pin against the paired owned-input
688/// [`From<RestartStrategy> for &'static str`] impl, plus a
689/// `.iter().map(Into::into)` pipe witness over
690/// [`RestartStrategy::ALL`], plus a direct round-trip witness through
691/// [`TryFrom<&str>`] that closes the two-way `&Self → &'static str →
692/// Self` round-trip without the wire-vocab intermediate the peer
693/// [`crate::CaixaKind`] axis pair requires).
694impl From<&RestartStrategy> for &'static str {
695    fn from(strategy: &RestartStrategy) -> &'static str {
696        strategy.as_str()
697    }
698}
699
700/// Trait-idiomatic *owned-`String`* forward projection on the M2
701/// OTP-shape sibling-restart-strategy closed-set typed enum — the
702/// owned-heap-string companion to the paired `&'static str`-returning
703/// [`From<RestartStrategy> for &'static str`] / [`From<&RestartStrategy>
704/// for &'static str`] impls immediately above. Routes byte-for-byte
705/// through the substrate-primitive [`RestartStrategy::as_str`]
706/// `pub const fn` accessor (via [`str::to_owned`]) so every consumer
707/// that binds a [`RestartStrategy`] through the standard-library
708/// `.into()` / [`From<Self> for String`] (equivalently
709/// [`Into<String>`]) axis — a future
710/// `serde_json::Value::String(strategy.into())` structured-payload
711/// composer where the `Value::String` arm typing demands an owned
712/// [`String`] and the sibling [`&'static str`]-returning axis forces an
713/// explicit `.to_owned()` / `String::from` restatement at every call
714/// site, a future
715/// `HashMap::<String, RestartStrategy>::from_iter(RestartStrategy::ALL
716/// .iter().map(|s| (s.into(), *s)))` per-strategy lookup where the
717/// map's key type is owned [`String`] rather than [`&'static str`], a
718/// future `Cow::<'static, str>::Owned(strategy.into())` composer on
719/// the future M4 admission-webhook rejection body's owned-arm, the
720/// future wasm-operator's per-supervisor `serde_json::json!({
721/// "estrategia": strategy })` diagnostic emit where the JSON
722/// serializer's `Serialize` impl on [`String`] owns the emit-path — reaches
723/// the same four-arm lifted
724/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
725/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
726/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
727/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const the
728/// paired [`std::fmt::Display`], [`AsRef<str>`],
729/// [`RestartStrategy::as_str`], and the two `&'static str`-returning
730/// forward-projection impls already return.
731///
732/// Opens the trait-idiomatic *owned-`String`* forward-projection axis
733/// on the closed-set fieldless typed enum surface — first-mover on the
734/// M2 OTP-shape sibling-restart-strategy axis, mirror of the
735/// [`crate::supervisor::RestartStrategy`] first-mover position that
736/// opened the paired owned-`&'static str` axis (523157d) and the
737/// borrowed-input `&'static str` axis on
738/// [`crate::dep::DepList`] (64aa742). Rust's standard library does not
739/// carry a blanket `impl<T: AsRef<str>> From<T> for String` (nor an
740/// `impl<T: fmt::Display> From<T> for String`), so every closed-set
741/// typed enum that carries the paired `AsRef<str>` / `Display` /
742/// `From<Self> for &'static str` triple but not the owned-[`String`]
743/// axis forces every owned-string call site through a `.to_string()` /
744/// `.as_str().to_owned()` / `String::from(strategy.as_str())` detour
745/// whose type bounds have no compile-time link to the substrate
746/// primitive.
747///
748/// Deliberately routes through the human-readable
749/// [`RestartStrategy::as_str`] axis — for this enum the wire format
750/// (`PascalCase`, tatara-lisp author surface `:estrategia OneForOne`)
751/// and the diagnostic byte-string share the same vocabulary by
752/// construction (unlike the sibling [`crate::CaixaKind`] enum whose two
753/// axes diverge), so the owned-[`String`] projection lands
754/// byte-identically on both the wire vocabulary the paired
755/// [`serde::Serialize`] derive emits and the diagnostic vocabulary the
756/// [`RestartStrategy::as_str`] helper returns.
757///
758/// The remaining fourteen closed-set typed enums on the caixa
759/// substrate surface (`RestartPolicy`, `CaixaKind`, `CaixaDialeto`,
760/// `DepList`, `PlacementStrategy`, `WitShape`, `RateLimitUnit`,
761/// `PathShapeViolation`, `InvariantKind`, `ArchVerdict`, `Severity`,
762/// `FixSafety`, `Semantic`, `FerriteRuntime`) are the future targets of
763/// this campaign — each carries the same paired `AsRef<str>` /
764/// `Display` / `From<Self> for &'static str` / `From<&Self> for
765/// &'static str` quadruple that this owned-[`String`] axis extends onto.
766///
767/// Pinned load-bearing by
768/// [`tests::restart_strategy_from_into_owned_string_routes_through_as_str_accessor`]
769/// (byte-parity pin against [`RestartStrategy::as_str`] across the
770/// four-arm emit-set, plus a blanket `.into::<String>()` shape witness)
771/// and
772/// [`tests::restart_strategy_from_into_owned_string_and_static_str_agree_on_every_arm`]
773/// (cross-axis partition pin against the paired owned-input
774/// [`From<RestartStrategy> for &'static str`] impl and the sibling
775/// [`ToString::to_string`] surface routed through [`std::fmt::Display`],
776/// plus a direct round-trip witness through [`TryFrom<&str>`] on the
777/// owned-[`String`]'s [`String::as_str`] borrow that closes the two-way
778/// `Self → String → Self` round-trip on the trait-idiomatic
779/// owned-[`String`] forward + reverse axis pair).
780impl From<RestartStrategy> for String {
781    fn from(strategy: RestartStrategy) -> String {
782        strategy.as_str().to_owned()
783    }
784}
785
786/// Trait-idiomatic *borrowed-input, owned-`String` output* forward
787/// projection on the M2 OTP-shape sibling-restart-strategy closed-set
788/// typed enum — the fourth (and closing) corner of the
789/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
790/// projection family. Routes byte-for-byte through the
791/// substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
792/// accessor (via [`str::to_owned`]) so every consumer that holds a
793/// borrowed [`&RestartStrategy`] and needs an owned [`String`] — a
794/// future `serde_json::Value::String(String::from(&strategy))`
795/// structured-payload composer over a borrowed field, a future
796/// `Iterator::map` over `&[RestartStrategy]` that projects to owned
797/// keys through `.iter().map(String::from)`, a future
798/// `HashMap::<String, RestartStrategy>::from_iter` that keys off a
799/// borrowed-iteration axis where dereferencing the strategy would force
800/// an unnecessary `Copy` at every step, the future wasm-operator's
801/// per-supervisor `strategies.iter().map(String::from).collect()`
802/// diagnostic emit whose iteration axis is borrowed by construction —
803/// reaches the same four-arm lifted
804/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
805/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
806/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
807/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const the
808/// paired [`std::fmt::Display`], [`AsRef<str>`],
809/// [`RestartStrategy::as_str`], and the three other trait-idiomatic
810/// forward-projection impls
811/// ([`From<RestartStrategy> for &'static str`],
812/// [`From<&RestartStrategy> for &'static str`],
813/// [`From<RestartStrategy> for String`]) already return.
814///
815/// Opens the trait-idiomatic *borrowed-input, owned-`String` output*
816/// forward-projection axis on closed-set fieldless typed enums —
817/// first-mover on the 2×2 completion corner, mirror of the
818/// [`crate::supervisor::RestartStrategy`] first-mover position that
819/// opened the paired owned-input owned-`String` axis (7baa18a), the
820/// owned-input owned-`&'static str` axis (523157d), and the paired
821/// [`crate::dep::DepList`] first-mover position that opened the
822/// borrowed-input `&'static str` axis (64aa742). Rust's standard
823/// library does not carry a blanket `impl<T: AsRef<str>> From<&T> for
824/// String` (nor an `impl<T: fmt::Display> From<&T> for String`), so
825/// every closed-set typed enum that carries the paired `AsRef<str>` /
826/// `Display` / `From<Self> for &'static str` / `From<&Self> for
827/// &'static str` / `From<Self> for String` quintuple but not the
828/// borrowed-input owned-[`String`] axis forces every borrowed-input
829/// owned-string call site through a `strategy.as_str().to_owned()` /
830/// `String::from(*strategy)` (with a spurious `Copy`) /
831/// `strategy.to_string()` (through `Display`) detour whose type bounds
832/// have no compile-time link to the substrate primitive.
833///
834/// Deliberately routes through the human-readable
835/// [`RestartStrategy::as_str`] axis — for this enum the wire format
836/// (`PascalCase`, tatara-lisp author surface `:estrategia OneForOne`)
837/// and the diagnostic byte-string share the same vocabulary by
838/// construction (unlike the sibling [`crate::CaixaKind`] enum whose two
839/// axes diverge), so the borrowed-input owned-[`String`] projection
840/// lands byte-identically on both the wire vocabulary the paired
841/// [`serde::Serialize`] derive emits and the diagnostic vocabulary the
842/// [`RestartStrategy::as_str`] helper returns.
843///
844/// The remaining fourteen closed-set typed enums on the caixa
845/// substrate surface (`RestartPolicy`, `CaixaKind`, `CaixaDialeto`,
846/// `DepList`, `PlacementStrategy`, `WitShape`, `RateLimitUnit`,
847/// `PathShapeViolation`, `InvariantKind`, `ArchVerdict`, `Severity`,
848/// `FixSafety`, `Semantic`, `FerriteRuntime`) are the future targets of
849/// this 2×2-completion campaign — each carries the same paired
850/// quintuple that this borrowed-input owned-[`String`] axis extends onto.
851///
852/// Pinned load-bearing by
853/// [`tests::restart_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
854/// (byte-parity pin against [`RestartStrategy::as_str`] across the
855/// four-arm emit-set through the borrowed-input surface) and
856/// [`tests::restart_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
857/// (cross-axis partition pin against the paired owned-input owned-
858/// [`String`] [`From<RestartStrategy> for String`] impl, the paired
859/// borrowed-input owned-[`&'static str`] [`From<&RestartStrategy> for
860/// &'static str`] impl, and the sibling [`ToString::to_string`] surface
861/// routed through [`std::fmt::Display`], plus a direct round-trip
862/// witness through [`TryFrom<&str>`] on the owned-[`String`]'s
863/// [`String::as_str`] borrow that closes the two-way
864/// `&Self → String → Self` round-trip on the trait-idiomatic
865/// borrowed-input owned-[`String`] forward + reverse axis pair).
866impl From<&RestartStrategy> for String {
867    fn from(strategy: &RestartStrategy) -> String {
868        strategy.as_str().to_owned()
869    }
870}
871
872/// Trait-idiomatic *owned-input, [`std::borrow::Cow<'static, str>`]
873/// output* forward projection on the M2 OTP-shape sibling-restart
874/// [`RestartStrategy`] closed-set typed enum — extends the substrate-
875/// wide [`std::borrow::Cow<'static, str>`] forward-projection family
876/// opened on [`crate::CaixaKind`] (99c1735) onto the first M2 OTP-
877/// shape closed-set fieldless typed enum peer on the caixa surface
878/// (`:supervisor :estrategia`). Routes byte-for-byte through the
879/// substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
880/// accessor (via [`std::borrow::Cow::Borrowed`]) so every consumer
881/// that binds a [`RestartStrategy`] through the trait-idiomatic
882/// [`std::borrow::Cow<'static, str>`] axis — a future
883/// `axum::response::IntoResponse` composer whose per-strategy
884/// diagnostic-body typing rules out the sibling [`AsRef<str>`]
885/// borrowed return, a future M4 admission-webhook rejection body
886/// that composes the accepted-strategy enumeration through the same
887/// `RestartStrategy::ALL.iter().map(Cow::from)` shape [`CaixaKind`]
888/// already routes through, a generic `<T: for<'a>
889/// Into<std::borrow::Cow<'static, str>>>`-bound structured-log
890/// emitter on a per-supervisor diagnostic column — reaches the same
891/// four-arm lifted [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`]
892/// / [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
893/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
894/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const
895/// the paired [`std::fmt::Display`], [`AsRef<str>`],
896/// [`RestartStrategy::as_str`], and the four
897/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
898/// forward-projection corners already return.
899///
900/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
901/// [`std::borrow::Cow::Owned`] — the substrate-primitive
902/// [`RestartStrategy::as_str`] accessor's return carries the
903/// `&'static str` lifetime by construction (each `match` arm resolves
904/// to a [`crate::render::SUPERVISOR_ESTRATEGIA_*`] `pub const &str`
905/// with static lifetime), so the zero-alloc borrowed arm is the
906/// type-correct projection with no runtime allocation.
907///
908/// Rust's standard library carries no blanket `impl<T: AsRef<str>>
909/// From<T> for Cow<'static, str>` (nor an `impl<T: fmt::Display>
910/// From<T> for Cow<'static, str>`), so the paired sibling
911/// [`From<RestartStrategy> for &'static str`],
912/// [`From<RestartStrategy> for String`], [`AsRef<str>`], and
913/// [`std::fmt::Display`] surfaces do not implicitly extend to a
914/// [`Cow<'static, str>`]-bound call site — every such site is forced
915/// through a `Cow::Borrowed(strategy.as_str())` /
916/// `Cow::Owned(strategy.to_string())` open-code whose type bounds
917/// have no compile-time link back to the substrate primitive until
918/// this lift.
919///
920/// First peer to extend the substrate-wide trait-idiomatic
921/// [`std::borrow::Cow<'static, str>`] forward-projection axis off the
922/// top-level [`crate::CaixaKind`] enum (99c1735 owned-input,
923/// d45c409 borrowed-input) onto the wider substrate — the remaining
924/// twelve peers (`RestartPolicy`, `PlacementStrategy`, `RateLimitUnit`,
925/// `DepList`, `CaixaDialeto`, and the outside-`caixa-core` peers
926/// `WitShape`, `PathShapeViolation`, `InvariantKind`, `ArchVerdict`,
927/// `Severity`, `FixSafety`, `Semantic`, `FerriteRuntime`) are the
928/// future targets of this campaign.
929///
930/// Pinned load-bearing by
931/// [`tests::restart_strategy_from_into_static_cow_str_routes_through_as_str_accessor`]
932/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
933/// against [`RestartStrategy::as_str`] across the four-arm
934/// [`RestartStrategy::ALL`]) and
935/// [`tests::restart_strategy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
936/// (cross-axis partition pin against the paired [`From<RestartStrategy>
937/// for &'static str`], [`From<RestartStrategy> for String`], and
938/// [`ToString`]-through-[`std::fmt::Display`] axes, plus a
939/// `.iter().copied().map(Cow::from)` pipe witness over
940/// [`RestartStrategy::ALL`] that materializes the four-arm accept-set
941/// through the [`Cow<'static, str>`] axis alone and pins the
942/// zero-alloc discipline on every element).
943impl From<RestartStrategy> for std::borrow::Cow<'static, str> {
944    fn from(strategy: RestartStrategy) -> std::borrow::Cow<'static, str> {
945        std::borrow::Cow::Borrowed(strategy.as_str())
946    }
947}
948
949/// Trait-idiomatic *borrowed-input, [`std::borrow::Cow<'static, str>`]
950/// output* forward projection on the M2 OTP-shape sibling-restart
951/// [`RestartStrategy`] closed-set typed enum — the borrowed-input
952/// companion to the paired owned-input
953/// [`From<RestartStrategy> for std::borrow::Cow<'static, str>`] impl
954/// immediately above (7dd28b3). Routes byte-for-byte through the same
955/// substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
956/// accessor (via [`std::borrow::Cow::Borrowed`]) so every consumer
957/// that holds a `&RestartStrategy` and needs a
958/// [`std::borrow::Cow<'static, str>`] — a
959/// `RestartStrategy::ALL.iter().map(std::borrow::Cow::from).collect::<Vec<_>>()`
960/// per-arm accept-set materializer (whose iterator over
961/// `&'static [RestartStrategy]` yields `&RestartStrategy`, not
962/// `RestartStrategy`, so the paired owned-input
963/// [`From<RestartStrategy> for std::borrow::Cow<'static, str>`] axis
964/// alone forces every call site through an explicit `.copied()` /
965/// dereference / [`Copy`]-bound restatement rather than the direct
966/// trait-idiomatic projection), a future generic
967/// `<T: for<'a> Into<std::borrow::Cow<'static, str>>>`-bound emitter
968/// on a per-strategy diagnostic column that walks the
969/// `iter().map(Into::into)` shape verbatim, the future M4 admission-
970/// webhook rejection body that composes the accepted-strategy
971/// enumeration from an iterated
972/// `RestartStrategy::ALL.iter().map(|s| s.into())` pipe rather than a
973/// per-arm `match s { … }` cascade — reaches the same four-arm lifted
974/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
975/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
976/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
977/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const
978/// the paired [`std::fmt::Display`], [`AsRef<str>`],
979/// [`RestartStrategy::as_str`], the four
980/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
981/// forward-projection corners, and the paired owned-input
982/// [`From<RestartStrategy> for std::borrow::Cow<'static, str>`] impl
983/// already return.
984///
985/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
986/// [`std::borrow::Cow::Owned`] — the substrate-primitive
987/// [`RestartStrategy::as_str`] accessor's return carries the
988/// `&'static str` lifetime by construction (each `match` arm resolves
989/// to a [`crate::render::SUPERVISOR_ESTRATEGIA_*`] `pub const &str`
990/// with static lifetime), so the zero-alloc borrowed arm is the
991/// type-correct projection with no runtime allocation.
992///
993/// Second peer on the substrate-wide trait-idiomatic
994/// [`std::borrow::Cow<'static, str>`] forward-projection family
995/// opened one commit prior (7dd28b3) on the paired owned-input
996/// [`From<RestartStrategy> for std::borrow::Cow<'static, str>`] impl
997/// — closes the `{Self, &Self}` input-shape corner of the
998/// [`Cow<'static, str>`] axis on the first M2 OTP-shape closed-set
999/// fieldless typed enum peer on the caixa surface, exactly as
1000/// d45c409 closed it on the top-level [`crate::CaixaKind`] one commit
1001/// after the owning half (99c1735) landed. Rust's standard library
1002/// does not carry a blanket `impl<T: AsRef<str>> From<&T> for
1003/// Cow<'static, str>` (nor an `impl<T: fmt::Display> From<&T> for
1004/// Cow<'static, str>`), so every closed-set fieldless typed enum peer
1005/// on the substrate that carries the paired owned-input
1006/// [`Cow<'static, str>`] axis but not the borrowed-input axis forces
1007/// every borrowed-input [`Cow<'static, str>`]-parameterized call site
1008/// through a spurious [`Copy`] deref
1009/// (`std::borrow::Cow::from(*strategy)`) or a
1010/// `std::borrow::Cow::Borrowed(strategy.as_str())` open-code whose
1011/// type bounds have no compile-time link to the substrate primitive.
1012///
1013/// Pinned load-bearing by
1014/// [`tests::restart_strategy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor`]
1015/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
1016/// against [`RestartStrategy::as_str`] across the four-arm
1017/// [`RestartStrategy::ALL`] through the borrowed-input surface) and
1018/// [`tests::restart_strategy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
1019/// (cross-axis partition pin against the paired owned-input
1020/// [`From<RestartStrategy> for std::borrow::Cow<'static, str>`], the
1021/// paired borrowed-input owned-`&'static str`
1022/// [`From<&RestartStrategy> for &'static str`], and the paired
1023/// borrowed-input owned-`String` [`From<&RestartStrategy> for String`]
1024/// impls, plus a `.iter().map(std::borrow::Cow::from)` pipe witness
1025/// over [`RestartStrategy::ALL`] — whose iterator yields
1026/// `&RestartStrategy` by construction, so the borrowed-input
1027/// [`Cow<'static, str>`] axis is what routes the pipe through the
1028/// substrate-primitive [`RestartStrategy::as_str`] accessor with the
1029/// zero-alloc [`Cow::Borrowed`] arm by construction and without a
1030/// spurious [`Copy`] deref).
1031impl From<&RestartStrategy> for std::borrow::Cow<'static, str> {
1032    fn from(strategy: &RestartStrategy) -> std::borrow::Cow<'static, str> {
1033        std::borrow::Cow::Borrowed(strategy.as_str())
1034    }
1035}
1036
1037/// Trait-idiomatic *owned-input, [`Box<str>`] output* forward
1038/// projection on the M2 OTP-shape sibling-restart [`RestartStrategy`]
1039/// closed-set fieldless typed enum — opens a fresh
1040/// substrate-wide `Box<str>` forward-projection campaign tier on the
1041/// first M2 OTP-shape closed-set fieldless typed enum peer on the
1042/// caixa surface, immediately after the paired `Cow<'static, str>`
1043/// axis (7dd28b3 / ee577fd) closed the
1044/// `{Self, &Self} × {&'static str, String, Cow<'static, str>}` 2×3
1045/// corner on this enum. Routes byte-for-byte through the
1046/// substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
1047/// accessor via [`Box::<str>::from`] on the returned `&'static str`,
1048/// so every consumer that binds a
1049/// `let key: Box<str> = strategy.into();`-shaped call site — a
1050/// per-supervisor metric-key materializer that stashes the strategy
1051/// discriminator in a `Box<str>`-typed heap-owned scalar for cheap
1052/// clone (a shared-nothing per-strategy accept-set the
1053/// `caixa-operator` reconciliation scheduler carries), a future
1054/// admission-webhook rejection body whose per-arm `Box<str>` field
1055/// composes from an owned `RestartStrategy` handle — reaches the
1056/// same four-arm lifted
1057/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
1058/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
1059/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
1060/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const
1061/// the sibling
1062/// `{Self, &Self} × {&'static str, String, Cow<'static, str>}`
1063/// forward-projection corner already returns. Rust's standard
1064/// library carries `impl From<&str> for Box<str>` and
1065/// `impl From<String> for Box<str>` but no blanket
1066/// `impl<T: AsRef<str>> From<T> for Box<str>`, so this axis is a
1067/// distinct trait-idiomatic surface that a downstream
1068/// `RestartStrategy → Box<str>` `.into()` reaches through this impl
1069/// and no other — without a
1070/// `Box::from(strategy.as_str())` open-code whose type bounds have
1071/// no compile-time link back to the substrate primitive.
1072///
1073/// Pinned load-bearing by
1074/// [`tests::restart_strategy_from_into_box_str_routes_through_as_str_accessor`]
1075/// (byte-parity pin against [`RestartStrategy::as_str`] across the
1076/// four-arm [`RestartStrategy::ALL`] emit-set on the owned-input
1077/// surface, plus a blanket-derived [`Into`] shape witness).
1078impl From<RestartStrategy> for Box<str> {
1079    fn from(strategy: RestartStrategy) -> Box<str> {
1080        Box::<str>::from(strategy.as_str())
1081    }
1082}
1083
1084/// Trait-idiomatic *borrowed-input, [`Box<str>`] output* forward
1085/// projection on the M2 OTP-shape sibling-restart [`RestartStrategy`]
1086/// closed-set fieldless typed enum — closes the `{Self, &Self}`
1087/// input-shape corner of the substrate-wide `Box<str>`
1088/// forward-projection axis opened one commit prior (69ef45c) on the
1089/// paired owned-input [`From<RestartStrategy> for Box<str>`] impl.
1090/// Routes byte-for-byte through the same substrate-primitive
1091/// [`RestartStrategy::as_str`] `pub const fn` accessor via
1092/// [`Box::<str>::from`] on the returned `&'static str`, so every
1093/// consumer that holds a `&RestartStrategy` and needs a
1094/// [`Box<str>`] — a
1095/// `RestartStrategy::ALL.iter().map(Box::<str>::from).collect::<Vec<_>>()`
1096/// per-arm accept-set materializer (whose iterator over
1097/// `&'static [RestartStrategy]` yields `&RestartStrategy`, not
1098/// `RestartStrategy`, so the paired owned-input
1099/// [`From<RestartStrategy> for Box<str>`] axis alone forces every
1100/// call site through an explicit `.copied()` / dereference /
1101/// [`Copy`]-bound restatement rather than the direct trait-idiomatic
1102/// projection), a per-supervisor metric-key materializer holding
1103/// `&RestartStrategy` through a `caixa-operator` reconciliation
1104/// scheduler's borrow lifetime, a future admission-webhook rejection
1105/// body whose per-arm `Box<str>` field composes from a borrowed
1106/// `&RestartStrategy` handle without a spurious [`Copy`] deref —
1107/// reaches the same four-arm lifted
1108/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
1109/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
1110/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
1111/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const
1112/// the paired owned-input [`From<RestartStrategy> for Box<str>`] and
1113/// the sibling
1114/// `{Self, &Self} × {&'static str, String, Cow<'static, str>}`
1115/// forward-projection corner already return.
1116///
1117/// Second peer on the substrate-wide trait-idiomatic
1118/// [`Box<str>`] forward-projection family opened one commit prior
1119/// (69ef45c) on the paired owned-input
1120/// [`From<RestartStrategy> for Box<str>`] impl — closes the
1121/// `{Self, &Self}` input-shape corner of the [`Box<str>`] axis on
1122/// the first M2 OTP-shape closed-set fieldless typed enum peer on
1123/// the caixa surface (`:supervisor :estrategia`), exactly as
1124/// ee577fd closed the paired [`Cow<'static, str>`] axis one commit
1125/// after its owning half (7dd28b3) landed. Rust's standard library
1126/// carries `impl From<&str> for Box<str>` and
1127/// `impl From<String> for Box<str>` but no blanket
1128/// `impl<T: AsRef<str>> From<&T> for Box<str>` (nor a
1129/// `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`), so
1130/// every closed-set fieldless typed enum peer on the substrate that
1131/// carries the paired owned-input `Box<str>` axis but not the
1132/// borrowed-input axis forces every borrowed-input
1133/// `Box<str>`-parameterized call site through a spurious [`Copy`]
1134/// deref (`Box::<str>::from((*strategy).as_str())`) or a
1135/// `Box::<str>::from(strategy.as_str())` open-code whose type bounds
1136/// have no compile-time link back to the substrate primitive.
1137///
1138/// Pinned load-bearing by
1139/// [`tests::restart_strategy_from_borrowed_into_box_str_routes_through_as_str_accessor`]
1140/// (byte-parity pin against [`RestartStrategy::as_str`] across the
1141/// four-arm [`RestartStrategy::ALL`] emit-set on the borrowed-input
1142/// surface, plus a blanket-derived [`Into`] shape witness and a
1143/// cross-axis pin against the paired owned-input
1144/// [`From<RestartStrategy> for Box<str>`] and the sibling
1145/// borrowed-input `{&'static str, String, Cow<'static, str>}`
1146/// return-shape axes).
1147impl From<&RestartStrategy> for Box<str> {
1148    fn from(strategy: &RestartStrategy) -> Box<str> {
1149        Box::<str>::from(strategy.as_str())
1150    }
1151}
1152
1153/// Trait-idiomatic *owned-input, [`std::sync::Arc<str>`] output*
1154/// forward projection on the M2 OTP-shape sibling-restart
1155/// [`RestartStrategy`] closed-set fieldless typed enum — opens the
1156/// substrate-wide [`std::sync::Arc<str>`] forward-projection campaign
1157/// tier on the first M2 OTP-shape closed-set fieldless typed enum peer
1158/// on the caixa surface (`:supervisor :estrategia`), immediately after
1159/// the paired [`Box<str>`] axis (69ef45c / 59ae5dc) closed the
1160/// `{Self, &Self} × {&'static str, String, Cow<'static, str>, Box<str>}`
1161/// 2×4 corner on this enum. Routes byte-for-byte through the
1162/// substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
1163/// accessor (via [`std::sync::Arc::<str>::from`] on the returned
1164/// `&'static str`), so every consumer that binds a
1165/// [`RestartStrategy`] through the standard-library `.into()` /
1166/// [`From<Self> for std::sync::Arc<str>`] (equivalently
1167/// [`Into<std::sync::Arc<str>>`]) axis — a future admission-webhook
1168/// running under `axum` + `tokio` whose per-arm structured-log field
1169/// crosses an `.await` boundary and demands the [`Sync`] +
1170/// [`Send`]-safe shared-ownership envelope [`std::sync::Arc<str>`]
1171/// provides (the sibling [`Box<str>`] axis's owned-move return-shape
1172/// forces every downstream `.clone()` through a heap allocation, while
1173/// [`std::sync::Arc<str>`]'s reference-counted shared-ownership
1174/// resolves the same `.clone()` through a refcount bump), a future
1175/// wasm-operator's per-supervisor reconciliation scheduler that
1176/// dispatches the same per-strategy diagnostic key onto multiple
1177/// concurrent reconcile-loop tasks holding shared-ownership through
1178/// [`std::sync::Arc<str>`], a future
1179/// `tracing::field::valuable::Value::Str(strategy.into())` structured-
1180/// log recorder whose typing folds a shared-ownership envelope onto
1181/// the span-context axis, a generic
1182/// `<T: Into<std::sync::Arc<str>>>`-bound diagnostic column on a
1183/// shared-ownership per-strategy cache — reaches the same four-arm
1184/// lifted [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
1185/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
1186/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
1187/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const
1188/// the sibling
1189/// `{Self, &Self} × {&'static str, String, Cow<'static, str>, Box<str>}`
1190/// forward-projection corner already returns.
1191///
1192/// First-mover on the substrate-wide trait-idiomatic
1193/// [`std::sync::Arc<str>`] forward-projection family — Rust's
1194/// standard library carries `impl From<&str> for std::sync::Arc<str>`
1195/// and `impl From<String> for std::sync::Arc<str>` but no blanket
1196/// `impl<T: AsRef<str>> From<T> for std::sync::Arc<str>` (nor an
1197/// `impl<T: fmt::Display> From<T> for std::sync::Arc<str>`), so every
1198/// closed-set fieldless typed enum on the substrate that carries the
1199/// paired [`AsRef<str>`] / [`std::fmt::Display`] /
1200/// [`From<Self> for &'static str`] / [`From<&Self> for &'static str`] /
1201/// [`From<Self> for String`] / [`From<&Self> for String`] /
1202/// [`From<Self> for Cow<'static, str>`] /
1203/// [`From<&Self> for Cow<'static, str>`] /
1204/// [`From<Self> for Box<str>`] / [`From<&Self> for Box<str>`] decet
1205/// but not the [`std::sync::Arc<str>`] axis forces every
1206/// `std::sync::Arc<str>`-parameterized call site through a
1207/// `std::sync::Arc::<str>::from(strategy.as_str())` open-code (or a
1208/// `std::sync::Arc::<str>::from(String::from(strategy))` two-step
1209/// composition through the owned-`String` axis that allocates
1210/// twice — once into the intermediate `String`, once into the
1211/// [`Arc<str>`] on the `From<String>` conversion) whose type bounds
1212/// have no compile-time link back to the substrate primitive. Opening
1213/// the axis on the first M2 OTP-shape closed-set fieldless typed enum
1214/// peer on the caixa substrate surface establishes the "route through
1215/// `as_str` via [`std::sync::Arc::<str>::from`] on the returned
1216/// `&'static str`" discipline; every future closed-set fieldless
1217/// typed enum peer on the substrate ([`RestartPolicy`],
1218/// [`crate::aplicacao::PlacementStrategy`],
1219/// [`crate::aplicacao::RateLimitUnit`], [`crate::aplicacao::WitShape`],
1220/// [`crate::dep::DepList`], [`crate::dialeto::CaixaDialeto`],
1221/// [`crate::kind::CaixaKind`],
1222/// [`crate::render::PathShapeViolation`], and the outside-`caixa-core`
1223/// peers `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`,
1224/// `Semantic`, `FerriteRuntime`) is a future target of the campaign,
1225/// tracking the same 14-peer emit-set every prior projection tier
1226/// ([`&'static str`], [`String`], [`Cow<'static, str>`], [`Box<str>`])
1227/// converged onto.
1228///
1229/// Peer of the sibling [`Box<str>`] forward-projection first-mover
1230/// (69ef45c) — same "opens a new substrate-wide projection tier"
1231/// discipline, extended onto the [`std::sync::Arc<str>`] axis whose
1232/// shared-ownership + [`Sync`] + [`Send`] contract is the distinct
1233/// value the [`Box<str>`] axis's owned-move return-shape cannot
1234/// provide.
1235///
1236/// Pinned load-bearing by
1237/// [`tests::restart_strategy_from_into_arc_str_routes_through_as_str_accessor`]
1238/// (byte-parity pin against [`RestartStrategy::as_str`] across the
1239/// four-arm [`RestartStrategy::ALL`] emit-set on the owned-input
1240/// surface, plus a blanket-derived [`Into`] shape witness and cross-
1241/// axis byte-parity pins against the sibling owned-input
1242/// `{&'static str, String, Cow<'static, str>, Box<str>}` return-shape
1243/// axes).
1244impl From<RestartStrategy> for std::sync::Arc<str> {
1245    fn from(strategy: RestartStrategy) -> std::sync::Arc<str> {
1246        std::sync::Arc::<str>::from(strategy.as_str())
1247    }
1248}
1249
1250/// Trait-idiomatic *borrowed-input, [`std::sync::Arc<str>`] output*
1251/// forward projection on the M2 OTP-shape sibling-restart
1252/// [`RestartStrategy`] closed-set fieldless typed enum — closes the
1253/// `{Self, &Self}` input-shape corner of the [`std::sync::Arc<str>`]
1254/// forward-projection axis on the first M2 OTP-shape closed-set
1255/// fieldless typed enum peer on the caixa surface
1256/// (`:supervisor :estrategia`), companion to the paired owned-input
1257/// [`From<RestartStrategy> for std::sync::Arc<str>`] impl one commit
1258/// prior (bca2ec8). Routes byte-for-byte through the
1259/// substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
1260/// accessor (via [`std::sync::Arc::<str>::from`] on the returned
1261/// `&'static str`), so every consumer that binds a
1262/// [`&RestartStrategy`] through the standard-library `.into()` /
1263/// [`From<&Self> for std::sync::Arc<str>`] (equivalently
1264/// [`Into<std::sync::Arc<str>>`]) axis — a future admission-webhook's
1265/// per-request borrowed-`&RestartStrategy` handle rendering a per-arm
1266/// `Sync` + `Send`-safe structured-log field across an `.await`
1267/// boundary through a `<T: Into<std::sync::Arc<str>>>`-bound
1268/// diagnostic-column dispatch, a future wasm-operator's per-
1269/// supervisor reconciliation pipeline whose
1270/// `.iter().map(std::sync::Arc::<str>::from)` collector reaches into
1271/// the shared-ownership per-strategy key without a spurious [`Copy`]
1272/// deref (which would only be reachable through the owned-input
1273/// [`From<RestartStrategy> for std::sync::Arc<str>`] axis by first
1274/// calling `.copied()` on the iterator), a future
1275/// `<T: Into<std::sync::Arc<str>>>`-bound `tracing`-span attributes
1276/// collector recording a borrowed-`&RestartStrategy` per-arm field
1277/// onto the parent span's shared-ownership context — reaches the
1278/// same four-arm lifted
1279/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
1280/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
1281/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
1282/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const
1283/// the paired owned-input
1284/// [`From<RestartStrategy> for std::sync::Arc<str>`] impl and the
1285/// sibling `{&'static str, String, Cow<'static, str>, Box<str>}`
1286/// forward-projection corner already return.
1287///
1288/// Second peer on the substrate-wide trait-idiomatic
1289/// [`std::sync::Arc<str>`] forward-projection family opened one
1290/// commit prior (bca2ec8) on the paired owned-input
1291/// [`From<RestartStrategy> for std::sync::Arc<str>`] impl — closes
1292/// the `{Self, &Self}` input-shape corner of the
1293/// [`std::sync::Arc<str>`] axis on the first M2 OTP-shape closed-set
1294/// fieldless typed enum peer on the caixa surface, exactly as
1295/// 59ae5dc closed the paired [`Box<str>`] axis one commit after its
1296/// owning half (69ef45c) landed. Rust's standard library carries
1297/// `impl From<&str> for std::sync::Arc<str>` and
1298/// `impl From<String> for std::sync::Arc<str>` but no blanket
1299/// `impl<T: AsRef<str>> From<&T> for std::sync::Arc<str>` (nor a
1300/// `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`), so
1301/// every closed-set fieldless typed enum peer on the substrate that
1302/// carries the paired owned-input [`std::sync::Arc<str>`] axis but
1303/// not the borrowed-input axis forces every borrowed-input
1304/// [`std::sync::Arc<str>`]-parameterized call site through a
1305/// spurious [`Copy`] deref
1306/// (`std::sync::Arc::<str>::from((*strategy).as_str())`) or a
1307/// `std::sync::Arc::<str>::from(strategy.as_str())` open-code whose
1308/// type bounds have no compile-time link back to the substrate
1309/// primitive.
1310///
1311/// Pinned load-bearing by
1312/// [`tests::restart_strategy_from_borrowed_into_arc_str_routes_through_as_str_accessor`]
1313/// (byte-parity pin against [`RestartStrategy::as_str`] across the
1314/// four-arm [`RestartStrategy::ALL`] emit-set on the borrowed-input
1315/// surface, plus a blanket-derived [`Into`] shape witness and a
1316/// cross-axis pin against the paired owned-input
1317/// [`From<RestartStrategy> for std::sync::Arc<str>`] and the sibling
1318/// borrowed-input `{&'static str, String, Cow<'static, str>,
1319/// Box<str>}` return-shape axes).
1320impl From<&RestartStrategy> for std::sync::Arc<str> {
1321    fn from(strategy: &RestartStrategy) -> std::sync::Arc<str> {
1322        std::sync::Arc::<str>::from(strategy.as_str())
1323    }
1324}
1325
1326/// Trait-idiomatic *owned-input, [`std::rc::Rc<str>`] output* forward
1327/// projection on the M2 OTP-shape sibling-restart [`RestartStrategy`]
1328/// closed-set fieldless typed enum — the single-threaded reference-
1329/// counted peer of the paired owned-input
1330/// [`From<RestartStrategy> for std::sync::Arc<str>`] impl (bca2ec8) on
1331/// the sibling atomically-reference-counted [`std::sync::Arc<str>`] axis.
1332/// Routes byte-for-byte through the substrate-primitive
1333/// [`RestartStrategy::as_str`] `pub const fn` accessor via
1334/// [`std::rc::Rc::<str>::from`] on the returned `&'static str`.
1335///
1336/// Rust's standard library carries `impl From<&str> for std::rc::Rc<str>`
1337/// and `impl From<String> for std::rc::Rc<str>` but no blanket
1338/// `impl<T: AsRef<str>> From<T> for std::rc::Rc<str>` (nor a `From<&T>`
1339/// blanket), and the [`std::sync::Arc<str>`] and [`std::rc::Rc<str>`]
1340/// trait tables are disjoint — so a single-threaded caixa-operator
1341/// reconciliation pass that shares the `:supervisor :estrategia` wire
1342/// byte-string across intra-reconcile-loop tree nodes through the cheaper
1343/// non-atomic [`std::rc::Rc<str>`] refcount (the atomically-reference-
1344/// counted [`std::sync::Arc<str>`] return-shape cannot provide within a
1345/// single-threaded reconciliation pass without paying the atomic-fence
1346/// cost the [`std::rc::Rc<str>`] axis skips by construction) reaches
1347/// the substrate primitive through this impl and no other.
1348///
1349/// Extends the trait-idiomatic [`std::rc::Rc<str>`] forward-projection
1350/// axis onto the first M2 OTP-shape closed-set fieldless typed enum peer
1351/// on the caixa surface (`:supervisor :estrategia`), matching the
1352/// trajectory the M3-mesh-primitive-defining
1353/// [`crate::aplicacao::PlacementStrategy`],
1354/// [`crate::aplicacao::RateLimitUnit`], and
1355/// [`crate::aplicacao::WitShape`] (1afb5f4) peers established, and the
1356/// eighth in-caixa-core closed-set fieldless typed-enum peer to pick up
1357/// the axis (after [`crate::CaixaKind`],
1358/// [`crate::dialeto::CaixaDialeto`], [`crate::dep::DepList`],
1359/// [`crate::version::CaixaVersion`], [`crate::render::PathShapeViolation`],
1360/// and the three M3-mesh-primitive-defining peers above).
1361///
1362/// Pinned load-bearing by
1363/// [`tests::restart_strategy_from_into_rc_str_routes_through_as_str_accessor`]
1364/// (byte-parity pin against [`RestartStrategy::as_str`] across the
1365/// four-arm [`RestartStrategy::ALL`] emit-set on the owned-input
1366/// surface, plus a blanket-derived [`Into`] shape witness and cross-
1367/// axis byte-parity pins against the sibling owned-input `{&'static
1368/// str, String, Cow<'static, str>, Box<str>, std::sync::Arc<str>}`
1369/// return-shape axes).
1370impl From<RestartStrategy> for std::rc::Rc<str> {
1371    fn from(strategy: RestartStrategy) -> std::rc::Rc<str> {
1372        std::rc::Rc::<str>::from(strategy.as_str())
1373    }
1374}
1375
1376/// Trait-idiomatic *borrowed-input, [`std::rc::Rc<str>`] output* forward
1377/// projection on the M2 OTP-shape sibling-restart [`RestartStrategy`]
1378/// closed-set fieldless typed enum — the borrowed-input companion to the
1379/// paired owned-input [`From<RestartStrategy> for std::rc::Rc<str>`]
1380/// impl immediately above, closing the `{Self, &Self}` input-shape
1381/// corner of the [`std::rc::Rc<str>`] axis on the first M2 OTP-shape
1382/// closed-set fieldless typed enum peer on the caixa surface. Routes
1383/// byte-for-byte through the substrate-primitive
1384/// [`RestartStrategy::as_str`] `pub const fn` accessor via
1385/// [`std::rc::Rc::<str>::from`] on the returned `&'static str`, so a
1386/// `RestartStrategy::ALL.iter().map(std::rc::Rc::<str>::from)`-shaped
1387/// pipe (whose iterator over `&'static [RestartStrategy]` yields
1388/// `&RestartStrategy` by construction) reaches the same four-arm lifted
1389/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
1390/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
1391/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
1392/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const
1393/// roster the paired owned-input axis and the sibling `{Self, &Self} ×
1394/// {&'static str, String, Cow<'static, str>, Box<str>,
1395/// std::sync::Arc<str>}` forward-projection corner already return.
1396///
1397/// Rust's standard library carries no blanket
1398/// `impl<T: AsRef<str>> From<&T> for std::rc::Rc<str>` (nor a `Copy`-
1399/// based `impl<T: Copy, U: From<T>> From<&T> for U`), so this borrowed-
1400/// input axis is a distinct trait-idiomatic surface — without it, the
1401/// `.iter().map(std::rc::Rc::<str>::from)` pipe would force a spurious
1402/// [`Copy`] deref or a `.copied()` restatement whose type bounds have
1403/// no compile-time link back to the substrate primitive.
1404///
1405/// Pinned load-bearing by
1406/// [`tests::restart_strategy_from_borrowed_into_rc_str_routes_through_as_str_accessor`]
1407/// (byte-parity pin against [`RestartStrategy::as_str`] across the
1408/// four-arm [`RestartStrategy::ALL`] emit-set on the borrowed-input
1409/// surface, plus a blanket-derived [`Into`] shape witness, a cross-axis
1410/// partition pin against the paired owned-input
1411/// [`From<RestartStrategy> for std::rc::Rc<str>`] and the sibling
1412/// borrowed-input `{&'static str, String, Cow<'static, str>, Box<str>,
1413/// std::sync::Arc<str>}` return-shape axes, and a
1414/// `.iter().map(std::rc::Rc::<str>::from)` pipe witness over
1415/// [`RestartStrategy::ALL`] that resolves through the borrowed-input
1416/// axis without a spurious [`Copy`] deref).
1417impl From<&RestartStrategy> for std::rc::Rc<str> {
1418    fn from(strategy: &RestartStrategy) -> std::rc::Rc<str> {
1419        std::rc::Rc::<str>::from(strategy.as_str())
1420    }
1421}
1422
1423/// Substrate-canonical [`AsRef<[u8]>`] byte-view projection on the M2
1424/// OTP-shape sibling-restart [`RestartStrategy`] closed-set fieldless
1425/// typed enum — routes byte-for-byte through the substrate-primitive
1426/// [`RestartStrategy::as_str`] `pub const fn` accessor via
1427/// [`str::as_bytes`] on the returned `&'static str`, so any future
1428/// consumer that binds a [`RestartStrategy`] through a standard-library
1429/// `<T: AsRef<[u8]>>` trait bound reaches the same four-arm lifted
1430/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
1431/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
1432/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
1433/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
1434/// `PascalCase` wire byte-string emit-set the paired sibling
1435/// [`AsRef<str>`] (5b828ed) / [`std::fmt::Display`] /
1436/// [`RestartStrategy::as_str`] str-view surfaces and every
1437/// `{Self, &Self} × {&'static str, String, Cow<'static, str>, Box<str>,
1438/// std::sync::Arc<str>}` reverse-projection corner already return —
1439/// through the byte-view axis, which the str-view axes cannot express.
1440///
1441/// Rust's standard library carries `impl AsRef<[u8]> for str` and
1442/// `impl AsRef<[u8]> for String`, so the two-hop composition
1443/// `strategy.as_str().as_bytes()` (or, equivalently,
1444/// `AsRef::<str>::as_ref(&strategy).as_bytes()`) is reachable through
1445/// the pre-existing str-view axis alone. But that two-hop shape has no
1446/// compile-time link back to the byte-projection axis, forces every
1447/// downstream `<T: AsRef<[u8]>>`-bound consumer to open-code the
1448/// two-hop composition at every call site, and admits a silent split
1449/// whenever a future call site takes a sibling reverse-projection axis
1450/// whose `.as_bytes()` byte-tail carries no compile-time byte-view
1451/// surface (`Display` returns a formatter, `String` / `Box<str>` /
1452/// `Arc<str>` allocate). The lifted single-hop impl closes the
1453/// byte-view axis so every future `<T: AsRef<[u8]>>`-bound consumer
1454/// reaches the substrate primitive through one trait dispatch, and
1455/// every future arm addition (an OTP-`rest_for_all` fifth arm the
1456/// theory
1457/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1458/// might reach for once the four canonical OTP strategies stop covering
1459/// the substrate's discovered load-shape) grows the byte-view axis
1460/// through one edit on the substrate-primitive `as_str` accessor, not a
1461/// coordinated rewrite across every future `<T: AsRef<[u8]>>`-bound
1462/// consumer's arm-set.
1463///
1464/// The primary compounding target is the same `caixa-lacre` BLAKE3
1465/// content-address closure the peer [`crate::CaixaKind`] (69d8d86),
1466/// [`crate::dialeto::CaixaDialeto`] (8151347),
1467/// [`crate::dep::DepList`] (05ffaca),
1468/// [`crate::aplicacao::PlacementStrategy`] (daa8705), and
1469/// [`crate::aplicacao::RateLimitUnit`] (4867e0f) `AsRef<[u8]>` impls
1470/// open onto: [`blake3::hash`] and [`blake3::Hasher::update`] both bind
1471/// their input through `impl AsRef<[u8]>`, so any future per-supervisor
1472/// content-address tag that folds an `:estrategia` discriminator
1473/// byte-tag into the [`crate::Lacre`] closure (a hypothetical
1474/// `hasher.update(estrategia);`-shape composition partitioning the
1475/// four OTP restart-topology closures at content-address time so
1476/// downstream `Lacre` consumers key per-strategy reconciliation caches
1477/// off the typed discriminator rather than the sibling `&'static str`
1478/// wire scalar) reaches the substrate-primitive `as_str` accessor
1479/// through this impl and no other.
1480///
1481/// Opens the trait-idiomatic byte-view axis on the first M2 OTP-shape
1482/// closed-set fieldless typed enum peer on the caixa surface
1483/// (`:supervisor :estrategia`), extending the substrate-wide byte-view
1484/// campaign the sibling [`crate::CaixaKind`] first-mover (69d8d86)
1485/// opened onto the fifth in-caixa-core enum peer. The remaining
1486/// in-caixa-core closed-set fieldless typed-enum peers
1487/// ([`RestartPolicy`], [`crate::aplicacao::WitShape`],
1488/// [`crate::upgrade::UpgradeInstruction`],
1489/// [`crate::render::PathShapeViolation`]) each carry the same
1490/// [`AsRef<str>`] + `pub const fn as_str` substrate-primitive accessor
1491/// discipline, so a future extension of the byte-view axis onto each
1492/// peer reaches through one impl per enum keyed to that peer's
1493/// substrate-primitive accessor.
1494///
1495/// Pinned load-bearing by
1496/// [`tests::restart_strategy_as_ref_bytes_routes_through_as_str_accessor`]
1497/// (fail-before-pass-after byte-parity pin against
1498/// [`RestartStrategy::as_str`] `.as_bytes()` across the four-arm
1499/// [`RestartStrategy::ALL`] emit-set, cross-axis witness against the
1500/// paired str-view [`AsRef<str>`] / [`std::fmt::Display`] /
1501/// [`RestartStrategy::as_str`] axes' `.as_bytes()` byte-tails,
1502/// cross-axis witness against the paired reverse-projection
1503/// `{&'static str, String, Cow<'static, str>, Box<str>,
1504/// std::sync::Arc<str>}` return-shape axes' `.as_bytes()` byte-tails,
1505/// a `<T: AsRef<[u8]>>`-bound-consumer witness that a generic
1506/// byte-input function accepts a [`RestartStrategy`] directly through
1507/// the trait bound, and a `blake3::Hasher::update`-shape byte-input
1508/// surface witness routed through the `<T: AsRef<[u8]>>`-bound
1509/// consumer axis to reach the caixa-lacre compounding target). Any
1510/// future silent detour that routes the byte-view impl off the
1511/// substrate-primitive [`RestartStrategy::as_str`] accessor (a per-arm
1512/// inline `b"OneForOne".as_slice()`-shaped re-inlining that opens a
1513/// compile-time link to the un-lifted arm-literal, a swap onto the
1514/// kebab-case [`gen_platform::Discriminant`] catalog identity that
1515/// would collide the wire axis with the dispatcher-catalog axis) trips
1516/// at caixa-core test time rather than at a downstream byte-consumer's
1517/// silent split.
1518impl AsRef<[u8]> for RestartStrategy {
1519    fn as_ref(&self) -> &[u8] {
1520        self.as_str().as_bytes()
1521    }
1522}
1523
1524/// Trait-idiomatic *owned-input, owned-`Vec<u8>` output* byte-owned
1525/// reverse projection on the first M2 OTP-shape closed-set fieldless
1526/// typed enum peer on the caixa surface ([`RestartStrategy`]) — the
1527/// byte-mirror of the [`From<RestartStrategy> for String`] str-owned
1528/// reverse-projection axis and the owned-`Vec<u8>` reverse-projection
1529/// sibling of the paired [`AsRef<[u8]>`] borrowed byte-view axis
1530/// (cd4c4e0) lifted on this same enum. Routes byte-for-byte through
1531/// the substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
1532/// accessor via [`str::as_bytes`] + [`slice::to_vec`] so every
1533/// consumer that binds a [`RestartStrategy`] through the standard-
1534/// library `impl From<RestartStrategy> for Vec<u8>` axis
1535/// (equivalently `<T: Into<Vec<u8>>>`) — a future
1536/// [`std::io::Write::write_all`]-shape per-supervisor audit-log byte-
1537/// sink whose input parameter is an owned [`Vec<u8>`] payload, a
1538/// future `bytes::Bytes::from(Vec::<u8>::from(strategy))` composer
1539/// folding the per-arm sibling-restart-topology byte-tag into the
1540/// [`bytes::Bytes`] framing surface, a future
1541/// `hasher.update(&Vec::<u8>::from(strategy))`-shape BLAKE3 content-
1542/// address closure that needs the owned byte-tail buffered before
1543/// folding into the [`crate::Lacre`] closure body, a future per-
1544/// strategy protobuf/CBOR/msgpack payload composer whose framer takes
1545/// an owned [`Vec<u8>`] rather than a borrowed byte-slice — reaches
1546/// the substrate primitive through one trait dispatch rather than an
1547/// open-coded per-call-site `strategy.as_str().as_bytes().to_vec()`
1548/// composition whose type bounds have no compile-time link back to
1549/// the substrate primitive.
1550///
1551/// Extends the substrate-wide trait-idiomatic byte-owned reverse-
1552/// projection axis onto the first M2-OTP-shape closed-set fieldless
1553/// typed-enum peer, matching the trajectory the first-mover
1554/// [`crate::CaixaKind`] `From<{Self, &Self}> for Vec<u8>` lift
1555/// (b245fd6), the second-mover [`crate::dialeto::CaixaDialeto`] lift
1556/// (4cceaf5), and the third-mover [`crate::dep::DepList`] lift
1557/// (e974ca2) established across the caixa-core-internal tier. Every
1558/// future arm addition (an OTP-`rest_for_all` fifth arm the theory
1559/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1560/// might reach for once the four canonical OTP strategies stop
1561/// covering the substrate's discovered load-shape) grows the byte-
1562/// owned axis through one edit on the substrate-primitive
1563/// [`RestartStrategy::as_str`] accessor, mirroring the discipline the
1564/// paired [`AsRef<[u8]>`] borrowed byte-view axis campaign already
1565/// tracked across every closed-set fieldless typed enum peer on the
1566/// substrate.
1567///
1568/// Pinned load-bearing by
1569/// [`tests::restart_strategy_from_into_owned_vec_bytes_routes_through_as_str_accessor`]
1570/// (byte-parity pin against [`RestartStrategy::as_str`] across the
1571/// four-arm [`RestartStrategy::ALL`] emit-set binding the byte-owned
1572/// reverse-projection axis against the paired [`AsRef<[u8]>`]
1573/// borrowed byte-view axis and the str-owned reverse-projection
1574/// family (`String`, `Cow<'static, str>`, `Box<str>`,
1575/// `std::sync::Arc<str>`) `.into_bytes()` / `.as_bytes().to_vec()`
1576/// byte-tails, a `<T: Into<Vec<u8>>>`-bound generic-consumer witness,
1577/// and a `std::io::Write::write_all`-shape owned-byte-sink surface
1578/// witness on both owned and borrowed input shapes).
1579impl From<RestartStrategy> for Vec<u8> {
1580    fn from(strategy: RestartStrategy) -> Vec<u8> {
1581        strategy.as_str().as_bytes().to_vec()
1582    }
1583}
1584
1585/// Trait-idiomatic *borrowed-input, owned-`Vec<u8>` output* byte-
1586/// owned reverse projection on the first M2 OTP-shape closed-set
1587/// fieldless typed enum peer on the caixa surface
1588/// ([`RestartStrategy`]) — the borrowed-input peer of
1589/// [`From<RestartStrategy> for Vec<u8>`], closing the
1590/// `{Self, &Self} → Vec<u8>` pair on the byte-owned reverse-projection
1591/// axis in one lift. Routes byte-for-byte through the substrate-
1592/// primitive [`RestartStrategy::as_str`] `pub const fn` accessor so
1593/// every consumer that holds a borrowed [`&RestartStrategy`] and
1594/// needs an owned [`Vec<u8>`] — a future
1595/// `.iter().map(Vec::<u8>::from).collect()` pipe over
1596/// `&[RestartStrategy]` (whose iterator yields `&RestartStrategy`,
1597/// not `RestartStrategy`, so the owned-input axis alone forces every
1598/// call site through an explicit `.copied()` / spurious [`Copy`]
1599/// deref restatement rather than the direct trait-idiomatic
1600/// projection), a future admission-webhook rejection body composer
1601/// that walks [`RestartStrategy::ALL`] through an `Into<Vec<u8>>`-
1602/// bound per-arm byte-writer to surface the accepted `:estrategia`
1603/// set — reaches the substrate primitive through one trait dispatch
1604/// rather than a `Vec::<u8>::from(*strategy)` spurious-`Copy`-deref
1605/// restatement.
1606impl From<&RestartStrategy> for Vec<u8> {
1607    fn from(strategy: &RestartStrategy) -> Vec<u8> {
1608        strategy.as_str().as_bytes().to_vec()
1609    }
1610}
1611
1612/// Trait-idiomatic *owned-input, [`std::borrow::Cow<'static, [u8]>`]
1613/// output* byte-owned reverse projection on the first M2 OTP-shape
1614/// closed-set fieldless typed enum peer on the caixa surface
1615/// ([`RestartStrategy`]) — the [`std::borrow::Cow<'static, [u8]>`] byte-
1616/// mirror of the paired [`From<RestartStrategy> for
1617/// std::borrow::Cow<'static, str>`] str-side impl (7dd28b3) and the
1618/// [`std::borrow::Cow<'static, [u8]>`] companion of the paired byte-
1619/// owned [`From<RestartStrategy> for Vec<u8>`] reverse-projection axis
1620/// immediately above. Routes byte-for-byte through the substrate-
1621/// primitive [`RestartStrategy::as_str`] `pub const fn` accessor via
1622/// [`std::borrow::Cow::Borrowed`]`(strategy.as_str().as_bytes())` — the
1623/// four `match` arms in [`Self::as_str`] resolve to
1624/// [`crate::render::SUPERVISOR_ESTRATEGIA_*`] `pub const &'static str`
1625/// bodies, so `.as_bytes()` on each returns `&'static [u8]` by
1626/// construction, and the zero-alloc [`Cow::Borrowed`] arm is the
1627/// type-correct projection with no runtime allocation (mirroring the
1628/// paired [`Cow<'static, str>`] axis's own [`Cow::Borrowed`]
1629/// discipline on this same primitive; contrasts with the sibling
1630/// [`crate::CaixaVersion`] [`Cow<'static, [u8]>`] impl (baf7537), whose
1631/// wrapped [`String`] storage is a runtime heap allocation with no
1632/// `&'static [u8]` lifetime, forcing the [`Cow::Owned`] arm there).
1633///
1634/// Extends the substrate-wide trait-idiomatic byte-owned reverse-
1635/// projection matrix onto the first M2-OTP-shape closed-set fieldless
1636/// typed-enum peer at the second byte-owned axis, following the
1637/// trajectory the same axis walked on [`crate::CaixaVersion`]
1638/// (98d38ed on the `Vec<u8>` axis, baf7537 on the `Cow<'static, [u8]>`
1639/// axis).
1640impl From<RestartStrategy> for std::borrow::Cow<'static, [u8]> {
1641    fn from(strategy: RestartStrategy) -> std::borrow::Cow<'static, [u8]> {
1642        std::borrow::Cow::Borrowed(strategy.as_str().as_bytes())
1643    }
1644}
1645
1646/// Trait-idiomatic *borrowed-input, [`std::borrow::Cow<'static, [u8]>`]
1647/// output* byte-owned reverse projection on the first M2 OTP-shape
1648/// closed-set fieldless typed enum peer on the caixa surface
1649/// ([`RestartStrategy`]) — the borrowed-input companion to the paired
1650/// owned-input [`From<RestartStrategy> for
1651/// std::borrow::Cow<'static, [u8]>`] impl immediately above, closing
1652/// the `{Self, &Self} → Cow<'static, [u8]>` byte-owned reverse-
1653/// projection family on this primitive at the borrowed-input corner.
1654/// Routes byte-for-byte through the same substrate-primitive
1655/// [`RestartStrategy::as_str`] `pub const fn` accessor via
1656/// [`std::borrow::Cow::Borrowed`]`(strategy.as_str().as_bytes())` —
1657/// the [`Cow::Borrowed`] arm is reachable on both input axes because
1658/// [`Self::as_str`] returns `&'static str` regardless of the input
1659/// shape, so no runtime allocation is forced on either corner.
1660/// Rust's `From` trait carries no blanket `impl<T> From<&T> for U
1661/// where U: From<T>` (nor an
1662/// `impl<T: AsRef<[u8]>> From<&T> for Cow<'static, [u8]>`), so every
1663/// closed-set fieldless typed enum peer that carries the paired
1664/// owned-input axis but not the borrowed-input axis forces every
1665/// borrowed call site through a spurious [`Copy`] deref
1666/// (`Cow::<'static, [u8]>::from(*strategy)`) or an open-coded
1667/// `Cow::Borrowed(strategy.as_str().as_bytes())` whose type bounds
1668/// have no compile-time link to the substrate primitive.
1669impl From<&RestartStrategy> for std::borrow::Cow<'static, [u8]> {
1670    fn from(strategy: &RestartStrategy) -> std::borrow::Cow<'static, [u8]> {
1671        std::borrow::Cow::Borrowed(strategy.as_str().as_bytes())
1672    }
1673}
1674
1675/// Trait-idiomatic *owned-input, [`Box<[u8]>`] output* byte-owned reverse
1676/// projection on the first M2-OTP-shape closed-set fieldless typed enum peer
1677/// on the caixa surface ([`RestartStrategy`]) — the [`Box<[u8]>`] companion
1678/// to the paired owned-input [`From<RestartStrategy> for Vec<u8>`] (98d38ed)
1679/// and [`From<RestartStrategy> for std::borrow::Cow<'static, [u8]>`]
1680/// (7f81539) reverse-projection impls on this same primitive, mirroring the
1681/// paired string-side [`From<RestartStrategy> for Box<str>`] (69ef45c)
1682/// forward-projection axis onto the byte-family side of the reverse-
1683/// projection matrix, and tracking the trajectory the same axis walked on
1684/// the sibling [`crate::CaixaVersion`] String-wrapper newtype primitive
1685/// (703b2fd on the [`Box<[u8]>`] corner). Routes byte-for-byte through the
1686/// substrate-primitive [`RestartStrategy::as_str`] `pub const fn` accessor
1687/// via [`Box::<[u8]>::from`] on the returned `&'static str`'s
1688/// [`str::as_bytes`] — the four `match` arms in [`Self::as_str`] resolve to
1689/// [`crate::render::SUPERVISOR_ESTRATEGIA_*`] `pub const &'static str`
1690/// bodies, so `.as_bytes()` returns `&'static [u8]` by construction, and
1691/// the standard-library [`Box::<[u8]>::from(&[u8])`] impl allocates a fit-
1692/// to-length boxed byte slice in one heap allocation without an
1693/// intermediary [`Vec<u8>`].
1694///
1695/// A future consumer that wants a [`Box<[u8]>`]-typed handle on a
1696/// [`RestartStrategy`] — a per-supervisor struct field typed [`Box<[u8]>`]
1697/// rather than [`Vec<u8>`] to trim the twenty-four-byte pointer + length +
1698/// capacity header down to the sixteen-byte pointer + length pair (a shape
1699/// the substrate acknowledges as the natural fixed-length storage for
1700/// once-written-never-mutated wire-scalar byte-tails held across the whole
1701/// operator reconciliation cycle), a future
1702/// `HashMap::<Box<[u8]>, _>::from_iter([(estrategia.into(), _)])`
1703/// per-strategy lookup where the map's key type is [`Box<[u8]>`] rather than
1704/// owned [`Vec<u8>`] so the map's per-entry key-slot carries the sixteen-
1705/// byte [`Box<[u8]>`] header instead of the twenty-four-byte [`Vec<u8>`]
1706/// header, a future M4 admission-webhook rejection body whose per-arm
1707/// error-frame composer accepts a [`Box<[u8]>`] intermediate for the same
1708/// reason — reaches the wire byte-string through this one dispatch, without
1709/// the pre-lift `Vec::<u8>::from(strategy).into_boxed_slice()` double-hop
1710/// that would still allocate through the same [`Vec<u8>`] intermediary on
1711/// the way to the same [`Box<[u8]>`] slot but with one extra header-slot
1712/// round-trip.
1713///
1714/// Peer of the paired owned-input [`From<RestartStrategy> for Vec<u8>`]
1715/// (98d38ed) and [`From<RestartStrategy> for std::borrow::Cow<'static,
1716/// [u8]>`] (7f81539) impls on the same primitive — the sibling
1717/// [`Vec<u8>`] axis returns a fresh heap allocation via
1718/// [`str::as_bytes`]`.to_vec()`; the sibling [`Cow<'static, [u8]>`] axis
1719/// binds the zero-alloc [`Cow::Borrowed`] arm on the same `&'static [u8]`
1720/// byte-tail; this axis allocates a fit-to-length boxed byte slice via
1721/// [`Box::<[u8]>::from(&[u8])`], preserving the fixed-length-storage
1722/// discipline the substrate opens on its byte-family reverse-projection
1723/// matrix across every closed-set fieldless typed enum peer.
1724///
1725/// Extends the substrate-wide trait-idiomatic *owned-input* byte-family
1726/// reverse-projection matrix onto the first M2-OTP-shape closed-set
1727/// fieldless typed enum peer at the [`Box<[u8]>`] corner — mirroring the
1728/// trajectory the same axis walked on the sibling [`crate::CaixaVersion`]
1729/// String-wrapper newtype primitive (98d38ed on [`Vec<u8>`], baf7537 on
1730/// [`Cow<'static, [u8]>`], 703b2fd on [`Box<[u8]>`], 3d5fc43 on
1731/// [`std::sync::Arc<[u8]>`], 6034943 on [`std::rc::Rc<[u8]>`]) and the
1732/// paired string-family [`Box<str>`] axis (69ef45c on the string-side).
1733/// Rust's standard library does not derive `From<Self> for Box<[u8]>` from
1734/// `From<Self> for Vec<u8>` (nor from `From<Self> for Cow<'static, [u8]>`),
1735/// so every closed-set fieldless typed enum peer that carries the paired
1736/// reverse [`Vec<u8>`] axis but not the paired [`Box<[u8]>`] axis forces
1737/// every [`Box<[u8]>`]-typed call site through a
1738/// `Vec::<u8>::from(strategy).into_boxed_slice()` intermediary allocation
1739/// whose bounds carry no compile-time link back to the substrate primitive.
1740///
1741/// Pinned load-bearing by
1742/// [`tests::restart_strategy_from_into_owned_box_bytes_routes_through_as_str_accessor`]
1743/// (byte-parity pin against [`RestartStrategy::as_str`] `.as_bytes()`
1744/// across the four-arm [`RestartStrategy::ALL`] accept-set on the owned-
1745/// input surface, plus a cross-axis witness against the paired owned-input
1746/// [`From<RestartStrategy> for Vec<u8>`] and
1747/// [`From<RestartStrategy> for Cow<'static, [u8]>`] byte-owned reverse-
1748/// projection axes and the paired string-side [`Box<str>`] axis on every
1749/// canonical `PascalCase` scalar, closing the "owned-input into `Vec<u8>`
1750/// vs. `Cow<'static, [u8]>` vs. `Box<[u8]>`" three-corner partition on the
1751/// same wire byte-string).
1752impl From<RestartStrategy> for Box<[u8]> {
1753    fn from(strategy: RestartStrategy) -> Box<[u8]> {
1754        Box::<[u8]>::from(strategy.as_str().as_bytes())
1755    }
1756}
1757
1758/// Trait-idiomatic *borrowed-input, [`Box<[u8]>`] output* byte-owned reverse
1759/// projection on the first M2-OTP-shape closed-set fieldless typed enum peer
1760/// on the caixa surface ([`RestartStrategy`]) — the borrowed-input companion
1761/// to the paired owned-input [`From<RestartStrategy> for Box<[u8]>`] impl
1762/// immediately above, closing the `{Self, &Self} → Box<[u8]>` byte-owned
1763/// reverse-projection family on this primitive at the borrowed-input corner.
1764/// Routes byte-for-byte through the same substrate-primitive
1765/// [`RestartStrategy::as_str`] `pub const fn` accessor via
1766/// [`Box::<[u8]>::from`] on the returned `&'static str`'s [`str::as_bytes`]
1767/// — the [`Box<[u8]>`] allocation happens on both input axes because
1768/// [`Self::as_str`] returns `&'static str` regardless of the input shape,
1769/// so the borrowed-input peer reaches the same wire byte-string through the
1770/// same one-heap-allocation path the owned-input peer already carries.
1771///
1772/// Rust's `From` trait carries no blanket `impl<T> From<&T> for U where
1773/// U: From<T>` (nor a `Copy`-based
1774/// `impl<T: Copy, U: From<T>> From<&T> for U`), so every closed-set
1775/// fieldless typed enum peer that carries the paired owned-input
1776/// [`Box<[u8]>`] axis but not the borrowed-input axis forces every borrowed
1777/// call site through a spurious [`Copy`] deref
1778/// (`Box::<[u8]>::from(*strategy)`) or an open-coded
1779/// `Box::<[u8]>::from(strategy.as_str().as_bytes())` whose type bounds have
1780/// no compile-time link to the substrate primitive.
1781///
1782/// Pinned load-bearing by
1783/// [`tests::restart_strategy_from_borrowed_into_owned_box_bytes_routes_through_as_str_accessor`]
1784/// (byte-parity pin against [`RestartStrategy::as_str`] `.as_bytes()` via a
1785/// borrowed input across the four-arm [`RestartStrategy::ALL`] accept-set,
1786/// plus a source-survival witness against silent move-out and a cross-
1787/// corner partition pin between owned-input and borrowed-input on the same
1788/// wire byte-string through the [`Box<[u8]>`] axis).
1789impl From<&RestartStrategy> for Box<[u8]> {
1790    fn from(strategy: &RestartStrategy) -> Box<[u8]> {
1791        Box::<[u8]>::from(strategy.as_str().as_bytes())
1792    }
1793}
1794
1795/// Trait-idiomatic *borrowed byte-slice input* reverse projection on the
1796/// first M2-OTP-shape closed-set fieldless typed enum peer on the caixa
1797/// surface ([`RestartStrategy`]) — the byte-view mirror of the str-view
1798/// reverse-projection axis carried by the paired
1799/// [`TryFrom<&str> for RestartStrategy`] impl (which routes through the
1800/// substrate-primitive [`RestartStrategy::from_wire`] `Option<Self>`
1801/// accessor on the four-arm `PascalCase` accept-set the sibling
1802/// [`RestartStrategy::as_str`] emitter returns). Routes byte-for-byte
1803/// through the standard-library [`std::str::from_utf8`] UTF-8 validator
1804/// and then through [`RestartStrategy::from_wire`] so every consumer that
1805/// holds a borrowed [`&[u8]`] and needs to project it back into a typed
1806/// [`RestartStrategy`] — a future `bytes::Bytes::as_ref()`-fed reader
1807/// that parses a per-supervisor `:estrategia` `PascalCase` wire scalar
1808/// from an already-borrowed framing byte-tail (a
1809/// `tracing::field::valuable::Value::Bytes` recorder on the future
1810/// wasm-operator's per-supervisor sibling-restart-strategy diagnostic
1811/// emission path, a future audit-report re-loader binding a prior
1812/// [`RestartStrategy::as_str`] output from a mmap'd byte-slice back
1813/// through the typed enum for cross-run comparison), a future M4
1814/// `mesh.pleme.io/v1alpha1/Supervisor` CR admission-webhook rejection
1815/// body that reads a `spec.estrategia` field off a raw HTTP body byte-
1816/// slice before UTF-8 validation commits allocation, a future generic
1817/// `<T: for<'a> TryFrom<&'a [u8]>>`-bound loader over any of the
1818/// substrate's closed-set typed enums — reaches the same four-arm
1819/// `PascalCase` wire accept-set the sibling method-named
1820/// [`RestartStrategy::from_wire`] resolver and the paired trait-idiomatic
1821/// [`TryFrom<&str>`] axis already resolve against, rather than an open-
1822/// coded per-call-site
1823/// `std::str::from_utf8(bytes).ok().and_then(RestartStrategy::from_wire)`
1824/// composition or a
1825/// `<RestartStrategy as TryFrom<&str>>::try_from(std::str::from_utf8(bytes)?)`
1826/// two-hop shape whose type bounds have no compile-time link to the
1827/// substrate primitive.
1828///
1829/// Extends the substrate-wide trait-idiomatic *byte-view reverse-
1830/// projection* family — opened on the structurally most fundamental
1831/// closed-set fieldless typed enum peer ([`crate::CaixaKind`], commit
1832/// 18d1940), extended onto the second caixa-core-internal peer
1833/// ([`crate::CaixaDialeto`], commit d102cb8) and the third
1834/// ([`crate::dep::DepList`], commit b8f25d5) — onto the first
1835/// M2-OTP-shape supervisor-slot closed-set fieldless typed enum peer,
1836/// tracking the "route through `from_wire` via `std::str::from_utf8`"
1837/// discipline the first-mover established. Rust's standard library
1838/// carries no blanket
1839/// `impl<T: for<'a> TryFrom<&'a str>> TryFrom<&[u8]> for T`, so a two-
1840/// hop composition through [`std::str::from_utf8`] + the paired
1841/// [`TryFrom<&str>`] axis is reachable at every call site but has no
1842/// compile-time link back to the byte-view reverse-projection axis.
1843/// Every remaining closed-set fieldless typed enum peer on the substrate
1844/// ([`RestartPolicy`], [`crate::aplicacao::PlacementStrategy`],
1845/// [`crate::aplicacao::RateLimitUnit`], [`crate::aplicacao::WitShape`],
1846/// and the outside-`caixa-core` peers `PathShapeViolation`,
1847/// `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`,
1848/// `FerriteRuntime`) is a future target of the campaign, mirroring the
1849/// trajectory the closed byte-owned reverse-projection family walked
1850/// arm-by-arm onto each peer.
1851///
1852/// `type Error = ()` matches the sibling [`RestartStrategy::from_wire`]'s
1853/// `Option<Self>` return-shape's deliberate deferral of error typing and
1854/// the paired trait-idiomatic [`TryFrom<&str>`] axis's unit-error shape —
1855/// the caller picks the diagnostic form appropriate for its use site (a
1856/// future `feira supervisor --estrategia …` arg-parse composes its own
1857/// per-verb "unknown strategy: <arg> — accepted: {…}" message enumerating
1858/// [`RestartStrategy::WIRE_NAMES`]; a future admission-webhook rejection
1859/// body wraps the `Err(())` outcome with the accepted-set enumeration for
1860/// operator diagnostics; a `Result::map_err` at the call site lifts the
1861/// unit-error to a per-verb error type). Two rejection paths route
1862/// through the single unit-error: an invalid UTF-8 byte-sequence
1863/// ([`std::str::from_utf8`] returns `Err`) and a valid UTF-8 byte-string
1864/// that falls outside the four-arm `PascalCase` accept-set
1865/// ([`RestartStrategy::from_wire`] returns `None`) — both collapse onto
1866/// `Err(())` so the trait signature stays consistent with the sibling
1867/// str-view reverse axis, and a caller that needs to distinguish the two
1868/// failure modes composes [`std::str::from_utf8`] +
1869/// [`RestartStrategy::from_wire`] explicitly.
1870///
1871/// Pinned load-bearing by
1872/// [`tests::restart_strategy_try_from_bytes_routes_through_from_wire_accessor`]
1873/// (byte-parity pin against [`RestartStrategy::from_wire`] across the
1874/// four-arm [`RestartStrategy::ALL`] accept-set on the borrowed byte-
1875/// slice surface, plus a cross-axis witness that the byte-view reverse
1876/// projection agrees with the paired [`TryFrom<&str>`] str-view reverse
1877/// axis on every accepted arm) and
1878/// [`tests::restart_strategy_try_from_bytes_rejects_unknown_and_non_utf8_bytes`]
1879/// (rejection witness against silent accept-set widening on both the
1880/// non-UTF-8 byte-sequence rejection path and the unknown-wire-vocabulary
1881/// rejection path — the latter includes the sibling kebab-case
1882/// dispatcher-catalog byte-strings on the two-axis wire/catalog split so
1883/// a caller that confuses the two axes trips here rather than at a
1884/// downstream K8s-CR round-trip miss).
1885impl TryFrom<&[u8]> for RestartStrategy {
1886    type Error = ();
1887
1888    fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
1889        std::str::from_utf8(bytes)
1890            .ok()
1891            .and_then(Self::from_wire)
1892            .ok_or(())
1893    }
1894}
1895
1896/// Trait-idiomatic *owned byte-vec input* reverse projection on the first
1897/// M2-OTP-shape supervisor-slot closed-set fieldless typed enum peer on the
1898/// caixa surface ([`RestartStrategy`]) — the owned-input peer of
1899/// [`TryFrom<&[u8]> for RestartStrategy`], mirroring the closed
1900/// [`From<RestartStrategy> for Vec<u8>`] + [`From<&RestartStrategy> for
1901/// Vec<u8>`] byte-owned *forward*-projection pair on this same enum onto
1902/// the byte-owned *reverse*-projection axis. Routes byte-for-byte through
1903/// [`<Self as TryFrom<&[u8]>>::try_from`] on the [`Vec<u8>::as_slice`]
1904/// borrow, so the owned-input surface reaches the same
1905/// [`std::str::from_utf8`] + [`RestartStrategy::from_wire`] resolution
1906/// chain the borrowed-input peer already carries — one substrate-primitive
1907/// accessor, one trait dispatch, no per-consumer detour.
1908///
1909/// Rust's standard library carries no blanket
1910/// `impl<T: for<'a> TryFrom<&'a [u8]>> TryFrom<Vec<u8>> for T`, so a
1911/// consumer that holds an owned [`Vec<u8>`] and needs a typed
1912/// [`RestartStrategy`] otherwise picks between (a) an open-coded
1913/// `<RestartStrategy as TryFrom<&[u8]>>::try_from(bytes.as_slice())` at
1914/// every call site (whose type bounds have no compile-time link to the
1915/// byte-owned reverse-projection axis), (b) a two-hop
1916/// `String::from_utf8(bytes)` + [`RestartStrategy::from_wire`] composition
1917/// whose error surface leaks the standard-library
1918/// [`std::string::FromUtf8Error`] (widening the sibling [`TryFrom<&[u8]>`]
1919/// axis's unit-error) and silently allocates a [`String`] on inputs that
1920/// will never make it past the wire vocabulary, or (c) an intermediate
1921/// `<RestartStrategy as TryFrom<&str>>::try_from(std::str::from_utf8(&bytes)?)`
1922/// three-hop shape. This impl closes the owned-byte-vec reverse-projection
1923/// axis at the substrate-primitive [`RestartStrategy::from_wire`] accessor
1924/// so every future `<T: TryFrom<Vec<u8>>>`-bound owned-byte-vec consumer —
1925/// a future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR admission-webhook
1926/// body reader that hands the `spec.estrategia` byte-tail off as a
1927/// [`Vec<u8>`] before UTF-8 validation commits allocation, a
1928/// `bytes::Bytes::to_vec()`-shape wire-body composer walking a prior
1929/// audit's per-supervisor rejection payload back to the typed enum, a
1930/// `std::io::Read::read_to_end`-shape audit-log source whose framing
1931/// yields an owned byte-vec per per-strategy scalar, an
1932/// `<T: TryFrom<Vec<u8>>>`-bound generic loader over any of the
1933/// substrate's closed-set typed enums — reaches the same four-arm
1934/// `PascalCase` wire accept-set through one trait dispatch.
1935///
1936/// Extends the substrate-wide trait-idiomatic *byte-owned reverse-
1937/// projection* family — opened on the structurally most fundamental
1938/// closed-set fieldless typed enum peer ([`crate::CaixaKind`], commit
1939/// 99c2849), extended onto the second caixa-core-internal peer
1940/// ([`crate::CaixaDialeto`], commit 83a1526) and the third
1941/// ([`crate::dep::DepList`], commit 42091cb) — onto the first M2-OTP-shape
1942/// supervisor-slot closed-set fieldless typed enum peer, tracking the
1943/// "delegate through `TryFrom<&[u8]>` on the `Vec<u8>::as_slice` borrow"
1944/// discipline the first-mover established. Every remaining closed-set
1945/// fieldless typed enum peer on the substrate ([`RestartPolicy`],
1946/// [`crate::aplicacao::PlacementStrategy`],
1947/// [`crate::aplicacao::RateLimitUnit`], [`crate::aplicacao::WitShape`],
1948/// [`crate::render::PathShapeViolation`], and the outside-`caixa-core`
1949/// peers `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`,
1950/// `Semantic`, `FerriteRuntime`) is a future target of the campaign,
1951/// mirroring the trajectory the closed byte-view reverse-projection
1952/// family (`TryFrom<&[u8]>`) and the closed byte-owned forward-projection
1953/// family (`From<{Self, &Self}> for Vec<u8>`) already walked.
1954///
1955/// `type Error = ()` matches the sibling [`TryFrom<&[u8]> for
1956/// RestartStrategy`] unit-error shape, preserving the trait-family
1957/// consistency across the borrowed-and-owned byte-view reverse-projection
1958/// pair. The owned [`Vec<u8>`] input is dropped on the error path (the
1959/// standard-library `String::from_utf8` convention of returning the input
1960/// in the error deliberately declined — a caller that needs the bytes
1961/// back holds a clone before the call, and the closed-set-enum use site
1962/// rarely wants the raw bytes back past a "did you mean" diagnostic that
1963/// operates on the wire vocabulary rather than the input).
1964///
1965/// Pinned load-bearing by
1966/// [`tests::restart_strategy_try_from_vec_bytes_routes_through_borrowed_byte_view_axis`]
1967/// (byte-parity pin against the paired borrowed [`TryFrom<&[u8]>`] axis
1968/// across the four-arm [`RestartStrategy::ALL`] accept-set on the owned
1969/// byte-vec surface, cross-axis witness that the byte-owned reverse
1970/// projection agrees with the paired str-view reverse-projection axis
1971/// ([`TryFrom<&str>`]) on every accepted arm through the shared
1972/// substrate-primitive [`RestartStrategy::from_wire`] accessor, and a
1973/// four-corner {owned-input, borrowed-input} × {`From<Self>` → `Vec<u8>`,
1974/// `From<&Self>` → `Vec<u8>`} round-trip witness available on this enum
1975/// because [`RestartStrategy::as_str`] and [`RestartStrategy::from_wire`]
1976/// share one `PascalCase` byte-vocabulary — unlike the sibling
1977/// [`crate::CaixaKind`] which its peer test deliberately declines the
1978/// four-corner witness on because the wire/diagnostic split makes the
1979/// forward and reverse pairs speak different byte-strings) and
1980/// [`tests::restart_strategy_try_from_vec_bytes_rejects_unknown_and_non_utf8_bytes`]
1981/// (rejection witness against silent accept-set widening on both the
1982/// non-UTF-8 byte-sequence rejection path and the unknown-wire-vocabulary
1983/// rejection path — the latter includes the sibling kebab-case
1984/// dispatcher-catalog byte-strings on the two-axis wire/catalog split so
1985/// a caller that confuses the two axes trips here rather than at a
1986/// downstream K8s-CR round-trip miss, plus a cross-axis witness that the
1987/// owned byte-vec reverse-projection axis agrees with the borrowed byte-
1988/// slice reverse-projection axis on every rejected input).
1989impl TryFrom<Vec<u8>> for RestartStrategy {
1990    type Error = ();
1991
1992    fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
1993        <Self as TryFrom<&[u8]>>::try_from(bytes.as_slice())
1994    }
1995}
1996
1997/// Trait-idiomatic *owned-`String` input, `Result<Self, ()>` output*
1998/// string-owned reverse projection on the first M2-OTP-shape supervisor-slot
1999/// closed-set fieldless typed enum peer on the caixa surface
2000/// ([`RestartStrategy`]) — the owned-input peer of the paired
2001/// [`TryFrom<&str> for RestartStrategy`] str-view reverse-projection axis, and
2002/// the string-owned reverse companion of the pre-existing string-owned
2003/// *forward* pair ([`From<RestartStrategy> for String`],
2004/// [`From<&RestartStrategy> for String`]) already lifted on this same enum.
2005/// Routes owned [`String`] input through the paired borrowed-input
2006/// [`TryFrom<&str>`] axis via [`String::as_str`] so every consumer that holds
2007/// an owned `String` — a future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
2008/// admission-webhook body reader that hands the `spec.estrategia`
2009/// `PascalCase` scalar off as an owned [`String`] after UTF-8 validation, a
2010/// `serde_yaml::from_str` / `serde_json::from_str` de-serialize round-trip
2011/// whose composer surfaces the `:estrategia` scalar as an owned [`String`]
2012/// typed field, a `feira supervisor --estrategia <OneForOne|OneForAll|
2013/// RestForOne|SimpleOneForOne>` `clap`-derived arg-parse whose owned-`String`
2014/// positional lands the canonical arm at the typed dispatch, a
2015/// per-`:supervisor`-slot overlay resolver reading an owned [`String`] out of
2016/// a `ConfigMap` `data.supervisor-estrategia` scalar, an
2017/// `<T: TryFrom<String>>`-bound generic loader over any of the substrate's
2018/// closed-set typed enums — reaches the same four-arm `PascalCase` accept-set
2019/// through one trait dispatch.
2020///
2021/// Extends the substrate-wide trait-idiomatic *string-owned reverse-
2022/// projection* family — opened on the compound M3-mesh
2023/// `:politicas :rate-limit` primitive [`crate::aplicacao::RateLimit`]
2024/// (a2e6f02), lifted onto the first closed-set fieldless typed-enum peer
2025/// [`crate::aplicacao::WitShape`] (e6aac29), extended onto the second closed-
2026/// set fieldless typed-enum peer [`crate::aplicacao::RateLimitUnit`]
2027/// (94a9c5e), extended onto the third closed-set fieldless typed-enum peer
2028/// [`crate::aplicacao::PlacementStrategy`] (d81a70a) — onto the first
2029/// M2-OTP-shape supervisor-slot closed-set fieldless typed-enum peer, the
2030/// per-`:supervisor` sibling-restart-strategy discriminator. The peers
2031/// [`RestartPolicy`], [`crate::CaixaKind`], [`crate::CaixaDialeto`], and
2032/// [`crate::dep::DepList`] remain the next targets of the campaign, mirroring
2033/// the trajectory the closed byte-view / byte-owned reverse-projection
2034/// families already walked across the same closed-set peers.
2035///
2036/// Rust's standard library carries no blanket
2037/// `impl<T: for<'a> TryFrom<&'a str>> TryFrom<String> for T`, so a consumer
2038/// that holds an owned [`String`] and needs a typed [`RestartStrategy`]
2039/// otherwise picks between (a) an open-coded
2040/// `<RestartStrategy as TryFrom<&str>>::try_from(s.as_str())` at every call
2041/// site whose type bounds have no compile-time link back to the string-owned
2042/// reverse-projection axis, (b) a `let s: &str = &s;
2043/// RestartStrategy::try_from(s)` two-step whose borrow arithmetic leaks a
2044/// per-call-site lifetime dance rather than a single trait dispatch, or (c) a
2045/// `String::into_bytes` + [`TryFrom<Vec<u8>>`] detour that reaches the
2046/// substrate-primitive `from_wire` accessor through a UTF-8 re-validation hop
2047/// the owned-`String` axis already knows to skip. This impl closes the
2048/// string-owned reverse-projection axis at the substrate-primitive
2049/// [`RestartStrategy::from_wire`] accessor so every future
2050/// `<T: TryFrom<String>>`-bound owned-string consumer reaches the same
2051/// four-arm `PascalCase` accept-set through one trait dispatch.
2052///
2053/// `type Error = ()` matches the sibling [`TryFrom<&str> for
2054/// RestartStrategy`], [`TryFrom<&[u8]> for RestartStrategy`], and
2055/// [`TryFrom<Vec<u8>> for RestartStrategy`] unit-error shapes, preserving the
2056/// trait-family consistency across the {str-view, byte-view, byte-owned,
2057/// string-owned} reverse-projection square. The owned [`String`] input is
2058/// dropped on the error path (the standard-library `String::from_utf8`
2059/// convention of returning the input in the error deliberately declined — a
2060/// caller that needs the string back holds a clone before the call, and the
2061/// closed-set-enum use site rarely wants the raw string back past a "did you
2062/// mean" diagnostic that operates on the wire vocabulary rather than the
2063/// input).
2064///
2065/// Pinned load-bearing by
2066/// [`tests::restart_strategy_try_from_owned_string_routes_through_borrowed_str_view_axis`]
2067/// (byte-parity pin against the paired borrowed [`TryFrom<&str>`] axis across
2068/// the four-arm [`RestartStrategy::ALL`] accept-set on the owned-`String`
2069/// surface, cross-axis witness that the string-owned reverse projection
2070/// agrees with the sibling byte-view / byte-owned reverse-projection axes on
2071/// every accepted arm through the shared substrate-primitive
2072/// [`RestartStrategy::from_wire`] accessor, and a closed-cycle witness
2073/// against the paired string-owned forward-projection pair — `Self → String
2074/// → TryFrom<String> → Self` round-trips to the originating arm on every
2075/// canonical `PascalCase` scalar) and
2076/// [`tests::restart_strategy_try_from_owned_string_rejects_unknown_wire_strings`]
2077/// (rejection witness against silent accept-set widening — mirrors the
2078/// corpus the paired [`TryFrom<&str>`] rejection witness already pins,
2079/// including empty / whitespace-only inputs, the sibling kebab-case
2080/// dispatcher-catalog byte-strings on the two-axis wire/catalog split so a
2081/// caller that confuses the two axes trips here rather than at a downstream
2082/// K8s-CR round-trip miss, case-fold rebrand candidates, whitespace-padded /
2083/// trailing-newline / quote-wrapped forms, and English-rebrand candidates,
2084/// with per-input cross-axis parity against the borrowed [`TryFrom<&str>`]
2085/// reverse-projection axis).
2086impl TryFrom<String> for RestartStrategy {
2087    type Error = ();
2088
2089    fn try_from(s: String) -> Result<Self, Self::Error> {
2090        <Self as TryFrom<&str>>::try_from(s.as_str())
2091    }
2092}
2093
2094/// Per-child restart policy.
2095///
2096/// Permanent / Temporary / Transient match Erlang/OTP semantics 1:1.
2097#[derive(
2098    Serialize,
2099    Deserialize,
2100    Debug,
2101    Clone,
2102    Copy,
2103    PartialEq,
2104    Eq,
2105    Hash,
2106    gen_platform::TypedDispatcher,
2107    gen_platform::Discriminant,
2108    gen_platform::IsVariant,
2109    gen_platform::FromStrKind,
2110)]
2111pub enum RestartPolicy {
2112    /// Always restart the child, regardless of how it died. Used for
2113    /// long-running services that must always be up.
2114    Permanent,
2115    /// Never restart. Used for one-shot work whose completion is
2116    /// itself the success signal (`oneShot` triggers map here).
2117    Temporary,
2118    /// Restart only when the child died *abnormally* (non-zero exit
2119    /// or unhandled exception). A clean exit completes the child.
2120    Transient,
2121}
2122
2123impl Default for RestartPolicy {
2124    fn default() -> Self {
2125        // Route the [`Default for RestartPolicy`] impl's return arm through
2126        // the substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed
2127        // `pub const` rather than a raw `Self::Permanent` arm — one source
2128        // of truth for the Erlang/OTP-canonical `permanent` worker-child
2129        // default across the two production consumers that currently
2130        // dispatch on it (this impl at the [`RestartPolicy::default`] call
2131        // and the serde-side `#[serde(default)]` on
2132        // [`ChildSpec::restart`] that resolves an author-omitted
2133        // `:children :restart` slot through `RestartPolicy::default()`).
2134        // Peer of the sibling per-`:supervisor` axis
2135        // [`Default for RestartStrategy`] → [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
2136        // route (95ffacc) — the two impls now share one substrate-primitive
2137        // lift discipline, so any future coherent rebrand of the OTP-shape
2138        // supervisor+child default set migrates through typed constants in
2139        // lockstep instead of splitting a lifted supervisor half against
2140        // an open-coded child half. Pinned by
2141        // `restart_policy_default_routes_through_lifted_default` +
2142        // `child_spec_serde_default_restart_routes_through_lifted_default`
2143        // in the tests module.
2144        SUPERVISOR_CHILD_RESTART_DEFAULT
2145    }
2146}
2147
2148impl RestartPolicy {
2149    /// Exhaustive iteration surface for every consumer that walks the
2150    /// closed three-arm [`RestartPolicy`] discriminator set (the future
2151    /// M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
2152    /// per-child admission-webhook rejection body naming the accepted-
2153    /// `:restart` list, a future `feira supervisor --restart …` CLI
2154    /// arg-parse's "did you mean" hint via a [`Self::from_wire`]-scan
2155    /// over the slice, the future `feira app graph` per-child restart
2156    /// column, any future round-trip fuzz harness that sweeps every
2157    /// arm). A future arm addition (an OTP-`intrinsic` fourth arm the
2158    /// theory
2159    /// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
2160    /// might reach for once the three canonical OTP restart policies
2161    /// stop covering the substrate's discovered load-shape) extends
2162    /// this slice as one edit and every consumer picks up the new entry
2163    /// by construction; the compiler-checked exhaustiveness on the
2164    /// sibling method `match` arms ([`Self::as_str`] / [`Self::from_wire`])
2165    /// is the build-time guarantee that no arm forgets to grow.
2166    ///
2167    /// Peer of the sibling closed-set typed enums'
2168    /// [`RestartStrategy::ALL`] (4eec29c) /
2169    /// [`crate::CaixaKind::ALL`] (6b1f4fb) /
2170    /// [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
2171    /// [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
2172    /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
2173    /// surfaces — the sixth (and the third and final M2 OTP-shape)
2174    /// closed-set typed enum on the caixa surface to converge onto the
2175    /// same one-canonical-arm-list-per-enum discipline. Sibling axis to
2176    /// the peer [`RestartStrategy::ALL`] on the per-supervisor
2177    /// sibling-restart-strategy axis; this closes the per-child
2178    /// restart-decision-policy axis on the same M2 `:supervisor` slot.
2179    pub const ALL: &'static [Self] = &[Self::Permanent, Self::Temporary, Self::Transient];
2180
2181    /// Substrate-canonical exhaustive accept-set on the [`RestartPolicy`]
2182    /// `PascalCase` wire byte-string axis — the closed three-arm roster
2183    /// of every byte-string [`Self::as_str`] returns, routed byte-for-byte
2184    /// through the paired
2185    /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2186    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2187    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] lifted
2188    /// `pub const` roster the [`Self::as_str`] emitter (and the
2189    /// [`std::fmt::Display`] impl / `Serialize` derive routed through it)
2190    /// walks — and byte-for-byte the same three strings the un-`rename`d
2191    /// `Serialize` derive emits under the paired
2192    /// [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] tag key on every
2193    /// JSON / YAML CR round-trip.
2194    ///
2195    /// Peer of the sibling [`crate::CaixaKind::WIRE_NAMES`] (bd708bd)
2196    /// roster on the top-level typed-kind discriminator's `PascalCase`
2197    /// wire byte-string axis, the sibling
2198    /// [`RestartStrategy::WIRE_NAMES`] (3033f45) roster on the per-
2199    /// supervisor sibling-restart-strategy axis (the first M2 OTP-shape
2200    /// closed-set typed enum to converge onto the paired-roster
2201    /// discipline), the sibling
2202    /// [`crate::aplicacao::PlacementStrategy::WIRE_NAMES`] (3e5b194)
2203    /// roster on the first M3 mesh-shape distribution-strategy closed-
2204    /// set typed enum, and the sibling
2205    /// [`crate::upgrade::UpgradeInstruction::WIRE_FORMS`] (cc42c0e) /
2206    /// [`crate::upgrade::UpgradeInstruction::LISP_FORMS`] (1898d77)
2207    /// rosters on the OTP-appup discriminator's two-axis roster split —
2208    /// the same closed-set exhaustive-accept-set roster discipline
2209    /// extended here onto the second and final M2 OTP-shape sibling-
2210    /// enum on the caixa surface, closing the per-child restart-decision-
2211    /// policy axis paired with the peer [`RestartStrategy::WIRE_NAMES`]
2212    /// per-supervisor sibling-restart-strategy axis on the same M2
2213    /// `:supervisor` slot.
2214    ///
2215    /// Downstream consumers of the closed accepted-wire-form set — a
2216    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR admission-
2217    /// webhook rejection body enumerating the accepted JSON `:restart`
2218    /// values verbatim (as distinct from the kebab-case dispatcher-
2219    /// catalog enumeration [`Self::discriminant`] serves, whose per-arm
2220    /// form `"permanent"` / `"temporary"` / `"transient"` structurally
2221    /// disagrees with the wire byte-string these `PascalCase` entries
2222    /// carry — the split the sibling
2223    /// [`tests::restart_policy_display_matches_serialized_wire_byte_string`]
2224    /// pin already makes load-bearing), a future `feira supervisor
2225    /// --restart …` CLI-side "did you mean" hint whose candidate-list
2226    /// must byte-match the wire form the operator's per-child dispatch
2227    /// keys off, a future `feira app graph` per-child `:restart`-
2228    /// histogram column that renders zero-count arms, a future
2229    /// `caixa-operator` per-reconcile-step diagnostic log line
2230    /// enumerating accepted wire forms on an unknown-policy rejection,
2231    /// a future
2232    /// `tracing::field::valuable::Value::List` structured-log accepted-
2233    /// wire-form emit — now reach for one lifted substrate-primitive
2234    /// roster rather than open-coding a three-string array-literal
2235    /// (`["Permanent", "Temporary", "Transient"]`) whose arm-set has no
2236    /// compile-time link back to the typed [`RestartPolicy`] enum. A
2237    /// future arm addition (an OTP-`intrinsic` fourth arm the theory
2238    /// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
2239    /// might reach for once the three canonical OTP restart policies
2240    /// stop covering the substrate's discovered load-shape) extends
2241    /// this roster as a single edit — paired with the [`Self::as_str`]
2242    /// match's compiler-checked exhaustiveness on the new arm — and
2243    /// every consumer picks up the new wire form by construction rather
2244    /// than a coordinated array-literal rewrite across every downstream
2245    /// site.
2246    ///
2247    /// Length is pinned load-bearing at `RestartPolicy::ALL.len()`
2248    /// (three) by
2249    /// [`tests::restart_policy_wire_names_covers_every_arm`], every
2250    /// variant's [`Self::as_str`] projection is pinned to a member of
2251    /// the roster so a silent skew between the emitter's arm-set and
2252    /// this const's arm-set trips at caixa-core test time rather than at
2253    /// a downstream consumer's accepted-set enumeration miss, and every
2254    /// entry is further pinned to open with an ASCII uppercase byte so
2255    /// a silent collapse of the `PascalCase` wire-form axis with the
2256    /// peer kebab-case dispatcher-catalog axis (an entry byte-identical
2257    /// to a sibling [`Self::discriminant`] kebab byte-string that would
2258    /// let a wire-axis consumer accept the dispatcher-catalog
2259    /// vocabulary) trips here rather than at a downstream K8s-CR round-
2260    /// trip miss.
2261    pub const WIRE_NAMES: &'static [&'static str] = &[
2262        crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
2263        crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
2264        crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
2265    ];
2266
2267    /// Canonical PascalCase discriminator scalar this variant serializes
2268    /// as under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`]. The three
2269    /// arms return the paired
2270    /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2271    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2272    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] lifted
2273    /// constants so every substrate consumer that dispatches on the
2274    /// per-child restart-decision policy (the future wasm-operator's
2275    /// per-child post-exit restart-decision branch, the future M4
2276    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
2277    /// admission-time enum-arm bind, the `caixa-operator`'s hierarchical
2278    /// reconciliation scheduler's per-child-policy fan-out) reads the
2279    /// same byte-string the `Serialize` derive emits — the pin test in
2280    /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
2281    /// asserts the two paths agree, peer of the M2
2282    /// [`RestartStrategy::as_str`] (09ffb2d) on the sibling per-supervisor
2283    /// sibling-restart-strategy axis and the M3
2284    /// [`crate::aplicacao::PlacementStrategy::as_str`] (cc8f749) on the
2285    /// per-Aplicacao distribution-strategy axis — the third of three
2286    /// OTP-shaped closed-enum discriminator axes on the caixa typed
2287    /// surface to converge onto the same three-path-convergence
2288    /// (`Serialize` derive → `as_str` helper → lifted constant)
2289    /// drift-detection posture.
2290    #[must_use]
2291    pub const fn as_str(self) -> &'static str {
2292        match self {
2293            Self::Permanent => crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
2294            Self::Temporary => crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
2295            Self::Transient => crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
2296        }
2297    }
2298
2299    /// Substrate-canonical reverse projection on the `:children :restart`
2300    /// closed-set axis — parses the `PascalCase` discriminator scalar
2301    /// back to the typed variant, or `None` when `s` is outside the
2302    /// closed-set arm-string set [`Self::as_str`] emits. Dispatches on
2303    /// the same lifted
2304    /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2305    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2306    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] constants
2307    /// the [`Self::as_str`] emitter walks, so the parse and emit halves
2308    /// of the round-trip migrate through one caixa-core edit on any
2309    /// future arm addition.
2310    ///
2311    /// Prior to this lift the substrate carried only the forward
2312    /// `Self → &str` projection on the OTP per-child restart-policy
2313    /// axis (the [`Self::as_str`] emitter, the [`std::fmt::Display`]
2314    /// impl routed through it, the `Serialize` derive that emits the
2315    /// same byte-string under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`])
2316    /// plus the kebab-case dispatcher-catalog identity via
2317    /// [`Self::discriminant`] — every non-serde consumer that wanted to
2318    /// parse a wire-form `PascalCase` policy scalar had to re-inline a
2319    /// three-arm `match s { "Permanent" => …, "Temporary" => …,
2320    /// "Transient" => …, _ => … }` cascade that expressed no
2321    /// compile-time link back to the typed variant's canonical lifted
2322    /// constant. A future variant rename or per-arm serde-attribute
2323    /// drift would silently split the wire byte-string one non-serde
2324    /// consumer parsed from the one the emitter wrote, with the failure
2325    /// surfacing at the operator's reconcile posture (a `:temporary`
2326    /// `oneShot` child being restarted on clean exit, treating the
2327    /// successful-completion signal as failure and re-running the
2328    /// completion-terminal one-shot indefinitely; a `:transient` child
2329    /// that clean-exited being restarted, masking the clean-completion
2330    /// contract) far from the rebrand commit and with no field naming
2331    /// the drift.
2332    ///
2333    /// Distinct axis from the [`std::str::FromStr`] impl the
2334    /// [`gen_platform::FromStrKind`] derive already installs on this
2335    /// enum by design, not by drift: `FromStr` parses the *kebab-case*
2336    /// dispatcher-catalog identity (`"permanent"` / `"temporary"` /
2337    /// `"transient"` — the inverse of [`Self::discriminant`]), while
2338    /// this method inverts the `PascalCase` wire byte-string
2339    /// [`Self::as_str`] emits. The two-axis split lets the dispatcher-
2340    /// catalog identity live in kebab-case (where every peer catalog
2341    /// identifier already lives) without forcing a wire-format rename
2342    /// on the tatara-lisp author surface (`:restart Permanent`,
2343    /// `PascalCase`) — the same two-axis distinction the sibling
2344    /// [`RestartStrategy::from_wire`] (4eec29c) /
2345    /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
2346    /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
2347    /// carry on their peer closed-set typed-enum wire round-trips.
2348    ///
2349    /// Same closed-set-reverse-projection discipline the sibling
2350    /// [`RestartStrategy::from_wire`] (4eec29c) /
2351    /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
2352    /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342) /
2353    /// [`crate::aplicacao::RateLimitUnit::from_suffix`] typed enums
2354    /// carry on the peer wire-side `str → Self` axes — extended onto
2355    /// the M2 OTP-shape per-child restart-policy closed-set axis, the
2356    /// sixth substrate-side closed-set typed enum (and the third and
2357    /// final OTP-shape closed-enum discriminator axis) to converge on
2358    /// the two-way `str ↔ Self` round-trip. Method-named `from_wire`
2359    /// (not `from_str`) to match the peer [`RestartStrategy::from_wire`]
2360    /// shape verbatim and side-step the [`std::str::FromStr`] impl the
2361    /// derive already installs on the sibling kebab-case axis. Returns
2362    /// `Option<Self>` (rather than `Result<Self, _>`) to match the peer
2363    /// shapes: the caller picks the diagnostic form appropriate for
2364    /// its use site.
2365    #[must_use]
2366    pub fn from_wire(s: &str) -> Option<Self> {
2367        match s {
2368            crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT => Some(Self::Permanent),
2369            crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY => Some(Self::Temporary),
2370            crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT => Some(Self::Transient),
2371            _ => None,
2372        }
2373    }
2374}
2375
2376/// [`std::fmt::Display`] routed through [`RestartPolicy::as_str`], so the
2377/// pretty-printed byte-string every consumer that formats the policy as
2378/// user-facing text lands on (the future wasm-operator's per-child
2379/// post-exit restart-decision diagnostic line, the future `feira app
2380/// graph` per-child restart column, the future M4
2381/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
2382/// admission-webhook rejection body) reaches for the same lifted
2383/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2384/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2385/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2386/// wire-format `Serialize` derive already emits under
2387/// [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
2388/// [`RestartPolicy::as_str`] helper already returns.
2389///
2390/// Pre-convergence the two paths structurally disagreed — the
2391/// `#[derive(gen_platform::Discriminant)]` + `#[discriminant(also_display)]`
2392/// route (now retired here) sent [`std::fmt::Display`] through the
2393/// gen-platform discriminant catalog string, which arrives kebab-case as
2394/// `"permanent"` / `"temporary"` / `"transient"` on this three-arm enum
2395/// (whose variant names each collapse to their own lowercase form under
2396/// the kebab-case transform), while the wire format ran as `PascalCase`
2397/// `"Permanent"` / `"Temporary"` / `"Transient"` through the un-`rename`d
2398/// serde derive. Every consumer that formatted the policy for a
2399/// diagnostic line, a graph column, or a rejection body under
2400/// `format!("{v}")` therefore landed under a different byte-string than
2401/// the wire format the operator's per-child-policy dispatch keyed off —
2402/// a silent split whose apply-time symptom (a `format!("{v}")`-carrying
2403/// diagnostic quoting `"permanent"` while the wire scalar the operator
2404/// probed was `"Permanent"`) surfaced as a confused correlate at
2405/// operator-log time far from the two-declaration site.
2406///
2407/// Routing `Display` through [`RestartPolicy::as_str`] closes the third
2408/// path: every `format!("{v}")` call reaches the same lifted
2409/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the wire format
2410/// and the [`RestartPolicy::as_str`] helper route through — `Debug` (the
2411/// compiler-derived variant name), `Display` (via `as_str`), and `Serialize`
2412/// (via the un-`rename`d derive) all resolve to the same `PascalCase`
2413/// byte-string per variant. A future variant rename or
2414/// `#[serde(rename_all = "kebab-case")]` attribute reaches every path at
2415/// exactly one place, structurally.
2416///
2417/// The dispatcher-catalog identity remains kebab-case — [`Self::discriminant`]
2418/// (from `#[derive(gen_platform::Discriminant)]`) still returns
2419/// `"permanent"` / `"temporary"` / `"transient"`, and the fleet-wide
2420/// [`gen_platform::register_dispatcher!("caixa.restart-policy", …)`]
2421/// registration keys the catalog off the same kebab identity. The two
2422/// naming worlds now live on separate typed methods (`Display` /
2423/// `as_str` for the wire byte-string, `discriminant` for the catalog
2424/// identity) rather than sharing one `Display` route that structurally
2425/// disagrees with the wire format.
2426///
2427/// Pin tests
2428/// [`tests::restart_policy_display_routes_through_as_str_helper`]
2429/// and
2430/// [`tests::restart_policy_display_matches_serialized_wire_byte_string`]
2431/// assert the three paths agree byte-for-byte on every variant, so a
2432/// future variant rename or per-arm serde attribute drift is a build
2433/// error visible at caixa-core test time, not a silent per-consumer
2434/// dispatch miss at apply / reconcile time.
2435///
2436/// Mirrors the M3 [`crate::aplicacao::PlacementStrategy`] `Display` impl
2437/// (aplicacao.rs:2306) on the per-Aplicacao distribution-strategy axis
2438/// and the sibling [`RestartStrategy`] `Display` impl on the
2439/// per-supervisor sibling-restart-strategy axis — same three-path-
2440/// convergence discipline, extended to close the third and final of
2441/// three OTP-shaped closed-enum discriminator axes on the caixa typed
2442/// surface.
2443impl std::fmt::Display for RestartPolicy {
2444    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2445        f.write_str(self.as_str())
2446    }
2447}
2448
2449/// Substrate-canonical [`AsRef<str>`] projection on the M2
2450/// per-child-restart-policy [`RestartPolicy`] closed-set typed enum —
2451/// routes through the same [`RestartPolicy::as_str`] `pub const fn`
2452/// scalar accessor the paired [`std::fmt::Display`] impl and the
2453/// un-`rename`d [`serde::Serialize`] derive already key off, so any
2454/// future consumer that binds a [`RestartPolicy`] through the
2455/// standard-library `impl AsRef<str>` bound (a future
2456/// [`caixa-feira`] `feira supervisor --restart <arm>` verb that
2457/// composes the emitted `PascalCase` wire scalar into a
2458/// [`std::process::Command::arg`] shell-out of the future
2459/// wasm-operator's per-child admission gate, a per-child structured-
2460/// log recorder on the future `caixa-operator`'s hierarchical
2461/// reconciliation surface that accepts `impl AsRef<str>` at the
2462/// `tracing::field::Value` `Str`-arm, a [`std::collections::HashMap`]
2463/// lookup keyed on the restart-policy wire byte through
2464/// `map.get::<str>(policy.as_ref())` on a future per-policy
2465/// dispatch table) reaches the paired
2466/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2467/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2468/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
2469/// lifted-const through one substrate-primitive dispatch rather
2470/// than an open-coded `.as_str()` projection at every wire-up.
2471///
2472/// Peer of the sibling [`std::fmt::Display`] impl on the same
2473/// primitive — both delegate to the shared [`RestartPolicy::as_str`]
2474/// `pub const fn` accessor, so [`format!("{v}")`], `v.as_str()`, and
2475/// `<RestartPolicy as AsRef<str>>::as_ref(&v)` resolve to the same
2476/// byte-string per instance by construction. A future variant rename
2477/// or `#[serde(rename_all = "kebab-case")]` attribute-drift on the
2478/// enum reaches every one of the three paths (plus the wire-format
2479/// `Serialize` derive that already routes through the same lifted
2480/// const) through exactly one caixa-core edit.
2481///
2482/// Same "route the trait impl through the substrate-primitive
2483/// accessor" discipline the sibling [`crate::CaixaVersion`]
2484/// [`AsRef<str>`] impl (16d5c7e) and the paired M2
2485/// [`RestartStrategy`] [`AsRef<str>`] impl (63eb1a4) carry — extends
2486/// the axis onto the paired per-child-restart-decision-policy
2487/// sibling on the same M2 `:supervisor` slot (the second M2
2488/// OTP-shape closed-set typed enum to converge onto the standard-
2489/// library [`AsRef<str>`] projection). Rust-side newtype/typed-enum
2490/// convention pairs [`AsRef<str>`] and [`fmt::Display`] on the same
2491/// primitive so a caller who has one has both; before this lift,
2492/// [`RestartPolicy`] carried [`fmt::Display`] but not the paired
2493/// [`AsRef<str>`] impl the convention names.
2494///
2495/// Pinned load-bearing by
2496/// [`tests::restart_policy_as_ref_str_routes_through_as_str_accessor`]
2497/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2498/// three-arm closed set) and
2499/// [`tests::restart_policy_as_ref_str_routes_through_display_via_shared_accessor`]
2500/// (three-path convergence: `AsRef<str>` + `Display` + `as_str` all
2501/// resolve to the same lifted `SUPERVISOR_CHILD_RESTART_*` const per
2502/// arm) — any future silent detour that routes the impl through a
2503/// divergent projection (a per-arm inline `match self { … }`
2504/// re-inlining that opens a compile-time link to the un-lifted
2505/// arm-literal, a swap onto the kebab-case
2506/// [`gen_platform::Discriminant`] catalog identity that would
2507/// collide the wire axis with the dispatcher-catalog axis) trips at
2508/// caixa-core test time under `assert_eq!` rather than at a
2509/// downstream `impl AsRef<str>`-bound consumer's silent split.
2510impl AsRef<str> for RestartPolicy {
2511    fn as_ref(&self) -> &str {
2512        self.as_str()
2513    }
2514}
2515
2516/// Trait-idiomatic reverse projection on the M2-OTP-shape per-child
2517/// restart-policy [`RestartPolicy`] closed-set typed enum — routes
2518/// byte-for-byte through the paired substrate-primitive
2519/// [`RestartPolicy::from_wire`] `Option<Self>` accessor so every future
2520/// consumer that binds a `PascalCase` `:children :restart` wire
2521/// byte-string through the standard-library `.try_into()` / [`TryFrom`]
2522/// axis (a future [`caixa-feira`] `feira supervisor --restart
2523/// <Permanent|Temporary|Transient>` CLI arg-parse that composes into
2524/// `let restart: RestartPolicy = s.try_into()?`, a future
2525/// `mesh.pleme.io/v1alpha1/Supervisor` CR admission-webhook that folds a
2526/// `spec.children[*].restart: String` field through
2527/// `RestartPolicy::try_from(&s)?`, a generic
2528/// `<T: TryFrom<&str>>`-bound loader over any of the substrate's closed-
2529/// set typed enums) reaches the same three-arm accept-set the sibling
2530/// [`RestartPolicy::from_wire`] resolver parses through and the sibling
2531/// [`RestartPolicy::as_str`] emits, rather than an open-coded per-arm
2532/// `match s { "Permanent" => …, "Temporary" => …, "Transient" => …, _ =>
2533/// … }` cascade whose arm-set has no compile-time link back to the
2534/// substrate primitive.
2535///
2536/// Complements the pre-existing forward-projection triple
2537/// ([`std::fmt::Display`], [`AsRef<str>`], [`RestartPolicy::as_str`])
2538/// with the paired trait-idiomatic reverse-projection axis: Rust-side
2539/// newtype/typed-enum convention pairs [`AsRef<str>`] with either
2540/// [`std::str::FromStr`] or [`TryFrom<&str>`] on the same primitive so a
2541/// caller who can project *out to* a `&str` can also project *in from*
2542/// one. The [`TryFrom<&str>`] axis is deliberately chosen over
2543/// [`std::str::FromStr`] to sidestep the `clippy::should_implement_trait`
2544/// lint the sibling method-named [`RestartPolicy::from_wire`] would
2545/// trigger under a `FromStr` impl and to avoid colliding with the
2546/// [`std::str::FromStr`] impl the [`gen_platform::FromStrKind`] derive
2547/// already installs on the paired *kebab-case dispatcher-catalog* axis
2548/// (which parses `"permanent"` / `"temporary"` / `"transient"`, the
2549/// inverse of [`Self::discriminant`]) — this impl closes the trait-
2550/// idiomatic reverse axis on the *`PascalCase` wire* half without
2551/// disturbing either the method-named `from_wire` shape every sibling
2552/// closed-set typed enum on the substrate already carries or the
2553/// pre-existing `FromStr` on the dispatcher-catalog half, keeping the
2554/// two-axis split the sibling [`Self::from_wire`] doc block motivates.
2555///
2556/// `type Error = ()` matches the sibling [`RestartPolicy::from_wire`]'s
2557/// `Option<Self>` return-shape's deliberate deferral of error typing: the
2558/// caller picks the diagnostic form appropriate for its use site (a
2559/// future `feira supervisor --restart` arg-parse composes its own
2560/// per-verb "unknown restart: <arg> — accepted: {…}" message enumerating
2561/// [`RestartPolicy::ALL`], a future M4 admission-webhook rejection body
2562/// wraps the `Err(())` outcome with the accepted-set enumeration for
2563/// operator diagnostics, a `Result::map_err` at the call site lifts the
2564/// unit-error to a per-verb error type). Same shape the peer
2565/// [`RestartStrategy`] (5b828ed) on the sibling per-supervisor axis,
2566/// [`crate::CaixaKind`] (3c83606), [`crate::CaixaDialeto`] (bf33136), and
2567/// [`crate::aplicacao::PlacementStrategy`] (6fd00cd) blocks motivate on
2568/// their peer closed-set typed enums' reverse projections.
2569///
2570/// The paired [`TryFrom<&str>`] impl reaches the same three-arm accept-
2571/// set the [`RestartPolicy::from_wire`] resolver dispatches through, so
2572/// any future arm addition (an OTP-`intrinsic` fourth arm the theory
2573/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
2574/// might reach for once the three canonical OTP restart policies stop
2575/// covering the substrate's discovered load-shape) grows the trait-
2576/// idiomatic axis by construction — one caixa-core edit on
2577/// [`RestartPolicy::from_wire`] extends both the method-named reverse
2578/// projection every existing consumer keys off and the trait-idiomatic
2579/// reverse projection this impl exposes, without a coordinated rewrite
2580/// across every future `TryFrom<&str>`-bound consumer's arm-set.
2581///
2582/// Extends the substrate-wide closed-set-enum reverse-projection family
2583/// ([`crate::CaixaKind`] via 3c83606, [`crate::CaixaDialeto`] via
2584/// bf33136, [`crate::aplicacao::PlacementStrategy`] via 6fd00cd, and
2585/// [`RestartStrategy`] via 5b828ed) onto the third and final OTP-shape
2586/// closed-enum discriminator axis on the caixa surface — the paired
2587/// per-child `:children :restart` closed set the future wasm-operator's
2588/// hierarchical reconciliation scheduler's per-child post-exit
2589/// restart-decision branch keys off end-to-end.
2590///
2591/// Pinned load-bearing by
2592/// [`tests::restart_policy_try_from_str_routes_through_from_wire_accessor`]
2593/// (byte-parity pin against [`RestartPolicy::from_wire`] across the
2594/// three-arm accept-set),
2595/// [`tests::restart_policy_try_from_str_rejects_unknown_byte_strings`]
2596/// (rejection witness against silent accept-set widening), and
2597/// [`tests::restart_policy_try_from_str_and_from_wire_partition_the_accept_set`]
2598/// (cross-axis partition pin locking the trait and method-named
2599/// projections onto one accept-set).
2600impl TryFrom<&str> for RestartPolicy {
2601    type Error = ();
2602
2603    fn try_from(s: &str) -> Result<Self, Self::Error> {
2604        Self::from_wire(s).ok_or(())
2605    }
2606}
2607
2608/// Trait-idiomatic forward projection on the M2-OTP-shape per-child
2609/// restart-policy [`RestartPolicy`] closed-set typed enum — routes
2610/// byte-for-byte through the paired substrate-primitive
2611/// [`RestartPolicy::as_str`] `pub const fn` accessor. Return type is
2612/// `&'static str` by construction — every [`RestartPolicy::as_str`] arm
2613/// resolves to a [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const
2614/// &str` with `'static` lifetime, so the trait's return-type promise is
2615/// upheld structurally without a [`String::leak`] cast or a per-arm inline
2616/// literal.
2617///
2618/// Every future consumer that specifically needs `&'static str` lifetime
2619/// bytes on the per-child restart-decision axis (a
2620/// [`tracing::field::valuable::Value::Str`] recording where the `Str`
2621/// arm's typing demands `&'static str`, a
2622/// [`std::borrow::Cow::Borrowed`]`::<'static, str>(policy.into())` composer
2623/// on the future M4 admission-webhook rejection body where the
2624/// `Cow<'static, str>` typing rules out the sibling [`AsRef<str>`]
2625/// borrowed return, a generic `<T: Into<&'static str>>`-bound serializer
2626/// or error formatter that requires the `'static` bound) reaches the same
2627/// lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2628/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2629/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] substrate-
2630/// primitive dispatch rather than an open-coded per-arm literal cascade
2631/// whose arm-set has no compile-time link back to the substrate primitive.
2632///
2633/// Peer of the sibling M2-OTP-shape [`RestartStrategy`] forward-projection
2634/// impl (523157d) on the per-supervisor sibling-restart-strategy axis —
2635/// the second (and second-of-two-in-M2) closed-set typed enum on the
2636/// caixa surface to converge onto the paired trait-idiomatic forward-
2637/// projection axis. With this lift the paired per-child
2638/// `:children :restart` closed-set typed enum carries the full sibling
2639/// quintet ([`std::fmt::Display`], [`AsRef<str>`], [`Self::as_str`],
2640/// [`TryFrom<&str>`] via 6fdd0d9, `From<Self> for &'static str` via this
2641/// lift) plus the round-trip witness through both the trait-idiomatic
2642/// (`From<Self> for &'static str` + `TryFrom<&str>`) and the method-named
2643/// (`as_str` + `from_wire`) axis pairs — mirrors the sibling
2644/// [`RestartStrategy`] surface arm-for-arm, so every future arm addition
2645/// (an OTP-`intrinsic` fourth arm the theory
2646/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
2647/// might reach for once the three canonical OTP restart policies stop
2648/// covering the substrate's discovered load-shape) grows the trait-
2649/// idiomatic forward axis by construction: one caixa-core edit on
2650/// [`RestartPolicy::as_str`] extends every one of the five sibling
2651/// forward-projection paths ([`std::fmt::Display`], [`AsRef<str>`],
2652/// [`Self::as_str`] itself, this `From<Self> for &'static str`, and the
2653/// un-`rename`d [`serde::Serialize`] derive that also emits `as_str`'s
2654/// bytes) without a coordinated rewrite across every future
2655/// `Into<&'static str>`-bound consumer's arm-set.
2656///
2657/// Pinned load-bearing by
2658/// [`tests::restart_policy_from_into_static_str_routes_through_as_str_accessor`]
2659/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2660/// three-arm emit-set, plus a `const`-context materialization witness for
2661/// the `&'static str` lifetime promise) and
2662/// [`tests::restart_policy_from_into_static_str_and_as_str_partition_the_emit_set`]
2663/// (partition pin asserting `<&'static str as From<RestartPolicy>>::from`
2664/// and [`RestartPolicy::as_str`] agree on every arm, plus a two-way
2665/// round-trip witness through the paired trait-idiomatic reverse-
2666/// projection axis [`TryFrom<&str>`] (6fdd0d9): every
2667/// `policy.into::<&'static str>()` output re-parses back through
2668/// [`RestartPolicy::try_from`] to the original variant, closing the two-
2669/// way `Self ↔ &'static str` round-trip on the trait-idiomatic axis pair).
2670impl From<RestartPolicy> for &'static str {
2671    fn from(policy: RestartPolicy) -> &'static str {
2672        policy.as_str()
2673    }
2674}
2675
2676/// Trait-idiomatic *forward* projection on [`RestartPolicy`] from a
2677/// *borrowed* input onto the `&'static str` axis — the borrowed-input
2678/// companion to the paired owned-input [`From<RestartPolicy> for
2679/// &'static str`] impl immediately above. Routes byte-for-byte through
2680/// the same substrate-primitive [`RestartPolicy::as_str`] `pub const
2681/// fn` accessor so every consumer that binds a `&RestartPolicy`
2682/// through the standard-library `.into()` / [`From<&Self> for &'static
2683/// str`] axis (a `RestartPolicy::ALL.iter().map(<&'static
2684/// str>::from).collect::<Vec<_>>()` per-arm accept-set materializer —
2685/// whose iterator over `&'static [RestartPolicy]` yields
2686/// `&RestartPolicy`, not `RestartPolicy`, so the owned-input
2687/// [`From<RestartPolicy>`] axis alone forces every call site through
2688/// an explicit `.copied()` / dereference / [`Copy`]-bound restatement
2689/// rather than the direct trait-idiomatic projection; a future generic
2690/// `<T: Copy + for<'a> Into<&'static str>>`-bound diagnostic column
2691/// that walks the `iter().map(Into::into)` shape verbatim across every
2692/// substrate-wide closed-set typed enum; the future wasm-operator's
2693/// per-child post-exit restart-decision diagnostic line that composes
2694/// the accepted-set enumeration from an iterated
2695/// `RestartPolicy::ALL.iter().map(|p| p.into())` pipe rather than a
2696/// per-arm `match p { … }` cascade; a future
2697/// `HashMap::<&'static str, RestartPolicy>::from_iter(
2698///     RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))`-style
2699/// per-policy reverse-lookup table the sibling [`TryFrom<&str>`] impl
2700/// cannot compose without this borrowed-input axis in place) reaches
2701/// the same three-arm lifted
2702/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2703/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2704/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2705/// paired owned-input [`From<RestartPolicy> for &'static str`], the
2706/// sibling [`std::fmt::Display`], [`AsRef<str>`], and
2707/// [`RestartPolicy::as_str`] surfaces already return.
2708///
2709/// Fifth peer on the substrate-wide trait-idiomatic *borrowed-input*
2710/// forward-projection family opened on [`crate::dep::DepList`]
2711/// (64aa742) and extended onto [`crate::CaixaKind`] (5ab993a),
2712/// [`crate::CaixaDialeto`] (807b0b5), and the paired
2713/// per-supervisor sibling-restart-strategy [`RestartStrategy`]
2714/// (e941836). Rust's `From` trait does not auto-derive the
2715/// `From<&Self>` sibling from a `From<Self>` impl (the blanket
2716/// `impl<T, U> From<&T> for U where T: Copy, U: From<T>` does not
2717/// exist in `core`), so every closed-set typed enum that carries the
2718/// owned-input axis but not the borrowed-input axis forces every
2719/// borrowed-input call site through a `.copied()` /
2720/// `<&'static str>::from(*policy)` / `policy.as_str()` detour whose
2721/// type bounds have no compile-time link to the substrate primitive.
2722/// [`RestartPolicy`] is the second (and second-of-two-in-M2)
2723/// OTP-shape peer to converge onto this campaign — sibling of the
2724/// paired per-supervisor [`RestartStrategy`] borrowed-input axis, so
2725/// with this lift both closed-set typed enums on the M2 `:supervisor`
2726/// slot now carry the full sibling quintet ([`std::fmt::Display`],
2727/// [`AsRef<str>`], [`Self::as_str`], `From<Self> for &'static str`,
2728/// `From<&Self> for &'static str`) plus the paired trait-idiomatic
2729/// reverse projection [`TryFrom<&str>`], closing the borrowed-input
2730/// forward-projection axis on the M2 OTP-shape slot as a unit.
2731///
2732/// Same three-path convergence discipline as the paired owned-input
2733/// impl (this borrowed-input axis, the paired owned-input
2734/// [`From<RestartPolicy> for &'static str`], and
2735/// [`RestartPolicy::as_str`] all route through the same lifted
2736/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const), so a future
2737/// variant rename or per-arm serde-attribute drift reaches every one
2738/// of the six sibling forward-projection paths
2739/// ([`std::fmt::Display`], [`AsRef<str>`], [`Self::as_str`],
2740/// [`From<Self> for &'static str`], this [`From<&Self> for &'static
2741/// str`], and the un-`rename`d [`serde::Serialize`] derive that also
2742/// emits [`Self::as_str`]'s bytes) through exactly one caixa-core
2743/// edit.
2744///
2745/// The [`RestartPolicy::as_str`] emit and [`RestartPolicy::from_wire`]
2746/// parse share the same `PascalCase` vocabulary by construction, so
2747/// the borrowed-input forward axis and the reverse axis compose
2748/// directly — the round-trip witness pin below locks this direct
2749/// composition without the intermediate wire-vocab hop the peer
2750/// [`crate::CaixaKind`] axis pair requires.
2751///
2752/// Pinned load-bearing by
2753/// [`tests::restart_policy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
2754/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2755/// three-arm emit-set via a borrowed input, plus a `const`-context
2756/// materialization witness for the `&'static str` lifetime promise,
2757/// plus a blanket `.into()` shape) and
2758/// [`tests::restart_policy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
2759/// (cross-axis partition pin against the paired owned-input
2760/// [`From<RestartPolicy> for &'static str`] impl, plus a
2761/// `.iter().map(Into::into)` pipe witness over
2762/// [`RestartPolicy::ALL`], plus a direct round-trip witness through
2763/// [`TryFrom<&str>`] that closes the two-way `&Self → &'static str →
2764/// Self` round-trip without the wire-vocab intermediate the peer
2765/// [`crate::CaixaKind`] axis pair requires).
2766impl From<&RestartPolicy> for &'static str {
2767    fn from(policy: &RestartPolicy) -> &'static str {
2768        policy.as_str()
2769    }
2770}
2771
2772/// Trait-idiomatic *owned-`String`* forward projection on the second
2773/// M2 OTP-shape closed-set typed enum ([`RestartPolicy`]) — the
2774/// owned-heap-string companion to the paired `&'static str`-returning
2775/// [`From<RestartPolicy> for &'static str`] / [`From<&RestartPolicy>
2776/// for &'static str`] impls immediately above. Routes byte-for-byte
2777/// through the substrate-primitive [`RestartPolicy::as_str`] `pub
2778/// const fn` accessor (via [`str::to_owned`]) so every consumer that
2779/// binds a [`RestartPolicy`] through the standard-library `.into()` /
2780/// [`From<Self> for String`] (equivalently [`Into<String>`]) axis — a
2781/// future `serde_json::Value::String(policy.into())` structured-payload
2782/// composer where the `Value::String` arm typing demands an owned
2783/// [`String`] and the sibling [`&'static str`]-returning axis forces
2784/// an explicit `.to_owned()` / `String::from` restatement at every
2785/// call site, a future `HashMap::<String, RestartPolicy>::from_iter(
2786/// RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))` per-policy
2787/// lookup where the map's key type is owned [`String`] rather than
2788/// [`&'static str`], a future `Cow::<'static, str>::Owned(policy.into())`
2789/// composer on the future M4 admission-webhook rejection body's
2790/// owned-arm, the future wasm-operator's per-child post-exit
2791/// diagnostic emit `serde_json::json!({ "restart": policy })` where the
2792/// JSON serializer's `Serialize` impl on [`String`] owns the emit-path
2793/// — reaches the same three-arm lifted
2794/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2795/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2796/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2797/// paired [`std::fmt::Display`], [`AsRef<str>`],
2798/// [`RestartPolicy::as_str`], and the two `&'static str`-returning
2799/// forward-projection impls already return.
2800///
2801/// Extends the trait-idiomatic *owned-`String`* forward-projection
2802/// axis onto the second-of-two M2 OTP-shape closed-set typed enums on
2803/// the caixa surface — mirror of the first-mover
2804/// [`From<RestartStrategy> for String`] (7baa18a) that opened this
2805/// axis on the sibling supervisor-level strategy enum. Rust's standard
2806/// library does not carry a blanket `impl<T: AsRef<str>> From<T> for
2807/// String` (nor an `impl<T: fmt::Display> From<T> for String`), so
2808/// every closed-set typed enum that carries the paired `AsRef<str>` /
2809/// `Display` / `From<Self> for &'static str` triple but not the
2810/// owned-[`String`] axis forces every owned-string call site through a
2811/// `.to_string()` / `.as_str().to_owned()` / `String::from(policy.as_str())`
2812/// detour whose type bounds have no compile-time link to the
2813/// substrate primitive.
2814///
2815/// Deliberately routes through the human-readable
2816/// [`RestartPolicy::as_str`] axis — for this enum the wire format
2817/// (`PascalCase`, tatara-lisp author surface `:restart Permanent`) and
2818/// the diagnostic byte-string share the same vocabulary by
2819/// construction (unlike the sibling [`crate::CaixaKind`] enum whose
2820/// two axes diverge), so the owned-[`String`] projection lands
2821/// byte-identically on both the wire vocabulary the paired
2822/// [`serde::Serialize`] derive emits and the diagnostic vocabulary the
2823/// [`RestartPolicy::as_str`] helper returns, and — because the paired
2824/// [`TryFrom<&str>`] / [`RestartPolicy::from_wire`] reverse-projection
2825/// axis parses the same `PascalCase` vocabulary — the direct two-way
2826/// `Self → String → Self` round-trip composes without the wire-vocab
2827/// intermediate hop the peer [`crate::CaixaKind`] owned-[`String`]
2828/// axis pair requires.
2829///
2830/// Pinned load-bearing by
2831/// [`tests::restart_policy_from_into_owned_string_routes_through_as_str_accessor`]
2832/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2833/// three-arm emit-set, plus a blanket `.into::<String>()` shape
2834/// witness) and
2835/// [`tests::restart_policy_from_into_owned_string_and_static_str_agree_on_every_arm`]
2836/// (cross-axis partition pin against the paired owned-input
2837/// [`From<RestartPolicy> for &'static str`] impl and the sibling
2838/// [`ToString::to_string`] surface routed through [`std::fmt::Display`],
2839/// plus a `.iter().copied().map(String::from)` pipe witness over
2840/// [`RestartPolicy::ALL`], plus a direct round-trip witness through
2841/// [`TryFrom<&str>`] on the owned-[`String`]'s [`String::as_str`]
2842/// borrow that closes the two-way `Self → String → Self` round-trip
2843/// on the trait-idiomatic owned-[`String`] forward + reverse axis
2844/// pair).
2845impl From<RestartPolicy> for String {
2846    fn from(policy: RestartPolicy) -> String {
2847        policy.as_str().to_owned()
2848    }
2849}
2850
2851/// Trait-idiomatic *borrowed-input, owned-`String` output* forward
2852/// projection on the second-of-two M2 OTP-shape closed-set typed enum
2853/// ([`RestartPolicy`]) — the fourth (and closing) corner of the
2854/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
2855/// projection family on this enum, mirror of the first-mover
2856/// [`From<&RestartStrategy> for String`] (579385f) that opened the
2857/// 2×2-completion corner on the sibling supervisor-level strategy
2858/// enum. Routes byte-for-byte through the substrate-primitive
2859/// [`RestartPolicy::as_str`] `pub const fn` accessor (via
2860/// [`str::to_owned`]) so every consumer that holds a borrowed
2861/// [`&RestartPolicy`] and needs an owned [`String`] — a future
2862/// `serde_json::Value::String(String::from(&policy))` structured-payload
2863/// composer over a borrowed field, a future `Iterator::map` over
2864/// `&[RestartPolicy]` that projects to owned keys through
2865/// `.iter().map(String::from)`, a future `HashMap::<String,
2866/// RestartPolicy>::from_iter` that keys off a borrowed-iteration axis
2867/// where dereferencing the policy would force an unnecessary `Copy` at
2868/// every step, the future wasm-operator's per-supervisor
2869/// `child_policies.iter().map(String::from).collect()` per-child post-
2870/// exit restart-decision diagnostic emit whose iteration axis is
2871/// borrowed by construction — reaches the same three-arm lifted
2872/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2873/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2874/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2875/// paired [`std::fmt::Display`], [`AsRef<str>`],
2876/// [`RestartPolicy::as_str`], and the three other trait-idiomatic
2877/// forward-projection impls
2878/// ([`From<RestartPolicy> for &'static str`],
2879/// [`From<&RestartPolicy> for &'static str`],
2880/// [`From<RestartPolicy> for String`]) already return.
2881///
2882/// Second peer on the substrate-wide trait-idiomatic *borrowed-input,
2883/// owned-`String` output* forward-projection family opened on
2884/// [`crate::supervisor::RestartStrategy`] (579385f) — closes the
2885/// `{Self, &Self} × {&'static str, String}` 2×2 projection corner on
2886/// both M2 OTP-shape sibling peers (the paired supervisor-level
2887/// sibling-restart-strategy axis and the per-child restart-decision-
2888/// policy axis), so the whole M2 OTP-shape axis pair now carries the
2889/// full four-corner family by construction. Rust's standard library
2890/// does not carry a blanket `impl<T: AsRef<str>> From<&T> for String`
2891/// (nor an `impl<T: fmt::Display> From<&T> for String`), so every
2892/// closed-set typed enum that carries the paired `AsRef<str>` /
2893/// `Display` / `From<Self> for &'static str` / `From<&Self> for
2894/// &'static str` / `From<Self> for String` quintuple but not the
2895/// borrowed-input owned-[`String`] axis forces every borrowed-input
2896/// owned-string call site through a `policy.as_str().to_owned()` /
2897/// `String::from(*policy)` (with a spurious `Copy`) /
2898/// `policy.to_string()` (through `Display`) detour whose type bounds
2899/// have no compile-time link to the substrate primitive.
2900///
2901/// Deliberately routes through the human-readable
2902/// [`RestartPolicy::as_str`] axis — for this enum the wire format
2903/// (`PascalCase`, tatara-lisp author surface `:restart Permanent`) and
2904/// the diagnostic byte-string share the same vocabulary by
2905/// construction (unlike the sibling [`crate::CaixaKind`] enum whose
2906/// two axes diverge), so the borrowed-input owned-[`String`]
2907/// projection lands byte-identically on both the wire vocabulary the
2908/// paired [`serde::Serialize`] derive emits and the diagnostic
2909/// vocabulary the [`RestartPolicy::as_str`] helper returns, and —
2910/// because the paired [`TryFrom<&str>`] / [`RestartPolicy::from_wire`]
2911/// reverse-projection axis parses the same `PascalCase` vocabulary —
2912/// the direct two-way `&Self → String → Self` round-trip composes
2913/// without the wire-vocab intermediate hop the peer
2914/// [`crate::CaixaKind`] axis pair requires.
2915///
2916/// The remaining thirteen closed-set typed enums on the caixa
2917/// substrate surface (`CaixaKind`, `CaixaDialeto`, `DepList`,
2918/// `PlacementStrategy`, `WitShape`, `RateLimitUnit`,
2919/// `PathShapeViolation`, `InvariantKind`, `ArchVerdict`, `Severity`,
2920/// `FixSafety`, `Semantic`, `FerriteRuntime`) are the future targets
2921/// of this 2×2-completion campaign — each carries the same paired
2922/// quintuple that this borrowed-input owned-[`String`] axis extends
2923/// onto.
2924///
2925/// Pinned load-bearing by
2926/// [`tests::restart_policy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
2927/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2928/// three-arm emit-set through the borrowed-input surface) and
2929/// [`tests::restart_policy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
2930/// (cross-axis partition pin against the paired owned-input owned-
2931/// [`String`] [`From<RestartPolicy> for String`] impl, the paired
2932/// borrowed-input owned-[`&'static str`] [`From<&RestartPolicy> for
2933/// &'static str`] impl, and the sibling [`ToString::to_string`]
2934/// surface routed through [`std::fmt::Display`], plus a direct round-
2935/// trip witness through [`TryFrom<&str>`] on the owned-[`String`]'s
2936/// [`String::as_str`] borrow that closes the two-way
2937/// `&Self → String → Self` round-trip on the trait-idiomatic
2938/// borrowed-input owned-[`String`] forward + reverse axis pair).
2939impl From<&RestartPolicy> for String {
2940    fn from(policy: &RestartPolicy) -> String {
2941        policy.as_str().to_owned()
2942    }
2943}
2944
2945/// Trait-idiomatic *owned-input, [`std::borrow::Cow<'static, str>`]
2946/// output* forward projection on the M2 OTP-shape per-child-restart
2947/// [`RestartPolicy`] closed-set typed enum — extends the substrate-
2948/// wide [`std::borrow::Cow<'static, str>`] forward-projection family
2949/// opened on [`crate::CaixaKind`] (99c1735 owned-input, d45c409
2950/// borrowed-input) and first extended off it onto the sibling M2
2951/// OTP-shape sibling-restart [`RestartStrategy`] (7dd28b3 owned-input,
2952/// 9b3e4b3 borrowed-input) onto the second (and second-of-two-in-M2)
2953/// M2 OTP-shape closed-set fieldless typed enum peer on the caixa
2954/// surface (`:children :restart`). Routes byte-for-byte through the
2955/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
2956/// accessor (via [`std::borrow::Cow::Borrowed`]) so every consumer
2957/// that binds a [`RestartPolicy`] through the trait-idiomatic
2958/// [`std::borrow::Cow<'static, str>`] axis — a future
2959/// `axum::response::IntoResponse` composer whose per-policy
2960/// diagnostic-body typing rules out the sibling [`AsRef<str>`]
2961/// borrowed return, a future M4 admission-webhook rejection body
2962/// that composes the accepted-policy enumeration through the same
2963/// `RestartPolicy::ALL.iter().map(Cow::from)` shape [`crate::CaixaKind`]
2964/// and [`RestartStrategy`] already route through, a generic `<T: for<'a>
2965/// Into<std::borrow::Cow<'static, str>>>`-bound structured-log
2966/// emitter on a per-child-policy diagnostic column — reaches the same
2967/// three-arm lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`]
2968/// / [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2969/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2970/// paired [`std::fmt::Display`], [`AsRef<str>`],
2971/// [`RestartPolicy::as_str`], and the four
2972/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
2973/// forward-projection corners already return.
2974///
2975/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
2976/// [`std::borrow::Cow::Owned`] — the substrate-primitive
2977/// [`RestartPolicy::as_str`] accessor's return carries the `&'static
2978/// str` lifetime by construction (each `match` arm resolves to a
2979/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const &str`
2980/// with static lifetime), so the zero-alloc borrowed arm is the
2981/// type-correct projection with no runtime allocation.
2982///
2983/// Rust's standard library carries no blanket `impl<T: AsRef<str>>
2984/// From<T> for Cow<'static, str>` (nor an `impl<T: fmt::Display>
2985/// From<T> for Cow<'static, str>`), so the paired sibling
2986/// [`From<RestartPolicy> for &'static str`] (9fb37d0),
2987/// [`From<RestartPolicy> for String`] (7851725), [`AsRef<str>`], and
2988/// [`std::fmt::Display`] surfaces do not implicitly extend to a
2989/// [`Cow<'static, str>`]-bound call site — every such site is forced
2990/// through a `Cow::Borrowed(policy.as_str())` /
2991/// `Cow::Owned(policy.to_string())` open-code whose type bounds have
2992/// no compile-time link back to the substrate primitive until this
2993/// lift.
2994///
2995/// Second peer to extend the substrate-wide trait-idiomatic
2996/// [`std::borrow::Cow<'static, str>`] forward-projection axis off the
2997/// top-level [`crate::CaixaKind`] enum (99c1735 owned-input, d45c409
2998/// borrowed-input) onto the wider substrate — closes the M2 OTP-shape
2999/// tier of the campaign (both sibling peers, `RestartStrategy` and
3000/// `RestartPolicy`, now carry the owned-input Cow<'static, str>
3001/// forward projection) so the remaining eleven peers
3002/// (`PlacementStrategy`, `RateLimitUnit`, `DepList`, `CaixaDialeto`,
3003/// and the outside-`caixa-core` peers `WitShape`, `PathShapeViolation`,
3004/// `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`,
3005/// `FerriteRuntime`) are the future targets. Every future arm addition
3006/// (an OTP-`intrinsic` fourth restart policy the ABSORPTION-ROADMAP
3007/// might reach for once the three canonical OTP restart policies stop
3008/// covering the substrate's discovered load-shape) grows the
3009/// Cow<'static, str> axis by construction through one caixa-core edit
3010/// on [`RestartPolicy::as_str`] — rather than a coordinated rewrite
3011/// across every future Cow<'static, str>-bound consumer site.
3012///
3013/// Pinned load-bearing by
3014/// [`tests::restart_policy_from_into_static_cow_str_routes_through_as_str_accessor`]
3015/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
3016/// against [`RestartPolicy::as_str`] across the three-arm
3017/// [`RestartPolicy::ALL`]) and
3018/// [`tests::restart_policy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
3019/// (cross-axis partition pin against the paired [`From<RestartPolicy>
3020/// for &'static str`], [`From<RestartPolicy> for String`], and
3021/// [`ToString`]-through-[`std::fmt::Display`] axes, plus a
3022/// `.iter().copied().map(Cow::from)` pipe witness over
3023/// [`RestartPolicy::ALL`] that materializes the three-arm accept-set
3024/// through the [`Cow<'static, str>`] axis alone and pins the
3025/// zero-alloc discipline on every element).
3026impl From<RestartPolicy> for std::borrow::Cow<'static, str> {
3027    fn from(policy: RestartPolicy) -> std::borrow::Cow<'static, str> {
3028        std::borrow::Cow::Borrowed(policy.as_str())
3029    }
3030}
3031
3032/// Trait-idiomatic *borrowed-input, [`std::borrow::Cow<'static, str>`]
3033/// output* forward projection on the M2 OTP-shape per-child-restart
3034/// [`RestartPolicy`] closed-set typed enum — the borrowed-input
3035/// companion to the paired owned-input
3036/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] impl
3037/// immediately above (0612398). Routes byte-for-byte through the same
3038/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
3039/// accessor (via [`std::borrow::Cow::Borrowed`]) so every consumer
3040/// that holds a `&RestartPolicy` and needs a
3041/// [`std::borrow::Cow<'static, str>`] — a
3042/// `RestartPolicy::ALL.iter().map(std::borrow::Cow::from).collect::<Vec<_>>()`
3043/// per-arm accept-set materializer (whose iterator over
3044/// `&'static [RestartPolicy]` yields `&RestartPolicy`, not
3045/// `RestartPolicy`, so the paired owned-input
3046/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] axis
3047/// alone forces every call site through an explicit `.copied()` /
3048/// dereference / [`Copy`]-bound restatement rather than the direct
3049/// trait-idiomatic projection), a future generic
3050/// `<T: for<'a> Into<std::borrow::Cow<'static, str>>>`-bound emitter
3051/// on a per-child-policy diagnostic column that walks the
3052/// `iter().map(Into::into)` shape verbatim, the future M4 admission-
3053/// webhook rejection body that composes the accepted-policy
3054/// enumeration from an iterated
3055/// `RestartPolicy::ALL.iter().map(|p| p.into())` pipe rather than a
3056/// per-arm `match p { … }` cascade — reaches the same three-arm
3057/// lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
3058/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
3059/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
3060/// paired [`std::fmt::Display`], [`AsRef<str>`],
3061/// [`RestartPolicy::as_str`], the four
3062/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
3063/// forward-projection corners, and the paired owned-input
3064/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] impl
3065/// already return.
3066///
3067/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
3068/// [`std::borrow::Cow::Owned`] — the substrate-primitive
3069/// [`RestartPolicy::as_str`] accessor's return carries the
3070/// `&'static str` lifetime by construction (each `match` arm resolves
3071/// to a [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const &str`
3072/// with static lifetime), so the zero-alloc borrowed arm is the
3073/// type-correct projection with no runtime allocation.
3074///
3075/// Closes the `{Self, &Self}` input-shape corner on the M2 OTP-shape
3076/// per-child-restart [`std::borrow::Cow<'static, str>`] axis opened
3077/// one commit prior (0612398) on the paired owned-input
3078/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] impl —
3079/// second-of-two-in-M2 closed-set fieldless typed enum peer on the
3080/// caixa surface (paired with the sibling-restart [`RestartStrategy`]
3081/// which carries both {Self, &Self} × Cow<'static, str> corners since
3082/// 7dd28b3 owned-input, 9b3e4b3 borrowed-input), exactly as d45c409
3083/// closed it on the top-level [`crate::CaixaKind`] one commit after
3084/// the owning half (99c1735) landed. This lift closes the whole M2
3085/// OTP-shape tier of the substrate-wide [`Cow<'static, str>`]
3086/// forward-projection campaign on both input-shape corners
3087/// ({Self, &Self}) of both M2 OTP-shape sibling peers
3088/// ([`RestartStrategy`] and [`RestartPolicy`]), so the remaining
3089/// eleven substrate-wide peers (`PlacementStrategy`, `RateLimitUnit`,
3090/// `DepList`, `CaixaDialeto`, `WitShape`, `PathShapeViolation`,
3091/// `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`,
3092/// `FerriteRuntime`) become the future targets of the campaign. Rust's
3093/// standard library does not carry a blanket
3094/// `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor an
3095/// `impl<T: fmt::Display> From<&T> for Cow<'static, str>`), so every
3096/// closed-set fieldless typed enum peer on the substrate that carries
3097/// the paired owned-input [`Cow<'static, str>`] axis but not the
3098/// borrowed-input axis forces every borrowed-input
3099/// [`Cow<'static, str>`]-parameterized call site through a spurious
3100/// [`Copy`] deref (`std::borrow::Cow::from(*policy)`) or a
3101/// `std::borrow::Cow::Borrowed(policy.as_str())` open-code whose type
3102/// bounds have no compile-time link to the substrate primitive.
3103///
3104/// Pinned load-bearing by
3105/// [`tests::restart_policy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor`]
3106/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
3107/// against [`RestartPolicy::as_str`] across the three-arm
3108/// [`RestartPolicy::ALL`] through the borrowed-input surface) and
3109/// [`tests::restart_policy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
3110/// (cross-axis partition pin against the paired owned-input
3111/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`], the
3112/// paired borrowed-input owned-`&'static str`
3113/// [`From<&RestartPolicy> for &'static str`], and the paired
3114/// borrowed-input owned-`String` [`From<&RestartPolicy> for String`]
3115/// impls, plus a `.iter().map(std::borrow::Cow::from)` pipe witness
3116/// over [`RestartPolicy::ALL`] — whose iterator yields
3117/// `&RestartPolicy` by construction, so the borrowed-input
3118/// [`Cow<'static, str>`] axis is what routes the pipe through the
3119/// substrate-primitive [`RestartPolicy::as_str`] accessor with the
3120/// zero-alloc [`Cow::Borrowed`] arm by construction and without a
3121/// spurious [`Copy`] deref).
3122impl From<&RestartPolicy> for std::borrow::Cow<'static, str> {
3123    fn from(policy: &RestartPolicy) -> std::borrow::Cow<'static, str> {
3124        std::borrow::Cow::Borrowed(policy.as_str())
3125    }
3126}
3127
3128/// Trait-idiomatic *owned-input, [`Box<str>`] output* forward
3129/// projection on the M2 OTP-shape per-child-restart [`RestartPolicy`]
3130/// closed-set fieldless typed enum — extends the substrate-wide
3131/// `Box<str>` forward-projection campaign tier opened one commit prior
3132/// (69ef45c) on the paired sibling-restart [`RestartStrategy`] onto
3133/// the second (and third-and-final) M2 OTP-shape closed-set fieldless
3134/// typed enum peer on the caixa surface (`:children :restart`),
3135/// immediately after the paired `Cow<'static, str>` axis (0612398 /
3136/// b4dc55c) closed the
3137/// `{Self, &Self} × {&'static str, String, Cow<'static, str>}` 2×3
3138/// corner on this enum. Routes byte-for-byte through the
3139/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
3140/// accessor via [`Box::<str>::from`] on the returned `&'static str`,
3141/// so every consumer that binds a
3142/// `let key: Box<str> = policy.into();`-shaped call site — a
3143/// per-child metric-key materializer that stashes the policy
3144/// discriminator in a `Box<str>`-typed heap-owned scalar for cheap
3145/// clone (a shared-nothing per-policy accept-set the `caixa-operator`
3146/// hierarchical reconciliation scheduler's per-child restart-decision
3147/// fan-out carries), a future admission-webhook rejection body whose
3148/// per-arm `Box<str>` field composes from an owned `RestartPolicy`
3149/// handle — reaches the same three-arm lifted
3150/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
3151/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
3152/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
3153/// sibling
3154/// `{Self, &Self} × {&'static str, String, Cow<'static, str>}`
3155/// forward-projection corner already returns. Rust's standard library
3156/// carries `impl From<&str> for Box<str>` and
3157/// `impl From<String> for Box<str>` but no blanket
3158/// `impl<T: AsRef<str>> From<T> for Box<str>` (nor any
3159/// `impl<T: Copy, U: From<T>> From<T> for U` route from the enum), so
3160/// this axis is a distinct trait-idiomatic surface that a downstream
3161/// `RestartPolicy → Box<str>` `.into()` reaches through this impl and
3162/// no other — without a `Box::from(policy.as_str())` open-code whose
3163/// type bounds have no compile-time link back to the substrate
3164/// primitive.
3165///
3166/// Second peer on the substrate-wide trait-idiomatic [`Box<str>`]
3167/// forward-projection family opened on the sibling-restart
3168/// [`RestartStrategy`] (69ef45c / 59ae5dc) — closes the whole M2
3169/// OTP-shape tier of the substrate-wide [`Box<str>`] forward-
3170/// projection campaign's owned-input corner on both M2 OTP-shape
3171/// sibling peers ([`RestartStrategy`] and [`RestartPolicy`]), the
3172/// paired borrowed-input `From<&RestartPolicy> for Box<str>` closer
3173/// and the remaining fieldless-enum peers on the M3 mesh-shape /
3174/// outside-M3 caixa-core / render-side / outside-caixa-core tiers
3175/// are the future targets of the campaign.
3176///
3177/// Pinned load-bearing by
3178/// [`tests::restart_policy_from_into_box_str_routes_through_as_str_accessor`]
3179/// (byte-parity pin against [`RestartPolicy::as_str`] across the
3180/// three-arm [`RestartPolicy::ALL`] emit-set on the owned-input
3181/// surface, plus a blanket-derived [`Into`] shape witness).
3182impl From<RestartPolicy> for Box<str> {
3183    fn from(policy: RestartPolicy) -> Box<str> {
3184        Box::<str>::from(policy.as_str())
3185    }
3186}
3187
3188/// Trait-idiomatic *borrowed-input, [`Box<str>`] output* forward
3189/// projection on the M2 OTP-shape per-child-restart [`RestartPolicy`]
3190/// closed-set fieldless typed enum — the borrowed-input companion to
3191/// the paired owned-input [`From<RestartPolicy> for Box<str>`] impl
3192/// (0a1b313, one commit prior) that closes the `{Self, &Self}`
3193/// input-shape corner of the substrate-wide [`Box<str>`] forward-
3194/// projection axis on the second (and third-and-final) M2 OTP-shape
3195/// closed-set fieldless typed enum peer on the caixa surface
3196/// (`:children :restart`), routing byte-for-byte through the
3197/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
3198/// accessor via [`Box::<str>::from`] on the returned `&'static str`.
3199/// Every consumer that holds a `&RestartPolicy` and needs a
3200/// [`Box<str>`] — a
3201/// `RestartPolicy::ALL.iter().map(Box::<str>::from).collect::<Vec<_>>()`
3202/// per-arm accept-set materializer (whose iterator over
3203/// `&'static [RestartPolicy]` yields `&RestartPolicy`, not
3204/// `RestartPolicy`, so the paired owned-input
3205/// [`From<RestartPolicy> for Box<str>`] axis alone forces every
3206/// call site through an explicit [`Copy`] deref or a
3207/// `.copied()` restatement rather than the direct trait-idiomatic
3208/// projection), a per-child metric-key materializer holding
3209/// `&RestartPolicy` through a `caixa-operator` hierarchical
3210/// reconciliation scheduler's borrow lifetime, a future admission-
3211/// webhook rejection body whose per-arm `Box<str>` field composes
3212/// from a borrowed `&RestartPolicy` handle — reaches the
3213/// substrate-primitive [`RestartPolicy::as_str`] accessor through
3214/// this impl and no other, without a
3215/// `Box::<str>::from(policy.as_str())` open-code whose type bounds
3216/// have no compile-time link back to the substrate primitive.
3217///
3218/// Rust's standard library carries `impl From<&str> for Box<str>`
3219/// and `impl From<String> for Box<str>` but no blanket
3220/// `impl<T: AsRef<str>> From<&T> for Box<str>` (nor a
3221/// `Copy`-based `impl<T: Copy, U: From<&T> for U`), so every closed-
3222/// set fieldless typed enum peer on the substrate that carries the
3223/// paired owned-input `Box<str>` axis but not the borrowed-input
3224/// axis forces every borrowed-input `Box<str>`-parameterized call
3225/// site through a spurious [`Copy`] deref
3226/// (`Box::<str>::from((*policy).as_str())`) or a
3227/// `Box::<str>::from(policy.as_str())` open-code whose type bounds
3228/// have no compile-time link back to the substrate primitive.
3229///
3230/// Fourth (and closing) peer on the substrate-wide trait-idiomatic
3231/// [`Box<str>`] forward-projection family on the M2 OTP-shape tier
3232/// — closes the whole `{Self, &Self}` input-shape corner of the
3233/// [`Box<str>`] axis on both M2 OTP-shape sibling peers
3234/// ([`RestartStrategy`] and [`RestartPolicy`]), exactly as b4dc55c
3235/// closed the paired [`Cow<'static, str>`] axis one commit after
3236/// its owning half (0612398) landed on this enum. The remaining
3237/// fieldless-enum peers on the M3 mesh-shape / outside-M3 caixa-
3238/// core / render-side / outside-caixa-core tiers are the future
3239/// targets of the [`Box<str>`] campaign.
3240///
3241/// Pinned load-bearing by
3242/// [`tests::restart_policy_from_borrowed_into_box_str_routes_through_as_str_accessor`]
3243/// (byte-parity pin against [`RestartPolicy::as_str`] across the
3244/// three-arm [`RestartPolicy::ALL`] emit-set on the borrowed-input
3245/// surface, plus a blanket-derived [`Into`] shape witness, a
3246/// cross-axis partition pin against the paired owned-input
3247/// [`From<RestartPolicy> for Box<str>`] and the sibling borrowed-
3248/// input `{&'static str, String, Cow<'static, str>}` return-shape
3249/// axes, and a `.iter().map(Box::<str>::from)` pipe witness over
3250/// [`RestartPolicy::ALL`] — whose iterator yields `&RestartPolicy`
3251/// by construction, so the borrowed-input [`Box<str>`] axis is
3252/// what routes the pipe through the substrate-primitive
3253/// [`RestartPolicy::as_str`] accessor without a spurious [`Copy`]
3254/// deref).
3255impl From<&RestartPolicy> for Box<str> {
3256    fn from(policy: &RestartPolicy) -> Box<str> {
3257        Box::<str>::from(policy.as_str())
3258    }
3259}
3260
3261/// Trait-idiomatic *owned-input, [`std::sync::Arc<str>`] output*
3262/// forward projection on the M2 OTP-shape per-child-restart
3263/// [`RestartPolicy`] closed-set fieldless typed enum — routes byte-
3264/// for-byte through the substrate-primitive [`RestartPolicy::as_str`]
3265/// `pub const fn` accessor via [`std::sync::Arc::<str>::from`] on the
3266/// returned `&'static str`, so every consumer that binds a
3267/// [`RestartPolicy`] through the standard-library `.into()` /
3268/// [`From<Self> for std::sync::Arc<str>`] (equivalently
3269/// [`Into<std::sync::Arc<str>>`]) axis — a future admission-webhook's
3270/// per-request `Sync` + `Send`-safe structured-log field composed
3271/// across an `.await` boundary through a
3272/// `<T: Into<std::sync::Arc<str>>>`-bound diagnostic-column dispatch,
3273/// a future wasm-operator's per-child post-exit restart-decision
3274/// pipeline holding a shared-ownership per-arm cache key, a
3275/// `<T: Into<std::sync::Arc<str>>>`-bound `tracing`-span attributes
3276/// collector recording a per-child-policy field onto the parent
3277/// span's shared-ownership context — reaches the same three-arm
3278/// lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
3279/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
3280/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
3281/// sibling
3282/// `{Self, &Self} × {&'static str, String, Cow<'static, str>, Box<str>}`
3283/// forward-projection corner already returns.
3284///
3285/// Second peer on the substrate-wide trait-idiomatic
3286/// [`std::sync::Arc<str>`] forward-projection family opened one
3287/// projection tier prior (bca2ec8) on the paired sibling-restart
3288/// [`RestartStrategy`] owned-input first-mover — extends the tier
3289/// onto the second (and third-and-final) M2 OTP-shape closed-set
3290/// fieldless typed enum peer on the caixa surface
3291/// (`:children :restart`), immediately after the paired [`Box<str>`]
3292/// axis (0a1b313 / cb1d068) closed the whole
3293/// `{Self, &Self} × {&'static str, String, Cow<'static, str>, Box<str>}`
3294/// 2×4 corner on this enum. Rust's standard library carries
3295/// `impl From<&str> for std::sync::Arc<str>` and
3296/// `impl From<String> for std::sync::Arc<str>` but no blanket
3297/// `impl<T: AsRef<str>> From<T> for std::sync::Arc<str>` (nor an
3298/// `impl<T: fmt::Display> From<T> for std::sync::Arc<str>`), so this
3299/// axis is a distinct trait-idiomatic surface that a
3300/// `let key: std::sync::Arc<str> = policy.into();`-shaped call site
3301/// reaches through this impl and no other — a paired
3302/// `std::sync::Arc::<str>::from(policy.as_str())` open-code has no
3303/// compile-time link back to the substrate primitive, and a two-step
3304/// `std::sync::Arc::<str>::from(String::from(policy))` composition
3305/// through the owned-`String` axis allocates twice (once into the
3306/// intermediate `String`, once into the [`Arc<str>`] on the
3307/// `From<String>` conversion) where the single-step trait impl
3308/// allocates once.
3309///
3310/// Peer of the sibling [`Box<str>`] second-tier extender (0a1b313) —
3311/// same "extends the substrate-wide projection tier onto the next
3312/// M2 OTP-shape peer" discipline, extended onto the
3313/// [`std::sync::Arc<str>`] axis whose shared-ownership + [`Sync`] +
3314/// [`Send`] contract is the distinct value the [`Box<str>`] axis's
3315/// owned-move return-shape cannot provide.
3316///
3317/// Pinned load-bearing by
3318/// [`tests::restart_policy_from_into_arc_str_routes_through_as_str_accessor`]
3319/// (byte-parity pin against [`RestartPolicy::as_str`] across the
3320/// three-arm [`RestartPolicy::ALL`] emit-set on the owned-input
3321/// surface, plus a blanket-derived [`Into`] shape witness and cross-
3322/// axis byte-parity pins against the sibling owned-input
3323/// `{&'static str, String, Cow<'static, str>, Box<str>}` return-shape
3324/// axes).
3325impl From<RestartPolicy> for std::sync::Arc<str> {
3326    fn from(policy: RestartPolicy) -> std::sync::Arc<str> {
3327        std::sync::Arc::<str>::from(policy.as_str())
3328    }
3329}
3330
3331/// Trait-idiomatic *borrowed-input, [`std::sync::Arc<str>`] output*
3332/// forward projection on the M2 OTP-shape per-child-restart
3333/// [`RestartPolicy`] closed-set fieldless typed enum — closes the
3334/// `{Self, &Self}` input-shape corner of the [`std::sync::Arc<str>`]
3335/// forward-projection axis on the second (and third-and-final) M2
3336/// OTP-shape closed-set fieldless typed enum peer on the caixa
3337/// surface (`:children :restart`), companion to the paired
3338/// owned-input [`From<RestartPolicy> for std::sync::Arc<str>`] impl
3339/// one commit prior (b05724e). Routes byte-for-byte through the
3340/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
3341/// accessor (via [`std::sync::Arc::<str>::from`] on the returned
3342/// `&'static str`), so every consumer that binds a
3343/// [`&RestartPolicy`] through the standard-library `.into()` /
3344/// [`From<&Self> for std::sync::Arc<str>`] (equivalently
3345/// [`Into<std::sync::Arc<str>>`]) axis — a future admission-webhook's
3346/// per-request borrowed-`&RestartPolicy` handle rendering a per-arm
3347/// `Sync` + `Send`-safe structured-log field across an `.await`
3348/// boundary through a `<T: Into<std::sync::Arc<str>>>`-bound
3349/// diagnostic-column dispatch, a future wasm-operator's per-child
3350/// post-exit restart-decision pipeline whose
3351/// `.iter().map(std::sync::Arc::<str>::from)` collector reaches
3352/// into the shared-ownership per-arm key without a spurious [`Copy`]
3353/// deref (which would only be reachable through the owned-input
3354/// [`From<RestartPolicy> for std::sync::Arc<str>`] axis by first
3355/// calling `.copied()` on the iterator), a future
3356/// `<T: Into<std::sync::Arc<str>>>`-bound `tracing`-span attributes
3357/// collector recording a borrowed-`&RestartPolicy` per-arm field
3358/// onto the parent span's shared-ownership context — reaches the
3359/// same three-arm lifted
3360/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
3361/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
3362/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
3363/// paired owned-input [`From<RestartPolicy> for std::sync::Arc<str>`]
3364/// impl and the sibling `{&'static str, String, Cow<'static, str>,
3365/// Box<str>}` forward-projection corner already return.
3366///
3367/// Closes the substrate-wide trait-idiomatic
3368/// [`std::sync::Arc<str>`] forward-projection family opened one
3369/// commit prior (b05724e) on the paired owned-input
3370/// [`From<RestartPolicy> for std::sync::Arc<str>`] impl — closes
3371/// the `{Self, &Self}` input-shape corner of the
3372/// [`std::sync::Arc<str>`] axis on the second (and third-and-final)
3373/// M2 OTP-shape closed-set fieldless typed enum peer on the caixa
3374/// surface, exactly as b3e72d7 closed the paired
3375/// [`std::sync::Arc<str>`] corner on the sibling-restart
3376/// [`RestartStrategy`] first-mover one commit after its owning half
3377/// (bca2ec8) landed, and as cb1d068 closed the paired [`Box<str>`]
3378/// corner on this enum one commit after its owning half (0a1b313)
3379/// landed. Rust's standard library carries `impl From<&str> for
3380/// std::sync::Arc<str>` and `impl From<String> for
3381/// std::sync::Arc<str>` but no blanket `impl<T: AsRef<str>> From<&T>
3382/// for std::sync::Arc<str>` (nor a `Copy`-based `impl<T: Copy,
3383/// U: From<T>> From<&T> for U`), so every closed-set fieldless typed
3384/// enum peer on the substrate that carries the paired owned-input
3385/// [`std::sync::Arc<str>`] axis but not the borrowed-input axis
3386/// forces every borrowed-input [`std::sync::Arc<str>`]-parameterized
3387/// call site through a spurious [`Copy`] deref
3388/// (`std::sync::Arc::<str>::from((*policy).as_str())`) or a
3389/// `std::sync::Arc::<str>::from(policy.as_str())` open-code whose
3390/// type bounds have no compile-time link back to the substrate
3391/// primitive.
3392///
3393/// Pinned load-bearing by
3394/// [`tests::restart_policy_from_borrowed_into_arc_str_routes_through_as_str_accessor`]
3395/// (byte-parity pin against [`RestartPolicy::as_str`] across the
3396/// three-arm [`RestartPolicy::ALL`] emit-set on the borrowed-input
3397/// surface, plus a blanket-derived [`Into`] shape witness, a
3398/// cross-axis pin against the paired owned-input
3399/// [`From<RestartPolicy> for std::sync::Arc<str>`] and the sibling
3400/// borrowed-input `{&'static str, String, Cow<'static, str>,
3401/// Box<str>}` return-shape axes, and a
3402/// `.iter().map(std::sync::Arc::<str>::from)` pipe witness over
3403/// [`RestartPolicy::ALL`]).
3404impl From<&RestartPolicy> for std::sync::Arc<str> {
3405    fn from(policy: &RestartPolicy) -> std::sync::Arc<str> {
3406        std::sync::Arc::<str>::from(policy.as_str())
3407    }
3408}
3409
3410/// Trait-idiomatic *owned-input, [`std::rc::Rc<str>`] output* forward
3411/// projection on the M2 OTP-shape per-child-restart [`RestartPolicy`]
3412/// closed-set fieldless typed enum — the single-threaded reference-
3413/// counted peer of the paired owned-input
3414/// [`From<RestartPolicy> for std::sync::Arc<str>`] impl (b05724e) on the
3415/// sibling atomically-reference-counted [`std::sync::Arc<str>`] axis.
3416/// Routes byte-for-byte through the substrate-primitive
3417/// [`RestartPolicy::as_str`] `pub const fn` accessor via
3418/// [`std::rc::Rc::<str>::from`] on the returned `&'static str`.
3419///
3420/// Rust's standard library carries `impl From<&str> for std::rc::Rc<str>`
3421/// and `impl From<String> for std::rc::Rc<str>` but no blanket
3422/// `impl<T: AsRef<str>> From<T> for std::rc::Rc<str>` (nor a `From<&T>`
3423/// blanket), and the [`std::sync::Arc<str>`] and [`std::rc::Rc<str>`]
3424/// trait tables are disjoint — so a single-threaded caixa-operator
3425/// reconciliation pass that shares the `:children :restart` wire
3426/// byte-string across intra-reconcile-loop tree nodes through the cheaper
3427/// non-atomic [`std::rc::Rc<str>`] refcount (the atomically-reference-
3428/// counted [`std::sync::Arc<str>`] return-shape cannot provide within a
3429/// single-threaded reconciliation pass without paying the atomic-fence
3430/// cost the [`std::rc::Rc<str>`] axis skips by construction) reaches
3431/// the substrate primitive through this impl and no other.
3432///
3433/// Closes the substrate-wide trait-idiomatic [`std::rc::Rc<str>`]
3434/// forward-projection axis on the M2-OTP-shape `:supervisor
3435/// :estrategia` and `:children :restart` slot pair the sibling-restart
3436/// [`RestartStrategy`] first-mover (71ad8f4) opened one projection tier
3437/// prior on the paired sibling enum — closes the paired axis on the
3438/// second (and third-and-final) M2 OTP-shape closed-set fieldless typed
3439/// enum peer on the caixa surface, matching the discipline the paired
3440/// [`std::sync::Arc<str>`] forward-projection axis campaign already
3441/// carried across the same slot pair (bca2ec8 → b3e72d7 on
3442/// [`RestartStrategy`]; b05724e → borrowed-close on this enum).
3443///
3444/// Pinned load-bearing by
3445/// [`tests::restart_policy_from_into_rc_str_routes_through_as_str_accessor`]
3446/// (byte-parity pin against [`RestartPolicy::as_str`] across the
3447/// three-arm [`RestartPolicy::ALL`] emit-set on the owned-input
3448/// surface, plus a blanket-derived [`Into`] shape witness and cross-
3449/// axis byte-parity pins against the sibling owned-input `{&'static
3450/// str, String, Cow<'static, str>, Box<str>, std::sync::Arc<str>}`
3451/// return-shape axes).
3452impl From<RestartPolicy> for std::rc::Rc<str> {
3453    fn from(policy: RestartPolicy) -> std::rc::Rc<str> {
3454        std::rc::Rc::<str>::from(policy.as_str())
3455    }
3456}
3457
3458/// Trait-idiomatic *borrowed-input, [`std::rc::Rc<str>`] output* forward
3459/// projection on the M2 OTP-shape per-child-restart [`RestartPolicy`]
3460/// closed-set fieldless typed enum — the borrowed-input companion to
3461/// the paired owned-input [`From<RestartPolicy> for std::rc::Rc<str>`]
3462/// impl immediately above, closing the `{Self, &Self}` input-shape
3463/// corner of the [`std::rc::Rc<str>`] axis on the second (and third-
3464/// and-final) M2 OTP-shape closed-set fieldless typed enum peer on the
3465/// caixa surface. Routes byte-for-byte through the substrate-primitive
3466/// [`RestartPolicy::as_str`] `pub const fn` accessor via
3467/// [`std::rc::Rc::<str>::from`] on the returned `&'static str`, so a
3468/// `RestartPolicy::ALL.iter().map(std::rc::Rc::<str>::from)`-shaped
3469/// pipe (whose iterator over `&'static [RestartPolicy]` yields
3470/// `&RestartPolicy` by construction) reaches the same three-arm lifted
3471/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
3472/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
3473/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const roster
3474/// the paired owned-input axis and the sibling `{Self, &Self} ×
3475/// {&'static str, String, Cow<'static, str>, Box<str>,
3476/// std::sync::Arc<str>}` forward-projection corner already return.
3477///
3478/// Rust's standard library carries no blanket
3479/// `impl<T: AsRef<str>> From<&T> for std::rc::Rc<str>` (nor a `Copy`-
3480/// based `impl<T: Copy, U: From<T>> From<&T> for U`), so this borrowed-
3481/// input axis is a distinct trait-idiomatic surface — without it, the
3482/// `.iter().map(std::rc::Rc::<str>::from)` pipe would force a spurious
3483/// [`Copy`] deref or a `.copied()` restatement whose type bounds have
3484/// no compile-time link back to the substrate primitive.
3485///
3486/// Closes the substrate-wide trait-idiomatic [`std::rc::Rc<str>`]
3487/// forward-projection family on the M2-OTP-shape `:supervisor
3488/// :estrategia` + `:children :restart` slot pair — the sibling
3489/// [`RestartStrategy`] first-mover (71ad8f4) opened + closed the pair
3490/// on the sibling `:supervisor :estrategia` half one projection tier
3491/// prior, and the paired owned-input [`From<RestartPolicy> for
3492/// std::rc::Rc<str>`] impl immediately above opens the same axis on
3493/// this half — this borrowed-input impl closes it.
3494///
3495/// Pinned load-bearing by
3496/// [`tests::restart_policy_from_borrowed_into_rc_str_routes_through_as_str_accessor`]
3497/// (byte-parity pin against [`RestartPolicy::as_str`] across the
3498/// three-arm [`RestartPolicy::ALL`] emit-set on the borrowed-input
3499/// surface, plus a blanket-derived [`Into`] shape witness, a cross-
3500/// axis partition pin against the paired owned-input
3501/// [`From<RestartPolicy> for std::rc::Rc<str>`] and the sibling
3502/// borrowed-input `{&'static str, String, Cow<'static, str>, Box<str>,
3503/// std::sync::Arc<str>}` return-shape axes, and a
3504/// `.iter().map(std::rc::Rc::<str>::from)` pipe witness over
3505/// [`RestartPolicy::ALL`] that resolves through the borrowed-input
3506/// axis without a spurious [`Copy`] deref).
3507impl From<&RestartPolicy> for std::rc::Rc<str> {
3508    fn from(policy: &RestartPolicy) -> std::rc::Rc<str> {
3509        std::rc::Rc::<str>::from(policy.as_str())
3510    }
3511}
3512
3513/// Trait-idiomatic byte-view surface on the per-child restart-decision
3514/// policy typed enum.
3515///
3516/// Every consumer that binds its input through the standard-library
3517/// [`AsRef<[u8]>`] trait bound — a byte-keyed
3518/// `HashMap<K: AsRef<[u8]>, V>` per-policy reconciliation-decision
3519/// table lookup on the future wasm-operator supervisor scheduler; a
3520/// `blake3::Hasher::update` / `ring::digest::Context::update` /
3521/// `sha2::Sha256::update` byte-input surface on any future per-child
3522/// content-address digest folded into the [`crate::Lacre`] closure so
3523/// downstream cache-keys partition on the three OTP restart policies
3524/// (`Permanent`, `Temporary`, `Transient`) at content-address time; an
3525/// `std::io::Write::write_all`-bound structured-log per-arm byte-sink —
3526/// reaches the substrate primitive through one trait dispatch rather
3527/// than open-coding the two-hop `restart.as_str().as_bytes()`
3528/// composition at every call site. Routed byte-for-byte through the
3529/// [`RestartPolicy::as_str`] `pub const fn` accessor the paired
3530/// str-view ([`AsRef<str>`], [`std::fmt::Display`],
3531/// [`RestartPolicy::as_str`]) and the five reverse-projection
3532/// (`&'static str`, `String`, `Cow<'static, str>`, `Box<str>`,
3533/// `std::sync::Arc<str>`) return-shape axes already resolve through,
3534/// so any future divergence between the byte-view and str-view axes
3535/// trips at caixa-core test time rather than at a downstream byte-
3536/// consumer's silent split.
3537///
3538/// Peer of the sibling per-supervisor-restart-strategy axis
3539/// [`AsRef<[u8]> for RestartStrategy`] (cd4c4e0, the first M2-OTP-
3540/// shape supervisor slot enum to open this axis) — the sixth
3541/// closed-set fieldless typed enum on the caixa surface to converge
3542/// onto the trait-idiomatic byte-view discipline, and the second (and
3543/// final) M2-OTP-shape sibling to pick it up, closing the byte-view
3544/// axis across the paired `:supervisor :estrategia` +
3545/// `:children :restart` M2 slot pair. Pin load-bearing by the paired
3546/// [`tests::restart_policy_as_ref_bytes_routes_through_as_str_accessor`]
3547/// (fail-before-pass-after byte-parity pin against
3548/// [`RestartPolicy::as_str`] `.as_bytes()` across the three-arm
3549/// [`RestartPolicy::ALL`] emit-set, cross-axis witness against the
3550/// paired str-view [`AsRef<str>`] / [`std::fmt::Display`] /
3551/// [`RestartPolicy::as_str`] axes' `.as_bytes()` byte-tails,
3552/// cross-axis witness against the paired reverse-projection
3553/// `{&'static str, String, Cow<'static, str>, Box<str>,
3554/// std::sync::Arc<str>}` return-shape axes' `.as_bytes()` byte-tails,
3555/// a `<T: AsRef<[u8]>>`-bound-consumer witness that a generic
3556/// byte-input function accepts a [`RestartPolicy`] directly through
3557/// the trait bound, and a `blake3::Hasher::update`-shape byte-input
3558/// surface witness routed through the `<T: AsRef<[u8]>>`-bound
3559/// consumer axis to reach the caixa-lacre compounding target). Any
3560/// future silent detour that routes the byte-view impl off the
3561/// substrate-primitive [`RestartPolicy::as_str`] accessor (a per-arm
3562/// inline `b"Permanent".as_slice()`-shaped re-inlining that opens a
3563/// compile-time link to the un-lifted arm-literal, a swap onto the
3564/// kebab-case [`gen_platform::Discriminant`] catalog identity that
3565/// would collide the wire axis with the dispatcher-catalog axis) trips
3566/// at caixa-core test time rather than at a downstream byte-consumer's
3567/// silent split.
3568impl AsRef<[u8]> for RestartPolicy {
3569    fn as_ref(&self) -> &[u8] {
3570        self.as_str().as_bytes()
3571    }
3572}
3573
3574/// Trait-idiomatic *owned-input, owned-`Vec<u8>` output* byte-owned
3575/// reverse projection on the second (and final) M2 OTP-shape closed-set
3576/// fieldless typed enum peer on the caixa surface ([`RestartPolicy`]) —
3577/// the byte-mirror of the [`From<RestartPolicy> for String`] str-owned
3578/// reverse-projection axis and the owned-`Vec<u8>` reverse-projection
3579/// sibling of the paired [`AsRef<[u8]>`] borrowed byte-view axis
3580/// (98b08fa) lifted on this same enum. Routes byte-for-byte through
3581/// the substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
3582/// accessor via [`str::as_bytes`] + [`slice::to_vec`] so every
3583/// consumer that binds a [`RestartPolicy`] through the standard-
3584/// library `impl From<RestartPolicy> for Vec<u8>` axis
3585/// (equivalently `<T: Into<Vec<u8>>>`) — a future
3586/// [`std::io::Write::write_all`]-shape per-child audit-log byte-sink
3587/// whose input parameter is an owned [`Vec<u8>`] payload, a future
3588/// `bytes::Bytes::from(Vec::<u8>::from(restart))` composer folding
3589/// the per-arm restart-decision-policy byte-tag into the
3590/// [`bytes::Bytes`] framing surface, a future
3591/// `hasher.update(&Vec::<u8>::from(restart))`-shape BLAKE3 content-
3592/// address closure that needs the owned byte-tail buffered before
3593/// folding into the [`crate::Lacre`] closure body, a future per-child
3594/// protobuf/CBOR/msgpack payload composer whose framer takes an owned
3595/// [`Vec<u8>`] rather than a borrowed byte-slice — reaches the
3596/// substrate primitive through one trait dispatch rather than an
3597/// open-coded per-call-site `restart.as_str().as_bytes().to_vec()`
3598/// composition whose type bounds have no compile-time link back to
3599/// the substrate primitive.
3600///
3601/// Closes the substrate-wide trait-idiomatic byte-owned reverse-
3602/// projection axis on the M2-OTP-shape `:supervisor :estrategia` +
3603/// `:children :restart` slot pair the sibling
3604/// [`RestartStrategy`] first-mover (63e5dd0) opened one commit prior,
3605/// matching the discipline the paired [`AsRef<[u8]>`] borrowed byte-
3606/// view axis campaign already carried across the same slot pair
3607/// (cd4c4e0 → 98b08fa). Every future arm addition (an OTP-
3608/// `intrinsic` fourth arm the theory
3609/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
3610/// might reach for once the three canonical OTP restart policies
3611/// stop covering the substrate's discovered load-shape) grows the
3612/// byte-owned axis through one edit on the substrate-primitive
3613/// [`RestartPolicy::as_str`] accessor.
3614///
3615/// Pinned load-bearing by
3616/// [`tests::restart_policy_from_into_owned_vec_bytes_routes_through_as_str_accessor`]
3617/// (byte-parity pin against [`RestartPolicy::as_str`] across the
3618/// three-arm [`RestartPolicy::ALL`] emit-set binding the byte-owned
3619/// reverse-projection axis against the paired [`AsRef<[u8]>`]
3620/// borrowed byte-view axis and the str-owned reverse-projection
3621/// family (`String`, `Cow<'static, str>`, `Box<str>`,
3622/// `std::sync::Arc<str>`) `.into_bytes()` / `.as_bytes().to_vec()`
3623/// byte-tails, a `<T: Into<Vec<u8>>>`-bound generic-consumer witness,
3624/// and a `std::io::Write::write_all`-shape owned-byte-sink surface
3625/// witness on both owned and borrowed input shapes).
3626impl From<RestartPolicy> for Vec<u8> {
3627    fn from(policy: RestartPolicy) -> Vec<u8> {
3628        policy.as_str().as_bytes().to_vec()
3629    }
3630}
3631
3632/// Trait-idiomatic *borrowed-input, owned-`Vec<u8>` output* byte-
3633/// owned reverse projection on the second (and final) M2 OTP-shape
3634/// closed-set fieldless typed enum peer on the caixa surface
3635/// ([`RestartPolicy`]) — the borrowed-input peer of
3636/// [`From<RestartPolicy> for Vec<u8>`], closing the
3637/// `{Self, &Self} → Vec<u8>` pair on the byte-owned reverse-projection
3638/// axis in one lift. Routes byte-for-byte through the substrate-
3639/// primitive [`RestartPolicy::as_str`] `pub const fn` accessor so
3640/// every consumer that holds a borrowed [`&RestartPolicy`] and needs
3641/// an owned [`Vec<u8>`] — a future
3642/// `.iter().map(Vec::<u8>::from).collect()` pipe over
3643/// `&[RestartPolicy]` (whose iterator yields `&RestartPolicy`,
3644/// not `RestartPolicy`, so the owned-input axis alone forces every
3645/// call site through an explicit `.copied()` / spurious [`Copy`]
3646/// deref restatement rather than the direct trait-idiomatic
3647/// projection), a future admission-webhook rejection body composer
3648/// that walks [`RestartPolicy::ALL`] through an `Into<Vec<u8>>`-
3649/// bound per-arm byte-writer to surface the accepted `:children
3650/// :restart` set — reaches the substrate primitive through one
3651/// trait dispatch rather than a `Vec::<u8>::from(*policy)` spurious-
3652/// [`Copy`]-deref restatement.
3653impl From<&RestartPolicy> for Vec<u8> {
3654    fn from(policy: &RestartPolicy) -> Vec<u8> {
3655        policy.as_str().as_bytes().to_vec()
3656    }
3657}
3658
3659/// Trait-idiomatic *borrowed byte-slice input* reverse projection on the
3660/// second (and final) M2-OTP-shape closed-set fieldless typed enum peer on
3661/// the caixa surface ([`RestartPolicy`]) — the byte-view mirror of the
3662/// str-view reverse-projection axis carried by the paired
3663/// [`TryFrom<&str> for RestartPolicy`] impl (which routes through the
3664/// substrate-primitive [`RestartPolicy::from_wire`] `Option<Self>` accessor
3665/// on the three-arm `PascalCase` accept-set the sibling
3666/// [`RestartPolicy::as_str`] emitter returns). Routes byte-for-byte through
3667/// the standard-library [`std::str::from_utf8`] UTF-8 validator and then
3668/// through [`RestartPolicy::from_wire`] so every consumer that holds a
3669/// borrowed [`&[u8]`] and needs to project it back into a typed
3670/// [`RestartPolicy`] — a future `bytes::Bytes::as_ref()`-fed reader that
3671/// parses a per-child `:restart` `PascalCase` wire scalar from an
3672/// already-borrowed framing byte-tail (a
3673/// `tracing::field::valuable::Value::Bytes` recorder on the future
3674/// wasm-operator's per-child restart-decision diagnostic emission path, a
3675/// future audit-report re-loader binding a prior
3676/// [`RestartPolicy::as_str`] output from a mmap'd byte-slice back through
3677/// the typed enum for cross-run comparison), a future M4
3678/// `mesh.pleme.io/v1alpha1/Supervisor` CR admission-webhook rejection body
3679/// that reads a `spec.children[].restart` field off a raw HTTP body
3680/// byte-slice before UTF-8 validation commits allocation, a future generic
3681/// `<T: for<'a> TryFrom<&'a [u8]>>`-bound loader over any of the
3682/// substrate's closed-set typed enums — reaches the same three-arm
3683/// `PascalCase` wire accept-set the sibling method-named
3684/// [`RestartPolicy::from_wire`] resolver and the paired trait-idiomatic
3685/// [`TryFrom<&str>`] axis already resolve against, rather than an open-
3686/// coded per-call-site
3687/// `std::str::from_utf8(bytes).ok().and_then(RestartPolicy::from_wire)`
3688/// composition or a
3689/// `<RestartPolicy as TryFrom<&str>>::try_from(std::str::from_utf8(bytes)?)`
3690/// two-hop shape whose type bounds have no compile-time link to the
3691/// substrate primitive.
3692///
3693/// Closes the substrate-wide trait-idiomatic *byte-view reverse-projection*
3694/// family on the M2-OTP-shape `:supervisor :estrategia` + `:children
3695/// :restart` slot pair the sibling [`RestartStrategy`] first-mover
3696/// (c699a83) opened one commit prior — extends the family from
3697/// [`crate::CaixaKind`] (18d1940), [`crate::CaixaDialeto`] (d102cb8),
3698/// [`crate::dep::DepList`] (b8f25d5), and [`RestartStrategy`] (c699a83)
3699/// onto the second (and final) M2-OTP-shape closed-set fieldless typed
3700/// enum peer on the caixa surface, matching the trajectory the paired
3701/// byte-owned reverse-projection axis campaign already walked across the
3702/// same slot pair (63e5dd0 → 96a522a). Rust's standard library carries no
3703/// blanket `impl<T: for<'a> TryFrom<&'a str>> TryFrom<&[u8]> for T`, so a
3704/// two-hop composition through [`std::str::from_utf8`] + the paired
3705/// [`TryFrom<&str>`] axis is reachable at every call site but has no
3706/// compile-time link back to the byte-view reverse-projection axis. Every
3707/// remaining closed-set fieldless typed enum peer on the substrate
3708/// ([`crate::aplicacao::PlacementStrategy`],
3709/// [`crate::aplicacao::RateLimitUnit`], [`crate::aplicacao::WitShape`],
3710/// and the outside-`caixa-core` peers `PathShapeViolation`,
3711/// `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`,
3712/// `FerriteRuntime`) is a future target of the campaign.
3713///
3714/// `type Error = ()` matches the sibling [`RestartPolicy::from_wire`]'s
3715/// `Option<Self>` return-shape's deliberate deferral of error typing and
3716/// the paired trait-idiomatic [`TryFrom<&str>`] axis's unit-error shape —
3717/// the caller picks the diagnostic form appropriate for its use site (a
3718/// future `feira supervisor --restart …` arg-parse composes its own
3719/// per-verb "unknown restart policy: <arg> — accepted: {…}" message
3720/// enumerating [`RestartPolicy::WIRE_NAMES`]; a future admission-webhook
3721/// rejection body wraps the `Err(())` outcome with the accepted-set
3722/// enumeration for operator diagnostics; a `Result::map_err` at the call
3723/// site lifts the unit-error to a per-verb error type). Two rejection
3724/// paths route through the single unit-error: an invalid UTF-8
3725/// byte-sequence ([`std::str::from_utf8`] returns `Err`) and a valid UTF-8
3726/// byte-string that falls outside the three-arm `PascalCase` accept-set
3727/// ([`RestartPolicy::from_wire`] returns `None`) — both collapse onto
3728/// `Err(())` so the trait signature stays consistent with the sibling
3729/// str-view reverse axis, and a caller that needs to distinguish the two
3730/// failure modes composes [`std::str::from_utf8`] +
3731/// [`RestartPolicy::from_wire`] explicitly.
3732///
3733/// Pinned load-bearing by
3734/// [`tests::restart_policy_try_from_bytes_routes_through_from_wire_accessor`]
3735/// (byte-parity pin against [`RestartPolicy::from_wire`] across the
3736/// three-arm [`RestartPolicy::ALL`] accept-set on the borrowed byte-slice
3737/// surface, plus a cross-axis witness that the byte-view reverse
3738/// projection agrees with the paired [`TryFrom<&str>`] str-view reverse
3739/// axis on every accepted arm, and a forward/reverse byte-view cross-axis
3740/// witness that feeding the paired [`AsRef<[u8]>`] byte-tail back through
3741/// the new impl round-trips to the originating arm) and
3742/// [`tests::restart_policy_try_from_bytes_rejects_unknown_and_non_utf8_bytes`]
3743/// (rejection witness against silent accept-set widening on both the
3744/// non-UTF-8 byte-sequence rejection path and the unknown-wire-vocabulary
3745/// rejection path — the latter includes the sibling kebab-case
3746/// dispatcher-catalog byte-strings on the two-axis wire/catalog split so
3747/// a caller that confuses the two axes trips here rather than at a
3748/// downstream K8s-CR round-trip miss).
3749impl TryFrom<&[u8]> for RestartPolicy {
3750    type Error = ();
3751
3752    fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
3753        std::str::from_utf8(bytes)
3754            .ok()
3755            .and_then(Self::from_wire)
3756            .ok_or(())
3757    }
3758}
3759
3760/// Trait-idiomatic *owned byte-vec input* reverse projection on the second
3761/// (and final) M2-OTP-shape supervisor-slot closed-set fieldless typed enum
3762/// peer on the caixa surface ([`RestartPolicy`]) — the owned-input peer of
3763/// [`TryFrom<&[u8]> for RestartPolicy`], closing the byte-view reverse-
3764/// projection *square* ({owned-input, borrowed-input} × {owned-output
3765/// byte-vec, borrowed-output byte-slice}) on the M2-OTP-shape
3766/// `:supervisor :estrategia` + `:children :restart` slot pair the sibling
3767/// [`RestartStrategy`] first-mover (34951fe) opened on the byte-owned
3768/// reverse-input axis one commit-window prior. Routes byte-for-byte through
3769/// [`<Self as TryFrom<&[u8]>>::try_from`] on the [`Vec<u8>::as_slice`]
3770/// borrow so the owned-input surface reaches the same
3771/// [`std::str::from_utf8`] + [`RestartPolicy::from_wire`] resolution chain
3772/// the borrowed-input peer already carries — one substrate-primitive
3773/// accessor, one trait dispatch, no per-consumer detour.
3774///
3775/// Rust's standard library carries no blanket
3776/// `impl<T: for<'a> TryFrom<&'a [u8]>> TryFrom<Vec<u8>> for T`, so a
3777/// consumer that holds an owned [`Vec<u8>`] and needs a typed
3778/// [`RestartPolicy`] otherwise picks between (a) an open-coded
3779/// `<RestartPolicy as TryFrom<&[u8]>>::try_from(bytes.as_slice())` at every
3780/// call site (whose type bounds have no compile-time link to the byte-
3781/// owned reverse-projection axis), (b) a two-hop
3782/// `String::from_utf8(bytes)` + [`RestartPolicy::from_wire`] composition
3783/// whose error surface leaks the standard-library
3784/// [`std::string::FromUtf8Error`] (widening the sibling [`TryFrom<&[u8]>`]
3785/// axis's unit-error) and silently allocates a [`String`] on inputs that
3786/// will never make it past the wire vocabulary, or (c) an intermediate
3787/// `<RestartPolicy as TryFrom<&str>>::try_from(std::str::from_utf8(&bytes)?)`
3788/// three-hop shape. This impl closes the owned-byte-vec reverse-projection
3789/// axis at the substrate-primitive [`RestartPolicy::from_wire`] accessor so
3790/// every future `<T: TryFrom<Vec<u8>>>`-bound owned-byte-vec consumer — a
3791/// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR admission-webhook body
3792/// reader that hands the `spec.children[].restart` byte-tail off as a
3793/// [`Vec<u8>`] before UTF-8 validation commits allocation, a
3794/// `bytes::Bytes::to_vec()`-shape wire-body composer walking a prior
3795/// audit's per-child rejection payload back to the typed enum, a
3796/// `std::io::Read::read_to_end`-shape audit-log source whose framing yields
3797/// an owned byte-vec per per-policy scalar, an
3798/// `<T: TryFrom<Vec<u8>>>`-bound generic loader over any of the
3799/// substrate's closed-set typed enums — reaches the same three-arm
3800/// `PascalCase` wire accept-set through one trait dispatch.
3801///
3802/// Extends the substrate-wide trait-idiomatic *byte-owned reverse-
3803/// projection* family — opened on the structurally most fundamental
3804/// closed-set fieldless typed enum peer ([`crate::CaixaKind`], commit
3805/// 99c2849), extended onto the second caixa-core-internal peer
3806/// ([`crate::CaixaDialeto`], commit 83a1526), the third
3807/// ([`crate::dep::DepList`], commit 42091cb), and the first M2-OTP-shape
3808/// supervisor-slot peer ([`RestartStrategy`], commit 34951fe) — onto the
3809/// second (and final) M2-OTP-shape supervisor-slot closed-set fieldless
3810/// typed enum peer, tracking the "delegate through `TryFrom<&[u8]>` on the
3811/// `Vec<u8>::as_slice` borrow" discipline the first-mover established.
3812/// Every remaining closed-set fieldless typed enum peer on the substrate
3813/// ([`crate::aplicacao::PlacementStrategy`],
3814/// [`crate::aplicacao::RateLimitUnit`], [`crate::aplicacao::WitShape`],
3815/// [`crate::render::PathShapeViolation`], and the outside-`caixa-core`
3816/// peers `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`,
3817/// `Semantic`, `FerriteRuntime`) is a future target of the campaign,
3818/// mirroring the trajectory the closed byte-view reverse-projection
3819/// family (`TryFrom<&[u8]>`) and the closed byte-owned forward-projection
3820/// family (`From<{Self, &Self}> for Vec<u8>`) already walked across the
3821/// same slot pair.
3822///
3823/// `type Error = ()` matches the sibling [`TryFrom<&[u8]> for
3824/// RestartPolicy`] unit-error shape, preserving the trait-family
3825/// consistency across the borrowed-and-owned byte-view reverse-projection
3826/// pair. The owned [`Vec<u8>`] input is dropped on the error path (the
3827/// standard-library `String::from_utf8` convention of returning the input
3828/// in the error deliberately declined — a caller that needs the bytes back
3829/// holds a clone before the call, and the closed-set-enum use site rarely
3830/// wants the raw bytes back past a "did you mean" diagnostic that operates
3831/// on the wire vocabulary rather than the input).
3832///
3833/// Pinned load-bearing by
3834/// [`tests::restart_policy_try_from_vec_bytes_routes_through_borrowed_byte_view_axis`]
3835/// (byte-parity pin against the paired borrowed [`TryFrom<&[u8]>`] axis
3836/// across the three-arm [`RestartPolicy::ALL`] accept-set on the owned
3837/// byte-vec surface, cross-axis witness that the byte-owned reverse
3838/// projection agrees with the paired str-view reverse-projection axis
3839/// ([`TryFrom<&str>`]) on every accepted arm through the shared substrate-
3840/// primitive [`RestartPolicy::from_wire`] accessor, and a four-corner
3841/// {owned-input, borrowed-input} × {`From<Self>` → `Vec<u8>`,
3842/// `From<&Self>` → `Vec<u8>`} round-trip witness available on this enum
3843/// because [`RestartPolicy::as_str`] and [`RestartPolicy::from_wire`]
3844/// share one `PascalCase` byte-vocabulary — like the sibling
3845/// [`RestartStrategy`] and unlike the sibling [`crate::CaixaKind`] which
3846/// its peer test deliberately declines the four-corner witness on because
3847/// the wire/diagnostic split makes the forward and reverse pairs speak
3848/// different byte-strings) and
3849/// [`tests::restart_policy_try_from_vec_bytes_rejects_unknown_and_non_utf8_bytes`]
3850/// (rejection witness against silent accept-set widening on both the
3851/// non-UTF-8 byte-sequence rejection path and the unknown-wire-vocabulary
3852/// rejection path — the latter includes the sibling kebab-case
3853/// dispatcher-catalog byte-strings on the two-axis wire/catalog split so
3854/// a caller that confuses the two axes trips here rather than at a
3855/// downstream K8s-CR round-trip miss, plus a cross-axis witness that the
3856/// owned byte-vec reverse-projection axis agrees with the borrowed byte-
3857/// slice reverse-projection axis on every rejected input).
3858impl TryFrom<Vec<u8>> for RestartPolicy {
3859    type Error = ();
3860
3861    fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
3862        <Self as TryFrom<&[u8]>>::try_from(bytes.as_slice())
3863    }
3864}
3865
3866/// Trait-idiomatic *owned-`String` input, `Result<Self, ()>` output*
3867/// string-owned reverse projection on the second (and final) M2-OTP-shape
3868/// supervisor-slot closed-set fieldless typed enum peer on the caixa
3869/// surface ([`RestartPolicy`]) — the owned-input peer of the paired
3870/// [`TryFrom<&str> for RestartPolicy`] str-view reverse-projection axis,
3871/// and the string-owned reverse companion of the pre-existing string-owned
3872/// *forward* pair ([`From<RestartPolicy> for String`],
3873/// [`From<&RestartPolicy> for String`]) already lifted on this same enum.
3874/// Routes owned [`String`] input through the paired borrowed-input
3875/// [`TryFrom<&str>`] axis via [`String::as_str`] so every consumer that
3876/// holds an owned `String` — a future M4 `mesh.pleme.io/v1alpha1/Supervisor`
3877/// CR admission-webhook body reader that hands the
3878/// `spec.children[].restart` `PascalCase` scalar off as an owned [`String`]
3879/// after UTF-8 validation, a `serde_yaml::from_str` / `serde_json::from_str`
3880/// de-serialize round-trip whose composer surfaces the `:children :restart`
3881/// scalar as an owned [`String`] typed field, a
3882/// `feira supervisor --restart <Permanent|Temporary|Transient>`
3883/// `clap`-derived arg-parse whose owned-`String` positional lands the
3884/// canonical arm at the typed dispatch, a per-`:children`-slot overlay
3885/// resolver reading an owned [`String`] out of a `ConfigMap`
3886/// `data.children-restart` scalar, an `<T: TryFrom<String>>`-bound generic
3887/// loader over any of the substrate's closed-set typed enums — reaches the
3888/// same three-arm `PascalCase` accept-set through one trait dispatch.
3889///
3890/// Extends the substrate-wide trait-idiomatic *string-owned reverse-
3891/// projection* family — opened on the compound M3-mesh
3892/// `:politicas :rate-limit` primitive [`crate::aplicacao::RateLimit`]
3893/// (a2e6f02), lifted onto the first closed-set fieldless typed-enum peer
3894/// [`crate::aplicacao::WitShape`] (e6aac29), extended onto the second
3895/// closed-set fieldless typed-enum peer [`crate::aplicacao::RateLimitUnit`]
3896/// (94a9c5e), extended onto the third closed-set fieldless typed-enum peer
3897/// [`crate::aplicacao::PlacementStrategy`] (d81a70a), extended onto the
3898/// first M2-OTP-shape supervisor-slot closed-set fieldless typed-enum peer
3899/// [`RestartStrategy`] (78fe8c8) — onto the second (and final) M2-OTP-shape
3900/// supervisor-slot closed-set fieldless typed-enum peer, the per-`:children`
3901/// restart-decision-policy discriminator. This closes the string-owned
3902/// reverse-projection axis on the M2-OTP-shape `:supervisor :estrategia` +
3903/// `:children :restart` slot pair, mirroring the trajectory the byte-view
3904/// / byte-owned / str-view reverse-projection families already walked
3905/// across the same slot pair. The peers [`crate::CaixaKind`],
3906/// [`crate::CaixaDialeto`], and [`crate::dep::DepList`] remain the next
3907/// targets of the campaign.
3908///
3909/// Rust's standard library carries no blanket
3910/// `impl<T: for<'a> TryFrom<&'a str>> TryFrom<String> for T`, so a consumer
3911/// that holds an owned [`String`] and needs a typed [`RestartPolicy`]
3912/// otherwise picks between (a) an open-coded
3913/// `<RestartPolicy as TryFrom<&str>>::try_from(s.as_str())` at every call
3914/// site whose type bounds have no compile-time link back to the string-
3915/// owned reverse-projection axis, (b) a `let s: &str = &s;
3916/// RestartPolicy::try_from(s)` two-step whose borrow arithmetic leaks a
3917/// per-call-site lifetime dance rather than a single trait dispatch, or
3918/// (c) a `String::into_bytes` + [`TryFrom<Vec<u8>>`] detour that reaches
3919/// the substrate-primitive `from_wire` accessor through a UTF-8 re-
3920/// validation hop the owned-`String` axis already knows to skip. This
3921/// impl closes the string-owned reverse-projection axis at the substrate-
3922/// primitive [`RestartPolicy::from_wire`] accessor so every future
3923/// `<T: TryFrom<String>>`-bound owned-string consumer reaches the same
3924/// three-arm `PascalCase` accept-set through one trait dispatch.
3925///
3926/// `type Error = ()` matches the sibling [`TryFrom<&str> for
3927/// RestartPolicy`], [`TryFrom<&[u8]> for RestartPolicy`], and
3928/// [`TryFrom<Vec<u8>> for RestartPolicy`] unit-error shapes, preserving
3929/// the trait-family consistency across the {str-view, byte-view, byte-
3930/// owned, string-owned} reverse-projection square. The owned [`String`]
3931/// input is dropped on the error path (the standard-library
3932/// `String::from_utf8` convention of returning the input in the error
3933/// deliberately declined — a caller that needs the string back holds a
3934/// clone before the call, and the closed-set-enum use site rarely wants
3935/// the raw string back past a "did you mean" diagnostic that operates on
3936/// the wire vocabulary rather than the input).
3937///
3938/// Pinned load-bearing by
3939/// [`tests::restart_policy_try_from_owned_string_routes_through_borrowed_str_view_axis`]
3940/// (byte-parity pin against the paired borrowed [`TryFrom<&str>`] axis
3941/// across the three-arm [`RestartPolicy::ALL`] accept-set on the owned-
3942/// `String` surface, cross-axis witness that the string-owned reverse
3943/// projection agrees with the sibling byte-view / byte-owned reverse-
3944/// projection axes on every accepted arm through the shared substrate-
3945/// primitive [`RestartPolicy::from_wire`] accessor, and a closed-cycle
3946/// witness against the paired string-owned forward-projection pair —
3947/// `Self → String → TryFrom<String> → Self` round-trips to the
3948/// originating arm on every canonical `PascalCase` scalar) and
3949/// [`tests::restart_policy_try_from_owned_string_rejects_unknown_wire_strings`]
3950/// (rejection witness against silent accept-set widening — mirrors the
3951/// corpus the paired [`TryFrom<&str>`] rejection witness already pins,
3952/// including empty / whitespace-only inputs, the sibling kebab-case
3953/// dispatcher-catalog byte-strings on the two-axis wire/catalog split so
3954/// a caller that confuses the two axes trips here rather than at a
3955/// downstream K8s-CR round-trip miss, case-fold rebrand candidates,
3956/// whitespace-padded / trailing-newline / quote-wrapped forms, and
3957/// English-rebrand candidates, with per-input cross-axis parity against
3958/// the borrowed [`TryFrom<&str>`] reverse-projection axis).
3959impl TryFrom<String> for RestartPolicy {
3960    type Error = ();
3961
3962    fn try_from(s: String) -> Result<Self, Self::Error> {
3963        <Self as TryFrom<&str>>::try_from(s.as_str())
3964    }
3965}
3966
3967// Fleet-wide dispatcher-catalog registrations for caixa's OTP
3968// supervisor surface — two more typed shadows over Erlang/OTP
3969// primitives the substrate now mechanically tracks (see
3970// theory/UNIFIED-COMPUTING-MODEL.md §VI for the roadmap +
3971// theory/TYPED-ABSORPTION.md for the absorption arc).
3972gen_platform::register_dispatcher!("caixa.restart-strategy", RestartStrategy);
3973gen_platform::register_dispatcher!("caixa.restart-policy", RestartPolicy);
3974
3975/// One child entry in the supervisor's `:children` list.
3976///
3977/// Every child references another caixa by `:caixa <nome>` + version
3978/// constraint. The supervisor materializes one ComputeUnit per entry.
3979#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
3980#[serde(rename_all = "camelCase")]
3981pub struct ChildSpec {
3982    /// The child caixa's `:nome`. Must resolve via the same dependency
3983    /// resolution path as `:deps` (caixa-resolver).
3984    pub caixa: String,
3985
3986    /// Semver constraint (`"^0.1"`, `"~0.1.2"`, etc.) — same shape as
3987    /// [`crate::dep::Dep::versao`].
3988    pub versao: String,
3989
3990    /// Restart policy — an author-omitted slot degrades onto the
3991    /// substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`]
3992    /// (`permanent`, the Erlang/OTP worker-child default) through the
3993    /// [`Default for RestartPolicy`] impl this `#[serde(default)]` routes
3994    /// to.
3995    #[serde(default)]
3996    pub restart: RestartPolicy,
3997}
3998
3999impl ChildSpec {
4000    /// Substrate-canonical per-`:children` child-caixa `:nome` scalar
4001    /// accessor every consumer that reads the OTP-shape supervised
4002    /// child's identity keys off — returns the author-declared
4003    /// `:children :caixa` byte-string verbatim as a `&str`, borrowed
4004    /// from the typed slot's own [`String`] storage.
4005    ///
4006    /// The `:children :caixa` slot carries the DNS-1123 label — the
4007    /// child caixa's `:nome` — that every emitted cluster artifact
4008    /// derives its `metadata.name` from verbatim: the rendered
4009    /// `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name` per child, the
4010    /// [`crate::LABEL_PROGRAM`] label value on every child's pod
4011    /// identity, and the per-child K8s Service `metadata.name` the
4012    /// future wasm-operator (M3) provisions for inter-child supervision-
4013    /// tree wiring. Every downstream consumer that fans on the child's
4014    /// caixa-name keys off this scalar (the [`SupervisorSpec::validate`]
4015    /// per-child DNS-1123 gate at
4016    /// `require_valid_dns_1123_label(child.nome(), …)`, the per-child
4017    /// duplicate-detection [`crate::render::insert_first_seen`] key, the
4018    /// [`validate_no_self_supervision`] cross-slot equality check
4019    /// against the parent's `:nome`, every `SupervisorError` variant
4020    /// carrying the offending child caixa verbatim for `feira lint`
4021    /// rendering, the future wasm-operator's hierarchical reconciliation
4022    /// scheduler's per-child ComputeUnit-name projection, the future M4
4023    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
4024    /// admission webhook).
4025    ///
4026    /// Prior to this lift the `.caixa` byte-string was accessed inline
4027    /// at seven sites in `supervisor.rs` — the DNS-1123 gate's
4028    /// `&child.caixa`, the four `SupervisorError::{ChildCaixaInvalid,
4029    /// EmptyChildVersion, ChildVersaoInvalid, DuplicateChildCaixa}`
4030    /// carriers' `child.caixa.clone()`, the dedup key's
4031    /// `child.caixa.as_str()`, and the [`validate_no_self_supervision`]
4032    /// `child.caixa == parent_nome` cross-slot check — seven open-coded
4033    /// field-accesses that expressed no compile-time link back to the
4034    /// typed slot. A future extension of the `:children :caixa` axis to
4035    /// a richer author surface (a per-cluster alias table the operator
4036    /// pins through a future `:placement`-scoped slot on the supervisor
4037    /// tree, a namespace-qualified rewrite the M4 CR materializer
4038    /// applies per-CR, a per-child overlay from the future `:children
4039    /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
4040    /// acknowledges) would have had to be threaded through every
4041    /// open-coded copy in lockstep or one consumer would silently
4042    /// disagree with the peers on which caixa a given child resolves to
4043    /// — a child-set lookup that treated the name as `"cart-worker"`
4044    /// while the peer duplicate-detector treated it as
4045    /// `"tenant-a/cart-worker"` would silently split the
4046    /// `DuplicateChildCaixa` membership-lookup diagnostic from the
4047    /// self-supervision detector's parent-equality check, a two-consumer
4048    /// split at the validator far from the source `caixa.lisp` with no
4049    /// field naming the identity-drift root cause. Lifting the resolution
4050    /// rule to a typed method on the substrate primitive means every
4051    /// downstream consumer of the Supervisor's per-`:children` identity
4052    /// surface reaches for exactly one typed dispatch — the resolver's
4053    /// accept-set migrates as a unit on any future axis addition.
4054    ///
4055    /// Sibling of the peer per-`:membros` [`crate::Membro::nome`]
4056    /// (4a32abf) member-caixa `:nome` scalar accessor on the M3
4057    /// mesh-slot surface — same "one typed dispatch on the substrate
4058    /// primitive, thin projections at each consumer" discipline extended
4059    /// onto the M2 supervisor-tree per-`:children` child-identity axis.
4060    /// The two typed axes (`Membro::nome` on the M3 Aplicacao side,
4061    /// `ChildSpec::nome` on the M2 Supervisor side) now share one
4062    /// accessor discipline for the shared substrate concept "another
4063    /// caixa referenced by `:nome`". Peer of the second M2 slot scalar
4064    /// accessor [`crate::UpgradeFromEntry::prior_versao`] (75d27a8) on
4065    /// the sibling per-`:upgrade-from :from` OTP-appup axis — the M2
4066    /// slot family's typed-accessor discipline now spans both the
4067    /// upgrade axis (`:upgrade-from`) and the supervision axis
4068    /// (`:children`), matching the closed M3 mesh-slot accessor family's
4069    /// shape. Named `nome()` to match the tatara-lisp author-surface
4070    /// term the field's docstring already reaches for ("The child
4071    /// caixa's `:nome`") and the peer [`crate::Membro::nome`] /
4072    /// [`crate::Caixa::nome`] / [`crate::dep::Dep::nome`] field-name
4073    /// discipline the substrate already carries — the accessor's name
4074    /// maps directly onto the canonical caixa-identity vocabulary rather
4075    /// than shadowing the field's storage-side `caixa` label.
4076    #[must_use]
4077    pub const fn nome(&self) -> &str {
4078        self.caixa.as_str()
4079    }
4080
4081    /// Substrate-canonical per-`:children` child-caixa `:versao` semver-
4082    /// requirement scalar accessor every consumer that reads the OTP-shape
4083    /// supervised child's version pin keys off — returns the author-declared
4084    /// `:children :versao` byte-string verbatim as a `&str`, borrowed from
4085    /// the typed slot's own [`String`] storage.
4086    ///
4087    /// The `:children :versao` slot carries the Cargo-shaped semver
4088    /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that pins
4089    /// which release of the supervised child caixa the OTP-shape supervisor
4090    /// tree materializes against — the same requirement grammar the peer
4091    /// `:deps :versao` / `:membros :versao` axes carry, resolved through the
4092    /// shared [`crate::render::require_valid_versao_requirement`] cascade
4093    /// and the shared [`crate::version::parse_requirement`] parser. Every
4094    /// downstream consumer that fans on the child's version pin keys off
4095    /// this scalar (the [`SupervisorSpec::validate`] per-child requirement
4096    /// gate at `require_valid_versao_requirement(child.versao_requirement(),
4097    /// …)`, the [`SupervisorError::ChildVersaoInvalid`] variant's carrier
4098    /// for `feira lint` rendering, every future per-cluster version-lock
4099    /// overlay the caixa-operator's hierarchical reconciliation scheduler
4100    /// pins through a future `:placement`-scoped supervisor-tree slot, the
4101    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
4102    /// per-child version resolver, the future wasm-operator's per-child
4103    /// lacre BLAKE3-closure lookup at `ComputeUnit` materialization time).
4104    ///
4105    /// Prior to this lift the `.versao` byte-string was accessed inline at
4106    /// two `&str`-shaped sites in `caixa-core/src/supervisor.rs` — the
4107    /// [`SupervisorSpec::validate`] requirement-gate call
4108    /// `require_valid_versao_requirement(&child.versao, …)` and the
4109    /// [`SupervisorError::ChildVersaoInvalid`] carrier at
4110    /// `versao: child.versao.clone()` — two open-coded field-accesses that
4111    /// expressed no compile-time link back to the typed slot. A future
4112    /// extension of the `:children :versao` axis to a richer author surface
4113    /// (a per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
4114    /// flow, a lacre-projected concrete-version rewrite the operator
4115    /// materializes at CR-admission time, a future `:children :versao-lock`
4116    /// per-cluster override slot the wasm-operator's hierarchical
4117    /// reconciliation scheduler authors per-CR) would have had to be
4118    /// threaded through both open-coded copies in lockstep or one consumer
4119    /// would silently disagree with the peer on which release constraint a
4120    /// given child resolves to — the requirement-gate call reading
4121    /// `"^0.1"` while the error-body carrier read `"tenant-a-pin/^0.1"`
4122    /// would silently split the `ChildVersaoInvalid` diagnostic quote from
4123    /// the actual gate rejection input, a two-consumer split at the
4124    /// validator far from the source `caixa.lisp` with no field naming the
4125    /// version-pin drift root cause. Lifting the resolution rule to a typed
4126    /// method on the substrate primitive means every downstream
4127    /// requirement-facing consumer of the Supervisor's per-`:children`
4128    /// version-pin surface reaches for exactly one typed dispatch — the
4129    /// resolver's accept-set migrates as a unit on any future axis addition.
4130    ///
4131    /// Sibling of the peer per-`:membros` [`crate::Membro::versao_requirement`]
4132    /// (a40b0e3) member-caixa `:versao` scalar accessor on the M3 mesh-slot
4133    /// surface — same "one typed dispatch on the substrate primitive, thin
4134    /// projections at each consumer" discipline extended onto the M2
4135    /// supervisor-tree per-`:children` child-version-pin axis. The two typed
4136    /// axes (`Membro::versao_requirement` on the M3 Aplicacao side,
4137    /// `ChildSpec::versao_requirement` on the M2 Supervisor side) now share
4138    /// one accessor discipline for the shared substrate concept "another
4139    /// caixa referenced by a Cargo-shaped semver requirement". Peer of the
4140    /// sibling per-`:children` [`ChildSpec::nome`] (57c61d0) child-caixa
4141    /// `:nome` scalar accessor — the pair
4142    /// `(nome(), versao_requirement())` jointly projects the
4143    /// `(caixa, versao)` field pair every OTP-shape supervisor-tree consumer
4144    /// that fans on per-child identity + version pin keys off, closing the
4145    /// last unlifted per-`:children` `String`-carry axis so every downstream
4146    /// per-`:children` reader now routes through a typed dispatch on the
4147    /// substrate primitive. Named `versao_requirement()` rather than
4148    /// `versao()` because the field's storage-side `.versao` label is
4149    /// already the author-surface term (`:versao`); the accessor's name
4150    /// carries the semantic role — the semver *requirement* string the
4151    /// shared [`crate::version::parse_requirement`] entry-point consumes —
4152    /// so a raw field access and a typed dispatch read differently at every
4153    /// consumer site. Matches the peer [`crate::Membro::versao_requirement`]
4154    /// naming discipline verbatim.
4155    #[must_use]
4156    pub const fn versao_requirement(&self) -> &str {
4157        self.versao.as_str()
4158    }
4159
4160    /// Substrate-canonical per-`:children` `:restart` OTP-shaped
4161    /// per-child post-exit restart-decision policy scalar accessor every
4162    /// consumer that dispatches on the supervised child's post-exit
4163    /// reconcile posture keys off — returns the author-declared
4164    /// `:children :restart` variant verbatim as a [`RestartPolicy`],
4165    /// `Copy`-projected from the typed slot's own [`RestartPolicy`]
4166    /// storage.
4167    ///
4168    /// The `:children :restart` slot carries the closed-set OTP-shaped
4169    /// per-child restart-decision policy discriminator
4170    /// ([`RestartPolicy::Permanent`] — always restart, the OTP `permanent`
4171    /// worker-child default; [`RestartPolicy::Transient`] — restart only
4172    /// on abnormal exit, the OTP `transient` clean-completion-aware
4173    /// default; [`RestartPolicy::Temporary`] — never restart, the OTP
4174    /// `temporary` one-shot default) that every downstream consumer of
4175    /// the Supervisor's per-child post-exit reconcile branch keys off.
4176    /// Every future downstream consumer that fans on the per-child
4177    /// restart-decision keys off this scalar (the future `feira app
4178    /// graph` per-child restart column, the future wasm-operator's
4179    /// per-child post-exit restart-decision branch, the future M4
4180    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
4181    /// admission webhook, the `caixa-operator`'s hierarchical
4182    /// reconciliation scheduler's per-child post-exit reconcile branch,
4183    /// the [`RestartPolicy::as_str`] `Serialize`-derive-pinning path the
4184    /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
4185    /// pin threads through).
4186    ///
4187    /// Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
4188    /// (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
4189    /// scalar accessor and the M3 mesh-slot
4190    /// [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
4191    /// [`crate::PlacementStrategy`] distribution-strategy scalar accessor
4192    /// — same "one typed dispatch on the substrate primitive,
4193    /// `Copy`-projected closed-set enum-arm discriminator that partitions
4194    /// the downstream renderer's per-arm fan-out" discipline extended
4195    /// onto the M2 supervisor-slot per-`:children` restart-decision-policy
4196    /// `Copy`-composite-enum scalar axis. Third axis on the per-`:children`
4197    /// [`ChildSpec`] type — companion to the sibling per-`:children`
4198    /// [`ChildSpec::nome`] (57c61d0) child-caixa `:nome` scalar accessor
4199    /// and the per-`:children` [`ChildSpec::versao_requirement`]
4200    /// (2c053c8) child-caixa `:versao` semver-requirement scalar accessor
4201    /// on the sibling `String`-carry axes. The triple
4202    /// `(nome(), versao_requirement(), restart())` jointly projects the
4203    /// `(caixa, versao, restart)` field trio every OTP-shape supervisor-
4204    /// tree consumer that fans on per-child identity + version pin +
4205    /// restart-decision keys off, closing the last unlifted per-`:children`
4206    /// axis so every downstream per-`:children` reader now routes through
4207    /// a typed dispatch on the substrate primitive. Named `restart()` to
4208    /// match the storage field's name and the author-surface
4209    /// `:children :restart` slot term verbatim; the accessor's identity
4210    /// name maps onto the canonical OTP-shape per-child restart-decision-
4211    /// policy vocabulary the [`RestartPolicy`] enum's docstring already
4212    /// carries.
4213    ///
4214    /// Declared `pub const fn` to close the last non-`const`
4215    /// `Copy`-return raw-field-getter posture on the M2
4216    /// per-`:children` [`ChildSpec`] substrate-primitive surface — peer
4217    /// of the sibling M2 per-`:supervisor`
4218    /// [`SupervisorSpec::estrategia`] (converted in this commit)
4219    /// `Copy`-composite-enum accessor, the sibling M2 per-`:supervisor`
4220    /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
4221    /// already lifted, and the peer M3 mesh-slot per-`:entrada`
4222    /// [`crate::Entrada::port`] (bafa004) / per-`:placement`
4223    /// [`crate::Placement::estrategia`] (bafa004) `Copy`-return
4224    /// `pub const fn` scalar accessors on the sibling M3 surface. Every
4225    /// downstream substrate-side `const`-context consumer of the
4226    /// per-`:children` restart-decision-policy scalar (a future
4227    /// module-scope `const _:() = assert!(matches!(child.restart(),
4228    /// RestartPolicy::Permanent))` invariant pin on a typed fixture, a
4229    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
4230    /// admission-webhook `const fn` per-child restart-decision floor
4231    /// over a typed [`ChildSpec`], any future `const fn` supervisor-tree
4232    /// composer over the substrate primitive that fans on the per-child
4233    /// restart-decision policy at compile time) now reaches through the
4234    /// same typed dispatch on the substrate primitive at const-eval
4235    /// time as at runtime. A future non-`Copy`-return promotion of the
4236    /// scalar (an `Option<RestartPolicy>`-shape migration on the
4237    /// per-child restart-decision axis once heterogeneous per-cluster
4238    /// restart-policy overlays land, a per-tenant restart-policy-alias
4239    /// table the M4 CR materializer resolves per-CR) that would drop
4240    /// the `const` qualifier fails the fail-before-pass-after pin
4241    /// [`tests::child_spec_restart_accessor_is_const_fn`] at caixa-core
4242    /// build time rather than surfacing as a downstream consumer
4243    /// regression.
4244    #[must_use]
4245    pub const fn restart(&self) -> RestartPolicy {
4246        self.restart
4247    }
4248}
4249
4250/// Supervisor-typed slots that live alongside the standard Caixa
4251/// fields when `:kind Supervisor`. Held flat in [`crate::Caixa`] so
4252/// the manifest stays a single typed form; this struct exists for
4253/// validation + conversion.
4254#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
4255#[serde(rename_all = "camelCase")]
4256pub struct SupervisorSpec {
4257    /// Restart strategy. Defaults to [`RestartStrategy::OneForOne`].
4258    #[serde(default)]
4259    pub estrategia: RestartStrategy,
4260
4261    /// Max restarts within [`Self::restart_window`] before the
4262    /// supervisor itself terminates (and its parent supervisor decides
4263    /// what to do). Default 5.
4264    #[serde(default = "default_max_restarts")]
4265    pub max_restarts: u32,
4266
4267    /// Sliding window for `max_restarts`. Authored as a duration
4268    /// string (`"60s"`, `"5m"`); absent = "never reset". A `Some(0s)`
4269    /// is rejected by [`Self::validate`] — Erlang/OTP's
4270    /// `MaxIntensity / Period` invariant requires a positive window
4271    /// (a zero-period supervisor either trips on the first failure or
4272    /// never trips, depending on operator interpretation, neither of
4273    /// which is the author's intent). Omit the slot to express "no
4274    /// reset"; carry a positive duration to express the sliding window.
4275    #[serde(
4276        default,
4277        skip_serializing_if = "Option::is_none",
4278        with = "duration_codec"
4279    )]
4280    pub restart_window: Option<Duration>,
4281
4282    /// Static children. Empty for `SimpleOneForOne` (children added
4283    /// dynamically); required for the other three strategies.
4284    #[serde(default)]
4285    pub children: Vec<ChildSpec>,
4286}
4287
4288const fn default_max_restarts() -> u32 {
4289    // Route the private serde-`#[serde(default = "…")]` helper through
4290    // the substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] typed
4291    // `pub const` rather than the raw `5` literal — one source of truth
4292    // for the Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
4293    // default across the two production consumers that currently
4294    // dispatch on it (this helper via `#[serde(default = "…")]` on
4295    // `SupervisorSpec::max_restarts` and the [`Default for SupervisorSpec`]
4296    // impl at line 962). Pinned by
4297    // `default_max_restarts_helper_routes_through_lifted_default` +
4298    // `supervisor_spec_default_max_restarts_routes_through_lifted_default`
4299    // in the tests module; peer of the sibling caixa-core
4300    // [`crate::manifest::Caixa::supervisor_view`] `unwrap_or(…)` fold
4301    // that now routes its author-omitted `:max-restarts` arm through
4302    // the same lifted constant.
4303    SUPERVISOR_MAX_RESTARTS_DEFAULT
4304}
4305
4306/// Substrate-canonical Erlang/OTP-shaped `MaxIntensity` restart-budget-
4307/// count default for the `:supervisor :max-restarts` axis — the
4308/// canonical `{intensity, 5, 60}` `MaxIntensity` half of Learn You Some
4309/// Erlang's worker-supervisor default, extracted as a typed `pub const`
4310/// so every substrate-side consumer that resolves "what
4311/// [`SupervisorSpec::max_restarts`] value does an author-omitted
4312/// `:max-restarts` slot degrade onto?" reaches for exactly one
4313/// substrate-primitive `u32`.
4314///
4315/// The `:max-restarts` default axis has two production consumers on the
4316/// substrate side today (both prior to this lift folded onto raw `5`
4317/// literals with no compile-time link back to a shared truth): the
4318/// serde-`#[serde(default = "default_max_restarts")]` helper on
4319/// [`SupervisorSpec::max_restarts`] that every author-omitted
4320/// `:supervisor :max-restarts` slot lands in past the derive-macro's
4321/// wire-format compose, and the [`crate::manifest::Caixa::supervisor_view`]
4322/// `.max_restarts().unwrap_or(5)` fold that every downstream consumer of
4323/// the composed [`SupervisorSpec`] altitude reaches through
4324/// (`feira app graph`, the future wasm-operator's per-supervisor
4325/// restart-intensity counter, the future M4
4326/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
4327/// webhook, the caixa-operator's hierarchical reconciliation scheduler).
4328/// A pair of open-coded `5`s across two files that expressed no
4329/// compile-time link back to the shared OTP-canonical default — a
4330/// future rebrand of the default (a tightening to Elixir's
4331/// `Supervisor.max_restarts: 3`, a widening to a per-cluster overlay
4332/// the operator pins through a future
4333/// `:supervisor :max-restarts-overrides` slot the MESH-COMPOSITION
4334/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
4335/// plain `u32` count to a richer `{MaxR, MaxT}` per-child-cohort
4336/// restart-budget-partition once the INSPIRATIONS §II.2 Erlang/OTP
4337/// per-child-cohort roadmap lands) would have had to be threaded
4338/// through both open-coded copies in lockstep or the wire-format
4339/// author-omitted arm and the view-construction author-omitted arm
4340/// would silently disagree on which restart-budget an omitted
4341/// `:max-restarts` resolves to (an author writing `:supervisor
4342/// (:max-restarts ())` would round-trip through serde with the new
4343/// default while `supervisor_view` silently continued to compose the
4344/// stale `5`, or vice versa), a two-consumer split at the composition
4345/// boundary far from the source `caixa.lisp` with no field naming the
4346/// default-drift root cause. Lifting the resolution rule to a typed
4347/// `pub const` on the substrate primitive means every downstream
4348/// consumer of the per-Supervisor default-restart-budget-count surface
4349/// reaches for exactly one substrate-primitive `u32` — the resolver's
4350/// accepted value migrates as a unit on any future axis change.
4351///
4352/// The `5` value pins Learn You Some Erlang's `{intensity, 5, 60}`
4353/// worker-supervisor default (the closest canonical OTP-shape
4354/// production reference the substrate carries, matching the sibling
4355/// `60s` `Period` default the [`Default for SupervisorSpec`] impl pairs
4356/// this constant with on the paired sliding-window axis). Two orders of
4357/// magnitude below the [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` ceiling
4358/// (the upper bracket on the same axis, sibling of this lower default;
4359/// both are typed `u32` const bounds on the `:supervisor :max-restarts`
4360/// axis and now share one accessor discipline on the substrate) and
4361/// above the OTP-`supervisor` callback-module `MaxR = 1` minimum-
4362/// restart floor — the "one restart, then escalate" default is
4363/// deliberately loose enough to absorb a short burst of transient
4364/// child failures without escalating past the supervisor's parent
4365/// while remaining tight enough to trip the `MaxIntensity / Period`
4366/// ratio's escalation on a genuinely-stuck child within the sibling
4367/// `60s` sliding window.
4368///
4369/// Lifted as a typed `pub const` so the bound has exactly one source
4370/// of truth — the serde-side wire-format author-omitted arm at
4371/// [`default_max_restarts`], the [`Default for SupervisorSpec`] impl's
4372/// struct-literal default field, and the caixa-core
4373/// [`crate::manifest::Caixa::supervisor_view`] fold's author-omitted
4374/// arm all read from one place. Same shape every other typed default
4375/// in this crate carries (the sibling
4376/// [`SUPERVISOR_MAX_RESTARTS_MAX`] upper cap on the same axis, the
4377/// paired [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the
4378/// sibling `:restart-window` axis, and the peer
4379/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
4380/// per-renderer defaults on the caixa-flux / caixa-helm rendering
4381/// axes).
4382pub const SUPERVISOR_MAX_RESTARTS_DEFAULT: u32 = 5;
4383
4384/// Upper-bound ceiling on the `:supervisor :max-restarts` axis — every
4385/// validated [`SupervisorSpec::max_restarts`] past
4386/// [`SupervisorSpec::validate`] lies in `1..=SUPERVISOR_MAX_RESTARTS_MAX`.
4387///
4388/// The typed field is `u32` (the zero-floor arm
4389/// [`SupervisorError::ZeroMaxRestarts`] already brackets the bottom edge),
4390/// so a programmatic struct literal
4391/// (`SupervisorSpec { max_restarts: u32::MAX, .. }`) and the equivalent
4392/// author-surface form (`:max-restarts 4294967295` or any
4393/// `:max-restarts 100000`-shape typo landing in the slot) both round-trip
4394/// cleanly through serde — a structurally unbounded `u32` ceiling. The
4395/// runtime substrate consuming the value (Erlang/OTP's
4396/// `MaxIntensity / Period` ratio, the future wasm-operator's
4397/// per-supervisor restart-intensity counter, the M4
4398/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook)
4399/// then turned a typed `:max-restarts` policy into a no-op supervisor: the
4400/// escalation threshold is structurally so high that no realistic
4401/// restarts-per-`:restart-window` traffic shape can reach it, the
4402/// supervisor never escalates to its parent, and a bad child can loop
4403/// inside the window indefinitely with the parent supervisor structurally
4404/// never receiving the "this subtree has exceeded its restart budget"
4405/// signal the typed slot is meant to express — the canonical
4406/// "supervisor intensity declared, no escalation" footgun, exactly the
4407/// peer of the [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap
4408/// on the `:politicas :circuit-breaker :max-failures` axis (both are
4409/// "trip the next-higher protection layer after N events in a rolling
4410/// window" counters with identical degenerate-at-the-high-end shape).
4411///
4412/// The `1000` ceiling matches the sibling
4413/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] (the closest
4414/// peer — same "events-per-window trip threshold" semantics, same `u32`
4415/// type, same no-op-at-the-high-end failure mode) so the M4
4416/// `mesh.pleme.io/v1alpha1/Supervisor` / `.../Aplicacao` CR materializers
4417/// and the future wasm-operator's per-supervisor restart-intensity
4418/// counter reach for either field knowing the value is in `1..=1000`
4419/// without re-validating at the reconciler layer. The cap sits two
4420/// orders of magnitude above every documented Erlang/OTP production
4421/// playbook recommendation (Learn You Some Erlang's
4422/// `{intensity, 5, 60}` worker-supervisor default, Elixir's `Supervisor`
4423/// `max_restarts: 3` default, OTP's `supervisor` callback module
4424/// `MaxR = 1` / `MaxT = 5` "minimal-restart" default, Riak Core's
4425/// typical `MaxR ∈ 5..=100`, RabbitMQ's broker-supervisor `MaxR = 5`
4426/// default) and below the clearly-pathological "effectively no
4427/// escalation" floor (`10_000`, `100_000`, `u32::MAX`): a value the
4428/// author can plausibly want at hyperscale (a long-running supervisor
4429/// over a very-flaky pool tolerating thousands of transient restarts
4430/// before escalating), but a hard wall above which the typed policy is
4431/// structurally a no-op carried verbatim on every emitted child-restart
4432/// reconciliation contract.
4433///
4434/// Lifted as a typed `pub const` so the bound has exactly one source of
4435/// truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
4436/// materializer's admission webhook and the wasm-operator-side
4437/// per-supervisor restart-intensity reconciler read from one place. Same
4438/// shape every other typed upper bound in this crate carries
4439/// ([`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
4440/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
4441/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
4442/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
4443/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
4444/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
4445pub const SUPERVISOR_MAX_RESTARTS_MAX: u32 = 1000;
4446
4447/// Upper-bound ceiling on the `:supervisor :restart-window` axis —
4448/// every validated `Some(`[`SupervisorSpec::restart_window`]`)` past
4449/// [`SupervisorSpec::validate`] lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
4450/// (inclusive on both ends, integer-millisecond magnitudes by the
4451/// canonical-form gate immediately preceding).
4452///
4453/// The typed field is `Option<Duration>` (the zero-floor arm
4454/// [`SupervisorError::RestartWindowZero`] already rejects
4455/// `Some(Duration::ZERO)`, and the canonical-form arm
4456/// [`SupervisorError::RestartWindowNotCanonical`] already rejects
4457/// sub-millisecond residue), so a programmatic struct literal
4458/// (`SupervisorSpec { restart_window: Some(Duration::from_secs(86_400)),
4459/// .. }` — 24h) and the equivalent author-surface form
4460/// (`(:supervisor (:restart-window "24h"))` — the shared duration codec
4461/// emits `"<n>h"` for any integer-hour magnitude) both round-trip
4462/// cleanly through serde — a structurally unbounded `Duration` ceiling.
4463/// A `:restart-window` value far above the documented Erlang/OTP
4464/// `MaxIntensity / Period` production-playbook band (Learn You Some
4465/// Erlang's `{intensity, 5, 60}` worker-supervisor `Period = 60s`
4466/// default, Elixir's `Supervisor` `max_seconds: 5` default, OTP's
4467/// `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's
4468/// `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default)
4469/// degenerates the supervisor's restart-intensity counter into a
4470/// lifetime counter: the rolling failure-counting window is structurally
4471/// so long that transient restarts are never forgotten, so the
4472/// `MaxIntensity / Period` ratio degenerates from "trip the parent
4473/// supervisor when the child has exceeded its restart budget *within
4474/// the recent window*" to "trip the parent when the child has exceeded
4475/// its restart budget *over its lifetime*" — every transient restart
4476/// counts against the budget forever, the supervisor's reset semantic
4477/// never reaches the child, and the typed `:restart-window` slot
4478/// becomes a no-op rolling window carried on every emitted hierarchical
4479/// reconciliation contract. The canonical
4480/// rolling-window-degenerates-to-lifetime-counter footgun the sibling
4481/// [`crate::POLICY_BREAKER_WINDOW_MAX`] cap closes on the peer
4482/// `:politicas :circuit-breaker :window` axis with identical shape (both
4483/// are "rolling failure-counting window with a per-`Period` reset" Duration
4484/// axes whose lifetime-counter degenerate at the high end is the same
4485/// "the reset semantic never fires" CSE invariant violation).
4486///
4487/// The `1h` (3600s = `3_600_000` ms) ceiling matches the largest unit
4488/// the shared duration codec emits (`"<n>h"` for any integer-hour
4489/// magnitude) — every value in the canonical authoring form's
4490/// `<integer><unit>` grammar at or below this cap renders to a clean
4491/// canonical string — and matches the three sibling typed-`Duration`
4492/// caps already lifted to this surface
4493/// ([`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
4494/// [`crate::POLICY_BREAKER_WINDOW_MAX`]). All four typed-`Duration`
4495/// axes — per-process `:limits :wall-clock`, per-edge `:politicas
4496/// :timeout`, per-breaker `:politicas :circuit-breaker :window`, and
4497/// per-supervisor `:supervisor :restart-window` — now share a single
4498/// uniform top edge at the codec's largest emitted unit so the next
4499/// typed-slot wiring (the future wasm-operator's per-supervisor
4500/// `MaxIntensity / Period` reconciler, the M4
4501/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
4502/// webhook, the `caixa-operator`'s hierarchical reconciliation
4503/// scheduler) reaches for any of the four knowing the value is in
4504/// `1ms..=1h` without re-validating at the renderer layer. The cap sits
4505/// two orders of magnitude above every documented Erlang/OTP / Elixir /
4506/// Riak Core / RabbitMQ production-playbook recommendation band
4507/// (`5s..=300s`) and below the clearly-pathological "rolling window
4508/// degenerates to lifetime counter" floor (`24h`, `7d`, `Duration::MAX`):
4509/// a value the author can plausibly want for a very-low-traffic
4510/// long-tail failure-restart window over a hyperscale-flaky child pool,
4511/// but a hard wall above which the rolling-window contract is
4512/// structurally a lifetime-counter contract.
4513///
4514/// Lifted as a typed `pub const` so the bound has exactly one source
4515/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
4516/// materializer's admission webhook, the wasm-operator-side
4517/// per-supervisor `MaxIntensity / Period` reconciler, and the
4518/// `caixa-operator`'s hierarchical reconciliation scheduler all read
4519/// from one place. Same shape every other typed upper bound in this
4520/// crate carries ([`SUPERVISOR_MAX_RESTARTS_MAX`],
4521/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
4522/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
4523/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
4524/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
4525/// [`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
4526/// [`crate::POLICY_BREAKER_WINDOW_MAX`],
4527/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
4528/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
4529pub const SUPERVISOR_RESTART_WINDOW_MAX: Duration = Duration::from_secs(3600);
4530
4531/// Substrate-canonical Erlang/OTP-shaped `Period` sliding-window-duration
4532/// default for the `:supervisor :restart-window` axis — the canonical
4533/// `{intensity, 5, 60}` `Period` half of Learn You Some Erlang's
4534/// worker-supervisor default, extracted as a typed `pub const` so every
4535/// substrate-side consumer that resolves "what
4536/// [`SupervisorSpec::restart_window`] value does an author-omitted
4537/// `:restart-window` slot degrade onto?" reaches for exactly one
4538/// substrate-primitive [`Duration`].
4539///
4540/// The `:restart-window` default axis has one production consumer on the
4541/// substrate side today: the [`Default for SupervisorSpec`] impl's
4542/// struct-literal `restart_window` field, which prior to this lift folded
4543/// onto a raw `Duration::from_secs(60)` literal with no compile-time link
4544/// back to the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity`
4545/// half of the same `{intensity, 5, 60}` OTP-canonical default. The
4546/// [`crate::manifest::Caixa::supervisor_view`] fold deliberately does
4547/// *not* fall back to this default on the sibling `:restart-window` axis
4548/// — an author-omitted `:supervisor :restart-window` composes to
4549/// `restart_window: None` (the shared codec's soft-swallow shape),
4550/// keeping author-declared intent ("no reset — never escalate on rolling
4551/// window") distinct from the [`Default for SupervisorSpec`] "canonical
4552/// 60s Period" arm every programmatic `SupervisorSpec::default()` caller
4553/// resolves to. Prior to this lift the paired `{intensity, 5, 60}` OTP
4554/// default was split across two files with no compile-time link between
4555/// the halves: [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] pinned the
4556/// `MaxIntensity` half at the substrate primitive while the `Period`
4557/// half rode as an open-coded literal at the composition site, so a
4558/// future coherent rebrand of the paired canonical (a tightening to
4559/// Elixir's `{max_restarts: 3, max_seconds: 5}`, a widening to a
4560/// per-cluster overlay the operator pins through a future
4561/// `:supervisor :restart-window-overrides` slot the MESH-COMPOSITION
4562/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
4563/// paired constants to a per-child-cohort `{MaxR, MaxT}` restart-budget-
4564/// partition once the INSPIRATIONS §II.2 Erlang/OTP per-child-cohort
4565/// roadmap lands) would have had to migrate the `MaxIntensity` half
4566/// through the lifted constant and the `Period` half through a raw
4567/// literal in lockstep or the two halves of the same OTP-canonical
4568/// default would silently drift out of pairing. Lifting the resolution
4569/// rule to a typed `pub const` on the substrate primitive means the
4570/// paired OTP-canonical default migrates as one unit on any future
4571/// axis change.
4572///
4573/// The `60s` value pins Learn You Some Erlang's `{intensity, 5, 60}`
4574/// worker-supervisor default (the closest canonical OTP-shape
4575/// production reference the substrate carries, matching the paired
4576/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5` `MaxIntensity` half this
4577/// constant is the `Period` denominator of on the same
4578/// `MaxIntensity / Period` restart-intensity ratio). Two orders of
4579/// magnitude below the [`SUPERVISOR_RESTART_WINDOW_MAX`] `3600s`
4580/// (`1h`) ceiling (the upper bracket on the same axis, sibling of
4581/// this lower default; both are typed [`Duration`] const bounds on the
4582/// `:supervisor :restart-window` axis and now share one accessor
4583/// discipline on the substrate) and above the OTP-`supervisor`
4584/// callback-module `MaxT = 5` seconds "minimal-window" floor — the "60s
4585/// rolling window" default is deliberately loose enough to absorb a
4586/// short burst of transient child failures without escalating past the
4587/// supervisor's parent while remaining tight enough for the paired
4588/// `MaxIntensity / Period` ratio's escalation to trip on a genuinely-
4589/// stuck child within a human-scale observation window.
4590///
4591/// Lifted as a typed `pub const` so the paired OTP-canonical default has
4592/// exactly one source of truth on each half — the sibling
4593/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half and this
4594/// `Period` `60s` half now share the same substrate-primitive lift
4595/// discipline. Same shape every other typed default in this crate
4596/// carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] paired
4597/// `MaxIntensity` half on the same OTP-canonical `{intensity, 5, 60}`,
4598/// the sibling [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the same
4599/// axis, and the peer [`crate::render::DEFAULT_NAMESPACE`] /
4600/// [`crate::render::DEFAULT_LIBRARY_NAME`] per-renderer defaults on the
4601/// caixa-flux / caixa-helm rendering axes).
4602pub const SUPERVISOR_RESTART_WINDOW_DEFAULT: Duration = Duration::from_secs(60);
4603
4604/// Substrate-canonical Erlang/OTP-shaped sibling-restart-strategy default
4605/// for the `:supervisor :estrategia` axis — the canonical `one_for_one`
4606/// half of Learn You Some Erlang's `{one_for_one, intensity, 5, 60}`
4607/// worker-supervisor default, extracted as a typed `pub const` so every
4608/// substrate-side consumer that resolves "what
4609/// [`SupervisorSpec::estrategia`] variant does an author-omitted
4610/// `:estrategia` slot degrade onto?" reaches for exactly one substrate-
4611/// primitive [`RestartStrategy`].
4612///
4613/// The `:estrategia` default axis has three production consumers on the
4614/// substrate side today: the [`Default for RestartStrategy`] impl's
4615/// return arm, the [`Default for SupervisorSpec`] impl's struct-literal
4616/// `estrategia` field, and the
4617/// [`crate::manifest::Caixa::supervisor_view`] fold's
4618/// `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)` `Option<RestartStrategy>`
4619/// collapse arm — three entry points onto the same OTP-canonical
4620/// `one_for_one` value that prior to this lift folded onto a raw
4621/// `Self::OneForOne` arm at the [`Default for RestartStrategy`] impl and
4622/// implicit `RestartStrategy::default()` routes at the sibling consumers,
4623/// with no compile-time link back to the paired
4624/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` half + the paired
4625/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` half of the same
4626/// `{one_for_one, intensity, 5, 60}` OTP-canonical default. The paired
4627/// triple was split across three altitudes with no compile-time link
4628/// between the halves: the `MaxIntensity` half rode through the lifted
4629/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant (b698ec0) and the `Period`
4630/// half rode through the lifted [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
4631/// constant (f7dcd0e) while the `one_for_one` half rode as an open-coded
4632/// discriminator at the [`Default for RestartStrategy`] impl, so a future
4633/// coherent rebrand of the triple (Elixir's `{:one_for_one,
4634/// max_restarts: 3, max_seconds: 5}` — same strategy, different
4635/// intensity/period; an OTP `rest_for_one` widening once the substrate
4636/// discovers startup-order-coupled child cohorts as the more common
4637/// worker-supervisor default; a per-cluster overlay the operator pins
4638/// through a future `:estrategia-overrides` slot the MESH-COMPOSITION
4639/// §III.2 supervision-canary roadmap acknowledges) would have had to
4640/// migrate the `MaxIntensity` + `Period` halves through the lifted
4641/// constants and the `one_for_one` half through an open-coded arm in
4642/// lockstep or the three halves of the same OTP-canonical default would
4643/// silently drift out of pairing. Lifting the resolution rule to a typed
4644/// `pub const` on the substrate primitive means the paired OTP-canonical
4645/// worker-supervisor default migrates as one unit on any future axis
4646/// change.
4647///
4648/// The [`RestartStrategy::OneForOne`] value pins Learn You Some Erlang's
4649/// `{one_for_one, intensity, 5, 60}` worker-supervisor default (the
4650/// closest canonical OTP-shape production reference the substrate
4651/// carries, matching the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5`
4652/// `MaxIntensity` half and the paired [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
4653/// `60s` `Period` half). The `one_for_one` strategy — restart only the
4654/// failed child, leaving siblings untouched — is the default for tree-of-
4655/// independent-workers use cases the substrate's [`RestartStrategy`]
4656/// discriminator's own docstring already carries as the default arm; it
4657/// composes with the `{5, 60}` restart-intensity ratio to name the same
4658/// substrate-canonical "canonical worker-supervisor" shape the paired
4659/// halves close on their respective axes.
4660///
4661/// Lifted as a typed `pub const` so the paired OTP-canonical default has
4662/// exactly one source of truth on each of its three halves — the sibling
4663/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half, the
4664/// sibling [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` `60s` half, and
4665/// this `one_for_one` strategy half now share the same substrate-
4666/// primitive lift discipline. Same shape every other typed default in
4667/// this crate carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] +
4668/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] paired halves on the same OTP-
4669/// canonical `{one_for_one, intensity, 5, 60}`, the sibling
4670/// [`SUPERVISOR_MAX_RESTARTS_MAX`] + [`SUPERVISOR_RESTART_WINDOW_MAX`]
4671/// upper caps on the paired sibling axes, and the peer
4672/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
4673/// per-renderer defaults on the caixa-flux / caixa-helm rendering axes).
4674pub const SUPERVISOR_ESTRATEGIA_DEFAULT: RestartStrategy = RestartStrategy::OneForOne;
4675
4676/// Substrate-canonical Erlang/OTP-shaped per-child restart-decision-policy
4677/// default for the `:children :restart` axis — the OTP `permanent`
4678/// worker-child default (`{ChildId, StartFunc, permanent, …}` in a
4679/// `supervisor`'s `init/1` child-spec tuple), extracted as a typed
4680/// `pub const` so every substrate-side consumer that resolves "what
4681/// [`ChildSpec::restart`] variant does an author-omitted `:children
4682/// :restart` slot degrade onto?" reaches for exactly one substrate-
4683/// primitive [`RestartPolicy`].
4684///
4685/// Completes the OTP-shape supervisor-tree default set at the substrate
4686/// primitive. The per-`:supervisor` axis already carries all three of its
4687/// halves as lifted typed constants — [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
4688/// (`one_for_one`, 95ffacc), [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
4689/// (`MaxIntensity` `5`, b698ec0), [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
4690/// (`Period` `60s`, f7dcd0e) — while the per-`:children` axis's own
4691/// OTP-canonical default rode as an open-coded `Self::Permanent` arm in
4692/// the [`Default for RestartPolicy`] impl, the last un-lifted default on
4693/// the M2 `:supervisor` slot family. The split mattered because the two
4694/// axes resolve *together* on every author-omitted supervisor: a
4695/// `(defcaixa :kind Supervisor :children ((:caixa "worker" :versao
4696/// "^0.1")))` with no `:estrategia` and no per-child `:restart` degrades
4697/// onto `{one_for_one, 5, 60}` through three lifted constants and onto
4698/// `permanent` through an open-coded enum arm, so a future coherent
4699/// rebrand of the OTP-shape default set (an Elixir-shaped
4700/// `{:one_for_one, max_restarts: 3, max_seconds: 5}` tightening, a
4701/// per-cluster overlay the operator pins through the MESH-COMPOSITION
4702/// §III.2 supervision-canary roadmap slots, an OTP-`transient` widening
4703/// once the substrate discovers clean-completion-aware children as the
4704/// more common child shape) would have had to migrate three halves
4705/// through typed constants and the fourth through a raw enum arm in
4706/// lockstep or the supervisor-level and child-level defaults would
4707/// silently drift apart.
4708///
4709/// The `:children :restart` default axis has two production consumers on
4710/// the substrate side today: the [`Default for RestartPolicy`] impl's
4711/// return arm, and the serde-side `#[serde(default)]` on
4712/// [`ChildSpec::restart`] that resolves an author-omitted `:children
4713/// :restart` slot through that same impl. Both now key off this one
4714/// substrate primitive, so the future wasm-operator's per-child post-exit
4715/// restart-decision branch, the future M4
4716/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
4717/// admission webhook, and the `caixa-operator`'s hierarchical
4718/// reconciliation scheduler's per-child fan-out all reach for one typed
4719/// identifier when they resolve an omitted per-child restart posture.
4720///
4721/// The [`RestartPolicy::Permanent`] value pins Erlang/OTP's `permanent`
4722/// worker-child restart type — always restart the child regardless of how
4723/// it died, the canonical posture for long-running services that must
4724/// always be up, matching the sibling [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
4725/// `one_for_one` tree-of-independent-workers strategy this constant pairs
4726/// with under the same `{one_for_one, intensity, 5, 60}` worker-supervisor
4727/// shape. The two alternatives the closed [`RestartPolicy::ALL`] accept-set
4728/// carries ([`RestartPolicy::Transient`] — restart only on abnormal exit;
4729/// [`RestartPolicy::Temporary`] — never restart) express deliberate
4730/// one-shot / clean-completion-aware postures an author declares
4731/// explicitly, never a posture an omitted slot should silently assume.
4732pub const SUPERVISOR_CHILD_RESTART_DEFAULT: RestartPolicy = RestartPolicy::Permanent;
4733
4734/// Route the manually-authored [`Default`] impl on [`SupervisorSpec`]
4735/// through the substrate-canonical [`SupervisorSpec::otp_canonical`]
4736/// `pub const fn` constructor rather than a struct-literal cascade over
4737/// the paired [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
4738/// [`default_max_restarts`] / [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
4739/// lifted consts — one source of truth for the Erlang/OTP-canonical
4740/// `{one_for_one, 5, 60}` worker-supervisor baseline across the two
4741/// paths every downstream consumer already reaches through (the
4742/// hand-authored-until-now [`Default::default`] the
4743/// `..SupervisorSpec::default()` struct-update-syntax on every
4744/// one-axis-under-test fixture in this crate's test module rests on,
4745/// and the `pub const fn` [`SupervisorSpec::otp_canonical`] constructor
4746/// every `const`-context consumer reaches through).
4747///
4748/// Extends the [`Default`]-through-const-ctor fold discipline the
4749/// [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
4750/// (abd52c2), [`crate::aplicacao::MeshPolicy`]
4751/// [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`] (91641a4),
4752/// and [`crate::BehaviorSpec`]
4753/// [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c) folds
4754/// closed on the M2 / M3 `Option`-only "canonical unset baseline"
4755/// typed-slot spec family — extended here onto the M2 supervisor-slot
4756/// [`SupervisorSpec`] whose canonical baseline is not "everything
4757/// `None`" but the OTP-canonical `{one_for_one, 5, 60}` worker-
4758/// supervisor triple. The `empty()` peer's naming did not fit
4759/// (`SupervisorSpec` carries a discriminator-shaped `estrategia` field
4760/// and a non-zero `max_restarts`/`restart_window` pair whose canonical
4761/// shape is Erlang/OTP-descended, not the "no axis declared" bottom
4762/// the sibling `Option`-only slots fold to), so this peer is named
4763/// [`SupervisorSpec::otp_canonical`] instead — the same phrasing the
4764/// existing per-arm pin tests
4765/// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`] /
4766/// [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`] /
4767/// [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
4768/// already reach for. Pinned load-bearing by
4769/// [`tests::supervisor_spec_default_routes_through_otp_canonical_ctor`]
4770/// (byte-parity pin against [`SupervisorSpec::otp_canonical`] under
4771/// [`PartialEq`], sharpening the sibling
4772/// `supervisor_spec_default_*_routes_through_lifted_default` per-arm
4773/// pins from a per-field lift into a whole-struct one-source-of-truth
4774/// pin — the derived-until-now [`Default::default`] and the
4775/// [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
4776/// construction, not by coincidence).
4777impl Default for SupervisorSpec {
4778    #[inline]
4779    fn default() -> Self {
4780        Self::otp_canonical()
4781    }
4782}
4783
4784impl SupervisorSpec {
4785    /// `const`-context peer of the [`Default for SupervisorSpec`]
4786    /// impl (which routes through this constructor) — returns the
4787    /// Erlang/OTP-canonical `{one_for_one, 5, 60}` worker-supervisor
4788    /// baseline this crate reaches for in every fixture-builder
4789    /// `..SupervisorSpec::default()` struct-update expression and
4790    /// every downstream `SupervisorSpec::default()` seed.
4791    ///
4792    /// Each field routes through the same substrate-canonical
4793    /// [`SUPERVISOR_ESTRATEGIA_DEFAULT`] / [`default_max_restarts`] /
4794    /// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] lifted consts the
4795    /// per-arm pin tests
4796    /// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`]
4797    /// / [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`]
4798    /// / [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
4799    /// already assert, so a future coherent rebrand of the OTP-canonical
4800    /// triple (Elixir's `{max_restarts: 3, max_seconds: 5}`, a per-
4801    /// cluster overlay via a future `:restart-window-overrides` slot, a
4802    /// per-child-cohort promotion the INSPIRATIONS.md §II.2 Erlang/OTP
4803    /// absorption roadmap acknowledges) migrates through three typed
4804    /// constants in lockstep, and the paired [`Default`] impl inherits
4805    /// every future extension by construction.
4806    ///
4807    /// `pub const fn` rather than the derived-style `Default::default`
4808    /// or a `pub const SUPERVISOR_SPEC_DEFAULT: SupervisorSpec` item —
4809    /// [`Default::default`] is not `const` on stable Rust, and
4810    /// `SupervisorSpec` is non-`Copy` so a `pub const` item would force
4811    /// every consumer through a [`Clone::clone`]. The `pub const fn`
4812    /// discipline lets `const`-context callers construct the OTP-
4813    /// canonical baseline at compile time without runtime dispatch on
4814    /// the derived [`Default::default`], the same posture the sibling
4815    /// [`crate::LimitsSpec::empty`] (9739971) /
4816    /// [`crate::aplicacao::MeshPolicy::empty`] (6df969b) /
4817    /// [`crate::BehaviorSpec::empty`] (f9b18e3) `Option`-only typed-slot
4818    /// spec `pub const fn` constructors carry on the sibling
4819    /// "everything `None`" baseline axis.
4820    ///
4821    /// Fourth peer on the M2 / M3 typed-slot-spec "const-context peer
4822    /// of the derived-style [`Default`]" family — sibling of the
4823    /// [`crate::LimitsSpec::empty`] / [`crate::aplicacao::MeshPolicy::empty`]
4824    /// / [`crate::BehaviorSpec::empty`] `Option`-only "canonical unset
4825    /// baseline" trio, extended here onto the M2 supervisor-slot
4826    /// [`SupervisorSpec`] whose canonical baseline is not "everything
4827    /// `None`" but the Erlang/OTP-canonical `{one_for_one, 5, 60}`
4828    /// worker-supervisor triple. Named [`Self::otp_canonical`] rather
4829    /// than `empty()` to name the actual invariant the return value
4830    /// pins — the same phrasing already used in the per-arm pin tests
4831    /// on this file. Pinned load-bearing by
4832    /// [`tests::supervisor_spec_otp_canonical_byte_equals_default`] and
4833    /// [`tests::supervisor_spec_otp_canonical_is_usable_in_const_context`].
4834    #[must_use]
4835    pub const fn otp_canonical() -> Self {
4836        Self {
4837            estrategia: SUPERVISOR_ESTRATEGIA_DEFAULT,
4838            max_restarts: default_max_restarts(),
4839            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
4840            children: Vec::new(),
4841        }
4842    }
4843
4844    /// Substrate-canonical per-`:supervisor` `:estrategia` OTP-shaped
4845    /// sibling-restart-strategy scalar accessor every consumer that
4846    /// dispatches on the supervisor's per-sibling restart-decision shape
4847    /// keys off — returns the author-declared `:supervisor :estrategia`
4848    /// variant verbatim as a [`RestartStrategy`], `Copy`-projected from
4849    /// the typed slot's own [`RestartStrategy`] storage.
4850    ///
4851    /// The `:supervisor :estrategia` slot carries the closed-set
4852    /// OTP-shaped sibling-restart-strategy discriminator ([`RestartStrategy::OneForOne`]
4853    /// — restart only the failed child, the Erlang/OTP `one_for_one` default;
4854    /// [`RestartStrategy::OneForAll`] — restart every child on any child
4855    /// failure, the Erlang/OTP `one_for_all` shared-state cohort default;
4856    /// [`RestartStrategy::RestForOne`] — restart the failed child and
4857    /// every child started after it, the Erlang/OTP `rest_for_one`
4858    /// startup-order default; [`RestartStrategy::SimpleOneForOne`] —
4859    /// dynamic children of the same shape, the Erlang/OTP
4860    /// `simple_one_for_one` per-session default) that every downstream
4861    /// consumer of the Supervisor's per-sibling restart-decision fan-out
4862    /// shape keys off. Validated by [`SupervisorSpec::validate`] to be
4863    /// paired coherently with the sibling `:children` axis
4864    /// (`SimpleOneForOne ↔ children.is_empty()` — the cross-slot
4865    /// partition the strategy-arm's [`SupervisorError::SimpleOneForOneWithStaticChildren`]
4866    /// / [`SupervisorError::NoChildren`] refusal cascade pins), and every
4867    /// downstream consumer that reads the strategy keys off this scalar
4868    /// (the [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
4869    /// partition-dispatch `match` arm, the non-`SimpleOneForOne`-arm
4870    /// declared-but-empty [`SupervisorError::NoChildren`] error carrier's
4871    /// `estrategia:` field, the future `feira app graph` per-Supervisor
4872    /// strategy print line, the future wasm-operator's per-supervisor
4873    /// sibling-restart-strategy branch, the future M4
4874    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-strategy
4875    /// admission-webhook resolver, the `caixa-operator`'s hierarchical
4876    /// reconciliation scheduler's per-strategy fan-out).
4877    ///
4878    /// Prior to this lift the `.estrategia` field was accessed inline at
4879    /// two production sites in `caixa-core/src/supervisor.rs` — the
4880    /// [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
4881    /// `match self.estrategia { … }` partition dispatch, and the
4882    /// non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
4883    /// carrier at `estrategia: self.estrategia` — two open-coded
4884    /// field-accesses that expressed no compile-time link back to the
4885    /// typed slot. A future extension of the `:supervisor :estrategia`
4886    /// axis to a richer author surface (a per-cluster strategy override
4887    /// the operator pins through a future `:supervisor :estrategia-overrides`
4888    /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
4889    /// acknowledges, a per-tenant strategy-alias table the M4 CR
4890    /// materializer resolves per-CR, a per-Supervisor dynamic strategy
4891    /// derivation the future adaptive-supervision engine computes from
4892    /// child-failure-history topology, a per-child-cohort strategy split
4893    /// the future `RestForCohort` extension acknowledged by the
4894    /// INSPIRATIONS.md §II.2 Erlang/OTP absorption roadmap acknowledges)
4895    /// would have had to be threaded through every open-coded copy in
4896    /// lockstep — one consumer reading the raw variant while a peer read
4897    /// the operator-resolved variant would silently split the
4898    /// [`SupervisorError::NoChildren`] diagnostic's quoted strategy from
4899    /// the actual partition-dispatch input the empty-children refusal
4900    /// arm reached under, a two-consumer split at the validator far from
4901    /// the source `caixa.lisp` with no field naming the strategy-drift
4902    /// root cause. Lifting the resolution rule to a typed method on the
4903    /// substrate primitive means every downstream consumer of the
4904    /// Supervisor's per-`:supervisor` sibling-restart-strategy surface
4905    /// reaches for exactly one typed dispatch — the resolver's accept-set
4906    /// migrates as a unit on any future axis addition.
4907    ///
4908    /// Peer of the sibling M3 mesh-slot [`crate::Placement::estrategia`]
4909    /// (921fe1b) `Copy`-return `PlacementStrategy` scalar accessor on the
4910    /// per-`:placement` distribution-strategy axis — same "one typed
4911    /// dispatch on the substrate primitive, thin projections at each
4912    /// consumer" discipline extended onto the M2 supervisor-slot
4913    /// per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
4914    /// scalar axis. The two typed axes (`Placement::estrategia` on the
4915    /// M3 Aplicacao side, `SupervisorSpec::estrategia` on the M2
4916    /// Supervisor side) now share one accessor discipline for the shared
4917    /// substrate concept "a `Copy`-projected closed-set enum-arm
4918    /// discriminator that partitions the downstream renderer's per-arm
4919    /// fan-out". First `Copy`-return accessor on the M2 supervisor-slot
4920    /// `SupervisorSpec` type — companion to the sibling per-`:children`
4921    /// [`crate::ChildSpec::nome`] (57c61d0) /
4922    /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
4923    /// scalar accessors on the sibling per-`:children` `String`-carry
4924    /// axes. Named `estrategia()` to match the storage field's name and
4925    /// the peer [`crate::Placement::estrategia`] method-name discipline
4926    /// verbatim; the accessor's identity name maps onto the canonical
4927    /// OTP-shape supervision vocabulary the [`RestartStrategy`] enum's
4928    /// docstring already carries.
4929    ///
4930    /// Declared `pub const fn` to close the M2 supervisor-slot
4931    /// `Copy`-return raw-field-getter `const`-eval-surface pass —
4932    /// sibling of the peer M2 per-`:children` [`ChildSpec::restart`]
4933    /// (converted in this commit) `Copy`-composite-enum accessor, peer
4934    /// of the sibling M2 per-`:supervisor`
4935    /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
4936    /// already lifted, and mirror of the peer M3 mesh-slot
4937    /// per-`:placement` [`crate::Placement::estrategia`] (bafa004)
4938    /// `Copy`-return `pub const fn` scalar accessor whose method-name
4939    /// discipline this accessor was authored to match. Every downstream
4940    /// substrate-side `const`-context consumer of the per-`:supervisor`
4941    /// sibling-restart-strategy scalar (a future module-scope `const
4942    /// _:() = assert!(matches!(sup.estrategia(),
4943    /// RestartStrategy::OneForOne))` invariant pin on a typed fixture,
4944    /// a future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
4945    /// admission-webhook `const fn` per-supervisor strategy-arm floor
4946    /// over a typed [`SupervisorSpec`], any future `const fn`
4947    /// supervisor-tree composer over the substrate primitive that fans
4948    /// on the sibling-restart-strategy at compile time) now reaches
4949    /// through the same typed dispatch on the substrate primitive at
4950    /// const-eval time as at runtime. A future non-`Copy`-return
4951    /// promotion of the scalar (an `Option<RestartStrategy>`-shape
4952    /// migration once the substrate grows per-cluster strategy overlays
4953    /// the [`SupervisorSpec`] docstring already anticipates, a
4954    /// per-tenant strategy-alias table the M4 CR materializer resolves
4955    /// per-CR) that would drop the `const` qualifier fails the
4956    /// fail-before-pass-after pin
4957    /// [`tests::supervisor_spec_estrategia_accessor_is_const_fn`] at
4958    /// caixa-core build time rather than surfacing as a downstream
4959    /// consumer regression.
4960    #[must_use]
4961    pub const fn estrategia(&self) -> RestartStrategy {
4962        self.estrategia
4963    }
4964
4965    /// Substrate-canonical per-`:supervisor` `:max-restarts` OTP-shaped
4966    /// `MaxIntensity` restart-budget scalar accessor every consumer that
4967    /// reads the supervisor's per-`:restart-window` restart-budget count
4968    /// keys off — returns the author-declared `:supervisor :max-restarts`
4969    /// typed `u32` verbatim, `Copy`-projected from the typed slot's own
4970    /// `u32` storage (`u32` is `Copy`, so the accessor returns by value; no
4971    /// borrow of `&self` past the call). Non-optional (the `u32` field
4972    /// carries the restart-budget count as a required axis with a
4973    /// [`default_max_restarts`]-supplied default; the zero-floor arm
4974    /// [`SupervisorError::ZeroMaxRestarts`] and the cap arm
4975    /// [`SupervisorError::MaxRestartsExceedsCap`] jointly bracket the
4976    /// accept-set to `1..=SUPERVISOR_MAX_RESTARTS_MAX`).
4977    ///
4978    /// The `:supervisor :max-restarts` slot carries the Erlang/OTP
4979    /// `MaxIntensity` restart-budget count that pairs with the sibling
4980    /// `:restart-window` `Period` to form the `MaxIntensity / Period`
4981    /// restart-intensity ratio the supervisor trips its own escalation on
4982    /// (`theory/RUNTIME-PATTERNS.md` §II.2, Learn You Some Erlang's
4983    /// `{intensity, 5, 60}` worker-supervisor default). Every downstream
4984    /// consumer of the Supervisor's per-`:supervisor` restart-budget count
4985    /// keys off this scalar (the [`SupervisorSpec::validate`] zero-floor +
4986    /// upper-cap bracket at
4987    /// `require_positive_bounded_u32(self.max_restarts(), …)`, the future
4988    /// wasm-operator's per-supervisor restart-intensity counter's
4989    /// budget-vs-count comparator, the future M4
4990    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
4991    /// webhook, the `caixa-operator`'s hierarchical reconciliation
4992    /// scheduler's per-supervisor escalation-decision branch, every
4993    /// `SupervisorError::MaxRestartsExceedsCap` variant carrying the
4994    /// offending count verbatim for `feira lint` rendering).
4995    ///
4996    /// Prior to this lift the `.max_restarts` field was accessed inline at
4997    /// one production site in `caixa-core/src/supervisor.rs` — the
4998    /// [`SupervisorSpec::validate`] `require_positive_bounded_u32(self
4999    /// .max_restarts, …)` bracket-gate call — one open-coded field-access
5000    /// that expressed no compile-time link back to the typed slot. A
5001    /// future extension of the `:max-restarts` axis to a richer author
5002    /// surface (a per-cluster restart-budget override the operator pins
5003    /// through a future `:supervisor :max-restarts-overrides` slot the
5004    /// MESH-COMPOSITION §III.2 supervision-canary roadmap acknowledges,
5005    /// a per-tenant restart-budget-alias table the M4 CR materializer
5006    /// resolves per-CR, a per-supervisor dynamic restart-budget derivation
5007    /// the future adaptive-supervision engine computes from child-failure-
5008    /// history topology, a promotion of the plain `u32` count to a richer
5009    /// `{MaxR, MaxT}` tuple once Erlang/OTP's per-child-cohort restart-
5010    /// budget-partition slot comes into scope) would have had to be
5011    /// threaded through every open-coded copy in lockstep or the validate
5012    /// gate and the future M4 emit path would silently disagree on which
5013    /// restart-budget count a given supervisor resolves to — an author's
5014    /// `:max-restarts 5` would satisfy validate while the emit path
5015    /// silently read a drifted other value (a `:max-restarts 10000`
5016    /// no-op supervisor at the emit boundary would carry the author's
5017    /// declared `5` verbatim in `feira lint` output while the future
5018    /// wasm-operator's restart-intensity counter operated under the
5019    /// drifted count), a two-consumer split at the validator far from the
5020    /// source `caixa.lisp` with no field naming the restart-budget-drift
5021    /// root cause. Lifting the resolution rule to a typed method on the
5022    /// substrate primitive means every downstream consumer of the
5023    /// Supervisor's per-`:supervisor` restart-budget-count surface reaches
5024    /// for exactly one typed dispatch — the resolver's accept-set migrates
5025    /// as a unit on any future axis addition.
5026    ///
5027    /// Peer of the sibling M3 mesh-slot [`crate::CircuitBreaker::max_failures`]
5028    /// (3a74062) `Copy`-return `u32` sub-struct required-scalar accessor
5029    /// on the per-`:politicas :circuit-breaker :max-failures` Envoy-
5030    /// outlier-detection trip-threshold axis — same "one typed dispatch on
5031    /// the substrate primitive, thin projections at each consumer"
5032    /// discipline extended onto the M2 supervisor-slot per-`:supervisor`
5033    /// restart-budget-count `Copy`-`u32` scalar axis. The two typed axes
5034    /// (`CircuitBreaker::max_failures` on the M3 Aplicacao side,
5035    /// `SupervisorSpec::max_restarts` on the M2 Supervisor side) now share
5036    /// one accessor discipline for the shared substrate concept "a
5037    /// `Copy`-projected required `u32` count that trips the next-higher
5038    /// protection layer after N events in a rolling window" — both are
5039    /// counters with identical degenerate-at-the-high-end shape and share
5040    /// the paired [`crate::POLICY_BREAKER_MAX_FAILURES_MAX`] /
5041    /// [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` cap. Second `Copy`-return
5042    /// accessor on the M2 supervisor-slot `SupervisorSpec` type, sibling
5043    /// to the [`SupervisorSpec::estrategia`] (eafb619) `Copy`-composite-
5044    /// enum `RestartStrategy` accessor. Named `max_restarts()` to match
5045    /// the storage field's name verbatim and the peer
5046    /// [`crate::CircuitBreaker::max_failures`] method-name discipline; the
5047    /// accessor's identity maps onto the canonical OTP-shape supervision
5048    /// vocabulary the [`SupervisorSpec::max_restarts`] field's docstring
5049    /// already carries.
5050    #[must_use]
5051    pub const fn max_restarts(&self) -> u32 {
5052        self.max_restarts
5053    }
5054
5055    /// Substrate-canonical per-`:supervisor` `:restart-window` OTP-shaped
5056    /// `Period` sliding-window scalar accessor every consumer of the
5057    /// supervisor's `MaxIntensity / Period` restart-intensity denominator
5058    /// keys off — returns the author-declared `:supervisor :restart-window`
5059    /// typed [`Duration`] verbatim as an `Option<Duration>`, copied out of
5060    /// the typed slot's own `Option<Duration>` storage (`Duration` is
5061    /// `Copy`, so `Option<Duration>` is `Copy` and the accessor returns by
5062    /// value; no borrow of `&self` past the call). `None` when the slot is
5063    /// absent (the canonical "never reset — every restart across the
5064    /// supervisor's lifetime counts against the sibling `:max-restarts`
5065    /// budget" sentinel the field's own docstring names and the peer
5066    /// `validate_accepts_none_restart_window` pin locks in on the
5067    /// [`SupervisorSpec::validate`] entry-side).
5068    ///
5069    /// The `:supervisor :restart-window` slot carries the Erlang/OTP
5070    /// `Period` sliding-observation-interval that pairs with the sibling
5071    /// `:max-restarts` `MaxIntensity` restart-budget count to form the
5072    /// `MaxIntensity / Period` restart-intensity ratio the supervisor
5073    /// trips its own escalation on (`theory/RUNTIME-PATTERNS.md` §II.2,
5074    /// Learn You Some Erlang's `{intensity, 5, 60}` worker-supervisor
5075    /// default). The typed slot's `Option<Duration>` accept-set —
5076    /// zero-floor rejected through [`SupervisorError::RestartWindowZero`]
5077    /// (Erlang/OTP's `MaxIntensity / Period` invariant requires
5078    /// `Period > 0`; a zero period either trips on the first failure or
5079    /// never trips depending on operator interpretation, neither of which
5080    /// is the author's intent — omit the slot to express "no reset";
5081    /// carry a positive duration to express the sliding window),
5082    /// integer-millisecond canonical form enforced through
5083    /// [`SupervisorError::RestartWindowNotCanonical`] (the duration
5084    /// codec's canonical form emits `"1500ms"` not `"1.5s"` and the
5085    /// future wasm-operator's per-supervisor restart-intensity counter
5086    /// quantizes at milliseconds), upper-bounded by
5087    /// [`SUPERVISOR_RESTART_WINDOW_MAX`] (1h — the coarsest per-
5088    /// supervisor rolling window any operationally-reachable supervisor
5089    /// can honor without spanning multiple scheduler epochs the
5090    /// hierarchical-reconciliation scheduler treats as independent) —
5091    /// maps onto the future wasm-operator (M3) per-supervisor
5092    /// restart-intensity counter's rolling-observation-interval, the
5093    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
5094    /// per-`spec.restartWindow` admission webhook, and the sibling
5095    /// `duration_codec`-serialized wire scalar every downstream consumer
5096    /// of the supervisor's per-`:supervisor` restart-intensity denominator
5097    /// keys off.
5098    ///
5099    /// Prior to this lift the `.restart_window` field was accessed inline
5100    /// at one production site in `caixa-core/src/supervisor.rs` — the
5101    /// [`SupervisorSpec::validate`] `if let Some(w) = self.restart_window {
5102    /// … }` zero-floor + canonical-form + upper-cap bracket arm — one
5103    /// open-coded field-access that expressed no compile-time link back to
5104    /// the typed slot. A future extension of the `:restart-window` axis to
5105    /// a richer author surface (a per-cluster restart-window override the
5106    /// operator pins through a future `:supervisor :restart-window-overrides`
5107    /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
5108    /// acknowledges, a per-tenant restart-window-alias table the M4 CR
5109    /// materializer resolves per-CR, a per-supervisor dynamic
5110    /// restart-window derivation the future adaptive-supervision engine
5111    /// computes from child-failure-history topology, a promotion of the
5112    /// plain `Option<Duration>` window to a richer `{observation, cooldown}`
5113    /// pair once Erlang/OTP's per-child-cohort observation-interval-
5114    /// partition slot comes into scope) would have had to be threaded
5115    /// through every open-coded copy in lockstep or the validate gate and
5116    /// the future M4 emit path would silently disagree on which
5117    /// restart-window a given supervisor resolves to — an author's
5118    /// `:restart-window "60s"` would satisfy validate while the emit path
5119    /// silently read a drifted other value (a `Some(Duration::from_secs(60))`
5120    /// authored slot at the emit boundary would carry the author's
5121    /// declared window verbatim in `feira lint` output while the future
5122    /// wasm-operator's restart-intensity counter operated under a
5123    /// drifted window, or vice versa: an author's `:restart-window ()`
5124    /// would carry the "never reset" sentinel through validate while the
5125    /// emit path silently substituted a default sliding window), a
5126    /// two-consumer split at the validator far from the source
5127    /// `caixa.lisp` with no field naming the restart-window-drift root
5128    /// cause. Lifting the resolution rule to a typed method on the
5129    /// substrate primitive means every downstream consumer of the
5130    /// Supervisor's per-`:supervisor` restart-intensity-denominator
5131    /// surface reaches for exactly one typed dispatch — the resolver's
5132    /// accept-set migrates as a unit on any future axis addition.
5133    ///
5134    /// Third `Copy`-return accessor on the M2 supervisor-slot
5135    /// `SupervisorSpec` type, closing the last unlifted per-`:supervisor`
5136    /// scalar-value axis (`children: Vec<ChildSpec>` carries a `Vec`
5137    /// payload rather than a `Copy`-scalar, and the per-`:children`
5138    /// [`crate::ChildSpec::nome`] (57c61d0) /
5139    /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
5140    /// scalar accessors already close the per-element `String`-carry
5141    /// axes). Sibling to the peer M2 [`crate::LimitsSpec::wall_clock`]
5142    /// (8cb717b) `Option<Duration>` accessor on the `:limits` slot's
5143    /// per-outermost-call wall-clock-deadline axis and the peer M3
5144    /// [`crate::MeshPolicy::timeout`] (7073d0f) `Option<Duration>`
5145    /// accessor on the `:politicas` slot's per-call-deadline axis — all
5146    /// three share the shared substrate concept "a `Copy`-projected
5147    /// optional `Duration` that carries a positive integer-millisecond
5148    /// canonical value with a `1ms..=<axis-specific>_MAX` accept-set and
5149    /// the paired zero-floor / non-canonical / above-cap refusal cascade"
5150    /// through the same [`crate::render::require_positive_canonical_bounded_duration`]
5151    /// bracket-helper the three axes each route through. Named
5152    /// `restart_window()` to match the storage field's name verbatim and
5153    /// the peer [`crate::LimitsSpec::wall_clock`] /
5154    /// [`crate::MeshPolicy::timeout`] method-name discipline; the
5155    /// accessor's identity maps onto the canonical OTP-shape supervision
5156    /// vocabulary the [`SupervisorSpec::restart_window`] field's docstring
5157    /// already carries.
5158    #[must_use]
5159    pub const fn restart_window(&self) -> Option<Duration> {
5160        self.restart_window
5161    }
5162
5163    /// Substrate-canonical per-`:supervisor` `:children` OTP-shaped
5164    /// static-child-list slice accessor every consumer that walks the
5165    /// supervisor's declared child set keys off — returns the author-
5166    /// declared `:supervisor :children` `Vec<ChildSpec>` verbatim as a
5167    /// `&[ChildSpec]` slice-view, borrowed from the typed slot's own
5168    /// `Vec<ChildSpec>` storage (a zero-copy slice-view over the same
5169    /// backing buffer the `Serialize`/`Deserialize` derives round-trip
5170    /// through). Non-optional: an empty slice is the load-bearing
5171    /// "author declared `:children ()`" sentinel every consumer of the
5172    /// cross-slot `SimpleOneForOne ↔ children.is_empty()` partition
5173    /// keys off (`SimpleOneForOne` requires the empty slice; the peer
5174    /// three strategies require a non-empty slice — the paired
5175    /// [`SupervisorError::SimpleOneForOneWithStaticChildren`] /
5176    /// [`SupervisorError::NoChildren`] refusal cascade pins the
5177    /// partition on both arms).
5178    ///
5179    /// The `:supervisor :children` slot carries the OTP-shaped static
5180    /// child list the supervisor materializes one ComputeUnit per
5181    /// entry from — the Erlang/OTP `supervisor:init/1`'s
5182    /// `{ok, {SupFlags, ChildSpecs}}` `ChildSpecs` list, projected
5183    /// through the tatara-lisp `:children` author surface onto a typed
5184    /// `Vec<ChildSpec>` whose per-element `(nome(),
5185    /// versao_requirement(), restart)` triple the per-child
5186    /// [`SupervisorSpec::validate`] loop already gates through the
5187    /// lifted [`ChildSpec::nome`] (57c61d0) /
5188    /// [`ChildSpec::versao_requirement`] (2c053c8) scalar accessors.
5189    /// Every downstream consumer that fans on the static child list
5190    /// keys off this slice (the [`SupervisorSpec::validate`]
5191    /// `SimpleOneForOne ↔ non-SimpleOneForOne` partition dispatch's
5192    /// `.is_empty()` probe on both arms, the [`SupervisorSpec::validate`]
5193    /// per-child DNS-1123 / semver-requirement / duplicate-detection
5194    /// fan-out loop, every future wasm-operator (M3) per-supervisor
5195    /// hierarchical-reconciliation scheduler's per-child ComputeUnit
5196    /// materialization loop, the future M4
5197    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
5198    /// admission-webhook fan-out, the future `feira app graph`
5199    /// per-supervisor tree-print traversal).
5200    ///
5201    /// Prior to this lift the `.children` `Vec<ChildSpec>` was accessed
5202    /// inline at three production sites in `caixa-core/src/supervisor.rs`
5203    /// — the [`SupervisorSpec::validate`] `SimpleOneForOne`-arm
5204    /// `!self.children.is_empty()` cross-slot refusal probe, the peer
5205    /// non-`SimpleOneForOne`-arm `self.children.is_empty()`
5206    /// [`SupervisorError::NoChildren`] refusal probe, and the per-child
5207    /// validate loop's `for child in &self.children` traversal head —
5208    /// three open-coded field-accesses that expressed no compile-time
5209    /// link back to the typed slot. A future extension of the
5210    /// `:supervisor :children` axis to a richer author surface (a
5211    /// per-cluster child-set overlay the operator pins through a future
5212    /// `:supervisor :children-overrides` slot the MESH-COMPOSITION §III.2
5213    /// supervision-canary roadmap acknowledges, a per-tenant
5214    /// child-set-alias table the M4 CR materializer resolves per-CR,
5215    /// a per-supervisor dynamic-child derivation the future adaptive-
5216    /// supervision engine computes from child-failure-history topology,
5217    /// a promotion of the plain `Vec<ChildSpec>` to a richer
5218    /// `{static, dynamic}` partition once Erlang/OTP's
5219    /// `simple_one_for_one` dynamic-child slot comes into typed scope)
5220    /// would have had to be threaded through all three open-coded copies
5221    /// in lockstep or one consumer would silently disagree with the
5222    /// peers on which child-set a given supervisor resolves to — the
5223    /// `SimpleOneForOne`-arm probe reading the raw slot while the peer
5224    /// non-`SimpleOneForOne`-arm probe read an operator-resolved slot
5225    /// would silently split the partition-dispatch's two-arm coherence
5226    /// (a supervisor that satisfies neither arm's precondition, or that
5227    /// satisfies both, at the cost of the paired
5228    /// `SimpleOneForOneWithStaticChildren`/`NoChildren` refusal cascade
5229    /// silently drifting from the per-child validate loop's actual
5230    /// traversal input), a three-consumer split at the validator far
5231    /// from the source `caixa.lisp` with no field naming the
5232    /// child-set-drift root cause. Lifting the resolution rule to a
5233    /// typed method on the substrate primitive means every downstream
5234    /// consumer of the Supervisor's per-`:supervisor` static-child-list
5235    /// surface reaches for exactly one typed dispatch — the resolver's
5236    /// accept-set migrates as a unit on any future axis addition.
5237    ///
5238    /// First slice-return (`&[T]`) accessor on any M2 or M3 typed slot
5239    /// — the seed for the same "one typed dispatch on the substrate
5240    /// primitive, thin projections at each consumer" discipline the
5241    /// closed [`crate::LimitsSpec`] / [`BehaviorSpec`] /
5242    /// [`crate::UpgradeFromEntry`] scalar-accessor families each carry
5243    /// on their `Copy` / `Option<Copy>` / `Option<&str>` axes, extended
5244    /// onto the first `Vec`-carry axis on the substrate. The four peer
5245    /// `Vec`-carry axes still unlifted at the time of this seed —
5246    /// [`crate::Placement::clusters`] (`Vec<String>` per-cluster
5247    /// distribution-target list), [`crate::AplicacaoSpec::membros`]
5248    /// (`Vec<Membro>` per-Aplicacao member list),
5249    /// [`crate::AplicacaoSpec::contratos`] (`Vec<WitContract>`
5250    /// per-Aplicacao WIT-typed edge list),
5251    /// [`crate::UpgradeFromEntry::instructions`]
5252    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
5253    /// — inherit this accessor's discipline as future compounding runs
5254    /// migrate their consumers onto the shared slice-return shape.
5255    /// Fourth (and final) accessor on the M2 supervisor-slot
5256    /// `SupervisorSpec` type, sibling to the three `Copy`-return
5257    /// [`SupervisorSpec::estrategia`] (eafb619) /
5258    /// [`SupervisorSpec::max_restarts`] (7844f4e) /
5259    /// [`SupervisorSpec::restart_window`] (7e7b32f) accessors — closes
5260    /// the last unlifted per-`:supervisor` field axis (the
5261    /// `Vec<ChildSpec>` static-child-list carrier) so every downstream
5262    /// per-`:supervisor` reader now routes through a typed dispatch on
5263    /// the substrate primitive. Named `children()` to match the storage
5264    /// field's name verbatim and the tatara-lisp author-surface term
5265    /// (`:children`) the field's own docstring already carries; the
5266    /// accessor's identity maps onto the canonical OTP-shape
5267    /// supervision vocabulary the [`SupervisorSpec::children`] field's
5268    /// docstring already reaches for ("Static children ..."). Returns
5269    /// `&[ChildSpec]` (not `&Vec<ChildSpec>`) because every downstream
5270    /// consumer of the child list treats it as a read-only sequence —
5271    /// the slice-view is the narrowest borrow that supports every
5272    /// present + roadmapped consumer (`.is_empty()`, `.iter()`,
5273    /// index, `.len()`) without leaking the backing `Vec`'s
5274    /// grow/push/reserve surface that no consumer of the typed view
5275    /// reaches for (the storage-side `Vec` remains reachable through
5276    /// the `pub children` field for the mutation-carrying
5277    /// `Caixa::supervisor_view` fold-in path in
5278    /// `manifest.rs:supervisor_view`).
5279    #[must_use]
5280    pub const fn children(&self) -> &[ChildSpec] {
5281        self.children.as_slice()
5282    }
5283
5284    /// Validate the supervisor's typed shape — strategy ↔ children
5285    /// invariants, max_restarts > 0, restart_window > 0 when set,
5286    /// per-child non-empty + duplicate-free names.
5287    ///
5288    /// Mirrors the value-shape discipline applied to every other
5289    /// typed slot:
5290    ///
5291    ///   - `Some(Duration::ZERO)` on a Duration-bearing axis is the
5292    ///     same "0 means the opposite of what you think" footgun
5293    ///     closed for `:politicas :timeout` (Envoy interprets a zero
5294    ///     timeout as `infinite`), `:politicas :circuit-breaker
5295    ///     :window`, and `:limits :wall-clock`. The
5296    ///     `MaxIntensity / Period` ratio in Erlang/OTP's
5297    ///     `supervisor` requires `Period > 0`; a zero period either
5298    ///     trips on the first failure or never trips depending on
5299    ///     operator interpretation, neither of which is the
5300    ///     author's intent. Omit `:restart-window` to express "no
5301    ///     reset"; carry a positive duration to express the window.
5302    ///   - duplicate `:children` `:caixa` names are the same
5303    ///     graph-node-set / multiset distinction closed for
5304    ///     `:membros` (4bb3f3d), `:placement :clusters` (c7c7799),
5305    ///     and `:entrada :paths` (eb3456d). Two children with the
5306    ///     same `:caixa` materialize as two ComputeUnits with the
5307    ///     same name in the cluster's HelmRelease values, one
5308    ///     silently overwriting the other. Erlang/OTP's
5309    ///     `child_spec.id` is required-unique per supervisor;
5310    ///     pleme-io enforces the same set-not-multiset shape on
5311    ///     `:caixa` (the load-bearing identity in our renderer).
5312    pub fn validate(&self) -> Result<(), SupervisorError> {
5313        // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition
5314        // dispatch and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
5315        // error carrier's `estrategia:` field through the lifted
5316        // [`SupervisorSpec::estrategia`] accessor rather than the raw
5317        // `self.estrategia` field access — the two production consumers
5318        // of the per-`:supervisor` sibling-restart-strategy scalar now
5319        // key off exactly one typed dispatch on the substrate primitive,
5320        // so any future rebrand on the axis (a per-cluster strategy
5321        // override the operator pins through a future `:supervisor
5322        // :estrategia-overrides` slot, a per-tenant strategy-alias table
5323        // the M4 CR materializer resolves per-CR) migrates as a single
5324        // caixa-core edit rather than a coordinated rewrite of the two
5325        // call sites — sibling of the peer M3 [`crate::Placement::estrategia`]
5326        // (921fe1b) four-consumer migration on the per-`:placement`
5327        // distribution-strategy axis.
5328        // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition-
5329        // dispatch's paired `.is_empty()` cross-slot refusal probes
5330        // (the `SimpleOneForOne`-arm
5331        // [`SupervisorError::SimpleOneForOneWithStaticChildren`] refusal
5332        // and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
5333        // refusal) through the lifted [`SupervisorSpec::children`]
5334        // slice-return accessor rather than the raw `self.children`
5335        // field access — the two paired production consumers of the
5336        // per-`:supervisor` static-child-list scalar-shape now key off
5337        // exactly one typed dispatch on the substrate primitive, so any
5338        // future rebrand on the axis (a per-cluster child-set overlay
5339        // the operator pins through a future `:supervisor
5340        // :children-overrides` slot, a per-tenant child-set-alias table
5341        // the M4 CR materializer resolves per-CR) migrates as a single
5342        // caixa-core edit rather than a coordinated rewrite of the
5343        // paired arms — first slice-return migration on any typed slot,
5344        // seed for the peer per-`:placement :clusters`,
5345        // per-`:membros`, per-`:contratos`, and per-`:upgrade-from
5346        // :instructions` `Vec`-carry axes.
5347        match self.estrategia() {
5348            RestartStrategy::SimpleOneForOne => {
5349                // SimpleOneForOne: children added at runtime. Static
5350                // list must be empty (one shape declared elsewhere).
5351                if !self.children().is_empty() {
5352                    return Err(SupervisorError::SimpleOneForOneWithStaticChildren);
5353                }
5354            }
5355            _ => {
5356                if self.children().is_empty() {
5357                    return Err(SupervisorError::no_children(self.estrategia()));
5358                }
5359            }
5360        }
5361        // Zero-floor + upper-cap bracket on the typed `:max-restarts`
5362        // axis. See [`crate::render::require_positive_bounded_u32`] for
5363        // the ordering discipline (zero-floor arm strictly precedes cap
5364        // arm so `0` surfaces the self-locating `ZeroMaxRestarts`
5365        // diagnostic with its counter-axis remediation directly named,
5366        // not the misleading `0 > SUPERVISOR_MAX_RESTARTS_MAX == false`
5367        // cap-arm miss). Until this bracket landed the top edge ran all
5368        // the way to `u32::MAX` and a struct-literal
5369        // `SupervisorSpec { max_restarts: 100_000, .. }` (or the
5370        // equivalent author-surface `:max-restarts 100000` /
5371        // `:max-restarts 4294967295` typo landing in the slot) silently
5372        // passed validate. The runtime substrate consuming the value
5373        // (Erlang/OTP's `MaxIntensity / Period` ratio, the future
5374        // wasm-operator's per-supervisor restart-intensity counter, the
5375        // M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
5376        // admission webhook) then turned a typed `:max-restarts`
5377        // policy into a no-op supervisor: the escalation threshold is
5378        // structurally so high that no realistic
5379        // restarts-per-`:restart-window` traffic shape can reach it,
5380        // the supervisor never escalates to its parent, and a bad
5381        // child can loop inside the window indefinitely with the
5382        // parent supervisor structurally never receiving the "this
5383        // subtree has exceeded its restart budget" signal the typed
5384        // slot is meant to express. The bracket set is
5385        // `1..=SUPERVISOR_MAX_RESTARTS_MAX`, peer with the
5386        // [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap on
5387        // the sibling `:politicas :circuit-breaker :max-failures` axis:
5388        // both are "trip the next-higher protection layer after N
5389        // events in a rolling window" counters with identical
5390        // degenerate-at-the-high-end shape and now share one canonical
5391        // bracket helper. The bracket precedes the sibling
5392        // `:restart-window` zero-floor / canonical-millisecond arms so
5393        // an over-cap `max_restarts` paired with a structurally invalid
5394        // window surfaces the bracket diagnostic first, mirroring the
5395        // `PolicyBreakerMaxFailuresExceedsCap` / window-axis cross-arm
5396        // ordering on the peer `:politicas :circuit-breaker` slot.
5397        // Route the [`SupervisorSpec::validate`] `:max-restarts` zero-floor +
5398        // upper-cap bracket-gate through the lifted [`SupervisorSpec::max_restarts`]
5399        // accessor rather than the raw `self.max_restarts` field access —
5400        // the one production consumer of the per-`:supervisor`
5401        // restart-budget-count scalar now keys off exactly one typed
5402        // dispatch on the substrate primitive, so any future rebrand on
5403        // the axis (a per-cluster restart-budget override the operator
5404        // pins through a future `:supervisor :max-restarts-overrides`
5405        // slot, a per-tenant restart-budget-alias table the M4 CR
5406        // materializer resolves per-CR) migrates as a single caixa-core
5407        // edit rather than a coordinated rewrite — sibling of the peer M3
5408        // [`crate::CircuitBreaker::max_failures`] (3a74062) migration on
5409        // the per-`:politicas :circuit-breaker :max-failures` axis.
5410        crate::render::require_positive_bounded_u32(
5411            self.max_restarts(),
5412            SUPERVISOR_MAX_RESTARTS_MAX,
5413            || SupervisorError::ZeroMaxRestarts,
5414            SupervisorError::max_restarts_exceeds_cap,
5415        )?;
5416        // Route the [`SupervisorSpec::validate`] `:restart-window`
5417        // zero-floor + integer-millisecond canonical-form + upper-cap
5418        // bracket-gate through the lifted [`SupervisorSpec::restart_window`]
5419        // accessor rather than the raw `self.restart_window` field access —
5420        // the one production consumer of the per-`:supervisor`
5421        // restart-intensity-denominator scalar now keys off exactly one
5422        // typed dispatch on the substrate primitive, so any future rebrand
5423        // on the axis (a per-cluster restart-window override the operator
5424        // pins through a future `:supervisor :restart-window-overrides`
5425        // slot, a per-tenant restart-window-alias table the M4 CR
5426        // materializer resolves per-CR) migrates as a single caixa-core
5427        // edit rather than a coordinated rewrite — sibling of the peer M2
5428        // [`crate::LimitsSpec::wall_clock`] (8cb717b) validate-arm-route
5429        // on the per-`:limits :wall-clock` axis and the peer M3
5430        // [`crate::MeshPolicy::timeout`] (7073d0f) accessor-route on the
5431        // per-`:politicas :timeout` axis.
5432        if let Some(w) = self.restart_window() {
5433            // Zero-floor + integer-millisecond canonical-form +
5434            // upper-cap bracket on the typed `:restart-window` axis.
5435            // See
5436            // [`crate::render::require_positive_canonical_bounded_duration`]
5437            // for the full three-arm ordering discipline (zero-floor
5438            // strictly precedes canonical-form so `Duration::ZERO`
5439            // surfaces the self-locating `RestartWindowZero`
5440            // diagnostic; canonical-form strictly precedes the cap arm
5441            // so a sub-millisecond above-cap value surfaces the more
5442            // fundamental round-trip-shape diagnostic first) and the
5443            // three peer typed-`Duration` sites that share this
5444            // canonical bracket ([`crate::MeshPolicy::timeout`],
5445            // [`crate::CircuitBreaker::window`],
5446            // [`crate::LimitsSpec::wall_clock`]). Every validated
5447            // value lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
5448            // (1ms..=1h), integer-millisecond granularity.
5449            crate::render::require_positive_canonical_bounded_duration(
5450                w,
5451                SUPERVISOR_RESTART_WINDOW_MAX,
5452                || SupervisorError::RestartWindowZero,
5453                SupervisorError::restart_window_not_canonical,
5454                SupervisorError::restart_window_exceeds_cap,
5455            )?;
5456        }
5457        // Route the per-child DNS-1123 / semver-requirement / duplicate-
5458        // detection fan-out loop through the lifted named per-slot gate
5459        // [`SupervisorSpec::validate_children`] rather than an inline
5460        // three-per-child cascade — every future consumer that wants to
5461        // re-check only the `:children` slot's per-entry axes (the M4
5462        // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
5463        // admission webhook re-validating one added/renamed child, the
5464        // future wasm-operator's per-child dynamic-add re-validator on
5465        // the `SimpleOneForOne` runtime-add path once dynamic-children
5466        // graduate to a typed slot, a future partial re-validator on a
5467        // per-`:children`-entry patch) reaches every per-entry axis
5468        // through one dispatch rather than re-inlining the three-arm
5469        // cascade in lockstep with `validate` or paying the peer
5470        // `:estrategia`/`:max-restarts`/`:restart-window` gates to
5471        // reach one entry check. Sibling of the peer M3 mesh-slot
5472        // per-slot gate family (`validate_membros` — the exact peer on
5473        // the M3 side, [`crate::AplicacaoSpec::validate_membros`];
5474        // `validate_contratos` — 906a5c6; `validate_entrada` — 20cd523;
5475        // `validate_placement`; `validate_politicas` routing through
5476        // `MeshPolicy::validate` — f03a154) — the M2 supervisor-slot
5477        // per-slot gate discipline now spans both the M3 mesh-slot
5478        // family and the M2 `:children` per-child-cascade axis on one
5479        // shape: one named per-slot gate per typed per-entry loop.
5480        self.validate_children()?;
5481        Ok(())
5482    }
5483
5484    /// Named per-slot gate on the M2 `:supervisor :children` per-entry
5485    /// axis — folds the per-child DNS-1123 name gate, semver-requirement
5486    /// gate, and duplicate-`:caixa` dedup arm into one call every
5487    /// consumer that wants to re-validate one `:children` entry (or the
5488    /// whole list) against the same accept-set [`SupervisorSpec::validate`]
5489    /// admits reaches through.
5490    ///
5491    /// Peer of the M3 mesh-slot [`crate::AplicacaoSpec::validate_membros`]
5492    /// per-slot gate on the analogous per-entry axis (`:membros`) — same
5493    /// three-per-entry shape (DNS-1123 name + semver-requirement +
5494    /// duplicate-`:caixa` dedup), lifted to one named substrate
5495    /// primitive per slot. The M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
5496    /// materializer's admission webhook re-checking one added or renamed
5497    /// child, the future wasm-operator's per-child dynamic-add
5498    /// re-validator on the `SimpleOneForOne` runtime-add path once
5499    /// dynamic-children graduate to a typed slot, a future partial
5500    /// re-validator on a per-`:children`-entry patch — each reaches the
5501    /// three per-entry axes through this one dispatch rather than
5502    /// re-inlining the three-arm cascade in lockstep with `validate`
5503    /// (the duplication the PRIME DIRECTIVE names as a bug) or paying
5504    /// the peer `:estrategia`/`:max-restarts`/`:restart-window` gates to
5505    /// reach one entry check.
5506    ///
5507    /// Self-contained on `&self` — resolves its own dedup `HashSet`
5508    /// through [`SupervisorSpec::children`] rather than borrowing one
5509    /// threaded down from `validate`, the same posture the peer M3
5510    /// mesh-slot per-slot gates ([`crate::AplicacaoSpec::validate_membros`],
5511    /// [`crate::AplicacaoSpec::validate_contratos`],
5512    /// [`crate::AplicacaoSpec::validate_entrada`],
5513    /// [`crate::AplicacaoSpec::validate_placement`]) each carry, so a
5514    /// consumer that reaches this gate directly (without first calling
5515    /// `validate`) still runs the full per-child cascade — pinned by
5516    /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
5517    /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
5518    /// + `validate_children_is_self_contained_on_children_slot`.
5519    ///
5520    /// The three per-entry arms run in the same canonical order the
5521    /// pre-lift inline cascade encoded (DNS-1123 → semver → dedup), so
5522    /// the diagnostic every author-declared per-`:children` entry surfaces
5523    /// through `validate` is byte-equal to the diagnostic this gate
5524    /// surfaces when called directly — the equivalence-pin pair
5525    /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
5526    /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
5527    /// asserts the two altitudes discriminate the same set on every
5528    /// per-entry-covered input.
5529    pub fn validate_children(&self) -> Result<(), SupervisorError> {
5530        let mut seen = std::collections::HashSet::new();
5531        for child in self.children() {
5532            // Every emitted cluster artifact's `metadata.name` for a
5533            // supervised child derives from this `:children :caixa` value
5534            // verbatim — the rendered `wasm.pleme.io/v1alpha1/ComputeUnit
5535            // .metadata.name` per child, the [`crate::LABEL_PROGRAM`]
5536            // label value on every child's pod identity, and the per-
5537            // child K8s [`Service`][svc] `metadata.name` the future
5538            // wasm-operator (M3) provisions for inter-child supervision
5539            // tree wiring. Each apiserver-side schema on each landing
5540            // site enforces the DNS-1123 label rule on admission; a
5541            // structurally invalid child name (`"Worker"`, `"my_worker"`,
5542            // `"team.worker"`, `"-worker"`, `"worker-"`, the >63-byte
5543            // UUID-shaped mistaken-identity slug) silently passes the
5544            // prior empty-/duplicate-only gate and the failure surfaces
5545            // at `kubectl apply` time as a `metadata.name: Invalid value`
5546            // rejection, far from the source caixa.lisp, with no field
5547            // naming the offending `:children` entry. Lifting the gate
5548            // to caixa-build time mirrors the `:membros :caixa` value-
5549            // shape trajectory (3f9d7a0) and the `:placement :clusters`
5550            // trajectory (6cbb900) onto the third DNS-1123-label-shaped
5551            // identifier axis — the supervisor tree's child names —
5552            // through the lifted
5553            // [`crate::render::require_valid_dns_1123_label`] gate the
5554            // seven peer name axes (`:membros :caixa`, `:placement
5555            // :clusters`, `:placement :affinity`, `:contratos :de`/`:para`,
5556            // `:entrada :para`, `:nome`, `:upgrade-from :module`) each
5557            // route through, so drift between the eight axes' accepted
5558            // DNS-1123-label sets is structurally impossible.
5559            //
5560            // [svc]: https://kubernetes.io/docs/concepts/services-networking/service/
5561            crate::render::require_valid_dns_1123_label(
5562                child.nome(),
5563                || SupervisorError::EmptyChildName,
5564                |reason| SupervisorError::child_caixa_invalid(child.nome(), reason),
5565            )?;
5566            // The author surface for `:children :versao` is the same
5567            // Cargo-shaped semver requirement string `:deps :versao` and
5568            // `:membros :versao` carry — and the lacre pipeline resolves
5569            // all three axes through the same
5570            // [`crate::version::parse_requirement`] entry-point. The
5571            // shared [`crate::render::require_valid_versao_requirement`]
5572            // helper brackets the empty-first + parse cascade both peer
5573            // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
5574            // [`crate::AplicacaoSpec::validate_membros`] on `:membros
5575            // :versao`) route through, so drift between the three axes'
5576            // accepted requirement sets is structurally impossible and
5577            // the parse-side no-op the empty-first arm closes (semver's
5578            // empty parse yields an implicit `*`) lives in exactly one
5579            // predicate. Every `ChildSpec::versao` past validate is
5580            // round-trippable through [`crate::parse_requirement`]
5581            // without re-checking at the resolver layer, and the three
5582            // `:versao` typed surfaces (`:deps`, `:membros`, `:children`)
5583            // are now structurally equivalent by construction.
5584            crate::render::require_valid_versao_requirement(
5585                child.versao_requirement(),
5586                || SupervisorError::empty_child_version(child.nome()),
5587                |reason| {
5588                    SupervisorError::child_versao_invalid(
5589                        child.nome(),
5590                        child.versao_requirement(),
5591                        reason,
5592                    )
5593                },
5594            )?;
5595            crate::render::insert_first_seen(&mut seen, child.nome(), || {
5596                SupervisorError::duplicate_child_caixa(child.nome())
5597            })?;
5598        }
5599        Ok(())
5600    }
5601}
5602
5603/// Cross-slot coherence gate on the supervision tree: no
5604/// `:children :caixa` entry may name the supervisor's own `:nome`.
5605///
5606/// A supervisor that lists itself as a child is a degenerate self-parent
5607/// — the supervision tree is a DAG rooted at the supervisor (OTP child
5608/// specs reference *distinct* child processes; a supervisor is never its
5609/// own child), and the wasm-operator's hierarchical reconciliation would
5610/// otherwise be handed a node that is its own parent: a one-node cycle it
5611/// either rejects far from the source `caixa.lisp` or recurses on. Because
5612/// every `:nome` is a globally-unique substrate identity (DNS-1123 label +
5613/// lacre closure root), a child whose `:caixa` equals the supervisor's
5614/// `:nome` *is* the supervisor itself, not a coincidentally-named peer.
5615///
5616/// Lives outside [`SupervisorSpec::validate`] because the typed view
5617/// carries the children but not the parent `:nome`; mirrors the
5618/// cross-slot precedence gate `validate_upgrade_from_against_versao`
5619/// (which likewise reads one slot against another at the
5620/// [`crate::layout`] wire-up site) and the mesh self-edge gate
5621/// `AplicacaoSpec`'s `ContratoSelfLoop` — the same "an edge from a graph
5622/// node to itself is structurally not a tree/mesh edge" discipline, here
5623/// on the supervision-tree axis.
5624pub fn validate_no_self_supervision(
5625    children: &[ChildSpec],
5626    parent_nome: &str,
5627) -> Result<(), SupervisorError> {
5628    for child in children {
5629        if child.nome() == parent_nome {
5630            return Err(SupervisorError::child_supervises_self(parent_nome));
5631        }
5632    }
5633    Ok(())
5634}
5635
5636#[derive(Debug, Error, PartialEq, Eq)]
5637pub enum SupervisorError {
5638    #[error("supervisor :estrategia {estrategia:?} requires at least one :children entry")]
5639    NoChildren { estrategia: RestartStrategy },
5640    #[error(
5641        "SimpleOneForOne supervisors must declare zero static children (children spawn dynamically)"
5642    )]
5643    SimpleOneForOneWithStaticChildren,
5644    #[error(":max-restarts must be > 0")]
5645    ZeroMaxRestarts,
5646    #[error(
5647        ":supervisor :max-restarts ({max_restarts}) exceeds the supervisor-policy ceiling \
5648         (SUPERVISOR_MAX_RESTARTS_MAX = 1000) — a value above this cap turns the typed \
5649         restart-intensity policy into a no-op supervisor: the escalation threshold is \
5650         structurally so high that no realistic restarts-per-:restart-window traffic shape \
5651         can reach it, so the supervisor never escalates to its parent and a bad child can \
5652         loop inside the window indefinitely. Every typed-slot consumer (Erlang/OTP's \
5653         MaxIntensity/Period ratio, the future wasm-operator's per-supervisor \
5654         restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
5655         materializer's admission webhook) emits a `:max-restarts` declaration that is \
5656         structurally never reached. Pin a value in 1..=1000 (Erlang/OTP / Elixir / Riak \
5657         Core / RabbitMQ production playbooks recommend 3..=100; the OTP `supervisor` \
5658         callback module's `MaxR = 1` minimal-restart default sits at the bottom of the \
5659         band) or restructure the supervision tree (split the flaky child into its own \
5660         sub-supervisor with a tighter budget) if you need a higher restart tolerance."
5661    )]
5662    MaxRestartsExceedsCap { max_restarts: u32 },
5663    #[error(
5664        ":restart-window must be > 0 when set — Erlang/OTP's MaxIntensity/Period \
5665         requires Period > 0; a zero window either trips on the first failure or \
5666         never trips depending on operator interpretation. Omit :restart-window to \
5667         express `never reset`; carry a positive duration to express the window."
5668    )]
5669    RestartWindowZero,
5670    #[error(
5671        ":supervisor :restart-window ({window:?}) carries a sub-millisecond residue the shared `duration_codec` cannot round-trip — \
5672         the codec truncates to `as_millis()` before picking the canonical unit, so a value with `subsec_nanos() % 1_000_000 != 0` either \
5673         truncates on first serialize (e.g. `Duration::from_micros(1500)` → \"1ms\" → `Duration::from_millis(1)` ≠ original) or renders \
5674         as \"0s\" the `RestartWindowZero` arm then rejects on re-validate. Pin an integer-millisecond magnitude in the canonical authoring form \
5675         (`<integer><unit>` for unit ∈ {{ms, s, m, h}}, e.g. `\"500ms\"`, `\"30s\"`, `\"2m\"`, `\"1h\"`) or omit the field for `never reset`"
5676    )]
5677    RestartWindowNotCanonical { window: Duration },
5678    #[error(
5679        ":supervisor :restart-window ({window:?}) exceeds the supervisor-policy ceiling \
5680         (SUPERVISOR_RESTART_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
5681         per-supervisor rolling-window restart-intensity counter into a lifetime counter: the \
5682         failure-counting window is structurally so long that transient restarts are never \
5683         forgotten, the MaxIntensity/Period ratio degenerates from `trip the parent supervisor \
5684         when the child has exceeded its restart budget within the recent window` to `trip the \
5685         parent when the child has exceeded its restart budget over its lifetime`, and the \
5686         supervisor's reset semantic never reaches the child — every typed-slot consumer \
5687         (Erlang/OTP's MaxIntensity/Period reconciler, the future wasm-operator's \
5688         per-supervisor restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
5689         materializer's admission webhook, the caixa-operator's hierarchical reconciliation \
5690         scheduler) emits a `:restart-window` declaration that is structurally a no-op rolling \
5691         window. Pin a value in 1ms..=1h (Learn You Some Erlang's `{{intensity, 5, 60}}` \
5692         worker-supervisor `Period = 60s` default, Elixir's `Supervisor` `max_seconds: 5` \
5693         default, OTP's `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's \
5694         `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default — every Erlang/OTP \
5695         / Elixir production playbook sits in the 5s..=300s band; the longest documented \
5696         per-supervisor restart-window any pleme-io substrate playbook recommends maxes at \
5697         ~30m) or omit :restart-window to express `never reset` (the supervisor's restart \
5698         budget then becomes a strict lifetime counter by design, not a degenerate one — the \
5699         author surfaces the lifetime-counter semantic explicitly at the slot, rather than \
5700         hiding it behind a rolling-window declaration the cap arm rejects)"
5701    )]
5702    RestartWindowExceedsCap { window: Duration },
5703    #[error("child entry has empty :caixa name")]
5704    EmptyChildName,
5705    #[error(
5706        "child :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
5707         (the K8s apiserver enforces this rule on every `metadata.name` / Service \
5708         name / label value the child name lands in — the per-child \
5709         `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name`, the `LABEL_PROGRAM` \
5710         label value, and the future wasm-operator per-child Service `metadata.name` \
5711         — each apiserver-side schema rejects names that don't match; use a \
5712         lowercase alphanumeric + hyphen identifier like `\"worker\"` or `\"cache-v2\"`)"
5713    )]
5714    ChildCaixaInvalid { caixa: String, reason: String },
5715    #[error("child {caixa:?} has empty :versao constraint")]
5716    EmptyChildVersion { caixa: String },
5717    #[error(
5718        "child {caixa:?} :versao {versao:?} is not a valid semver requirement: \
5719         {reason} (use Cargo-shaped forms like `\"^0.1\"`, `\"~0.1.2\"`, \
5720         `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` and \
5721         `:membros :versao` carry; the lacre pipeline resolves all three \
5722         through the same parser)"
5723    )]
5724    ChildVersaoInvalid {
5725        caixa: String,
5726        versao: String,
5727        reason: String,
5728    },
5729    #[error(
5730        "child {caixa:?} appears more than once (Erlang/OTP requires unique \
5731         child_spec.id per supervisor; duplicate children materialize as duplicate \
5732         ComputeUnits in the rendered chart, one silently overwriting the other)"
5733    )]
5734    DuplicateChildCaixa { caixa: String },
5735    #[error(
5736        "supervisor {caixa:?} lists itself as a :children entry — a supervisor is \
5737         never its own child (the supervision tree is a DAG rooted at the supervisor; \
5738         OTP child specs reference distinct child processes). Since every :nome is a \
5739         globally-unique substrate identity, a child naming the supervisor's own :nome \
5740         is a one-node reconciliation cycle, not a coincidentally-named peer; drop the \
5741         self-referential :children entry or rename it to the actual child caixa."
5742    )]
5743    ChildSupervisesSelf { caixa: String },
5744}
5745
5746// Fold the three `SupervisorError::<Variant> { caixa: <&str>.to_string() }`
5747// caixa-only struct-variant wire-up sites at [`SupervisorSpec::validate_children`]
5748// and [`validate_no_self_supervision`] onto one substrate primitive per
5749// typed variant — the sibling on `SupervisorError` of the four uniform-shape
5750// `LayoutError`-envelope constructor families the peer
5751// [`crate::layout::layout_violation_ctors!`] macro closed (131ca0d, 16
5752// variants on `{ caixa, issue }`), the [`crate::layout::layout_slot_kind_ctors!`]
5753// macro closed (0419438, 4 variants on `{ caixa, kind, slots }`), the
5754// [`crate::LayoutError::missing_entry`] one-variant ctor closed (1b09f9d,
5755// on `{ kind, path }`), and the [`crate::layout::layout_nome_only_ctors!`]
5756// macro closed (3fe3dd7, 6 variants on `<Variant>(String)`), plus the
5757// [`crate::AplicacaoError::entrada_host_invalid`] one-variant ctor
5758// (17dd504, `{ host, reason }`), the [`crate::aplicacao::contrato_target_ctors!`]
5759// macro (14b81d5, 2 variants on `{ de, para, wit, expected }`), and the
5760// [`crate::aplicacao::contrato_empty_pair_ctors!`] macro (8580068, 4
5761// variants on `{ de, para }`) already at that discipline on the peer
5762// `AplicacaoError` envelopes.
5763//
5764// Each of the three wire-up sites on this shape (`EmptyChildVersion` at
5765// the per-`:children` semver-requirement empty-first arm, `DuplicateChildCaixa`
5766// at the per-`:children` dedup arm, `ChildSupervisesSelf` at the cross-slot
5767// self-supervision arm) opened the identical
5768// `SupervisorError::<Variant> { caixa: <&str>.to_string() }` struct-literal —
5769// the exact "same block re-inlined at every consumer" shape the PRIME
5770// DIRECTIVE names as a bug, on the same altitude the peer `LayoutError` /
5771// `AplicacaoError` families each closed on their sibling envelopes. The
5772// three variants share one `{ caixa: String }` shape, so the fold routes
5773// each wire-up site through one dispatch per typed variant.
5774//
5775// The macro below generates one static constructor per variant of shape
5776// `fn <slot>(caixa: &str) -> SupervisorError`, so every wire-up site
5777// collapses onto one dispatch:
5778// `SupervisorError::<slot>(<&str>)`, byte-equal to the pre-lift
5779// struct-literal on the same `&str` fixture. The uniform one-field
5780// construction (`caixa: caixa.to_string()`) is spelled once — inside the
5781// macro — rather than at every wire-up site. Every constructor is
5782// `#[must_use]` so a caller who mistakenly discards the constructed error
5783// trips a compile warning at the wire-up site.
5784//
5785// Every future consumer that wants to construct one of these three
5786// variants outside `SupervisorSpec::validate_children` /
5787// `validate_no_self_supervision` — a deferred
5788// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
5789// webhook re-checking one added/renamed child, a future
5790// `feira validate --supervisor` per-caixa admission verb, a per-child
5791// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path
5792// once dynamic-children graduate to a typed slot, a per-Supervisor
5793// overlay resolver rejecting a duplicate/self-supervising child against
5794// a cluster-local snapshot — now reaches each variant through one call
5795// rather than re-inlining the three-line struct-literal in lockstep
5796// with the three in-crate wire-up sites.
5797macro_rules! supervisor_caixa_only_ctors {
5798    ($($ctor:ident => $variant:ident),* $(,)?) => {
5799        impl SupervisorError {
5800            $(
5801                #[doc = concat!(
5802                    "Construct a [`SupervisorError::",
5803                    stringify!($variant),
5804                    "`] naming the offending `:children :caixa` (or ",
5805                    "supervisor `:nome`, on the self-supervision arm). ",
5806                    "Folds the uniform `Self::",
5807                    stringify!($variant),
5808                    " { caixa: caixa.to_string() }` one-field ",
5809                    "struct-literal onto one substrate primitive so ",
5810                    "every [`SupervisorSpec::validate_children`] / ",
5811                    "[`validate_no_self_supervision`] wire-up on this ",
5812                    "variant reads through one dispatch rather than the ",
5813                    "pre-lift open-coded struct-literal block."
5814                )]
5815                #[must_use]
5816                pub fn $ctor(caixa: &str) -> Self {
5817                    Self::$variant { caixa: caixa.to_string() }
5818                }
5819            )*
5820        }
5821    };
5822}
5823
5824supervisor_caixa_only_ctors! {
5825    empty_child_version => EmptyChildVersion,
5826    duplicate_child_caixa => DuplicateChildCaixa,
5827    child_supervises_self => ChildSupervisesSelf,
5828}
5829
5830// Fold the two `SupervisorError::{ChildCaixaInvalid, ChildVersaoInvalid}`
5831// struct-variant wire-up sites at [`SupervisorSpec::validate_children`] onto
5832// one substrate primitive per typed variant — the M2 supervisor-side siblings
5833// of the peer [`crate::AplicacaoError::membro_caixa_invalid`] two-slot ctor
5834// already lifted through the sibling
5835// [`crate::aplicacao::aplicacao_field_reason_ctors!`] macro (981060b) on the
5836// peer `AplicacaoError { caixa: String, reason: String }` envelope. The
5837// `ChildCaixaInvalid` variant carries the same `{ <name>: String, reason:
5838// String }` two-slot shape the peer seven-variant
5839// [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold closed on the
5840// `AplicacaoError` envelope (`MembroCaixaInvalid`, `EntradaParaInvalid`,
5841// `EntradaHostInvalid`, `EntradaPathInvalid`, `PlacementClusterInvalid`,
5842// `PlacementAffinityInvalid`, `ShardKeyInvalid`); the `ChildVersaoInvalid`
5843// variant carries the `{ caixa: String, versao: String, reason: String }`
5844// three-slot shape the sibling `AplicacaoError::MembroVersaoInvalid` axis
5845// carries on the same `:versao` value-shape.
5846//
5847// Each of the two wire-up sites opened the same closure-shaped
5848// `|reason| SupervisorError::<Variant> { caixa: child.nome().to_string(),
5849// [versao: child.versao_requirement().to_string(),] reason }` block inside
5850// the paired [`crate::render::require_valid_dns_1123_label`] and
5851// [`crate::render::require_valid_versao_requirement`] callbacks — the exact
5852// "same block re-inlined at every consumer" shape the PRIME DIRECTIVE names
5853// as a bug, on the same altitude the peer `AplicacaoError` /
5854// `SupervisorError` / `LayoutError` / `DepError` / `LimitsError` ctor
5855// families already closed on their sibling envelopes.
5856//
5857// The two `#[must_use]` inherent constructors below fold each wire-up onto
5858// one dispatch: `SupervisorError::child_caixa_invalid(<name>, <reason>)`
5859// and `SupervisorError::child_versao_invalid(<name>, <versao>, <reason>)`,
5860// byte-equal to the pre-lift struct-literal on the same scalar fixtures.
5861// The uniform per-field `.to_string()` / `.into()` construction is spelled
5862// once — inside each ctor body — rather than at every wire-up site. The
5863// `reason: impl Into<String>` bound accepts both `&str` literals and
5864// `format!(…)` outputs verbatim so no wire-up site changes its per-arm
5865// diagnostic shape at the lift, matching the peer
5866// [`aplicacao_field_reason_ctors!`] and
5867// [`crate::aplicacao::contrato_pair_value_reason_ctors!`] bounds on the
5868// sibling envelopes.
5869//
5870// Every future consumer that wants to construct one of these two variants
5871// outside `SupervisorSpec::validate_children` — a deferred
5872// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook
5873// re-checking one added/renamed child's `:caixa` or `:versao`, a future
5874// `feira validate --supervisor` per-caixa admission verb, a per-child
5875// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path once
5876// dynamic-children graduate to a typed slot, a per-Supervisor overlay
5877// resolver rejecting a shape-invalid child `:caixa`/`:versao` against a
5878// cluster-local snapshot — now reaches each variant through one call rather
5879// than re-inlining the per-shape struct-literal block in lockstep with the
5880// two in-crate wire-up sites.
5881impl SupervisorError {
5882    /// Construct a [`SupervisorError::ChildCaixaInvalid`] naming the
5883    /// offending `:children :caixa` value under the given `reason`. Folds
5884    /// the uniform `Self::ChildCaixaInvalid { caixa: caixa.to_string(),
5885    /// reason: reason.into() }` two-slot struct-literal onto one substrate
5886    /// primitive so every wire-up on this variant reads through one
5887    /// dispatch, matching the peer
5888    /// [`crate::AplicacaoError::membro_caixa_invalid`] ctor's shape on the
5889    /// sibling `AplicacaoError { caixa: String, reason: String }`
5890    /// envelope. `reason` accepts both `&str` literals and `format!(…)`
5891    /// outputs through the `impl Into<String>` bound.
5892    #[must_use]
5893    pub fn child_caixa_invalid(caixa: &str, reason: impl Into<String>) -> Self {
5894        Self::ChildCaixaInvalid {
5895            caixa: caixa.to_string(),
5896            reason: reason.into(),
5897        }
5898    }
5899
5900    /// Construct a [`SupervisorError::ChildVersaoInvalid`] naming the
5901    /// offending `:children :caixa` and its `:versao` requirement under
5902    /// the given `reason`. Folds the uniform `Self::ChildVersaoInvalid {
5903    /// caixa: caixa.to_string(), versao: versao.to_string(), reason:
5904    /// reason.into() }` three-slot struct-literal onto one substrate
5905    /// primitive so every wire-up on this variant reads through one
5906    /// dispatch, matching the sibling `AplicacaoError::MembroVersaoInvalid
5907    /// { caixa, versao, reason }` three-slot axis on the peer
5908    /// `AplicacaoError` envelope. `reason` accepts both `&str` literals
5909    /// and `format!(…)` outputs through the `impl Into<String>` bound.
5910    #[must_use]
5911    pub fn child_versao_invalid(caixa: &str, versao: &str, reason: impl Into<String>) -> Self {
5912        Self::ChildVersaoInvalid {
5913            caixa: caixa.to_string(),
5914            versao: versao.to_string(),
5915            reason: reason.into(),
5916        }
5917    }
5918}
5919
5920// Fold the four `SupervisorError::<Variant> { <field>: <Copy> }` one-field
5921// Copy-scalar struct-variant wire-up sites at [`SupervisorSpec::validate`]'s
5922// three bracket-arms — one struct-literal at the `:children`-empty
5923// non-`SimpleOneForOne` refusal cascade (`NoChildren { estrategia }`) plus
5924// three `impl FnOnce(<ty>) -> SupervisorError` bracket-closures at the
5925// [`crate::render::require_positive_bounded_u32`] `:max-restarts` cap arm
5926// (`MaxRestartsExceedsCap { max_restarts }`) and the paired
5927// [`crate::render::require_positive_canonical_bounded_duration`]
5928// `:restart-window` canonical-form + cap arms (`RestartWindowNotCanonical
5929// { window }`, `RestartWindowExceedsCap { window }`) — onto one substrate
5930// primitive per typed variant, matching the sibling
5931// [`crate::aplicacao::aplicacao_policy_scalar_ctors!`] macro (7ef425e, 8
5932// variants on the same `{ <field>: Duration | u32 }` shape) at that
5933// discipline on the peer `AplicacaoError` envelope's per-`:politicas`
5934// scalar axis. Every variant is a one-field `Copy`-pass-through struct-
5935// literal — `RestartStrategy | u32 | Duration` — so the fold routes each
5936// wire-up site through one dispatch per typed variant without a runtime-
5937// work delta.
5938//
5939// Each of the four wire-up sites opened the identical
5940// `SupervisorError::<Variant> { <field>: <val> }` struct-literal — the
5941// exact "same block re-inlined at every consumer" shape the PRIME
5942// DIRECTIVE names as a bug, on the same altitude the peer
5943// `aplicacao_policy_scalar_ctors!` fold closed on the sibling
5944// `AplicacaoError` envelope's per-`:politicas` per-axis cap / canonical-
5945// form arms. The four variants share one `{ <field>: <Copy> }` shape, so
5946// the fold routes each wire-up site through one dispatch per typed
5947// variant.
5948//
5949// The macro below generates one static constructor per variant of shape
5950// `const fn <ctor>(<field>: <ty>) -> SupervisorError`, so every wire-up
5951// site collapses onto one dispatch: `SupervisorError::<ctor>(<val>)`,
5952// byte-equal to the pre-lift struct-literal on the same `Copy`-`<ty>`
5953// fixture — as a direct call at the [`SupervisorSpec::validate`]
5954// `:children`-empty refusal, or as a bare function pointer in the
5955// `impl FnOnce(<ty>) -> SupervisorError` bracket-closure slot every
5956// [`crate::render::require_positive_bounded_u32`] /
5957// [`crate::render::require_positive_canonical_bounded_duration`] gate
5958// carries — rather than the pre-lift open-coded one-line closure over
5959// the same one-field struct-literal. `const fn` preserves the `Copy`-
5960// pass-through's zero-runtime-work property verbatim. Every constructor
5961// is `#[must_use]` so a caller who mistakenly discards the constructed
5962// error trips a compile warning at the wire-up site.
5963//
5964// Every future consumer that wants to construct one of these four
5965// variants outside `SupervisorSpec::validate` — a deferred
5966// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
5967// webhook re-checking one edited `:estrategia` / `:max-restarts` /
5968// `:restart-window` slot against the cap + canonical-form cascade, a
5969// future `feira validate --supervisor` per-caixa admission verb re-
5970// running the shape gates on demand, a per-Supervisor overlay resolver
5971// rejecting an author-supplied slot against a cluster-local snapshot —
5972// now reaches each variant through one call rather than re-inlining the
5973// per-shape struct-literal block in lockstep with the four in-crate
5974// wire-up sites.
5975macro_rules! supervisor_scalar_ctors {
5976    ($($ctor:ident => $variant:ident { $field:ident: $ty:ty }),* $(,)?) => {
5977        impl SupervisorError {
5978            $(
5979                #[doc = concat!(
5980                    "Construct a [`SupervisorError::",
5981                    stringify!($variant),
5982                    "`] naming the offending per-`:supervisor` `",
5983                    stringify!($field),
5984                    "` scalar. Folds the uniform `Self::",
5985                    stringify!($variant),
5986                    " { ",
5987                    stringify!($field),
5988                    " }` one-field `Copy`-pass-through struct-literal onto ",
5989                    "one substrate primitive so every per-axis wire-up on ",
5990                    "this variant reads through one dispatch — as a direct ",
5991                    "call (`SupervisorError::",
5992                    stringify!($ctor),
5993                    "(<val>)`, byte-equal to the pre-lift struct-literal on ",
5994                    "the same `Copy`-`",
5995                    stringify!($ty),
5996                    "` fixture) or as a bare function pointer in the ",
5997                    "`impl FnOnce(",
5998                    stringify!($ty),
5999                    ") -> SupervisorError` bracket-closure slot every ",
6000                    "`crate::render::require_positive_bounded_*` / ",
6001                    "`crate::render::require_positive_canonical_bounded_*` ",
6002                    "gate carries — rather than the pre-lift open-coded ",
6003                    "one-line closure over the same one-field struct-",
6004                    "literal. `const fn` preserves the `Copy`-pass-through's ",
6005                    "zero-runtime-work property verbatim."
6006                )]
6007                #[must_use]
6008                pub const fn $ctor($field: $ty) -> Self {
6009                    Self::$variant { $field }
6010                }
6011            )*
6012        }
6013    };
6014}
6015
6016supervisor_scalar_ctors! {
6017    no_children => NoChildren { estrategia: RestartStrategy },
6018    max_restarts_exceeds_cap => MaxRestartsExceedsCap { max_restarts: u32 },
6019    restart_window_not_canonical => RestartWindowNotCanonical { window: Duration },
6020    restart_window_exceeds_cap => RestartWindowExceedsCap { window: Duration },
6021}
6022
6023/// Shared duration string codec for the typed slots that take a
6024/// duration (`restart_window`, `MeshPolicy::timeout`,
6025/// `CircuitBreaker::window`, …). Public so [`crate::aplicacao`] can
6026/// reuse it without duplicating the parser.
6027pub mod duration_codec {
6028    use super::Duration;
6029    use serde::{Deserializer, Serializer};
6030
6031    pub fn serialize<S: Serializer>(v: &Option<Duration>, s: S) -> Result<S::Ok, S::Error> {
6032        // Route through the canonical [`crate::render::serialize_option_via_str`]
6033        // — the substrate-side single-owner primitive for the forward
6034        // arm of the typed-magnitude codec family. See its docstring
6035        // for the full sibling roster.
6036        crate::render::serialize_option_via_str(v, s, render)
6037    }
6038
6039    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Duration>, D::Error> {
6040        // Route through the canonical [`crate::render::deserialize_option_via_str`]
6041        // — the substrate-side single-owner primitive for the reverse
6042        // arm of the typed-magnitude codec family. See its docstring
6043        // for the full sibling roster.
6044        crate::render::deserialize_option_via_str(d, parse)
6045    }
6046
6047    pub(crate) fn parse(s: &str) -> Result<Duration, String> {
6048        // Paired whitespace-rejection arm — same canonical-form
6049        // render-determinism discipline as the peer
6050        // `limits::parse_byte_size` / `limits::parse_duration` /
6051        // `limits::parse_millicores` /
6052        // `aplicacao::rate_limit_codec::parse` sites: the ASCII
6053        // byte-scan closes the WhatWG-conformant whitespace bytes
6054        // (`0x20`, `0x09`, `0x0A`, `0x0C`, `0x0D`), the non-ASCII
6055        // `char::is_whitespace` scan closes the strictly-complementary
6056        // Unicode `White_Space` class (NBSP `\u{00A0}`, LINE SEPARATOR
6057        // `\u{2028}`, EM-SPACE `\u{2003}`, and the peer typography
6058        // codepoints) that `str::trim` at parse entry silently strips.
6059        // Either drift class would round-trip through `render` to a
6060        // *different* canonical form on next emit — breaking the
6061        // THEORY.md Part V render-determinism contract on three typed-
6062        // duration slots at once (`:supervisor :restart-window`,
6063        // `:politicas :timeout`, `:politicas :circuit-breaker :window`)
6064        // via the shared codec.
6065        //
6066        // Routed through the lifted [`crate::render::reject_whitespace`]
6067        // primitive — the substrate-side single-owner paired-arm gate
6068        // every typed-magnitude codec in caixa-core shares.
6069        crate::render::reject_whitespace::<String, _, _>(
6070            s,
6071            |b| {
6072                format!(
6073                    "duration: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
6074                 authoring form for the typed duration slots routed through this shared codec \
6075                 (`:supervisor :restart-window`, `:politicas :timeout`, \
6076                 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
6077                 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no whitespace bytes \
6078                 anywhere. A whitespace-carrying shape (`\" 30s\"`, `\"30s \"`, `\"30 s\"`, \
6079                 `\"\\t30s\"`, `\"30s\\n\"`) round-trips through `render` to a *different* \
6080                 canonical form (`\"30s\"`) on first serialize — breaking the THEORY.md \
6081                 Part V render-determinism contract every typed slot carries. Strip every \
6082                 whitespace byte (write `\"30s\"` verbatim)"
6083                )
6084            },
6085            |ch| {
6086                format!(
6087                    "duration: value {s:?} contains non-ASCII Unicode whitespace character \
6088                 {ch:?} (U+{cp:04X}) — the canonical authoring form for the typed \
6089                 duration slots routed through this shared codec (`:supervisor \
6090                 :restart-window`, `:politicas :timeout`, `:politicas :circuit-breaker \
6091                 :window`) is `<integer><unit>` (e.g. `\"30s\"`, `\"500ms\"`, `\"2m\"`, \
6092                 `\"1h\"`) with no whitespace characters anywhere (ASCII or Unicode). A \
6093                 non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}30s\"`, \
6094                 `\"30s\\u{{2028}}\"`, `\"30\\u{{2003}}s\"`) survives the ASCII byte-scan \
6095                 but `str::trim` (which uses `char::is_whitespace` — the Unicode \
6096                 `White_Space` property, strictly wider than the ASCII byte set) silently \
6097                 strips it at parse entry, and the value round-trips through `render` to \
6098                 a *different* canonical form (`\"30s\"`) on first serialize — breaking \
6099                 the THEORY.md Part V render-determinism contract every typed slot \
6100                 carries. Strip every non-ASCII whitespace character (write `\"30s\"` \
6101                 verbatim with only ASCII bytes)",
6102                    cp = ch as u32
6103                )
6104            },
6105        )?;
6106        let s = s.trim();
6107        // Routed through the lifted
6108        // [`crate::render::split_magnitude_and_alpha_unit`] primitive —
6109        // the single-owner split every ASCII-alphabetic-unit typed-
6110        // magnitude codec in caixa-core (`limits::parse_byte_size` /
6111        // `limits::parse_duration` / this shared duration codec) shares.
6112        // See its docstring for the full sibling roster on the same
6113        // primitive altitude.
6114        let (num_part, unit) = crate::render::split_magnitude_and_alpha_unit(s);
6115        let num_trim = num_part.trim();
6116        // The canonical authoring form for every typed slot routed
6117        // through this shared codec — `:supervisor :restart-window`,
6118        // `:politicas :timeout`, `:politicas :circuit-breaker :window`
6119        // — is `<integer><unit>`. Every magnitude [`render`] emits is a
6120        // non-negative integer with no decimal point and no leading
6121        // sign, so the parser's accepted set must match for
6122        // serialize/deserialize to round-trip without canonical-form
6123        // drift. Until this gate landed the parser accepted any
6124        // `f64`-shaped magnitude (`"1.5s"` → 1500ms, `"1.0s"` → 1s,
6125        // `"0.5m"` → 30s, `"+30s"` → 30s) and serde silently round-
6126        // tripped the value to a *different* canonical string on the
6127        // next emit (`"1.5s"` → 1500ms → `"1500ms"`, `"1.0s"` → 1s →
6128        // `"1s"`, `"0.5m"` → 30s → `"30s"`, `"+30s"` → 30s → `"30s"`)
6129        // — breaking the THEORY.md Part V render-determinism contract
6130        // on three typed slots at once. Same canonical-form discipline
6131        // `crate::limits::parse_duration` (818dd38, the immediate
6132        // predecessor on the peer `:limits :wall-clock` codec) applies;
6133        // this gate lifts the discipline onto the shared codec that
6134        // backs the remaining three typed-duration slots in caixa-core.
6135        //
6136        // Strict canonical form: every byte of the magnitude is an
6137        // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
6138        // inputs the gate distinguishes "non-canonical-but-numeric"
6139        // (parses as f64 or i64 — surfaced with a self-locating
6140        // diagnostic naming the canonical authoring form, the
6141        // round-trip drift each rejected shape would produce on first
6142        // serialize, and the canonical-form remediation) from
6143        // "garbage" (parses as neither — surfaced with the existing
6144        // narrower "bad duration magnitude" wording so its diagnostic
6145        // shape remains stable for the parser-shape footgun case).
6146        // The pre-existing `num < 0.0` arm is now unreachable — the
6147        // digit-only gate strictly precedes magnitude parsing, and a
6148        // leading `-` is not an ASCII digit, so `"-30s"` lands on the
6149        // non-canonical-but-numeric branch with the `-30` named
6150        // verbatim in the diagnostic rather than the prior
6151        // value-laundered "negative duration in \"-30s\"" wording.
6152        //
6153        // Routed through the lifted
6154        // [`crate::render::is_digit_only_magnitude`] predicate — the
6155        // same source of truth the four peer typed-magnitude codec
6156        // sites share.
6157        let digit_only = crate::render::is_digit_only_magnitude(num_trim);
6158        if !digit_only {
6159            let numeric = num_trim.parse::<f64>().is_ok() || num_trim.parse::<i64>().is_ok();
6160            if numeric {
6161                return Err(format!(
6162                    "duration: magnitude {num_trim:?} is not a non-negative integer — the \
6163                     canonical authoring form for the typed duration slots routed through \
6164                     this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
6165                     `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
6166                     `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no decimal point and \
6167                     no leading `+` / `-` sign. A fractional / decimal-shaped magnitude \
6168                     (`\"1.5s\"`, `\"1.0s\"`, `\"0.5m\"`, `\"+30s\"`, `\"-30s\"`) round-trips \
6169                     through `render` to a *different* canonical form (`\"1500ms\"`, `\"1s\"`, \
6170                     `\"30s\"`, `\"30s\"`, `\"30s\"`) on first serialize — breaking the \
6171                     THEORY.md Part V render-determinism contract every typed slot carries. \
6172                     Pick an integer magnitude in the unit that divides cleanly (write \
6173                     `\"1500ms\"` instead of `\"1.5s\"`; `\"30s\"` instead of `\"0.5m\"`)"
6174                ));
6175            }
6176            return Err(format!("bad duration magnitude in {s:?}"));
6177        }
6178        // Leading-zero arm — peer with the `rate_limit_codec` leading-
6179        // zero arm (4f46830) on the same canonical-form render-
6180        // determinism axis. The digit-only gate accepts `"030s"`,
6181        // `"00s"`, `"01h"`, `"0500ms"` as `u64::from_str` parses them
6182        // losslessly (= 30, 0, 1, 500), but `render` emits the leading-
6183        // zero-stripped form (`"30s"`, `"0s"`, `"1h"`, `"500ms"`) — a
6184        // *different* canonical string on the next emit, breaking the
6185        // THEORY.md Part V render-determinism contract the same way
6186        // `"+30s"` did before the leading-`+` arm landed. The single-
6187        // byte magnitude `"0"` (or `"0s"` / `"0ms"`) round-trips
6188        // losslessly through `render` (`render(Duration::ZERO)` emits
6189        // `"0s"`) — the downstream semantic-zero gates (e.g.
6190        // `SupervisorError::ZeroRestartWindow` on
6191        // `:supervisor :restart-window`,
6192        // `AplicacaoError::PolicyTimeoutZero` /
6193        // `PolicyCircuitBreakerWindowZero` on the typed `:politicas`
6194        // duration slots) refuse zero-magnitude authoring at the typed-
6195        // validate layer above, so the single-byte `"0"` stays in the
6196        // accepted set at this codec layer and the diagnostic
6197        // partitioning between canonical-form drift (this arm) and
6198        // semantic-zero (the downstream gates) remains stable.
6199        // Peer with the future leading-zero arms on the two remaining
6200        // typed-magnitude codecs the trajectory acknowledges:
6201        // `limits::parse_duration` backing `:limits :wall-clock`,
6202        // `limits::parse_byte_size` backing `:limits :memory` — each
6203        // carries the same canonical-form-drift class today; this
6204        // gate lands the discipline on the shared duration codec
6205        // first because the `rate_limit_codec` predecessor on the
6206        // same canonical-form-drift axis is the closest peer on the
6207        // trajectory.
6208        //
6209        // Routed through the lifted
6210        // [`crate::render::is_leading_zero_padded_magnitude`]
6211        // predicate — the same source of truth the four peer
6212        // typed-magnitude codec sites share.
6213        if crate::render::is_leading_zero_padded_magnitude(num_trim) {
6214            return Err(format!(
6215                "duration: magnitude {num_trim:?} has a non-canonical leading zero — the \
6216                 canonical authoring form for the typed duration slots routed through \
6217                 this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
6218                 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
6219                 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no leading-zero padding \
6220                 on the magnitude. A leading-zero magnitude (`\"030s\"`, `\"00s\"`, \
6221                 `\"01h\"`, `\"0500ms\"`) round-trips through `render` to a *different* \
6222                 canonical form (`\"30s\"`, `\"0s\"`, `\"1h\"`, `\"500ms\"`) on first \
6223                 serialize — breaking the THEORY.md Part V render-determinism contract \
6224                 every typed slot carries. Strip the leading zeros (write \
6225                 `\"30s\"` instead of `\"030s\"`)"
6226            ));
6227        }
6228        // The digit-only gate guarantees every byte is `[0-9]`, and
6229        // the leading-zero arm above guarantees the magnitude is
6230        // either the single byte `"0"` or starts with `[1-9]`, so
6231        // the only way `u64::from_str` can fail here is overflow (the
6232        // magnitude exceeds `u64::MAX`). Surface that with an
6233        // overflow-shaped wording so the diagnostic names the offending
6234        // magnitude verbatim rather than collapsing onto the
6235        // non-canonical arm. The codec now operates on `u64` end-to-end
6236        // — every accepted magnitude is integer-exact; no f64 mantissa
6237        // drift between author-supplied magnitude and the consumer's
6238        // `Duration` value. Same shape `crate::limits::parse_duration`
6239        // (818dd38) carries on the peer `:limits :wall-clock` axis.
6240        let num: u64 = num_trim.parse::<u64>().map_err(|_| {
6241            format!("bad duration magnitude in {s:?} (digit-only magnitude overflows u64)")
6242        })?;
6243        // Route the `{"ms" | "s" | "" | "m" | "h"} → Duration`
6244        // unit-arm dispatch through the canonical
6245        // [`crate::render::duration_from_integer_magnitude_and_unit`]
6246        // primitive — the substrate-side single-owner unit-dispatch
6247        // table every typed-duration codec in caixa-core routes
6248        // through (peer: `crate::limits::parse_duration` backing
6249        // `:limits :wall-clock`). Every unit conversion is integer-
6250        // exact for an integer magnitude; overflow surfaces via the
6251        // typed `DurationUnitError::Overflow { multiplier }`
6252        // discriminant so this arm reconstructs the pre-lift
6253        // `"duration <num><unit> overflows u64 (magnitude × 60 …)"`
6254        // wording verbatim from `num` / `unit_trim` / the returned
6255        // `multiplier`, and the unknown-unit arm reconstructs the
6256        // pre-lift `"unknown duration unit \"<other>\""` wording from
6257        // the caller-scoped `unit_trim`. Load-bearing pinned by
6258        // `crate::render::tests::duration_from_integer_magnitude_and_unit_matches_pre_lift_unit_dispatch_table`.
6259        let unit_trim = unit.trim();
6260        let dur = crate::render::duration_from_integer_magnitude_and_unit(num, unit_trim).map_err(
6261            |e| match e {
6262                crate::render::DurationUnitError::Overflow { multiplier } => format!(
6263                    "duration {num}{unit_trim} overflows u64 (magnitude × {multiplier} > 2^64-1)"
6264                ),
6265                crate::render::DurationUnitError::UnknownUnit => {
6266                    format!("unknown duration unit {unit_trim:?}")
6267                }
6268            },
6269        )?;
6270        Ok(dur)
6271    }
6272
6273    /// Render a [`Duration`] in the canonical pleme-io duration string
6274    /// form (`"30s"`, `"1m"`, `"1h"`, `"500ms"`). The same form every
6275    /// caixa typed-duration slot serializes to and the same form K8s
6276    /// Gateway API HTTPRoute `timeouts` / `backendRequest` and Cilium
6277    /// EnvoyConfig per-route timeouts both expect (an integer
6278    /// followed by `s`/`m`/`h`/`ms`, no fractional values, no leading
6279    /// `+`). Lifted to `pub` so caixa-side renderers
6280    /// (`caixa-mesh::gateway_routes`'s :politicas :timeout overlay,
6281    /// the future per-:politicas `CiliumClusterwideEnvoyConfig`
6282    /// emitter, the future caixa-otel collector pipeline emitter) can
6283    /// consume the same canonical formatter without re-inlining the
6284    /// magnitude/unit decision tree (and inheriting the same drift
6285    /// footguns: a subtly different `300ms` vs `0.3s` rendering breaks
6286    /// downstream apply-time parsing in non-obvious ways).
6287    pub fn render(d: Duration) -> String {
6288        let total_ms = d.as_millis();
6289        if total_ms == 0 {
6290            return "0s".into();
6291        }
6292        if total_ms.is_multiple_of(3600 * 1000) {
6293            return format!("{}h", total_ms / (3600 * 1000));
6294        }
6295        if total_ms.is_multiple_of(60 * 1000) {
6296            return format!("{}m", total_ms / (60 * 1000));
6297        }
6298        if total_ms.is_multiple_of(1000) {
6299            return format!("{}s", total_ms / 1000);
6300        }
6301        format!("{total_ms}ms")
6302    }
6303
6304    /// True iff `d` round-trips losslessly through [`render`] + [`parse`].
6305    ///
6306    /// [`render`] truncates a `Duration` to `as_millis()` before picking the
6307    /// largest divisor unit, so any sub-millisecond residue
6308    /// (`d.subsec_nanos() % 1_000_000 != 0`) silently breaks the THEORY.md
6309    /// §V.2.7 render-determinism contract:
6310    ///
6311    ///   - `Duration::from_micros(1500)` (= `1_500_000` ns) → `as_millis() == 1`
6312    ///     → renders `"1ms"` → parses back to `Duration::from_millis(1)` =
6313    ///     `1_000_000` ns ≠ original `1_500_000` ns;
6314    ///   - `Duration::from_nanos(1)` (= 1 ns) → `as_millis() == 0` →
6315    ///     renders the literal `"0s"`, which the per-axis zero-floor gate
6316    ///     on every typed-`Duration` slot then rejects on re-validate.
6317    ///
6318    /// Lifted to a `pub` predicate next to the [`render`] / [`parse`] pair so
6319    /// the codec's round-trippable accepted set lives in exactly one place —
6320    /// every typed-`Duration` slot that routes through this shared codec
6321    /// (`SupervisorSpec::restart_window` via [`super::duration_codec`],
6322    /// [`crate::MeshPolicy::timeout`] / [`crate::CircuitBreaker::window`] via
6323    /// `supervisor::duration_codec` + [`super::duration_codec_required`]) and
6324    /// every typed-`Duration` slot whose own codec shares the same
6325    /// `as_millis()`-truncation shape ([`crate::LimitsSpec::wall_clock`] via
6326    /// [`crate::limits`]'s in-module `parse_duration` / `render_duration`
6327    /// pair) calls this predicate from its `validate()` to bracket the
6328    /// accepted set against the codec's accepted set, structurally. Drift
6329    /// between the codec's granularity and any typed slot's accepted set is
6330    /// then a single-source-of-truth edit at this predicate rather than a
6331    /// silent round-trip break the next consumer discovers at apply time.
6332    ///
6333    /// Peer of [`crate::aplicacao::POLICY_RETRIES_MAX`] /
6334    /// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] and the
6335    /// `is_dns_1123_label` / `is_canonical_rate_limit_window` predicate
6336    /// family — same "typed-slot's valid set matches its codec's accepted
6337    /// set, structurally" discipline carried at the codec layer.
6338    #[must_use]
6339    pub fn is_integer_millisecond_duration(d: Duration) -> bool {
6340        d.subsec_nanos().is_multiple_of(1_000_000)
6341    }
6342}
6343
6344/// Required-Duration variant for fields that aren't Option<Duration>.
6345pub mod duration_codec_required {
6346    use super::Duration;
6347    use serde::{Deserialize, Deserializer, Serializer};
6348
6349    pub fn serialize<S: Serializer>(v: &Duration, s: S) -> Result<S::Ok, S::Error> {
6350        s.serialize_str(&super::duration_codec::render(*v))
6351    }
6352
6353    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Duration, D::Error> {
6354        let s = String::deserialize(d)?;
6355        super::duration_codec::parse(&s).map_err(serde::de::Error::custom)
6356    }
6357}
6358
6359#[cfg(test)]
6360mod tests {
6361    use super::*;
6362
6363    fn child(name: &str, ver: &str, restart: RestartPolicy) -> ChildSpec {
6364        ChildSpec {
6365            caixa: name.into(),
6366            versao: ver.into(),
6367            restart,
6368        }
6369    }
6370
6371    #[test]
6372    fn child_spec_string_scalar_accessor_pair_is_const_fn() {
6373        // Fail-before-pass-after pin on [`ChildSpec::nome`] +
6374        // [`ChildSpec::versao_requirement`]'s `const`-eval-surface
6375        // posture. Each accessor projects the per-`:children :caixa`
6376        // / per-`:children :versao` [`String`] storage through the
6377        // `pub const fn` [`String::as_str`] (const-stable since Rust
6378        // 1.87, well within the workspace MSRV) — any future
6379        // accidental downgrade to non-`const` fails the corresponding
6380        // `<name>_via_const_fn` wrapper at caixa-core build time with
6381        // E0015 (`cannot call non-const method`), strictly stronger
6382        // than a runtime `assert!`. Sibling of the peer
6383        // per-M2/M3/universal-axis `String → &str` scalar-accessor
6384        // family pins on the sibling `const`-eval-surface passes
6385        // ([`crate::Caixa::nome`] / [`crate::Caixa::versao`] at the
6386        // top-level manifest, [`crate::CaixaVersion::as_str`] at the
6387        // typed-newtype wrapper, [`crate::aplicacao::Membro::nome`] /
6388        // [`crate::aplicacao::Membro::versao_requirement`] at the M3
6389        // membership axis, [`crate::aplicacao::Entrada::hostname`] /
6390        // [`crate::aplicacao::Entrada::destination`] at the M3
6391        // ingress axis,
6392        // [`crate::upgrade::UpgradeFromEntry::prior_versao`] at the
6393        // M2 upgrade axis, [`crate::dep::Dep::nome`] /
6394        // [`crate::dep::Dep::versao_requirement`] at the dep-graph
6395        // axis, and the per-`:contratos`
6396        // [`crate::aplicacao::WitContract::source`] /
6397        // [`crate::aplicacao::WitContract::destination`] /
6398        // [`crate::aplicacao::WitContract::world_ref`] trio the
6399        // sibling pin at 279823b already anchors).
6400        const fn nome_via_const_fn(c: &ChildSpec) -> &str {
6401            c.nome()
6402        }
6403        const fn versao_via_const_fn(c: &ChildSpec) -> &str {
6404            c.versao_requirement()
6405        }
6406        for (caixa, versao) in [
6407            ("worker-a", "^0.1"),
6408            ("worker-b", "~0.2.3"),
6409            ("collector", "*"),
6410        ] {
6411            let c = child(caixa, versao, RestartPolicy::Permanent);
6412            assert_eq!(nome_via_const_fn(&c), c.nome());
6413            assert_eq!(versao_via_const_fn(&c), c.versao_requirement());
6414            assert_eq!(c.nome(), caixa);
6415            assert_eq!(c.versao_requirement(), versao);
6416        }
6417    }
6418
6419    #[test]
6420    fn supervisor_children_slice_return_accessor_is_const_fn() {
6421        // Fail-before-pass-after pin on [`SupervisorSpec::children`]'s
6422        // `const`-eval-surface posture. The accessor destructures the
6423        // per-`:children` `Vec<ChildSpec>` storage through the
6424        // `pub const fn` [`Vec::as_slice`] (const-stable since Rust
6425        // 1.66, well within the workspace MSRV) — any future
6426        // accidental downgrade to non-`const` fails
6427        // `children_via_const_fn` at caixa-core build time with E0015
6428        // (`cannot call non-const method`), strictly stronger than a
6429        // runtime `assert!`. Sibling of the peer per-M3-mesh-slot
6430        // `Vec → &[T]` slice-return accessor family pin
6431        // [`crate::aplicacao::tests::m3_reference_return_accessor_family_is_const_fn`]
6432        // on the M3 mesh-slot per-`:clusters` / per-`:paths` /
6433        // per-`:membros` / per-`:contratos` slice-return axes, and of
6434        // the peer M2 upgrade-appup axis pin
6435        // [`crate::upgrade::tests::upgrade_from_entry_instructions_slice_return_accessor_is_const_fn`]
6436        // on the per-`:upgrade-from :instructions` slice-return axis.
6437        const fn children_via_const_fn(s: &SupervisorSpec) -> &[ChildSpec] {
6438            s.children()
6439        }
6440        // Sweep both the empty-children (leaf-supervisor with no
6441        // static children — the `SimpleOneForOne` dynamic-child
6442        // arm's canonical shape) and the populated-children
6443        // (`OneForOne` / `OneForAll` / `RestForOne` static-child
6444        // arm's canonical shape) axes so the accessor carries a
6445        // const-dispatch pin on both arms.
6446        let s_empty = SupervisorSpec {
6447            estrategia: RestartStrategy::SimpleOneForOne,
6448            max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
6449            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
6450            children: vec![],
6451        };
6452        assert!(children_via_const_fn(&s_empty).is_empty());
6453        assert_eq!(children_via_const_fn(&s_empty), s_empty.children());
6454        let s_full = SupervisorSpec {
6455            estrategia: RestartStrategy::OneForOne,
6456            max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
6457            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
6458            children: vec![
6459                child("worker-a", "^0.1", RestartPolicy::Permanent),
6460                child("worker-b", "~0.2.3", RestartPolicy::Transient),
6461                child("collector", "*", RestartPolicy::Temporary),
6462            ],
6463        };
6464        assert_eq!(children_via_const_fn(&s_full).len(), 3);
6465        assert_eq!(children_via_const_fn(&s_full), s_full.children());
6466    }
6467
6468    #[test]
6469    fn default_has_one_for_one_and_5_restarts_in_60s() {
6470        let s = SupervisorSpec::default();
6471        assert_eq!(s.estrategia, RestartStrategy::OneForOne);
6472        assert_eq!(s.max_restarts, 5);
6473        assert_eq!(s.restart_window, Some(Duration::from_secs(60)));
6474        assert!(s.children.is_empty());
6475    }
6476
6477    #[test]
6478    fn validate_one_for_one_requires_children() {
6479        // Explicit-empty via struct-update rather than `let mut s = default(); s.children = vec![];`
6480        // — the peer `validate_simple_one_for_one_forbids_static_children` below already uses
6481        // struct-update to name the axis under test at construction, and this shape matches
6482        // it. Also keeps the "empty children is the axis under test" intent visible at the
6483        // binding site rather than one line down, and side-steps `clippy::field_reassign_with_default`.
6484        let mut s = SupervisorSpec {
6485            children: vec![],
6486            ..SupervisorSpec::default()
6487        };
6488        assert!(matches!(
6489            s.validate().unwrap_err(),
6490            SupervisorError::NoChildren { .. }
6491        ));
6492        s.children = vec![child("worker", "^0.1", RestartPolicy::Permanent)];
6493        s.validate().unwrap();
6494    }
6495
6496    #[test]
6497    fn validate_simple_one_for_one_forbids_static_children() {
6498        let mut s = SupervisorSpec {
6499            estrategia: RestartStrategy::SimpleOneForOne,
6500            ..SupervisorSpec::default()
6501        };
6502        s.children
6503            .push(child("w", "^0.1", RestartPolicy::Permanent));
6504        assert_eq!(
6505            s.validate().unwrap_err(),
6506            SupervisorError::SimpleOneForOneWithStaticChildren
6507        );
6508        s.children.clear();
6509        s.validate().unwrap();
6510    }
6511
6512    #[test]
6513    fn validate_rejects_zero_max_restarts() {
6514        let s = SupervisorSpec {
6515            max_restarts: 0,
6516            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6517            ..SupervisorSpec::default()
6518        };
6519        assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
6520    }
6521
6522    // ── upper-cap: SUPERVISOR_MAX_RESTARTS_MAX brackets the typed slot ─────
6523    //
6524    // The cap arm lifts the `:politicas :circuit-breaker :max-failures` /
6525    // `POLICY_BREAKER_MAX_FAILURES_MAX` (2b51ace) discipline onto the peer
6526    // `:supervisor :max-restarts` axis — both fields are "trip the
6527    // next-higher protection layer after N events in a rolling window"
6528    // counters with identical degenerate-at-the-high-end shape, so the
6529    // typed-slot's accepted set lies in `1..=1000` on the supervisor side
6530    // exactly as it lies in `1..=1000` on the breaker side.
6531
6532    #[test]
6533    fn validate_rejects_max_restarts_above_cap() {
6534        // The fail-before-pass-after pin: `SUPERVISOR_MAX_RESTARTS_MAX +
6535        // 1` is structurally one past the cap and silently passed
6536        // validate on every pre-gate codebase because the typed slot's
6537        // only check was the zero-floor arm. The no-op-supervisor vector
6538        // only surfaced at the runtime substrate (Erlang/OTP
6539        // MaxIntensity/Period ratio, the future wasm-operator's
6540        // per-supervisor restart-intensity counter) far from the source
6541        // caixa.lisp with no field naming the offending supervisor.
6542        let s = SupervisorSpec {
6543            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
6544            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6545            ..SupervisorSpec::default()
6546        };
6547        assert_eq!(
6548            s.validate().unwrap_err(),
6549            SupervisorError::MaxRestartsExceedsCap {
6550                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
6551            }
6552        );
6553    }
6554
6555    #[test]
6556    fn validate_rejects_max_restarts_far_above_cap() {
6557        // The `u32::MAX` worst case — the four-billion-restart
6558        // threshold a typo (`:max-restarts 4294967295`) or a
6559        // struct-literal copy-paste lands in the slot. Pin the cap
6560        // arm's coverage explicitly across the full `u32` overflow so
6561        // a future relaxation that drops the upper bound surfaces
6562        // here. Same shape every other typed-cap arm on this surface
6563        // carries (POLICY_BREAKER_MAX_FAILURES_MAX,
6564        // POLICY_RETRIES_MAX, POLICY_RATE_LIMIT_MAX).
6565        let s = SupervisorSpec {
6566            max_restarts: u32::MAX,
6567            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6568            ..SupervisorSpec::default()
6569        };
6570        assert_eq!(
6571            s.validate().unwrap_err(),
6572            SupervisorError::MaxRestartsExceedsCap {
6573                max_restarts: u32::MAX,
6574            }
6575        );
6576    }
6577
6578    #[test]
6579    fn validate_accepts_max_restarts_at_cap() {
6580        // The boundary value — exactly SUPERVISOR_MAX_RESTARTS_MAX —
6581        // must validate. The cap is inclusive on the top edge,
6582        // matching the POLICY_BREAKER_MAX_FAILURES_MAX /
6583        // POLICY_RETRIES_MAX / LIMITS_MEMORY_WASM32_MAX_BYTES
6584        // discipline on the sibling capped axes. Pin the boundary
6585        // explicitly so a future off-by-one tightening
6586        // (`>= SUPERVISOR_MAX_RESTARTS_MAX` instead of `>`) surfaces
6587        // here as a test failure rather than a silent contract
6588        // narrowing.
6589        let s = SupervisorSpec {
6590            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX,
6591            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6592            ..SupervisorSpec::default()
6593        };
6594        s.validate()
6595            .expect("max_restarts == SUPERVISOR_MAX_RESTARTS_MAX must validate");
6596    }
6597
6598    #[test]
6599    fn validate_accepts_max_restarts_typical_values() {
6600        // The documented production-playbook band positive-control
6601        // sweep — every value Erlang/OTP / Elixir / Riak Core /
6602        // RabbitMQ recommend (1..=100) must pass, plus a sweep
6603        // through the hyperscale band (200, 500, 1000) the cap
6604        // accepts. Pin the inclusive validated set explicitly so a
6605        // future tightening of the ceiling surfaces here.
6606        for n in [1u32, 3, 5, 10, 20, 50, 100, 200, 500, 1000] {
6607            let s = SupervisorSpec {
6608                max_restarts: n,
6609                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6610                ..SupervisorSpec::default()
6611            };
6612            s.validate()
6613                .unwrap_or_else(|e| panic!("max_restarts={n} must validate; got {e:?}"));
6614        }
6615    }
6616
6617    #[test]
6618    fn zero_max_restarts_takes_precedence_over_cap() {
6619        // The cross-arm ordering pin: `0` is structurally outside
6620        // both `1..` (zero-floor) and `..=SUPERVISOR_MAX_RESTARTS_MAX`
6621        // (cap), but the zero-floor diagnostic is the more
6622        // self-locating one (it directly names the counter-axis
6623        // remediation), so the validate gate must fire on zero first.
6624        // Same shape every other zero-then-shape ordering on this
6625        // surface uses (PolicyRetriesZero then
6626        // PolicyRetriesExceedsCap; PolicyBreakerZeroFailures then
6627        // PolicyBreakerMaxFailuresExceedsCap).
6628        let s = SupervisorSpec {
6629            max_restarts: 0,
6630            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6631            ..SupervisorSpec::default()
6632        };
6633        assert_eq!(
6634            s.validate().unwrap_err(),
6635            SupervisorError::ZeroMaxRestarts,
6636            "max_restarts == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
6637        );
6638    }
6639
6640    #[test]
6641    fn max_restarts_cap_takes_precedence_over_restart_window_gates() {
6642        // The cross-arm ordering pin between the cap and the sibling
6643        // `:restart-window` gates (zero-window, canonical-window). A
6644        // supervisor carrying both an over-cap `max_restarts` AND a
6645        // structurally invalid window (zero, sub-ms) must surface the
6646        // cap diagnostic first — the cap arm is wired immediately
6647        // after the zero-restart arm and strictly before the window
6648        // arms, so the offending value the diagnostic names matches
6649        // the order the author would discover the gates by reading
6650        // top-to-bottom through `SupervisorSpec::validate`. Pin the
6651        // order so a future refactor that reorders the arms surfaces
6652        // here as a test failure rather than a silent diagnostic
6653        // regression. Peer of
6654        // `circuit_breaker_max_failures_cap_takes_precedence_over_window_gates`
6655        // on the sibling `:politicas :circuit-breaker` slot.
6656        let s = SupervisorSpec {
6657            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
6658            restart_window: Some(Duration::ZERO),
6659            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6660            ..SupervisorSpec::default()
6661        };
6662        assert_eq!(
6663            s.validate().unwrap_err(),
6664            SupervisorError::MaxRestartsExceedsCap {
6665                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
6666            },
6667            "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
6668        );
6669    }
6670
6671    #[test]
6672    fn max_restarts_cap_diagnostic_carries_offending_value() {
6673        // The diagnostic-shape pin: the offending `u32` is carried
6674        // verbatim into the `SupervisorError::MaxRestartsExceedsCap`
6675        // variant so the surfaced error message names the value the
6676        // author wrote (`":supervisor :max-restarts (50000) exceeds the
6677        // supervisor-policy ceiling …"`), not just the cap. Same
6678        // self-locating diagnostic shape every other typed-cap arm on
6679        // this surface carries
6680        // (`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap` carries
6681        // the offending failure count verbatim,
6682        // `AplicacaoError::PolicyRetriesExceedsCap` carries the offending
6683        // retries count verbatim).
6684        let s = SupervisorSpec {
6685            max_restarts: 50_000,
6686            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6687            ..SupervisorSpec::default()
6688        };
6689        let err = s.validate().unwrap_err();
6690        assert!(
6691            matches!(
6692                err,
6693                SupervisorError::MaxRestartsExceedsCap {
6694                    max_restarts: 50_000
6695                }
6696            ),
6697            "got {err:?}"
6698        );
6699        let msg = err.to_string();
6700        assert!(
6701            msg.contains("50000"),
6702            ":supervisor :max-restarts cap diagnostic must carry the offending value verbatim (got: {msg})"
6703        );
6704    }
6705
6706    #[test]
6707    fn supervisor_max_restarts_default_pins_otp_canonical_value() {
6708        // Pin [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] at `5` — the
6709        // Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
6710        // half of Learn You Some Erlang's worker-supervisor default,
6711        // sibling of the `60s` `Period` half that the paired
6712        // [`Default for SupervisorSpec`] impl already pins on the
6713        // sibling `restart_window` axis. Pinning the literal here
6714        // surfaces a future rebrand (a tightening to Elixir's `3`,
6715        // a widening to a per-cluster overlay the operator pins
6716        // through a future `:max-restarts-overrides` slot) as a
6717        // deliberate test edit, not a silent contract migration.
6718        // Peer of the sibling
6719        // [`supervisor_max_restarts_cap_pins_canonical_value`]
6720        // upper-bracket pin on the same axis.
6721        assert_eq!(SUPERVISOR_MAX_RESTARTS_DEFAULT, 5);
6722    }
6723
6724    #[test]
6725    fn default_max_restarts_helper_routes_through_lifted_default() {
6726        // Composition pin: the private `default_max_restarts()`
6727        // serde-`#[serde(default = "…")]` helper on
6728        // [`SupervisorSpec::max_restarts`] must route through the
6729        // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
6730        // typed `pub const` rather than a raw `5` literal. Prior to
6731        // the lift the helper carried an inline `5` with no compile-
6732        // time link back to the shared default, so the wire-format
6733        // author-omitted arm and the caixa-core
6734        // [`crate::manifest::Caixa::supervisor_view`] fold's `unwrap_or(5)`
6735        // arm could silently split on any future default rebrand.
6736        // Byte-parity against the lifted constant closes the split.
6737        assert_eq!(default_max_restarts(), SUPERVISOR_MAX_RESTARTS_DEFAULT);
6738    }
6739
6740    #[test]
6741    fn supervisor_spec_default_max_restarts_routes_through_lifted_default() {
6742        // Composition pin: the [`Default for SupervisorSpec`] impl's
6743        // struct-literal `max_restarts` field must route through the
6744        // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
6745        // typed `pub const` (via the private helper this test's
6746        // sibling `default_max_restarts_helper_routes_through_lifted_default`
6747        // already pins onto the constant). Structurally: every
6748        // `SupervisorSpec::default()` call must yield a
6749        // `max_restarts` field byte-equal to the lifted constant
6750        // (the two paired defaults — the serde-side wire-format arm
6751        // and the struct-literal default arm — cannot silently split
6752        // on any future default rebrand). Peer of the sibling
6753        // `default_has_one_for_one_and_5_restarts_in_60s` shape pin
6754        // — this pin closes the byte-parity arm on the two paired
6755        // altitude entry points onto the shared substrate constant.
6756        assert_eq!(
6757            SupervisorSpec::default().max_restarts(),
6758            SUPERVISOR_MAX_RESTARTS_DEFAULT,
6759        );
6760    }
6761
6762    #[test]
6763    fn supervisor_restart_window_default_pins_otp_canonical_value() {
6764        // Pin [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] at `60s` — the
6765        // Erlang/OTP-canonical `{intensity, 5, 60}` `Period` half of
6766        // Learn You Some Erlang's worker-supervisor default, paired
6767        // with the sibling `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5`
6768        // `MaxIntensity` half this constant is the sliding-window
6769        // denominator of on the same `MaxIntensity / Period`
6770        // restart-intensity ratio. Pinning the literal here surfaces a
6771        // future coherent rebrand of the paired default (Elixir's
6772        // `{max_restarts: 3, max_seconds: 5}`, a per-cluster overlay
6773        // the operator pins through a future
6774        // `:restart-window-overrides` slot) as a deliberate test edit,
6775        // not a silent contract migration. Peer of the sibling
6776        // [`supervisor_max_restarts_default_pins_otp_canonical_value`]
6777        // paired-half pin on the same OTP-canonical default and the
6778        // [`supervisor_restart_window_cap_pins_canonical_value`]
6779        // upper-bracket pin on the same axis.
6780        assert_eq!(SUPERVISOR_RESTART_WINDOW_DEFAULT, Duration::from_secs(60),);
6781    }
6782
6783    #[test]
6784    fn supervisor_spec_default_restart_window_routes_through_lifted_default() {
6785        // Composition pin: the [`Default for SupervisorSpec`] impl's
6786        // struct-literal `restart_window` field must route through the
6787        // substrate-canonical [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
6788        // typed `pub const` rather than a raw
6789        // `Duration::from_secs(60)` literal. Prior to this lift the
6790        // paired `{intensity, 5, 60}` OTP-canonical default was split
6791        // across two altitudes with no compile-time link between the
6792        // halves — the `MaxIntensity` half rode through the lifted
6793        // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant while the
6794        // `Period` half rode as an open-coded literal at the
6795        // composition site, so a future coherent rebrand of the paired
6796        // canonical would have had to migrate one half through the
6797        // constant and the other through a raw literal in lockstep.
6798        // Byte-parity against the lifted constant on the `Period` half
6799        // closes the split — the paired OTP-canonical default now
6800        // migrates as one unit on any future axis change. Peer of the
6801        // sibling
6802        // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
6803        // byte-parity pin on the paired `MaxIntensity` half.
6804        assert_eq!(
6805            SupervisorSpec::default().restart_window(),
6806            Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
6807        );
6808    }
6809
6810    #[test]
6811    fn supervisor_estrategia_default_pins_otp_canonical_value() {
6812        // Pin [`SUPERVISOR_ESTRATEGIA_DEFAULT`] at [`RestartStrategy::OneForOne`]
6813        // — the Erlang/OTP-canonical `one_for_one` half of Learn You Some
6814        // Erlang's `{one_for_one, intensity, 5, 60}` worker-supervisor
6815        // canonical default, paired with the sibling
6816        // `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5` `MaxIntensity` half and the
6817        // sibling `SUPERVISOR_RESTART_WINDOW_DEFAULT` `60s` `Period` half
6818        // this constant is the strategy discriminator of on the same
6819        // OTP-canonical worker-supervisor default. Pinning the arm here
6820        // surfaces a future coherent rebrand of the paired triple (Elixir's
6821        // `{:one_for_one, max_restarts: 3, max_seconds: 5}` on the sibling
6822        // intensity/period axes leaving this strategy arm untouched, an OTP
6823        // `rest_for_one` widening once the substrate discovers startup-
6824        // order-coupled child cohorts as the more common worker-supervisor
6825        // shape, a per-cluster overlay the operator pins through a future
6826        // `:estrategia-overrides` slot the MESH-COMPOSITION §III.2
6827        // supervision-canary roadmap acknowledges) as a deliberate test
6828        // edit, not a silent contract migration. Peer of the sibling
6829        // [`supervisor_max_restarts_default_pins_otp_canonical_value`] +
6830        // [`supervisor_restart_window_default_pins_otp_canonical_value`]
6831        // paired-half pins on the same OTP-canonical default.
6832        assert_eq!(SUPERVISOR_ESTRATEGIA_DEFAULT, RestartStrategy::OneForOne);
6833    }
6834
6835    #[test]
6836    fn restart_strategy_default_routes_through_lifted_default() {
6837        // Composition pin: the [`Default for RestartStrategy`] impl's
6838        // return arm must route through the substrate-canonical
6839        // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
6840        // a raw `Self::OneForOne` arm. Prior to the lift the impl carried
6841        // an inline `Self::OneForOne` with no compile-time link back to
6842        // the shared OTP-canonical `one_for_one` strategy the paired
6843        // [`Default for SupervisorSpec`] impl's struct-literal `estrategia`
6844        // field and the [`crate::manifest::Caixa::supervisor_view`] fold's
6845        // `.unwrap_or_default()` (now
6846        // `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)`) arm both key off —
6847        // so a future rebrand of the OTP-canonical strategy default (an
6848        // OTP `rest_for_one` widening once the substrate discovers
6849        // startup-order-coupled child cohorts as the more common worker-
6850        // supervisor shape, a per-cluster overlay the operator pins
6851        // through a future `:estrategia-overrides` slot) would have had to
6852        // be threaded through the `Default` impl and the two peer routes
6853        // in lockstep or the three consumers would silently split. Byte-
6854        // parity against the lifted constant closes the split. Peer of
6855        // the sibling
6856        // [`default_max_restarts_helper_routes_through_lifted_default`] +
6857        // [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
6858        // composition pins on the paired `MaxIntensity` + `Period` halves.
6859        assert_eq!(RestartStrategy::default(), SUPERVISOR_ESTRATEGIA_DEFAULT,);
6860    }
6861
6862    #[test]
6863    fn supervisor_spec_default_estrategia_routes_through_lifted_default() {
6864        // Composition pin: the [`Default for SupervisorSpec`] impl's
6865        // struct-literal `estrategia` field must route through the
6866        // substrate-canonical [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed
6867        // `pub const` (either directly, or via the
6868        // [`RestartStrategy::default`] impl that the sibling
6869        // `restart_strategy_default_routes_through_lifted_default` pin
6870        // already routes onto the constant). Structurally: every
6871        // `SupervisorSpec::default()` call must yield an `estrategia`
6872        // field byte-equal to the lifted constant (the three paired
6873        // defaults — the [`Default for RestartStrategy`] impl arm, the
6874        // struct-literal default arm here, and the
6875        // [`crate::manifest::Caixa::supervisor_view`] fold arm — cannot
6876        // silently split on any future default rebrand). Peer of the
6877        // sibling
6878        // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
6879        // + [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
6880        // byte-parity pins on the paired `MaxIntensity` + `Period` halves
6881        // of the same `SupervisorSpec::default()` composed altitude.
6882        assert_eq!(
6883            SupervisorSpec::default().estrategia(),
6884            SUPERVISOR_ESTRATEGIA_DEFAULT,
6885        );
6886    }
6887
6888    #[test]
6889    fn supervisor_spec_default_routes_through_otp_canonical_ctor() {
6890        // Composition pin: the [`Default for SupervisorSpec`] impl must
6891        // route through the substrate-canonical
6892        // [`SupervisorSpec::otp_canonical`] `pub const fn` constructor
6893        // rather than a re-hand-authored struct-literal cascade. Sharpens
6894        // the sibling per-arm
6895        // `supervisor_spec_default_*_routes_through_lifted_default` pins
6896        // from a per-field lift into a whole-struct one-source-of-truth
6897        // pin — the derived-until-now [`Default::default`] and the
6898        // [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
6899        // construction, not by coincidence.
6900        //
6901        // A future extension of the OTP-canonical baseline (a fifth
6902        // `restart_intensity` field the Erlang/OTP `#supervisor` record
6903        // grows, a per-child-cohort split of the `restart_window` /
6904        // `max_restarts` pair, an M4 `mesh.pleme.io/v1alpha1/Supervisor`
6905        // CR materializer's admission-time overlay pass) reaches both
6906        // paths through exactly one edit on
6907        // [`SupervisorSpec::otp_canonical`] — the derived path could
6908        // silently disagree with the constructor's shape on any new
6909        // field whose [`Default::default`] resolves to a different arm
6910        // than the OTP-canonical baseline the constructor names, while
6911        // this delegated impl reaches the constructor directly and
6912        // picks up every future extension by construction.
6913        //
6914        // Fourth peer on the M2 / M3 typed-slot-spec
6915        // [`Default`]-through-const-ctor fold family — sibling of the
6916        // [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
6917        // (abd52c2), [`crate::aplicacao::MeshPolicy`]
6918        // [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`]
6919        // (91641a4), and [`crate::BehaviorSpec`]
6920        // [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c)
6921        // per-`Option`-only-typed-slot folds — extended here onto the
6922        // M2 supervisor-slot [`SupervisorSpec`] whose canonical baseline
6923        // is not "everything `None`" but the Erlang/OTP-canonical
6924        // `{one_for_one, 5, 60}` worker-supervisor triple.
6925        assert_eq!(SupervisorSpec::default(), SupervisorSpec::otp_canonical());
6926    }
6927
6928    #[test]
6929    fn supervisor_spec_otp_canonical_byte_equals_default() {
6930        // Value pin: [`SupervisorSpec::otp_canonical`] must byte-equal
6931        // the hand-authored `{one_for_one, 5, 60, []}` OTP-canonical
6932        // baseline the sibling `default_has_one_for_one_and_5_restarts_in_60s`
6933        // pin already asserts against the [`Default::default`] path.
6934        // Sharpens the pair-invariant into a per-constructor pin so a
6935        // future extension of [`SupervisorSpec`] with a fifth field
6936        // whose OTP-canonical shape is non-`Default::default`-equivalent
6937        // trips at caixa-core test time rather than at a downstream
6938        // consumer that composed [`SupervisorSpec::otp_canonical`] with
6939        // [`SupervisorSpec::validate`] as its "canonical baseline
6940        // seed".
6941        let canonical = SupervisorSpec::otp_canonical();
6942        assert_eq!(canonical.estrategia, RestartStrategy::OneForOne);
6943        assert_eq!(canonical.max_restarts, 5);
6944        assert_eq!(canonical.restart_window, Some(Duration::from_secs(60)));
6945        assert!(canonical.children.is_empty());
6946    }
6947
6948    #[test]
6949    fn supervisor_spec_otp_canonical_is_usable_in_const_context() {
6950        // Const-context pin: [`SupervisorSpec::otp_canonical`] must
6951        // remain callable from a `const`-bound position so downstream
6952        // `const`-context callers wanting a canonical OTP-baseline seed
6953        // can construct one at compile time without runtime dispatch on
6954        // the derived [`Default::default`]. Peer of the sibling
6955        // `pub const fn` [`crate::LimitsSpec::empty`] /
6956        // [`crate::aplicacao::MeshPolicy::empty`] /
6957        // [`crate::BehaviorSpec::empty`] constructors on the sibling
6958        // typed-slot-spec `pub const fn` axis. If a future edit breaks
6959        // the `const`-eligibility of [`SupervisorSpec::otp_canonical`]
6960        // (a non-`const` field-default helper, a non-`const`-stable
6961        // container type promotion), this evaluation fails at
6962        // build time on this file rather than at a downstream
6963        // `const`-context call site.
6964        const CANONICAL: SupervisorSpec = SupervisorSpec::otp_canonical();
6965        assert_eq!(CANONICAL.estrategia, SUPERVISOR_ESTRATEGIA_DEFAULT);
6966        assert_eq!(CANONICAL.max_restarts, SUPERVISOR_MAX_RESTARTS_DEFAULT);
6967        assert_eq!(
6968            CANONICAL.restart_window,
6969            Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
6970        );
6971        assert!(CANONICAL.children.is_empty());
6972    }
6973
6974    #[test]
6975    fn supervisor_child_restart_default_pins_otp_canonical_value() {
6976        // Pin [`SUPERVISOR_CHILD_RESTART_DEFAULT`] at
6977        // [`RestartPolicy::Permanent`] — Erlang/OTP's `permanent`
6978        // worker-child restart type (`{ChildId, StartFunc, permanent, …}`
6979        // in a `supervisor`'s `init/1` child-spec tuple), the per-child
6980        // half of the same OTP-shape supervisor-tree default set whose
6981        // per-`:supervisor` halves the sibling
6982        // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
6983        // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] /
6984        // [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] constants pin. Pinning the
6985        // arm here surfaces a future rebrand of the per-child default (an
6986        // OTP-`transient` widening once the substrate discovers clean-
6987        // completion-aware children as the more common child shape, a
6988        // per-cluster overlay the operator pins through a future
6989        // `:restart-overrides` slot the MESH-COMPOSITION §III.2
6990        // supervision-canary roadmap acknowledges) as a deliberate test
6991        // edit, not a silent contract migration. Peer of the sibling
6992        // [`supervisor_estrategia_default_pins_otp_canonical_value`] /
6993        // [`supervisor_max_restarts_default_pins_otp_canonical_value`] /
6994        // [`supervisor_restart_window_default_pins_otp_canonical_value`]
6995        // value pins on the per-`:supervisor` halves.
6996        assert_eq!(SUPERVISOR_CHILD_RESTART_DEFAULT, RestartPolicy::Permanent);
6997    }
6998
6999    #[test]
7000    fn restart_policy_default_routes_through_lifted_default() {
7001        // Composition pin: the [`Default for RestartPolicy`] impl's return
7002        // arm must route through the substrate-canonical
7003        // [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const` rather
7004        // than a raw `Self::Permanent` arm. Prior to the lift the impl
7005        // carried an inline `Self::Permanent` with no compile-time link
7006        // back to the OTP-shape supervisor-tree default set whose three
7007        // per-`:supervisor` halves already rode through lifted constants
7008        // — so a future coherent rebrand of the set would have had to
7009        // migrate three halves through typed constants and this fourth
7010        // through a raw enum arm in lockstep or the supervisor-level and
7011        // child-level defaults would silently drift apart. Byte-parity
7012        // against the lifted constant closes the split. Peer of the
7013        // sibling
7014        // [`restart_strategy_default_routes_through_lifted_default`]
7015        // composition pin on the per-`:supervisor` `:estrategia` axis.
7016        assert_eq!(RestartPolicy::default(), SUPERVISOR_CHILD_RESTART_DEFAULT);
7017    }
7018
7019    #[test]
7020    fn child_spec_serde_default_restart_routes_through_lifted_default() {
7021        // Composition pin: the serde-side `#[serde(default)]` on
7022        // [`ChildSpec::restart`] — the wire-format author-omitted
7023        // `:children :restart` arm — must resolve onto the substrate-
7024        // canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const`
7025        // (via the [`Default for RestartPolicy`] impl the sibling
7026        // `restart_policy_default_routes_through_lifted_default` pin
7027        // already routes onto the constant). Structurally: a `ChildSpec`
7028        // deserialized from a payload that omits the `restart` key must
7029        // yield a `restart` field byte-equal to the lifted constant, so
7030        // the wire-format author-omitted arm and the
7031        // [`RestartPolicy::default`] impl arm cannot silently split on any
7032        // future default rebrand. Peer of the sibling
7033        // [`supervisor_spec_default_estrategia_routes_through_lifted_default`]
7034        // / [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
7035        // / [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
7036        // byte-parity pins on the per-`:supervisor` halves of the same
7037        // author-omitted-slot resolution surface.
7038        let omitted: ChildSpec = serde_json::from_str(r#"{"caixa":"worker","versao":"^0.1"}"#)
7039            .expect("ChildSpec must deserialize with the restart key omitted");
7040        assert_eq!(
7041            omitted.restart(),
7042            SUPERVISOR_CHILD_RESTART_DEFAULT,
7043            "an author-omitted :children :restart slot must degrade onto \
7044             the SUPERVISOR_CHILD_RESTART_DEFAULT typed pub const (got \
7045             {:?}, expected {:?})",
7046            omitted.restart(),
7047            SUPERVISOR_CHILD_RESTART_DEFAULT,
7048        );
7049    }
7050
7051    #[test]
7052    fn supervisor_max_restarts_cap_pins_canonical_value() {
7053        // The SUPERVISOR_MAX_RESTARTS_MAX constant pins the value at
7054        // 1000 — the same ceiling the peer
7055        // POLICY_BREAKER_MAX_FAILURES_MAX cap carries on the
7056        // `:politicas :circuit-breaker :max-failures` axis (both are
7057        // "trip the next-higher protection layer after N events in a
7058        // rolling window" counters with identical
7059        // degenerate-at-the-high-end shape; uniform top edge so the
7060        // M4 CR materializers and the wasm-operator reconciler reach
7061        // for either field knowing the value is in `1..=1000`). Two
7062        // orders of magnitude above every documented Erlang/OTP /
7063        // Elixir / Riak Core / RabbitMQ production-playbook
7064        // recommendation band and below the clearly-pathological
7065        // "effectively no escalation" floor (10_000, 100_000,
7066        // u32::MAX). Pinning the literal value here surfaces a future
7067        // drift (a relaxation to 10_000, a tightening to 100) as a
7068        // deliberate test edit, not a silent contract narrowing.
7069        assert_eq!(SUPERVISOR_MAX_RESTARTS_MAX, 1000);
7070    }
7071
7072    #[test]
7073    fn validate_rejects_empty_child_name() {
7074        let s = SupervisorSpec {
7075            children: vec![child("", "^0.1", RestartPolicy::Permanent)],
7076            ..SupervisorSpec::default()
7077        };
7078        assert_eq!(s.validate().unwrap_err(), SupervisorError::EmptyChildName);
7079    }
7080
7081    #[test]
7082    fn validate_rejects_empty_child_version() {
7083        let s = SupervisorSpec {
7084            children: vec![child("w", "", RestartPolicy::Permanent)],
7085            ..SupervisorSpec::default()
7086        };
7087        assert!(matches!(
7088            s.validate().unwrap_err(),
7089            SupervisorError::EmptyChildVersion { .. }
7090        ));
7091    }
7092
7093    // ── value-shape: parse-as-VersionReq on :children :versao ─────────────
7094
7095    #[test]
7096    fn validate_rejects_invalid_child_versao_requirement() {
7097        // The fail-before-pass-after pin: a non-empty but malformed
7098        // semver requirement (`"^bad-version"`) silently passed
7099        // `validate()` on every pre-gate codebase because the prior
7100        // shape only refused the empty string. The parse failure
7101        // surfaced far downstream at lacre-resolve time with a
7102        // `semver::Error` that didn't name which `:children` entry
7103        // carried the typo. The new gate moves the check to caixa-build
7104        // time at the source caixa.lisp — the third `:versao` typed
7105        // axis (`:children`) joins `:deps` and `:membros` (9888b13) at
7106        // structural parity.
7107        let s = SupervisorSpec {
7108            children: vec![
7109                child("worker", "^0.1", RestartPolicy::Permanent),
7110                child("cache", "^bad-version", RestartPolicy::Transient),
7111            ],
7112            ..SupervisorSpec::default()
7113        };
7114        let err = s.validate().unwrap_err();
7115        assert!(
7116            matches!(
7117                err,
7118                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
7119                    if caixa == "cache" && versao == "^bad-version"
7120            ),
7121            "got {err:?}"
7122        );
7123    }
7124
7125    #[test]
7126    fn validate_rejects_child_versao_with_double_caret_typo() {
7127        // `"^^0.1"` is the canonical doubled-caret typo — looks
7128        // Cargo-shaped on first glance but fails the parser because
7129        // semver doesn't accept stacked operators. Pin this
7130        // adjacent-shape footgun explicitly so a future relaxation that
7131        // accepts "looks-canonical-but-isn't" forms surfaces here.
7132        let s = SupervisorSpec {
7133            children: vec![child("worker", "^^0.1", RestartPolicy::Permanent)],
7134            ..SupervisorSpec::default()
7135        };
7136        let err = s.validate().unwrap_err();
7137        assert!(
7138            matches!(
7139                err,
7140                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
7141                    if caixa == "worker" && versao == "^^0.1"
7142            ),
7143            "got {err:?}"
7144        );
7145    }
7146
7147    #[test]
7148    fn validate_rejects_child_versao_with_v_prefixed_tag() {
7149        // `"v0.1"` is the canonical "git-tag-shape leaking into the
7150        // semver requirement slot" typo — an author copies the
7151        // publish-side git-tag string verbatim into `:versao`, but
7152        // Cargo's semver parser rejects the leading `v`. Same
7153        // adjacent-shape footgun pinned for `:membros :versao`
7154        // (9888b13).
7155        let s = SupervisorSpec {
7156            children: vec![child("worker", "v0.1", RestartPolicy::Permanent)],
7157            ..SupervisorSpec::default()
7158        };
7159        let err = s.validate().unwrap_err();
7160        assert!(
7161            matches!(
7162                err,
7163                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
7164                    if caixa == "worker" && versao == "v0.1"
7165            ),
7166            "got {err:?}"
7167        );
7168    }
7169
7170    #[test]
7171    fn validate_accepts_canonical_child_versao_forms() {
7172        // The Cargo-shaped requirement forms `:deps :versao` and
7173        // `:membros :versao` already accept via
7174        // `crate::parse_requirement` must pass the children gate
7175        // without re-validating at the resolver layer. Pin every leg so
7176        // a future tightening of the canonical set surfaces here as a
7177        // test failure.
7178        for form in [
7179            "^0.1",      // caret — minor-range pin (the most common shape)
7180            "~0.1.2",    // tilde — patch-range pin
7181            "0.1.0",     // exact — single-version pin
7182            "*",         // wildcard — any version (semver::VersionReq::STAR)
7183            ">=0.1, <2", // multi-range — comma-separated comparators
7184        ] {
7185            let s = SupervisorSpec {
7186                children: vec![child("worker", form, RestartPolicy::Permanent)],
7187                ..SupervisorSpec::default()
7188            };
7189            s.validate()
7190                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
7191        }
7192    }
7193
7194    #[test]
7195    fn child_versao_empty_takes_precedence_over_invalid() {
7196        // Order pin: the existing `EmptyChildVersion` diagnostic (which
7197        // doesn't try to parse) fires before the new
7198        // `ChildVersaoInvalid` parse-side diagnostic, so an empty
7199        // `:versao` keeps its narrower error message —
7200        // `parse_requirement` would also reject `""`, but the
7201        // empty-string arm is the more self-locating diagnostic for the
7202        // author. Same ordering discipline as
7203        // `membro_versao_empty_takes_precedence_over_invalid` in
7204        // aplicacao.rs.
7205        let s = SupervisorSpec {
7206            children: vec![child("worker", "", RestartPolicy::Permanent)],
7207            ..SupervisorSpec::default()
7208        };
7209        let err = s.validate().unwrap_err();
7210        assert!(
7211            matches!(err, SupervisorError::EmptyChildVersion { ref caixa } if caixa == "worker"),
7212            "got {err:?}"
7213        );
7214    }
7215
7216    #[test]
7217    fn child_versao_invalid_fires_before_duplicate_check() {
7218        // Order pin: a malformed requirement on a non-duplicate entry
7219        // surfaces *its own* diagnostic (which names the offending
7220        // `:versao` string), even when a later entry would otherwise
7221        // collapse onto an earlier name. The per-entry shape gate runs
7222        // inline before the duplicate-key insert — parallel to
7223        // `membro_versao_invalid_fires_before_duplicate_check` in
7224        // aplicacao.rs and the b0c8389 / c4213a4 ordering discipline.
7225        let s = SupervisorSpec {
7226            children: vec![
7227                child("worker", "^bad", RestartPolicy::Permanent),
7228                child("cache", "^0.1", RestartPolicy::Transient),
7229                child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
7230            ],
7231            ..SupervisorSpec::default()
7232        };
7233        let err = s.validate().unwrap_err();
7234        assert!(
7235            matches!(
7236                err,
7237                SupervisorError::ChildVersaoInvalid { ref caixa, .. } if caixa == "worker"
7238            ),
7239            "got {err:?}"
7240        );
7241    }
7242
7243    #[test]
7244    fn child_versao_invalid_diagnostic_carries_offending_versao() {
7245        // The diagnostic-shape pin: the error names the offending
7246        // `:versao` value verbatim so the author can grep their
7247        // caixa.lisp without re-running the build, and carries a
7248        // non-empty `reason` from `semver::VersionReq::parse` so the
7249        // parser's own wording flows through to the diagnostic.
7250        let s = SupervisorSpec {
7251            children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
7252            ..SupervisorSpec::default()
7253        };
7254        let err = s.validate().unwrap_err();
7255        let SupervisorError::ChildVersaoInvalid {
7256            caixa,
7257            versao,
7258            reason,
7259        } = err
7260        else {
7261            panic!("expected ChildVersaoInvalid, got other variant");
7262        };
7263        assert_eq!(caixa, "worker");
7264        assert_eq!(versao, "not-a-req");
7265        assert!(
7266            !reason.is_empty(),
7267            "ChildVersaoInvalid `reason` must carry the parser's wording verbatim"
7268        );
7269    }
7270
7271    // ── value-shape: DNS-1123 label rule on :children :caixa ──────────────
7272
7273    #[test]
7274    fn validate_rejects_child_caixa_with_uppercase() {
7275        // The canonical "I copied the Servico's display name verbatim"
7276        // typo — child caixa names are lowercase per K8s DNS-1123 label
7277        // rule. The diagnostic names the offending name and suggests the
7278        // lower-cased fix in one edit, mirroring the
7279        // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0).
7280        let s = SupervisorSpec {
7281            children: vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
7282            ..SupervisorSpec::default()
7283        };
7284        let err = s.validate().unwrap_err();
7285        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
7286            panic!("expected ChildCaixaInvalid, got other variant");
7287        };
7288        assert_eq!(caixa, "Worker");
7289        assert!(
7290            reason.contains("uppercase"),
7291            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
7292        );
7293        assert!(
7294            reason.contains("\"worker\""),
7295            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
7296        );
7297    }
7298
7299    #[test]
7300    fn validate_rejects_child_caixa_with_underscore() {
7301        // The canonical "I'm thinking of a Python module / Postgres
7302        // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
7303        // label schema. K8s rejects `metadata.name: my_worker` at
7304        // admission time with an opaque `field is invalid` (no source-
7305        // citing diagnostic). The gate moves it to caixa-build time.
7306        let s = SupervisorSpec {
7307            children: vec![child("my_worker", "^0.1", RestartPolicy::Permanent)],
7308            ..SupervisorSpec::default()
7309        };
7310        let err = s.validate().unwrap_err();
7311        assert!(
7312            matches!(
7313                err,
7314                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
7315                    if caixa == "my_worker" && reason.contains('_')
7316            ),
7317            "got {err:?}"
7318        );
7319    }
7320
7321    #[test]
7322    fn validate_rejects_child_caixa_with_dot() {
7323        // A `:children :caixa` entry is a single DNS-1123 label, not a
7324        // subdomain. The K8s Service / ComputeUnit `metadata.name` rules
7325        // forbid dots. Same shape as `rejects_membro_caixa_with_dot`
7326        // (3f9d7a0) on the peer name axis.
7327        let s = SupervisorSpec {
7328            children: vec![child("team.worker", "^0.1", RestartPolicy::Permanent)],
7329            ..SupervisorSpec::default()
7330        };
7331        let err = s.validate().unwrap_err();
7332        assert!(
7333            matches!(
7334                err,
7335                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
7336                    if caixa == "team.worker" && reason.contains('.')
7337            ),
7338            "got {err:?}"
7339        );
7340    }
7341
7342    #[test]
7343    fn validate_rejects_child_caixa_with_leading_hyphen() {
7344        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
7345        // with an alphanumeric. The K8s apiserver rejects `-worker`
7346        // outright; the renderer would emit a `metadata.name: "-worker"`
7347        // that fails admission far from the source caixa.lisp.
7348        let s = SupervisorSpec {
7349            children: vec![child("-worker", "^0.1", RestartPolicy::Permanent)],
7350            ..SupervisorSpec::default()
7351        };
7352        let err = s.validate().unwrap_err();
7353        assert!(
7354            matches!(
7355                err,
7356                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
7357                    if caixa == "-worker" && reason.contains("start and end")
7358            ),
7359            "got {err:?}"
7360        );
7361    }
7362
7363    #[test]
7364    fn validate_rejects_child_caixa_with_trailing_hyphen() {
7365        // The symmetric arm of the boundary rule. Pin separately so
7366        // both ends of the label are covered against a future relaxation
7367        // that only checks one boundary.
7368        let s = SupervisorSpec {
7369            children: vec![child("worker-", "^0.1", RestartPolicy::Permanent)],
7370            ..SupervisorSpec::default()
7371        };
7372        let err = s.validate().unwrap_err();
7373        assert!(
7374            matches!(
7375                err,
7376                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
7377                    if caixa == "worker-"
7378            ),
7379            "got {err:?}"
7380        );
7381    }
7382
7383    #[test]
7384    fn validate_rejects_child_caixa_with_unicode() {
7385        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
7386        // (`xn--…`) by the author before it reaches K8s. The byte-by-
7387        // byte ASCII validity check rejects multi-byte UTF-8 sequences
7388        // by the first byte that fails the `[a-z0-9-]` predicate.
7389        let s = SupervisorSpec {
7390            children: vec![child("café", "^0.1", RestartPolicy::Permanent)],
7391            ..SupervisorSpec::default()
7392        };
7393        let err = s.validate().unwrap_err();
7394        assert!(
7395            matches!(
7396                err,
7397                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
7398                    if caixa == "café"
7399            ),
7400            "got {err:?}"
7401        );
7402    }
7403
7404    #[test]
7405    fn validate_rejects_child_caixa_with_whitespace() {
7406        // Whitespace is the canonical "I pasted from a sketch / doc"
7407        // footgun. The apiserver rejects every `metadata.name` value
7408        // carrying whitespace; pin the gate fires at the right boundary.
7409        let s = SupervisorSpec {
7410            children: vec![child("my worker", "^0.1", RestartPolicy::Permanent)],
7411            ..SupervisorSpec::default()
7412        };
7413        let err = s.validate().unwrap_err();
7414        assert!(
7415            matches!(
7416                err,
7417                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
7418                    if caixa == "my worker"
7419            ),
7420            "got {err:?}"
7421        );
7422    }
7423
7424    #[test]
7425    fn validate_rejects_child_caixa_too_long() {
7426        // The 64-byte boundary pin. DNS-1123 / DNS-1035 cap labels at
7427        // 63 bytes; the K8s apiserver rejects every `metadata.name`
7428        // axis over the limit at admission time. The diagnostic names
7429        // both the cap and the actual length so the author can shorten
7430        // in one edit, mirroring `rejects_membro_caixa_too_long`
7431        // (3f9d7a0) and `rejects_placement_cluster_too_long` (6cbb900).
7432        let too_long = "a".repeat(64);
7433        let s = SupervisorSpec {
7434            children: vec![child(&too_long, "^0.1", RestartPolicy::Permanent)],
7435            ..SupervisorSpec::default()
7436        };
7437        let err = s.validate().unwrap_err();
7438        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
7439            panic!("expected ChildCaixaInvalid, got other variant");
7440        };
7441        assert_eq!(caixa, too_long);
7442        assert!(
7443            reason.contains("63"),
7444            "diagnostic must name the 63-byte cap (got: {reason:?})"
7445        );
7446        assert!(
7447            reason.contains("64"),
7448            "diagnostic must name the actual length (got: {reason:?})"
7449        );
7450    }
7451
7452    #[test]
7453    fn child_caixa_max_length_validates() {
7454        // The 63-byte boundary control pin — exactly-at-the-cap is
7455        // accepted, mirroring `membro_caixa_max_length_validates`
7456        // (3f9d7a0) and `placement_cluster_max_length_validates`
7457        // (6cbb900). Pinned separately so a future off-by-one tightening
7458        // surfaces here.
7459        let max_label = "a".repeat(63);
7460        let s = SupervisorSpec {
7461            children: vec![child(&max_label, "^0.1", RestartPolicy::Permanent)],
7462            ..SupervisorSpec::default()
7463        };
7464        s.validate().unwrap();
7465    }
7466
7467    #[test]
7468    fn validate_accepts_canonical_child_caixa_forms() {
7469        // The realistic shapes a supervised child's `:caixa` carries —
7470        // single-word `worker`, version-suffixed `cache-v2`, single-char
7471        // `a`, two-char `db`, digit-start `2-pool`, longer hyphen-joined
7472        // `payment-retry`, all-digit `0`. Pin every leg so a future
7473        // tightening (e.g. requiring a leading lowercase letter) surfaces
7474        // here as a test failure. Mirrors `accepts_canonical_membro_caixa_forms`
7475        // (3f9d7a0) and `accepts_canonical_placement_cluster_forms`
7476        // (6cbb900).
7477        for form in [
7478            "worker",
7479            "cache-v2",
7480            "a",
7481            "db",
7482            "2-pool",
7483            "payment-retry",
7484            "0",
7485        ] {
7486            let s = SupervisorSpec {
7487                children: vec![child(form, "^0.1", RestartPolicy::Permanent)],
7488                ..SupervisorSpec::default()
7489            };
7490            s.validate()
7491                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
7492        }
7493    }
7494
7495    #[test]
7496    fn child_caixa_empty_takes_precedence_over_invalid() {
7497        // Order pin: the existing `EmptyChildName` diagnostic (which
7498        // doesn't try to parse the DNS-1123 shape) fires before the new
7499        // `ChildCaixaInvalid` per-axis gate, so an empty `:caixa` keeps
7500        // its narrower error message — `is_dns_1123_label` would reject
7501        // the empty string too (boundary check on the first byte), but
7502        // the empty-string arm is the more self-locating diagnostic for
7503        // the author. Same ordering discipline as
7504        // `membro_caixa_empty_takes_precedence_over_invalid` in
7505        // aplicacao.rs.
7506        let s = SupervisorSpec {
7507            children: vec![child("", "^0.1", RestartPolicy::Permanent)],
7508            ..SupervisorSpec::default()
7509        };
7510        let err = s.validate().unwrap_err();
7511        assert_eq!(err, SupervisorError::EmptyChildName);
7512    }
7513
7514    #[test]
7515    fn child_caixa_invalid_fires_before_versao_check() {
7516        // Order pin: the per-axis shape gate runs inline before the
7517        // per-entry versao check, so a malformed `:caixa` on an entry
7518        // whose `:versao` would also fail surfaces the more self-
7519        // locating name-axis diagnostic first. Parallel to
7520        // `membro_versao_invalid_fires_before_duplicate_check` (9888b13)
7521        // and `placement_cluster_invalid_fires_before_duplicate_check`
7522        // (6cbb900).
7523        let s = SupervisorSpec {
7524            children: vec![child("My_Worker", "", RestartPolicy::Permanent)],
7525            ..SupervisorSpec::default()
7526        };
7527        let err = s.validate().unwrap_err();
7528        assert!(
7529            matches!(
7530                err,
7531                SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "My_Worker"
7532            ),
7533            "got {err:?}"
7534        );
7535    }
7536
7537    #[test]
7538    fn child_caixa_invalid_fires_before_duplicate_check() {
7539        // Order pin: a malformed name on a non-duplicate entry surfaces
7540        // its own diagnostic, even when a later entry would otherwise
7541        // collapse onto an earlier name. The per-entry shape gate runs
7542        // inline before the duplicate-key HashSet insert, mirroring
7543        // `placement_cluster_invalid_fires_before_duplicate_check`
7544        // (6cbb900).
7545        let s = SupervisorSpec {
7546            children: vec![
7547                child("Worker", "^0.1", RestartPolicy::Permanent),
7548                child("cache", "^0.1", RestartPolicy::Transient),
7549                child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
7550            ],
7551            ..SupervisorSpec::default()
7552        };
7553        let err = s.validate().unwrap_err();
7554        assert!(
7555            matches!(
7556                err,
7557                SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "Worker"
7558            ),
7559            "got {err:?}"
7560        );
7561    }
7562
7563    #[test]
7564    fn child_caixa_invalid_diagnostic_carries_offending_caixa() {
7565        // The diagnostic-shape pin: the error names the offending
7566        // `:caixa` verbatim plus a non-empty parser-shaped `reason` so
7567        // the author can grep their caixa.lisp without re-running the
7568        // build. Mirrors the diagnostic-shape sweep on every prior
7569        // value-shape gate (3f9d7a0, 6cbb900, c7d05ec).
7570        let s = SupervisorSpec {
7571            children: vec![child("My_Worker", "^0.1", RestartPolicy::Permanent)],
7572            ..SupervisorSpec::default()
7573        };
7574        let err = s.validate().unwrap_err();
7575        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
7576            panic!("expected ChildCaixaInvalid, got other variant");
7577        };
7578        assert_eq!(caixa, "My_Worker");
7579        assert!(
7580            !reason.is_empty(),
7581            "ChildCaixaInvalid `reason` must carry the parser's wording verbatim"
7582        );
7583    }
7584
7585    // ── value-shape: zero restart_window + duplicate child names ──────────
7586
7587    #[test]
7588    fn validate_accepts_none_restart_window() {
7589        // Omitted `:restart-window` is the "never reset" sentinel —
7590        // valid by design. Mirrors :limits axes where None = unbounded.
7591        let s = SupervisorSpec {
7592            restart_window: None,
7593            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7594            ..SupervisorSpec::default()
7595        };
7596        s.validate().unwrap();
7597    }
7598
7599    #[test]
7600    fn validate_rejects_zero_restart_window() {
7601        // Same "0 means the opposite of what you think" footgun closed
7602        // for :politicas :timeout (Envoy treats 0s as infinite) and
7603        // :limits :wall-clock (wasmtime traps before the call starts).
7604        // Erlang/OTP's MaxIntensity/Period requires Period > 0.
7605        let s = SupervisorSpec {
7606            restart_window: Some(Duration::ZERO),
7607            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7608            ..SupervisorSpec::default()
7609        };
7610        assert_eq!(
7611            s.validate().unwrap_err(),
7612            SupervisorError::RestartWindowZero
7613        );
7614    }
7615
7616    // ── value-shape: integer-ms canonical-form on :restart-window ─────────
7617    //
7618    // The fourth (and last) typed-`Duration` axis in caixa-core to get
7619    // the integer-millisecond canonical-form gate — peer with
7620    // `:limits :wall-clock` (82fc3ef), `:politicas :timeout` (a4ae535),
7621    // and `:politicas :circuit-breaker :window` (a4ae535). The serde
7622    // path is already gated at the shared codec layer (see
7623    // `restart_window_serde_rejects_fractional_seconds`); this arm
7624    // closes the programmatic-struct-literal path the codec gate can't
7625    // see.
7626
7627    #[test]
7628    fn validate_rejects_sub_millisecond_restart_window() {
7629        // The fail-before-pass-after pin: a programmatic
7630        // `Duration::from_micros(1500)` (= 1_500_000 ns) silently passed
7631        // `validate` on every pre-gate codebase, then truncated to
7632        // `as_millis() == 1` on first serialize — the shared codec
7633        // emits `"1ms"`, parses it back to `Duration::from_millis(1)` =
7634        // 1_000_000 ns, the typed `restart_window` no longer matches
7635        // its rendered form.
7636        let s = SupervisorSpec {
7637            restart_window: Some(Duration::from_micros(1500)),
7638            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7639            ..SupervisorSpec::default()
7640        };
7641        match s.validate().unwrap_err() {
7642            SupervisorError::RestartWindowNotCanonical { window } => {
7643                assert_eq!(window, Duration::from_micros(1500));
7644            }
7645            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
7646        }
7647    }
7648
7649    #[test]
7650    fn validate_rejects_one_nanosecond_restart_window() {
7651        // The far-sub-ms case: `Duration::from_nanos(1)` is non-zero
7652        // (so `RestartWindowZero` doesn't fire) but `as_millis() == 0`,
7653        // so the shared codec emits the literal `"0s"` — the next
7654        // serde round-trip would parse back to `Duration::ZERO`, which
7655        // the `RestartWindowZero` arm then rejects on re-validate. The
7656        // canonical-form gate at this layer surfaces a self-locating
7657        // diagnostic naming the offending Duration verbatim rather
7658        // than a downstream `RestartWindowZero` whose remediation
7659        // points at omitting the slot.
7660        let s = SupervisorSpec {
7661            restart_window: Some(Duration::from_nanos(1)),
7662            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7663            ..SupervisorSpec::default()
7664        };
7665        match s.validate().unwrap_err() {
7666            SupervisorError::RestartWindowNotCanonical { window } => {
7667                assert_eq!(window, Duration::from_nanos(1));
7668            }
7669            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
7670        }
7671    }
7672
7673    #[test]
7674    fn validate_rejects_nanosecond_past_canonical_boundary_restart_window() {
7675        // The 1-ns-past-1ms boundary case: a `Duration` carrying
7676        // 1_000_001 ns is structurally past the integer-ms granularity
7677        // floor — `subsec_nanos() % 1_000_000 == 1`. The codec round-
7678        // trip would truncate to `1ms` and the consumer would observe
7679        // a 1-ns drift on every emit. Same boundary the peer
7680        // `validate_rejects_nanosecond_past_canonical_boundary` test
7681        // in limits.rs pins for the `:limits :wall-clock` axis.
7682        let w = Duration::from_nanos(1_000_001);
7683        let s = SupervisorSpec {
7684            restart_window: Some(w),
7685            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7686            ..SupervisorSpec::default()
7687        };
7688        assert_eq!(
7689            s.validate().unwrap_err(),
7690            SupervisorError::RestartWindowNotCanonical { window: w }
7691        );
7692    }
7693
7694    #[test]
7695    fn validate_accepts_integer_millisecond_restart_window_values() {
7696        // The positive-control sweep: every `Duration` the shared
7697        // codec can round-trip losslessly — the canonical
7698        // `<integer>{ms,s,m,h}` set the codec's `render` / `parse`
7699        // pair emits and accepts — passes `validate` without
7700        // surfacing the new canonical-form arm. Mirrors
7701        // `validate_accepts_integer_millisecond_wall_clock_values` on
7702        // the sibling `:limits :wall-clock` axis.
7703        for w in [
7704            Duration::from_millis(1),
7705            Duration::from_millis(500),
7706            Duration::from_millis(1500),
7707            Duration::from_secs(1),
7708            Duration::from_secs(30),
7709            Duration::from_secs(60),
7710            Duration::from_secs(120),
7711            Duration::from_secs(3600),
7712        ] {
7713            let s = SupervisorSpec {
7714                restart_window: Some(w),
7715                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7716                ..SupervisorSpec::default()
7717            };
7718            s.validate()
7719                .unwrap_or_else(|e| panic!("integer-ms {w:?} must validate, got {e:?}"));
7720        }
7721    }
7722
7723    #[test]
7724    fn validate_restart_window_zero_takes_precedence_over_canonical_gate() {
7725        // Cross-arm ordering pin: `Duration::ZERO` has
7726        // `subsec_nanos() == 0` and would otherwise pass the
7727        // canonical-form arm — the zero-floor arm must fire first so
7728        // the more self-locating `RestartWindowZero` diagnostic (with
7729        // its omit-axis remediation directly named) leads. Same
7730        // posture every peer zero-then-shape gate uses
7731        // (`WallClockZero` → `WallClockNotCanonical`,
7732        // `PolicyTimeoutZero` → `PolicyTimeoutNotCanonical`,
7733        // `PolicyBreakerZeroWindow` → `PolicyBreakerWindowNotCanonical`).
7734        let s = SupervisorSpec {
7735            restart_window: Some(Duration::ZERO),
7736            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7737            ..SupervisorSpec::default()
7738        };
7739        assert_eq!(
7740            s.validate().unwrap_err(),
7741            SupervisorError::RestartWindowZero
7742        );
7743    }
7744
7745    #[test]
7746    fn restart_window_canonical_diagnostic_carries_offending_duration() {
7747        // Diagnostic-shape pin: the canonical-form arm names the
7748        // offending `Duration` verbatim so the author's grep lands on
7749        // the field's value, not a generic "duration not canonical"
7750        // message. Same shape every other typed-canonical-form arm
7751        // on this surface carries (`WallClockNotCanonical` carries
7752        // the offending `Duration` verbatim,
7753        // `PolicyTimeoutNotCanonical` carries the offending
7754        // `Duration` verbatim).
7755        let w = Duration::from_micros(500);
7756        let s = SupervisorSpec {
7757            restart_window: Some(w),
7758            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7759            ..SupervisorSpec::default()
7760        };
7761        let err = s.validate().unwrap_err();
7762        let msg = err.to_string();
7763        assert!(
7764            msg.contains("500"),
7765            "diagnostic must carry the offending magnitude verbatim (got {msg:?})"
7766        );
7767        assert!(
7768            msg.contains("sub-millisecond"),
7769            "diagnostic must name the sub-millisecond residue class (got {msg:?})"
7770        );
7771    }
7772
7773    #[test]
7774    fn restart_window_validated_value_round_trips_through_codec() {
7775        // The structural property the canonical-ms gate enforces:
7776        // every `SupervisorSpec::restart_window` past
7777        // `SupervisorSpec::validate` round-trips losslessly through
7778        // the shared duration codec (serialize → string →
7779        // deserialize → equal value). Pin this end-to-end so a future
7780        // change to either side (the validate gate's accepted
7781        // granularity, the codec's parse/render unit set) that breaks
7782        // the alignment surfaces here. Peer of
7783        // `wall_clock_validated_value_round_trips_through_codec` on
7784        // the sibling `:limits :wall-clock` axis.
7785        for w in [
7786            Duration::from_millis(1),
7787            Duration::from_millis(1500),
7788            Duration::from_secs(30),
7789            Duration::from_secs(3600),
7790        ] {
7791            let s = SupervisorSpec {
7792                restart_window: Some(w),
7793                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7794                ..SupervisorSpec::default()
7795            };
7796            s.validate().unwrap();
7797            let json = serde_json::to_string(&s).unwrap();
7798            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
7799            assert_eq!(back.restart_window, Some(w));
7800        }
7801    }
7802
7803    // ── value-shape: upper cap on :restart-window ─────────────────────────
7804    //
7805    // The fourth (and last) typed-`Duration` axis in caixa-core to get
7806    // the 1h upper cap — peer with `:limits :wall-clock` (51e0dbd),
7807    // `:politicas :timeout` (2e8ee7e), and `:politicas
7808    // :circuit-breaker :window` (379a814). Brackets the typed
7809    // `:restart-window` axis structurally: every validated value lies
7810    // in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`, integer-millisecond
7811    // granularity, closing the
7812    // rolling-window-degenerates-to-lifetime-counter footgun the prior
7813    // zero-floor-and-canonical-form-only checks left open.
7814
7815    #[test]
7816    fn validate_rejects_restart_window_above_cap() {
7817        // The fail-before-pass-after pin: 3601s = 1h + 1s is
7818        // structurally one canonical-tick past the
7819        // [`SUPERVISOR_RESTART_WINDOW_MAX`] ceiling (1h = 3600s) — an
7820        // integer-millisecond magnitude the canonical-form arm above
7821        // accepts cleanly, that the shared duration codec round-trips
7822        // losslessly as `"3601s"`, and that silently passed validate on
7823        // every pre-gate codebase because the typed slot's only checks
7824        // were the zero-floor and canonical-form arms. The runtime
7825        // substrate consuming the value (Erlang/OTP's MaxIntensity/
7826        // Period reconciler, the future wasm-operator's per-supervisor
7827        // restart-intensity counter) reaches for a `Duration` so long
7828        // no realistic restart-recovery pattern resets the counter,
7829        // far from the source caixa.lisp.
7830        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
7831        let s = SupervisorSpec {
7832            restart_window: Some(w),
7833            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7834            ..SupervisorSpec::default()
7835        };
7836        assert_eq!(
7837            s.validate().unwrap_err(),
7838            SupervisorError::RestartWindowExceedsCap { window: w }
7839        );
7840    }
7841
7842    #[test]
7843    fn validate_rejects_restart_window_one_millisecond_above_cap() {
7844        // Boundary case: exactly 1ms past the cap (the granularity the
7845        // canonical-form gate enforces). Catches a future "strictly
7846        // less than" half-measure and pins the diagnostic to name the
7847        // offending `Duration` verbatim. Peer of
7848        // `validate_rejects_wall_clock_one_millisecond_above_cap` /
7849        // `rejects_policy_timeout_one_millisecond_above_cap` /
7850        // `rejects_circuit_breaker_window_one_millisecond_above_cap`
7851        // on the sibling typed-`Duration` axes' top edges.
7852        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
7853        let s = SupervisorSpec {
7854            restart_window: Some(w),
7855            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7856            ..SupervisorSpec::default()
7857        };
7858        assert_eq!(
7859            s.validate().unwrap_err(),
7860            SupervisorError::RestartWindowExceedsCap { window: w }
7861        );
7862    }
7863
7864    #[test]
7865    fn validate_rejects_restart_window_far_above_cap() {
7866        // The "obvious authoring footgun" case: a `(:restart-window "24h")`,
7867        // `(:restart-window "7d")`, or any "I want a lifetime counter
7868        // but wrote a `<integer>h` magnitude anyway" typo — values the
7869        // canonical-form arm accepts as integer-millisecond magnitudes,
7870        // the codec round-trips losslessly through serde, but the
7871        // operator's `MaxIntensity / Period` reconciler cannot honor
7872        // as a meaningful rolling window. Until this gate landed
7873        // validate accepted them. Pin the common above-cap values (24h,
7874        // 7d, ~11.5d) so a future relaxation that drops the upper bound
7875        // surfaces here.
7876        for w in [
7877            Duration::from_secs(86_400),    // 24h
7878            Duration::from_secs(604_800),   // 7d
7879            Duration::from_secs(1_000_000), // ~11.5 days
7880        ] {
7881            let s = SupervisorSpec {
7882                restart_window: Some(w),
7883                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7884                ..SupervisorSpec::default()
7885            };
7886            assert_eq!(
7887                s.validate().unwrap_err(),
7888                SupervisorError::RestartWindowExceedsCap { window: w }
7889            );
7890        }
7891    }
7892
7893    #[test]
7894    fn validate_accepts_restart_window_at_cap() {
7895        // The boundary value — exactly [`SUPERVISOR_RESTART_WINDOW_MAX`]
7896        // (1h) — must validate. The cap is inclusive on the top edge,
7897        // matching the [`crate::LIMITS_WALL_CLOCK_MAX`] /
7898        // [`crate::POLICY_TIMEOUT_MAX`] /
7899        // [`crate::POLICY_BREAKER_WINDOW_MAX`] discipline on the sibling
7900        // capped axes. Pin the boundary explicitly so a future
7901        // off-by-one tightening (`>= SUPERVISOR_RESTART_WINDOW_MAX`
7902        // instead of `>`) surfaces here as a test failure rather than a
7903        // silent contract narrowing.
7904        let s = SupervisorSpec {
7905            restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
7906            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7907            ..SupervisorSpec::default()
7908        };
7909        s.validate()
7910            .expect("restart_window == SUPERVISOR_RESTART_WINDOW_MAX must validate");
7911    }
7912
7913    #[test]
7914    fn validate_accepts_restart_window_typical_values() {
7915        // The documented Erlang/OTP / Elixir / Riak Core / RabbitMQ
7916        // per-supervisor production-playbook band positive-control
7917        // sweep — every value Learn You Some Erlang's `{intensity, 5,
7918        // 60}` worker-supervisor `Period = 60s` default, Elixir's
7919        // `Supervisor` `max_seconds: 5` default, OTP's `supervisor`
7920        // callback module `MaxT = 5..=60` typical, Riak Core's `MaxT ∈
7921        // 10s..=300s`, and RabbitMQ broker-supervisor `MaxT = 5s`
7922        // default recommend (5s..=300s) must pass, plus a sweep
7923        // through the long-tail-flaky-pool band (5m, 15m, 30m, 1h) the
7924        // cap accepts. Mirrors `validate_accepts_wall_clock_typical_values`
7925        // on the sibling `:limits :wall-clock` axis.
7926        for w in [
7927            Duration::from_millis(1),
7928            Duration::from_millis(500),
7929            Duration::from_secs(1),
7930            Duration::from_secs(5),  // RabbitMQ broker-supervisor default
7931            Duration::from_secs(10), // Riak Core lower
7932            Duration::from_secs(30),
7933            Duration::from_secs(60),  // Learn You Some Erlang default
7934            Duration::from_secs(120), // OTP supervisor MaxT typical
7935            Duration::from_secs(300), // Riak Core upper
7936            Duration::from_secs(900), // 15m
7937            Duration::from_secs(1800),
7938            Duration::from_secs(3600), // exactly 1h, the cap
7939        ] {
7940            let s = SupervisorSpec {
7941                restart_window: Some(w),
7942                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7943                ..SupervisorSpec::default()
7944            };
7945            s.validate()
7946                .unwrap_or_else(|e| panic!("restart_window={w:?} must validate; got {e:?}"));
7947        }
7948    }
7949
7950    #[test]
7951    fn restart_window_zero_takes_precedence_over_cap() {
7952        // The cross-arm ordering pin: `Duration::ZERO` is structurally
7953        // outside both `>= 1ms` (zero-floor) and `<=
7954        // SUPERVISOR_RESTART_WINDOW_MAX` (cap), but the zero-floor
7955        // diagnostic is the more self-locating one (it directly names
7956        // the omit-axis remediation), so the validate gate must fire
7957        // on zero first. Same shape every other zero-then-cap ordering
7958        // on this surface uses (`WallClockZero` then
7959        // `WallClockExceedsCap`, `PolicyTimeoutZero` then
7960        // `PolicyTimeoutExceedsCap`, `PolicyBreakerZeroWindow` then
7961        // `PolicyBreakerWindowExceedsCap`).
7962        let s = SupervisorSpec {
7963            restart_window: Some(Duration::ZERO),
7964            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7965            ..SupervisorSpec::default()
7966        };
7967        assert_eq!(
7968            s.validate().unwrap_err(),
7969            SupervisorError::RestartWindowZero,
7970            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
7971        );
7972    }
7973
7974    #[test]
7975    fn restart_window_canonical_takes_precedence_over_cap() {
7976        // The cross-arm ordering pin: a `Duration` that is *both*
7977        // sub-millisecond (non-canonical-form) and structurally above
7978        // the cap surfaces the canonical-form diagnostic first,
7979        // because the round-trip-shape break is the more fundamental
7980        // issue (the value can't even round-trip through the codec,
7981        // so the cap diagnostic naming `1ms..=1h` would be misleading
7982        // — there's no integer-ms form of the offending value). Pin
7983        // the order so a future refactor that reorders the arms
7984        // surfaces here as a test failure rather than a silent
7985        // diagnostic regression. Peer of
7986        // `wall_clock_canonical_takes_precedence_over_cap` /
7987        // `policy_timeout_canonical_takes_precedence_over_cap`.
7988        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_nanos(1);
7989        let s = SupervisorSpec {
7990            restart_window: Some(w),
7991            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7992            ..SupervisorSpec::default()
7993        };
7994        assert_eq!(
7995            s.validate().unwrap_err(),
7996            SupervisorError::RestartWindowNotCanonical { window: w },
7997            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
7998        );
7999    }
8000
8001    #[test]
8002    fn max_restarts_cap_takes_precedence_over_restart_window_cap() {
8003        // The cross-arm ordering pin between the `:max-restarts` cap
8004        // and the sibling `:restart-window` cap. A supervisor carrying
8005        // both an over-cap `max_restarts` AND an over-cap window must
8006        // surface the `MaxRestartsExceedsCap` diagnostic first — the
8007        // cap arm is wired immediately after the zero-restart arm and
8008        // strictly before every window-axis arm (zero / canonical /
8009        // cap), so the offending value the diagnostic names matches
8010        // the order the author would discover the gates by reading
8011        // top-to-bottom through `SupervisorSpec::validate`. Pin the
8012        // order so a future refactor that reorders the arms surfaces
8013        // here as a test failure rather than a silent diagnostic
8014        // regression. Peer of
8015        // `max_restarts_cap_takes_precedence_over_restart_window_gates`
8016        // on the sibling zero / canonical window arms.
8017        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
8018        let s = SupervisorSpec {
8019            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
8020            restart_window: Some(w),
8021            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
8022            ..SupervisorSpec::default()
8023        };
8024        assert_eq!(
8025            s.validate().unwrap_err(),
8026            SupervisorError::MaxRestartsExceedsCap {
8027                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
8028            },
8029            "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
8030        );
8031    }
8032
8033    #[test]
8034    fn restart_window_cap_diagnostic_carries_offending_value() {
8035        // The diagnostic-shape pin: the offending `Duration` is
8036        // carried verbatim into the
8037        // [`SupervisorError::RestartWindowExceedsCap`] variant so the
8038        // surfaced error message names the value the author wrote,
8039        // not just the cap. Same self-locating diagnostic shape every
8040        // other typed-cap arm on this surface carries
8041        // (`WallClockExceedsCap` carries the offending `Duration`
8042        // verbatim, `PolicyTimeoutExceedsCap` carries the offending
8043        // `Duration` verbatim, `PolicyBreakerWindowExceedsCap` carries
8044        // the offending `Duration` verbatim).
8045        let w = Duration::from_secs(7200); // 2h
8046        let s = SupervisorSpec {
8047            restart_window: Some(w),
8048            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
8049            ..SupervisorSpec::default()
8050        };
8051        let err = s.validate().unwrap_err();
8052        assert!(
8053            matches!(err, SupervisorError::RestartWindowExceedsCap { window } if window == w),
8054            "got {err:?}"
8055        );
8056        let msg = err.to_string();
8057        assert!(
8058            msg.contains("7200"),
8059            ":supervisor :restart-window cap diagnostic must carry the offending value verbatim (got: {msg})"
8060        );
8061    }
8062
8063    #[test]
8064    fn supervisor_restart_window_cap_pins_canonical_value() {
8065        // The SUPERVISOR_RESTART_WINDOW_MAX constant pins the value at
8066        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
8067        // shared duration codec emits as a clean canonical string
8068        // (`"<n>h"`). Pinning the literal value here surfaces a future
8069        // drift (a relaxation to 24h, a tightening to 5m) as a
8070        // deliberate test edit, not a silent contract narrowing.
8071        //
8072        // The four typed-`Duration` caps on the validation surface
8073        // (`LIMITS_WALL_CLOCK_MAX` per-process, `POLICY_TIMEOUT_MAX`
8074        // per-edge, `POLICY_BREAKER_WINDOW_MAX` per-breaker,
8075        // `SUPERVISOR_RESTART_WINDOW_MAX` per-supervisor) share a
8076        // single uniform top edge at the codec's largest emitted unit
8077        // — a structural-property invariant the equality assertions
8078        // here enshrine, so a future drift on any of the four
8079        // surfaces as a deliberate test edit. Same shape every other
8080        // typed-cap value pin uses
8081        // (`wall_clock_cap_pins_canonical_value`,
8082        // `policy_timeout_cap_pins_canonical_value`,
8083        // `circuit_breaker_window_cap_pins_canonical_value`).
8084        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, Duration::from_secs(3600));
8085        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX.as_millis(), 3_600_000);
8086        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::LIMITS_WALL_CLOCK_MAX);
8087        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::POLICY_TIMEOUT_MAX);
8088        assert_eq!(
8089            SUPERVISOR_RESTART_WINDOW_MAX,
8090            crate::POLICY_BREAKER_WINDOW_MAX
8091        );
8092    }
8093
8094    #[test]
8095    fn restart_window_cap_value_round_trips_through_codec() {
8096        // The codec round-trip property the cap arm preserves: the
8097        // [`SUPERVISOR_RESTART_WINDOW_MAX`] constant itself round-trips
8098        // through the shared duration codec — every value at the cap
8099        // serializes to the canonical `"1h"` form and parses back
8100        // identically. Pin the round-trip so a future change to the
8101        // codec's unit set or to the cap's magnitude that breaks the
8102        // round-trip property surfaces here. Peer of
8103        // `wall_clock_cap_value_round_trips_through_codec` on the
8104        // sibling `:limits :wall-clock` axis.
8105        let s = SupervisorSpec {
8106            restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
8107            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
8108            ..SupervisorSpec::default()
8109        };
8110        s.validate().unwrap();
8111        let json = serde_json::to_string(&s).unwrap();
8112        assert!(
8113            json.contains("\"1h\""),
8114            "SUPERVISOR_RESTART_WINDOW_MAX must serialize to the canonical `\"1h\"` form (got {json})"
8115        );
8116        let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
8117        assert_eq!(back.restart_window, Some(SUPERVISOR_RESTART_WINDOW_MAX));
8118    }
8119
8120    #[test]
8121    fn validate_rejects_duplicate_child_caixa() {
8122        // Two children with the same :caixa render to two ComputeUnits
8123        // with the same name in the cluster's HelmRelease values —
8124        // one silently overwrites the other. Erlang/OTP's child_spec.id
8125        // is required-unique per supervisor; same set-not-multiset
8126        // discipline applied here as for :membros / :placement
8127        // :clusters / :entrada :paths.
8128        let s = SupervisorSpec {
8129            children: vec![
8130                child("worker", "^0.1", RestartPolicy::Permanent),
8131                child("cache", "^0.1", RestartPolicy::Transient),
8132                child("worker", "^0.2", RestartPolicy::Permanent),
8133            ],
8134            ..SupervisorSpec::default()
8135        };
8136        let err = s.validate().unwrap_err();
8137        assert!(
8138            matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "worker"),
8139            "got {err:?}"
8140        );
8141    }
8142
8143    #[test]
8144    fn validate_duplicate_child_diagnostic_names_first_collision() {
8145        // Iteration walks the :children list in declaration order —
8146        // the diagnostic names the first repeat, deterministically,
8147        // even when multiple names duplicate.
8148        let s = SupervisorSpec {
8149            children: vec![
8150                child("a", "^0.1", RestartPolicy::Permanent),
8151                child("b", "^0.1", RestartPolicy::Permanent),
8152                child("a", "^0.1", RestartPolicy::Permanent),
8153                child("b", "^0.1", RestartPolicy::Permanent),
8154            ],
8155            ..SupervisorSpec::default()
8156        };
8157        let err = s.validate().unwrap_err();
8158        assert!(
8159            matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "a"),
8160            "got {err:?}"
8161        );
8162    }
8163
8164    // ── self-supervision cross-slot gate ──────────────────────────
8165
8166    #[test]
8167    fn validate_no_self_supervision_rejects_self_referential_child() {
8168        // A supervisor whose `:children` lists its own `:nome` is a
8169        // one-node reconciliation cycle — rejected, naming the parent.
8170        let children = vec![
8171            child("worker", "^0.1", RestartPolicy::Permanent),
8172            child("orquestra", "^0.1", RestartPolicy::Permanent),
8173        ];
8174        let err = validate_no_self_supervision(&children, "orquestra").unwrap_err();
8175        assert!(
8176            matches!(err, SupervisorError::ChildSupervisesSelf { ref caixa } if caixa == "orquestra"),
8177            "got {err:?}"
8178        );
8179    }
8180
8181    #[test]
8182    fn validate_no_self_supervision_accepts_distinct_children() {
8183        // Positive control: distinct child names (including a child that
8184        // is itself a supervisor — nested trees are valid OTP) pass.
8185        let children = vec![
8186            child("worker", "^0.1", RestartPolicy::Permanent),
8187            child("sub-tree", "^0.1", RestartPolicy::Permanent),
8188        ];
8189        validate_no_self_supervision(&children, "orquestra").unwrap();
8190    }
8191
8192    #[test]
8193    fn validate_no_self_supervision_empty_children_is_ok() {
8194        // SimpleOneForOne / no-static-children supervisors have nothing
8195        // to self-reference — the gate is vacuously satisfied.
8196        validate_no_self_supervision(&[], "orquestra").unwrap();
8197    }
8198
8199    #[test]
8200    fn validate_simple_one_for_one_skips_uniqueness_check() {
8201        // SimpleOneForOne supervisors carry no static children — the
8202        // duplicate-child loop never runs. A zero-window declaration
8203        // on a SimpleOneForOne supervisor still trips the window check
8204        // (window applies to dynamic children too).
8205        let s = SupervisorSpec {
8206            estrategia: RestartStrategy::SimpleOneForOne,
8207            restart_window: None,
8208            children: vec![],
8209            ..SupervisorSpec::default()
8210        };
8211        s.validate().unwrap();
8212        let s_zero = SupervisorSpec {
8213            estrategia: RestartStrategy::SimpleOneForOne,
8214            restart_window: Some(Duration::ZERO),
8215            children: vec![],
8216            ..SupervisorSpec::default()
8217        };
8218        assert_eq!(
8219            s_zero.validate().unwrap_err(),
8220            SupervisorError::RestartWindowZero
8221        );
8222    }
8223
8224    #[test]
8225    fn validate_zero_window_runs_after_max_restarts_check() {
8226        // Pin the order: max_restarts == 0 fires before
8227        // restart_window == 0s, so an author with both wrong sees the
8228        // counter-axis diagnostic first (matches the order in the
8229        // struct and in the doc comment).
8230        let s = SupervisorSpec {
8231            max_restarts: 0,
8232            restart_window: Some(Duration::ZERO),
8233            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
8234            ..SupervisorSpec::default()
8235        };
8236        assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
8237    }
8238
8239    #[test]
8240    fn round_trip_all_strategies() {
8241        for &strat in RestartStrategy::ALL {
8242            // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
8243            // shape partition through the [`gen_platform::IsVariant`]
8244            // derive-generated [`RestartStrategy::is_simple_one_for_one`]
8245            // predicate rather than the raw
8246            // `matches!(strat, RestartStrategy::SimpleOneForOne)`
8247            // open-coded pattern-match — same closed-set-typed-enum
8248            // arm-discriminator dispatch discipline the sibling
8249            // [`crate::upgrade::UpgradeInstruction::is_restart`] convergence
8250            // (915a934) extended onto its two paired positive / negated
8251            // `matches!` filter sites, and the sibling
8252            // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
8253            // predicate convergence (766ec63) extended onto the M3 mesh-
8254            // slot per-`:placement` distribution-strategy `matches!`
8255            // discriminator axis. See the sibling
8256            // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
8257            // fixture and the peer `manifest::tests::
8258            // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
8259            // fixture — all three sites (the last unlifted
8260            // `matches!`-based arm-discriminator axis on the OTP-shape
8261            // supervisor sibling-restart-strategy closed-set typed enum,
8262            // acknowledged in 915a934's Prior-commits footnote as the
8263            // outstanding follow-up) now consult one typed dispatch on
8264            // the substrate primitive.
8265            let s = SupervisorSpec {
8266                estrategia: strat,
8267                children: if strat.is_simple_one_for_one() {
8268                    vec![]
8269                } else {
8270                    vec![child("w", "^0.1", RestartPolicy::Permanent)]
8271                },
8272                ..SupervisorSpec::default()
8273            };
8274            let json = serde_json::to_string(&s).unwrap();
8275            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
8276            assert_eq!(s, back);
8277        }
8278    }
8279
8280    #[test]
8281    fn round_trip_all_restart_policies() {
8282        for policy in [
8283            RestartPolicy::Permanent,
8284            RestartPolicy::Temporary,
8285            RestartPolicy::Transient,
8286        ] {
8287            let c = child("w", "^0.1", policy);
8288            let json = serde_json::to_string(&c).unwrap();
8289            let back: ChildSpec = serde_json::from_str(&json).unwrap();
8290            assert_eq!(c, back);
8291        }
8292    }
8293
8294    #[test]
8295    fn restart_strategy_is_simple_one_for_one_predicate_partitions_the_arm_set() {
8296        // The fail-before-pass-after pin on the `gen_platform::IsVariant`
8297        // derive's [`RestartStrategy::is_simple_one_for_one`] arm-
8298        // discriminator predicate: [`RestartStrategy::SimpleOneForOne`]
8299        // is the only variant that satisfies `.is_simple_one_for_one()`;
8300        // every static-children-bearing arm (`OneForOne` / `OneForAll`
8301        // / `RestForOne`) returns `false`. This pin makes the partition
8302        // invariant load-bearing at caixa-core test time so a future
8303        // derive regression (a hole that returns `false` for
8304        // `SimpleOneForOne` too, or a byte-collision that flips a second
8305        // variant to `true`) trips here rather than laundering the arm
8306        // at the three test-fixture builder sites (a hole flips the
8307        // `SimpleOneForOne` fixture to carry a non-empty children list
8308        // and the subsequent `SupervisorSpec::validate` would refuse the
8309        // fixture with [`SupervisorError::SimpleOneForOneWithStaticChildren`];
8310        // a collision flips a peer strategy's fixture to carry an empty
8311        // children list and the subsequent `validate` would refuse with
8312        // [`SupervisorError::NoChildren`] — either way, the pin fires
8313        // here, at the derive site, rather than at the fixture-refusal
8314        // site far away). Peer of the sibling
8315        // [`crate::upgrade::tests::upgrade_instruction_is_restart_predicate_partitions_the_arm_set`]
8316        // (915a934) pin on the M2 OTP-appup axis and the sibling
8317        // [`crate::kind::tests::caixa_kind_is_variant_predicates_partition_the_arm_set`]
8318        // pin on the M0 `:kind` axis.
8319        let cases: &[(RestartStrategy, bool)] = &[
8320            (RestartStrategy::OneForOne, false),
8321            (RestartStrategy::OneForAll, false),
8322            (RestartStrategy::RestForOne, false),
8323            (RestartStrategy::SimpleOneForOne, true),
8324        ];
8325        for (variant, expected) in cases {
8326            assert_eq!(
8327                variant.is_simple_one_for_one(),
8328                *expected,
8329                "RestartStrategy::{variant:?}.is_simple_one_for_one() must \
8330                 return {expected} (partition invariant on the \
8331                 IsVariant-derived arm-discriminator predicate — every \
8332                 test-fixture site that partitions the `:children` slot \
8333                 shape on `SimpleOneForOne ↔ non-SimpleOneForOne` keys \
8334                 off this typed dispatch, so a derive regression must \
8335                 surface here rather than at the fixture-refusal site)"
8336            );
8337        }
8338    }
8339
8340    #[test]
8341    fn restart_strategy_fixture_partition_routes_through_is_simple_one_for_one_predicate() {
8342        // Byte-identity pin on the `SimpleOneForOne ↔ non-SimpleOneForOne`
8343        // fixture-shape partition against the pre-lift
8344        // `matches!(strat, RestartStrategy::SimpleOneForOne)` open-coded
8345        // pattern-match every test-fixture builder site previously
8346        // coupled to inline. Asserts the two projections agree byte-for-
8347        // byte on every arm of the enum, so a future derive regression
8348        // that flipped either predicate's arm-set would surface here at
8349        // caixa-core test time rather than at the three fixture-builder
8350        // sites (`supervisor::tests::round_trip_all_strategies`,
8351        // `supervisor::tests::supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`,
8352        // `manifest::tests::caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`)
8353        // far from the derive site. Same peer-shape byte-identity pin
8354        // every sibling `IsVariant`-derive-routed convergence carries on
8355        // the substrate's closed-set typed-enum surface (peer of
8356        // [`crate::upgrade::tests::validate_restart_exclusive_routes_through_is_restart_predicate`]
8357        // on the M2 OTP-appup axis).
8358        for &strat in RestartStrategy::ALL {
8359            let via_predicate = strat.is_simple_one_for_one();
8360            let via_matches = matches!(strat, RestartStrategy::SimpleOneForOne);
8361            assert_eq!(
8362                via_predicate, via_matches,
8363                "RestartStrategy::{strat:?}: is_simple_one_for_one() must \
8364                 byte-equal matches!(_, RestartStrategy::SimpleOneForOne) — \
8365                 the pre-lift open-coded pattern and the \
8366                 IsVariant-derived predicate are the same axis, \
8367                 one typed dispatch"
8368            );
8369        }
8370    }
8371
8372    #[test]
8373    fn duration_codec_round_trip_canonical_units() {
8374        // Note the canonical-form rule: durations serialize to the
8375        // *largest* unit that divides cleanly, so 60s ↔ "1m" and not
8376        // "60s" — but the round-trip preserves the underlying Duration.
8377        let cases = [
8378            ("30s", Duration::from_secs(30)),
8379            ("5m", Duration::from_secs(300)),
8380            ("1h", Duration::from_secs(3600)),
8381            ("500ms", Duration::from_millis(500)),
8382        ];
8383        for (lit, dur) in cases {
8384            let s = SupervisorSpec {
8385                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
8386                restart_window: Some(dur),
8387                ..SupervisorSpec::default()
8388            };
8389            let json = serde_json::to_string(&s).unwrap();
8390            assert!(
8391                json.contains(&format!("\"{lit}\"")),
8392                "expected \"{lit}\" in {json}"
8393            );
8394            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
8395            assert_eq!(back.restart_window, Some(dur));
8396        }
8397    }
8398
8399    #[test]
8400    fn duration_canonicalizes_to_largest_unit() {
8401        // 60 seconds → "1m" (largest cleanly-divisible unit), but the
8402        // typed Duration still equals 60s on the way back.
8403        let s = SupervisorSpec {
8404            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
8405            restart_window: Some(Duration::from_secs(60)),
8406            ..SupervisorSpec::default()
8407        };
8408        let json = serde_json::to_string(&s).unwrap();
8409        assert!(json.contains("\"1m\""), "{json}");
8410        let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
8411        assert_eq!(back.restart_window, Some(Duration::from_secs(60)));
8412    }
8413
8414    #[test]
8415    fn three_child_one_for_one_validates() {
8416        let s = SupervisorSpec {
8417            estrategia: RestartStrategy::OneForOne,
8418            max_restarts: 5,
8419            restart_window: Some(Duration::from_secs(60)),
8420            children: vec![
8421                child("worker", "^0.1", RestartPolicy::Permanent),
8422                child("cache", "^0.1", RestartPolicy::Transient),
8423                child("scratch", "^0.1", RestartPolicy::Temporary),
8424            ],
8425        };
8426        s.validate().unwrap();
8427    }
8428
8429    #[test]
8430    fn json_uses_pascal_case_for_strategy_and_policy() {
8431        // Variant names are PascalCase by default in serde, matching
8432        // tatara-lisp's enum convention (`:estrategia OneForOne`).
8433        let c = child("w", "^0.1", RestartPolicy::Permanent);
8434        let json = serde_json::to_string(&c).unwrap();
8435        assert!(json.contains("\"Permanent\""));
8436        assert!(!json.contains("\"permanent\""));
8437
8438        let s = SupervisorSpec {
8439            estrategia: RestartStrategy::OneForOne,
8440            children: vec![c],
8441            ..SupervisorSpec::default()
8442        };
8443        let json = serde_json::to_string(&s).unwrap();
8444        assert!(json.contains("\"estrategia\":\"OneForOne\""));
8445    }
8446
8447    // ── shared duration codec: integer-magnitude canonical-form gate ──
8448    //
8449    // The gate lifts the discipline `crate::limits::parse_duration`
8450    // (818dd38) carries on the peer `:limits :wall-clock` codec onto
8451    // the shared codec backing the remaining three typed-duration
8452    // slots: `:supervisor :restart-window`, `:politicas :timeout`, and
8453    // `:politicas :circuit-breaker :window`. Every magnitude `render`
8454    // emits is a non-negative integer with no decimal point and no
8455    // leading sign, so the codec's accepted set must match for
8456    // serialize/deserialize to round-trip without canonical-form
8457    // drift.
8458
8459    #[test]
8460    fn parse_accepts_integer_canonical_units() {
8461        // Pin the happy-path: every canonical author shape `render`
8462        // ever emits parses to the same `Duration` value, so the
8463        // codec's accepted set is at least a superset of its emitted
8464        // set on the canonical-unit axis.
8465        for (lit, dur) in [
8466            ("30s", Duration::from_secs(30)),
8467            ("500ms", Duration::from_millis(500)),
8468            ("2m", Duration::from_secs(120)),
8469            ("1h", Duration::from_secs(3600)),
8470            ("0s", Duration::ZERO),
8471        ] {
8472            assert_eq!(
8473                duration_codec::parse(lit).unwrap(),
8474                dur,
8475                "parse({lit:?}) should be {dur:?}"
8476            );
8477        }
8478    }
8479
8480    #[test]
8481    fn parse_accepts_bare_integer_as_seconds() {
8482        // The `"s" | ""` arm: a bare integer with no unit is read as
8483        // seconds. Pin this so the unit-empty form keeps parsing (it
8484        // renders to `"<n>s"` on serialize — that's a unit-choice
8485        // drift the integer-magnitude gate does NOT close, matching
8486        // the `parse_byte_size` `"1024"` → `"1KiB"` scope decision in
8487        // the peer `:limits :memory` codec).
8488        assert_eq!(
8489            duration_codec::parse("30").unwrap(),
8490            Duration::from_secs(30)
8491        );
8492    }
8493
8494    #[test]
8495    fn parse_rejects_fractional_seconds_with_canonical_form_diagnostic() {
8496        // `"1.5s"` parses as f64 to 1.5 → renders back as `"1500ms"`
8497        // on first serialize — DRIFT. The integer-magnitude gate names
8498        // the offending `"1.5"` verbatim and points at the canonical
8499        // remediation `"1500ms"`.
8500        let err = duration_codec::parse("1.5s").unwrap_err();
8501        assert!(err.contains("\"1.5\""), "missing magnitude in {err:?}");
8502        assert!(
8503            err.contains("not a non-negative integer"),
8504            "missing canonical-form reason in {err:?}"
8505        );
8506        assert!(
8507            err.contains("\"1500ms\""),
8508            "missing canonical-form remediation in {err:?}"
8509        );
8510    }
8511
8512    #[test]
8513    fn parse_rejects_decimal_shaped_integer_seconds() {
8514        // `"1.0s"` is the trickiest drift class: numerically `1.0s` is
8515        // `1s` exactly, so the round-trip looks correct — but the
8516        // emitted canonical form is `"1s"`, not `"1.0s"`. Gate the
8517        // decimal-shape-with-integer-value form so author intent is
8518        // never silently rewritten.
8519        let err = duration_codec::parse("1.0s").unwrap_err();
8520        assert!(err.contains("\"1.0\""), "missing magnitude in {err:?}");
8521        assert!(
8522            err.contains("not a non-negative integer"),
8523            "missing canonical-form reason in {err:?}"
8524        );
8525    }
8526
8527    #[test]
8528    fn parse_rejects_half_unit_minute() {
8529        // `"0.5m"` is the unit-fraction footgun — author writes a
8530        // human-readable half-minute, serde silently rewrites to
8531        // `"30s"` on next emit. The gate names the offending
8532        // magnitude `"0.5"` and points at the integer-in-smaller-unit
8533        // form.
8534        let err = duration_codec::parse("0.5m").unwrap_err();
8535        assert!(err.contains("\"0.5\""), "missing magnitude in {err:?}");
8536        assert!(
8537            err.contains("\"30s\""),
8538            "missing canonical-form remediation in {err:?}"
8539        );
8540    }
8541
8542    #[test]
8543    fn parse_rejects_leading_plus_sign() {
8544        // `u64::from_str` rejects `"+30"` but `f64::from_str` accepts
8545        // it as `30.0` — the prior parser used f64 so `"+30s"` parsed
8546        // cleanly to 30s and round-tripped to `"30s"` on next emit
8547        // (DRIFT). The digit-only gate closes the leading-sign class
8548        // first; the diagnostic names `"+30"` verbatim.
8549        let err = duration_codec::parse("+30s").unwrap_err();
8550        assert!(err.contains("\"+30\""), "missing magnitude in {err:?}");
8551        assert!(
8552            err.contains("not a non-negative integer"),
8553            "missing canonical-form reason in {err:?}"
8554        );
8555    }
8556
8557    #[test]
8558    fn parse_rejects_leading_minus_sign() {
8559        // The former `num < 0.0` arm: `"-30s"` parsed as f64 to -30,
8560        // rejected with `"negative duration in \"-30s\""`. Under the
8561        // integer-magnitude gate the diagnostic is unified — `-30` is
8562        // non-digit-only, f64-numeric, and surfaces with the canonical-
8563        // form reason (no leading `+` / `-` sign) naming the offending
8564        // `"-30"` verbatim. Same diagnostic shape as every other
8565        // rejected non-integer magnitude.
8566        let err = duration_codec::parse("-30s").unwrap_err();
8567        assert!(err.contains("\"-30\""), "missing magnitude in {err:?}");
8568        assert!(
8569            err.contains("not a non-negative integer"),
8570            "missing canonical-form reason in {err:?}"
8571        );
8572    }
8573
8574    #[test]
8575    fn parse_garbage_still_falls_through_to_bad_magnitude() {
8576        // Non-digit-only AND non-numeric (`"--1s"`, `"abc"`) falls
8577        // through to the narrower "bad duration magnitude" arm — the
8578        // canonical-form diagnostic is reserved for the parser-shape
8579        // footgun case, not the "not a number at all" case. Same
8580        // shape `parse_byte_size`'s `BadByteMagnitude` arm carries on
8581        // the peer `:limits :memory` codec.
8582        let err = duration_codec::parse("--1s").unwrap_err();
8583        assert!(
8584            err.contains("bad duration magnitude"),
8585            "expected bad-magnitude wording in {err:?}"
8586        );
8587    }
8588
8589    #[test]
8590    fn parse_digit_only_magnitude_carries_zero_f64_drift() {
8591        // The accepted set is now closed under `u64`-exact integer
8592        // arithmetic: `"500ms"` → `Duration::from_millis(500)` exactly,
8593        // `"3600s"` → `Duration::from_secs(3600)` exactly, `"1h"` →
8594        // `Duration::from_secs(3600)` exactly, no f64 mantissa drift
8595        // possible. Pin the integer-exact arms across the four unit
8596        // suffixes so a future refactor that reaches back for f64
8597        // (`from_secs_f64`, `mul_f64`) surfaces here.
8598        assert_eq!(
8599            duration_codec::parse("3600s").unwrap(),
8600            Duration::from_secs(3600)
8601        );
8602        assert_eq!(
8603            duration_codec::parse("60m").unwrap(),
8604            Duration::from_secs(3600)
8605        );
8606        assert_eq!(
8607            duration_codec::parse("1h").unwrap(),
8608            Duration::from_secs(3600)
8609        );
8610        assert_eq!(
8611            duration_codec::parse("999ms").unwrap(),
8612            Duration::from_millis(999)
8613        );
8614    }
8615
8616    #[test]
8617    fn restart_window_serde_rejects_fractional_seconds() {
8618        // The shared codec backs `SupervisorSpec::restart_window`
8619        // (`with = "duration_codec"`) — so the gate applies on serde
8620        // deserialize for the typed Supervisor slot. A
8621        // `{"restartWindow":"1.5s"}` payload that previously round-
8622        // tripped to a different canonical string on next serialize
8623        // is now refused at deserialize with the integer-magnitude
8624        // diagnostic.
8625        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
8626            "restartWindow":"1.5s",
8627            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
8628        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
8629        let msg = err.to_string();
8630        assert!(
8631            msg.contains("not a non-negative integer"),
8632            "expected integer-magnitude diagnostic in {msg:?}"
8633        );
8634        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
8635    }
8636
8637    #[test]
8638    fn restart_window_serde_rejects_leading_plus() {
8639        // The `u64::from_str` leading-`+` permissiveness gap that
8640        // motivated the digit-only gate (the `f64`-side accepted
8641        // `"+30"`, the prior parser silently round-tripped to `"30s"`)
8642        // is now closed on the shared codec — surfaces as a structured
8643        // diagnostic at the serde layer for every typed-duration slot.
8644        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
8645            "restartWindow":"+30s",
8646            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
8647        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
8648        let msg = err.to_string();
8649        assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
8650        assert!(
8651            msg.contains("not a non-negative integer"),
8652            "missing canonical-form reason in {msg:?}"
8653        );
8654    }
8655
8656    #[test]
8657    fn parse_rejects_leading_zero_magnitude() {
8658        // `"030s"` is digit-only, so the existing non-digit-only / sign
8659        // / fractional arm doesn't catch it — `u64::from_str("030")`
8660        // returns `Ok(30)`, so before this gate `"030s"` parsed to
8661        // `Duration::from_secs(30)` and round-tripped through `render`
8662        // to `"30s"` — a *different* canonical string on the next emit,
8663        // breaking the THEORY.md Part V render-determinism contract
8664        // exactly the way `"+30s"` did before the leading-`+` arm
8665        // landed. Peer with the `rate_limit_codec` leading-zero arm
8666        // (4f46830) on the same canonical-form-drift axis.
8667        let err = duration_codec::parse("030s").unwrap_err();
8668        assert!(
8669            err.contains("non-canonical leading zero"),
8670            "expected leading-zero diagnostic in {err:?}"
8671        );
8672        assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
8673        assert!(
8674            err.contains("\"30s\""),
8675            "missing canonical-form remediation in {err:?}"
8676        );
8677        assert!(
8678            err.contains("THEORY.md"),
8679            "missing render-determinism citation in {err:?}"
8680        );
8681    }
8682
8683    #[test]
8684    fn parse_rejects_multi_digit_zero_magnitude() {
8685        // `"00s"` and `"00ms"` are the all-zero leading-zero footgun —
8686        // digit-only, parse losslessly to `Duration::ZERO`, but render
8687        // back to `"0s"` (the single-byte canonical form) on the next
8688        // emit. The leading-zero arm refuses the drift class at the
8689        // codec layer; the semantic-zero gate downstream
8690        // (`SupervisorError::ZeroRestartWindow`, etc.) would refuse
8691        // the single-byte canonical form `"0s"` separately on the
8692        // typed-validate layer.
8693        let err = duration_codec::parse("00s").unwrap_err();
8694        assert!(
8695            err.contains("non-canonical leading zero"),
8696            "expected leading-zero diagnostic in {err:?}"
8697        );
8698        assert!(err.contains("\"00\""), "missing magnitude in {err:?}");
8699    }
8700
8701    #[test]
8702    fn parse_rejects_leading_zero_per_hour_window() {
8703        // `"01h"` is the per-hour-window footgun — multi-byte magnitude
8704        // starting with `0`, parses losslessly to `Duration::from_secs(3600)`,
8705        // renders to `"1h"` (DRIFT). The arm is unit-agnostic: every
8706        // canonical unit suffix the codec accepts (`ms` / `s` / `m` /
8707        // `h` / bare-integer-as-seconds) inherits the same gate.
8708        let err = duration_codec::parse("01h").unwrap_err();
8709        assert!(
8710            err.contains("non-canonical leading zero"),
8711            "expected leading-zero diagnostic in {err:?}"
8712        );
8713        assert!(err.contains("\"01\""), "missing magnitude in {err:?}");
8714    }
8715
8716    #[test]
8717    fn parse_rejects_leading_zero_bare_integer_as_seconds() {
8718        // The `parse_accepts_bare_integer_as_seconds` happy-path
8719        // (`"30"` → 30s) inherits the leading-zero arm: `"030"` is
8720        // multi-byte starts-with-`0`, parses losslessly to
8721        // `Duration::from_secs(30)`, renders to `"30s"` (DRIFT). The
8722        // bare-integer surface accepts permissive unit-empty
8723        // shorthand but still must reject leading-zero padding.
8724        let err = duration_codec::parse("030").unwrap_err();
8725        assert!(
8726            err.contains("non-canonical leading zero"),
8727            "expected leading-zero diagnostic in {err:?}"
8728        );
8729        assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
8730    }
8731
8732    #[test]
8733    fn parse_accepts_single_zero_magnitude_at_codec_layer() {
8734        // The codec-layer / typed-validate-layer boundary: `"0s"` /
8735        // `"0ms"` / `"0"` are the single-byte canonical-zero forms —
8736        // each round-trips losslessly through `render`
8737        // (`render(Duration::ZERO)` → `"0s"`), so the codec layer
8738        // accepts them. The downstream semantic-zero gates
8739        // (`SupervisorError::ZeroRestartWindow`,
8740        // `AplicacaoError::PolicyTimeoutZero`,
8741        // `AplicacaoError::PolicyCircuitBreakerWindowZero`) refuse
8742        // zero-magnitude authoring at the typed-validate layer above,
8743        // peer with the `rate_limit_codec` codec-layer / typed-
8744        // validate-layer partition for `"0/s"`.
8745        assert_eq!(duration_codec::parse("0s").unwrap(), Duration::ZERO);
8746        assert_eq!(duration_codec::parse("0ms").unwrap(), Duration::ZERO);
8747        assert_eq!(duration_codec::parse("0").unwrap(), Duration::ZERO);
8748    }
8749
8750    #[test]
8751    fn parse_accepts_canonical_magnitude_with_leading_one() {
8752        // The complementary boundary: a future tightening cannot
8753        // drift into rejecting valid canonical magnitudes that
8754        // happen to start with `1` (or any digit `[1-9]`). Pin
8755        // every canonical-unit suffix so the leading-zero arm
8756        // remains strictly narrower than the digit-only arm.
8757        assert_eq!(
8758            duration_codec::parse("100ms").unwrap(),
8759            Duration::from_millis(100)
8760        );
8761        assert_eq!(
8762            duration_codec::parse("100s").unwrap(),
8763            Duration::from_secs(100)
8764        );
8765        assert_eq!(
8766            duration_codec::parse("10m").unwrap(),
8767            Duration::from_secs(600)
8768        );
8769        assert_eq!(
8770            duration_codec::parse("10h").unwrap(),
8771            Duration::from_secs(36_000)
8772        );
8773    }
8774
8775    #[test]
8776    fn restart_window_serde_rejects_leading_zero() {
8777        // The shared codec backs `SupervisorSpec::restart_window`
8778        // (`with = "duration_codec"`) — so the leading-zero arm
8779        // applies on serde deserialize for the typed Supervisor slot.
8780        // A `{"restartWindow":"030s"}` payload that previously round-
8781        // tripped to a different canonical string on next serialize
8782        // is now refused at deserialize with the leading-zero
8783        // diagnostic. Peer with `restart_window_serde_rejects_leading_plus`
8784        // / `restart_window_serde_rejects_fractional_seconds` on the
8785        // same canonical-form-drift axis.
8786        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
8787            "restartWindow":"030s",
8788            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
8789        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
8790        let msg = err.to_string();
8791        assert!(
8792            msg.contains("non-canonical leading zero"),
8793            "expected leading-zero diagnostic in {msg:?}"
8794        );
8795        assert!(msg.contains("\"030\""), "missing magnitude in {msg:?}");
8796    }
8797
8798    #[test]
8799    fn parse_rejects_leading_whitespace() {
8800        // `" 30s"` — the canonical paste-from-aligned-doc /
8801        // paste-from-YAML-quoted-plain-scalar footgun. Before this
8802        // gate the top-level `s.trim()` at parse entry silently ate
8803        // the leading space and parsed the value to
8804        // `Duration::from_secs(30)`, which then round-tripped through
8805        // `render` to `"30s"` (a *different* canonical string on the
8806        // next emit) — the exact canonical-form-drift class the
8807        // leading-`+` / leading-zero arms already close, extended
8808        // to the whitespace-byte class. Peer with the sibling
8809        // `rate_limit_codec` whitespace-rejection arm (1ad7755) on
8810        // the M3 `:politicas` axis.
8811        let err = duration_codec::parse(" 30s").unwrap_err();
8812        assert!(
8813            err.contains("contains whitespace byte"),
8814            "expected whitespace diagnostic in {err:?}"
8815        );
8816        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
8817        assert!(
8818            err.contains("THEORY.md"),
8819            "missing render-determinism contract citation in {err:?}"
8820        );
8821    }
8822
8823    #[test]
8824    fn parse_rejects_trailing_whitespace() {
8825        // `"30s "` — the canonical shell-history / trailing-space
8826        // paste footgun. Before this gate the top-level `s.trim()`
8827        // silently ate the trailing space and parsed to
8828        // `Duration::from_secs(30)`, round-tripping to `"30s"` on the
8829        // next emit — same canonical-form drift as the leading-space
8830        // sibling, closed on the same whitespace-byte arm.
8831        let err = duration_codec::parse("30s ").unwrap_err();
8832        assert!(
8833            err.contains("contains whitespace byte"),
8834            "expected whitespace diagnostic in {err:?}"
8835        );
8836        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
8837    }
8838
8839    #[test]
8840    fn parse_rejects_internal_whitespace_between_magnitude_and_unit() {
8841        // `"30 s"` — the canonical typographically-spaced author
8842        // shape (the same idiom every prose reference to a duration
8843        // renders as, mistakenly retained when the value is pasted
8844        // into a codec-shaped slot). Before this gate the per-part
8845        // `num_part.trim()` / `unit.trim()` calls silently ate the
8846        // whitespace between the magnitude and the unit and parsed
8847        // the value to `Duration::from_secs(30)`, round-tripping to
8848        // `"30s"` — the codec's *internal* whitespace-tolerance
8849        // vector, orthogonal to the leading / trailing surface but
8850        // the same canonical-form-drift class. Pins the arm as
8851        // strictly stronger than the pre-existing top-level
8852        // `s.trim()` behavior: it fires on whitespace anywhere in
8853        // the value, not just at the string boundary.
8854        let err = duration_codec::parse("30 s").unwrap_err();
8855        assert!(
8856            err.contains("contains whitespace byte"),
8857            "expected whitespace diagnostic in {err:?}"
8858        );
8859        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
8860    }
8861
8862    #[test]
8863    fn parse_rejects_tab_byte() {
8864        // `"\t30s"` — the canonical paste-from-indented-doc /
8865        // paste-from-YAML-block-scalar footgun where a tab byte leads
8866        // the magnitude. Pins that the gate covers tab (`0x09`) as
8867        // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
8868        // members and both would be silently swallowed by `s.trim()`
8869        // pre-gate. The `is_ascii_whitespace` coverage extends beyond
8870        // space alone to the full ASCII-whitespace set (space `0x20`,
8871        // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
8872        // the tab arm as a representative of the non-space members.
8873        let err = duration_codec::parse("\t30s").unwrap_err();
8874        assert!(
8875            err.contains("contains whitespace byte"),
8876            "expected whitespace diagnostic in {err:?}"
8877        );
8878        assert!(
8879            err.contains("0x09"),
8880            "missing offending tab byte in {err:?}"
8881        );
8882    }
8883
8884    #[test]
8885    fn restart_window_serde_rejects_whitespace() {
8886        // The shared codec backs `SupervisorSpec::restart_window`
8887        // (`with = "duration_codec"`) — so the whitespace arm
8888        // applies on serde deserialize for the typed Supervisor slot.
8889        // A `{"restartWindow":" 30s"}` payload that previously round-
8890        // tripped to a different canonical string on next serialize
8891        // is now refused at deserialize with the whitespace-byte
8892        // diagnostic. Peer with `restart_window_serde_rejects_leading_zero`
8893        // / `restart_window_serde_rejects_leading_plus` /
8894        // `restart_window_serde_rejects_fractional_seconds` on the
8895        // same canonical-form-drift axis.
8896        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
8897            "restartWindow":" 30s",
8898            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
8899        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
8900        let msg = err.to_string();
8901        assert!(
8902            msg.contains("contains whitespace byte"),
8903            "expected whitespace diagnostic in {msg:?}"
8904        );
8905        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
8906    }
8907
8908    // ── canonical-form: non-ASCII Unicode `White_Space` duration gate ─────
8909    //
8910    // Successor to the ASCII-whitespace arm (a7ae622) on the shared
8911    // duration codec — closes the strictly-complementary class the
8912    // byte-scan cannot see, through the lifted
8913    // [`crate::render::find_non_ascii_whitespace_char`] predicate.
8914    // Applies to `:supervisor :restart-window`, `:politicas :timeout`,
8915    // and `:politicas :circuit-breaker :window` simultaneously via
8916    // this shared codec.
8917
8918    #[test]
8919    fn duration_codec_parse_rejects_leading_nbsp() {
8920        // NBSP prefix — the strictly-complementary drift class the
8921        // ASCII byte-scan cannot see. `str::trim` strips it silently
8922        // and the value drifts to `"30s"` on next serialize.
8923        let err = duration_codec::parse("\u{00A0}30s").unwrap_err();
8924        assert!(
8925            err.contains("non-ASCII Unicode whitespace character"),
8926            "expected non-ASCII whitespace diagnostic in {err:?}"
8927        );
8928        assert!(err.contains("U+00A0"), "missing codepoint in {err:?}");
8929    }
8930
8931    #[test]
8932    fn duration_codec_parse_rejects_trailing_line_separator() {
8933        // LINE SEPARATOR (`\u{2028}`) trailing — paste-from-web-doc
8934        // footgun.
8935        let err = duration_codec::parse("30s\u{2028}").unwrap_err();
8936        assert!(
8937            err.contains("non-ASCII Unicode whitespace character"),
8938            "expected non-ASCII whitespace diagnostic in {err:?}"
8939        );
8940        assert!(err.contains("U+2028"), "missing codepoint in {err:?}");
8941    }
8942
8943    #[test]
8944    fn duration_codec_parse_accepts_ascii_only_forms_after_unicode_arm() {
8945        // Positive-control pin: every ASCII-only canonical form the
8946        // renderer emits stays accepted through the new arm.
8947        assert_eq!(
8948            duration_codec::parse("30s").unwrap(),
8949            Duration::from_secs(30)
8950        );
8951        assert_eq!(
8952            duration_codec::parse("500ms").unwrap(),
8953            Duration::from_millis(500)
8954        );
8955        assert_eq!(
8956            duration_codec::parse("1h").unwrap(),
8957            Duration::from_secs(3600)
8958        );
8959    }
8960
8961    #[test]
8962    fn restart_window_serde_rejects_non_ascii_whitespace() {
8963        // The shared codec backs `SupervisorSpec::restart_window` — so
8964        // the new non-ASCII Unicode whitespace arm applies on serde
8965        // deserialize for the typed Supervisor slot. A
8966        // `{"restartWindow":" 30s"}` payload that previously
8967        // survived the ASCII byte-scan (only ASCII whitespace was
8968        // refused) is now refused at deserialize with the
8969        // non-ASCII-whitespace-and-codepoint diagnostic.
8970        let payload = "{\"estrategia\":\"OneForOne\",\"maxRestarts\":5,\
8971            \"restartWindow\":\"\u{00A0}30s\",\
8972            \"children\":[{\"caixa\":\"w\",\"versao\":\"^0.1\",\"restart\":\"Permanent\"}]}";
8973        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
8974        let msg = err.to_string();
8975        assert!(
8976            msg.contains("non-ASCII Unicode whitespace character"),
8977            "expected non-ASCII whitespace diagnostic in {msg:?}"
8978        );
8979        assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
8980    }
8981
8982    // ── drift-detection: serde-derive-to-SUPERVISOR_KEY_* identity ────────
8983
8984    #[test]
8985    fn supervisor_spec_serde_keys_match_lifted_supervisor_key_consts() {
8986        // Load-bearing invariant: the four `SUPERVISOR_KEY_*` consts
8987        // (`SUPERVISOR_KEY_ESTRATEGIA` / `SUPERVISOR_KEY_MAX_RESTARTS` /
8988        // `SUPERVISOR_KEY_RESTART_WINDOW` / `SUPERVISOR_KEY_CHILDREN`)
8989        // name the exact camelCase JSON keys the
8990        // `#[serde(rename_all = "camelCase")]` attribute on
8991        // `SupervisorSpec` emits. Serialize a fully-populated spec (each
8992        // field carries `Some(_)` / non-empty) and pin that each canonical
8993        // byte-sequence appears verbatim in the JSON — a future accidental
8994        // `rename_all = "snake_case"` / `"kebab-case"` / verbatim-field-
8995        // name flip at the derive attribute (any of which would silently
8996        // break every downstream JSON consumer that reaches for one of the
8997        // four consts via `Value::get(...)`) surfaces here as a build-time
8998        // test failure at `supervisor.rs`, not as an apply-time
8999        // `.get(<stale-canonical-const>)` returning `None` far from the
9000        // derive-attr drift's commit. Peer with the sibling
9001        // `limits_spec_serde_keys_match_lifted_m2_limits_key_consts`
9002        // (d8b8b4f) pin on the M2 `:limits` axis — same discipline the
9003        // M2 typed-slot family established, extended here to close the
9004        // top-level Supervisor axis.
9005        let spec = SupervisorSpec {
9006            estrategia: RestartStrategy::OneForOne,
9007            max_restarts: 5,
9008            restart_window: Some(Duration::from_secs(60)),
9009            children: vec![ChildSpec {
9010                caixa: "w".into(),
9011                versao: "^0.1".into(),
9012                restart: RestartPolicy::Permanent,
9013            }],
9014        };
9015        let json = serde_json::to_string(&spec).unwrap();
9016        for key in [
9017            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
9018            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
9019            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
9020            crate::render::SUPERVISOR_KEY_CHILDREN,
9021        ] {
9022            let quoted = format!("\"{key}\"");
9023            assert!(
9024                json.contains(&quoted),
9025                "serialized SupervisorSpec must carry the lifted \
9026                 SUPERVISOR_KEY_* byte-sequence {quoted} verbatim in \
9027                 the JSON emission (got: {json})",
9028            );
9029        }
9030    }
9031
9032    #[test]
9033    fn supervisor_key_consts_are_pairwise_distinct() {
9034        // Cross-axis drift-detection pin: a future collapse of two
9035        // canonical top-level byte-strings onto the same value (e.g. an
9036        // accidental copy-paste flip of `SUPERVISOR_KEY_CHILDREN` to
9037        // also read `"estrategia"`) would silently reroute every
9038        // downstream probe on one axis onto the sibling axis's overlay
9039        // entry and pass every propagation-probe test that expected only
9040        // the stale axis's value. Peer of the sibling four-way distinct
9041        // pin on the `M2_LIMITS_KEY_*` tetrad (d8b8b4f).
9042        let all = [
9043            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
9044            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
9045            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
9046            crate::render::SUPERVISOR_KEY_CHILDREN,
9047        ];
9048        for (i, a) in all.iter().enumerate() {
9049            for b in all.iter().skip(i + 1) {
9050                assert_ne!(
9051                    a, b,
9052                    "SUPERVISOR_KEY_* consts must be pairwise-distinct \
9053                     canonical byte-sequences — got `{a}` == `{b}`",
9054                );
9055            }
9056        }
9057    }
9058
9059    #[test]
9060    fn supervisor_key_consts_are_lower_camel_case_shape() {
9061        // Shape-pin: every `SUPERVISOR_KEY_*` const must be a
9062        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
9063        // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
9064        // capital, no whitespace / dots) — the canonical shape the
9065        // `#[serde(rename_all = "camelCase")]` derive produces on
9066        // `SupervisorSpec`. A future flip to a non-camelCase attribute
9067        // at the derive surfaces both here (this test fails on the
9068        // stale-constant shape) and at
9069        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
9070        // (that test fails on the mismatch between const and derive).
9071        // Peer with `m2_limits_key_consts_are_lower_camel_case_shape`
9072        // (d8b8b4f) on the sibling M2 `:limits` axis.
9073        for key in [
9074            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
9075            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
9076            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
9077            crate::render::SUPERVISOR_KEY_CHILDREN,
9078        ] {
9079            assert!(
9080                !key.is_empty(),
9081                "SUPERVISOR_KEY_* must be non-empty (got {key:?})"
9082            );
9083            let first = key.chars().next().unwrap();
9084            assert!(
9085                first.is_ascii_lowercase(),
9086                "SUPERVISOR_KEY_* must lead with an ASCII-lowercase byte \
9087                 (got {key:?}, leads with {first:?})",
9088            );
9089            assert!(
9090                key.chars().all(|c| c.is_ascii_alphanumeric()),
9091                "SUPERVISOR_KEY_* must be ASCII-alphanumeric only \
9092                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
9093            );
9094        }
9095    }
9096
9097    #[test]
9098    fn supervisor_key_consts_are_byte_distinct_from_supervisor_author_key_peers() {
9099        // Cross-axis drift pin: the four `SUPERVISOR_KEY_*` consts
9100        // (camelCase JSON keys, no leading colon) must never collide
9101        // byte-for-byte with the four peer `SUPERVISOR_AUTHOR_KEY_*`
9102        // consts (kebab-case author-facing labels with leading colon)
9103        // that sit next to them at `caixa_core::render`. Both families
9104        // cover the same four typed Supervisor slots on two distinct
9105        // axes (author-side kebab vs renderer-side camelCase);
9106        // collapsing either family onto the other's byte-shape would
9107        // silently reroute the render-side probe onto the author-facing
9108        // surface, or vice versa. Peer of the byte-distinctness
9109        // discipline the `M3_PLACEMENT_KEY_ESTRATEGIA` docstring names
9110        // against the peer `M3_AUTHOR_KEY_PLACEMENT`.
9111        let pairs = [
9112            (
9113                crate::render::SUPERVISOR_KEY_ESTRATEGIA,
9114                crate::render::SUPERVISOR_AUTHOR_KEY_ESTRATEGIA,
9115            ),
9116            (
9117                crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
9118                crate::render::SUPERVISOR_AUTHOR_KEY_MAX_RESTARTS,
9119            ),
9120            (
9121                crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
9122                crate::render::SUPERVISOR_AUTHOR_KEY_RESTART_WINDOW,
9123            ),
9124            (
9125                crate::render::SUPERVISOR_KEY_CHILDREN,
9126                crate::render::SUPERVISOR_AUTHOR_KEY_CHILDREN,
9127            ),
9128        ];
9129        for (json_key, author_key) in pairs {
9130            assert_ne!(
9131                json_key, author_key,
9132                "SUPERVISOR_KEY_* (JSON side) must differ byte-for-byte \
9133                 from the peer SUPERVISOR_AUTHOR_KEY_* (author side); \
9134                 got JSON `{json_key}` == author `{author_key}`",
9135            );
9136        }
9137    }
9138
9139    // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_KEY_* identity ──
9140
9141    #[test]
9142    fn child_spec_serde_keys_match_lifted_supervisor_child_key_consts() {
9143        // Load-bearing invariant: the three `SUPERVISOR_CHILD_KEY_*` consts
9144        // (`SUPERVISOR_CHILD_KEY_CAIXA` / `SUPERVISOR_CHILD_KEY_VERSAO` /
9145        // `SUPERVISOR_CHILD_KEY_RESTART`) name the exact camelCase JSON
9146        // keys the `#[serde(rename_all = "camelCase")]` attribute on
9147        // `ChildSpec` emits. Serialize a fully-populated `ChildSpec` and
9148        // pin that each canonical byte-sequence appears verbatim in the
9149        // JSON — a future accidental `rename_all = "snake_case"` /
9150        // `"kebab-case"` / verbatim-field-name flip at the derive
9151        // attribute (any of which would silently break every downstream
9152        // JSON consumer that reaches for one of the three consts via
9153        // `Value::get(...)`) surfaces here as a build-time test failure at
9154        // `supervisor.rs`, not as an apply-time
9155        // `.get(<stale-canonical-const>)` returning `None` far from the
9156        // derive-attr drift's commit. Peer with the enclosing
9157        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
9158        // (40cc4e5) pin on the M2 supervision-tree top-level axis — same
9159        // discipline the SupervisorSpec top-level lift established,
9160        // extended here to the sibling per-`:children` entry `ChildSpec`
9161        // derive so the last M2 typed-struct sub-block
9162        // `#[serde(rename_all = "camelCase")]` axis on the Supervisor
9163        // surface without a lifted serde-key peer joins the substrate's
9164        // "one canonical byte-string per typed serialized-key axis"
9165        // discipline.
9166        let c = ChildSpec {
9167            caixa: "worker".into(),
9168            versao: "^0.1".into(),
9169            restart: RestartPolicy::Permanent,
9170        };
9171        let json = serde_json::to_string(&c).unwrap();
9172        for key in [
9173            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
9174            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
9175            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
9176        ] {
9177            let quoted = format!("\"{key}\"");
9178            assert!(
9179                json.contains(&quoted),
9180                "serialized ChildSpec must carry the lifted \
9181                 SUPERVISOR_CHILD_KEY_* byte-sequence {quoted} verbatim \
9182                 in the JSON emission (got: {json})",
9183            );
9184        }
9185    }
9186
9187    #[test]
9188    fn supervisor_child_key_consts_are_pairwise_distinct() {
9189        // Cross-axis drift-detection pin: a future collapse of two
9190        // canonical `ChildSpec` per-entry byte-strings onto the same
9191        // value (e.g. an accidental copy-paste flip of
9192        // `SUPERVISOR_CHILD_KEY_RESTART` to also read `"caixa"`) would
9193        // silently reroute every downstream probe on one axis onto the
9194        // sibling axis's overlay entry and pass every propagation-probe
9195        // test that expected only the stale axis's value. Peer of the
9196        // sibling three-way distinct pin on the `CONTRATO_KEY_*` triad
9197        // (ca463a4) and the two-way distinct pin on the `MEMBRO_KEY_*`
9198        // pair (ce80ca0).
9199        let all = [
9200            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
9201            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
9202            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
9203        ];
9204        for (i, a) in all.iter().enumerate() {
9205            for b in all.iter().skip(i + 1) {
9206                assert_ne!(
9207                    a, b,
9208                    "SUPERVISOR_CHILD_KEY_* consts must be pairwise-\
9209                     distinct canonical byte-sequences — got `{a}` == `{b}`",
9210                );
9211            }
9212        }
9213    }
9214
9215    #[test]
9216    fn supervisor_child_key_consts_are_lower_camel_case_shape() {
9217        // Shape-pin: every `SUPERVISOR_CHILD_KEY_*` const must be a
9218        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
9219        // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
9220        // capital, no whitespace / dots) — the canonical shape the
9221        // `#[serde(rename_all = "camelCase")]` derive produces on
9222        // `ChildSpec`. A future flip to a non-camelCase attribute at the
9223        // derive surfaces both here (this test fails on the
9224        // stale-constant shape) and at
9225        // `child_spec_serde_keys_match_lifted_supervisor_child_key_consts`
9226        // (that test fails on the mismatch between const and derive).
9227        // Peer with `supervisor_key_consts_are_lower_camel_case_shape`
9228        // (40cc4e5) on the sibling `SupervisorSpec` top-level axis.
9229        for key in [
9230            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
9231            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
9232            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
9233        ] {
9234            assert!(
9235                !key.is_empty(),
9236                "SUPERVISOR_CHILD_KEY_* must be non-empty (got {key:?})"
9237            );
9238            let first = key.chars().next().unwrap();
9239            assert!(
9240                first.is_ascii_lowercase(),
9241                "SUPERVISOR_CHILD_KEY_* must lead with an ASCII-lowercase \
9242                 byte (got {key:?}, leads with {first:?})",
9243            );
9244            assert!(
9245                key.chars().all(|c| c.is_ascii_alphanumeric()),
9246                "SUPERVISOR_CHILD_KEY_* must be ASCII-alphanumeric only \
9247                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
9248            );
9249        }
9250    }
9251
9252    // ── drift-detection: serde-derive-to-SUPERVISOR_ESTRATEGIA_* identity ────
9253
9254    #[test]
9255    fn restart_strategy_variants_serialize_to_lifted_scalar_values() {
9256        // The fail-before-pass-after pin: pre-lift there was no
9257        // single-source binding between the [`RestartStrategy`] variant
9258        // name the un-`rename`d `Serialize` derive emits under
9259        // [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`] and the byte-string
9260        // every downstream cluster-side dispatcher (the future
9261        // wasm-operator's per-supervisor sibling-restart branch, the
9262        // future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
9263        // admission-time enum-arm bind, the `caixa-operator`'s
9264        // hierarchical reconciliation scheduler's per-strategy fan-out)
9265        // probes verbatim. A future `#[serde(rename_all = "kebab-case")]`
9266        // attribute on the enum — or a per-variant `#[serde(rename = "…")]`
9267        // override, or a variant rename in the source — would silently
9268        // rebrand the emitted scalar under one spelling while every
9269        // downstream dispatcher still probed the other, with the failure
9270        // surfacing at the operator's reconcile posture (subtrees coming
9271        // up under the `default()` `OneForOne` arm rather than the typed
9272        // slot's declared strategy — a bad child would then only take
9273        // itself down instead of the sibling set the author intended, so
9274        // shared-state children fall out of sync) far from the source
9275        // rebrand commit and with no field naming the drift. Pinning the
9276        // two paths (the `Serialize` derive's serialized string AND the
9277        // [`RestartStrategy::as_str`] helper) to the same four lifted
9278        // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
9279        // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
9280        // [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
9281        // [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
9282        // byte-strings makes any future drift on either endpoint fail
9283        // here at caixa-core build time. Peer of the M3
9284        // `placement_strategy_variants_serialize_to_lifted_scalar_values`
9285        // (3f0e21c) on the sibling `PlacementStrategy` axis — same
9286        // three-path-convergence discipline, extended to close the
9287        // OTP-shaped per-supervisor sibling-restart axis.
9288        for (variant, expected) in [
9289            (
9290                RestartStrategy::OneForOne,
9291                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
9292            ),
9293            (
9294                RestartStrategy::OneForAll,
9295                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
9296            ),
9297            (
9298                RestartStrategy::RestForOne,
9299                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
9300            ),
9301            (
9302                RestartStrategy::SimpleOneForOne,
9303                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
9304            ),
9305        ] {
9306            let json = serde_json::to_string(&variant).unwrap();
9307            assert_eq!(
9308                json,
9309                format!("\"{expected}\""),
9310                "RestartStrategy::{variant:?} must serialize to {expected:?}"
9311            );
9312            assert_eq!(
9313                variant.as_str(),
9314                expected,
9315                "RestartStrategy::{variant:?}.as_str() must return the lifted \
9316                 SUPERVISOR_ESTRATEGIA_* constant"
9317            );
9318        }
9319    }
9320
9321    #[test]
9322    fn supervisor_estrategia_consts_are_pairwise_distinct() {
9323        // Cross-arm drift-detection pin: a future collapse of two
9324        // canonical variant byte-strings onto the same value (e.g. an
9325        // accidental copy-paste flip of `SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`
9326        // to also read `"OneForOne"`) would silently reroute every
9327        // downstream operator's per-strategy dispatch onto the sibling
9328        // arm's reconcile branch and pass every propagation-probe test
9329        // that expected only the stale arm's value — the mis-strategied
9330        // subtree would come up with the wrong sibling-restart posture
9331        // on every subsequent failure. Peer of the sibling four-way
9332        // distinct pin `supervisor_key_consts_are_pairwise_distinct`
9333        // (40cc4e5) on the top-level `SUPERVISOR_KEY_*` axis.
9334        let all = [
9335            crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
9336            crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
9337            crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
9338            crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
9339        ];
9340        for (i, a) in all.iter().enumerate() {
9341            for (j, b) in all.iter().enumerate() {
9342                if i != j {
9343                    assert_ne!(
9344                        a, b,
9345                        "SUPERVISOR_ESTRATEGIA_* consts must be pairwise distinct \
9346                         — got duplicate {a:?} at indices {i} and {j}",
9347                    );
9348                }
9349            }
9350        }
9351    }
9352
9353    #[test]
9354    fn restart_strategy_display_routes_through_as_str_helper() {
9355        // The fail-before-pass-after pin on the first half of the
9356        // three-path convergence: pre-convergence the sibling
9357        // OTP-shape typed enum [`RestartStrategy`] carried a
9358        // [`std::fmt::Display`] surface via its
9359        // `#[discriminant(also_display)]` gen-platform derive route,
9360        // which arrived kebab-case as `"one-for-one"` /
9361        // `"one-for-all"` / `"rest-for-one"` /
9362        // `"simple-one-for-one"` while the wire format ran as
9363        // PascalCase `"OneForOne"` / `"OneForAll"` / `"RestForOne"` /
9364        // `"SimpleOneForOne"` through the un-`rename`d serde derive.
9365        // Every consumer reaching for a strategy byte-string past the
9366        // wire format had to pick between three paths
9367        // ([`RestartStrategy::as_str`], the `Serialize` derive's
9368        // serialized string, or `format!("{v}")` on the
9369        // discriminant-Display route), any two of which a future
9370        // variant rename or `#[serde(rename_all = "kebab-case")]`
9371        // attribute would silently desynchronize. Wiring
9372        // [`std::fmt::Display`] through [`RestartStrategy::as_str`]
9373        // closes the third path: every `format!("{v}")` call reaches
9374        // the same lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
9375        // const the wire format and the [`RestartStrategy::as_str`]
9376        // helper already route through, so a future variant rename
9377        // lands at exactly one place. Pin the routing here so a future
9378        // `impl std::fmt::Display for RestartStrategy`
9379        // reimplementation that hand-rolls the arms instead of
9380        // delegating to [`RestartStrategy::as_str`] fails at
9381        // caixa-core build time. Peer of the M3
9382        // `placement_strategy_display_routes_through_as_str_helper`
9383        // (cc8f749) which the M3 axis converged first.
9384        for &variant in RestartStrategy::ALL {
9385            assert_eq!(
9386                variant.to_string(),
9387                variant.as_str(),
9388                "RestartStrategy::{variant:?} Display must route through \
9389                 RestartStrategy::as_str (single source of truth: the lifted \
9390                 SUPERVISOR_ESTRATEGIA_* const the wire format also emits)"
9391            );
9392        }
9393    }
9394
9395    #[test]
9396    fn restart_strategy_display_matches_serialized_wire_byte_string() {
9397        // The fail-before-pass-after pin on the second half of the
9398        // three-path convergence: `Display` (user-facing text) agrees
9399        // byte-for-byte with the `Serialize` derive's wire format
9400        // (canonical camelCase-schema `SUPERVISOR_KEY_ESTRATEGIA`
9401        // scalar) on every variant. Pre-convergence the two paths
9402        // were structurally independent — a future
9403        // `#[serde(rename_all = "kebab-case")]` attribute on the
9404        // enum would silently rebrand the emitted wire scalar
9405        // (`one-for-one`, `one-for-all`, `rest-for-one`,
9406        // `simple-one-for-one`) while every consumer that
9407        // pretty-prints the strategy (the future wasm-operator's
9408        // per-supervisor sibling-restart-strategy diagnostic line,
9409        // the future `feira app graph` per-supervisor strategy line,
9410        // the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
9411        // materializer's admission-webhook rejection body) would
9412        // still emit the PascalCase form the `as_str` / `Display`
9413        // route returns, with the mismatch surfacing at consumer
9414        // parse time / operator dispatch time far from the source
9415        // rebrand commit. Pin the two paths byte-for-byte here so any
9416        // future serde-attribute or variant-rename drift is a
9417        // caixa-core-build-time test failure at this call, not a
9418        // silent per-consumer dispatch miss. Peer of the M3
9419        // `placement_strategy_display_matches_serialized_wire_byte_string`
9420        // (cc8f749) which the M3 axis converged first.
9421        for &variant in RestartStrategy::ALL {
9422            let wire = serde_json::to_string(&variant).unwrap();
9423            let unquoted = wire
9424                .strip_prefix('"')
9425                .and_then(|s| s.strip_suffix('"'))
9426                .expect("serialized RestartStrategy is a JSON string");
9427            assert_eq!(
9428                variant.to_string(),
9429                unquoted,
9430                "RestartStrategy::{variant:?} Display byte-string must match the \
9431                 Serialize derive's wire byte-string (three-path convergence: \
9432                 Display + as_str + Serialize all resolve to the same \
9433                 SUPERVISOR_ESTRATEGIA_* const)"
9434            );
9435        }
9436    }
9437
9438    #[test]
9439    fn restart_strategy_as_ref_str_routes_through_as_str_accessor() {
9440        // Fail-before-pass-after byte-parity pin on the lifted
9441        // `impl AsRef<str> for RestartStrategy` — asserts the
9442        // standard-library trait impl and the substrate-primitive
9443        // [`RestartStrategy::as_str`] `pub const fn` accessor resolve
9444        // to the same `&str` per instance across the four-arm
9445        // closed set, so any future silent detour that routes the
9446        // impl through a divergent projection (a per-arm inline
9447        // `match self { RestartStrategy::OneForOne => "OneForOne", … }`
9448        // re-inlining that opens a compile-time link to the un-lifted
9449        // arm-literal, a swap onto the kebab-case
9450        // [`gen_platform::Discriminant`] catalog identity that would
9451        // collide the wire axis with the dispatcher-catalog axis) trips
9452        // at caixa-core test time under `PartialEq` rather than at a
9453        // downstream `impl AsRef<str>`-bound consumer's silent split.
9454        // Sweeps every one of the four arms
9455        // [`RestartStrategy::ALL`] carries so no arm's projection is
9456        // covered only by the sibling wire-format `Serialize` derive
9457        // path. Peer of the sibling
9458        // [`crate::version::tests::caixa_version_as_ref_str_routes_through_as_str_accessor`]
9459        // (16d5c7e) `AsRef<str>`-byte-parity pin on the paired
9460        // top-level `:versao` typed newtype — the two pins together
9461        // cover the substrate primitive's `AsRef<str>` projection axis
9462        // on the paired newtype + closed-set-typed-enum surface.
9463        for &variant in RestartStrategy::ALL {
9464            assert_eq!(
9465                <RestartStrategy as AsRef<str>>::as_ref(&variant),
9466                variant.as_str(),
9467                "AsRef<str> impl on RestartStrategy::{variant:?} must \
9468                 byte-equal RestartStrategy::as_str on the same instance \
9469                 — divergence signals a silent detour off the substrate-\
9470                 primitive accessor"
9471            );
9472        }
9473    }
9474
9475    #[test]
9476    fn restart_strategy_as_ref_str_routes_through_display_via_shared_accessor() {
9477        // Fail-before-pass-after byte-parity pin on the three-path
9478        // convergence discipline the M2 sibling-restart primitive now
9479        // carries on the `&str`-projection axis:
9480        // `<RestartStrategy as AsRef<str>>::as_ref(&s)` (the newly
9481        // lifted impl), `format!("{s}")` (the pre-existing
9482        // [`fmt::Display`] impl), and `s.as_str()` (the substrate-
9483        // primitive `pub const fn` accessor both trait impls delegate
9484        // through) must resolve to the same byte-string on every
9485        // instance across the four-arm closed set. Refuses any future
9486        // divergence between the two trait impls (a stray
9487        // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
9488        // rather than delegating through the shared accessor; a
9489        // hypothetical `AsRef<str>` rewrite that inlines a per-arm
9490        // literal cascade) that would silently split the two
9491        // projection paths of the same closed-set typed enum. Mirrors
9492        // the sibling three-path-convergence discipline the peer
9493        // [`crate::CaixaVersion`] typed newtype carries on its
9494        // `AsRef<str>` / `Display` / `as_str` triple
9495        // (version.rs pin
9496        // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
9497        // 16d5c7e).
9498        for &variant in RestartStrategy::ALL {
9499            let via_as_ref: &str = <RestartStrategy as AsRef<str>>::as_ref(&variant);
9500            let via_display: String = format!("{variant}");
9501            let via_accessor: &str = variant.as_str();
9502            assert_eq!(via_as_ref, via_accessor);
9503            assert_eq!(via_display, via_accessor);
9504            assert_eq!(via_as_ref, via_display.as_str());
9505        }
9506    }
9507
9508    #[test]
9509    fn restart_strategy_all_enumerates_every_variant_exactly_once() {
9510        // Fail-before-pass-after pin on the [`RestartStrategy::ALL`]
9511        // exhaustive-iteration surface: every variant appears exactly
9512        // once, and the slice length matches the arm count of the
9513        // closed set. Every consumer that walks the accepted-strategy
9514        // set (a future `feira supervisor --estrategia …` CLI-side
9515        // arg-parse's "did you mean" hint, a future M4 admission-
9516        // webhook's rejection body naming the accepted-`:estrategia`
9517        // list, the [`RestartStrategy::from_wire`] reverse-projection
9518        // consumers that iterate the accept-set for diagnostic
9519        // rendering) reads through this slice, so a future arm addition
9520        // that grows the enum but forgets to grow [`Self::ALL`]
9521        // silently truncates every downstream consumer's accept-set at
9522        // the same pre-addition boundary — this pin fails at caixa-core
9523        // build time on the pairwise-distinct + arm-count invariants.
9524        //
9525        // Peer of the sibling [`crate::CaixaKind::ALL`] (6b1f4fb) /
9526        // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
9527        // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
9528        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
9529        // pins on the peer closed-set typed-enum axes.
9530        let all: &[RestartStrategy] = RestartStrategy::ALL;
9531        assert_eq!(
9532            all.len(),
9533            4,
9534            "RestartStrategy::ALL must enumerate every variant of the \
9535             four-arm closed set (OneForOne, OneForAll, RestForOne, \
9536             SimpleOneForOne); got {all:?}"
9537        );
9538        for (i, a) in all.iter().enumerate() {
9539            for (j, b) in all.iter().enumerate() {
9540                if i != j {
9541                    assert_ne!(
9542                        a, b,
9543                        "RestartStrategy::ALL must carry every variant exactly \
9544                         once — got duplicate {a:?} at indices {i} and {j}"
9545                    );
9546                }
9547            }
9548        }
9549        for variant in [
9550            RestartStrategy::OneForOne,
9551            RestartStrategy::OneForAll,
9552            RestartStrategy::RestForOne,
9553            RestartStrategy::SimpleOneForOne,
9554        ] {
9555            assert!(
9556                all.contains(&variant),
9557                "RestartStrategy::ALL must contain {variant:?} — a future arm \
9558                 addition that grows the enum but forgets to grow the ALL slice \
9559                 silently truncates every downstream consumer's accept-set at \
9560                 the pre-addition boundary"
9561            );
9562        }
9563    }
9564
9565    #[test]
9566    fn restart_strategy_wire_names_covers_every_arm() {
9567        // Load-bearing pin on the substrate-canonical
9568        // [`RestartStrategy::WIRE_NAMES`] exhaustive accept-set roster
9569        // on the `PascalCase` wire byte-string axis: every variant of
9570        // the sibling [`RestartStrategy::ALL`] exhaustive-iteration
9571        // surface must project through [`RestartStrategy::as_str`] onto
9572        // an entry the [`RestartStrategy::WIRE_NAMES`] roster carries,
9573        // and the roster's length must byte-equal
9574        // `RestartStrategy::ALL.len()` so a silent skew between the
9575        // [`RestartStrategy::as_str`] match's arm-set and the roster's
9576        // arm-set trips here at caixa-core test time rather than at a
9577        // downstream M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
9578        // admission-webhook rejection body's wire-form `:estrategia`
9579        // accepted-set enumeration miss / a `feira supervisor
9580        // --estrategia …` "did you mean" hint drift / a future
9581        // wasm-operator per-reconcile-step diagnostic log line's
9582        // accepted-wire-form enumeration miss. A future arm addition
9583        // (an OTP-`rest_for_all` arm the theory
9584        // [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
9585        // might reach for once the four canonical OTP strategies stop
9586        // covering the substrate's discovered load-shape) extends
9587        // [`RestartStrategy::ALL`] as a single edit and this pin
9588        // sweeps the new arm by iteration; the paired
9589        // [`RestartStrategy::WIRE_NAMES`] roster must grow in lockstep
9590        // or this assertion trips. Every entry is further pinned to
9591        // open with an ASCII uppercase byte so a silent collapse of
9592        // the wire-form axis with the peer kebab-case
9593        // dispatcher-catalog axis (an entry byte-identical to a
9594        // sibling [`Self::discriminant`] kebab byte-string that would
9595        // let a wire-axis consumer accept the dispatcher-catalog
9596        // vocabulary) trips here rather than at a downstream K8s-CR
9597        // round-trip miss.
9598        //
9599        // Peer of the sibling
9600        // [`crate::kind::tests::caixa_kind_wire_names_covers_every_arm`]
9601        // (bd708bd) pin on the top-level typed-kind discriminator's
9602        // `PascalCase` wire byte-string axis, and of the sibling
9603        // [`crate::upgrade::tests::upgrade_instruction_wire_forms_covers_every_arm`]
9604        // (cc42c0e) /
9605        // [`crate::upgrade::tests::upgrade_instruction_lisp_forms_covers_every_arm`]
9606        // (1898d77) pins on the OTP-appup discriminator's two-axis
9607        // roster split — the same closed-set exhaustive-roster
9608        // coverage discipline extended here onto the first M2
9609        // OTP-shape sibling-restart closed-set typed enum.
9610        //
9611        // Fail-before-pass-after locally verified by mutating one arm
9612        // of the paired [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
9613        // const family (e.g. dropping the trailing `e` from
9614        // `"OneForOne"` → `"OneForOn"`) — the length pin still passes
9615        // but the `contains` check fires on the mutated arm; and by
9616        // shortening the roster to three entries — the length pin
9617        // fires first.
9618        assert_eq!(
9619            RestartStrategy::WIRE_NAMES.len(),
9620            RestartStrategy::ALL.len(),
9621            "RestartStrategy::WIRE_NAMES.len() must byte-equal \
9622             RestartStrategy::ALL.len() — a mismatch means the roster \
9623             and the enum's arm-set have drifted; downstream consumers \
9624             that fan through both will silently disagree on the \
9625             accepted arm-set"
9626        );
9627        for &variant in RestartStrategy::ALL {
9628            let wire = variant.as_str();
9629            assert!(
9630                RestartStrategy::WIRE_NAMES.contains(&wire),
9631                "RestartStrategy::{variant:?}.as_str() = {wire:?} must \
9632                 be a member of RestartStrategy::WIRE_NAMES — the \
9633                 emitter and the roster have drifted out of lockstep"
9634            );
9635        }
9636        for tag in RestartStrategy::WIRE_NAMES {
9637            let first = tag.chars().next().unwrap_or_else(|| {
9638                panic!(
9639                    "RestartStrategy::WIRE_NAMES entry {tag:?} must be \
9640                     a non-empty PascalCase byte-string"
9641                )
9642            });
9643            assert!(
9644                first.is_ascii_uppercase(),
9645                "RestartStrategy::WIRE_NAMES entry {tag:?} must open \
9646                 with an ASCII uppercase byte (PascalCase wire form) — \
9647                 a lowercase entry would collide the wire-form axis \
9648                 with the peer kebab-case dispatcher-catalog axis \
9649                 [`RestartStrategy::discriminant`] serves"
9650            );
9651        }
9652    }
9653
9654    #[test]
9655    fn restart_strategy_from_wire_accepts_every_lifted_constant() {
9656        // Fail-before-pass-after pin on the forward accept-set of the
9657        // [`RestartStrategy::from_wire`] reverse projection: every
9658        // canonical [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
9659        // constant the [`RestartStrategy::as_str`] emitter walks parses
9660        // back to its paired variant. Any future arm addition that
9661        // grows the emitter's `as_str` match but forgets to grow the
9662        // parser's `from_wire` match silently splits the two halves of
9663        // the round-trip — the wire byte-string one non-serde consumer
9664        // parses from the one the emitter wrote — with the failure
9665        // surfacing at parse time far from the rebrand commit. Pinning
9666        // the four-arm accept-set here catches the drift at caixa-core
9667        // build time.
9668        //
9669        // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
9670        // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
9671        // accept-set pins on the peer closed-set typed-enum `str → Self`
9672        // axes.
9673        for (wire, expected) in [
9674            (
9675                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
9676                RestartStrategy::OneForOne,
9677            ),
9678            (
9679                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
9680                RestartStrategy::OneForAll,
9681            ),
9682            (
9683                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
9684                RestartStrategy::RestForOne,
9685            ),
9686            (
9687                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
9688                RestartStrategy::SimpleOneForOne,
9689            ),
9690        ] {
9691            let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
9692                panic!(
9693                    "RestartStrategy::from_wire({wire:?}) must accept every \
9694                     SUPERVISOR_ESTRATEGIA_* constant — got None for the \
9695                     lifted canonical byte-string that RestartStrategy::{expected:?} \
9696                     serializes as under SUPERVISOR_KEY_ESTRATEGIA"
9697                )
9698            });
9699            assert_eq!(
9700                parsed, expected,
9701                "RestartStrategy::from_wire({wire:?}) must return \
9702                 RestartStrategy::{expected:?}; got RestartStrategy::{parsed:?}"
9703            );
9704        }
9705    }
9706
9707    #[test]
9708    fn restart_strategy_from_wire_round_trips_through_as_str() {
9709        // Fail-before-pass-after pin on the closed round-trip between
9710        // the forward [`RestartStrategy::as_str`] emitter and the
9711        // reverse [`RestartStrategy::from_wire`] parser: for every
9712        // variant in [`RestartStrategy::ALL`], parsing the emitter's
9713        // output must return exactly the same variant. Any per-arm
9714        // divergence — a future arm added to `as_str` but not
9715        // `from_wire`, an accidental copy-paste flip in one but not
9716        // the other — silently splits the emit and parse halves and
9717        // the failure surfaces at consumer parse time far from the
9718        // drift site. The `ALL`-iterating shape means a future arm
9719        // addition picks up the coverage by construction.
9720        //
9721        // Peer of the sibling
9722        // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
9723        // (18c7342) round-trip pin on
9724        // [`crate::aplicacao::PlacementStrategy::from_wire`] and
9725        // [`crate::kind::tests::caixa_kind_wire_round_trips_through_from_wire`]
9726        // (6b1f4fb) round-trip pin on [`crate::CaixaKind::from_wire`].
9727        for &variant in RestartStrategy::ALL {
9728            let wire = variant.as_str();
9729            let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
9730                panic!(
9731                    "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
9732                     must be Some({variant:?}) — the two halves of the round-trip \
9733                     dispatch on the same lifted SUPERVISOR_ESTRATEGIA_* consts; \
9734                     got None on wire byte-string {wire:?}"
9735                )
9736            });
9737            assert_eq!(
9738                parsed, variant,
9739                "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
9740                 must round-trip to the same variant; got {parsed:?}"
9741            );
9742        }
9743    }
9744
9745    #[test]
9746    fn restart_strategy_from_wire_rejects_unknown_byte_strings() {
9747        // Fail-before-pass-after pin on the closed-set refusal
9748        // discipline of [`RestartStrategy::from_wire`]: every
9749        // byte-string outside the four-arm accept-set returns `None`
9750        // rather than silently collapsing onto the [`Default`]
9751        // (`OneForOne`) arm or an arbitrary neighbor. The refusal set
9752        // exercised here sweeps the load-bearing drift shapes: the
9753        // empty string (a stripped serde-attribute drift), all-
9754        // whitespace strings (the canonical text-editor accidental
9755        // padding shape), the kebab-case dispatcher-catalog identities
9756        // (`"one-for-one"` / `"one-for-all"` / `"rest-for-one"` /
9757        // `"simple-one-for-one"` — the [`gen_platform::FromStrKind`]-
9758        // derived [`std::str::FromStr`] accept-set, which parses the
9759        // *other* axis of this enum's two-axis split and must not leak
9760        // into the `from_wire` PascalCase-wire accept-set), the
9761        // lowercased single-word forms (`"oneforone"`), the padded
9762        // canonical scalar (`" OneForOne "`), the trailing-newline
9763        // shapes (`"OneForOne\n"`), and neighboring-but-unknown arms
9764        // (`"AllForOne"` — the canonical typo direction).
9765        //
9766        // Peer of the sibling
9767        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
9768        // (2aa6d23) +
9769        // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
9770        // (18c7342) refusal pins on the peer closed-set typed-enum
9771        // axes.
9772        for bad in [
9773            "",
9774            " ",
9775            "\n",
9776            "\t",
9777            "one-for-one",
9778            "one-for-all",
9779            "rest-for-one",
9780            "simple-one-for-one",
9781            "oneforone",
9782            "OneForOnes",
9783            "one_for_one",
9784            "one for one",
9785            "ONEFORONE",
9786            "OneForOne ",
9787            " OneForOne",
9788            " SimpleOneForOne ",
9789            "OneForOne\n",
9790            "restforone",
9791            "REST_FOR_ONE",
9792            "AllForOne",
9793            "Simple",
9794            "?",
9795        ] {
9796            assert!(
9797                RestartStrategy::from_wire(bad).is_none(),
9798                "RestartStrategy::from_wire({bad:?}) must return None — the \
9799                 parser's accept-set is exactly the four RestartStrategy::as_str \
9800                 outputs (OneForOne, OneForAll, RestForOne, SimpleOneForOne), \
9801                 and this byte-string is outside that closed set"
9802            );
9803        }
9804    }
9805
9806    #[test]
9807    fn restart_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
9808        // Fail-before-pass-after pin on the fourth path of the four-path
9809        // convergence: `from_wire` (the reverse projection) inverts the
9810        // `Serialize` derive's wire byte-string on every variant.
9811        // Together with the pre-existing three-path convergence
9812        // (`Display` + `as_str` + `Serialize` all resolve to the same
9813        // lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const,
9814        // pinned by
9815        // [`restart_strategy_display_matches_serialized_wire_byte_string`])
9816        // this closes the round-trip: the wire byte-string the
9817        // `Serialize` derive emits parses back to the same variant
9818        // through `from_wire`, so any future serde-attribute or variant-
9819        // rename drift on the emit half now surfaces as a matched drift
9820        // on the parse half at caixa-core build time — the two halves
9821        // migrate as a unit through the lifted consts on any future
9822        // rename, and the round-trip cannot silently split.
9823        //
9824        // Peer of the sibling
9825        // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
9826        // (18c7342) wire-format pin on
9827        // [`crate::aplicacao::PlacementStrategy::from_wire`].
9828        for &variant in RestartStrategy::ALL {
9829            let wire = serde_json::to_string(&variant).unwrap();
9830            let unquoted = wire
9831                .strip_prefix('"')
9832                .and_then(|s| s.strip_suffix('"'))
9833                .expect("serialized RestartStrategy is a JSON string");
9834            let parsed = RestartStrategy::from_wire(unquoted).unwrap_or_else(|| {
9835                panic!(
9836                    "RestartStrategy::from_wire({unquoted:?}) must accept the \
9837                     Serialize derive's wire byte-string for \
9838                     RestartStrategy::{variant:?} — the four-path convergence \
9839                     (Display + as_str + Serialize + from_wire) resolves through \
9840                     the same lifted SUPERVISOR_ESTRATEGIA_* const; got None"
9841                )
9842            });
9843            assert_eq!(
9844                parsed, variant,
9845                "RestartStrategy::from_wire of the Serialize derive's wire \
9846                 byte-string for RestartStrategy::{variant:?} must round-trip \
9847                 to the same variant; got {parsed:?}"
9848            );
9849        }
9850    }
9851
9852    #[test]
9853    fn restart_strategy_try_from_str_routes_through_from_wire_accessor() {
9854        // Fail-before-pass-after byte-parity pin on the newly lifted
9855        // `impl TryFrom<&str> for RestartStrategy` — asserts the standard-
9856        // library trait impl and the substrate-primitive
9857        // [`RestartStrategy::from_wire`] `Option<Self>` accessor resolve to
9858        // the same four-arm accept-set across every arm the exhaustive
9859        // [`RestartStrategy::ALL`] slice enumerates. Any future silent
9860        // detour that routes the trait impl through a divergent projection
9861        // (a per-arm inline `match s { "OneForOne" => Ok(Self::OneForOne),
9862        // … }` re-inlining that opens a compile-time link to the un-
9863        // lifted arm-literal, a hypothetical `#[serde(rename_all = "…")]`
9864        // attribute drift that silently splits the wire byte-string from
9865        // every consumer that reaches for this typed dispatch, an
9866        // accidental swap onto the kebab-case dispatcher-catalog axis the
9867        // pre-existing [`std::str::FromStr`] impl parses through and which
9868        // would collide the two-axis wire/catalog split the sibling
9869        // [`RestartStrategy::from_wire`] doc block makes load-bearing)
9870        // trips at caixa-core test time under `assert_eq!` rather than at
9871        // a downstream `impl TryFrom<&str>`-bound consumer's silent split.
9872        // Sweeps every one of the four arms [`RestartStrategy::ALL`]
9873        // carries so no arm's projection is covered only by the sibling
9874        // method-named `from_wire` path. Peer of the sibling
9875        // [`crate::kind::tests::caixa_kind_try_from_str_routes_through_from_wire_accessor`]
9876        // (3c83606),
9877        // [`crate::dialeto::tests::caixa_dialeto_try_from_str_routes_through_from_wire_accessor`]
9878        // (bf33136), and the M3
9879        // [`crate::aplicacao::tests::placement_strategy_try_from_str_routes_through_from_wire_accessor`]
9880        // (6fd00cd) — extends the trait-idiomatic reverse-projection axis
9881        // onto the first M2-OTP-shape closed-set typed enum on the caixa
9882        // surface.
9883        for &variant in RestartStrategy::ALL {
9884            let wire = variant.as_str();
9885            assert_eq!(
9886                <RestartStrategy as TryFrom<&str>>::try_from(wire),
9887                Ok(variant),
9888                "TryFrom<&str> impl on RestartStrategy must round-trip \
9889                 RestartStrategy::{variant:?}.as_str() = {wire:?} back to \
9890                 Ok(RestartStrategy::{variant:?}) — divergence from \
9891                 RestartStrategy::from_wire signals a silent detour off \
9892                 the substrate-primitive accessor"
9893            );
9894            assert_eq!(
9895                <RestartStrategy as TryFrom<&str>>::try_from(wire).ok(),
9896                RestartStrategy::from_wire(wire),
9897                "TryFrom<&str> ok()-projection on {wire:?} must byte-equal \
9898                 RestartStrategy::from_wire on the same input"
9899            );
9900        }
9901    }
9902
9903    #[test]
9904    fn restart_strategy_try_from_str_rejects_unknown_byte_strings() {
9905        // Rejection witness on the `impl TryFrom<&str> for
9906        // RestartStrategy` — sweeps a candidate set of byte-strings
9907        // outside the four-arm PascalCase wire accept-set the sibling
9908        // [`RestartStrategy::as_str`] emits and asserts every one lands on
9909        // `Err(())`, so a future accidental widening of the trait impl's
9910        // accept-set (a stray additional
9911        // `_ if s.eq_ignore_ascii_case("OneForOne") => Ok(…)` case-fold
9912        // path, a silent inclusion of the kebab-case dispatcher-catalog
9913        // byte-string the pre-existing [`std::str::FromStr`] impl the
9914        // [`gen_platform::FromStrKind`] derive installs parses onto the
9915        // wire axis — which would collide the two-axis
9916        // wire/dispatcher-catalog split the sibling
9917        // [`RestartStrategy::from_wire`] doc block makes load-bearing —
9918        // an English-rebrand or plural-arm silent alias that would
9919        // widen the wire accept-set past the OTP-canonical four) trips at
9920        // caixa-core test time. The candidate set includes the empty
9921        // string, whitespace-only padding, the kebab-case dispatcher-
9922        // catalog byte-strings on the sibling axis (a caller who confuses
9923        // the two axes trips here rather than at a downstream consumer's
9924        // silent reject), a lowercase / uppercase / mixed-case fold of
9925        // each PascalCase arm (a caller who assumes case-fold acceptance
9926        // trips here), leading/trailing whitespace padding, the trailing-
9927        // newline shape, quote-wrapped candidates, and a residual set of
9928        // plausible-but-wrong English rebrand candidates. Peer of the
9929        // sibling
9930        // [`crate::kind::tests::caixa_kind_try_from_str_rejects_unknown_byte_strings`]
9931        // (3c83606) and
9932        // [`crate::aplicacao::tests::placement_strategy_try_from_str_rejects_unknown_byte_strings`]
9933        // (6fd00cd) rejection witnesses.
9934        let rejected: &[&str] = &[
9935            "",
9936            " ",
9937            "\n",
9938            "\t",
9939            "one-for-one",
9940            "one-for-all",
9941            "rest-for-one",
9942            "simple-one-for-one",
9943            "oneforone",
9944            "one_for_one",
9945            "OneForOnes",
9946            "ONEFORONE",
9947            "oneforall",
9948            "restforone",
9949            "simpleoneforone",
9950            "OneForOne ",
9951            " OneForOne",
9952            " OneForAll ",
9953            "OneForOne\n",
9954            "RestForOne\t",
9955            "OneForEach",
9956            "AllForOne",
9957            "one for one",
9958            "\"OneForOne\"",
9959            "?",
9960        ];
9961        for &input in rejected {
9962            assert_eq!(
9963                <RestartStrategy as TryFrom<&str>>::try_from(input),
9964                Err(()),
9965                "TryFrom<&str> impl on RestartStrategy must reject the \
9966                 non-wire byte-string {input:?} — silent acceptance signals \
9967                 an accept-set widening off the paired \
9968                 RestartStrategy::from_wire resolver"
9969            );
9970        }
9971    }
9972
9973    #[test]
9974    fn restart_strategy_try_from_str_and_from_wire_partition_the_accept_set() {
9975        // Cross-axis partition pin: the paired `TryFrom<&str>` and
9976        // `from_wire` reverse projections must resolve identically on
9977        // *every* input, not just the ones [`RestartStrategy::ALL`]
9978        // enumerates. Sweeps a mixed candidate set spanning accepted
9979        // (four-arm PascalCase wire byte-strings) and rejected (kebab-case
9980        // dispatcher-catalog byte-strings, empty, whitespace-padded,
9981        // quoted, English-rebrand candidates) inputs and asserts the
9982        // trait's `Result::ok()` projection byte-equals the method-named
9983        // resolver's `Option<Self>` return-shape on each, locking the two
9984        // paths together by construction so any future detour (a stray
9985        // `try_from` special-case that widens or narrows the accept-set
9986        // outside the paired `from_wire` resolver, an accidental swap
9987        // onto the kebab-case [`std::str::FromStr`] impl the
9988        // [`gen_platform::FromStrKind`] derive installs on the sibling
9989        // dispatcher-catalog axis) trips at caixa-core test time. Peer of
9990        // the sibling
9991        // [`crate::kind::tests::caixa_kind_try_from_str_and_from_wire_partition_the_accept_set`]
9992        // pin — extends the round-trip discipline onto the M2-OTP-shape
9993        // sibling-restart axis.
9994        let candidates: &[&str] = &[
9995            "OneForOne",
9996            "OneForAll",
9997            "RestForOne",
9998            "SimpleOneForOne",
9999            "",
10000            "one-for-one",
10001            "one-for-all",
10002            "rest-for-one",
10003            "simple-one-for-one",
10004            "oneforone",
10005            "unknown",
10006            "OneForOne ",
10007            " OneForOne",
10008            "\"OneForOne\"",
10009            "OneForEach",
10010            "?",
10011        ];
10012        for &input in candidates {
10013            let via_trait: Option<RestartStrategy> =
10014                <RestartStrategy as TryFrom<&str>>::try_from(input).ok();
10015            let via_method: Option<RestartStrategy> = RestartStrategy::from_wire(input);
10016            assert_eq!(
10017                via_trait, via_method,
10018                "TryFrom<&str> and from_wire must resolve identically on \
10019                 input {input:?} — divergence signals the two reverse-\
10020                 projection paths have drifted onto different accept-sets"
10021            );
10022        }
10023    }
10024
10025    #[test]
10026    fn restart_strategy_from_into_static_str_routes_through_as_str_accessor() {
10027        // Fail-before-pass-after byte-parity pin on the newly lifted
10028        // `impl From<RestartStrategy> for &'static str` — asserts the
10029        // standard-library trait impl and the substrate-primitive
10030        // [`RestartStrategy::as_str`] `pub const fn` accessor resolve to
10031        // the same four-arm emit-set across every arm the exhaustive
10032        // [`RestartStrategy::ALL`] slice enumerates. Any future silent
10033        // detour that routes the trait impl through a divergent
10034        // projection (a per-arm inline `match strategy { OneForOne =>
10035        // "OneForOne", … }` re-inlining that opens a compile-time link to
10036        // the un-lifted arm-literal, an accidental swap onto the sibling
10037        // kebab-case [`Self::discriminant`] dispatcher-catalog axis that
10038        // would collide the two-axis wire/catalog split the sibling
10039        // [`RestartStrategy::from_wire`] doc block makes load-bearing) trips
10040        // at caixa-core test time under `assert_eq!` rather than at a
10041        // downstream `impl Into<&'static str>`-bound consumer's silent
10042        // split. Sweeps every one of the four arms
10043        // [`RestartStrategy::ALL`] carries so no arm's projection is
10044        // covered only by the sibling method-named `as_str` /
10045        // [`std::fmt::Display`] / [`AsRef<str>`] paths. Materializes the
10046        // `<&'static str as From<RestartStrategy>>::from` output in a
10047        // `const`-shape binding to make the `'static` lifetime promise a
10048        // build-time invariant — a future accidental downgrade of any of
10049        // the four arms' [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
10050        // constants to a non-`&'static str` (a `String::leak()`-produced
10051        // return, a `Box::leak`-cast) trips at caixa-core build time
10052        // rather than at a downstream `'static`-bound consumer.
10053        const ONE_FOR_ONE: &str = RestartStrategy::OneForOne.as_str();
10054        const ONE_FOR_ALL: &str = RestartStrategy::OneForAll.as_str();
10055        const REST_FOR_ONE: &str = RestartStrategy::RestForOne.as_str();
10056        const SIMPLE_ONE_FOR_ONE: &str = RestartStrategy::SimpleOneForOne.as_str();
10057        for &variant in RestartStrategy::ALL {
10058            let via_trait: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
10059            let via_method: &'static str = variant.as_str();
10060            assert_eq!(
10061                via_trait, via_method,
10062                "From<RestartStrategy> for &'static str impl must round-trip \
10063                 RestartStrategy::{variant:?} to the same lifted \
10064                 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str returns — \
10065                 divergence signals a silent detour off the substrate-primitive \
10066                 accessor"
10067            );
10068            let via_into: &'static str = variant.into();
10069            assert_eq!(
10070                via_into, via_method,
10071                "Into<&'static str>::into on RestartStrategy::{variant:?} must \
10072                 byte-equal RestartStrategy::as_str on the same input — the \
10073                 blanket-derived Into shape must resolve to the same as_str \
10074                 dispatch as the explicit From impl"
10075            );
10076        }
10077        assert_eq!(
10078            [ONE_FOR_ONE, ONE_FOR_ALL, REST_FOR_ONE, SIMPLE_ONE_FOR_ONE],
10079            [
10080                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
10081                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
10082                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
10083                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
10084            ],
10085            "const-context RestartStrategy::as_str must resolve to the four \
10086             lifted SUPERVISOR_ESTRATEGIA_* consts — a future accidental \
10087             downgrade of any arm to a non-const or non-static byte-string \
10088             breaks the `&'static str`-lifetime promise the paired \
10089             From<RestartStrategy> for &'static str impl carries by \
10090             construction"
10091        );
10092    }
10093
10094    #[test]
10095    fn restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set() {
10096        // Cross-axis partition pin: the paired trait-idiomatic
10097        // `From<RestartStrategy> for &'static str` forward projection and
10098        // the method-named [`RestartStrategy::as_str`] forward projection
10099        // must resolve identically on *every* arm, not just the ones
10100        // named in the primary byte-parity pin above. Sweeps every
10101        // [`RestartStrategy::ALL`] arm and asserts the trait's `From::from`
10102        // output byte-equals the method-named accessor's return-value on
10103        // each, locking the two forward-projection paths together by
10104        // construction so any future detour (a stray `From` special-case
10105        // that lands on a divergent per-arm literal outside the paired
10106        // `as_str` dispatch, a hypothetical rebrand touching one axis
10107        // without the other) trips at caixa-core test time. Peer of the
10108        // sibling reverse-projection partition pin
10109        // [`restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
10110        // — extends the round-trip discipline onto the trait-idiomatic
10111        // *forward* axis, closing the two-way `Self ↔ &'static str`
10112        // round-trip on the trait-idiomatic pair
10113        // (`From<Self> for &'static str` + `TryFrom<&str> for Self`) as
10114        // well as the pre-existing method-named pair
10115        // (`as_str` + `from_wire`).
10116        for &variant in RestartStrategy::ALL {
10117            let via_trait: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
10118            let via_method: &'static str = variant.as_str();
10119            assert_eq!(
10120                via_trait, via_method,
10121                "From<RestartStrategy> for &'static str and \
10122                 RestartStrategy::as_str must resolve identically on \
10123                 RestartStrategy::{variant:?} — divergence signals the \
10124                 two forward-projection paths have drifted onto different \
10125                 emit-sets"
10126            );
10127        }
10128        // Round-trip witness: every arm's forward `From` output re-parses
10129        // through the paired trait-idiomatic reverse `TryFrom<&str>` back
10130        // to the original variant. Closes the two-way `RestartStrategy ↔
10131        // &'static str` round-trip on the trait-idiomatic axis pair,
10132        // mirroring the pre-existing method-named `as_str` + `from_wire`
10133        // round-trip on the substrate-primitive axis pair.
10134        for &variant in RestartStrategy::ALL {
10135            let emitted: &'static str = variant.into();
10136            let re_parsed: Result<RestartStrategy, ()> =
10137                <RestartStrategy as TryFrom<&str>>::try_from(emitted);
10138            assert_eq!(
10139                re_parsed,
10140                Ok(variant),
10141                "trait-idiomatic axis pair must round-trip \
10142                 RestartStrategy::{variant:?} through `.into::<&'static \
10143                 str>()` and back through `TryFrom<&str>` — a break signals \
10144                 the forward-emit and reverse-parse axes have drifted onto \
10145                 different vocabularies"
10146            );
10147        }
10148    }
10149
10150    #[test]
10151    fn restart_strategy_from_borrowed_into_static_str_routes_through_as_str_accessor() {
10152        // Fail-before-pass-after byte-parity pin on the newly lifted
10153        // `impl From<&RestartStrategy> for &'static str` — asserts the
10154        // borrowed-input standard-library trait impl and the substrate-
10155        // primitive [`RestartStrategy::as_str`] `pub const fn` accessor
10156        // resolve to the same four-arm emit-set across every arm the
10157        // exhaustive [`RestartStrategy::ALL`] slice enumerates. Rust's
10158        // `From` trait does not auto-derive the borrowed-input sibling
10159        // from a paired owned-input impl (no `impl<T, U> From<&T> for U
10160        // where T: Copy, U: From<T>` blanket in `core`), so the
10161        // borrowed-input axis is a distinct trait-idiomatic surface
10162        // that a `.iter().map(Into::into)` shape over
10163        // [`RestartStrategy::ALL`] (whose iterator yields
10164        // `&RestartStrategy`, not `RestartStrategy`) reaches through
10165        // this impl and no other — the paired owned-input
10166        // [`From<RestartStrategy>`] impl requires an explicit
10167        // `.copied()` / dereference before the trait fires.
10168        // Materializes the `<&'static str as
10169        // From<&RestartStrategy>>::from` output in a `const`-shape
10170        // binding to make the `'static` lifetime promise a build-time
10171        // invariant.
10172        const ONE_FOR_ONE: &str = RestartStrategy::OneForOne.as_str();
10173        const ONE_FOR_ALL: &str = RestartStrategy::OneForAll.as_str();
10174        const REST_FOR_ONE: &str = RestartStrategy::RestForOne.as_str();
10175        const SIMPLE_ONE_FOR_ONE: &str = RestartStrategy::SimpleOneForOne.as_str();
10176        for variant in RestartStrategy::ALL {
10177            let via_trait: &'static str = <&'static str as From<&RestartStrategy>>::from(variant);
10178            let via_method: &'static str = variant.as_str();
10179            assert_eq!(
10180                via_trait, via_method,
10181                "From<&RestartStrategy> for &'static str impl must \
10182                 round-trip &RestartStrategy::{variant:?} to the same \
10183                 lifted SUPERVISOR_ESTRATEGIA_* const \
10184                 RestartStrategy::as_str returns — divergence signals a \
10185                 silent detour off the substrate-primitive accessor"
10186            );
10187            let via_into: &'static str = variant.into();
10188            assert_eq!(
10189                via_into, via_method,
10190                "Into<&'static str>::into on &RestartStrategy::{variant:?} \
10191                 must byte-equal RestartStrategy::as_str on the same input — \
10192                 the blanket-derived Into shape must resolve to the same \
10193                 as_str dispatch as the explicit From impl"
10194            );
10195        }
10196        assert_eq!(
10197            [ONE_FOR_ONE, ONE_FOR_ALL, REST_FOR_ONE, SIMPLE_ONE_FOR_ONE],
10198            [
10199                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
10200                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
10201                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
10202                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
10203            ],
10204            "const-context RestartStrategy::as_str must resolve to the \
10205             four lifted SUPERVISOR_ESTRATEGIA_* consts — the borrowed-\
10206             input From<&RestartStrategy> for &'static str impl inherits \
10207             its `'static` lifetime promise from the same accessor the \
10208             owned-input sibling routes through"
10209        );
10210    }
10211
10212    #[test]
10213    fn restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
10214        // Cross-axis partition pin: the paired trait-idiomatic
10215        // owned-input `From<RestartStrategy> for &'static str` (523157d
10216        // campaign-shape) and borrowed-input `From<&RestartStrategy> for
10217        // &'static str` (this lift) forward projections must resolve
10218        // identically on every arm, locking the two input-shape paths
10219        // together so any future detour trips at caixa-core test time.
10220        // Then a witness that a `.iter().map(Into::into)` pipe over
10221        // [`RestartStrategy::ALL`] (whose iterator yields
10222        // `&RestartStrategy`) materializes the four-arm accept-set
10223        // through the borrowed-input axis alone — the exact shape a
10224        // future wasm-operator per-supervisor sibling-restart-strategy
10225        // diagnostic line, a future substrate-wide per-arm diagnostic
10226        // column, or a
10227        // `HashMap::<&'static str, RestartStrategy>::from_iter(
10228        //     RestartStrategy::ALL.iter().map(|s| (s.into(), *s)))`-style
10229        // per-strategy lookup reaches through — closing the two-way
10230        // owned/borrowed input-shape symmetry on the forward-projection
10231        // trait-idiomatic axis. Peer of the sibling
10232        // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
10233        // (64aa742) /
10234        // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
10235        // (5ab993a) /
10236        // [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
10237        // (807b0b5) partition pins on the sibling closed-set typed-enum
10238        // discriminator axes — extends the borrowed-input axis
10239        // discipline onto the first M2 OTP-shape sibling-restart
10240        // closed-set typed enum on the caixa surface. Also closes the
10241        // direct two-way `&Self → &'static str → Self` round-trip via
10242        // the paired [`TryFrom<&str>`] axis — unlike the peer
10243        // [`crate::CaixaKind`] axis pair (whose forward `From` emits
10244        // lowercase Portuguese diagnostic bytes while the reverse
10245        // `TryFrom` parses `PascalCase` wire bytes, forcing the round-
10246        // trip through an intermediate wire-vocab hop), the
10247        // [`RestartStrategy::as_str`] emit and
10248        // [`RestartStrategy::from_wire`] parse share the same
10249        // `PascalCase` vocabulary by construction, so the borrowed-
10250        // input forward axis and the reverse axis compose directly.
10251        for &variant in RestartStrategy::ALL {
10252            let owned: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
10253            let borrowed: &'static str = <&'static str as From<&RestartStrategy>>::from(&variant);
10254            assert_eq!(
10255                owned, borrowed,
10256                "From<RestartStrategy> and From<&RestartStrategy> for \
10257                 &'static str must resolve identically on \
10258                 RestartStrategy::{variant:?} — divergence signals the \
10259                 owned-input and borrowed-input forward-projection paths \
10260                 have drifted onto different emit-sets"
10261            );
10262        }
10263        let via_iter: Vec<&'static str> = RestartStrategy::ALL.iter().map(Into::into).collect();
10264        let via_method: Vec<&'static str> =
10265            RestartStrategy::ALL.iter().map(|s| s.as_str()).collect();
10266        assert_eq!(
10267            via_iter, via_method,
10268            "`.iter().map(Into::into)` over RestartStrategy::ALL must \
10269             byte-equal `.iter().map(|s| s.as_str())` on every arm — the \
10270             borrowed-input `From<&RestartStrategy> for &'static str` \
10271             axis is what makes the `.iter().map(Into::into)` shape route \
10272             through the substrate-primitive `RestartStrategy::as_str` \
10273             accessor rather than through a per-call-site `.copied()` / \
10274             dereference detour"
10275        );
10276        for variant in RestartStrategy::ALL {
10277            let emitted: &'static str = variant.into();
10278            let re_parsed: Result<RestartStrategy, ()> =
10279                <RestartStrategy as TryFrom<&str>>::try_from(emitted);
10280            assert_eq!(
10281                re_parsed,
10282                Ok(*variant),
10283                "trait-idiomatic borrowed-input forward-projection + \
10284                 reverse-projection axis pair must round-trip \
10285                 &RestartStrategy::{variant:?} through `.into::<&'static \
10286                 str>()` (via the borrowed-input axis) and back through \
10287                 `TryFrom<&str>` — a break signals the borrowed-input \
10288                 forward-emit and reverse-parse axes have drifted onto \
10289                 different vocabularies"
10290            );
10291        }
10292    }
10293
10294    #[test]
10295    fn restart_strategy_from_into_owned_string_routes_through_as_str_accessor() {
10296        // Fail-before-pass-after byte-parity pin on the newly lifted
10297        // `impl From<RestartStrategy> for String` — asserts the
10298        // owned-`String`-returning standard-library trait impl and the
10299        // substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
10300        // accessor resolve to the same four-arm emit-set across every
10301        // arm the exhaustive [`RestartStrategy::ALL`] slice enumerates.
10302        // Rust's standard library does not carry a blanket
10303        // `impl<T: AsRef<str>> From<T> for String` (nor an
10304        // `impl<T: fmt::Display> From<T> for String`), so the
10305        // owned-`String` forward-projection axis is a distinct
10306        // trait-idiomatic surface that a
10307        // `let key: String = strategy.into();`-shaped call site
10308        // reaches through this impl and no other — the paired sibling
10309        // `From<RestartStrategy> for &'static str` impl forces every
10310        // owned-`String` call site through an explicit
10311        // `.to_owned()` / `String::from` restatement.
10312        for &variant in RestartStrategy::ALL {
10313            let via_trait: String = <String as From<RestartStrategy>>::from(variant);
10314            let via_method: &'static str = variant.as_str();
10315            assert_eq!(
10316                via_trait.as_str(),
10317                via_method,
10318                "From<RestartStrategy> for String impl must round-trip \
10319                 RestartStrategy::{variant:?} to the same lifted \
10320                 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
10321                 returns — divergence signals a silent detour off the \
10322                 substrate-primitive accessor"
10323            );
10324            let via_into: String = variant.into();
10325            assert_eq!(
10326                via_into.as_str(),
10327                via_method,
10328                "Into<String>::into on RestartStrategy::{variant:?} must \
10329                 byte-equal RestartStrategy::as_str on the same input — the \
10330                 blanket-derived Into shape must resolve to the same as_str \
10331                 dispatch as the explicit From impl"
10332            );
10333        }
10334    }
10335
10336    #[test]
10337    fn restart_strategy_from_into_owned_string_and_static_str_agree_on_every_arm() {
10338        // Cross-axis partition pin: the paired trait-idiomatic
10339        // owned-`String` `From<RestartStrategy> for String` (this lift)
10340        // and owned-`&'static str` `From<RestartStrategy> for &'static
10341        // str` (523157d) forward projections must resolve identically
10342        // on every arm, locking the two return-type-shape paths
10343        // together so any future detour trips at caixa-core test time.
10344        // Also byte-parity witness against the sibling
10345        // [`ToString::to_string`] surface routed through
10346        // [`std::fmt::Display`] — the three owned-heap-string paths
10347        // (`.into::<String>()`, `String::from`, `.to_string()`) must
10348        // resolve identically on every arm so a future consumer that
10349        // picks any of the three lands on the same lifted
10350        // SUPERVISOR_ESTRATEGIA_* const. Then a direct round-trip
10351        // witness through the paired trait-idiomatic reverse
10352        // [`TryFrom<&str>`] axis on the owned-`String`'s
10353        // [`String::as_str`] borrow that closes the two-way
10354        // `Self → String → Self` round-trip on the trait-idiomatic
10355        // owned-`String` forward + reverse axis pair.
10356        for &variant in RestartStrategy::ALL {
10357            let owned_string: String = <String as From<RestartStrategy>>::from(variant);
10358            let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
10359            assert_eq!(
10360                owned_string.as_str(),
10361                owned_static,
10362                "From<RestartStrategy> for String and From<RestartStrategy> \
10363                 for &'static str must resolve identically on \
10364                 RestartStrategy::{variant:?} — divergence signals the \
10365                 owned-`String` and owned-`&'static str` forward-projection \
10366                 return-type-shape paths have drifted onto different \
10367                 emit-sets"
10368            );
10369            let via_to_string: String = variant.to_string();
10370            assert_eq!(
10371                owned_string, via_to_string,
10372                "From<RestartStrategy> for String must byte-equal \
10373                 RestartStrategy::to_string on RestartStrategy::{variant:?} — \
10374                 divergence signals the trait-idiomatic owned-`String` \
10375                 forward-projection axis and the ToString-through-Display \
10376                 axis have drifted onto different emit-sets"
10377            );
10378        }
10379        let via_iter: Vec<String> = RestartStrategy::ALL
10380            .iter()
10381            .copied()
10382            .map(String::from)
10383            .collect();
10384        let via_method: Vec<String> = RestartStrategy::ALL
10385            .iter()
10386            .map(|s| s.as_str().to_owned())
10387            .collect();
10388        assert_eq!(
10389            via_iter, via_method,
10390            "`.iter().copied().map(String::from)` over RestartStrategy::ALL \
10391             must byte-equal `.iter().map(|s| s.as_str().to_owned())` on \
10392             every arm — the owned-`String` `From<RestartStrategy> for \
10393             String` axis is what makes the `String::from` composition \
10394             route through the substrate-primitive `RestartStrategy::as_str` \
10395             accessor rather than through a per-call-site `.to_owned()` / \
10396             `String::from(strategy.as_str())` detour"
10397        );
10398        for &variant in RestartStrategy::ALL {
10399            let emitted: String = variant.into();
10400            let re_parsed: Result<RestartStrategy, ()> =
10401                <RestartStrategy as TryFrom<&str>>::try_from(emitted.as_str());
10402            assert_eq!(
10403                re_parsed,
10404                Ok(variant),
10405                "trait-idiomatic owned-`String` forward-projection + \
10406                 reverse-projection axis pair must round-trip \
10407                 RestartStrategy::{variant:?} through `.into::<String>()` \
10408                 and back through `TryFrom<&str>` on the owned-`String`'s \
10409                 String::as_str borrow — a break signals the owned-`String` \
10410                 forward-emit and reverse-parse axes have drifted onto \
10411                 different vocabularies"
10412            );
10413        }
10414    }
10415
10416    #[test]
10417    fn restart_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor() {
10418        // Fail-before-pass-after byte-parity pin on the newly lifted
10419        // `impl From<&RestartStrategy> for String` — asserts the
10420        // borrowed-input owned-`String`-returning standard-library trait
10421        // impl and the substrate-primitive [`RestartStrategy::as_str`]
10422        // `pub const fn` accessor resolve to the same four-arm emit-set
10423        // across every arm the exhaustive [`RestartStrategy::ALL`] slice
10424        // enumerates. Rust's standard library does not carry a blanket
10425        // `impl<T: AsRef<str>> From<&T> for String` (nor an
10426        // `impl<T: fmt::Display> From<&T> for String`), so the
10427        // borrowed-input owned-`String` forward-projection axis is a
10428        // distinct trait-idiomatic surface that a
10429        // `let key: String = (&strategy).into();`-shaped call site
10430        // reaches through this impl and no other — the paired sibling
10431        // `From<RestartStrategy> for String` impl forces every
10432        // borrowed-input call site through an explicit `Copy` deref
10433        // (`String::from(*strategy)`) or an `.as_str().to_owned()` /
10434        // `.to_string()` detour.
10435        for &variant in RestartStrategy::ALL {
10436            let via_trait: String = <String as From<&RestartStrategy>>::from(&variant);
10437            let via_method: &'static str = variant.as_str();
10438            assert_eq!(
10439                via_trait.as_str(),
10440                via_method,
10441                "From<&RestartStrategy> for String impl must round-trip \
10442                 &RestartStrategy::{variant:?} to the same lifted \
10443                 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
10444                 returns — divergence signals a silent detour off the \
10445                 substrate-primitive accessor"
10446            );
10447            let via_into: String = (&variant).into();
10448            assert_eq!(
10449                via_into.as_str(),
10450                via_method,
10451                "Into<String>::into on &RestartStrategy::{variant:?} must \
10452                 byte-equal RestartStrategy::as_str on the same input — the \
10453                 blanket-derived Into shape must resolve to the same as_str \
10454                 dispatch as the explicit From impl"
10455            );
10456        }
10457    }
10458
10459    #[test]
10460    fn restart_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm() {
10461        // Cross-axis partition pin: the newly lifted trait-idiomatic
10462        // borrowed-input owned-`String` `From<&RestartStrategy> for
10463        // String` (this lift), the paired owned-input owned-`String`
10464        // `From<RestartStrategy> for String` (7baa18a), the paired
10465        // borrowed-input owned-`&'static str` `From<&RestartStrategy>
10466        // for &'static str` (e941836), and the paired owned-input
10467        // owned-`&'static str` `From<RestartStrategy> for &'static str`
10468        // (523157d) — every corner of the `{Self, &Self} × {&'static
10469        // str, String}` 2×2 trait-idiomatic projection family — must
10470        // resolve identically on every arm, locking the four
10471        // return-shape × input-shape paths together so any future
10472        // detour trips at caixa-core test time. Also byte-parity
10473        // witness against the sibling [`ToString::to_string`] surface
10474        // routed through [`std::fmt::Display`] and a direct round-trip
10475        // witness through the paired trait-idiomatic reverse
10476        // [`TryFrom<&str>`] axis on the owned-`String`'s
10477        // [`String::as_str`] borrow that closes the two-way
10478        // `&Self → String → Self` round-trip on the trait-idiomatic
10479        // borrowed-input owned-`String` forward + reverse axis pair.
10480        for &variant in RestartStrategy::ALL {
10481            let borrowed_string: String = <String as From<&RestartStrategy>>::from(&variant);
10482            let owned_string: String = <String as From<RestartStrategy>>::from(variant);
10483            let borrowed_static: &'static str =
10484                <&'static str as From<&RestartStrategy>>::from(&variant);
10485            let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
10486            assert_eq!(
10487                borrowed_string, owned_string,
10488                "From<&RestartStrategy> for String and From<RestartStrategy> \
10489                 for String must resolve identically on \
10490                 RestartStrategy::{variant:?} — divergence signals the \
10491                 borrowed-input and owned-input owned-`String` \
10492                 forward-projection input-shape paths have drifted onto \
10493                 different emit-sets"
10494            );
10495            assert_eq!(
10496                borrowed_string.as_str(),
10497                borrowed_static,
10498                "From<&RestartStrategy> for String and From<&RestartStrategy> \
10499                 for &'static str must resolve identically on \
10500                 RestartStrategy::{variant:?} — divergence signals the \
10501                 borrowed-input `&'static str` and owned-`String` \
10502                 return-shape paths have drifted onto different emit-sets"
10503            );
10504            assert_eq!(
10505                borrowed_string.as_str(),
10506                owned_static,
10507                "From<&RestartStrategy> for String and From<RestartStrategy> \
10508                 for &'static str must resolve identically on \
10509                 RestartStrategy::{variant:?} — divergence signals a break \
10510                 in the diagonal corner of the {{Self, &Self}} × \
10511                 {{&'static str, String}} 2×2 trait-idiomatic \
10512                 projection family"
10513            );
10514            let via_to_string: String = variant.to_string();
10515            assert_eq!(
10516                borrowed_string, via_to_string,
10517                "From<&RestartStrategy> for String must byte-equal \
10518                 RestartStrategy::to_string on RestartStrategy::{variant:?} — \
10519                 divergence signals the trait-idiomatic borrowed-input \
10520                 owned-`String` forward-projection axis and the \
10521                 ToString-through-Display axis have drifted onto different \
10522                 emit-sets"
10523            );
10524        }
10525        let via_iter: Vec<String> = RestartStrategy::ALL.iter().map(String::from).collect();
10526        let via_method: Vec<String> = RestartStrategy::ALL
10527            .iter()
10528            .map(|s| s.as_str().to_owned())
10529            .collect();
10530        assert_eq!(
10531            via_iter, via_method,
10532            "`.iter().map(String::from)` over RestartStrategy::ALL — a \
10533             call site whose iteration axis holds `&RestartStrategy` by \
10534             construction — must byte-equal `.iter().map(|s| \
10535             s.as_str().to_owned())` on every arm — the borrowed-input \
10536             owned-`String` `From<&RestartStrategy> for String` axis is \
10537             what makes the `String::from` composition route through the \
10538             substrate-primitive `RestartStrategy::as_str` accessor \
10539             without a spurious `Copy` deref (which would only be \
10540             reachable through the owned-input `From<RestartStrategy> for \
10541             String` axis by first calling `.copied()` on the iterator)"
10542        );
10543        for &variant in RestartStrategy::ALL {
10544            let emitted: String = (&variant).into();
10545            let re_parsed: Result<RestartStrategy, ()> =
10546                <RestartStrategy as TryFrom<&str>>::try_from(emitted.as_str());
10547            assert_eq!(
10548                re_parsed,
10549                Ok(variant),
10550                "trait-idiomatic borrowed-input owned-`String` \
10551                 forward-projection + reverse-projection axis pair must \
10552                 round-trip &RestartStrategy::{variant:?} through \
10553                 `.into::<String>()` on the borrowed-input surface and \
10554                 back through `TryFrom<&str>` on the owned-`String`'s \
10555                 String::as_str borrow — a break signals the \
10556                 borrowed-input owned-`String` forward-emit and \
10557                 reverse-parse axes have drifted onto different \
10558                 vocabularies"
10559            );
10560        }
10561    }
10562
10563    #[test]
10564    fn restart_strategy_from_into_static_cow_str_routes_through_as_str_accessor() {
10565        // Fail-before-pass-after byte-parity pin on the newly lifted
10566        // `impl From<RestartStrategy> for std::borrow::Cow<'static, str>` —
10567        // asserts the standard-library trait impl and the substrate-
10568        // primitive [`super::RestartStrategy::as_str`] `pub const fn`
10569        // accessor resolve to the same four-arm emit-set across every
10570        // arm the exhaustive [`super::RestartStrategy::ALL`] slice
10571        // enumerates. Rust's standard library does not carry a blanket
10572        // `impl<T: AsRef<str>> From<T> for Cow<'static, str>` (nor an
10573        // `impl<T: fmt::Display> From<T> for Cow<'static, str>`), so
10574        // the `Cow<'static, str>` forward-projection axis is a
10575        // distinct trait-idiomatic surface that a
10576        // `let key: Cow<'static, str> = strategy.into();`-shaped call
10577        // site reaches through this impl and no other — the paired
10578        // sibling `From<RestartStrategy> for &'static str` and
10579        // `From<RestartStrategy> for String` impls force every
10580        // `Cow<'static, str>`-parameterized call site through a
10581        // `Cow::Borrowed(strategy.as_str())` /
10582        // `Cow::Owned(strategy.to_string())` composition whose type
10583        // bounds have no compile-time link back to the substrate
10584        // primitive.
10585        //
10586        // Also asserts the projection lands on the zero-alloc
10587        // [`std::borrow::Cow::Borrowed`] arm (not the
10588        // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
10589        // [`super::RestartStrategy::as_str`] accessor's `&'static str`
10590        // return lifetime by construction makes the borrowed arm the
10591        // type-correct projection with no runtime allocation. Any
10592        // future silent detour that routes the impl through the owned
10593        // arm (an accidental `Cow::Owned(strategy.to_string())` rewrite
10594        // that would allocate on every call site where the
10595        // `&'static str` return of [`super::RestartStrategy::as_str`]
10596        // makes the zero-alloc borrowed projection type-correct) trips
10597        // at caixa-core test time under the
10598        // [`std::borrow::Cow::Borrowed`] discriminator witness rather
10599        // than at a downstream `Cow<'static, str>`-bound consumer's
10600        // silent allocation.
10601        //
10602        // First peer on the substrate-wide trait-idiomatic
10603        // [`std::borrow::Cow<'static, str>`] forward-projection family
10604        // to extend the axis off the top-level [`super::CaixaKind`]
10605        // enum (99c1735 owned-input, d45c409 borrowed-input) onto the
10606        // first M2 OTP-shape closed-set fieldless typed enum on the
10607        // caixa surface.
10608        for &variant in RestartStrategy::ALL {
10609            let via_trait: std::borrow::Cow<'static, str> =
10610                <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
10611            let via_method: &'static str = variant.as_str();
10612            assert_eq!(
10613                via_trait.as_ref(),
10614                via_method,
10615                "From<RestartStrategy> for Cow<'static, str> impl must \
10616                 round-trip RestartStrategy::{variant:?} to the same \
10617                 lifted SUPERVISOR_ESTRATEGIA_* const \
10618                 RestartStrategy::as_str returns — divergence signals a \
10619                 silent detour off the substrate-primitive accessor"
10620            );
10621            assert!(
10622                matches!(via_trait, std::borrow::Cow::Borrowed(_)),
10623                "From<RestartStrategy> for Cow<'static, str> impl must \
10624                 land on the zero-alloc Cow::Borrowed arm on \
10625                 RestartStrategy::{variant:?} — a Cow::Owned outcome \
10626                 signals the projection has silently allocated where \
10627                 the substrate-primitive RestartStrategy::as_str \
10628                 `&'static str` return makes the borrowed arm the \
10629                 type-correct projection"
10630            );
10631            let via_into: std::borrow::Cow<'static, str> = variant.into();
10632            assert_eq!(
10633                via_into.as_ref(),
10634                via_method,
10635                "Into<Cow<'static, str>>::into on \
10636                 RestartStrategy::{variant:?} must byte-equal \
10637                 RestartStrategy::as_str on the same input — the \
10638                 blanket-derived Into shape must resolve to the same \
10639                 as_str dispatch as the explicit From impl"
10640            );
10641            assert!(
10642                matches!(via_into, std::borrow::Cow::Borrowed(_)),
10643                "Into<Cow<'static, str>>::into on \
10644                 RestartStrategy::{variant:?} must land on the \
10645                 zero-alloc Cow::Borrowed arm — the blanket-derived \
10646                 Into shape must resolve to the same Cow::Borrowed \
10647                 dispatch as the explicit From impl"
10648            );
10649        }
10650    }
10651
10652    #[test]
10653    fn restart_strategy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
10654        // Cross-axis partition pin: the newly lifted trait-idiomatic
10655        // `From<RestartStrategy> for std::borrow::Cow<'static, str>`
10656        // (this lift), the paired owned-input `From<RestartStrategy>
10657        // for &'static str` (523157d), and the paired owned-input
10658        // `From<RestartStrategy> for String` (7baa18a) forward
10659        // projections must resolve identically on every arm, locking
10660        // the three return-shape paths together by construction so any
10661        // future detour trips at caixa-core test time. Also byte-parity
10662        // witness against the sibling [`ToString::to_string`] surface
10663        // routed through [`std::fmt::Display`] — every owned-heap-
10664        // string path (the `Cow::Owned` promotion of this axis's
10665        // `.into_owned()`, `From<RestartStrategy> for String`, and
10666        // `.to_string()`) resolves to the same lifted
10667        // [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const per arm.
10668        //
10669        // Then a `.iter().copied().map(std::borrow::Cow::from)` pipe
10670        // witness over [`super::RestartStrategy::ALL`] that
10671        // materializes the four-arm accept-set through the
10672        // [`std::borrow::Cow<'static, str>`] axis alone — the exact
10673        // shape a future `axum::response::IntoResponse` per-strategy
10674        // rejection-body composer, a future M4 admission-webhook
10675        // per-strategy rejection-reason emitter whose typing rules out
10676        // the sibling [`AsRef<str>`] borrowed return, or a future
10677        // substrate-wide per-strategy diagnostic surface that binds
10678        // through a [`Cow<'static, str>`] boundary reaches through.
10679        // The pipe witness also pins the zero-alloc discipline: every
10680        // element in the collected vector satisfies the
10681        // [`std::borrow::Cow::Borrowed`] arm predicate, so a future
10682        // accidental silent-allocation regression on the pipe's
10683        // iteration axis is a caixa-core-test-time failure.
10684        for &variant in RestartStrategy::ALL {
10685            let via_cow: std::borrow::Cow<'static, str> =
10686                <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
10687            let via_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
10688            let via_string: String = <String as From<RestartStrategy>>::from(variant);
10689            assert_eq!(
10690                via_cow.as_ref(),
10691                via_static,
10692                "From<RestartStrategy> for Cow<'static, str> and \
10693                 From<RestartStrategy> for &'static str must resolve \
10694                 identically on RestartStrategy::{variant:?} — \
10695                 divergence signals the Cow<'static, str> and \
10696                 &'static str return-shape paths have drifted onto \
10697                 different emit-sets"
10698            );
10699            assert_eq!(
10700                via_cow.as_ref(),
10701                via_string.as_str(),
10702                "From<RestartStrategy> for Cow<'static, str> and \
10703                 From<RestartStrategy> for String must resolve \
10704                 identically on RestartStrategy::{variant:?} — \
10705                 divergence signals the Cow<'static, str> and String \
10706                 return-shape paths have drifted onto different \
10707                 emit-sets"
10708            );
10709            let via_to_string: String = variant.to_string();
10710            assert_eq!(
10711                via_cow.as_ref(),
10712                via_to_string.as_str(),
10713                "From<RestartStrategy> for Cow<'static, str> must \
10714                 byte-equal RestartStrategy::to_string on \
10715                 RestartStrategy::{variant:?} — divergence signals the \
10716                 trait-idiomatic Cow<'static, str> forward-projection \
10717                 axis and the ToString-through-Display axis have \
10718                 drifted onto different emit-sets"
10719            );
10720        }
10721        let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
10722            .iter()
10723            .copied()
10724            .map(std::borrow::Cow::from)
10725            .collect();
10726        let via_method: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
10727            .iter()
10728            .map(|s| std::borrow::Cow::Borrowed(s.as_str()))
10729            .collect();
10730        assert_eq!(
10731            via_iter, via_method,
10732            "`.iter().copied().map(Cow::from)` over \
10733             RestartStrategy::ALL must byte-equal `.iter().map(|s| \
10734             Cow::Borrowed(s.as_str()))` on every arm — the \
10735             trait-idiomatic `From<RestartStrategy> for Cow<'static, \
10736             str>` axis is what makes the `Cow::from` composition \
10737             route through the substrate-primitive \
10738             `RestartStrategy::as_str` accessor with the zero-alloc \
10739             Cow::Borrowed arm by construction, rather than a \
10740             per-call-site `Cow::Owned(strategy.to_string())` \
10741             allocation"
10742        );
10743        for cow in &via_iter {
10744            assert!(
10745                matches!(cow, std::borrow::Cow::Borrowed(_)),
10746                "every element of the \
10747                 .iter().copied().map(Cow::from) pipe over \
10748                 RestartStrategy::ALL must land on the zero-alloc \
10749                 Cow::Borrowed arm — a Cow::Owned outcome on any arm \
10750                 signals the pipe's iteration axis has silently \
10751                 allocated where the substrate-primitive \
10752                 RestartStrategy::as_str `&'static str` return makes \
10753                 the borrowed arm the type-correct projection"
10754            );
10755        }
10756    }
10757
10758    #[test]
10759    fn restart_strategy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor() {
10760        // Fail-before-pass-after byte-parity pin on the newly lifted
10761        // `impl From<&RestartStrategy> for std::borrow::Cow<'static, str>` —
10762        // asserts the borrowed-input standard-library trait impl and
10763        // the substrate-primitive [`super::RestartStrategy::as_str`]
10764        // `pub const fn` accessor resolve to the same four-arm emit-
10765        // set across every arm the exhaustive
10766        // [`super::RestartStrategy::ALL`] slice enumerates. Rust's
10767        // standard library does not carry a blanket
10768        // `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor a
10769        // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`), so
10770        // the borrowed-input `Cow<'static, str>` forward-projection
10771        // axis is a distinct trait-idiomatic surface that a
10772        // `let key: Cow<'static, str> = (&strategy).into();`-shaped
10773        // call site or a
10774        // `RestartStrategy::ALL.iter().map(Cow::from)`-shaped pipe
10775        // reaches through this impl and no other — the paired owned-
10776        // input `From<RestartStrategy> for Cow<'static, str>` impl
10777        // (7dd28b3) forces every borrowed-input call site through an
10778        // explicit `Copy` deref (`Cow::from(*strategy)`) or a
10779        // `Cow::Borrowed(strategy.as_str())` open-code whose type
10780        // bounds have no compile-time link back to the substrate
10781        // primitive.
10782        //
10783        // Also asserts the projection lands on the zero-alloc
10784        // [`std::borrow::Cow::Borrowed`] arm (not the
10785        // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
10786        // [`super::RestartStrategy::as_str`] accessor's `&'static str`
10787        // return lifetime by construction makes the borrowed arm the
10788        // type-correct projection with no runtime allocation on the
10789        // borrowed-input surface just as on the paired owned-input
10790        // surface.
10791        //
10792        // Second peer on the substrate-wide trait-idiomatic
10793        // [`std::borrow::Cow<'static, str>`] forward-projection family
10794        // on this enum — closes the `{Self, &Self}` input-shape
10795        // corner of the [`Cow<'static, str>`] axis on the first M2
10796        // OTP-shape closed-set fieldless typed enum peer on the caixa
10797        // surface (`:supervisor :estrategia`), exactly as d45c409
10798        // closed it on the top-level [`super::CaixaKind`] one commit
10799        // after the owning half (99c1735) landed. Every future
10800        // closed-set fieldless typed enum peer on the substrate is a
10801        // future target of the campaign.
10802        for &variant in RestartStrategy::ALL {
10803            let via_trait: std::borrow::Cow<'static, str> =
10804                <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&variant);
10805            let via_method: &'static str = variant.as_str();
10806            assert_eq!(
10807                via_trait.as_ref(),
10808                via_method,
10809                "From<&RestartStrategy> for Cow<'static, str> impl must \
10810                 round-trip &RestartStrategy::{variant:?} to the same \
10811                 lifted SUPERVISOR_ESTRATEGIA_* const \
10812                 RestartStrategy::as_str returns — divergence signals a \
10813                 silent detour off the substrate-primitive accessor"
10814            );
10815            assert!(
10816                matches!(via_trait, std::borrow::Cow::Borrowed(_)),
10817                "From<&RestartStrategy> for Cow<'static, str> impl must \
10818                 land on the zero-alloc Cow::Borrowed arm on \
10819                 &RestartStrategy::{variant:?} — a Cow::Owned outcome \
10820                 signals the projection has silently allocated where \
10821                 the substrate-primitive RestartStrategy::as_str \
10822                 `&'static str` return makes the borrowed arm the \
10823                 type-correct projection"
10824            );
10825            let via_into: std::borrow::Cow<'static, str> = (&variant).into();
10826            assert_eq!(
10827                via_into.as_ref(),
10828                via_method,
10829                "Into<Cow<'static, str>>::into on \
10830                 &RestartStrategy::{variant:?} must byte-equal \
10831                 RestartStrategy::as_str on the same input — the \
10832                 blanket-derived Into shape must resolve to the same \
10833                 as_str dispatch as the explicit From impl"
10834            );
10835            assert!(
10836                matches!(via_into, std::borrow::Cow::Borrowed(_)),
10837                "Into<Cow<'static, str>>::into on \
10838                 &RestartStrategy::{variant:?} must land on the \
10839                 zero-alloc Cow::Borrowed arm — the blanket-derived \
10840                 Into shape must resolve to the same Cow::Borrowed \
10841                 dispatch as the explicit From impl"
10842            );
10843        }
10844    }
10845
10846    #[test]
10847    fn restart_strategy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
10848        // Cross-axis partition pin: the newly lifted trait-idiomatic
10849        // borrowed-input `From<&RestartStrategy> for
10850        // std::borrow::Cow<'static, str>` (this lift), the paired
10851        // owned-input `From<RestartStrategy> for
10852        // std::borrow::Cow<'static, str>` (7dd28b3), the paired
10853        // borrowed-input owned-`&'static str` `From<&RestartStrategy>
10854        // for &'static str`, and the paired borrowed-input owned-
10855        // `String` `From<&RestartStrategy> for String` must resolve
10856        // identically on every arm, locking the four
10857        // return-shape × input-shape paths together by construction so
10858        // any future detour trips at caixa-core test time. Also byte-
10859        // parity witness against the sibling [`ToString::to_string`]
10860        // surface routed through [`std::fmt::Display`] — every owned-
10861        // heap-string path (this axis's `.into_owned()` promotion, the
10862        // paired [`From<&RestartStrategy> for String`], and
10863        // `.to_string()`) resolves to the same lifted
10864        // [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const per arm.
10865        //
10866        // Then a `.iter().map(std::borrow::Cow::from)` pipe witness
10867        // over [`super::RestartStrategy::ALL`] — whose iterator yields
10868        // `&RestartStrategy` by construction, so the borrowed-input
10869        // [`Cow<'static, str>`] axis is what routes the pipe through
10870        // the substrate-primitive [`super::RestartStrategy::as_str`]
10871        // accessor without a spurious [`Copy`] deref (which would only
10872        // be reachable through the owned-input
10873        // [`From<RestartStrategy> for Cow<'static, str>`] axis by
10874        // first calling `.copied()` on the iterator). The pipe witness
10875        // also pins the zero-alloc discipline: every element in the
10876        // collected vector satisfies the [`std::borrow::Cow::Borrowed`]
10877        // arm predicate, so a future accidental silent-allocation
10878        // regression on the pipe's iteration axis is a caixa-core-
10879        // test-time failure.
10880        for &strategy in RestartStrategy::ALL {
10881            let borrowed_cow: std::borrow::Cow<'static, str> =
10882                <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&strategy);
10883            let owned_cow: std::borrow::Cow<'static, str> =
10884                <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(strategy);
10885            let borrowed_static: &'static str =
10886                <&'static str as From<&RestartStrategy>>::from(&strategy);
10887            let borrowed_string: String = <String as From<&RestartStrategy>>::from(&strategy);
10888            assert_eq!(
10889                borrowed_cow, owned_cow,
10890                "From<&RestartStrategy> for Cow<'static, str> and \
10891                 From<RestartStrategy> for Cow<'static, str> must \
10892                 resolve identically on RestartStrategy::{strategy:?} — \
10893                 divergence signals the borrowed-input and owned-input \
10894                 Cow<'static, str> forward-projection input-shape \
10895                 paths have drifted onto different emit-sets"
10896            );
10897            assert_eq!(
10898                borrowed_cow.as_ref(),
10899                borrowed_static,
10900                "From<&RestartStrategy> for Cow<'static, str> and \
10901                 From<&RestartStrategy> for &'static str must resolve \
10902                 identically on RestartStrategy::{strategy:?} — \
10903                 divergence signals the borrowed-input Cow<'static, \
10904                 str> and &'static str return-shape paths have drifted \
10905                 onto different emit-sets"
10906            );
10907            assert_eq!(
10908                borrowed_cow.as_ref(),
10909                borrowed_string.as_str(),
10910                "From<&RestartStrategy> for Cow<'static, str> and \
10911                 From<&RestartStrategy> for String must resolve \
10912                 identically on RestartStrategy::{strategy:?} — \
10913                 divergence signals the borrowed-input Cow<'static, \
10914                 str> and owned-`String` return-shape paths have \
10915                 drifted onto different emit-sets"
10916            );
10917            let via_to_string: String = strategy.to_string();
10918            assert_eq!(
10919                borrowed_cow.as_ref(),
10920                via_to_string.as_str(),
10921                "From<&RestartStrategy> for Cow<'static, str> must \
10922                 byte-equal RestartStrategy::to_string on \
10923                 RestartStrategy::{strategy:?} — divergence signals \
10924                 the trait-idiomatic borrowed-input Cow<'static, str> \
10925                 forward-projection axis and the ToString-through-\
10926                 Display axis have drifted onto different emit-sets"
10927            );
10928        }
10929        let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
10930            .iter()
10931            .map(std::borrow::Cow::from)
10932            .collect();
10933        let via_method: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
10934            .iter()
10935            .map(|s| std::borrow::Cow::Borrowed(s.as_str()))
10936            .collect();
10937        assert_eq!(
10938            via_iter, via_method,
10939            "`.iter().map(Cow::from)` over RestartStrategy::ALL — a \
10940             call site whose iteration axis holds `&RestartStrategy` \
10941             by construction — must byte-equal `.iter().map(|s| \
10942             Cow::Borrowed(s.as_str()))` on every arm — the borrowed-\
10943             input Cow<'static, str> `From<&RestartStrategy> for \
10944             Cow<'static, str>` axis is what makes the `Cow::from` \
10945             composition route through the substrate-primitive \
10946             `RestartStrategy::as_str` accessor with the zero-alloc \
10947             Cow::Borrowed arm by construction and without a spurious \
10948             `Copy` deref (which would only be reachable through the \
10949             owned-input `From<RestartStrategy> for Cow<'static, str>` \
10950             axis by first calling `.copied()` on the iterator)"
10951        );
10952        for cow in &via_iter {
10953            assert!(
10954                matches!(cow, std::borrow::Cow::Borrowed(_)),
10955                "every element of the .iter().map(Cow::from) pipe \
10956                 over RestartStrategy::ALL must land on the zero-\
10957                 alloc Cow::Borrowed arm — a Cow::Owned outcome on \
10958                 any arm signals the pipe's iteration axis has \
10959                 silently allocated where the substrate-primitive \
10960                 RestartStrategy::as_str `&'static str` return makes \
10961                 the borrowed arm the type-correct projection"
10962            );
10963        }
10964    }
10965
10966    #[test]
10967    fn restart_strategy_from_into_box_str_routes_through_as_str_accessor() {
10968        // Fail-before-pass-after byte-parity pin on the newly lifted
10969        // `impl From<RestartStrategy> for Box<str>` — asserts the
10970        // owned-input standard-library trait impl and the
10971        // substrate-primitive [`super::RestartStrategy::as_str`]
10972        // `pub const fn` accessor resolve to the same four-arm emit-
10973        // set across every arm the exhaustive
10974        // [`super::RestartStrategy::ALL`] slice enumerates. Opens the
10975        // substrate-wide `Box<str>` forward-projection campaign tier
10976        // on the first M2 OTP-shape closed-set fieldless typed enum
10977        // peer on the caixa surface (`:supervisor :estrategia`),
10978        // immediately after the paired `Cow<'static, str>` axis
10979        // (7dd28b3 / ee577fd) closed the
10980        // `{Self, &Self} × {&'static str, String, Cow<'static, str>}`
10981        // 2×3 corner on this enum. Rust's standard library carries
10982        // `impl From<&str> for Box<str>` and
10983        // `impl From<String> for Box<str>` but no blanket
10984        // `impl<T: AsRef<str>> From<T> for Box<str>`, so this axis is
10985        // a distinct trait-idiomatic surface that a
10986        // `let key: Box<str> = strategy.into();`-shaped call site
10987        // reaches through this impl and no other — a paired
10988        // `Box::from(strategy.as_str())` open-code has no compile-
10989        // time link back to the substrate primitive.
10990        for &variant in RestartStrategy::ALL {
10991            let via_trait: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
10992            let via_method: &'static str = variant.as_str();
10993            assert_eq!(
10994                via_trait.as_ref(),
10995                via_method,
10996                "From<RestartStrategy> for Box<str> impl must round-\
10997                 trip RestartStrategy::{variant:?} to the same lifted \
10998                 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
10999                 returns — divergence signals a silent detour off the \
11000                 substrate-primitive accessor"
11001            );
11002            let via_into: Box<str> = variant.into();
11003            assert_eq!(
11004                via_into.as_ref(),
11005                via_method,
11006                "Into<Box<str>>::into on RestartStrategy::{variant:?} \
11007                 must byte-equal RestartStrategy::as_str on the same \
11008                 input — the blanket-derived Into shape must resolve \
11009                 to the same as_str dispatch as the explicit From impl"
11010            );
11011        }
11012    }
11013
11014    #[test]
11015    fn restart_strategy_from_borrowed_into_box_str_routes_through_as_str_accessor() {
11016        // Fail-before-pass-after byte-parity pin on the newly lifted
11017        // `impl From<&RestartStrategy> for Box<str>` — asserts the
11018        // borrowed-input standard-library trait impl and the
11019        // substrate-primitive [`super::RestartStrategy::as_str`]
11020        // `pub const fn` accessor resolve to the same four-arm emit-
11021        // set across every arm the exhaustive
11022        // [`super::RestartStrategy::ALL`] slice enumerates. Rust's
11023        // standard library does not carry a blanket
11024        // `impl<T: AsRef<str>> From<&T> for Box<str>` (nor a
11025        // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`),
11026        // so the borrowed-input `Box<str>` forward-projection axis
11027        // is a distinct trait-idiomatic surface that a
11028        // `let key: Box<str> = (&strategy).into();`-shaped call site
11029        // or a `RestartStrategy::ALL.iter().map(Box::<str>::from)`-
11030        // shaped pipe reaches through this impl and no other — the
11031        // paired owned-input `From<RestartStrategy> for Box<str>`
11032        // impl (69ef45c) forces every borrowed-input call site
11033        // through an explicit `Copy` deref
11034        // (`Box::<str>::from((*strategy).as_str())`) or a
11035        // `Box::<str>::from(strategy.as_str())` open-code whose
11036        // type bounds have no compile-time link back to the
11037        // substrate primitive.
11038        //
11039        // Second peer on the substrate-wide trait-idiomatic
11040        // [`Box<str>`] forward-projection family on this enum —
11041        // closes the `{Self, &Self}` input-shape corner of the
11042        // [`Box<str>`] axis on the first M2 OTP-shape closed-set
11043        // fieldless typed enum peer on the caixa surface
11044        // (`:supervisor :estrategia`), exactly as ee577fd closed
11045        // the paired [`Cow<'static, str>`] axis one commit after
11046        // its owning half (7dd28b3) landed. Every future closed-
11047        // set fieldless typed enum peer on the substrate is a
11048        // future target of the campaign.
11049        //
11050        // Also byte-parity witness against the paired owned-input
11051        // [`From<RestartStrategy> for Box<str>`] and the sibling
11052        // borrowed-input [`From<&RestartStrategy> for &'static str`],
11053        // [`From<&RestartStrategy> for String`], and
11054        // [`From<&RestartStrategy> for Cow<'static, str>`]
11055        // return-shape axes — locking the four
11056        // return-shape × input-shape paths together by construction
11057        // so any future detour trips at caixa-core test time. Then a
11058        // `.iter().map(Box::<str>::from)` pipe witness over
11059        // [`super::RestartStrategy::ALL`] — whose iterator yields
11060        // `&RestartStrategy` by construction, so the borrowed-input
11061        // [`Box<str>`] axis is what routes the pipe through the
11062        // substrate-primitive [`super::RestartStrategy::as_str`]
11063        // accessor without a spurious [`Copy`] deref (which would
11064        // only be reachable through the owned-input
11065        // [`From<RestartStrategy> for Box<str>`] axis by first
11066        // calling `.copied()` on the iterator).
11067        for &variant in RestartStrategy::ALL {
11068            let via_trait: Box<str> = <Box<str> as From<&RestartStrategy>>::from(&variant);
11069            let via_method: &'static str = variant.as_str();
11070            assert_eq!(
11071                via_trait.as_ref(),
11072                via_method,
11073                "From<&RestartStrategy> for Box<str> impl must \
11074                 round-trip &RestartStrategy::{variant:?} to the same \
11075                 lifted SUPERVISOR_ESTRATEGIA_* const \
11076                 RestartStrategy::as_str returns — divergence signals \
11077                 a silent detour off the substrate-primitive accessor"
11078            );
11079            let via_into: Box<str> = (&variant).into();
11080            assert_eq!(
11081                via_into.as_ref(),
11082                via_method,
11083                "Into<Box<str>>::into on &RestartStrategy::{variant:?} \
11084                 must byte-equal RestartStrategy::as_str on the same \
11085                 input — the blanket-derived Into shape must resolve \
11086                 to the same as_str dispatch as the explicit From impl"
11087            );
11088            let owned_box: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
11089            assert_eq!(
11090                via_trait, owned_box,
11091                "From<&RestartStrategy> for Box<str> and \
11092                 From<RestartStrategy> for Box<str> must resolve \
11093                 identically on RestartStrategy::{variant:?} — \
11094                 divergence signals the borrowed-input and owned-input \
11095                 Box<str> forward-projection input-shape paths have \
11096                 drifted onto different emit-sets"
11097            );
11098            let borrowed_static: &'static str =
11099                <&'static str as From<&RestartStrategy>>::from(&variant);
11100            assert_eq!(
11101                via_trait.as_ref(),
11102                borrowed_static,
11103                "From<&RestartStrategy> for Box<str> and \
11104                 From<&RestartStrategy> for &'static str must resolve \
11105                 identically on RestartStrategy::{variant:?} — \
11106                 divergence signals the borrowed-input Box<str> and \
11107                 &'static str return-shape paths have drifted onto \
11108                 different emit-sets"
11109            );
11110            let borrowed_string: String = <String as From<&RestartStrategy>>::from(&variant);
11111            assert_eq!(
11112                via_trait.as_ref(),
11113                borrowed_string.as_str(),
11114                "From<&RestartStrategy> for Box<str> and \
11115                 From<&RestartStrategy> for String must resolve \
11116                 identically on RestartStrategy::{variant:?} — \
11117                 divergence signals the borrowed-input Box<str> and \
11118                 owned-`String` return-shape paths have drifted onto \
11119                 different emit-sets"
11120            );
11121            let borrowed_cow: std::borrow::Cow<'static, str> =
11122                <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&variant);
11123            assert_eq!(
11124                via_trait.as_ref(),
11125                borrowed_cow.as_ref(),
11126                "From<&RestartStrategy> for Box<str> and \
11127                 From<&RestartStrategy> for Cow<'static, str> must \
11128                 resolve identically on RestartStrategy::{variant:?} — \
11129                 divergence signals the borrowed-input Box<str> and \
11130                 Cow<'static, str> return-shape paths have drifted \
11131                 onto different emit-sets"
11132            );
11133        }
11134        let via_iter: Vec<Box<str>> = RestartStrategy::ALL.iter().map(Box::<str>::from).collect();
11135        let via_method: Vec<Box<str>> = RestartStrategy::ALL
11136            .iter()
11137            .map(|s| Box::<str>::from(s.as_str()))
11138            .collect();
11139        assert_eq!(
11140            via_iter, via_method,
11141            "`.iter().map(Box::<str>::from)` over \
11142             RestartStrategy::ALL — a call site whose iteration axis \
11143             holds `&RestartStrategy` by construction — must byte-\
11144             equal `.iter().map(|s| Box::<str>::from(s.as_str()))` \
11145             on every arm — the borrowed-input Box<str> \
11146             `From<&RestartStrategy> for Box<str>` axis is what \
11147             makes the `Box::<str>::from` composition route through \
11148             the substrate-primitive `RestartStrategy::as_str` \
11149             accessor without a spurious `Copy` deref (which would \
11150             only be reachable through the owned-input \
11151             `From<RestartStrategy> for Box<str>` axis by first \
11152             calling `.copied()` on the iterator)"
11153        );
11154    }
11155
11156    #[test]
11157    fn restart_strategy_from_into_arc_str_routes_through_as_str_accessor() {
11158        // Fail-before-pass-after byte-parity pin on the newly lifted
11159        // `impl From<RestartStrategy> for std::sync::Arc<str>` — asserts
11160        // the owned-input standard-library trait impl and the
11161        // substrate-primitive [`super::RestartStrategy::as_str`]
11162        // `pub const fn` accessor resolve to the same four-arm emit-
11163        // set across every arm the exhaustive
11164        // [`super::RestartStrategy::ALL`] slice enumerates. Opens the
11165        // substrate-wide [`std::sync::Arc<str>`] forward-projection
11166        // campaign tier on the first M2 OTP-shape closed-set fieldless
11167        // typed enum peer on the caixa surface
11168        // (`:supervisor :estrategia`), immediately after the paired
11169        // [`Box<str>`] axis (69ef45c / 59ae5dc) closed the
11170        // `{Self, &Self} × {&'static str, String, Cow<'static, str>,
11171        // Box<str>}` 2×4 corner on this enum. Rust's standard library
11172        // carries `impl From<&str> for std::sync::Arc<str>` and
11173        // `impl From<String> for std::sync::Arc<str>` but no blanket
11174        // `impl<T: AsRef<str>> From<T> for std::sync::Arc<str>` (nor
11175        // an `impl<T: fmt::Display> From<T> for std::sync::Arc<str>`),
11176        // so this axis is a distinct trait-idiomatic surface that a
11177        // `let key: std::sync::Arc<str> = strategy.into();`-shaped call
11178        // site reaches through this impl and no other — a paired
11179        // `std::sync::Arc::<str>::from(strategy.as_str())` open-code
11180        // has no compile-time link back to the substrate primitive,
11181        // and a two-step `std::sync::Arc::<str>::from(String::from(
11182        // strategy))` composition through the owned-`String` axis
11183        // allocates twice (once into the intermediate `String`, once
11184        // into the [`Arc<str>`] on the `From<String>` conversion)
11185        // where the single-step trait impl allocates once.
11186        //
11187        // Cross-axis byte-parity witness against the sibling owned-
11188        // input `{&'static str, String, Cow<'static, str>, Box<str>}`
11189        // return-shape axes — locking the five return-shape paths on
11190        // the owned-input surface together by construction so any
11191        // future detour off the substrate-primitive
11192        // [`super::RestartStrategy::as_str`] accessor trips at caixa-
11193        // core test time.
11194        for &variant in RestartStrategy::ALL {
11195            let via_trait: std::sync::Arc<str> =
11196                <std::sync::Arc<str> as From<RestartStrategy>>::from(variant);
11197            let via_method: &'static str = variant.as_str();
11198            assert_eq!(
11199                via_trait.as_ref(),
11200                via_method,
11201                "From<RestartStrategy> for std::sync::Arc<str> impl \
11202                 must round-trip RestartStrategy::{variant:?} to the \
11203                 same lifted SUPERVISOR_ESTRATEGIA_* const \
11204                 RestartStrategy::as_str returns — divergence signals \
11205                 a silent detour off the substrate-primitive accessor"
11206            );
11207            let via_into: std::sync::Arc<str> = variant.into();
11208            assert_eq!(
11209                via_into.as_ref(),
11210                via_method,
11211                "Into<std::sync::Arc<str>>::into on \
11212                 RestartStrategy::{variant:?} must byte-equal \
11213                 RestartStrategy::as_str on the same input — the \
11214                 blanket-derived Into shape must resolve to the same \
11215                 as_str dispatch as the explicit From impl"
11216            );
11217            let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
11218            assert_eq!(
11219                via_trait.as_ref(),
11220                owned_static,
11221                "From<RestartStrategy> for std::sync::Arc<str> and \
11222                 From<RestartStrategy> for &'static str must resolve \
11223                 identically on RestartStrategy::{variant:?} — \
11224                 divergence signals the owned-input std::sync::Arc<str> \
11225                 and &'static str return-shape paths have drifted onto \
11226                 different emit-sets"
11227            );
11228            let owned_string: String = <String as From<RestartStrategy>>::from(variant);
11229            assert_eq!(
11230                via_trait.as_ref(),
11231                owned_string.as_str(),
11232                "From<RestartStrategy> for std::sync::Arc<str> and \
11233                 From<RestartStrategy> for String must resolve \
11234                 identically on RestartStrategy::{variant:?} — \
11235                 divergence signals the owned-input std::sync::Arc<str> \
11236                 and owned-`String` return-shape paths have drifted \
11237                 onto different emit-sets"
11238            );
11239            let owned_cow: std::borrow::Cow<'static, str> =
11240                <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
11241            assert_eq!(
11242                via_trait.as_ref(),
11243                owned_cow.as_ref(),
11244                "From<RestartStrategy> for std::sync::Arc<str> and \
11245                 From<RestartStrategy> for Cow<'static, str> must \
11246                 resolve identically on RestartStrategy::{variant:?} — \
11247                 divergence signals the owned-input std::sync::Arc<str> \
11248                 and Cow<'static, str> return-shape paths have drifted \
11249                 onto different emit-sets"
11250            );
11251            let owned_box: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
11252            assert_eq!(
11253                via_trait.as_ref(),
11254                owned_box.as_ref(),
11255                "From<RestartStrategy> for std::sync::Arc<str> and \
11256                 From<RestartStrategy> for Box<str> must resolve \
11257                 identically on RestartStrategy::{variant:?} — \
11258                 divergence signals the owned-input std::sync::Arc<str> \
11259                 and Box<str> return-shape paths have drifted onto \
11260                 different emit-sets"
11261            );
11262        }
11263    }
11264
11265    #[test]
11266    fn restart_strategy_from_borrowed_into_arc_str_routes_through_as_str_accessor() {
11267        // Fail-before-pass-after byte-parity pin on the newly lifted
11268        // `impl From<&RestartStrategy> for std::sync::Arc<str>` —
11269        // asserts the borrowed-input standard-library trait impl and
11270        // the substrate-primitive [`super::RestartStrategy::as_str`]
11271        // `pub const fn` accessor resolve to the same four-arm emit-
11272        // set across every arm the exhaustive
11273        // [`super::RestartStrategy::ALL`] slice enumerates. Rust's
11274        // standard library does not carry a blanket
11275        // `impl<T: AsRef<str>> From<&T> for std::sync::Arc<str>` (nor
11276        // a `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`),
11277        // so the borrowed-input [`std::sync::Arc<str>`] forward-
11278        // projection axis is a distinct trait-idiomatic surface that a
11279        // `let key: std::sync::Arc<str> = (&strategy).into();`-shaped
11280        // call site or a
11281        // `RestartStrategy::ALL.iter().map(std::sync::Arc::<str>::from)`-
11282        // shaped pipe reaches through this impl and no other — the
11283        // paired owned-input
11284        // `From<RestartStrategy> for std::sync::Arc<str>` impl
11285        // (bca2ec8) forces every borrowed-input call site through an
11286        // explicit `Copy` deref
11287        // (`std::sync::Arc::<str>::from((*strategy).as_str())`) or a
11288        // `std::sync::Arc::<str>::from(strategy.as_str())` open-code
11289        // whose type bounds have no compile-time link back to the
11290        // substrate primitive.
11291        //
11292        // Second peer on the substrate-wide trait-idiomatic
11293        // [`std::sync::Arc<str>`] forward-projection family on this
11294        // enum — closes the `{Self, &Self}` input-shape corner of
11295        // the [`std::sync::Arc<str>`] axis on the first M2 OTP-shape
11296        // closed-set fieldless typed enum peer on the caixa surface
11297        // (`:supervisor :estrategia`), exactly as 59ae5dc closed the
11298        // paired [`Box<str>`] axis one commit after its owning half
11299        // (69ef45c) landed. Every future closed-set fieldless typed
11300        // enum peer on the substrate is a future target of the
11301        // campaign.
11302        //
11303        // Also byte-parity witness against the paired owned-input
11304        // [`From<RestartStrategy> for std::sync::Arc<str>`] and the
11305        // sibling borrowed-input
11306        // [`From<&RestartStrategy> for &'static str`],
11307        // [`From<&RestartStrategy> for String`],
11308        // [`From<&RestartStrategy> for Cow<'static, str>`], and
11309        // [`From<&RestartStrategy> for Box<str>`] return-shape axes —
11310        // locking the five return-shape × input-shape paths together
11311        // by construction so any future detour trips at caixa-core
11312        // test time. Then a
11313        // `.iter().map(std::sync::Arc::<str>::from)` pipe witness over
11314        // [`super::RestartStrategy::ALL`] — whose iterator yields
11315        // `&RestartStrategy` by construction, so the borrowed-input
11316        // [`std::sync::Arc<str>`] axis is what routes the pipe
11317        // through the substrate-primitive
11318        // [`super::RestartStrategy::as_str`] accessor without a
11319        // spurious [`Copy`] deref (which would only be reachable
11320        // through the owned-input
11321        // [`From<RestartStrategy> for std::sync::Arc<str>`] axis by
11322        // first calling `.copied()` on the iterator).
11323        for &variant in RestartStrategy::ALL {
11324            let via_trait: std::sync::Arc<str> =
11325                <std::sync::Arc<str> as From<&RestartStrategy>>::from(&variant);
11326            let via_method: &'static str = variant.as_str();
11327            assert_eq!(
11328                via_trait.as_ref(),
11329                via_method,
11330                "From<&RestartStrategy> for std::sync::Arc<str> impl \
11331                 must round-trip &RestartStrategy::{variant:?} to the \
11332                 same lifted SUPERVISOR_ESTRATEGIA_* const \
11333                 RestartStrategy::as_str returns — divergence signals \
11334                 a silent detour off the substrate-primitive accessor"
11335            );
11336            let via_into: std::sync::Arc<str> = (&variant).into();
11337            assert_eq!(
11338                via_into.as_ref(),
11339                via_method,
11340                "Into<std::sync::Arc<str>>::into on \
11341                 &RestartStrategy::{variant:?} must byte-equal \
11342                 RestartStrategy::as_str on the same input — the \
11343                 blanket-derived Into shape must resolve to the same \
11344                 as_str dispatch as the explicit From impl"
11345            );
11346            let owned_arc: std::sync::Arc<str> =
11347                <std::sync::Arc<str> as From<RestartStrategy>>::from(variant);
11348            assert_eq!(
11349                via_trait, owned_arc,
11350                "From<&RestartStrategy> for std::sync::Arc<str> and \
11351                 From<RestartStrategy> for std::sync::Arc<str> must \
11352                 resolve identically on RestartStrategy::{variant:?} — \
11353                 divergence signals the borrowed-input and owned-input \
11354                 std::sync::Arc<str> forward-projection input-shape \
11355                 paths have drifted onto different emit-sets"
11356            );
11357            let borrowed_static: &'static str =
11358                <&'static str as From<&RestartStrategy>>::from(&variant);
11359            assert_eq!(
11360                via_trait.as_ref(),
11361                borrowed_static,
11362                "From<&RestartStrategy> for std::sync::Arc<str> and \
11363                 From<&RestartStrategy> for &'static str must resolve \
11364                 identically on RestartStrategy::{variant:?} — \
11365                 divergence signals the borrowed-input \
11366                 std::sync::Arc<str> and &'static str return-shape \
11367                 paths have drifted onto different emit-sets"
11368            );
11369            let borrowed_string: String = <String as From<&RestartStrategy>>::from(&variant);
11370            assert_eq!(
11371                via_trait.as_ref(),
11372                borrowed_string.as_str(),
11373                "From<&RestartStrategy> for std::sync::Arc<str> and \
11374                 From<&RestartStrategy> for String must resolve \
11375                 identically on RestartStrategy::{variant:?} — \
11376                 divergence signals the borrowed-input \
11377                 std::sync::Arc<str> and owned-`String` return-shape \
11378                 paths have drifted onto different emit-sets"
11379            );
11380            let borrowed_cow: std::borrow::Cow<'static, str> =
11381                <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&variant);
11382            assert_eq!(
11383                via_trait.as_ref(),
11384                borrowed_cow.as_ref(),
11385                "From<&RestartStrategy> for std::sync::Arc<str> and \
11386                 From<&RestartStrategy> for Cow<'static, str> must \
11387                 resolve identically on RestartStrategy::{variant:?} — \
11388                 divergence signals the borrowed-input \
11389                 std::sync::Arc<str> and Cow<'static, str> return-shape \
11390                 paths have drifted onto different emit-sets"
11391            );
11392            let borrowed_box: Box<str> = <Box<str> as From<&RestartStrategy>>::from(&variant);
11393            assert_eq!(
11394                via_trait.as_ref(),
11395                borrowed_box.as_ref(),
11396                "From<&RestartStrategy> for std::sync::Arc<str> and \
11397                 From<&RestartStrategy> for Box<str> must resolve \
11398                 identically on RestartStrategy::{variant:?} — \
11399                 divergence signals the borrowed-input \
11400                 std::sync::Arc<str> and Box<str> return-shape paths \
11401                 have drifted onto different emit-sets"
11402            );
11403        }
11404        let via_iter: Vec<std::sync::Arc<str>> = RestartStrategy::ALL
11405            .iter()
11406            .map(std::sync::Arc::<str>::from)
11407            .collect();
11408        let via_method: Vec<std::sync::Arc<str>> = RestartStrategy::ALL
11409            .iter()
11410            .map(|s| std::sync::Arc::<str>::from(s.as_str()))
11411            .collect();
11412        assert_eq!(
11413            via_iter, via_method,
11414            "`.iter().map(std::sync::Arc::<str>::from)` over \
11415             RestartStrategy::ALL — a call site whose iteration axis \
11416             holds `&RestartStrategy` by construction — must byte-\
11417             equal `.iter().map(|s| std::sync::Arc::<str>::from(s.as_str()))` \
11418             on every arm — the borrowed-input std::sync::Arc<str> \
11419             `From<&RestartStrategy> for std::sync::Arc<str>` axis is \
11420             what makes the `std::sync::Arc::<str>::from` composition \
11421             route through the substrate-primitive \
11422             `RestartStrategy::as_str` accessor without a spurious \
11423             `Copy` deref (which would only be reachable through the \
11424             owned-input `From<RestartStrategy> for std::sync::Arc<str>` \
11425             axis by first calling `.copied()` on the iterator)"
11426        );
11427    }
11428
11429    #[test]
11430    fn restart_strategy_from_into_rc_str_routes_through_as_str_accessor() {
11431        // Fail-before-pass-after byte-parity pin on the newly lifted
11432        // `impl From<RestartStrategy> for std::rc::Rc<str>` — asserts
11433        // the owned-input standard-library trait impl and the
11434        // substrate-primitive [`super::RestartStrategy::as_str`]
11435        // `pub const fn` accessor resolve to the same four-arm emit-
11436        // set across every arm the exhaustive
11437        // [`super::RestartStrategy::ALL`] slice enumerates, and cross-
11438        // witnesses against every sibling owned-input `{&'static str,
11439        // String, Cow<'static, str>, Box<str>, std::sync::Arc<str>}`
11440        // return-shape axis so the six return-shape paths on the
11441        // owned-input surface lock together by construction. Extends
11442        // the substrate-wide [`std::rc::Rc<str>`] forward-projection
11443        // campaign onto the first M2 OTP-shape closed-set fieldless
11444        // typed enum peer on the caixa surface
11445        // (`:supervisor :estrategia`).
11446        for &variant in RestartStrategy::ALL {
11447            let via_trait: std::rc::Rc<str> =
11448                <std::rc::Rc<str> as From<RestartStrategy>>::from(variant);
11449            let via_method: &'static str = variant.as_str();
11450            assert_eq!(
11451                via_trait.as_ref(),
11452                via_method,
11453                "From<RestartStrategy> for std::rc::Rc<str> impl must \
11454                 round-trip RestartStrategy::{variant:?} to the same \
11455                 lifted SUPERVISOR_ESTRATEGIA_* const \
11456                 RestartStrategy::as_str returns — divergence signals \
11457                 a silent detour off the substrate-primitive accessor"
11458            );
11459            let via_into: std::rc::Rc<str> = variant.into();
11460            assert_eq!(
11461                via_into.as_ref(),
11462                via_method,
11463                "Into<std::rc::Rc<str>>::into on \
11464                 RestartStrategy::{variant:?} must byte-equal \
11465                 RestartStrategy::as_str on the same input — the \
11466                 blanket-derived Into shape must resolve to the same \
11467                 as_str dispatch as the explicit From impl"
11468            );
11469            let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
11470            assert_eq!(
11471                via_trait.as_ref(),
11472                owned_static,
11473                "From<RestartStrategy> for std::rc::Rc<str> and \
11474                 From<RestartStrategy> for &'static str must resolve \
11475                 identically on RestartStrategy::{variant:?}"
11476            );
11477            let owned_string: String = <String as From<RestartStrategy>>::from(variant);
11478            assert_eq!(
11479                via_trait.as_ref(),
11480                owned_string.as_str(),
11481                "From<RestartStrategy> for std::rc::Rc<str> and \
11482                 From<RestartStrategy> for String must resolve \
11483                 identically on RestartStrategy::{variant:?}"
11484            );
11485            let owned_cow: std::borrow::Cow<'static, str> =
11486                <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
11487            assert_eq!(
11488                via_trait.as_ref(),
11489                owned_cow.as_ref(),
11490                "From<RestartStrategy> for std::rc::Rc<str> and \
11491                 From<RestartStrategy> for Cow<'static, str> must \
11492                 resolve identically on RestartStrategy::{variant:?}"
11493            );
11494            let owned_box: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
11495            assert_eq!(
11496                via_trait.as_ref(),
11497                owned_box.as_ref(),
11498                "From<RestartStrategy> for std::rc::Rc<str> and \
11499                 From<RestartStrategy> for Box<str> must resolve \
11500                 identically on RestartStrategy::{variant:?}"
11501            );
11502            let owned_arc: std::sync::Arc<str> =
11503                <std::sync::Arc<str> as From<RestartStrategy>>::from(variant);
11504            assert_eq!(
11505                via_trait.as_ref(),
11506                owned_arc.as_ref(),
11507                "From<RestartStrategy> for std::rc::Rc<str> and \
11508                 From<RestartStrategy> for std::sync::Arc<str> must \
11509                 resolve identically on RestartStrategy::{variant:?}"
11510            );
11511        }
11512    }
11513
11514    #[test]
11515    fn restart_strategy_from_borrowed_into_rc_str_routes_through_as_str_accessor() {
11516        // Fail-before-pass-after byte-parity pin on the newly lifted
11517        // `impl From<&RestartStrategy> for std::rc::Rc<str>` — asserts
11518        // the borrowed-input standard-library trait impl and the
11519        // substrate-primitive [`super::RestartStrategy::as_str`]
11520        // `pub const fn` accessor resolve to the same four-arm emit-
11521        // set across every arm the exhaustive
11522        // [`super::RestartStrategy::ALL`] slice enumerates. Closes the
11523        // `{Self, &Self}` input-shape corner of the
11524        // [`std::rc::Rc<str>`] axis on this enum, cross-witnesses
11525        // against the paired owned-input axis and every sibling
11526        // borrowed-input return-shape axis, and locks the
11527        // `.iter().map(std::rc::Rc::<str>::from)` pipe over
11528        // [`super::RestartStrategy::ALL`] to the substrate-primitive
11529        // accessor without a spurious [`Copy`] deref (which would only
11530        // be reachable through the owned-input axis by first calling
11531        // `.copied()` on the iterator).
11532        for &variant in RestartStrategy::ALL {
11533            let via_trait: std::rc::Rc<str> =
11534                <std::rc::Rc<str> as From<&RestartStrategy>>::from(&variant);
11535            let via_method: &'static str = variant.as_str();
11536            assert_eq!(
11537                via_trait.as_ref(),
11538                via_method,
11539                "From<&RestartStrategy> for std::rc::Rc<str> impl must \
11540                 round-trip &RestartStrategy::{variant:?} to the same \
11541                 lifted SUPERVISOR_ESTRATEGIA_* const \
11542                 RestartStrategy::as_str returns"
11543            );
11544            let via_into: std::rc::Rc<str> = (&variant).into();
11545            assert_eq!(
11546                via_into.as_ref(),
11547                via_method,
11548                "Into<std::rc::Rc<str>>::into on \
11549                 &RestartStrategy::{variant:?} must byte-equal \
11550                 RestartStrategy::as_str on the same input"
11551            );
11552            let owned_rc: std::rc::Rc<str> =
11553                <std::rc::Rc<str> as From<RestartStrategy>>::from(variant);
11554            assert_eq!(
11555                via_trait, owned_rc,
11556                "From<&RestartStrategy> for std::rc::Rc<str> and \
11557                 From<RestartStrategy> for std::rc::Rc<str> must \
11558                 resolve identically on RestartStrategy::{variant:?}"
11559            );
11560            let borrowed_static: &'static str =
11561                <&'static str as From<&RestartStrategy>>::from(&variant);
11562            assert_eq!(
11563                via_trait.as_ref(),
11564                borrowed_static,
11565                "From<&RestartStrategy> for std::rc::Rc<str> and \
11566                 From<&RestartStrategy> for &'static str must resolve \
11567                 identically on RestartStrategy::{variant:?}"
11568            );
11569            let borrowed_string: String = <String as From<&RestartStrategy>>::from(&variant);
11570            assert_eq!(
11571                via_trait.as_ref(),
11572                borrowed_string.as_str(),
11573                "From<&RestartStrategy> for std::rc::Rc<str> and \
11574                 From<&RestartStrategy> for String must resolve \
11575                 identically on RestartStrategy::{variant:?}"
11576            );
11577            let borrowed_cow: std::borrow::Cow<'static, str> =
11578                <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&variant);
11579            assert_eq!(
11580                via_trait.as_ref(),
11581                borrowed_cow.as_ref(),
11582                "From<&RestartStrategy> for std::rc::Rc<str> and \
11583                 From<&RestartStrategy> for Cow<'static, str> must \
11584                 resolve identically on RestartStrategy::{variant:?}"
11585            );
11586            let borrowed_box: Box<str> = <Box<str> as From<&RestartStrategy>>::from(&variant);
11587            assert_eq!(
11588                via_trait.as_ref(),
11589                borrowed_box.as_ref(),
11590                "From<&RestartStrategy> for std::rc::Rc<str> and \
11591                 From<&RestartStrategy> for Box<str> must resolve \
11592                 identically on RestartStrategy::{variant:?}"
11593            );
11594            let borrowed_arc: std::sync::Arc<str> =
11595                <std::sync::Arc<str> as From<&RestartStrategy>>::from(&variant);
11596            assert_eq!(
11597                via_trait.as_ref(),
11598                borrowed_arc.as_ref(),
11599                "From<&RestartStrategy> for std::rc::Rc<str> and \
11600                 From<&RestartStrategy> for std::sync::Arc<str> must \
11601                 resolve identically on RestartStrategy::{variant:?}"
11602            );
11603        }
11604        let via_iter: Vec<std::rc::Rc<str>> = RestartStrategy::ALL
11605            .iter()
11606            .map(std::rc::Rc::<str>::from)
11607            .collect();
11608        let via_method: Vec<std::rc::Rc<str>> = RestartStrategy::ALL
11609            .iter()
11610            .map(|s| std::rc::Rc::<str>::from(s.as_str()))
11611            .collect();
11612        assert_eq!(
11613            via_iter, via_method,
11614            "`.iter().map(std::rc::Rc::<str>::from)` over \
11615             RestartStrategy::ALL — a call site whose iteration axis \
11616             holds `&RestartStrategy` by construction — must byte-\
11617             equal `.iter().map(|s| std::rc::Rc::<str>::from(s.as_str()))` \
11618             on every arm — the borrowed-input std::rc::Rc<str> \
11619             `From<&RestartStrategy> for std::rc::Rc<str>` axis is \
11620             what makes the `std::rc::Rc::<str>::from` composition \
11621             route through the substrate-primitive \
11622             `RestartStrategy::as_str` accessor without a spurious \
11623             `Copy` deref (which would only be reachable through the \
11624             owned-input `From<RestartStrategy> for std::rc::Rc<str>` \
11625             axis by first calling `.copied()` on the iterator)"
11626        );
11627    }
11628
11629    #[test]
11630    #[allow(
11631        clippy::too_many_lines,
11632        reason = "cross-axis partition pin folds the substrate-primitive \
11633                  as_str accessor's `.as_bytes()` byte-tail plus the \
11634                  paired str-view (AsRef<str>, Display, as_str) and \
11635                  reverse-projection ({&'static str, String, Cow<'static, \
11636                  str>, Box<str>, std::sync::Arc<str>}) return-shape \
11637                  axes' `.as_bytes()` byte-tails plus a <T: AsRef<[u8]>>\
11638                  -bound-consumer witness plus a blake3::Hasher::update-\
11639                  shape byte-input surface witness into one exhaustive \
11640                  round-trip over RestartStrategy::ALL — the accepted \
11641                  line-count cost of opening the byte-view axis keyed \
11642                  to the substrate-primitive as_str accessor at the \
11643                  same test-site"
11644    )]
11645    #[allow(
11646        clippy::needless_borrows_for_generic_args,
11647        reason = "the borrowed-input surface (&variant) is exercised \
11648                  deliberately: the `<T: AsRef<[u8]>>`-bound consumer \
11649                  and the `blake3::Hasher::update`-shape byte-input \
11650                  surface both accept either owned or borrowed input \
11651                  through the standard-library blanket \
11652                  `impl<T: ?Sized + AsRef<[u8]>> AsRef<[u8]> for &T`, \
11653                  and this pin round-trips both input shapes to lock \
11654                  the borrowed-input path load-bearing against a \
11655                  future silent regression"
11656    )]
11657    fn restart_strategy_as_ref_bytes_routes_through_as_str_accessor() {
11658        // `<T: AsRef<[u8]>>`-bound generic-consumer witness: a byte-input
11659        // function that binds its argument through the standard-library
11660        // [`AsRef<[u8]>`] trait bound accepts a [`super::RestartStrategy`]
11661        // directly, without the caller open-coding the two-hop
11662        // `estrategia.as_str().as_bytes()` composition. Lifted to the top
11663        // of the function per `clippy::items_after_statements`.
11664        fn generic_bytes_sink<T: AsRef<[u8]>>(t: T) -> Vec<u8> {
11665            t.as_ref().to_vec()
11666        }
11667        // `blake3::Hasher::update`-shape byte-input surface mock: mirrors
11668        // `blake3::Hasher::update` / `ring::digest::Context::update` /
11669        // `sha2::Sha256::update`'s `impl AsRef<[u8]>`-bound `update`
11670        // signature so a per-supervisor BLAKE3 content-address closure
11671        // that composes `hasher.update(estrategia)` on the
11672        // [`crate::Lacre`] closure builder reaches the substrate-primitive
11673        // `as_str` accessor through the [`super::RestartStrategy`]
11674        // `AsRef<[u8]>` axis and no other. Lifted to the top of the
11675        // function per `clippy::items_after_statements`.
11676        struct MockHasher(Vec<u8>);
11677        impl MockHasher {
11678            fn new() -> Self {
11679                Self(Vec::new())
11680            }
11681            fn update(&mut self, bytes: impl AsRef<[u8]>) -> &mut Self {
11682                self.0.extend_from_slice(bytes.as_ref());
11683                self
11684            }
11685            fn finalize(self) -> Vec<u8> {
11686                self.0
11687            }
11688        }
11689
11690        // Fail-before-pass-after byte-parity pin on the newly lifted
11691        // `impl AsRef<[u8]> for RestartStrategy` — asserts the trait-
11692        // idiomatic byte-view standard-library impl and the substrate-
11693        // primitive [`super::RestartStrategy::as_str`] `pub const fn`
11694        // accessor's `.as_bytes()` byte-tail resolve to the same four-arm
11695        // `PascalCase` wire byte-string emit-set across every arm the
11696        // exhaustive [`super::RestartStrategy::ALL`] slice enumerates.
11697        // Opens the trait-idiomatic byte-view axis onto the first M2
11698        // OTP-shape closed-set fieldless typed enum peer on the caixa
11699        // surface (`:supervisor :estrategia`), extending the substrate-
11700        // wide byte-view campaign the sibling
11701        // [`super::crate::CaixaKind`] first-mover (69d8d86) opened.
11702        //
11703        // Rust's standard library carries `impl AsRef<[u8]> for str` and
11704        // `impl AsRef<[u8]> for String`, so a two-hop composition
11705        // `estrategia.as_str().as_bytes()` (or the equally two-hop
11706        // `AsRef::<str>::as_ref(&estrategia).as_bytes()`) is reachable
11707        // through the pre-existing str-view axis alone. But that two-hop
11708        // shape has no compile-time link back to the byte-projection
11709        // axis, forces every downstream `<T: AsRef<[u8]>>`-bound
11710        // consumer to open-code the two-hop composition at every call
11711        // site, and admits a silent split whenever a future call site
11712        // takes a sibling reverse-projection axis whose `.as_bytes()`
11713        // byte-tail carries no compile-time byte-view surface. This
11714        // impl closes the byte-view axis at the substrate-primitive
11715        // [`super::RestartStrategy::as_str`] accessor so every future
11716        // `<T: AsRef<[u8]>>`-bound consumer reaches the same lifted
11717        // [`super::crate::render::SUPERVISOR_ESTRATEGIA_*`] const roster
11718        // the paired str-view axes already return through — through one
11719        // trait dispatch.
11720        for &variant in RestartStrategy::ALL {
11721            let via_trait: &[u8] = <RestartStrategy as AsRef<[u8]>>::as_ref(&variant);
11722            let via_method_bytes: &[u8] = variant.as_str().as_bytes();
11723            assert_eq!(
11724                via_trait, via_method_bytes,
11725                "AsRef<[u8]> for RestartStrategy impl must byte-equal \
11726                 RestartStrategy::as_str().as_bytes() on \
11727                 RestartStrategy::{variant:?} — divergence signals a \
11728                 silent detour off the substrate-primitive accessor"
11729            );
11730            // Cross-axis witness against the paired str-view axes'
11731            // `.as_bytes()` byte-tails: [`AsRef<str>`] /
11732            // [`std::fmt::Display`] / [`super::RestartStrategy::as_str`]
11733            // all resolve to the same lifted
11734            // [`super::crate::render::SUPERVISOR_ESTRATEGIA_*`] const
11735            // roster, and the byte-view axis must byte-equal each of
11736            // their `.as_bytes()` byte-tails by construction — locking
11737            // the str-view and byte-view axes together at the
11738            // substrate-primitive accessor.
11739            let str_view_ref: &str = <RestartStrategy as AsRef<str>>::as_ref(&variant);
11740            assert_eq!(
11741                via_trait,
11742                str_view_ref.as_bytes(),
11743                "AsRef<[u8]> for RestartStrategy and AsRef<str> for \
11744                 RestartStrategy must resolve to byte-equal byte-tails \
11745                 on RestartStrategy::{variant:?} — divergence signals \
11746                 the byte-view and str-view axes have drifted off the \
11747                 same substrate-primitive as_str accessor"
11748            );
11749            let display_bytes = variant.to_string();
11750            assert_eq!(
11751                via_trait,
11752                display_bytes.as_bytes(),
11753                "AsRef<[u8]> for RestartStrategy and \
11754                 <RestartStrategy as std::fmt::Display>::to_string must \
11755                 resolve to byte-equal byte-tails on \
11756                 RestartStrategy::{variant:?} — divergence signals the \
11757                 byte-view axis and the Display formatter axis have \
11758                 drifted off the same substrate-primitive as_str \
11759                 accessor"
11760            );
11761            // Cross-axis witness against the paired reverse-projection
11762            // axes' `.as_bytes()` byte-tails: every one of `{&'static
11763            // str, String, Cow<'static, str>, Box<str>,
11764            // std::sync::Arc<str>}` allocates (or borrows) the same
11765            // `PascalCase` wire byte-string the substrate-primitive
11766            // accessor emits, so the byte-view axis must byte-equal
11767            // each of their `.as_bytes()` byte-tails by construction.
11768            let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
11769            assert_eq!(
11770                via_trait,
11771                owned_static.as_bytes(),
11772                "AsRef<[u8]> for RestartStrategy and From<RestartStrategy> \
11773                 for &'static str must resolve to byte-equal byte-tails \
11774                 on RestartStrategy::{variant:?}"
11775            );
11776            let owned_string: String = <String as From<RestartStrategy>>::from(variant);
11777            assert_eq!(
11778                via_trait,
11779                owned_string.as_bytes(),
11780                "AsRef<[u8]> for RestartStrategy and From<RestartStrategy> \
11781                 for String must resolve to byte-equal byte-tails on \
11782                 RestartStrategy::{variant:?}"
11783            );
11784            let owned_cow: std::borrow::Cow<'static, str> =
11785                <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
11786            assert_eq!(
11787                via_trait,
11788                owned_cow.as_bytes(),
11789                "AsRef<[u8]> for RestartStrategy and From<RestartStrategy> \
11790                 for Cow<'static, str> must resolve to byte-equal byte-\
11791                 tails on RestartStrategy::{variant:?}"
11792            );
11793            let owned_box: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
11794            assert_eq!(
11795                via_trait,
11796                owned_box.as_bytes(),
11797                "AsRef<[u8]> for RestartStrategy and From<RestartStrategy> \
11798                 for Box<str> must resolve to byte-equal byte-tails on \
11799                 RestartStrategy::{variant:?}"
11800            );
11801            let owned_arc: std::sync::Arc<str> =
11802                <std::sync::Arc<str> as From<RestartStrategy>>::from(variant);
11803            assert_eq!(
11804                via_trait,
11805                owned_arc.as_bytes(),
11806                "AsRef<[u8]> for RestartStrategy and From<RestartStrategy> \
11807                 for std::sync::Arc<str> must resolve to byte-equal byte-\
11808                 tails on RestartStrategy::{variant:?}"
11809            );
11810        }
11811        // `<T: AsRef<[u8]>>`-bound-consumer witness: the generic byte-
11812        // input function `generic_bytes_sink` (lifted above per
11813        // `clippy::items_after_statements`) accepts a
11814        // [`super::RestartStrategy`] directly through the trait bound,
11815        // without the caller open-coding the two-hop
11816        // `estrategia.as_str().as_bytes()` composition. This is the
11817        // shape that reaches the caixa-lacre BLAKE3 content-address
11818        // closure's `blake3::Hasher::update(impl AsRef<[u8]>)` byte-
11819        // input surface through this impl and no other.
11820        for &variant in RestartStrategy::ALL {
11821            let via_generic = generic_bytes_sink(variant);
11822            let via_borrowed_generic = generic_bytes_sink(&variant);
11823            let via_method_bytes = variant.as_str().as_bytes().to_vec();
11824            assert_eq!(
11825                via_generic, via_method_bytes,
11826                "generic `<T: AsRef<[u8]>>`-bound consumer on \
11827                 RestartStrategy::{variant:?} must yield the same byte-\
11828                 tail RestartStrategy::as_str().as_bytes() returns — \
11829                 divergence signals the byte-view axis fails to bridge \
11830                 a generic byte-input trait bound to the substrate-\
11831                 primitive accessor"
11832            );
11833            assert_eq!(
11834                via_borrowed_generic, via_method_bytes,
11835                "generic `<T: AsRef<[u8]>>`-bound consumer on \
11836                 &RestartStrategy::{variant:?} must yield the same byte-\
11837                 tail RestartStrategy::as_str().as_bytes() returns — \
11838                 the borrowed-input surface must resolve to the same \
11839                 as_str dispatch"
11840            );
11841        }
11842        // `blake3::Hasher::update`-shape byte-input surface witness on
11843        // the caixa-lacre compounding target: the `MockHasher` (lifted
11844        // above per `clippy::items_after_statements`) mirrors
11845        // `blake3::Hasher::update` / `ring::digest::Context::update` /
11846        // `sha2::Sha256::update`'s `impl AsRef<[u8]>`-bound update
11847        // signature and accepts a [`super::RestartStrategy`] directly,
11848        // routing its byte-tail through the substrate-primitive
11849        // `as_str` accessor — the shape a future per-supervisor BLAKE3
11850        // content-address closure composes to fold an `:estrategia`
11851        // discriminator byte-tag into the [`crate::Lacre`] closure
11852        // body.
11853        for &variant in RestartStrategy::ALL {
11854            let mut owned_hasher = MockHasher::new();
11855            owned_hasher.update(variant);
11856            let owned_folded = owned_hasher.finalize();
11857            assert_eq!(
11858                owned_folded,
11859                variant.as_str().as_bytes(),
11860                "`hasher.update(estrategia)`-shape composition on \
11861                 RestartStrategy::{variant:?} must fold the same byte-\
11862                 tail RestartStrategy::as_str().as_bytes() returns — \
11863                 the shape a future per-supervisor BLAKE3 content-\
11864                 address closure composes to fold an `:estrategia` \
11865                 discriminator byte-tag into the Lacre closure body"
11866            );
11867            let mut borrowed_hasher = MockHasher::new();
11868            borrowed_hasher.update(&variant);
11869            let borrowed_folded = borrowed_hasher.finalize();
11870            assert_eq!(
11871                borrowed_folded,
11872                variant.as_str().as_bytes(),
11873                "`hasher.update(&estrategia)`-shape composition on \
11874                 &RestartStrategy::{variant:?} must fold the same byte-\
11875                 tail RestartStrategy::as_str().as_bytes() returns — \
11876                 the borrowed-input surface must resolve to the same \
11877                 as_str dispatch"
11878            );
11879        }
11880    }
11881
11882    #[test]
11883    #[expect(
11884        clippy::too_many_lines,
11885        reason = "the byte-owned reverse-projection axis is extended \
11886                  here onto the first M2-OTP-shape closed-set fieldless \
11887                  typed-enum peer, so the pin binds the new impl against \
11888                  every paired byte-view and str-owned axis on the same \
11889                  enum plus a generic <T: Into<Vec<u8>>>-bound consumer \
11890                  witness and a std::io::Write::write_all-shape owned-\
11891                  byte-sink surface witness on both owned and borrowed \
11892                  input shapes to lock the whole family against a future \
11893                  silent regression"
11894    )]
11895    fn restart_strategy_from_into_owned_vec_bytes_routes_through_as_str_accessor() {
11896        // `<T: Into<Vec<u8>>>`-bound-consumer witness helper: a generic
11897        // owned-byte-input function accepts a [`super::RestartStrategy`]
11898        // directly through the trait bound, without the caller open-
11899        // coding the three-hop `strategy.as_str().as_bytes().to_vec()`
11900        // composition. Lifted to the top of the function per
11901        // `clippy::items_after_statements`.
11902        fn generic_owned_bytes_sink<T: Into<Vec<u8>>>(t: T) -> Vec<u8> {
11903            t.into()
11904        }
11905        // `std::io::Write::write_all`-shape owned-byte-sink surface
11906        // mock: mirrors `std::io::Write::write_all` /
11907        // `bytes::BytesMut::extend_from_slice` / any per-arm audit-log
11908        // byte-sink that consumes a `Vec<u8>` payload via
11909        // `Into<Vec<u8>>`, so a future per-supervisor per-`:estrategia`
11910        // audit-log emit reaches the substrate-primitive `as_str`
11911        // accessor through the byte-owned reverse-projection axis and
11912        // no other. Lifted to the top of the function per
11913        // `clippy::items_after_statements`.
11914        struct MockOwnedByteSink(Vec<u8>);
11915        impl MockOwnedByteSink {
11916            fn new() -> Self {
11917                Self(Vec::new())
11918            }
11919            fn write_all(&mut self, bytes: impl Into<Vec<u8>>) -> &mut Self {
11920                self.0.extend_from_slice(&bytes.into());
11921                self
11922            }
11923            fn finalize(self) -> Vec<u8> {
11924                self.0
11925            }
11926        }
11927
11928        // Fail-before-pass-after byte-parity pin on the newly lifted
11929        // `impl From<RestartStrategy> for Vec<u8>` and
11930        // `impl From<&RestartStrategy> for Vec<u8>` — asserts the trait-
11931        // idiomatic byte-owned reverse-projection standard-library
11932        // impls and the substrate-primitive
11933        // [`super::RestartStrategy::as_str`] `pub const fn` accessor's
11934        // `.as_bytes().to_vec()` byte-tail resolve to the same four-arm
11935        // PascalCase wire byte-string emit-set across every arm the
11936        // exhaustive [`super::RestartStrategy::ALL`] slice enumerates.
11937        // Extends the substrate-wide trait-idiomatic byte-owned
11938        // reverse-projection axis onto the first M2-OTP-shape closed-
11939        // set fieldless typed-enum peer on the caixa surface
11940        // (`:supervisor :estrategia`), matching the trajectory the
11941        // first-mover [`super::crate::CaixaKind`] lift (b245fd6), the
11942        // second-mover [`super::crate::dialeto::CaixaDialeto`] lift
11943        // (4cceaf5), and the third-mover
11944        // [`super::crate::dep::DepList`] lift (e974ca2) established
11945        // across the caixa-core-internal tier.
11946        for &variant in RestartStrategy::ALL {
11947            let via_owned_from: Vec<u8> = <Vec<u8> as From<RestartStrategy>>::from(variant);
11948            let via_borrowed_from: Vec<u8> = <Vec<u8> as From<&RestartStrategy>>::from(&variant);
11949            let via_method_bytes: Vec<u8> = variant.as_str().as_bytes().to_vec();
11950            assert_eq!(
11951                via_owned_from, via_method_bytes,
11952                "From<RestartStrategy> for Vec<u8> impl must byte-equal \
11953                 RestartStrategy::as_str().as_bytes().to_vec() on \
11954                 RestartStrategy::{variant:?} — divergence signals a \
11955                 silent detour off the substrate-primitive accessor"
11956            );
11957            assert_eq!(
11958                via_borrowed_from, via_method_bytes,
11959                "From<&RestartStrategy> for Vec<u8> impl must byte-\
11960                 equal RestartStrategy::as_str().as_bytes().to_vec() \
11961                 on RestartStrategy::{variant:?} — divergence signals \
11962                 a silent detour off the substrate-primitive accessor"
11963            );
11964            assert_eq!(
11965                via_owned_from, via_borrowed_from,
11966                "From<RestartStrategy> for Vec<u8> and \
11967                 From<&RestartStrategy> for Vec<u8> must byte-equal \
11968                 each other on RestartStrategy::{variant:?} — \
11969                 divergence signals the owned-input and borrowed-input \
11970                 paths have drifted off the same substrate-primitive \
11971                 as_str accessor"
11972            );
11973            // Cross-axis witness against the paired [`AsRef<[u8]>`]
11974            // borrowed byte-view axis (cd4c4e0): the byte-owned
11975            // reverse-projection axis must byte-equal the paired
11976            // borrowed byte-view axis by construction — locking the
11977            // byte-view and byte-owned axes together at the substrate-
11978            // primitive accessor.
11979            let borrowed_bytes: &[u8] = <RestartStrategy as AsRef<[u8]>>::as_ref(&variant);
11980            assert_eq!(
11981                via_owned_from,
11982                borrowed_bytes.to_vec(),
11983                "From<RestartStrategy> for Vec<u8> and AsRef<[u8]> \
11984                 for RestartStrategy must resolve to byte-equal byte-\
11985                 tails on RestartStrategy::{variant:?} — divergence \
11986                 signals the byte-owned and byte-view axes have \
11987                 drifted off the same substrate-primitive as_str \
11988                 accessor"
11989            );
11990            // Cross-axis witness against the str-owned reverse-
11991            // projection family's `.into_bytes()` / `.as_bytes().to_vec()`
11992            // byte-tails: every one of `{String, Cow<'static, str>,
11993            // Box<str>, std::sync::Arc<str>, std::rc::Rc<str>}`
11994            // allocates (or borrows) the same PascalCase wire byte-
11995            // string the substrate-primitive accessor emits, so the
11996            // byte-owned axis must byte-equal each of their owned
11997            // byte-tails by construction.
11998            let owned_string: String = <String as From<RestartStrategy>>::from(variant);
11999            assert_eq!(
12000                via_owned_from,
12001                owned_string.into_bytes(),
12002                "From<RestartStrategy> for Vec<u8> and \
12003                 String::from(strategy).into_bytes() must resolve to \
12004                 byte-equal byte-tails on RestartStrategy::{variant:?}"
12005            );
12006            let owned_cow: std::borrow::Cow<'static, str> =
12007                <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
12008            assert_eq!(
12009                via_owned_from,
12010                owned_cow.as_bytes().to_vec(),
12011                "From<RestartStrategy> for Vec<u8> and \
12012                 From<RestartStrategy> for Cow<'static, str> must \
12013                 resolve to byte-equal byte-tails on \
12014                 RestartStrategy::{variant:?}"
12015            );
12016            let owned_box: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
12017            assert_eq!(
12018                via_owned_from,
12019                owned_box.as_bytes().to_vec(),
12020                "From<RestartStrategy> for Vec<u8> and \
12021                 From<RestartStrategy> for Box<str> must resolve to \
12022                 byte-equal byte-tails on RestartStrategy::{variant:?}"
12023            );
12024            let owned_arc: std::sync::Arc<str> =
12025                <std::sync::Arc<str> as From<RestartStrategy>>::from(variant);
12026            assert_eq!(
12027                via_owned_from,
12028                owned_arc.as_bytes().to_vec(),
12029                "From<RestartStrategy> for Vec<u8> and \
12030                 From<RestartStrategy> for std::sync::Arc<str> must \
12031                 resolve to byte-equal byte-tails on \
12032                 RestartStrategy::{variant:?}"
12033            );
12034        }
12035        // `<T: Into<Vec<u8>>>`-bound-consumer witness on both owned
12036        // and borrowed input shapes: the generic owned-byte-input
12037        // function `generic_owned_bytes_sink` (lifted above per
12038        // `clippy::items_after_statements`) accepts a
12039        // [`super::RestartStrategy`] and a `&RestartStrategy`
12040        // directly through the trait bound, without the caller open-
12041        // coding the three-hop `strategy.as_str().as_bytes().to_vec()`
12042        // composition.
12043        for &variant in RestartStrategy::ALL {
12044            let via_generic_owned = generic_owned_bytes_sink(variant);
12045            // Bind the borrowed-input path through an explicit
12046            // `&RestartStrategy` local so the generic-consumer witness
12047            // routes through `From<&RestartStrategy> for Vec<u8>` (T
12048            // binds to `&RestartStrategy`) rather than clippy-collapsing
12049            // the borrow onto the owned-input peer.
12050            let variant_ref: &RestartStrategy = &variant;
12051            let via_generic_borrowed = generic_owned_bytes_sink(variant_ref);
12052            let via_method_bytes = variant.as_str().as_bytes().to_vec();
12053            assert_eq!(
12054                via_generic_owned, via_method_bytes,
12055                "generic `<T: Into<Vec<u8>>>`-bound consumer on \
12056                 RestartStrategy::{variant:?} must yield the same byte-\
12057                 tail RestartStrategy::as_str().as_bytes() returns — \
12058                 divergence signals the byte-owned axis fails to bridge \
12059                 a generic owned-byte-input trait bound to the \
12060                 substrate-primitive accessor"
12061            );
12062            assert_eq!(
12063                via_generic_borrowed, via_method_bytes,
12064                "generic `<T: Into<Vec<u8>>>`-bound consumer on \
12065                 &RestartStrategy::{variant:?} must yield the same byte-\
12066                 tail RestartStrategy::as_str().as_bytes() returns — \
12067                 the borrowed-input surface must resolve to the same \
12068                 as_str dispatch"
12069            );
12070        }
12071        // `std::io::Write::write_all`-shape owned-byte-sink surface
12072        // witness: the `MockOwnedByteSink` (lifted above per
12073        // `clippy::items_after_statements`) mirrors
12074        // `std::io::Write::write_all` /
12075        // `bytes::BytesMut::extend_from_slice`'s `impl Into<Vec<u8>>`-
12076        // bound owned-byte input signature and accepts a
12077        // [`super::RestartStrategy`] directly on both owned and
12078        // borrowed input shapes, routing its byte-tail through the
12079        // substrate-primitive `as_str` accessor — the shape a future
12080        // per-supervisor per-`:estrategia` audit-log emit composes to
12081        // fold an `:estrategia` discriminator byte-tag into a
12082        // downstream owned-byte-sink surface.
12083        for &variant in RestartStrategy::ALL {
12084            let mut owned_sink = MockOwnedByteSink::new();
12085            owned_sink.write_all(variant);
12086            let owned_folded = owned_sink.finalize();
12087            assert_eq!(
12088                owned_folded,
12089                variant.as_str().as_bytes(),
12090                "`sink.write_all(strategy)`-shape composition on \
12091                 RestartStrategy::{variant:?} must fold the same byte-\
12092                 tail RestartStrategy::as_str().as_bytes() returns"
12093            );
12094            let mut borrowed_sink = MockOwnedByteSink::new();
12095            let variant_ref: &RestartStrategy = &variant;
12096            borrowed_sink.write_all(variant_ref);
12097            let borrowed_folded = borrowed_sink.finalize();
12098            assert_eq!(
12099                borrowed_folded,
12100                variant.as_str().as_bytes(),
12101                "`sink.write_all(&strategy)`-shape composition on \
12102                 &RestartStrategy::{variant:?} must fold the same byte-\
12103                 tail RestartStrategy::as_str().as_bytes() returns — \
12104                 the borrowed-input surface must resolve to the same \
12105                 as_str dispatch"
12106            );
12107        }
12108    }
12109
12110    #[test]
12111    fn restart_strategy_from_into_owned_cow_bytes_routes_through_as_str_accessor() {
12112        // Fail-before-pass-after byte-parity pin on the newly lifted
12113        // `impl From<RestartStrategy> for std::borrow::Cow<'static, [u8]>`
12114        // and `impl From<&RestartStrategy> for std::borrow::Cow<'static, [u8]>` —
12115        // asserts the trait-idiomatic byte-owned reverse-projection standard-
12116        // library impls and the substrate-primitive
12117        // [`super::RestartStrategy::as_str`] `pub const fn` accessor's
12118        // `.as_bytes()` byte-view resolve to the same four-arm PascalCase
12119        // wire byte-string emit-set across every arm the exhaustive
12120        // [`super::RestartStrategy::ALL`] slice enumerates. Additionally
12121        // asserts the returned `Cow<'static, [u8]>` binds the zero-alloc
12122        // `Cow::Borrowed` arm on both input shapes, because
12123        // `Self::as_str` returns `&'static str` and `.as_bytes()` on it
12124        // preserves the `&'static [u8]` lifetime by construction.
12125        //
12126        // Generic `<T: Into<Cow<'static, [u8]>>>`-bound consumer witness
12127        // helper: a future per-supervisor byte-writer that accepts a
12128        // `Cow<'static, [u8]>` composes on both owned and borrowed input
12129        // shapes without an open-coded three-hop
12130        // `Cow::Borrowed(strategy.as_str().as_bytes())` at every call
12131        // site. Lifted to the top of the function per
12132        // `clippy::items_after_statements`.
12133        fn generic_cow_bytes_sink<T: Into<std::borrow::Cow<'static, [u8]>>>(
12134            t: T,
12135        ) -> std::borrow::Cow<'static, [u8]> {
12136            t.into()
12137        }
12138        for &variant in RestartStrategy::ALL {
12139            let via_owned_from: std::borrow::Cow<'static, [u8]> =
12140                <std::borrow::Cow<'static, [u8]> as From<RestartStrategy>>::from(variant);
12141            let via_borrowed_from: std::borrow::Cow<'static, [u8]> =
12142                <std::borrow::Cow<'static, [u8]> as From<&RestartStrategy>>::from(&variant);
12143            let via_method_bytes: &'static [u8] = variant.as_str().as_bytes();
12144            assert_eq!(
12145                via_owned_from.as_ref(),
12146                via_method_bytes,
12147                "From<RestartStrategy> for Cow<'static, [u8]> impl must \
12148                 byte-equal RestartStrategy::as_str().as_bytes() on \
12149                 RestartStrategy::{variant:?} — divergence signals a \
12150                 silent detour off the substrate-primitive accessor"
12151            );
12152            assert_eq!(
12153                via_borrowed_from.as_ref(),
12154                via_method_bytes,
12155                "From<&RestartStrategy> for Cow<'static, [u8]> impl must \
12156                 byte-equal RestartStrategy::as_str().as_bytes() on \
12157                 RestartStrategy::{variant:?} — divergence signals a \
12158                 silent detour off the substrate-primitive accessor"
12159            );
12160            assert!(
12161                matches!(via_owned_from, std::borrow::Cow::Borrowed(_)),
12162                "From<RestartStrategy> for Cow<'static, [u8]> must bind \
12163                 the zero-alloc Cow::Borrowed arm on \
12164                 RestartStrategy::{variant:?} — Self::as_str returns \
12165                 &'static str, so a Cow::Owned arm signals a silent \
12166                 allocation off the substrate primitive"
12167            );
12168            assert!(
12169                matches!(via_borrowed_from, std::borrow::Cow::Borrowed(_)),
12170                "From<&RestartStrategy> for Cow<'static, [u8]> must bind \
12171                 the zero-alloc Cow::Borrowed arm on \
12172                 &RestartStrategy::{variant:?} — Self::as_str returns \
12173                 &'static str, so a Cow::Owned arm signals a silent \
12174                 allocation off the substrate primitive"
12175            );
12176            // Cross-axis partition against the paired byte-owned
12177            // `Vec<u8>` reverse-projection axis (7cc10eb line 1579) on
12178            // the same enum — the two byte-owned reverse-projection
12179            // axes must byte-agree on every arm.
12180            let via_vec_bytes: Vec<u8> = <Vec<u8> as From<RestartStrategy>>::from(variant);
12181            assert_eq!(
12182                via_owned_from.as_ref(),
12183                via_vec_bytes.as_slice(),
12184                "From<RestartStrategy> for Cow<'static, [u8]> and \
12185                 From<RestartStrategy> for Vec<u8> must byte-agree on \
12186                 RestartStrategy::{variant:?} — divergence signals the \
12187                 two byte-owned reverse-projection axes have drifted \
12188                 off the same substrate-primitive as_str accessor"
12189            );
12190            // Cross-axis partition against the paired str-side
12191            // `Cow<'static, str>` reverse-projection axis (7dd28b3) on
12192            // the same enum — the byte-side and str-side Cow<'static, _>
12193            // axes must both bind the Cow::Borrowed arm on every arm
12194            // (both route through Self::as_str's &'static return).
12195            let via_cow_str: std::borrow::Cow<'static, str> =
12196                <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
12197            assert_eq!(
12198                via_owned_from.as_ref(),
12199                via_cow_str.as_bytes(),
12200                "From<RestartStrategy> for Cow<'static, [u8]> and \
12201                 From<RestartStrategy> for Cow<'static, str> must \
12202                 byte-agree on RestartStrategy::{variant:?} — \
12203                 divergence signals a silent detour off the shared \
12204                 substrate-primitive as_str accessor"
12205            );
12206        }
12207        for &variant in RestartStrategy::ALL {
12208            let owned_via_generic = generic_cow_bytes_sink(variant);
12209            let variant_ref: &RestartStrategy = &variant;
12210            let borrowed_via_generic = generic_cow_bytes_sink(variant_ref);
12211            assert_eq!(
12212                owned_via_generic.as_ref(),
12213                variant.as_str().as_bytes(),
12214                "<T: Into<Cow<'static, [u8]>>>-bound composition on \
12215                 RestartStrategy::{variant:?} must fold the same byte-\
12216                 tail RestartStrategy::as_str().as_bytes() returns"
12217            );
12218            assert_eq!(
12219                borrowed_via_generic.as_ref(),
12220                variant.as_str().as_bytes(),
12221                "<T: Into<Cow<'static, [u8]>>>-bound composition on \
12222                 &RestartStrategy::{variant:?} must fold the same byte-\
12223                 tail RestartStrategy::as_str().as_bytes() returns"
12224            );
12225        }
12226    }
12227
12228    #[test]
12229    fn restart_policy_try_from_str_routes_through_from_wire_accessor() {
12230        // Fail-before-pass-after byte-parity pin on the newly lifted
12231        // `impl TryFrom<&str> for RestartPolicy` — asserts the standard-
12232        // library trait impl and the substrate-primitive
12233        // [`RestartPolicy::from_wire`] `Option<Self>` accessor resolve to
12234        // the same three-arm accept-set across every arm the exhaustive
12235        // [`RestartPolicy::ALL`] slice enumerates. Any future silent
12236        // detour that routes the trait impl through a divergent
12237        // projection (a per-arm inline `match s { "Permanent" =>
12238        // Ok(Self::Permanent), … }` re-inlining that opens a compile-time
12239        // link to the un-lifted arm-literal, a hypothetical
12240        // `#[serde(rename_all = "…")]` attribute drift that silently
12241        // splits the wire byte-string from every consumer that reaches
12242        // for this typed dispatch, an accidental swap onto the kebab-case
12243        // dispatcher-catalog axis the pre-existing [`std::str::FromStr`]
12244        // impl parses through and which would collide the two-axis
12245        // wire/catalog split the sibling [`RestartPolicy::from_wire`]
12246        // doc block makes load-bearing) trips at caixa-core test time
12247        // under `assert_eq!` rather than at a downstream
12248        // `impl TryFrom<&str>`-bound consumer's silent split. Sweeps
12249        // every one of the three arms [`RestartPolicy::ALL`] carries so
12250        // no arm's projection is covered only by the sibling method-
12251        // named `from_wire` path. Peer of the sibling
12252        // [`restart_strategy_try_from_str_routes_through_from_wire_accessor`]
12253        // (5b828ed) — extends the trait-idiomatic reverse-projection
12254        // axis onto the third and final M2-OTP-shape closed-set typed
12255        // enum on the caixa surface (the paired per-child restart-
12256        // decision-policy sibling on the same M2 `:supervisor` slot).
12257        for &variant in RestartPolicy::ALL {
12258            let wire = variant.as_str();
12259            assert_eq!(
12260                <RestartPolicy as TryFrom<&str>>::try_from(wire),
12261                Ok(variant),
12262                "TryFrom<&str> impl on RestartPolicy must round-trip \
12263                 RestartPolicy::{variant:?}.as_str() = {wire:?} back to \
12264                 Ok(RestartPolicy::{variant:?}) — divergence from \
12265                 RestartPolicy::from_wire signals a silent detour off \
12266                 the substrate-primitive accessor"
12267            );
12268            assert_eq!(
12269                <RestartPolicy as TryFrom<&str>>::try_from(wire).ok(),
12270                RestartPolicy::from_wire(wire),
12271                "TryFrom<&str> ok()-projection on {wire:?} must byte-\
12272                 equal RestartPolicy::from_wire on the same input"
12273            );
12274        }
12275    }
12276
12277    #[test]
12278    fn restart_policy_try_from_str_rejects_unknown_byte_strings() {
12279        // Rejection witness on the `impl TryFrom<&str> for
12280        // RestartPolicy` — sweeps a candidate set of byte-strings
12281        // outside the three-arm PascalCase wire accept-set the sibling
12282        // [`RestartPolicy::as_str`] emits and asserts every one lands on
12283        // `Err(())`, so a future accidental widening of the trait impl's
12284        // accept-set (a stray additional
12285        // `_ if s.eq_ignore_ascii_case("Permanent") => Ok(…)` case-fold
12286        // path, a silent inclusion of the kebab-case dispatcher-catalog
12287        // byte-string the pre-existing [`std::str::FromStr`] impl the
12288        // [`gen_platform::FromStrKind`] derive installs parses onto the
12289        // wire axis — which would collide the two-axis
12290        // wire/dispatcher-catalog split the sibling
12291        // [`RestartPolicy::from_wire`] doc block makes load-bearing —
12292        // an English-rebrand or plural-arm silent alias that would widen
12293        // the wire accept-set past the OTP-canonical three) trips at
12294        // caixa-core test time. The candidate set includes the empty
12295        // string, whitespace-only padding, the kebab-case dispatcher-
12296        // catalog byte-strings on the sibling axis (a caller who
12297        // confuses the two axes trips here rather than at a downstream
12298        // consumer's silent reject), a lowercase / uppercase / mixed-case
12299        // fold of each PascalCase arm (a caller who assumes case-fold
12300        // acceptance trips here), leading/trailing whitespace padding,
12301        // the trailing-newline shape, quote-wrapped candidates, and a
12302        // residual set of plausible-but-wrong English rebrand
12303        // candidates. Peer of the sibling
12304        // [`restart_strategy_try_from_str_rejects_unknown_byte_strings`]
12305        // (5b828ed) rejection witness.
12306        let rejected: &[&str] = &[
12307            "",
12308            " ",
12309            "\n",
12310            "\t",
12311            "permanent",
12312            "temporary",
12313            "transient",
12314            "PERMANENT",
12315            "TEMPORARY",
12316            "TRANSIENT",
12317            "Permanents",
12318            "Permanent ",
12319            " Permanent",
12320            " Temporary ",
12321            "Permanent\n",
12322            "Transient\t",
12323            "\"Permanent\"",
12324            "Ephemeral",
12325            "Always",
12326            "Never",
12327            "OnAbnormalExit",
12328            "intrinsic",
12329            "?",
12330        ];
12331        for &input in rejected {
12332            assert_eq!(
12333                <RestartPolicy as TryFrom<&str>>::try_from(input),
12334                Err(()),
12335                "TryFrom<&str> impl on RestartPolicy must reject the \
12336                 non-wire byte-string {input:?} — silent acceptance \
12337                 signals an accept-set widening off the paired \
12338                 RestartPolicy::from_wire resolver"
12339            );
12340        }
12341    }
12342
12343    #[test]
12344    fn restart_policy_try_from_str_and_from_wire_partition_the_accept_set() {
12345        // Cross-axis partition pin: the paired `TryFrom<&str>` and
12346        // `from_wire` reverse projections must resolve identically on
12347        // *every* input, not just the ones [`RestartPolicy::ALL`]
12348        // enumerates. Sweeps a mixed candidate set spanning accepted
12349        // (three-arm PascalCase wire byte-strings) and rejected (kebab-
12350        // case dispatcher-catalog byte-strings, empty, whitespace-
12351        // padded, quoted, English-rebrand candidates) inputs and asserts
12352        // the trait's `Result::ok()` projection byte-equals the method-
12353        // named resolver's `Option<Self>` return-shape on each, locking
12354        // the two paths together by construction so any future detour
12355        // (a stray `try_from` special-case that widens or narrows the
12356        // accept-set outside the paired `from_wire` resolver, an
12357        // accidental swap onto the kebab-case [`std::str::FromStr`]
12358        // impl the [`gen_platform::FromStrKind`] derive installs on the
12359        // sibling dispatcher-catalog axis) trips at caixa-core test
12360        // time. Peer of the sibling
12361        // [`restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
12362        // pin — extends the round-trip discipline onto the M2-OTP-shape
12363        // per-child restart-policy axis.
12364        let candidates: &[&str] = &[
12365            "Permanent",
12366            "Temporary",
12367            "Transient",
12368            "",
12369            "permanent",
12370            "temporary",
12371            "transient",
12372            "PERMANENT",
12373            "unknown",
12374            "Permanent ",
12375            " Permanent",
12376            "\"Permanent\"",
12377            "Ephemeral",
12378            "OnAbnormalExit",
12379            "?",
12380        ];
12381        for &input in candidates {
12382            let via_trait: Option<RestartPolicy> =
12383                <RestartPolicy as TryFrom<&str>>::try_from(input).ok();
12384            let via_method: Option<RestartPolicy> = RestartPolicy::from_wire(input);
12385            assert_eq!(
12386                via_trait, via_method,
12387                "TryFrom<&str> and from_wire must resolve identically on \
12388                 input {input:?} — divergence signals the two reverse-\
12389                 projection paths have drifted onto different accept-sets"
12390            );
12391        }
12392    }
12393
12394    #[test]
12395    fn restart_policy_from_into_static_str_routes_through_as_str_accessor() {
12396        // Fail-before-pass-after byte-parity pin on the newly lifted
12397        // `impl From<RestartPolicy> for &'static str` — asserts the
12398        // standard-library trait impl and the substrate-primitive
12399        // [`RestartPolicy::as_str`] `pub const fn` accessor resolve to
12400        // the same three-arm emit-set across every arm the exhaustive
12401        // [`RestartPolicy::ALL`] slice enumerates. Any future silent
12402        // detour that routes the trait impl through a divergent
12403        // projection (a per-arm inline `match policy { Permanent =>
12404        // "Permanent", … }` re-inlining that opens a compile-time link
12405        // to the un-lifted arm-literal, an accidental swap onto the
12406        // sibling kebab-case [`Self::discriminant`] dispatcher-catalog
12407        // axis that would collide the two-axis wire/catalog split the
12408        // sibling [`RestartPolicy::from_wire`] doc block makes
12409        // load-bearing) trips at caixa-core test time under
12410        // `assert_eq!` rather than at a downstream
12411        // `impl Into<&'static str>`-bound consumer's silent split.
12412        // Sweeps every one of the three arms [`RestartPolicy::ALL`]
12413        // carries so no arm's projection is covered only by the sibling
12414        // method-named `as_str` / [`std::fmt::Display`] / [`AsRef<str>`]
12415        // paths. Materializes the `<&'static str as
12416        // From<RestartPolicy>>::from` output in a `const`-shape binding
12417        // to make the `'static` lifetime promise a build-time invariant
12418        // — a future accidental downgrade of any of the three arms'
12419        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] constants to a
12420        // non-`&'static str` (a `String::leak()`-produced return, a
12421        // `Box::leak`-cast) trips at caixa-core build time rather than
12422        // at a downstream `'static`-bound consumer. Peer of the sibling
12423        // [`restart_strategy_from_into_static_str_routes_through_as_str_accessor`]
12424        // (523157d) — extends the trait-idiomatic forward-projection
12425        // axis onto the second (and second-of-two-in-M2) closed-set
12426        // typed enum on the caixa surface (the paired per-child
12427        // restart-decision-policy sibling on the same M2 `:supervisor`
12428        // slot).
12429        const PERMANENT: &str = RestartPolicy::Permanent.as_str();
12430        const TEMPORARY: &str = RestartPolicy::Temporary.as_str();
12431        const TRANSIENT: &str = RestartPolicy::Transient.as_str();
12432        for &variant in RestartPolicy::ALL {
12433            let via_trait: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
12434            let via_method: &'static str = variant.as_str();
12435            assert_eq!(
12436                via_trait, via_method,
12437                "From<RestartPolicy> for &'static str impl must round-trip \
12438                 RestartPolicy::{variant:?} to the same lifted \
12439                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str returns — \
12440                 divergence signals a silent detour off the substrate-primitive \
12441                 accessor"
12442            );
12443            let via_into: &'static str = variant.into();
12444            assert_eq!(
12445                via_into, via_method,
12446                "Into<&'static str>::into on RestartPolicy::{variant:?} must \
12447                 byte-equal RestartPolicy::as_str on the same input — the \
12448                 blanket-derived Into shape must resolve to the same as_str \
12449                 dispatch as the explicit From impl"
12450            );
12451        }
12452        assert_eq!(
12453            [PERMANENT, TEMPORARY, TRANSIENT],
12454            [
12455                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
12456                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
12457                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
12458            ],
12459            "const-context RestartPolicy::as_str must resolve to the three \
12460             lifted SUPERVISOR_CHILD_RESTART_* consts — a future accidental \
12461             downgrade of any arm to a non-const or non-static byte-string \
12462             breaks the `&'static str`-lifetime promise the paired \
12463             From<RestartPolicy> for &'static str impl carries by \
12464             construction"
12465        );
12466    }
12467
12468    #[test]
12469    fn restart_policy_from_into_static_str_and_as_str_partition_the_emit_set() {
12470        // Cross-axis partition pin: the paired trait-idiomatic
12471        // `From<RestartPolicy> for &'static str` forward projection and
12472        // the method-named [`RestartPolicy::as_str`] forward projection
12473        // must resolve identically on *every* arm, not just the ones
12474        // named in the primary byte-parity pin above. Sweeps every
12475        // [`RestartPolicy::ALL`] arm and asserts the trait's `From::from`
12476        // output byte-equals the method-named accessor's return-value on
12477        // each, locking the two forward-projection paths together by
12478        // construction so any future detour (a stray `From` special-case
12479        // that lands on a divergent per-arm literal outside the paired
12480        // `as_str` dispatch, a hypothetical rebrand touching one axis
12481        // without the other) trips at caixa-core test time. Peer of the
12482        // sibling forward-projection partition pin
12483        // [`restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
12484        // (523157d) — extends the round-trip discipline onto the
12485        // second-of-two M2-OTP-shape closed-set typed enum on the caixa
12486        // surface, closing the two-way `Self ↔ &'static str` round-trip
12487        // on the trait-idiomatic pair (`From<Self> for &'static str` +
12488        // `TryFrom<&str> for Self`) as well as the pre-existing method-
12489        // named pair (`as_str` + `from_wire`).
12490        for &variant in RestartPolicy::ALL {
12491            let via_trait: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
12492            let via_method: &'static str = variant.as_str();
12493            assert_eq!(
12494                via_trait, via_method,
12495                "From<RestartPolicy> for &'static str and \
12496                 RestartPolicy::as_str must resolve identically on \
12497                 RestartPolicy::{variant:?} — divergence signals the \
12498                 two forward-projection paths have drifted onto different \
12499                 emit-sets"
12500            );
12501        }
12502        // Round-trip witness: every arm's forward `From` output re-parses
12503        // through the paired trait-idiomatic reverse `TryFrom<&str>` back
12504        // to the original variant. Closes the two-way `RestartPolicy ↔
12505        // &'static str` round-trip on the trait-idiomatic axis pair,
12506        // mirroring the pre-existing method-named `as_str` + `from_wire`
12507        // round-trip on the substrate-primitive axis pair.
12508        for &variant in RestartPolicy::ALL {
12509            let emitted: &'static str = variant.into();
12510            let re_parsed: Result<RestartPolicy, ()> =
12511                <RestartPolicy as TryFrom<&str>>::try_from(emitted);
12512            assert_eq!(
12513                re_parsed,
12514                Ok(variant),
12515                "trait-idiomatic axis pair must round-trip \
12516                 RestartPolicy::{variant:?} through `.into::<&'static \
12517                 str>()` and back through `TryFrom<&str>` — a break signals \
12518                 the forward-emit and reverse-parse axes have drifted onto \
12519                 different vocabularies"
12520            );
12521        }
12522    }
12523
12524    #[test]
12525    fn restart_policy_from_borrowed_into_static_str_routes_through_as_str_accessor() {
12526        // Fail-before-pass-after byte-parity pin on the newly lifted
12527        // `impl From<&RestartPolicy> for &'static str` — asserts the
12528        // borrowed-input standard-library trait impl and the substrate-
12529        // primitive [`RestartPolicy::as_str`] `pub const fn` accessor
12530        // resolve to the same three-arm emit-set across every arm the
12531        // exhaustive [`RestartPolicy::ALL`] slice enumerates. Rust's
12532        // `From` trait does not auto-derive the borrowed-input sibling
12533        // from a paired owned-input impl (no `impl<T, U> From<&T> for U
12534        // where T: Copy, U: From<T>` blanket in `core`), so the
12535        // borrowed-input axis is a distinct trait-idiomatic surface
12536        // that a `.iter().map(Into::into)` shape over
12537        // [`RestartPolicy::ALL`] (whose iterator yields
12538        // `&RestartPolicy`, not `RestartPolicy`) reaches through this
12539        // impl and no other — the paired owned-input
12540        // [`From<RestartPolicy>`] impl requires an explicit `.copied()`
12541        // / dereference before the trait fires. Materializes the
12542        // `<&'static str as From<&RestartPolicy>>::from` output in a
12543        // `const`-shape binding to make the `'static` lifetime promise
12544        // a build-time invariant.
12545        const PERMANENT: &str = RestartPolicy::Permanent.as_str();
12546        const TEMPORARY: &str = RestartPolicy::Temporary.as_str();
12547        const TRANSIENT: &str = RestartPolicy::Transient.as_str();
12548        for variant in RestartPolicy::ALL {
12549            let via_trait: &'static str = <&'static str as From<&RestartPolicy>>::from(variant);
12550            let via_method: &'static str = variant.as_str();
12551            assert_eq!(
12552                via_trait, via_method,
12553                "From<&RestartPolicy> for &'static str impl must round-trip \
12554                 &RestartPolicy::{variant:?} to the same lifted \
12555                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
12556                 returns — divergence signals a silent detour off the \
12557                 substrate-primitive accessor"
12558            );
12559            let via_into: &'static str = variant.into();
12560            assert_eq!(
12561                via_into, via_method,
12562                "Into<&'static str>::into on &RestartPolicy::{variant:?} \
12563                 must byte-equal RestartPolicy::as_str on the same input — \
12564                 the blanket-derived Into shape must resolve to the same \
12565                 as_str dispatch as the explicit From impl"
12566            );
12567        }
12568        assert_eq!(
12569            [PERMANENT, TEMPORARY, TRANSIENT],
12570            [
12571                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
12572                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
12573                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
12574            ],
12575            "const-context RestartPolicy::as_str must resolve to the three \
12576             lifted SUPERVISOR_CHILD_RESTART_* consts — the borrowed-input \
12577             From<&RestartPolicy> for &'static str impl inherits its \
12578             `'static` lifetime promise from the same accessor the \
12579             owned-input sibling routes through"
12580        );
12581    }
12582
12583    #[test]
12584    fn restart_policy_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
12585        // Cross-axis partition pin: the paired trait-idiomatic
12586        // owned-input `From<RestartPolicy> for &'static str` (9fb37d0
12587        // campaign-shape) and borrowed-input `From<&RestartPolicy> for
12588        // &'static str` (this lift) forward projections must resolve
12589        // identically on every arm, locking the two input-shape paths
12590        // together so any future detour trips at caixa-core test time.
12591        // Then a witness that a `.iter().map(Into::into)` pipe over
12592        // [`RestartPolicy::ALL`] (whose iterator yields
12593        // `&RestartPolicy`) materializes the three-arm accept-set
12594        // through the borrowed-input axis alone — the exact shape a
12595        // future wasm-operator per-child post-exit restart-decision
12596        // diagnostic line, a future substrate-wide per-arm diagnostic
12597        // column, or a
12598        // `HashMap::<&'static str, RestartPolicy>::from_iter(
12599        //     RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))`-style
12600        // per-policy lookup reaches through — closing the two-way
12601        // owned/borrowed input-shape symmetry on the forward-projection
12602        // trait-idiomatic axis. Peer of the sibling
12603        // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
12604        // (64aa742) /
12605        // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
12606        // (5ab993a) /
12607        // [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
12608        // (807b0b5) /
12609        // [`restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
12610        // (e941836) partition pins on the sibling closed-set typed-enum
12611        // discriminator axes — extends the borrowed-input axis
12612        // discipline onto the second-of-two M2 OTP-shape closed-set
12613        // typed enum on the caixa surface (per-child restart-decision
12614        // policy). Also closes the direct two-way `&Self → &'static
12615        // str → Self` round-trip via the paired [`TryFrom<&str>`] axis
12616        // — unlike the peer [`crate::CaixaKind`] axis pair (whose
12617        // forward `From` emits lowercase Portuguese diagnostic bytes
12618        // while the reverse `TryFrom` parses `PascalCase` wire bytes,
12619        // forcing the round-trip through an intermediate wire-vocab
12620        // hop), the [`RestartPolicy::as_str`] emit and
12621        // [`RestartPolicy::from_wire`] parse share the same
12622        // `PascalCase` vocabulary by construction, so the borrowed-
12623        // input forward axis and the reverse axis compose directly.
12624        for &variant in RestartPolicy::ALL {
12625            let owned: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
12626            let borrowed: &'static str = <&'static str as From<&RestartPolicy>>::from(&variant);
12627            assert_eq!(
12628                owned, borrowed,
12629                "From<RestartPolicy> and From<&RestartPolicy> for \
12630                 &'static str must resolve identically on \
12631                 RestartPolicy::{variant:?} — divergence signals the \
12632                 owned-input and borrowed-input forward-projection paths \
12633                 have drifted onto different emit-sets"
12634            );
12635        }
12636        let via_iter: Vec<&'static str> = RestartPolicy::ALL.iter().map(Into::into).collect();
12637        let via_method: Vec<&'static str> = RestartPolicy::ALL.iter().map(|p| p.as_str()).collect();
12638        assert_eq!(
12639            via_iter, via_method,
12640            "`.iter().map(Into::into)` over RestartPolicy::ALL must \
12641             byte-equal `.iter().map(|p| p.as_str())` on every arm — the \
12642             borrowed-input `From<&RestartPolicy> for &'static str` axis \
12643             is what makes the `.iter().map(Into::into)` shape route \
12644             through the substrate-primitive `RestartPolicy::as_str` \
12645             accessor rather than through a per-call-site `.copied()` / \
12646             dereference detour"
12647        );
12648        for variant in RestartPolicy::ALL {
12649            let emitted: &'static str = variant.into();
12650            let re_parsed: Result<RestartPolicy, ()> =
12651                <RestartPolicy as TryFrom<&str>>::try_from(emitted);
12652            assert_eq!(
12653                re_parsed,
12654                Ok(*variant),
12655                "trait-idiomatic borrowed-input forward-projection + \
12656                 reverse-projection axis pair must round-trip \
12657                 &RestartPolicy::{variant:?} through `.into::<&'static \
12658                 str>()` (via the borrowed-input axis) and back through \
12659                 `TryFrom<&str>` — a break signals the borrowed-input \
12660                 forward-emit and reverse-parse axes have drifted onto \
12661                 different vocabularies"
12662            );
12663        }
12664    }
12665
12666    #[test]
12667    fn restart_policy_from_into_owned_string_routes_through_as_str_accessor() {
12668        // Fail-before-pass-after byte-parity pin on the newly lifted
12669        // `impl From<RestartPolicy> for String` — asserts the
12670        // owned-`String`-returning standard-library trait impl and the
12671        // substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
12672        // accessor resolve to the same three-arm emit-set across every
12673        // arm the exhaustive [`RestartPolicy::ALL`] slice enumerates.
12674        // Rust's standard library does not carry a blanket
12675        // `impl<T: AsRef<str>> From<T> for String` (nor an
12676        // `impl<T: fmt::Display> From<T> for String`), so the
12677        // owned-`String` forward-projection axis is a distinct
12678        // trait-idiomatic surface that a `let key: String =
12679        // policy.into();`-shaped call site reaches through this impl
12680        // and no other — the paired sibling `From<RestartPolicy> for
12681        // &'static str` impl forces every owned-`String` call site
12682        // through an explicit `.to_owned()` / `String::from`
12683        // restatement. Peer of the first-mover
12684        // [`restart_strategy_from_into_owned_string_routes_through_as_str_accessor`]
12685        // (7baa18a) — extends the trait-idiomatic owned-`String`
12686        // forward-projection axis onto the second-of-two M2 OTP-shape
12687        // closed-set typed enums on the caixa surface (per-child
12688        // restart-decision-policy sibling on the same M2 `:supervisor`
12689        // slot).
12690        for &variant in RestartPolicy::ALL {
12691            let via_trait: String = <String as From<RestartPolicy>>::from(variant);
12692            let via_method: &'static str = variant.as_str();
12693            assert_eq!(
12694                via_trait.as_str(),
12695                via_method,
12696                "From<RestartPolicy> for String impl must round-trip \
12697                 RestartPolicy::{variant:?} to the same lifted \
12698                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
12699                 returns — divergence signals a silent detour off the \
12700                 substrate-primitive accessor"
12701            );
12702            let via_into: String = variant.into();
12703            assert_eq!(
12704                via_into.as_str(),
12705                via_method,
12706                "Into<String>::into on RestartPolicy::{variant:?} must \
12707                 byte-equal RestartPolicy::as_str on the same input — the \
12708                 blanket-derived Into shape must resolve to the same as_str \
12709                 dispatch as the explicit From impl"
12710            );
12711        }
12712    }
12713
12714    #[test]
12715    fn restart_policy_from_into_owned_string_and_static_str_agree_on_every_arm() {
12716        // Cross-axis partition pin: the paired trait-idiomatic
12717        // owned-`String` `From<RestartPolicy> for String` (this lift)
12718        // and owned-`&'static str` `From<RestartPolicy> for &'static
12719        // str` (9fb37d0) forward projections must resolve identically
12720        // on every arm, locking the two return-type-shape paths
12721        // together so any future detour trips at caixa-core test time.
12722        // Also byte-parity witness against the sibling
12723        // [`ToString::to_string`] surface routed through
12724        // [`std::fmt::Display`] — the three owned-heap-string paths
12725        // (`.into::<String>()`, `String::from`, `.to_string()`) must
12726        // resolve identically on every arm so a future consumer that
12727        // picks any of the three lands on the same lifted
12728        // SUPERVISOR_CHILD_RESTART_* const. Then a `.iter().copied()
12729        // .map(String::from)` pipe witness over [`RestartPolicy::ALL`]
12730        // that materializes the three-arm accept-set through the
12731        // owned-`String` axis alone — the exact shape a future
12732        // wasm-operator per-child post-exit restart-decision
12733        // diagnostic line composer or a
12734        // `HashMap::<String, RestartPolicy>::from_iter(
12735        //     RestartPolicy::ALL.iter().copied().map(|p| (p.into(), p)))`-style
12736        // owned-key per-policy lookup reaches through — closing the
12737        // owned-`String` forward-projection axis's iterator-pipe
12738        // shape. Then a direct round-trip witness through the paired
12739        // trait-idiomatic reverse [`TryFrom<&str>`] axis on the
12740        // owned-`String`'s [`String::as_str`] borrow that closes the
12741        // two-way `Self → String → Self` round-trip on the trait-
12742        // idiomatic owned-`String` forward + reverse axis pair —
12743        // unlike the peer [`crate::CaixaKind`] axis pair (whose
12744        // forward `From` emits lowercase Portuguese diagnostic bytes
12745        // while the reverse `TryFrom` parses `PascalCase` wire bytes,
12746        // forcing the round-trip through an intermediate wire-vocab
12747        // hop), the [`RestartPolicy::as_str`] emit and
12748        // [`RestartPolicy::from_wire`] parse share the same
12749        // `PascalCase` vocabulary by construction, so the owned-
12750        // `String` forward axis and the reverse axis compose directly.
12751        for &variant in RestartPolicy::ALL {
12752            let owned_string: String = <String as From<RestartPolicy>>::from(variant);
12753            let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
12754            assert_eq!(
12755                owned_string.as_str(),
12756                owned_static,
12757                "From<RestartPolicy> for String and From<RestartPolicy> \
12758                 for &'static str must resolve identically on \
12759                 RestartPolicy::{variant:?} — divergence signals the \
12760                 owned-`String` and owned-`&'static str` forward-projection \
12761                 return-type-shape paths have drifted onto different \
12762                 emit-sets"
12763            );
12764            let via_to_string: String = variant.to_string();
12765            assert_eq!(
12766                owned_string, via_to_string,
12767                "From<RestartPolicy> for String must byte-equal \
12768                 RestartPolicy::to_string on RestartPolicy::{variant:?} — \
12769                 divergence signals the trait-idiomatic owned-`String` \
12770                 forward-projection axis and the ToString-through-Display \
12771                 axis have drifted onto different emit-sets"
12772            );
12773        }
12774        let via_iter: Vec<String> = RestartPolicy::ALL
12775            .iter()
12776            .copied()
12777            .map(String::from)
12778            .collect();
12779        let via_method: Vec<String> = RestartPolicy::ALL
12780            .iter()
12781            .map(|p| p.as_str().to_owned())
12782            .collect();
12783        assert_eq!(
12784            via_iter, via_method,
12785            "`.iter().copied().map(String::from)` over RestartPolicy::ALL \
12786             must byte-equal `.iter().map(|p| p.as_str().to_owned())` on \
12787             every arm — the owned-`String` `From<RestartPolicy> for \
12788             String` axis is what makes the `String::from` composition \
12789             route through the substrate-primitive `RestartPolicy::as_str` \
12790             accessor rather than through a per-call-site `.to_owned()` / \
12791             `String::from(policy.as_str())` detour"
12792        );
12793        for &variant in RestartPolicy::ALL {
12794            let emitted: String = variant.into();
12795            let re_parsed: Result<RestartPolicy, ()> =
12796                <RestartPolicy as TryFrom<&str>>::try_from(emitted.as_str());
12797            assert_eq!(
12798                re_parsed,
12799                Ok(variant),
12800                "trait-idiomatic owned-`String` forward-projection + \
12801                 reverse-projection axis pair must round-trip \
12802                 RestartPolicy::{variant:?} through `.into::<String>()` \
12803                 and back through `TryFrom<&str>` on the owned-`String`'s \
12804                 String::as_str borrow — a break signals the owned-`String` \
12805                 forward-emit and reverse-parse axes have drifted onto \
12806                 different vocabularies"
12807            );
12808        }
12809    }
12810
12811    #[test]
12812    fn restart_policy_from_into_borrowed_owned_string_routes_through_as_str_accessor() {
12813        // Fail-before-pass-after byte-parity pin on the newly lifted
12814        // `impl From<&RestartPolicy> for String` — asserts the
12815        // borrowed-input owned-`String`-returning standard-library
12816        // trait impl and the substrate-primitive
12817        // [`RestartPolicy::as_str`] `pub const fn` accessor resolve to
12818        // the same three-arm emit-set across every arm the exhaustive
12819        // [`RestartPolicy::ALL`] slice enumerates. Rust's standard
12820        // library does not carry a blanket `impl<T: AsRef<str>>
12821        // From<&T> for String` (nor an `impl<T: fmt::Display> From<&T>
12822        // for String`), so the borrowed-input owned-`String` forward-
12823        // projection axis is a distinct trait-idiomatic surface that a
12824        // `let key: String = (&policy).into();`-shaped call site
12825        // reaches through this impl and no other — the paired sibling
12826        // `From<RestartPolicy> for String` impl forces every borrowed-
12827        // input call site through an explicit `Copy` deref
12828        // (`String::from(*policy)`) or an `.as_str().to_owned()` /
12829        // `.to_string()` detour. Peer of the first-mover
12830        // [`restart_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
12831        // (579385f) — extends the trait-idiomatic borrowed-input
12832        // owned-`String` forward-projection axis onto the second-of-
12833        // two M2 OTP-shape closed-set typed enums on the caixa surface
12834        // (per-child restart-decision-policy sibling on the same M2
12835        // `:supervisor` slot).
12836        for &variant in RestartPolicy::ALL {
12837            let via_trait: String = <String as From<&RestartPolicy>>::from(&variant);
12838            let via_method: &'static str = variant.as_str();
12839            assert_eq!(
12840                via_trait.as_str(),
12841                via_method,
12842                "From<&RestartPolicy> for String impl must round-trip \
12843                 &RestartPolicy::{variant:?} to the same lifted \
12844                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
12845                 returns — divergence signals a silent detour off the \
12846                 substrate-primitive accessor"
12847            );
12848            let via_into: String = (&variant).into();
12849            assert_eq!(
12850                via_into.as_str(),
12851                via_method,
12852                "Into<String>::into on &RestartPolicy::{variant:?} must \
12853                 byte-equal RestartPolicy::as_str on the same input — \
12854                 the blanket-derived Into shape must resolve to the \
12855                 same as_str dispatch as the explicit From impl"
12856            );
12857        }
12858    }
12859
12860    #[test]
12861    fn restart_policy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm() {
12862        // Cross-axis partition pin: the newly lifted trait-idiomatic
12863        // borrowed-input owned-`String` `From<&RestartPolicy> for
12864        // String` (this lift), the paired owned-input owned-`String`
12865        // `From<RestartPolicy> for String` (7851725), the paired
12866        // borrowed-input owned-`&'static str` `From<&RestartPolicy>
12867        // for &'static str` (842c7f3), and the paired owned-input
12868        // owned-`&'static str` `From<RestartPolicy> for &'static str`
12869        // (9fb37d0) — every corner of the `{Self, &Self} × {&'static
12870        // str, String}` 2×2 trait-idiomatic projection family — must
12871        // resolve identically on every arm, locking the four
12872        // return-shape × input-shape paths together so any future
12873        // detour trips at caixa-core test time. Also byte-parity
12874        // witness against the sibling [`ToString::to_string`] surface
12875        // routed through [`std::fmt::Display`] and a direct round-trip
12876        // witness through the paired trait-idiomatic reverse
12877        // [`TryFrom<&str>`] axis on the owned-`String`'s
12878        // [`String::as_str`] borrow that closes the two-way
12879        // `&Self → String → Self` round-trip on the trait-idiomatic
12880        // borrowed-input owned-`String` forward + reverse axis pair.
12881        // Peer of the first-mover
12882        // [`restart_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
12883        // (579385f) — closes the whole `{Self, &Self} × {&'static str,
12884        // String}` 2×2 projection corner on both M2 OTP-shape sibling
12885        // peers.
12886        for &variant in RestartPolicy::ALL {
12887            let borrowed_string: String = <String as From<&RestartPolicy>>::from(&variant);
12888            let owned_string: String = <String as From<RestartPolicy>>::from(variant);
12889            let borrowed_static: &'static str =
12890                <&'static str as From<&RestartPolicy>>::from(&variant);
12891            let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
12892            assert_eq!(
12893                borrowed_string, owned_string,
12894                "From<&RestartPolicy> for String and From<RestartPolicy> \
12895                 for String must resolve identically on \
12896                 RestartPolicy::{variant:?} — divergence signals the \
12897                 borrowed-input and owned-input owned-`String` \
12898                 forward-projection input-shape paths have drifted onto \
12899                 different emit-sets"
12900            );
12901            assert_eq!(
12902                borrowed_string.as_str(),
12903                borrowed_static,
12904                "From<&RestartPolicy> for String and From<&RestartPolicy> \
12905                 for &'static str must resolve identically on \
12906                 RestartPolicy::{variant:?} — divergence signals the \
12907                 borrowed-input `&'static str` and owned-`String` \
12908                 return-shape paths have drifted onto different \
12909                 emit-sets"
12910            );
12911            assert_eq!(
12912                borrowed_string.as_str(),
12913                owned_static,
12914                "From<&RestartPolicy> for String and From<RestartPolicy> \
12915                 for &'static str must resolve identically on \
12916                 RestartPolicy::{variant:?} — divergence signals a \
12917                 break in the diagonal corner of the {{Self, &Self}} × \
12918                 {{&'static str, String}} 2×2 trait-idiomatic \
12919                 projection family"
12920            );
12921            let via_to_string: String = variant.to_string();
12922            assert_eq!(
12923                borrowed_string, via_to_string,
12924                "From<&RestartPolicy> for String must byte-equal \
12925                 RestartPolicy::to_string on RestartPolicy::{variant:?} \
12926                 — divergence signals the trait-idiomatic borrowed-input \
12927                 owned-`String` forward-projection axis and the \
12928                 ToString-through-Display axis have drifted onto \
12929                 different emit-sets"
12930            );
12931        }
12932        let via_iter: Vec<String> = RestartPolicy::ALL.iter().map(String::from).collect();
12933        let via_method: Vec<String> = RestartPolicy::ALL
12934            .iter()
12935            .map(|p| p.as_str().to_owned())
12936            .collect();
12937        assert_eq!(
12938            via_iter, via_method,
12939            "`.iter().map(String::from)` over RestartPolicy::ALL — a \
12940             call site whose iteration axis holds `&RestartPolicy` by \
12941             construction — must byte-equal `.iter().map(|p| \
12942             p.as_str().to_owned())` on every arm — the borrowed-input \
12943             owned-`String` `From<&RestartPolicy> for String` axis is \
12944             what makes the `String::from` composition route through \
12945             the substrate-primitive `RestartPolicy::as_str` accessor \
12946             without a spurious `Copy` deref (which would only be \
12947             reachable through the owned-input `From<RestartPolicy> \
12948             for String` axis by first calling `.copied()` on the \
12949             iterator)"
12950        );
12951        for &variant in RestartPolicy::ALL {
12952            let emitted: String = (&variant).into();
12953            let re_parsed: Result<RestartPolicy, ()> =
12954                <RestartPolicy as TryFrom<&str>>::try_from(emitted.as_str());
12955            assert_eq!(
12956                re_parsed,
12957                Ok(variant),
12958                "trait-idiomatic borrowed-input owned-`String` \
12959                 forward-projection + reverse-projection axis pair must \
12960                 round-trip &RestartPolicy::{variant:?} through \
12961                 `.into::<String>()` on the borrowed-input surface and \
12962                 back through `TryFrom<&str>` on the owned-`String`'s \
12963                 String::as_str borrow — a break signals the \
12964                 borrowed-input owned-`String` forward-emit and \
12965                 reverse-parse axes have drifted onto different \
12966                 vocabularies"
12967            );
12968        }
12969    }
12970
12971    #[test]
12972    fn restart_policy_from_into_static_cow_str_routes_through_as_str_accessor() {
12973        // Fail-before-pass-after byte-parity pin on the newly lifted
12974        // `impl From<RestartPolicy> for std::borrow::Cow<'static, str>` —
12975        // asserts the standard-library trait impl and the substrate-
12976        // primitive [`super::RestartPolicy::as_str`] `pub const fn`
12977        // accessor resolve to the same three-arm emit-set across every
12978        // arm the exhaustive [`super::RestartPolicy::ALL`] slice
12979        // enumerates. Rust's standard library does not carry a blanket
12980        // `impl<T: AsRef<str>> From<T> for Cow<'static, str>` (nor an
12981        // `impl<T: fmt::Display> From<T> for Cow<'static, str>`), so
12982        // the `Cow<'static, str>` forward-projection axis is a
12983        // distinct trait-idiomatic surface that a
12984        // `let key: Cow<'static, str> = policy.into();`-shaped call
12985        // site reaches through this impl and no other — the paired
12986        // sibling `From<RestartPolicy> for &'static str` and
12987        // `From<RestartPolicy> for String` impls force every
12988        // `Cow<'static, str>`-parameterized call site through a
12989        // `Cow::Borrowed(policy.as_str())` /
12990        // `Cow::Owned(policy.to_string())` composition whose type
12991        // bounds have no compile-time link back to the substrate
12992        // primitive.
12993        //
12994        // Also asserts the projection lands on the zero-alloc
12995        // [`std::borrow::Cow::Borrowed`] arm (not the
12996        // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
12997        // [`super::RestartPolicy::as_str`] accessor's `&'static str`
12998        // return lifetime by construction makes the borrowed arm the
12999        // type-correct projection with no runtime allocation. Any
13000        // future silent detour that routes the impl through the owned
13001        // arm (an accidental `Cow::Owned(policy.to_string())` rewrite
13002        // that would allocate on every call site where the
13003        // `&'static str` return of [`super::RestartPolicy::as_str`]
13004        // makes the zero-alloc borrowed projection type-correct) trips
13005        // at caixa-core test time under the
13006        // [`std::borrow::Cow::Borrowed`] discriminator witness rather
13007        // than at a downstream `Cow<'static, str>`-bound consumer's
13008        // silent allocation.
13009        //
13010        // Second peer on the substrate-wide trait-idiomatic
13011        // [`std::borrow::Cow<'static, str>`] forward-projection family
13012        // to extend the axis off the top-level [`super::CaixaKind`]
13013        // enum (99c1735 owned-input, d45c409 borrowed-input) onto the
13014        // second (and second-of-two-in-M2) M2 OTP-shape closed-set
13015        // fieldless typed enum peer on the caixa surface — closes the
13016        // M2 OTP-shape tier of the campaign on the owned-input axis
13017        // (both sibling peers, `RestartStrategy` and `RestartPolicy`,
13018        // now carry the owned-input Cow<'static, str> forward
13019        // projection).
13020        for &variant in RestartPolicy::ALL {
13021            let via_trait: std::borrow::Cow<'static, str> =
13022                <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
13023            let via_method: &'static str = variant.as_str();
13024            assert_eq!(
13025                via_trait.as_ref(),
13026                via_method,
13027                "From<RestartPolicy> for Cow<'static, str> impl must \
13028                 round-trip RestartPolicy::{variant:?} to the same \
13029                 lifted SUPERVISOR_CHILD_RESTART_* const \
13030                 RestartPolicy::as_str returns — divergence signals a \
13031                 silent detour off the substrate-primitive accessor"
13032            );
13033            assert!(
13034                matches!(via_trait, std::borrow::Cow::Borrowed(_)),
13035                "From<RestartPolicy> for Cow<'static, str> impl must \
13036                 land on the zero-alloc Cow::Borrowed arm on \
13037                 RestartPolicy::{variant:?} — a Cow::Owned outcome \
13038                 signals the projection has silently allocated where \
13039                 the substrate-primitive RestartPolicy::as_str \
13040                 `&'static str` return makes the borrowed arm the \
13041                 type-correct projection"
13042            );
13043            let via_into: std::borrow::Cow<'static, str> = variant.into();
13044            assert_eq!(
13045                via_into.as_ref(),
13046                via_method,
13047                "Into<Cow<'static, str>>::into on \
13048                 RestartPolicy::{variant:?} must byte-equal \
13049                 RestartPolicy::as_str on the same input — the \
13050                 blanket-derived Into shape must resolve to the same \
13051                 as_str dispatch as the explicit From impl"
13052            );
13053            assert!(
13054                matches!(via_into, std::borrow::Cow::Borrowed(_)),
13055                "Into<Cow<'static, str>>::into on \
13056                 RestartPolicy::{variant:?} must land on the \
13057                 zero-alloc Cow::Borrowed arm — the blanket-derived \
13058                 Into shape must resolve to the same Cow::Borrowed \
13059                 dispatch as the explicit From impl"
13060            );
13061        }
13062    }
13063
13064    #[test]
13065    fn restart_policy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
13066        // Cross-axis partition pin: the newly lifted trait-idiomatic
13067        // `From<RestartPolicy> for std::borrow::Cow<'static, str>`
13068        // (this lift), the paired owned-input `From<RestartPolicy>
13069        // for &'static str` (9fb37d0), and the paired owned-input
13070        // `From<RestartPolicy> for String` (7851725) forward
13071        // projections must resolve identically on every arm, locking
13072        // the three return-shape paths together by construction so any
13073        // future detour trips at caixa-core test time. Also byte-parity
13074        // witness against the sibling [`ToString::to_string`] surface
13075        // routed through [`std::fmt::Display`] — every owned-heap-
13076        // string path (the `Cow::Owned` promotion of this axis's
13077        // `.into_owned()`, `From<RestartPolicy> for String`, and
13078        // `.to_string()`) resolves to the same lifted
13079        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const per arm.
13080        //
13081        // Then a `.iter().copied().map(std::borrow::Cow::from)` pipe
13082        // witness over [`super::RestartPolicy::ALL`] that
13083        // materializes the three-arm accept-set through the
13084        // [`std::borrow::Cow<'static, str>`] axis alone — the exact
13085        // shape a future `axum::response::IntoResponse` per-policy
13086        // rejection-body composer, a future M4 admission-webhook
13087        // per-policy rejection-reason emitter whose typing rules out
13088        // the sibling [`AsRef<str>`] borrowed return, or a future
13089        // substrate-wide per-policy diagnostic surface that binds
13090        // through a [`Cow<'static, str>`] boundary reaches through.
13091        // The pipe witness also pins the zero-alloc discipline: every
13092        // element in the collected vector satisfies the
13093        // [`std::borrow::Cow::Borrowed`] arm predicate, so a future
13094        // accidental silent-allocation regression on the pipe's
13095        // iteration axis is a caixa-core-test-time failure. Peer of
13096        // the first-mover
13097        // [`restart_strategy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
13098        // (7dd28b3) on the sibling M2 OTP-shape sibling-restart axis
13099        // — closes the whole owned-input `Cow<'static, str>` +
13100        // paired `{&'static str, String}` cross-axis-parity corner on
13101        // both M2 OTP-shape sibling peers.
13102        for &variant in RestartPolicy::ALL {
13103            let via_cow: std::borrow::Cow<'static, str> =
13104                <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
13105            let via_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
13106            let via_string: String = <String as From<RestartPolicy>>::from(variant);
13107            assert_eq!(
13108                via_cow.as_ref(),
13109                via_static,
13110                "From<RestartPolicy> for Cow<'static, str> and \
13111                 From<RestartPolicy> for &'static str must resolve \
13112                 identically on RestartPolicy::{variant:?} — \
13113                 divergence signals the Cow<'static, str> and \
13114                 &'static str return-shape paths have drifted onto \
13115                 different emit-sets"
13116            );
13117            assert_eq!(
13118                via_cow.as_ref(),
13119                via_string.as_str(),
13120                "From<RestartPolicy> for Cow<'static, str> and \
13121                 From<RestartPolicy> for String must resolve \
13122                 identically on RestartPolicy::{variant:?} — \
13123                 divergence signals the Cow<'static, str> and String \
13124                 return-shape paths have drifted onto different \
13125                 emit-sets"
13126            );
13127            let via_to_string: String = variant.to_string();
13128            assert_eq!(
13129                via_cow.as_ref(),
13130                via_to_string.as_str(),
13131                "From<RestartPolicy> for Cow<'static, str> must \
13132                 byte-equal RestartPolicy::to_string on \
13133                 RestartPolicy::{variant:?} — divergence signals the \
13134                 trait-idiomatic Cow<'static, str> forward-projection \
13135                 axis and the ToString-through-Display axis have \
13136                 drifted onto different emit-sets"
13137            );
13138        }
13139        let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
13140            .iter()
13141            .copied()
13142            .map(std::borrow::Cow::from)
13143            .collect();
13144        let via_method: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
13145            .iter()
13146            .map(|p| std::borrow::Cow::Borrowed(p.as_str()))
13147            .collect();
13148        assert_eq!(
13149            via_iter, via_method,
13150            "`.iter().copied().map(Cow::from)` over \
13151             RestartPolicy::ALL must byte-equal `.iter().map(|p| \
13152             Cow::Borrowed(p.as_str()))` on every arm — the \
13153             trait-idiomatic `From<RestartPolicy> for Cow<'static, \
13154             str>` axis is what makes the `Cow::from` composition \
13155             route through the substrate-primitive \
13156             `RestartPolicy::as_str` accessor with the zero-alloc \
13157             Cow::Borrowed arm by construction, rather than a \
13158             per-call-site `Cow::Owned(policy.to_string())` \
13159             allocation"
13160        );
13161        for cow in &via_iter {
13162            assert!(
13163                matches!(cow, std::borrow::Cow::Borrowed(_)),
13164                "every element of the \
13165                 .iter().copied().map(Cow::from) pipe over \
13166                 RestartPolicy::ALL must land on the zero-alloc \
13167                 Cow::Borrowed arm — a Cow::Owned outcome on any arm \
13168                 signals the pipe's iteration axis has silently \
13169                 allocated where the substrate-primitive \
13170                 RestartPolicy::as_str `&'static str` return makes \
13171                 the borrowed arm the type-correct projection"
13172            );
13173        }
13174    }
13175
13176    #[test]
13177    fn restart_policy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor() {
13178        // Fail-before-pass-after byte-parity pin on the newly lifted
13179        // `impl From<&RestartPolicy> for std::borrow::Cow<'static, str>` —
13180        // asserts the borrowed-input standard-library trait impl and
13181        // the substrate-primitive [`super::RestartPolicy::as_str`]
13182        // `pub const fn` accessor resolve to the same three-arm emit-
13183        // set across every arm the exhaustive
13184        // [`super::RestartPolicy::ALL`] slice enumerates. Rust's
13185        // standard library does not carry a blanket
13186        // `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor a
13187        // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`), so
13188        // the borrowed-input `Cow<'static, str>` forward-projection
13189        // axis is a distinct trait-idiomatic surface that a
13190        // `let key: Cow<'static, str> = (&policy).into();`-shaped
13191        // call site or a
13192        // `RestartPolicy::ALL.iter().map(Cow::from)`-shaped pipe
13193        // reaches through this impl and no other — the paired owned-
13194        // input `From<RestartPolicy> for Cow<'static, str>` impl
13195        // (0612398) forces every borrowed-input call site through an
13196        // explicit `Copy` deref (`Cow::from(*policy)`) or a
13197        // `Cow::Borrowed(policy.as_str())` open-code whose type
13198        // bounds have no compile-time link back to the substrate
13199        // primitive.
13200        //
13201        // Also asserts the projection lands on the zero-alloc
13202        // [`std::borrow::Cow::Borrowed`] arm (not the
13203        // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
13204        // [`super::RestartPolicy::as_str`] accessor's `&'static str`
13205        // return lifetime by construction makes the borrowed arm the
13206        // type-correct projection with no runtime allocation on the
13207        // borrowed-input surface just as on the paired owned-input
13208        // surface.
13209        //
13210        // Closes the `{Self, &Self}` input-shape corner on the M2
13211        // OTP-shape per-child-restart [`Cow<'static, str>`] axis on
13212        // the second-of-two-in-M2 closed-set fieldless typed enum peer
13213        // on the caixa surface (`:supervisor :children :restart`),
13214        // exactly as d45c409 closed it on the top-level
13215        // [`super::CaixaKind`] one commit after the owning half
13216        // (99c1735) landed and as 9b3e4b3 closed it on the sibling
13217        // M2 OTP-shape [`super::RestartStrategy`] one commit after
13218        // (7dd28b3) landed. This lift closes the whole M2 OTP-shape
13219        // tier of the substrate-wide Cow<'static, str> forward-
13220        // projection campaign on both input-shape corners
13221        // ({Self, &Self}) of both M2 OTP-shape sibling peers.
13222        for &variant in RestartPolicy::ALL {
13223            let via_trait: std::borrow::Cow<'static, str> =
13224                <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&variant);
13225            let via_method: &'static str = variant.as_str();
13226            assert_eq!(
13227                via_trait.as_ref(),
13228                via_method,
13229                "From<&RestartPolicy> for Cow<'static, str> impl must \
13230                 round-trip &RestartPolicy::{variant:?} to the same \
13231                 lifted SUPERVISOR_CHILD_RESTART_* const \
13232                 RestartPolicy::as_str returns — divergence signals a \
13233                 silent detour off the substrate-primitive accessor"
13234            );
13235            assert!(
13236                matches!(via_trait, std::borrow::Cow::Borrowed(_)),
13237                "From<&RestartPolicy> for Cow<'static, str> impl must \
13238                 land on the zero-alloc Cow::Borrowed arm on \
13239                 &RestartPolicy::{variant:?} — a Cow::Owned outcome \
13240                 signals the projection has silently allocated where \
13241                 the substrate-primitive RestartPolicy::as_str \
13242                 `&'static str` return makes the borrowed arm the \
13243                 type-correct projection"
13244            );
13245            let via_into: std::borrow::Cow<'static, str> = (&variant).into();
13246            assert_eq!(
13247                via_into.as_ref(),
13248                via_method,
13249                "Into<Cow<'static, str>>::into on \
13250                 &RestartPolicy::{variant:?} must byte-equal \
13251                 RestartPolicy::as_str on the same input — the \
13252                 blanket-derived Into shape must resolve to the same \
13253                 as_str dispatch as the explicit From impl"
13254            );
13255            assert!(
13256                matches!(via_into, std::borrow::Cow::Borrowed(_)),
13257                "Into<Cow<'static, str>>::into on \
13258                 &RestartPolicy::{variant:?} must land on the \
13259                 zero-alloc Cow::Borrowed arm — the blanket-derived \
13260                 Into shape must resolve to the same Cow::Borrowed \
13261                 dispatch as the explicit From impl"
13262            );
13263        }
13264    }
13265
13266    #[test]
13267    fn restart_policy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
13268        // Cross-axis partition pin: the newly lifted trait-idiomatic
13269        // borrowed-input `From<&RestartPolicy> for
13270        // std::borrow::Cow<'static, str>` (this lift), the paired
13271        // owned-input `From<RestartPolicy> for
13272        // std::borrow::Cow<'static, str>` (0612398), the paired
13273        // borrowed-input owned-`&'static str` `From<&RestartPolicy>
13274        // for &'static str`, and the paired borrowed-input owned-
13275        // `String` `From<&RestartPolicy> for String` must resolve
13276        // identically on every arm, locking the four
13277        // return-shape × input-shape paths together by construction so
13278        // any future detour trips at caixa-core test time. Also byte-
13279        // parity witness against the sibling [`ToString::to_string`]
13280        // surface routed through [`std::fmt::Display`] — every owned-
13281        // heap-string path (this axis's `.into_owned()` promotion, the
13282        // paired [`From<&RestartPolicy> for String`], and
13283        // `.to_string()`) resolves to the same lifted
13284        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const per arm.
13285        //
13286        // Then a `.iter().map(std::borrow::Cow::from)` pipe witness
13287        // over [`super::RestartPolicy::ALL`] — whose iterator yields
13288        // `&RestartPolicy` by construction, so the borrowed-input
13289        // [`Cow<'static, str>`] axis is what routes the pipe through
13290        // the substrate-primitive [`super::RestartPolicy::as_str`]
13291        // accessor without a spurious [`Copy`] deref (which would only
13292        // be reachable through the owned-input
13293        // [`From<RestartPolicy> for Cow<'static, str>`] axis by first
13294        // calling `.copied()` on the iterator). The pipe witness also
13295        // pins the zero-alloc discipline: every element in the
13296        // collected vector satisfies the [`std::borrow::Cow::Borrowed`]
13297        // arm predicate, so a future accidental silent-allocation
13298        // regression on the pipe's iteration axis is a caixa-core-
13299        // test-time failure. Peer of the sibling
13300        // [`restart_strategy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
13301        // (9b3e4b3) on the M2 OTP-shape sibling-restart axis — closes
13302        // the whole borrowed-input `Cow<'static, str>` +
13303        // paired `{&'static str, String}` cross-axis-parity corner on
13304        // both M2 OTP-shape sibling peers.
13305        for &policy in RestartPolicy::ALL {
13306            let borrowed_cow: std::borrow::Cow<'static, str> =
13307                <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&policy);
13308            let owned_cow: std::borrow::Cow<'static, str> =
13309                <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(policy);
13310            let borrowed_static: &'static str =
13311                <&'static str as From<&RestartPolicy>>::from(&policy);
13312            let borrowed_string: String = <String as From<&RestartPolicy>>::from(&policy);
13313            assert_eq!(
13314                borrowed_cow, owned_cow,
13315                "From<&RestartPolicy> for Cow<'static, str> and \
13316                 From<RestartPolicy> for Cow<'static, str> must \
13317                 resolve identically on RestartPolicy::{policy:?} — \
13318                 divergence signals the borrowed-input and owned-input \
13319                 Cow<'static, str> forward-projection input-shape \
13320                 paths have drifted onto different emit-sets"
13321            );
13322            assert_eq!(
13323                borrowed_cow.as_ref(),
13324                borrowed_static,
13325                "From<&RestartPolicy> for Cow<'static, str> and \
13326                 From<&RestartPolicy> for &'static str must resolve \
13327                 identically on RestartPolicy::{policy:?} — \
13328                 divergence signals the borrowed-input Cow<'static, \
13329                 str> and &'static str return-shape paths have drifted \
13330                 onto different emit-sets"
13331            );
13332            assert_eq!(
13333                borrowed_cow.as_ref(),
13334                borrowed_string.as_str(),
13335                "From<&RestartPolicy> for Cow<'static, str> and \
13336                 From<&RestartPolicy> for String must resolve \
13337                 identically on RestartPolicy::{policy:?} — \
13338                 divergence signals the borrowed-input Cow<'static, \
13339                 str> and owned-`String` return-shape paths have \
13340                 drifted onto different emit-sets"
13341            );
13342            let via_to_string: String = policy.to_string();
13343            assert_eq!(
13344                borrowed_cow.as_ref(),
13345                via_to_string.as_str(),
13346                "From<&RestartPolicy> for Cow<'static, str> must \
13347                 byte-equal RestartPolicy::to_string on \
13348                 RestartPolicy::{policy:?} — divergence signals \
13349                 the trait-idiomatic borrowed-input Cow<'static, str> \
13350                 forward-projection axis and the ToString-through-\
13351                 Display axis have drifted onto different emit-sets"
13352            );
13353        }
13354        let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
13355            .iter()
13356            .map(std::borrow::Cow::from)
13357            .collect();
13358        let via_method: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
13359            .iter()
13360            .map(|p| std::borrow::Cow::Borrowed(p.as_str()))
13361            .collect();
13362        assert_eq!(
13363            via_iter, via_method,
13364            "`.iter().map(Cow::from)` over RestartPolicy::ALL — a \
13365             call site whose iteration axis holds `&RestartPolicy` \
13366             by construction — must byte-equal `.iter().map(|p| \
13367             Cow::Borrowed(p.as_str()))` on every arm — the borrowed-\
13368             input Cow<'static, str> `From<&RestartPolicy> for \
13369             Cow<'static, str>` axis is what makes the `Cow::from` \
13370             composition route through the substrate-primitive \
13371             `RestartPolicy::as_str` accessor with the zero-alloc \
13372             Cow::Borrowed arm by construction and without a spurious \
13373             `Copy` deref (which would only be reachable through the \
13374             owned-input `From<RestartPolicy> for Cow<'static, str>` \
13375             axis by first calling `.copied()` on the iterator)"
13376        );
13377        for cow in &via_iter {
13378            assert!(
13379                matches!(cow, std::borrow::Cow::Borrowed(_)),
13380                "every element of the .iter().map(Cow::from) pipe \
13381                 over RestartPolicy::ALL must land on the zero-\
13382                 alloc Cow::Borrowed arm — a Cow::Owned outcome on \
13383                 any arm signals the pipe's iteration axis has \
13384                 silently allocated where the substrate-primitive \
13385                 RestartPolicy::as_str `&'static str` return makes \
13386                 the borrowed arm the type-correct projection"
13387            );
13388        }
13389    }
13390
13391    #[test]
13392    fn restart_policy_from_into_box_str_routes_through_as_str_accessor() {
13393        // Fail-before-pass-after byte-parity pin on the newly lifted
13394        // `impl From<RestartPolicy> for Box<str>` — asserts the
13395        // owned-input standard-library trait impl and the
13396        // substrate-primitive [`super::RestartPolicy::as_str`]
13397        // `pub const fn` accessor resolve to the same three-arm emit-
13398        // set across every arm the exhaustive
13399        // [`super::RestartPolicy::ALL`] slice enumerates. Extends the
13400        // substrate-wide `Box<str>` forward-projection campaign tier
13401        // opened one commit prior (69ef45c) on the paired sibling-
13402        // restart [`RestartStrategy`] onto the second (and third-and-
13403        // final) M2 OTP-shape closed-set fieldless typed enum peer on
13404        // the caixa surface (`:children :restart`), immediately after
13405        // the paired `Cow<'static, str>` axis (0612398 / b4dc55c)
13406        // closed the
13407        // `{Self, &Self} × {&'static str, String, Cow<'static, str>}`
13408        // 2×3 corner on this enum. Rust's standard library carries
13409        // `impl From<&str> for Box<str>` and
13410        // `impl From<String> for Box<str>` but no blanket
13411        // `impl<T: AsRef<str>> From<T> for Box<str>`, so this axis is
13412        // a distinct trait-idiomatic surface that a
13413        // `let key: Box<str> = policy.into();`-shaped call site
13414        // reaches through this impl and no other — a paired
13415        // `Box::from(policy.as_str())` open-code has no compile-time
13416        // link back to the substrate primitive. Peer of the sibling
13417        // [`restart_strategy_from_into_box_str_routes_through_as_str_accessor`]
13418        // (69ef45c) — extends the trait-idiomatic owned-input
13419        // [`Box<str>`] forward-projection axis onto the third and
13420        // final M2-OTP-shape closed-set typed enum on the caixa
13421        // surface.
13422        for &variant in RestartPolicy::ALL {
13423            let via_trait: Box<str> = <Box<str> as From<RestartPolicy>>::from(variant);
13424            let via_method: &'static str = variant.as_str();
13425            assert_eq!(
13426                via_trait.as_ref(),
13427                via_method,
13428                "From<RestartPolicy> for Box<str> impl must round-\
13429                 trip RestartPolicy::{variant:?} to the same lifted \
13430                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
13431                 returns — divergence signals a silent detour off the \
13432                 substrate-primitive accessor"
13433            );
13434            let via_into: Box<str> = variant.into();
13435            assert_eq!(
13436                via_into.as_ref(),
13437                via_method,
13438                "Into<Box<str>>::into on RestartPolicy::{variant:?} \
13439                 must byte-equal RestartPolicy::as_str on the same \
13440                 input — the blanket-derived Into shape must resolve \
13441                 to the same as_str dispatch as the explicit From impl"
13442            );
13443        }
13444    }
13445
13446    #[test]
13447    fn restart_policy_from_borrowed_into_box_str_routes_through_as_str_accessor() {
13448        // Fail-before-pass-after byte-parity pin on the newly lifted
13449        // `impl From<&RestartPolicy> for Box<str>` — asserts the
13450        // borrowed-input standard-library trait impl and the
13451        // substrate-primitive [`super::RestartPolicy::as_str`]
13452        // `pub const fn` accessor resolve to the same three-arm emit-
13453        // set across every arm the exhaustive
13454        // [`super::RestartPolicy::ALL`] slice enumerates. Rust's
13455        // standard library does not carry a blanket
13456        // `impl<T: AsRef<str>> From<&T> for Box<str>` (nor a
13457        // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`),
13458        // so the borrowed-input `Box<str>` forward-projection axis
13459        // is a distinct trait-idiomatic surface that a
13460        // `let key: Box<str> = (&policy).into();`-shaped call site
13461        // or a `RestartPolicy::ALL.iter().map(Box::<str>::from)`-
13462        // shaped pipe reaches through this impl and no other — the
13463        // paired owned-input `From<RestartPolicy> for Box<str>`
13464        // impl (0a1b313) forces every borrowed-input call site
13465        // through an explicit `Copy` deref
13466        // (`Box::<str>::from((*policy).as_str())`) or a
13467        // `Box::<str>::from(policy.as_str())` open-code whose
13468        // type bounds have no compile-time link back to the
13469        // substrate primitive.
13470        //
13471        // Fourth (and closing) peer on the substrate-wide trait-
13472        // idiomatic [`Box<str>`] forward-projection family on the
13473        // M2 OTP-shape tier — closes the `{Self, &Self}` input-
13474        // shape corner of the [`Box<str>`] axis on the second (and
13475        // third-and-final) M2 OTP-shape closed-set fieldless typed
13476        // enum peer on the caixa surface (`:children :restart`),
13477        // exactly as b4dc55c closed the paired [`Cow<'static, str>`]
13478        // axis one commit after its owning half (0612398) landed
13479        // on this enum. Every remaining closed-set fieldless typed
13480        // enum peer on the M3 mesh-shape / outside-M3 caixa-core /
13481        // render-side / outside-caixa-core tiers is a future
13482        // target of the campaign.
13483        //
13484        // Also byte-parity witness against the paired owned-input
13485        // [`From<RestartPolicy> for Box<str>`] and the sibling
13486        // borrowed-input [`From<&RestartPolicy> for &'static str`],
13487        // [`From<&RestartPolicy> for String`], and
13488        // [`From<&RestartPolicy> for Cow<'static, str>`]
13489        // return-shape axes — locking the four
13490        // return-shape × input-shape paths together by construction
13491        // so any future detour trips at caixa-core test time. Then a
13492        // `.iter().map(Box::<str>::from)` pipe witness over
13493        // [`super::RestartPolicy::ALL`] — whose iterator yields
13494        // `&RestartPolicy` by construction, so the borrowed-input
13495        // [`Box<str>`] axis is what routes the pipe through the
13496        // substrate-primitive [`super::RestartPolicy::as_str`]
13497        // accessor without a spurious [`Copy`] deref (which would
13498        // only be reachable through the owned-input
13499        // [`From<RestartPolicy> for Box<str>`] axis by first
13500        // calling `.copied()` on the iterator).
13501        for &variant in RestartPolicy::ALL {
13502            let via_trait: Box<str> = <Box<str> as From<&RestartPolicy>>::from(&variant);
13503            let via_method: &'static str = variant.as_str();
13504            assert_eq!(
13505                via_trait.as_ref(),
13506                via_method,
13507                "From<&RestartPolicy> for Box<str> impl must round-\
13508                 trip &RestartPolicy::{variant:?} to the same lifted \
13509                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
13510                 returns — divergence signals a silent detour off the \
13511                 substrate-primitive accessor"
13512            );
13513            let via_into: Box<str> = (&variant).into();
13514            assert_eq!(
13515                via_into.as_ref(),
13516                via_method,
13517                "Into<Box<str>>::into on &RestartPolicy::{variant:?} \
13518                 must byte-equal RestartPolicy::as_str on the same \
13519                 input — the blanket-derived Into shape must resolve \
13520                 to the same as_str dispatch as the explicit From impl"
13521            );
13522            let owned_box: Box<str> = <Box<str> as From<RestartPolicy>>::from(variant);
13523            assert_eq!(
13524                via_trait, owned_box,
13525                "From<&RestartPolicy> for Box<str> and \
13526                 From<RestartPolicy> for Box<str> must resolve \
13527                 identically on RestartPolicy::{variant:?} — \
13528                 divergence signals the borrowed-input and owned-input \
13529                 Box<str> forward-projection input-shape paths have \
13530                 drifted onto different emit-sets"
13531            );
13532            let borrowed_static: &'static str =
13533                <&'static str as From<&RestartPolicy>>::from(&variant);
13534            assert_eq!(
13535                via_trait.as_ref(),
13536                borrowed_static,
13537                "From<&RestartPolicy> for Box<str> and \
13538                 From<&RestartPolicy> for &'static str must resolve \
13539                 identically on RestartPolicy::{variant:?} — \
13540                 divergence signals the borrowed-input Box<str> and \
13541                 &'static str return-shape paths have drifted onto \
13542                 different emit-sets"
13543            );
13544            let borrowed_string: String = <String as From<&RestartPolicy>>::from(&variant);
13545            assert_eq!(
13546                via_trait.as_ref(),
13547                borrowed_string.as_str(),
13548                "From<&RestartPolicy> for Box<str> and \
13549                 From<&RestartPolicy> for String must resolve \
13550                 identically on RestartPolicy::{variant:?} — \
13551                 divergence signals the borrowed-input Box<str> and \
13552                 owned-`String` return-shape paths have drifted onto \
13553                 different emit-sets"
13554            );
13555            let borrowed_cow: std::borrow::Cow<'static, str> =
13556                <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&variant);
13557            assert_eq!(
13558                via_trait.as_ref(),
13559                borrowed_cow.as_ref(),
13560                "From<&RestartPolicy> for Box<str> and \
13561                 From<&RestartPolicy> for Cow<'static, str> must \
13562                 resolve identically on RestartPolicy::{variant:?} — \
13563                 divergence signals the borrowed-input Box<str> and \
13564                 Cow<'static, str> return-shape paths have drifted \
13565                 onto different emit-sets"
13566            );
13567        }
13568        let via_iter: Vec<Box<str>> = RestartPolicy::ALL.iter().map(Box::<str>::from).collect();
13569        let via_method: Vec<Box<str>> = RestartPolicy::ALL
13570            .iter()
13571            .map(|p| Box::<str>::from(p.as_str()))
13572            .collect();
13573        assert_eq!(
13574            via_iter, via_method,
13575            "`.iter().map(Box::<str>::from)` over \
13576             RestartPolicy::ALL — a call site whose iteration axis \
13577             holds `&RestartPolicy` by construction — must byte-\
13578             equal `.iter().map(|p| Box::<str>::from(p.as_str()))` \
13579             on every arm — the borrowed-input Box<str> \
13580             `From<&RestartPolicy> for Box<str>` axis is what \
13581             makes the `Box::<str>::from` composition route through \
13582             the substrate-primitive `RestartPolicy::as_str` \
13583             accessor without a spurious `Copy` deref (which would \
13584             only be reachable through the owned-input \
13585             `From<RestartPolicy> for Box<str>` axis by first \
13586             calling `.copied()` on the iterator)"
13587        );
13588    }
13589
13590    #[test]
13591    fn restart_policy_from_into_arc_str_routes_through_as_str_accessor() {
13592        // Fail-before-pass-after byte-parity pin on the newly lifted
13593        // `impl From<RestartPolicy> for std::sync::Arc<str>` — asserts
13594        // the owned-input standard-library trait impl and the
13595        // substrate-primitive [`super::RestartPolicy::as_str`]
13596        // `pub const fn` accessor resolve to the same three-arm emit-
13597        // set across every arm the exhaustive
13598        // [`super::RestartPolicy::ALL`] slice enumerates. Extends the
13599        // substrate-wide [`std::sync::Arc<str>`] forward-projection
13600        // campaign tier opened one projection tier prior (bca2ec8) on
13601        // the paired sibling-restart [`RestartStrategy`] owned-input
13602        // first-mover onto the second (and third-and-final) M2 OTP-
13603        // shape closed-set fieldless typed enum peer on the caixa
13604        // surface (`:children :restart`), immediately after the paired
13605        // [`Box<str>`] axis (0a1b313 / cb1d068) closed the
13606        // `{Self, &Self} × {&'static str, String, Cow<'static, str>,
13607        // Box<str>}` 2×4 corner on this enum. Rust's standard library
13608        // carries `impl From<&str> for std::sync::Arc<str>` and
13609        // `impl From<String> for std::sync::Arc<str>` but no blanket
13610        // `impl<T: AsRef<str>> From<T> for std::sync::Arc<str>` (nor
13611        // an `impl<T: fmt::Display> From<T> for std::sync::Arc<str>`),
13612        // so this axis is a distinct trait-idiomatic surface that a
13613        // `let key: std::sync::Arc<str> = policy.into();`-shaped call
13614        // site reaches through this impl and no other — a paired
13615        // `std::sync::Arc::<str>::from(policy.as_str())` open-code
13616        // has no compile-time link back to the substrate primitive,
13617        // and a two-step `std::sync::Arc::<str>::from(String::from(
13618        // policy))` composition through the owned-`String` axis
13619        // allocates twice (once into the intermediate `String`, once
13620        // into the [`Arc<str>`] on the `From<String>` conversion)
13621        // where the single-step trait impl allocates once.
13622        //
13623        // Cross-axis byte-parity witness against the sibling owned-
13624        // input `{&'static str, String, Cow<'static, str>, Box<str>}`
13625        // return-shape axes — locking the five return-shape paths on
13626        // the owned-input surface together by construction so any
13627        // future detour off the substrate-primitive
13628        // [`super::RestartPolicy::as_str`] accessor trips at caixa-
13629        // core test time.
13630        for &variant in RestartPolicy::ALL {
13631            let via_trait: std::sync::Arc<str> =
13632                <std::sync::Arc<str> as From<RestartPolicy>>::from(variant);
13633            let via_method: &'static str = variant.as_str();
13634            assert_eq!(
13635                via_trait.as_ref(),
13636                via_method,
13637                "From<RestartPolicy> for std::sync::Arc<str> impl \
13638                 must round-trip RestartPolicy::{variant:?} to the \
13639                 same lifted SUPERVISOR_CHILD_RESTART_* const \
13640                 RestartPolicy::as_str returns — divergence signals \
13641                 a silent detour off the substrate-primitive accessor"
13642            );
13643            let via_into: std::sync::Arc<str> = variant.into();
13644            assert_eq!(
13645                via_into.as_ref(),
13646                via_method,
13647                "Into<std::sync::Arc<str>>::into on \
13648                 RestartPolicy::{variant:?} must byte-equal \
13649                 RestartPolicy::as_str on the same input — the \
13650                 blanket-derived Into shape must resolve to the same \
13651                 as_str dispatch as the explicit From impl"
13652            );
13653            let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
13654            assert_eq!(
13655                via_trait.as_ref(),
13656                owned_static,
13657                "From<RestartPolicy> for std::sync::Arc<str> and \
13658                 From<RestartPolicy> for &'static str must resolve \
13659                 identically on RestartPolicy::{variant:?} — \
13660                 divergence signals the owned-input std::sync::Arc<str> \
13661                 and &'static str return-shape paths have drifted onto \
13662                 different emit-sets"
13663            );
13664            let owned_string: String = <String as From<RestartPolicy>>::from(variant);
13665            assert_eq!(
13666                via_trait.as_ref(),
13667                owned_string.as_str(),
13668                "From<RestartPolicy> for std::sync::Arc<str> and \
13669                 From<RestartPolicy> for String must resolve \
13670                 identically on RestartPolicy::{variant:?} — \
13671                 divergence signals the owned-input std::sync::Arc<str> \
13672                 and owned-`String` return-shape paths have drifted \
13673                 onto different emit-sets"
13674            );
13675            let owned_cow: std::borrow::Cow<'static, str> =
13676                <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
13677            assert_eq!(
13678                via_trait.as_ref(),
13679                owned_cow.as_ref(),
13680                "From<RestartPolicy> for std::sync::Arc<str> and \
13681                 From<RestartPolicy> for Cow<'static, str> must \
13682                 resolve identically on RestartPolicy::{variant:?} — \
13683                 divergence signals the owned-input std::sync::Arc<str> \
13684                 and Cow<'static, str> return-shape paths have drifted \
13685                 onto different emit-sets"
13686            );
13687            let owned_box: Box<str> = <Box<str> as From<RestartPolicy>>::from(variant);
13688            assert_eq!(
13689                via_trait.as_ref(),
13690                owned_box.as_ref(),
13691                "From<RestartPolicy> for std::sync::Arc<str> and \
13692                 From<RestartPolicy> for Box<str> must resolve \
13693                 identically on RestartPolicy::{variant:?} — \
13694                 divergence signals the owned-input std::sync::Arc<str> \
13695                 and Box<str> return-shape paths have drifted onto \
13696                 different emit-sets"
13697            );
13698        }
13699    }
13700
13701    #[test]
13702    fn restart_policy_from_borrowed_into_arc_str_routes_through_as_str_accessor() {
13703        // Fail-before-pass-after byte-parity pin on the newly lifted
13704        // `impl From<&RestartPolicy> for std::sync::Arc<str>` —
13705        // asserts the borrowed-input standard-library trait impl and
13706        // the substrate-primitive [`super::RestartPolicy::as_str`]
13707        // `pub const fn` accessor resolve to the same three-arm
13708        // emit-set across every arm the exhaustive
13709        // [`super::RestartPolicy::ALL`] slice enumerates. Rust's
13710        // standard library carries `impl From<&str> for
13711        // std::sync::Arc<str>` and `impl From<String> for
13712        // std::sync::Arc<str>` but no blanket
13713        // `impl<T: AsRef<str>> From<&T> for std::sync::Arc<str>` (nor
13714        // a `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`),
13715        // so the borrowed-input [`std::sync::Arc<str>`] forward-
13716        // projection axis is a distinct trait-idiomatic surface that
13717        // a `let key: std::sync::Arc<str> = (&policy).into();`-shaped
13718        // call site or a
13719        // `RestartPolicy::ALL.iter().map(std::sync::Arc::<str>::from)`-
13720        // shaped pipe reaches through this impl and no other — the
13721        // paired owned-input [`From<RestartPolicy> for
13722        // std::sync::Arc<str>`] impl (b05724e) forces every borrowed-
13723        // input call site through an explicit [`Copy`] deref
13724        // (`std::sync::Arc::<str>::from((*policy).as_str())`) or a
13725        // `std::sync::Arc::<str>::from(policy.as_str())` open-code
13726        // whose type bounds have no compile-time link back to the
13727        // substrate primitive.
13728        //
13729        // Closes the `{Self, &Self}` input-shape corner of the
13730        // substrate-wide trait-idiomatic [`std::sync::Arc<str>`]
13731        // forward-projection family on the second (and third-and-
13732        // final) M2 OTP-shape closed-set fieldless typed enum peer
13733        // on the caixa surface (`:children :restart`), one commit
13734        // after b05724e opened the owned-input half — exactly as
13735        // b3e72d7 closed the paired [`std::sync::Arc<str>`] corner on
13736        // the sibling-restart [`RestartStrategy`] first-mover one
13737        // commit after its owning half (bca2ec8) landed, and as
13738        // cb1d068 closed the paired [`Box<str>`] corner on this
13739        // enum one commit after its owning half (0a1b313) landed.
13740        //
13741        // Also byte-parity witness against the paired owned-input
13742        // [`From<RestartPolicy> for std::sync::Arc<str>`] and the
13743        // sibling borrowed-input [`From<&RestartPolicy> for
13744        // &'static str`], [`From<&RestartPolicy> for String`],
13745        // [`From<&RestartPolicy> for Cow<'static, str>`], and
13746        // [`From<&RestartPolicy> for Box<str>`] return-shape axes —
13747        // locking the five return-shape × input-shape paths together
13748        // by construction so any future detour off the substrate-
13749        // primitive [`super::RestartPolicy::as_str`] accessor trips
13750        // at caixa-core test time. Then a
13751        // `.iter().map(std::sync::Arc::<str>::from)` pipe witness
13752        // over [`super::RestartPolicy::ALL`] — whose iterator yields
13753        // `&RestartPolicy` by construction, so the borrowed-input
13754        // [`std::sync::Arc<str>`] axis is what routes the pipe
13755        // through the substrate-primitive
13756        // [`super::RestartPolicy::as_str`] accessor without a
13757        // spurious [`Copy`] deref (which would only be reachable
13758        // through the owned-input
13759        // [`From<RestartPolicy> for std::sync::Arc<str>`] axis by
13760        // first calling `.copied()` on the iterator).
13761        for &variant in RestartPolicy::ALL {
13762            let via_trait: std::sync::Arc<str> =
13763                <std::sync::Arc<str> as From<&RestartPolicy>>::from(&variant);
13764            let via_method: &'static str = variant.as_str();
13765            assert_eq!(
13766                via_trait.as_ref(),
13767                via_method,
13768                "From<&RestartPolicy> for std::sync::Arc<str> impl \
13769                 must round-trip &RestartPolicy::{variant:?} to the \
13770                 same lifted SUPERVISOR_CHILD_RESTART_* const \
13771                 RestartPolicy::as_str returns — divergence signals \
13772                 a silent detour off the substrate-primitive accessor"
13773            );
13774            let via_into: std::sync::Arc<str> = (&variant).into();
13775            assert_eq!(
13776                via_into.as_ref(),
13777                via_method,
13778                "Into<std::sync::Arc<str>>::into on \
13779                 &RestartPolicy::{variant:?} must byte-equal \
13780                 RestartPolicy::as_str on the same input — the \
13781                 blanket-derived Into shape must resolve to the same \
13782                 as_str dispatch as the explicit From impl"
13783            );
13784            let owned_arc: std::sync::Arc<str> =
13785                <std::sync::Arc<str> as From<RestartPolicy>>::from(variant);
13786            assert_eq!(
13787                via_trait, owned_arc,
13788                "From<&RestartPolicy> for std::sync::Arc<str> and \
13789                 From<RestartPolicy> for std::sync::Arc<str> must \
13790                 resolve identically on RestartPolicy::{variant:?} — \
13791                 divergence signals the borrowed-input and owned-input \
13792                 std::sync::Arc<str> forward-projection input-shape \
13793                 paths have drifted onto different emit-sets"
13794            );
13795            let borrowed_static: &'static str =
13796                <&'static str as From<&RestartPolicy>>::from(&variant);
13797            assert_eq!(
13798                via_trait.as_ref(),
13799                borrowed_static,
13800                "From<&RestartPolicy> for std::sync::Arc<str> and \
13801                 From<&RestartPolicy> for &'static str must resolve \
13802                 identically on RestartPolicy::{variant:?} — \
13803                 divergence signals the borrowed-input std::sync::Arc<str> \
13804                 and &'static str return-shape paths have drifted onto \
13805                 different emit-sets"
13806            );
13807            let borrowed_string: String = <String as From<&RestartPolicy>>::from(&variant);
13808            assert_eq!(
13809                via_trait.as_ref(),
13810                borrowed_string.as_str(),
13811                "From<&RestartPolicy> for std::sync::Arc<str> and \
13812                 From<&RestartPolicy> for String must resolve \
13813                 identically on RestartPolicy::{variant:?} — \
13814                 divergence signals the borrowed-input std::sync::Arc<str> \
13815                 and owned-`String` return-shape paths have drifted \
13816                 onto different emit-sets"
13817            );
13818            let borrowed_cow: std::borrow::Cow<'static, str> =
13819                <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&variant);
13820            assert_eq!(
13821                via_trait.as_ref(),
13822                borrowed_cow.as_ref(),
13823                "From<&RestartPolicy> for std::sync::Arc<str> and \
13824                 From<&RestartPolicy> for Cow<'static, str> must \
13825                 resolve identically on RestartPolicy::{variant:?} — \
13826                 divergence signals the borrowed-input std::sync::Arc<str> \
13827                 and Cow<'static, str> return-shape paths have drifted \
13828                 onto different emit-sets"
13829            );
13830            let borrowed_box: Box<str> = <Box<str> as From<&RestartPolicy>>::from(&variant);
13831            assert_eq!(
13832                via_trait.as_ref(),
13833                borrowed_box.as_ref(),
13834                "From<&RestartPolicy> for std::sync::Arc<str> and \
13835                 From<&RestartPolicy> for Box<str> must resolve \
13836                 identically on RestartPolicy::{variant:?} — \
13837                 divergence signals the borrowed-input std::sync::Arc<str> \
13838                 and Box<str> return-shape paths have drifted onto \
13839                 different emit-sets"
13840            );
13841        }
13842        let via_iter: Vec<std::sync::Arc<str>> = RestartPolicy::ALL
13843            .iter()
13844            .map(std::sync::Arc::<str>::from)
13845            .collect();
13846        let via_method: Vec<std::sync::Arc<str>> = RestartPolicy::ALL
13847            .iter()
13848            .map(|p| std::sync::Arc::<str>::from(p.as_str()))
13849            .collect();
13850        assert_eq!(
13851            via_iter, via_method,
13852            "`.iter().map(std::sync::Arc::<str>::from)` over \
13853             RestartPolicy::ALL — a call site whose iteration axis \
13854             holds `&RestartPolicy` by construction — must byte-\
13855             equal `.iter().map(|p| std::sync::Arc::<str>::from(p.as_str()))` \
13856             on every arm — the borrowed-input std::sync::Arc<str> \
13857             `From<&RestartPolicy> for std::sync::Arc<str>` axis is \
13858             what makes the `std::sync::Arc::<str>::from` composition \
13859             route through the substrate-primitive \
13860             `RestartPolicy::as_str` accessor without a spurious \
13861             `Copy` deref (which would only be reachable through the \
13862             owned-input `From<RestartPolicy> for std::sync::Arc<str>` \
13863             axis by first calling `.copied()` on the iterator)"
13864        );
13865    }
13866
13867    #[test]
13868    fn restart_policy_from_into_rc_str_routes_through_as_str_accessor() {
13869        // Fail-before-pass-after byte-parity pin on the newly lifted
13870        // `impl From<RestartPolicy> for std::rc::Rc<str>` — asserts
13871        // the owned-input standard-library trait impl and the
13872        // substrate-primitive [`super::RestartPolicy::as_str`]
13873        // `pub const fn` accessor resolve to the same three-arm emit-
13874        // set across every arm the exhaustive
13875        // [`super::RestartPolicy::ALL`] slice enumerates, and cross-
13876        // witnesses against every sibling owned-input `{&'static str,
13877        // String, Cow<'static, str>, Box<str>, std::sync::Arc<str>}`
13878        // return-shape axis so the six return-shape paths on the
13879        // owned-input surface lock together by construction. Closes
13880        // the substrate-wide [`std::rc::Rc<str>`] forward-projection
13881        // campaign on the M2-OTP-shape `:supervisor :estrategia` +
13882        // `:children :restart` slot pair the sibling-restart
13883        // [`RestartStrategy`] first-mover (71ad8f4) opened one
13884        // projection tier prior on the paired sibling enum.
13885        for &variant in RestartPolicy::ALL {
13886            let via_trait: std::rc::Rc<str> =
13887                <std::rc::Rc<str> as From<RestartPolicy>>::from(variant);
13888            let via_method: &'static str = variant.as_str();
13889            assert_eq!(
13890                via_trait.as_ref(),
13891                via_method,
13892                "From<RestartPolicy> for std::rc::Rc<str> impl must \
13893                 round-trip RestartPolicy::{variant:?} to the same \
13894                 lifted SUPERVISOR_CHILD_RESTART_* const \
13895                 RestartPolicy::as_str returns — divergence signals \
13896                 a silent detour off the substrate-primitive accessor"
13897            );
13898            let via_into: std::rc::Rc<str> = variant.into();
13899            assert_eq!(
13900                via_into.as_ref(),
13901                via_method,
13902                "Into<std::rc::Rc<str>>::into on \
13903                 RestartPolicy::{variant:?} must byte-equal \
13904                 RestartPolicy::as_str on the same input — the \
13905                 blanket-derived Into shape must resolve to the same \
13906                 as_str dispatch as the explicit From impl"
13907            );
13908            let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
13909            assert_eq!(
13910                via_trait.as_ref(),
13911                owned_static,
13912                "From<RestartPolicy> for std::rc::Rc<str> and \
13913                 From<RestartPolicy> for &'static str must resolve \
13914                 identically on RestartPolicy::{variant:?}"
13915            );
13916            let owned_string: String = <String as From<RestartPolicy>>::from(variant);
13917            assert_eq!(
13918                via_trait.as_ref(),
13919                owned_string.as_str(),
13920                "From<RestartPolicy> for std::rc::Rc<str> and \
13921                 From<RestartPolicy> for String must resolve \
13922                 identically on RestartPolicy::{variant:?}"
13923            );
13924            let owned_cow: std::borrow::Cow<'static, str> =
13925                <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
13926            assert_eq!(
13927                via_trait.as_ref(),
13928                owned_cow.as_ref(),
13929                "From<RestartPolicy> for std::rc::Rc<str> and \
13930                 From<RestartPolicy> for Cow<'static, str> must \
13931                 resolve identically on RestartPolicy::{variant:?}"
13932            );
13933            let owned_box: Box<str> = <Box<str> as From<RestartPolicy>>::from(variant);
13934            assert_eq!(
13935                via_trait.as_ref(),
13936                owned_box.as_ref(),
13937                "From<RestartPolicy> for std::rc::Rc<str> and \
13938                 From<RestartPolicy> for Box<str> must resolve \
13939                 identically on RestartPolicy::{variant:?}"
13940            );
13941            let owned_arc: std::sync::Arc<str> =
13942                <std::sync::Arc<str> as From<RestartPolicy>>::from(variant);
13943            assert_eq!(
13944                via_trait.as_ref(),
13945                owned_arc.as_ref(),
13946                "From<RestartPolicy> for std::rc::Rc<str> and \
13947                 From<RestartPolicy> for std::sync::Arc<str> must \
13948                 resolve identically on RestartPolicy::{variant:?}"
13949            );
13950        }
13951    }
13952
13953    #[test]
13954    fn restart_policy_from_borrowed_into_rc_str_routes_through_as_str_accessor() {
13955        // Fail-before-pass-after byte-parity pin on the newly lifted
13956        // `impl From<&RestartPolicy> for std::rc::Rc<str>` — asserts
13957        // the borrowed-input standard-library trait impl and the
13958        // substrate-primitive [`super::RestartPolicy::as_str`]
13959        // `pub const fn` accessor resolve to the same three-arm emit-
13960        // set across every arm the exhaustive
13961        // [`super::RestartPolicy::ALL`] slice enumerates. Closes the
13962        // `{Self, &Self}` input-shape corner of the
13963        // [`std::rc::Rc<str>`] axis on this enum, cross-witnesses
13964        // against the paired owned-input axis and every sibling
13965        // borrowed-input return-shape axis, and locks the
13966        // `.iter().map(std::rc::Rc::<str>::from)` pipe over
13967        // [`super::RestartPolicy::ALL`] to the substrate-primitive
13968        // accessor without a spurious [`Copy`] deref (which would only
13969        // be reachable through the owned-input axis by first calling
13970        // `.copied()` on the iterator).
13971        for &variant in RestartPolicy::ALL {
13972            let via_trait: std::rc::Rc<str> =
13973                <std::rc::Rc<str> as From<&RestartPolicy>>::from(&variant);
13974            let via_method: &'static str = variant.as_str();
13975            assert_eq!(
13976                via_trait.as_ref(),
13977                via_method,
13978                "From<&RestartPolicy> for std::rc::Rc<str> impl must \
13979                 round-trip &RestartPolicy::{variant:?} to the same \
13980                 lifted SUPERVISOR_CHILD_RESTART_* const \
13981                 RestartPolicy::as_str returns"
13982            );
13983            let via_into: std::rc::Rc<str> = (&variant).into();
13984            assert_eq!(
13985                via_into.as_ref(),
13986                via_method,
13987                "Into<std::rc::Rc<str>>::into on \
13988                 &RestartPolicy::{variant:?} must byte-equal \
13989                 RestartPolicy::as_str on the same input"
13990            );
13991            let owned_rc: std::rc::Rc<str> =
13992                <std::rc::Rc<str> as From<RestartPolicy>>::from(variant);
13993            assert_eq!(
13994                via_trait, owned_rc,
13995                "From<&RestartPolicy> for std::rc::Rc<str> and \
13996                 From<RestartPolicy> for std::rc::Rc<str> must \
13997                 resolve identically on RestartPolicy::{variant:?}"
13998            );
13999            let borrowed_static: &'static str =
14000                <&'static str as From<&RestartPolicy>>::from(&variant);
14001            assert_eq!(
14002                via_trait.as_ref(),
14003                borrowed_static,
14004                "From<&RestartPolicy> for std::rc::Rc<str> and \
14005                 From<&RestartPolicy> for &'static str must resolve \
14006                 identically on RestartPolicy::{variant:?}"
14007            );
14008            let borrowed_string: String = <String as From<&RestartPolicy>>::from(&variant);
14009            assert_eq!(
14010                via_trait.as_ref(),
14011                borrowed_string.as_str(),
14012                "From<&RestartPolicy> for std::rc::Rc<str> and \
14013                 From<&RestartPolicy> for String must resolve \
14014                 identically on RestartPolicy::{variant:?}"
14015            );
14016            let borrowed_cow: std::borrow::Cow<'static, str> =
14017                <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&variant);
14018            assert_eq!(
14019                via_trait.as_ref(),
14020                borrowed_cow.as_ref(),
14021                "From<&RestartPolicy> for std::rc::Rc<str> and \
14022                 From<&RestartPolicy> for Cow<'static, str> must \
14023                 resolve identically on RestartPolicy::{variant:?}"
14024            );
14025            let borrowed_box: Box<str> = <Box<str> as From<&RestartPolicy>>::from(&variant);
14026            assert_eq!(
14027                via_trait.as_ref(),
14028                borrowed_box.as_ref(),
14029                "From<&RestartPolicy> for std::rc::Rc<str> and \
14030                 From<&RestartPolicy> for Box<str> must resolve \
14031                 identically on RestartPolicy::{variant:?}"
14032            );
14033            let borrowed_arc: std::sync::Arc<str> =
14034                <std::sync::Arc<str> as From<&RestartPolicy>>::from(&variant);
14035            assert_eq!(
14036                via_trait.as_ref(),
14037                borrowed_arc.as_ref(),
14038                "From<&RestartPolicy> for std::rc::Rc<str> and \
14039                 From<&RestartPolicy> for std::sync::Arc<str> must \
14040                 resolve identically on RestartPolicy::{variant:?}"
14041            );
14042        }
14043        let via_iter: Vec<std::rc::Rc<str>> = RestartPolicy::ALL
14044            .iter()
14045            .map(std::rc::Rc::<str>::from)
14046            .collect();
14047        let via_method: Vec<std::rc::Rc<str>> = RestartPolicy::ALL
14048            .iter()
14049            .map(|p| std::rc::Rc::<str>::from(p.as_str()))
14050            .collect();
14051        assert_eq!(
14052            via_iter, via_method,
14053            "`.iter().map(std::rc::Rc::<str>::from)` over \
14054             RestartPolicy::ALL — a call site whose iteration axis \
14055             holds `&RestartPolicy` by construction — must byte-\
14056             equal `.iter().map(|p| std::rc::Rc::<str>::from(p.as_str()))` \
14057             on every arm — the borrowed-input std::rc::Rc<str> \
14058             `From<&RestartPolicy> for std::rc::Rc<str>` axis is \
14059             what makes the `std::rc::Rc::<str>::from` composition \
14060             route through the substrate-primitive \
14061             `RestartPolicy::as_str` accessor without a spurious \
14062             `Copy` deref (which would only be reachable through the \
14063             owned-input `From<RestartPolicy> for std::rc::Rc<str>` \
14064             axis by first calling `.copied()` on the iterator)"
14065        );
14066    }
14067
14068    // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_RESTART_* identity ─
14069
14070    #[test]
14071    fn restart_policy_variants_serialize_to_lifted_scalar_values() {
14072        // The fail-before-pass-after pin: pre-lift there was no
14073        // single-source binding between the [`RestartPolicy`] variant
14074        // name the un-`rename`d `Serialize` derive emits under
14075        // [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
14076        // byte-string every downstream cluster-side dispatcher (the
14077        // future wasm-operator's per-child post-exit restart-decision
14078        // branch, the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
14079        // materializer's admission-time enum-arm bind, the
14080        // `caixa-operator`'s hierarchical reconciliation scheduler's
14081        // per-child-policy fan-out) probes verbatim. A future
14082        // `#[serde(rename_all = "kebab-case")]` attribute on the enum —
14083        // or a per-variant `#[serde(rename = "…")]` override, or a
14084        // variant rename in the source — would silently rebrand the
14085        // emitted scalar under one spelling while every downstream
14086        // dispatcher still probed the other, with the failure surfacing
14087        // at the operator's reconcile posture (children coming up under
14088        // the `default()` `Permanent` arm rather than the typed slot's
14089        // declared policy — a `:temporary` `oneShot` child would be
14090        // restarted on clean exit, treating the successful-completion
14091        // signal as failure and re-running the completion-terminal
14092        // one-shot indefinitely; a `:transient` child that clean-exited
14093        // would be restarted, masking the clean-completion contract)
14094        // far from the source rebrand commit and with no field naming
14095        // the drift. Pinning the two paths (the `Serialize` derive's
14096        // serialized string AND the [`RestartPolicy::as_str`] helper)
14097        // to the same three lifted
14098        // [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
14099        // [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
14100        // [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
14101        // byte-strings makes any future drift on either endpoint fail
14102        // here at caixa-core build time. Peer of the sibling
14103        // [`restart_strategy_variants_serialize_to_lifted_scalar_values`]
14104        // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
14105        // and the M3
14106        // `placement_strategy_variants_serialize_to_lifted_scalar_values`
14107        // (3f0e21c) on the per-Aplicacao distribution-strategy axis —
14108        // same three-path-convergence discipline, extended to close the
14109        // third OTP-shaped closed-enum discriminator axis on the caixa
14110        // typed surface (per-child restart-decision policy).
14111        for (variant, expected) in [
14112            (
14113                RestartPolicy::Permanent,
14114                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
14115            ),
14116            (
14117                RestartPolicy::Temporary,
14118                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
14119            ),
14120            (
14121                RestartPolicy::Transient,
14122                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
14123            ),
14124        ] {
14125            let json = serde_json::to_string(&variant).unwrap();
14126            assert_eq!(
14127                json,
14128                format!("\"{expected}\""),
14129                "RestartPolicy::{variant:?} must serialize to {expected:?}"
14130            );
14131            assert_eq!(
14132                variant.as_str(),
14133                expected,
14134                "RestartPolicy::{variant:?}.as_str() must return the lifted \
14135                 SUPERVISOR_CHILD_RESTART_* constant"
14136            );
14137        }
14138    }
14139
14140    #[test]
14141    fn supervisor_child_restart_consts_are_pairwise_distinct() {
14142        // Cross-arm drift-detection pin: a future collapse of two
14143        // canonical variant byte-strings onto the same value (e.g. an
14144        // accidental copy-paste flip of `SUPERVISOR_CHILD_RESTART_TRANSIENT`
14145        // to also read `"Permanent"`) would silently reroute every
14146        // downstream operator's per-child-policy dispatch onto the
14147        // sibling arm's reconcile branch and pass every propagation-probe
14148        // test that expected only the stale arm's value — a `:transient`
14149        // child would come up under the `:permanent` restart-decision
14150        // posture on every subsequent clean exit, so a completion-terminal
14151        // child would be restarted indefinitely against its declared
14152        // policy. Peer of the sibling
14153        // [`supervisor_estrategia_consts_are_pairwise_distinct`]
14154        // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
14155        // and the four-way distinct pin
14156        // `supervisor_key_consts_are_pairwise_distinct` (40cc4e5) on the
14157        // top-level `SUPERVISOR_KEY_*` axis.
14158        let all = [
14159            crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
14160            crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
14161            crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
14162        ];
14163        for (i, a) in all.iter().enumerate() {
14164            for (j, b) in all.iter().enumerate() {
14165                if i != j {
14166                    assert_ne!(
14167                        a, b,
14168                        "SUPERVISOR_CHILD_RESTART_* consts must be pairwise distinct \
14169                         — got duplicate {a:?} at indices {i} and {j}",
14170                    );
14171                }
14172            }
14173        }
14174    }
14175
14176    #[test]
14177    fn restart_policy_display_routes_through_as_str_helper() {
14178        // The fail-before-pass-after pin on the first half of the
14179        // three-path convergence: pre-convergence [`RestartPolicy`]
14180        // carried a [`std::fmt::Display`] surface via its
14181        // `#[discriminant(also_display)]` gen-platform derive route,
14182        // which arrived kebab-case as `"permanent"` / `"temporary"`
14183        // / `"transient"` on this three-arm enum (whose variant
14184        // names each collapse to their own lowercase form under the
14185        // kebab-case transform) while the wire format ran as
14186        // PascalCase `"Permanent"` / `"Temporary"` / `"Transient"`
14187        // through the un-`rename`d serde derive. Every consumer
14188        // reaching for a policy byte-string past the wire format had
14189        // to pick between three paths ([`RestartPolicy::as_str`],
14190        // the `Serialize` derive's serialized string, or
14191        // `format!("{v}")` on the discriminant-Display route), any
14192        // two of which a future variant rename or
14193        // `#[serde(rename_all = "kebab-case")]` attribute would
14194        // silently desynchronize. Wiring [`std::fmt::Display`]
14195        // through [`RestartPolicy::as_str`] closes the third path:
14196        // every `format!("{v}")` call reaches the same lifted
14197        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the
14198        // wire format and the [`RestartPolicy::as_str`] helper
14199        // already route through, so a future variant rename lands at
14200        // exactly one place. Pin the routing here so a future
14201        // `impl std::fmt::Display for RestartPolicy`
14202        // reimplementation that hand-rolls the arms instead of
14203        // delegating to [`RestartPolicy::as_str`] fails at
14204        // caixa-core build time. Peer of the sibling
14205        // [`restart_strategy_display_routes_through_as_str_helper`]
14206        // on the per-supervisor sibling-restart-strategy axis and
14207        // the M3
14208        // `placement_strategy_display_routes_through_as_str_helper`
14209        // (cc8f749) — the third of three OTP-shape closed-enum
14210        // discriminator axes on the caixa typed surface now
14211        // converged onto the same three-path
14212        // (Display → as_str → lifted const) discipline.
14213        for variant in [
14214            RestartPolicy::Permanent,
14215            RestartPolicy::Temporary,
14216            RestartPolicy::Transient,
14217        ] {
14218            assert_eq!(
14219                variant.to_string(),
14220                variant.as_str(),
14221                "RestartPolicy::{variant:?} Display must route through \
14222                 RestartPolicy::as_str (single source of truth: the lifted \
14223                 SUPERVISOR_CHILD_RESTART_* const the wire format also emits)"
14224            );
14225        }
14226    }
14227
14228    #[test]
14229    fn restart_policy_display_matches_serialized_wire_byte_string() {
14230        // The fail-before-pass-after pin on the second half of the
14231        // three-path convergence: `Display` (user-facing text) agrees
14232        // byte-for-byte with the `Serialize` derive's wire format
14233        // (canonical camelCase-schema `SUPERVISOR_CHILD_KEY_RESTART`
14234        // scalar) on every variant. Pre-convergence the two paths
14235        // were structurally independent — a future
14236        // `#[serde(rename_all = "kebab-case")]` attribute on the
14237        // enum would silently rebrand the emitted wire scalar
14238        // (`permanent`, `temporary`, `transient`) while every
14239        // consumer that pretty-prints the policy (the future
14240        // wasm-operator's per-child post-exit restart-decision
14241        // diagnostic line, the future `feira app graph` per-child
14242        // restart column, the future M4
14243        // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
14244        // per-child admission-webhook rejection body) would still
14245        // emit the PascalCase form the `as_str` / `Display` route
14246        // returns, with the mismatch surfacing at consumer parse
14247        // time / operator dispatch time far from the source rebrand
14248        // commit. Pin the two paths byte-for-byte here so any future
14249        // serde-attribute or variant-rename drift is a
14250        // caixa-core-build-time test failure at this call, not a
14251        // silent per-consumer dispatch miss. Peer of the sibling
14252        // [`restart_strategy_display_matches_serialized_wire_byte_string`]
14253        // on the per-supervisor sibling-restart-strategy axis and
14254        // the M3
14255        // `placement_strategy_display_matches_serialized_wire_byte_string`
14256        // (cc8f749).
14257        for variant in [
14258            RestartPolicy::Permanent,
14259            RestartPolicy::Temporary,
14260            RestartPolicy::Transient,
14261        ] {
14262            let wire = serde_json::to_string(&variant).unwrap();
14263            let unquoted = wire
14264                .strip_prefix('"')
14265                .and_then(|s| s.strip_suffix('"'))
14266                .expect("serialized RestartPolicy is a JSON string");
14267            assert_eq!(
14268                variant.to_string(),
14269                unquoted,
14270                "RestartPolicy::{variant:?} Display byte-string must match the \
14271                 Serialize derive's wire byte-string (three-path convergence: \
14272                 Display + as_str + Serialize all resolve to the same \
14273                 SUPERVISOR_CHILD_RESTART_* const)"
14274            );
14275        }
14276    }
14277
14278    #[test]
14279    fn restart_policy_as_ref_str_routes_through_as_str_accessor() {
14280        // Fail-before-pass-after byte-parity pin on the lifted
14281        // `impl AsRef<str> for RestartPolicy` — asserts the
14282        // standard-library trait impl and the substrate-primitive
14283        // [`RestartPolicy::as_str`] `pub const fn` accessor resolve
14284        // to the same `&str` per instance across the three-arm
14285        // closed set, so any future silent detour that routes the
14286        // impl through a divergent projection (a per-arm inline
14287        // `match self { RestartPolicy::Permanent => "Permanent", … }`
14288        // re-inlining that opens a compile-time link to the un-lifted
14289        // arm-literal, a swap onto the kebab-case
14290        // [`gen_platform::Discriminant`] catalog identity that would
14291        // collide the wire axis with the dispatcher-catalog axis) trips
14292        // at caixa-core test time under `PartialEq` rather than at a
14293        // downstream `impl AsRef<str>`-bound consumer's silent split.
14294        // Sweeps every one of the three arms
14295        // [`RestartPolicy::ALL`] carries so no arm's projection is
14296        // covered only by the sibling wire-format `Serialize` derive
14297        // path. Peer of the sibling
14298        // [`restart_strategy_as_ref_str_routes_through_as_str_accessor`]
14299        // (63eb1a4) on the paired per-supervisor sibling-restart-
14300        // strategy axis and the [`crate::CaixaVersion`]
14301        // `AsRef<str>`-byte-parity pin (16d5c7e) on the paired
14302        // top-level `:versao` typed newtype — the three pins together
14303        // cover the substrate primitive's `AsRef<str>` projection axis
14304        // on the paired newtype + M2 closed-set-typed-enum surface.
14305        for &variant in RestartPolicy::ALL {
14306            assert_eq!(
14307                <RestartPolicy as AsRef<str>>::as_ref(&variant),
14308                variant.as_str(),
14309                "AsRef<str> impl on RestartPolicy::{variant:?} must \
14310                 byte-equal RestartPolicy::as_str on the same instance \
14311                 — divergence signals a silent detour off the substrate-\
14312                 primitive accessor"
14313            );
14314        }
14315    }
14316
14317    #[test]
14318    fn restart_policy_as_ref_str_routes_through_display_via_shared_accessor() {
14319        // Fail-before-pass-after byte-parity pin on the three-path
14320        // convergence discipline the M2 per-child-restart-policy
14321        // primitive now carries on the `&str`-projection axis:
14322        // `<RestartPolicy as AsRef<str>>::as_ref(&v)` (the newly
14323        // lifted impl), `format!("{v}")` (the pre-existing
14324        // [`fmt::Display`] impl), and `v.as_str()` (the substrate-
14325        // primitive `pub const fn` accessor both trait impls delegate
14326        // through) must resolve to the same byte-string on every
14327        // instance across the three-arm closed set. Refuses any future
14328        // divergence between the two trait impls (a stray
14329        // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
14330        // rather than delegating through the shared accessor; a
14331        // hypothetical `AsRef<str>` rewrite that inlines a per-arm
14332        // literal cascade) that would silently split the two
14333        // projection paths of the same closed-set typed enum. Mirrors
14334        // the sibling three-path-convergence discipline the peer
14335        // [`RestartStrategy`] typed enum carries on its
14336        // `AsRef<str>` / `Display` / `as_str` triple
14337        // (supervisor.rs pin
14338        // `restart_strategy_as_ref_str_routes_through_display_via_shared_accessor`,
14339        // 63eb1a4) and the [`crate::CaixaVersion`] typed newtype
14340        // carries on the same triple (version.rs pin
14341        // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
14342        // 16d5c7e).
14343        for &variant in RestartPolicy::ALL {
14344            let via_as_ref: &str = <RestartPolicy as AsRef<str>>::as_ref(&variant);
14345            let via_display: String = format!("{variant}");
14346            let via_accessor: &str = variant.as_str();
14347            assert_eq!(via_as_ref, via_accessor);
14348            assert_eq!(via_display, via_accessor);
14349            assert_eq!(via_as_ref, via_display.as_str());
14350        }
14351    }
14352
14353    // The `generic_bytes_sink(&variant)` and `borrowed_hasher.update(&variant)`
14354    // shapes below are the borrowed-input witness half of the by-value +
14355    // by-reference partition the paired witness pair carries: the pair proves
14356    // the trait bound accepts both owned (`variant`) and borrowed (`&variant`)
14357    // shapes through the same substrate-primitive `as_str` accessor, which is
14358    // the shape the caixa-lacre BLAKE3 content-address closure composes.
14359    // `clippy::needless_borrows_for_generic_args` would fold the borrowed half
14360    // into the owned half and collapse the by-value/by-reference partition
14361    // this test load-bears; the `#[allow]` documents that the partition is
14362    // deliberate, not an oversight.
14363    #[allow(clippy::needless_borrows_for_generic_args)]
14364    #[test]
14365    fn restart_policy_as_ref_bytes_routes_through_as_str_accessor() {
14366        // `<T: AsRef<[u8]>>`-bound generic-consumer witness: a byte-input
14367        // function that binds its argument through the standard-library
14368        // [`AsRef<[u8]>`] trait bound accepts a [`super::RestartPolicy`]
14369        // directly, without the caller open-coding the two-hop
14370        // `restart.as_str().as_bytes()` composition. Lifted to the top
14371        // of the function per `clippy::items_after_statements`.
14372        fn generic_bytes_sink<T: AsRef<[u8]>>(t: T) -> Vec<u8> {
14373            t.as_ref().to_vec()
14374        }
14375        // `blake3::Hasher::update`-shape byte-input surface mock: mirrors
14376        // `blake3::Hasher::update` / `ring::digest::Context::update` /
14377        // `sha2::Sha256::update`'s `impl AsRef<[u8]>`-bound `update`
14378        // signature so a per-child BLAKE3 content-address closure that
14379        // composes `hasher.update(restart)` on the [`crate::Lacre`]
14380        // closure builder reaches the substrate-primitive `as_str`
14381        // accessor through the [`super::RestartPolicy`] `AsRef<[u8]>`
14382        // axis and no other. Lifted to the top of the function per
14383        // `clippy::items_after_statements`.
14384        struct MockHasher(Vec<u8>);
14385        impl MockHasher {
14386            fn new() -> Self {
14387                Self(Vec::new())
14388            }
14389            fn update(&mut self, bytes: impl AsRef<[u8]>) -> &mut Self {
14390                self.0.extend_from_slice(bytes.as_ref());
14391                self
14392            }
14393            fn finalize(self) -> Vec<u8> {
14394                self.0
14395            }
14396        }
14397
14398        // Fail-before-pass-after byte-parity pin on the newly lifted
14399        // `impl AsRef<[u8]> for RestartPolicy` — asserts the trait-
14400        // idiomatic byte-view standard-library impl and the substrate-
14401        // primitive [`super::RestartPolicy::as_str`] `pub const fn`
14402        // accessor's `.as_bytes()` byte-tail resolve to the same three-
14403        // arm `PascalCase` wire byte-string emit-set across every arm
14404        // the exhaustive [`super::RestartPolicy::ALL`] slice enumerates.
14405        // Extends the trait-idiomatic byte-view axis onto the second
14406        // (and final) M2 OTP-shape closed-set fieldless typed enum peer
14407        // on the caixa surface (the paired per-child restart-decision
14408        // policy sibling on the same M2 `:supervisor` slot), closing
14409        // the byte-view axis across the `:supervisor :estrategia` +
14410        // `:children :restart` M2 slot pair the sibling
14411        // [`super::RestartStrategy`] first-mover (cd4c4e0) opened.
14412        //
14413        // Rust's standard library carries `impl AsRef<[u8]> for str` and
14414        // `impl AsRef<[u8]> for String`, so a two-hop composition
14415        // `restart.as_str().as_bytes()` (or the equally two-hop
14416        // `AsRef::<str>::as_ref(&restart).as_bytes()`) is reachable
14417        // through the pre-existing str-view axis alone. But that two-hop
14418        // shape has no compile-time link back to the byte-projection
14419        // axis, forces every downstream `<T: AsRef<[u8]>>`-bound
14420        // consumer to open-code the two-hop composition at every call
14421        // site, and admits a silent split whenever a future call site
14422        // takes a sibling reverse-projection axis whose `.as_bytes()`
14423        // byte-tail carries no compile-time byte-view surface. This
14424        // impl closes the byte-view axis at the substrate-primitive
14425        // [`super::RestartPolicy::as_str`] accessor so every future
14426        // `<T: AsRef<[u8]>>`-bound consumer reaches the same lifted
14427        // [`super::crate::render::SUPERVISOR_CHILD_RESTART_*`] const
14428        // roster the paired str-view axes already return through —
14429        // through one trait dispatch.
14430        for &variant in RestartPolicy::ALL {
14431            let via_trait: &[u8] = <RestartPolicy as AsRef<[u8]>>::as_ref(&variant);
14432            let via_method_bytes: &[u8] = variant.as_str().as_bytes();
14433            assert_eq!(
14434                via_trait, via_method_bytes,
14435                "AsRef<[u8]> for RestartPolicy impl must byte-equal \
14436                 RestartPolicy::as_str().as_bytes() on \
14437                 RestartPolicy::{variant:?} — divergence signals a \
14438                 silent detour off the substrate-primitive accessor"
14439            );
14440            // Cross-axis witness against the paired str-view axes'
14441            // `.as_bytes()` byte-tails: [`AsRef<str>`] /
14442            // [`std::fmt::Display`] / [`super::RestartPolicy::as_str`]
14443            // all resolve to the same lifted
14444            // [`super::crate::render::SUPERVISOR_CHILD_RESTART_*`] const
14445            // roster, and the byte-view axis must byte-equal each of
14446            // their `.as_bytes()` byte-tails by construction — locking
14447            // the str-view and byte-view axes together at the
14448            // substrate-primitive accessor.
14449            let str_view_ref: &str = <RestartPolicy as AsRef<str>>::as_ref(&variant);
14450            assert_eq!(
14451                via_trait,
14452                str_view_ref.as_bytes(),
14453                "AsRef<[u8]> for RestartPolicy and AsRef<str> for \
14454                 RestartPolicy must resolve to byte-equal byte-tails \
14455                 on RestartPolicy::{variant:?} — divergence signals \
14456                 the byte-view and str-view axes have drifted off the \
14457                 same substrate-primitive as_str accessor"
14458            );
14459            let display_bytes = variant.to_string();
14460            assert_eq!(
14461                via_trait,
14462                display_bytes.as_bytes(),
14463                "AsRef<[u8]> for RestartPolicy and \
14464                 <RestartPolicy as std::fmt::Display>::to_string must \
14465                 resolve to byte-equal byte-tails on \
14466                 RestartPolicy::{variant:?} — divergence signals the \
14467                 byte-view axis and the Display formatter axis have \
14468                 drifted off the same substrate-primitive as_str \
14469                 accessor"
14470            );
14471            // Cross-axis witness against the paired reverse-projection
14472            // axes' `.as_bytes()` byte-tails: every one of `{&'static
14473            // str, String, Cow<'static, str>, Box<str>,
14474            // std::sync::Arc<str>}` allocates (or borrows) the same
14475            // `PascalCase` wire byte-string the substrate-primitive
14476            // accessor emits, so the byte-view axis must byte-equal
14477            // each of their `.as_bytes()` byte-tails by construction.
14478            let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
14479            assert_eq!(
14480                via_trait,
14481                owned_static.as_bytes(),
14482                "AsRef<[u8]> for RestartPolicy and From<RestartPolicy> \
14483                 for &'static str must resolve to byte-equal byte-tails \
14484                 on RestartPolicy::{variant:?}"
14485            );
14486            let owned_string: String = <String as From<RestartPolicy>>::from(variant);
14487            assert_eq!(
14488                via_trait,
14489                owned_string.as_bytes(),
14490                "AsRef<[u8]> for RestartPolicy and From<RestartPolicy> \
14491                 for String must resolve to byte-equal byte-tails on \
14492                 RestartPolicy::{variant:?}"
14493            );
14494            let owned_cow: std::borrow::Cow<'static, str> =
14495                <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
14496            assert_eq!(
14497                via_trait,
14498                owned_cow.as_bytes(),
14499                "AsRef<[u8]> for RestartPolicy and From<RestartPolicy> \
14500                 for Cow<'static, str> must resolve to byte-equal byte-\
14501                 tails on RestartPolicy::{variant:?}"
14502            );
14503            let owned_box: Box<str> = <Box<str> as From<RestartPolicy>>::from(variant);
14504            assert_eq!(
14505                via_trait,
14506                owned_box.as_bytes(),
14507                "AsRef<[u8]> for RestartPolicy and From<RestartPolicy> \
14508                 for Box<str> must resolve to byte-equal byte-tails on \
14509                 RestartPolicy::{variant:?}"
14510            );
14511            let owned_arc: std::sync::Arc<str> =
14512                <std::sync::Arc<str> as From<RestartPolicy>>::from(variant);
14513            assert_eq!(
14514                via_trait,
14515                owned_arc.as_bytes(),
14516                "AsRef<[u8]> for RestartPolicy and From<RestartPolicy> \
14517                 for std::sync::Arc<str> must resolve to byte-equal \
14518                 byte-tails on RestartPolicy::{variant:?}"
14519            );
14520        }
14521        // `<T: AsRef<[u8]>>`-bound-consumer witness: the generic byte-
14522        // input function `generic_bytes_sink` (lifted above per
14523        // `clippy::items_after_statements`) accepts a
14524        // [`super::RestartPolicy`] directly through the trait bound,
14525        // without the caller open-coding the two-hop
14526        // `restart.as_str().as_bytes()` composition. This is the shape
14527        // that reaches the caixa-lacre BLAKE3 content-address closure's
14528        // `blake3::Hasher::update(impl AsRef<[u8]>)` byte-input surface
14529        // through this impl and no other.
14530        for &variant in RestartPolicy::ALL {
14531            let via_generic = generic_bytes_sink(variant);
14532            let via_borrowed_generic = generic_bytes_sink(&variant);
14533            let via_method_bytes = variant.as_str().as_bytes().to_vec();
14534            assert_eq!(
14535                via_generic, via_method_bytes,
14536                "generic `<T: AsRef<[u8]>>`-bound consumer on \
14537                 RestartPolicy::{variant:?} must yield the same byte-\
14538                 tail RestartPolicy::as_str().as_bytes() returns — \
14539                 divergence signals the byte-view axis fails to bridge \
14540                 a generic byte-input trait bound to the substrate-\
14541                 primitive accessor"
14542            );
14543            assert_eq!(
14544                via_borrowed_generic, via_method_bytes,
14545                "generic `<T: AsRef<[u8]>>`-bound consumer on \
14546                 &RestartPolicy::{variant:?} must yield the same byte-\
14547                 tail RestartPolicy::as_str().as_bytes() returns — the \
14548                 borrowed-input surface must resolve to the same as_str \
14549                 dispatch"
14550            );
14551        }
14552        // `blake3::Hasher::update`-shape byte-input surface witness on
14553        // the caixa-lacre compounding target: the `MockHasher` (lifted
14554        // above per `clippy::items_after_statements`) mirrors
14555        // `blake3::Hasher::update` / `ring::digest::Context::update` /
14556        // `sha2::Sha256::update`'s `impl AsRef<[u8]>`-bound update
14557        // signature and accepts a [`super::RestartPolicy`] directly,
14558        // routing its byte-tail through the substrate-primitive
14559        // `as_str` accessor — the shape a future per-child BLAKE3
14560        // content-address closure composes to fold a `:restart`
14561        // discriminator byte-tag into the [`crate::Lacre`] closure
14562        // body.
14563        for &variant in RestartPolicy::ALL {
14564            let mut owned_hasher = MockHasher::new();
14565            owned_hasher.update(variant);
14566            let owned_folded = owned_hasher.finalize();
14567            assert_eq!(
14568                owned_folded,
14569                variant.as_str().as_bytes(),
14570                "`hasher.update(restart)`-shape composition on \
14571                 RestartPolicy::{variant:?} must fold the same byte-\
14572                 tail RestartPolicy::as_str().as_bytes() returns — the \
14573                 shape a future per-child BLAKE3 content-address \
14574                 closure composes to fold a `:restart` discriminator \
14575                 byte-tag into the Lacre closure body"
14576            );
14577            let mut borrowed_hasher = MockHasher::new();
14578            borrowed_hasher.update(&variant);
14579            let borrowed_folded = borrowed_hasher.finalize();
14580            assert_eq!(
14581                borrowed_folded,
14582                variant.as_str().as_bytes(),
14583                "`hasher.update(&restart)`-shape composition on \
14584                 &RestartPolicy::{variant:?} must fold the same byte-\
14585                 tail RestartPolicy::as_str().as_bytes() returns — the \
14586                 borrowed-input surface must resolve to the same as_str \
14587                 dispatch"
14588            );
14589        }
14590    }
14591
14592    #[test]
14593    #[expect(
14594        clippy::too_many_lines,
14595        reason = "the byte-owned reverse-projection axis is closed \
14596                  here across the M2-OTP-shape :supervisor slot pair by \
14597                  extending onto the second and final M2-OTP-shape \
14598                  closed-set fieldless typed-enum peer, so the pin \
14599                  binds the new impl against every paired byte-view \
14600                  and str-owned axis on the same enum plus a generic \
14601                  <T: Into<Vec<u8>>>-bound consumer witness and a \
14602                  std::io::Write::write_all-shape owned-byte-sink \
14603                  surface witness on both owned and borrowed input \
14604                  shapes to lock the whole family against a future \
14605                  silent regression"
14606    )]
14607    fn restart_policy_from_into_owned_vec_bytes_routes_through_as_str_accessor() {
14608        // `<T: Into<Vec<u8>>>`-bound-consumer witness helper: a generic
14609        // owned-byte-input function accepts a [`super::RestartPolicy`]
14610        // directly through the trait bound, without the caller open-
14611        // coding the three-hop `restart.as_str().as_bytes().to_vec()`
14612        // composition. Lifted to the top of the function per
14613        // `clippy::items_after_statements`.
14614        fn generic_owned_bytes_sink<T: Into<Vec<u8>>>(t: T) -> Vec<u8> {
14615            t.into()
14616        }
14617        // `std::io::Write::write_all`-shape owned-byte-sink surface
14618        // mock: mirrors `std::io::Write::write_all` /
14619        // `bytes::BytesMut::extend_from_slice` / any per-arm audit-log
14620        // byte-sink that consumes a `Vec<u8>` payload via
14621        // `Into<Vec<u8>>`, so a future per-child per-`:restart` audit-
14622        // log emit reaches the substrate-primitive `as_str` accessor
14623        // through the byte-owned reverse-projection axis and no
14624        // other. Lifted to the top of the function per
14625        // `clippy::items_after_statements`.
14626        struct MockOwnedByteSink(Vec<u8>);
14627        impl MockOwnedByteSink {
14628            fn new() -> Self {
14629                Self(Vec::new())
14630            }
14631            fn write_all(&mut self, bytes: impl Into<Vec<u8>>) -> &mut Self {
14632                self.0.extend(bytes.into());
14633                self
14634            }
14635            fn finalize(self) -> Vec<u8> {
14636                self.0
14637            }
14638        }
14639
14640        // Fail-before-pass-after byte-parity pin on the newly lifted
14641        // `impl From<RestartPolicy> for Vec<u8>` and
14642        // `impl From<&RestartPolicy> for Vec<u8>` — asserts the trait-
14643        // idiomatic byte-owned reverse-projection standard-library
14644        // impls and the substrate-primitive
14645        // [`super::RestartPolicy::as_str`] `pub const fn` accessor's
14646        // `.as_bytes().to_vec()` byte-tail resolve to the same three-
14647        // arm PascalCase wire byte-string emit-set across every arm
14648        // the exhaustive [`super::RestartPolicy::ALL`] slice
14649        // enumerates. Closes the substrate-wide trait-idiomatic byte-
14650        // owned reverse-projection axis on the M2-OTP-shape closed-
14651        // set typed-enum pair the sibling first-mover
14652        // [`super::RestartStrategy`] `From<{Self, &Self}> for Vec<u8>`
14653        // lift (63e5dd0) opened one commit prior, matching the
14654        // trajectory the paired [`AsRef<[u8]>`] borrowed byte-view
14655        // axis campaign already tracked across the same slot pair
14656        // (cd4c4e0 → 98b08fa).
14657        for &variant in RestartPolicy::ALL {
14658            let via_owned_from: Vec<u8> = <Vec<u8> as From<RestartPolicy>>::from(variant);
14659            let via_borrowed_from: Vec<u8> = <Vec<u8> as From<&RestartPolicy>>::from(&variant);
14660            let via_method_bytes: Vec<u8> = variant.as_str().as_bytes().to_vec();
14661            assert_eq!(
14662                via_owned_from, via_method_bytes,
14663                "From<RestartPolicy> for Vec<u8> impl must byte-equal \
14664                 RestartPolicy::as_str().as_bytes().to_vec() on \
14665                 RestartPolicy::{variant:?} — divergence signals a \
14666                 silent detour off the substrate-primitive accessor"
14667            );
14668            assert_eq!(
14669                via_borrowed_from, via_method_bytes,
14670                "From<&RestartPolicy> for Vec<u8> impl must byte-\
14671                 equal RestartPolicy::as_str().as_bytes().to_vec() \
14672                 on RestartPolicy::{variant:?} — divergence signals \
14673                 a silent detour off the substrate-primitive accessor"
14674            );
14675            assert_eq!(
14676                via_owned_from, via_borrowed_from,
14677                "From<RestartPolicy> for Vec<u8> and \
14678                 From<&RestartPolicy> for Vec<u8> must byte-equal \
14679                 each other on RestartPolicy::{variant:?} — \
14680                 divergence signals the owned-input and borrowed-input \
14681                 paths have drifted off the same substrate-primitive \
14682                 as_str accessor"
14683            );
14684            // Cross-axis witness against the paired [`AsRef<[u8]>`]
14685            // borrowed byte-view axis (98b08fa): the byte-owned
14686            // reverse-projection axis must byte-equal the paired
14687            // borrowed byte-view axis by construction — locking the
14688            // byte-view and byte-owned axes together at the substrate-
14689            // primitive accessor.
14690            let borrowed_bytes: &[u8] = <RestartPolicy as AsRef<[u8]>>::as_ref(&variant);
14691            assert_eq!(
14692                via_owned_from,
14693                borrowed_bytes.to_vec(),
14694                "From<RestartPolicy> for Vec<u8> and AsRef<[u8]> for \
14695                 RestartPolicy must resolve to byte-equal byte-tails \
14696                 on RestartPolicy::{variant:?} — divergence signals \
14697                 the byte-owned and byte-view axes have drifted off \
14698                 the same substrate-primitive as_str accessor"
14699            );
14700            // Cross-axis witness against the str-owned reverse-
14701            // projection family's `.into_bytes()` / `.as_bytes().to_vec()`
14702            // byte-tails: every one of `{String, Cow<'static, str>,
14703            // Box<str>, std::sync::Arc<str>}` allocates (or borrows)
14704            // the same PascalCase wire byte-string the substrate-
14705            // primitive accessor emits, so the byte-owned axis must
14706            // byte-equal each of their owned byte-tails by
14707            // construction.
14708            let owned_string: String = <String as From<RestartPolicy>>::from(variant);
14709            assert_eq!(
14710                via_owned_from,
14711                owned_string.into_bytes(),
14712                "From<RestartPolicy> for Vec<u8> and \
14713                 String::from(policy).into_bytes() must resolve to \
14714                 byte-equal byte-tails on RestartPolicy::{variant:?}"
14715            );
14716            let owned_cow: std::borrow::Cow<'static, str> =
14717                <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
14718            assert_eq!(
14719                via_owned_from,
14720                owned_cow.as_bytes().to_vec(),
14721                "From<RestartPolicy> for Vec<u8> and \
14722                 From<RestartPolicy> for Cow<'static, str> must \
14723                 resolve to byte-equal byte-tails on \
14724                 RestartPolicy::{variant:?}"
14725            );
14726            let owned_box: Box<str> = <Box<str> as From<RestartPolicy>>::from(variant);
14727            assert_eq!(
14728                via_owned_from,
14729                owned_box.as_bytes().to_vec(),
14730                "From<RestartPolicy> for Vec<u8> and \
14731                 From<RestartPolicy> for Box<str> must resolve to \
14732                 byte-equal byte-tails on RestartPolicy::{variant:?}"
14733            );
14734            let owned_arc: std::sync::Arc<str> =
14735                <std::sync::Arc<str> as From<RestartPolicy>>::from(variant);
14736            assert_eq!(
14737                via_owned_from,
14738                owned_arc.as_bytes().to_vec(),
14739                "From<RestartPolicy> for Vec<u8> and \
14740                 From<RestartPolicy> for std::sync::Arc<str> must \
14741                 resolve to byte-equal byte-tails on \
14742                 RestartPolicy::{variant:?}"
14743            );
14744        }
14745        // `<T: Into<Vec<u8>>>`-bound-consumer witness on both owned
14746        // and borrowed input shapes: the generic owned-byte-input
14747        // function `generic_owned_bytes_sink` (lifted above per
14748        // `clippy::items_after_statements`) accepts a
14749        // [`super::RestartPolicy`] and a `&RestartPolicy` directly
14750        // through the trait bound, without the caller open-coding
14751        // the three-hop `restart.as_str().as_bytes().to_vec()`
14752        // composition.
14753        for &variant in RestartPolicy::ALL {
14754            let via_generic_owned = generic_owned_bytes_sink(variant);
14755            // Bind the borrowed-input path through an explicit
14756            // `&RestartPolicy` local so the generic-consumer witness
14757            // routes through `From<&RestartPolicy> for Vec<u8>` (T
14758            // binds to `&RestartPolicy`) rather than clippy-collapsing
14759            // the borrow onto the owned-input peer.
14760            let variant_ref: &RestartPolicy = &variant;
14761            let via_generic_borrowed = generic_owned_bytes_sink(variant_ref);
14762            let via_method_bytes = variant.as_str().as_bytes().to_vec();
14763            assert_eq!(
14764                via_generic_owned, via_method_bytes,
14765                "generic `<T: Into<Vec<u8>>>`-bound consumer on \
14766                 RestartPolicy::{variant:?} must yield the same byte-\
14767                 tail RestartPolicy::as_str().as_bytes() returns — \
14768                 divergence signals the byte-owned axis fails to bridge \
14769                 a generic owned-byte-input trait bound to the \
14770                 substrate-primitive accessor"
14771            );
14772            assert_eq!(
14773                via_generic_borrowed, via_method_bytes,
14774                "generic `<T: Into<Vec<u8>>>`-bound consumer on \
14775                 &RestartPolicy::{variant:?} must yield the same byte-\
14776                 tail RestartPolicy::as_str().as_bytes() returns — \
14777                 the borrowed-input surface must resolve to the same \
14778                 as_str dispatch"
14779            );
14780        }
14781        // `std::io::Write::write_all`-shape owned-byte-sink surface
14782        // witness: the `MockOwnedByteSink` (lifted above per
14783        // `clippy::items_after_statements`) mirrors
14784        // `std::io::Write::write_all` /
14785        // `bytes::BytesMut::extend_from_slice`'s `impl Into<Vec<u8>>`-
14786        // bound owned-byte input signature and accepts a
14787        // [`super::RestartPolicy`] directly on both owned and
14788        // borrowed input shapes, routing its byte-tail through the
14789        // substrate-primitive `as_str` accessor — the shape a future
14790        // per-child per-`:restart` audit-log emit composes to fold a
14791        // `:restart` discriminator byte-tag into a downstream owned-
14792        // byte-sink surface.
14793        for &variant in RestartPolicy::ALL {
14794            let mut owned_sink = MockOwnedByteSink::new();
14795            owned_sink.write_all(variant);
14796            let owned_folded = owned_sink.finalize();
14797            assert_eq!(
14798                owned_folded,
14799                variant.as_str().as_bytes(),
14800                "`sink.write_all(restart)`-shape composition on \
14801                 RestartPolicy::{variant:?} must fold the same byte-\
14802                 tail RestartPolicy::as_str().as_bytes() returns"
14803            );
14804            let mut borrowed_sink = MockOwnedByteSink::new();
14805            let variant_ref: &RestartPolicy = &variant;
14806            borrowed_sink.write_all(variant_ref);
14807            let borrowed_folded = borrowed_sink.finalize();
14808            assert_eq!(
14809                borrowed_folded,
14810                variant.as_str().as_bytes(),
14811                "`sink.write_all(&restart)`-shape composition on \
14812                 &RestartPolicy::{variant:?} must fold the same byte-\
14813                 tail RestartPolicy::as_str().as_bytes() returns — \
14814                 the borrowed-input surface must resolve to the same \
14815                 as_str dispatch"
14816            );
14817        }
14818    }
14819
14820    #[test]
14821    fn restart_policy_all_enumerates_every_variant_exactly_once() {
14822        // Fail-before-pass-after pin on the [`RestartPolicy::ALL`]
14823        // exhaustive-iteration surface: every variant appears exactly
14824        // once, and the slice length matches the arm count of the
14825        // closed set. Every consumer that walks the accepted-policy
14826        // set (a future `feira supervisor --restart …` CLI-side
14827        // arg-parse's "did you mean" hint, a future M4 admission-
14828        // webhook's per-child rejection body naming the accepted-
14829        // `:restart` list, the [`RestartPolicy::from_wire`] reverse-
14830        // projection consumers that iterate the accept-set for
14831        // diagnostic rendering) reads through this slice, so a future
14832        // arm addition that grows the enum but forgets to grow
14833        // [`Self::ALL`] silently truncates every downstream consumer's
14834        // accept-set at the same pre-addition boundary — this pin
14835        // fails at caixa-core build time on the pairwise-distinct +
14836        // arm-count invariants.
14837        //
14838        // Peer of the sibling [`RestartStrategy::ALL`] (4eec29c) /
14839        // [`crate::CaixaKind::ALL`] (6b1f4fb) /
14840        // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
14841        // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
14842        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
14843        // pins on the peer closed-set typed-enum axes.
14844        let all: &[RestartPolicy] = RestartPolicy::ALL;
14845        assert_eq!(
14846            all.len(),
14847            3,
14848            "RestartPolicy::ALL must enumerate every variant of the \
14849             three-arm closed set (Permanent, Temporary, Transient); \
14850             got {all:?}"
14851        );
14852        for (i, a) in all.iter().enumerate() {
14853            for (j, b) in all.iter().enumerate() {
14854                if i != j {
14855                    assert_ne!(
14856                        a, b,
14857                        "RestartPolicy::ALL must carry every variant exactly \
14858                         once — got duplicate {a:?} at indices {i} and {j}"
14859                    );
14860                }
14861            }
14862        }
14863        for variant in [
14864            RestartPolicy::Permanent,
14865            RestartPolicy::Temporary,
14866            RestartPolicy::Transient,
14867        ] {
14868            assert!(
14869                all.contains(&variant),
14870                "RestartPolicy::ALL must contain {variant:?} — a future arm \
14871                 addition that grows the enum but forgets to grow the ALL slice \
14872                 silently truncates every downstream consumer's accept-set at \
14873                 the pre-addition boundary"
14874            );
14875        }
14876    }
14877
14878    #[test]
14879    fn restart_policy_wire_names_covers_every_arm() {
14880        // Load-bearing pin on the substrate-canonical
14881        // [`RestartPolicy::WIRE_NAMES`] exhaustive accept-set roster on
14882        // the `PascalCase` wire byte-string axis: every variant of the
14883        // sibling [`RestartPolicy::ALL`] exhaustive-iteration surface
14884        // must project through [`RestartPolicy::as_str`] onto an entry
14885        // the [`RestartPolicy::WIRE_NAMES`] roster carries, and the
14886        // roster's length must byte-equal `RestartPolicy::ALL.len()` so
14887        // a silent skew between the [`RestartPolicy::as_str`] match's
14888        // arm-set and the roster's arm-set trips here at caixa-core
14889        // test time rather than at a downstream M4
14890        // `mesh.pleme.io/v1alpha1/Supervisor` CR admission-webhook
14891        // rejection body's wire-form `:restart` accepted-set
14892        // enumeration miss / a `feira supervisor --restart …` "did you
14893        // mean" hint drift / a future wasm-operator per-reconcile-step
14894        // diagnostic log line's accepted-wire-form enumeration miss.
14895        // A future arm addition (an OTP-`intrinsic` fourth arm the
14896        // theory
14897        // [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
14898        // might reach for once the three canonical OTP restart policies
14899        // stop covering the substrate's discovered load-shape) extends
14900        // [`RestartPolicy::ALL`] as a single edit and this pin sweeps
14901        // the new arm by iteration; the paired
14902        // [`RestartPolicy::WIRE_NAMES`] roster must grow in lockstep or
14903        // this assertion trips. Every entry is further pinned to open
14904        // with an ASCII uppercase byte so a silent collapse of the
14905        // wire-form axis with the peer kebab-case dispatcher-catalog
14906        // axis (an entry byte-identical to a sibling
14907        // [`RestartPolicy::discriminant`] kebab byte-string that would
14908        // let a wire-axis consumer accept the dispatcher-catalog
14909        // vocabulary) trips here rather than at a downstream K8s-CR
14910        // round-trip miss.
14911        //
14912        // Peer of the sibling
14913        // [`restart_strategy_wire_names_covers_every_arm`] (3033f45)
14914        // pin on the first M2 OTP-shape sibling-restart closed-set
14915        // typed enum, the sibling
14916        // [`crate::aplicacao::tests::placement_strategy_wire_names_covers_every_arm`]
14917        // (3e5b194) pin on the first M3 mesh-shape distribution-strategy
14918        // closed-set typed enum, the sibling
14919        // [`crate::kind::tests::caixa_kind_wire_names_covers_every_arm`]
14920        // (bd708bd) pin on the top-level typed-kind discriminator's
14921        // `PascalCase` wire byte-string axis, and the sibling
14922        // [`crate::upgrade::tests::upgrade_instruction_wire_forms_covers_every_arm`]
14923        // (cc42c0e) /
14924        // [`crate::upgrade::tests::upgrade_instruction_lisp_forms_covers_every_arm`]
14925        // (1898d77) pins on the OTP-appup discriminator's two-axis
14926        // roster split — the same closed-set exhaustive-roster coverage
14927        // discipline extended here onto the second and final M2
14928        // OTP-shape sibling-enum on the caixa surface, closing the
14929        // per-child restart-decision-policy axis paired with the peer
14930        // per-supervisor sibling-restart-strategy axis on the same M2
14931        // `:supervisor` slot.
14932        //
14933        // Fail-before-pass-after locally verified by mutating one arm
14934        // of the paired [`crate::render::SUPERVISOR_CHILD_RESTART_*`]
14935        // const family (e.g. dropping the trailing `t` from
14936        // `"Permanent"` → `"Permanen"`) — the length pin still passes
14937        // but the `contains` check fires on the mutated arm; and by
14938        // shortening the roster to two entries — the length pin fires
14939        // first.
14940        assert_eq!(
14941            RestartPolicy::WIRE_NAMES.len(),
14942            RestartPolicy::ALL.len(),
14943            "RestartPolicy::WIRE_NAMES.len() must byte-equal \
14944             RestartPolicy::ALL.len() — a mismatch means the roster \
14945             and the enum's arm-set have drifted; downstream consumers \
14946             that fan through both will silently disagree on the \
14947             accepted arm-set"
14948        );
14949        for &variant in RestartPolicy::ALL {
14950            let wire = variant.as_str();
14951            assert!(
14952                RestartPolicy::WIRE_NAMES.contains(&wire),
14953                "RestartPolicy::{variant:?}.as_str() = {wire:?} must \
14954                 be a member of RestartPolicy::WIRE_NAMES — the \
14955                 emitter and the roster have drifted out of lockstep"
14956            );
14957        }
14958        for tag in RestartPolicy::WIRE_NAMES {
14959            let first = tag.chars().next().unwrap_or_else(|| {
14960                panic!(
14961                    "RestartPolicy::WIRE_NAMES entry {tag:?} must be \
14962                     a non-empty PascalCase byte-string"
14963                )
14964            });
14965            assert!(
14966                first.is_ascii_uppercase(),
14967                "RestartPolicy::WIRE_NAMES entry {tag:?} must open \
14968                 with an ASCII uppercase byte (PascalCase wire form) — \
14969                 a lowercase entry would collide the wire-form axis \
14970                 with the peer kebab-case dispatcher-catalog axis \
14971                 [`RestartPolicy::discriminant`] serves"
14972            );
14973        }
14974    }
14975
14976    #[test]
14977    fn restart_policy_from_wire_accepts_every_lifted_constant() {
14978        // Fail-before-pass-after pin on the forward accept-set of the
14979        // [`RestartPolicy::from_wire`] reverse projection: every
14980        // canonical [`crate::render::SUPERVISOR_CHILD_RESTART_*`]
14981        // constant the [`RestartPolicy::as_str`] emitter walks parses
14982        // back to its paired variant. Any future arm addition that
14983        // grows the emitter's `as_str` match but forgets to grow the
14984        // parser's `from_wire` match silently splits the two halves of
14985        // the round-trip — the wire byte-string one non-serde consumer
14986        // parses from the one the emitter wrote — with the failure
14987        // surfacing at the operator's reconcile posture (a `:temporary`
14988        // `oneShot` child restarted on clean exit, a `:transient` child
14989        // restarted after clean completion) far from the rebrand
14990        // commit. Pinning the three-arm accept-set here catches the
14991        // drift at caixa-core build time.
14992        //
14993        // Peer of the sibling [`RestartStrategy::from_wire`] (4eec29c)
14994        // + [`crate::CaixaKind::from_wire`] (2aa6d23)
14995        // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
14996        // accept-set pins on the peer closed-set typed-enum `str → Self`
14997        // axes.
14998        for (wire, expected) in [
14999            (
15000                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
15001                RestartPolicy::Permanent,
15002            ),
15003            (
15004                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
15005                RestartPolicy::Temporary,
15006            ),
15007            (
15008                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
15009                RestartPolicy::Transient,
15010            ),
15011        ] {
15012            let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
15013                panic!(
15014                    "RestartPolicy::from_wire({wire:?}) must accept every \
15015                     SUPERVISOR_CHILD_RESTART_* constant — got None for the \
15016                     lifted canonical byte-string that RestartPolicy::{expected:?} \
15017                     serializes as under SUPERVISOR_CHILD_KEY_RESTART"
15018                )
15019            });
15020            assert_eq!(
15021                parsed, expected,
15022                "RestartPolicy::from_wire({wire:?}) must return \
15023                 RestartPolicy::{expected:?}; got RestartPolicy::{parsed:?}"
15024            );
15025        }
15026    }
15027
15028    #[test]
15029    fn restart_policy_from_wire_round_trips_through_as_str() {
15030        // Fail-before-pass-after pin on the closed round-trip between
15031        // the forward [`RestartPolicy::as_str`] emitter and the
15032        // reverse [`RestartPolicy::from_wire`] parser: for every
15033        // variant in [`RestartPolicy::ALL`], parsing the emitter's
15034        // output must return exactly the same variant. Any per-arm
15035        // divergence — a future arm added to `as_str` but not
15036        // `from_wire`, an accidental copy-paste flip in one but not
15037        // the other — silently splits the emit and parse halves and
15038        // the failure surfaces at consumer parse time far from the
15039        // drift site. The `ALL`-iterating shape means a future arm
15040        // addition picks up the coverage by construction.
15041        //
15042        // Peer of the sibling
15043        // [`restart_strategy_from_wire_round_trips_through_as_str`]
15044        // (4eec29c) round-trip pin on
15045        // [`RestartStrategy::from_wire`] and the M3
15046        // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
15047        // (18c7342) round-trip pin on
15048        // [`crate::aplicacao::PlacementStrategy::from_wire`].
15049        for &variant in RestartPolicy::ALL {
15050            let wire = variant.as_str();
15051            let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
15052                panic!(
15053                    "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
15054                     must be Some({variant:?}) — the two halves of the round-trip \
15055                     dispatch on the same lifted SUPERVISOR_CHILD_RESTART_* consts; \
15056                     got None on wire byte-string {wire:?}"
15057                )
15058            });
15059            assert_eq!(
15060                parsed, variant,
15061                "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
15062                 must round-trip to the same variant; got {parsed:?}"
15063            );
15064        }
15065    }
15066
15067    #[test]
15068    fn restart_policy_from_wire_rejects_unknown_byte_strings() {
15069        // Fail-before-pass-after pin on the closed-set refusal
15070        // discipline of [`RestartPolicy::from_wire`]: every
15071        // byte-string outside the three-arm accept-set returns `None`
15072        // rather than silently collapsing onto the [`Default`]
15073        // (`Permanent`) arm or an arbitrary neighbor. The refusal set
15074        // exercised here sweeps the load-bearing drift shapes: the
15075        // empty string (a stripped serde-attribute drift), all-
15076        // whitespace strings (the canonical text-editor accidental
15077        // padding shape), the kebab-case dispatcher-catalog identities
15078        // (`"permanent"` / `"temporary"` / `"transient"` — the
15079        // [`gen_platform::FromStrKind`]-derived [`std::str::FromStr`]
15080        // accept-set, which parses the *other* axis of this enum's
15081        // two-axis split and must not leak into the `from_wire`
15082        // PascalCase-wire accept-set — a lowercase leak here would
15083        // silently accept the operator's kebab-case
15084        // dispatcher-catalog probe under the wire-axis parser and mis-
15085        // route a `:permanent` intent), the padded canonical scalar
15086        // (`" Permanent "`), the trailing-newline shapes
15087        // (`"Permanent\n"`), the uppercase-single-word forms
15088        // (`"PERMANENT"`), and neighboring-but-unknown arms
15089        // (`"Restart"` — the canonical typo direction toward the
15090        // sibling [`RestartStrategy`] enum's own wire-arm namespace).
15091        //
15092        // Peer of the sibling
15093        // [`restart_strategy_from_wire_rejects_unknown_byte_strings`]
15094        // (4eec29c) +
15095        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
15096        // (2aa6d23) +
15097        // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
15098        // (18c7342) refusal pins on the peer closed-set typed-enum
15099        // axes.
15100        for bad in [
15101            "",
15102            " ",
15103            "\n",
15104            "\t",
15105            "permanent",
15106            "temporary",
15107            "transient",
15108            "PERMANENT",
15109            "TEMPORARY",
15110            "TRANSIENT",
15111            "Permanents",
15112            "Permanent ",
15113            " Permanent",
15114            " Transient ",
15115            "Permanent\n",
15116            "perma",
15117            "Trans",
15118            "OneForOne",
15119            "Restart",
15120            "?",
15121        ] {
15122            assert!(
15123                RestartPolicy::from_wire(bad).is_none(),
15124                "RestartPolicy::from_wire({bad:?}) must return None — the \
15125                 parser's accept-set is exactly the three RestartPolicy::as_str \
15126                 outputs (Permanent, Temporary, Transient), and this \
15127                 byte-string is outside that closed set"
15128            );
15129        }
15130    }
15131
15132    #[test]
15133    fn restart_policy_from_wire_matches_serialize_derive_wire_byte_string() {
15134        // Fail-before-pass-after pin on the fourth path of the four-path
15135        // convergence: `from_wire` (the reverse projection) inverts the
15136        // `Serialize` derive's wire byte-string on every variant.
15137        // Together with the pre-existing three-path convergence
15138        // (`Display` + `as_str` + `Serialize` all resolve to the same
15139        // lifted [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const,
15140        // pinned by
15141        // [`restart_policy_display_matches_serialized_wire_byte_string`])
15142        // this closes the round-trip: the wire byte-string the
15143        // `Serialize` derive emits parses back to the same variant
15144        // through `from_wire`, so any future serde-attribute or variant-
15145        // rename drift on the emit half now surfaces as a matched drift
15146        // on the parse half at caixa-core build time — the two halves
15147        // migrate as a unit through the lifted consts on any future
15148        // rename, and the round-trip cannot silently split.
15149        //
15150        // Peer of the sibling
15151        // [`restart_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
15152        // (4eec29c) wire-format pin on
15153        // [`RestartStrategy::from_wire`] and the M3
15154        // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
15155        // (18c7342) wire-format pin on
15156        // [`crate::aplicacao::PlacementStrategy::from_wire`].
15157        for &variant in RestartPolicy::ALL {
15158            let wire = serde_json::to_string(&variant).unwrap();
15159            let unquoted = wire
15160                .strip_prefix('"')
15161                .and_then(|s| s.strip_suffix('"'))
15162                .expect("serialized RestartPolicy is a JSON string");
15163            let parsed = RestartPolicy::from_wire(unquoted).unwrap_or_else(|| {
15164                panic!(
15165                    "RestartPolicy::from_wire({unquoted:?}) must accept the \
15166                     Serialize derive's wire byte-string for \
15167                     RestartPolicy::{variant:?} — the four-path convergence \
15168                     (Display + as_str + Serialize + from_wire) resolves through \
15169                     the same lifted SUPERVISOR_CHILD_RESTART_* const; got None"
15170                )
15171            });
15172            assert_eq!(
15173                parsed, variant,
15174                "RestartPolicy::from_wire of the Serialize derive's wire \
15175                 byte-string for RestartPolicy::{variant:?} must round-trip \
15176                 to the same variant; got {parsed:?}"
15177            );
15178        }
15179    }
15180
15181    // ── drift-detection: ChildSpec::nome accessor pins ────────────────────
15182    //
15183    // The M2 supervisor-tree sibling of the M3 `Membro::nome` (4a32abf) pin
15184    // pair (`membro_nome_returns_caixa_byte_equal_across_permutations` +
15185    // `membro_nome_borrows_from_caixa_storage`) — extended here to the M2
15186    // per-`:children` child-caixa `:nome` axis, sibling to the first M2
15187    // slot scalar accessor `UpgradeFromEntry::prior_versao` (75d27a8) on
15188    // the peer per-`:upgrade-from :from` axis. The three pins jointly
15189    // brace the accessor against every future silent detour that would
15190    // desynchronize it from the raw `.caixa` field access every consumer
15191    // previously open-coded.
15192
15193    #[test]
15194    fn child_spec_nome_returns_caixa_byte_equal_across_permutations() {
15195        // The canonical per-`:children` child-caixa `:nome`-scalar pin:
15196        // [`ChildSpec::nome`] must return the `:children :caixa` field
15197        // byte-for-byte across every DNS-1123-label value the upstream
15198        // [`crate::render::require_valid_dns_1123_label`] gate at
15199        // `SupervisorSpec::validate` admits. Peer of the sibling
15200        // `membro_nome_returns_caixa_byte_equal_across_permutations`
15201        // (4a32abf) pin on the M3 per-`:membros` axis — same "the
15202        // substrate-primitive accessor must byte-equal the raw field
15203        // access verbatim across every author-declared value" discipline
15204        // extended to the M2 supervisor-tree per-`:children` arm. Pins
15205        // against a future silent detour that re-normalized the child
15206        // identity (an accidental `.to_lowercase()` — every `:children
15207        // :caixa` is validated as a DNS-1123 label upstream, so any
15208        // re-normalization is redundant + a drift surface between the
15209        // validator and the accessor), a namespace-prefix rewrite (an
15210        // accidental `format!("{namespace}/{caixa}")` per-CR
15211        // fully-qualified rewrite that didn't land on the peer axes), or
15212        // a per-cluster alias stamp the future wasm-operator's
15213        // hierarchical reconciliation scheduler authors on one consumer
15214        // without the others. Five values sweep the accept-set the
15215        // DNS-1123 gate upstream admits (short single-word / dashed /
15216        // v-suffixed / mixed-digit child names).
15217        for name in [
15218            "worker",
15219            "cache-server",
15220            "scratch-job",
15221            "orders-v2",
15222            "session-8080",
15223        ] {
15224            let c = ChildSpec {
15225                caixa: name.into(),
15226                versao: "^0.1".into(),
15227                restart: RestartPolicy::Permanent,
15228            };
15229            assert_eq!(
15230                c.nome(),
15231                name,
15232                "ChildSpec::nome must return :children :caixa verbatim \
15233                 (got {:?}, expected {name:?})",
15234                c.nome(),
15235            );
15236            assert_eq!(
15237                c.nome(),
15238                c.caixa.as_str(),
15239                "ChildSpec::nome must byte-equal the .caixa field access",
15240            );
15241        }
15242    }
15243
15244    #[test]
15245    fn child_spec_nome_borrows_from_caixa_storage() {
15246        // The borrow-not-copy pin: [`ChildSpec::nome`] must return a
15247        // `&str` slice that borrows from the typed slot's own [`String`]
15248        // storage — same-address invariant with `c.caixa.as_str()`. Pins
15249        // against a future silent detour that allocated a fresh `String`
15250        // (`self.caixa.clone()` in the body would type-check but silently
15251        // drop the borrow, and every downstream consumer that assumed
15252        // the returned slice outlives `&self` would break on a stale-
15253        // reference use-after-free — the [`crate::render::insert_first_seen`]
15254        // dedup key at [`SupervisorSpec::validate`], the
15255        // [`validate_no_self_supervision`] equality check against the
15256        // parent's `:nome` string slice, the DNS-1123 gate's `&str`
15257        // borrow — each would silently misbehave if this accessor
15258        // produced a detached copy). Peer of the sibling
15259        // `membro_nome_borrows_from_caixa_storage` (4a32abf) pin on the
15260        // M3 per-`:membros` axis and the
15261        // `prior_versao_borrows_from_from_storage` (75d27a8) pin on the
15262        // first M2 slot scalar accessor.
15263        let c = ChildSpec {
15264            caixa: "worker".into(),
15265            versao: "^0.1".into(),
15266            restart: RestartPolicy::Permanent,
15267        };
15268        let name = c.nome();
15269        let caixa_slice = c.caixa.as_str();
15270        assert_eq!(
15271            name.as_ptr(),
15272            caixa_slice.as_ptr(),
15273            "ChildSpec::nome must borrow from the .caixa String's backing \
15274             storage — a fresh allocation here means the accessor no \
15275             longer names the substrate-primitive typed dispatch and \
15276             every downstream consumer would silently carry a detached \
15277             copy",
15278        );
15279        assert_eq!(
15280            name.len(),
15281            caixa_slice.len(),
15282            "ChildSpec::nome and .caixa.as_str() must byte-equal in length \
15283             as well as in address",
15284        );
15285    }
15286
15287    #[test]
15288    fn validate_gates_child_nome_through_lifted_accessor() {
15289        // Bilateral coherence pin: every `:children :caixa` that
15290        // [`SupervisorSpec::validate`] accepts is one
15291        // [`crate::render::require_valid_dns_1123_label`] accepts on the
15292        // accessor-projected value, and vice versa on the reject side.
15293        // This closes the "the validator reads through the accessor"
15294        // contract structurally — a future silent detour that made the
15295        // accessor return a different byte-string than the validator
15296        // gates against would surface here as a coverage mismatch, not
15297        // as an apply-time DNS-1123 rejection at
15298        // `metadata.name: Invalid value` far from the caixa.lisp source.
15299        // Peer of the M2 sibling
15300        // `validate_parses_prior_versao_through_lifted_accessor`
15301        // (75d27a8) on the per-`:upgrade-from :from` axis and the M3
15302        // `validate_membros` peer discipline.
15303        //
15304        // Accept-set sweep: five DNS-1123-label values the upstream gate
15305        // admits.
15306        for ok_name in ["a", "worker", "cache-server", "orders-v2", "svc-8080"] {
15307            let s = SupervisorSpec {
15308                children: vec![ChildSpec {
15309                    caixa: ok_name.into(),
15310                    versao: "^0.1".into(),
15311                    restart: RestartPolicy::Permanent,
15312                }],
15313                ..SupervisorSpec::default()
15314            };
15315            s.validate().unwrap_or_else(|e| {
15316                panic!(
15317                    "SupervisorSpec::validate must accept :children :caixa {ok_name:?} \
15318                     (upstream DNS-1123 gate accepts it): got {e:?}",
15319                );
15320            });
15321            let c = ChildSpec {
15322                caixa: ok_name.into(),
15323                versao: "^0.1".into(),
15324                restart: RestartPolicy::Permanent,
15325            };
15326            crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| ())
15327                .unwrap_or_else(|()| {
15328                    panic!(
15329                        "require_valid_dns_1123_label must accept the accessor-projected \
15330                     :children :caixa {ok_name:?}",
15331                    );
15332                });
15333        }
15334        // Reject-set sweep: five DNS-1123-label-violating shapes the
15335        // upstream gate refuses (empty / uppercase / underscore / dot /
15336        // leading-hyphen). Every rejection at the validator must
15337        // correspond to a rejection when the accessor's projected value
15338        // is fed back through the shared gate.
15339        for bad_name in ["", "Worker", "my_worker", "team.worker", "-worker"] {
15340            let s = SupervisorSpec {
15341                children: vec![ChildSpec {
15342                    caixa: bad_name.into(),
15343                    versao: "^0.1".into(),
15344                    restart: RestartPolicy::Permanent,
15345                }],
15346                ..SupervisorSpec::default()
15347            };
15348            let err = s.validate().unwrap_err();
15349            assert!(
15350                matches!(
15351                    err,
15352                    SupervisorError::EmptyChildName | SupervisorError::ChildCaixaInvalid { .. }
15353                ),
15354                "SupervisorSpec::validate must reject :children :caixa {bad_name:?} \
15355                 via the DNS-1123 gate: got {err:?}",
15356            );
15357            let c = ChildSpec {
15358                caixa: bad_name.into(),
15359                versao: "^0.1".into(),
15360                restart: RestartPolicy::Permanent,
15361            };
15362            assert!(
15363                crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| (),)
15364                    .is_err(),
15365                "require_valid_dns_1123_label must reject the accessor-projected \
15366                 :children :caixa {bad_name:?}",
15367            );
15368        }
15369    }
15370
15371    // ── drift-detection: ChildSpec::versao_requirement accessor pins ──────
15372    //
15373    // Sibling of the peer per-`:membros` `membro_versao_requirement_*`
15374    // (a40b0e3) pin pair on the M3 mesh-slot surface — extended here to the
15375    // M2 supervisor-tree per-`:children` child-`:versao` axis, sibling to
15376    // the just-landed [`ChildSpec::nome`] (57c61d0) child-`:nome` pin
15377    // trio on the peer per-`:children` `String`-carry axis. The three pins
15378    // jointly brace the accessor against every future silent detour that
15379    // would desynchronize it from the raw `.versao` field access the
15380    // requirement gate + error carrier previously open-coded.
15381    //
15382    // Closes the last unlifted per-`:children` `String`-carry axis: the
15383    // pair (`nome`, `versao_requirement`) now jointly projects the
15384    // (`.caixa`, `.versao`) field pair every OTP-shape supervisor-tree
15385    // consumer that fans on per-child identity + version pin reads,
15386    // matching the peer M3 (`Membro::nome`, `Membro::versao_requirement`)
15387    // pair discipline verbatim.
15388    #[test]
15389    fn child_spec_versao_requirement_returns_versao_byte_equal_across_permutations() {
15390        // The canonical per-`:children` child-`:versao`-scalar pin:
15391        // [`ChildSpec::versao_requirement`] must return the `:children
15392        // :versao` field byte-for-byte across every Cargo-shaped semver
15393        // requirement value the upstream
15394        // [`crate::render::require_valid_versao_requirement`] gate admits.
15395        // Peer of the sibling
15396        // `membro_versao_requirement_returns_versao_byte_equal_across_permutations`
15397        // (a40b0e3) pin on the M3 per-`:membros` axis — same "the
15398        // substrate-primitive accessor must byte-equal the raw field
15399        // access verbatim across every author-declared value" discipline
15400        // extended to the M2 supervisor-tree per-`:children` arm. Pins
15401        // against a future silent detour that re-canonicalized the
15402        // requirement (an accidental `.to_string()` via
15403        // [`crate::version::parse_requirement`] → [`std::fmt::Display`]
15404        // round-trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and
15405        // silently drifted the error carrier's quoted requirement away
15406        // from the source `caixa.lisp`, an accidental whitespace trim on
15407        // `"^ 0.1"` that no consumer ever produced from the field-access
15408        // side, an accidental per-cluster lacre-projected concrete-version
15409        // rewrite that didn't land on the peer requirement-gate call).
15410        // Five values sweep the accept-set the shared
15411        // [`crate::render::require_valid_versao_requirement`] gate admits
15412        // (caret / tilde / exact / wildcard / bare-major).
15413        for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
15414            let c = ChildSpec {
15415                caixa: "worker".into(),
15416                versao: req.into(),
15417                restart: RestartPolicy::Permanent,
15418            };
15419            assert_eq!(
15420                c.versao_requirement(),
15421                req,
15422                "ChildSpec::versao_requirement must return :children :versao \
15423                 verbatim (got {:?}, expected {req:?})",
15424                c.versao_requirement(),
15425            );
15426            assert_eq!(
15427                c.versao_requirement(),
15428                c.versao.as_str(),
15429                "ChildSpec::versao_requirement must byte-equal the .versao \
15430                 field access",
15431            );
15432        }
15433    }
15434
15435    #[test]
15436    fn child_spec_versao_requirement_borrows_from_versao_storage() {
15437        // The borrow-not-copy pin: [`ChildSpec::versao_requirement`] must
15438        // return a `&str` slice that borrows from the typed slot's own
15439        // [`String`] storage — same-address invariant with
15440        // `c.versao.as_str()`. Pins against a future silent detour that
15441        // allocated a fresh `String` (`self.versao.clone()` in the body
15442        // would type-check but silently drop the borrow, and every
15443        // downstream consumer that assumed the returned slice outlives
15444        // `&self` — the [`crate::render::require_valid_versao_requirement`]
15445        // gate's `&str` borrow, the [`SupervisorError::ChildVersaoInvalid`]
15446        // `.to_string()` carrier's byte-length assumption — would silently
15447        // misbehave if this accessor produced a detached copy). Peer of
15448        // the sibling `child_spec_nome_borrows_from_caixa_storage`
15449        // (57c61d0) pin on the per-`:children` `:nome` axis and the M3
15450        // `membro_versao_requirement_borrows_from_versao_storage` (a40b0e3)
15451        // pin on the peer per-`:membros` `:versao` axis.
15452        let c = ChildSpec {
15453            caixa: "worker".into(),
15454            versao: "^0.1".into(),
15455            restart: RestartPolicy::Permanent,
15456        };
15457        let req = c.versao_requirement();
15458        let versao_slice = c.versao.as_str();
15459        assert_eq!(
15460            req.as_ptr(),
15461            versao_slice.as_ptr(),
15462            "ChildSpec::versao_requirement must borrow from the .versao \
15463             String's backing storage — a fresh allocation here means the \
15464             accessor no longer names the substrate-primitive typed \
15465             dispatch and every downstream consumer would silently carry \
15466             a detached copy",
15467        );
15468        assert_eq!(
15469            req.len(),
15470            versao_slice.len(),
15471            "ChildSpec::versao_requirement and .versao.as_str() must \
15472             byte-equal in length as well as in address",
15473        );
15474    }
15475
15476    #[test]
15477    fn validate_gates_child_versao_through_lifted_accessor() {
15478        // Bilateral coherence pin: every `:children :versao` that
15479        // [`SupervisorSpec::validate`] accepts is one
15480        // [`crate::render::require_valid_versao_requirement`] accepts on
15481        // the accessor-projected value, and vice versa on the reject side.
15482        // This closes the "the validator reads through the accessor"
15483        // contract structurally — a future silent detour that made the
15484        // accessor return a different byte-string than the validator gates
15485        // against would surface here as a coverage mismatch, not as a
15486        // resolver-time semver-parse rejection at lacre-closure time far
15487        // from the caixa.lisp source. Peer of the sibling
15488        // `validate_gates_child_nome_through_lifted_accessor` (57c61d0) on
15489        // the per-`:children :caixa` axis and the M2
15490        // `validate_parses_prior_versao_through_lifted_accessor` (75d27a8)
15491        // on the peer per-`:upgrade-from :from` axis.
15492        //
15493        // Accept-set sweep: five Cargo-shaped semver requirement values
15494        // the upstream gate admits (caret / tilde / exact / wildcard /
15495        // bare-major).
15496        for ok_req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
15497            let s = SupervisorSpec {
15498                children: vec![ChildSpec {
15499                    caixa: "worker".into(),
15500                    versao: ok_req.into(),
15501                    restart: RestartPolicy::Permanent,
15502                }],
15503                ..SupervisorSpec::default()
15504            };
15505            s.validate().unwrap_or_else(|e| {
15506                panic!(
15507                    "SupervisorSpec::validate must accept :children :versao {ok_req:?} \
15508                     (upstream versao-requirement gate accepts it): got {e:?}",
15509                );
15510            });
15511            let c = ChildSpec {
15512                caixa: "worker".into(),
15513                versao: ok_req.into(),
15514                restart: RestartPolicy::Permanent,
15515            };
15516            crate::render::require_valid_versao_requirement(
15517                c.versao_requirement(),
15518                || (),
15519                |_reason| (),
15520            )
15521            .unwrap_or_else(|()| {
15522                panic!(
15523                    "require_valid_versao_requirement must accept the accessor-projected \
15524                     :children :versao {ok_req:?}",
15525                );
15526            });
15527        }
15528        // Reject-set sweep: five requirement-violating shapes the upstream
15529        // gate refuses. The empty string closes the empty-first arm of the
15530        // shared [`crate::render::require_valid_versao_requirement`]
15531        // cascade; the four non-empty arms exercise distinct semver-parse
15532        // failure modes the M3 peer per-`:membros` reject-set already pins
15533        // (`rejects_invalid_membro_versao_requirement` on `^bad-version`,
15534        // `rejects_membro_versao_with_double_caret_typo` on `^^0.1`,
15535        // `rejects_membro_versao_with_v_prefixed_tag` on `v0.1`) — the
15536        // shared parser routing means the same reject-set must fail
15537        // identically at the M2 supervisor-tree per-`:children` accessor
15538        // arm here. Every rejection at the validator must correspond to a
15539        // rejection when the accessor's projected value is fed back
15540        // through the shared gate.
15541        //
15542        // (Bare partial magnitudes like `"0.1"` and bare identifiers like
15543        // `"not-a-semver"` are intentionally *not* in the reject-set: the
15544        // semver crate accepts `"0.1"` as an implicit `^0.1` requirement,
15545        // and the identifier-tail arm's grammar admits some non-canonical
15546        // shapes — matching what the M3 peer test suite already documents
15547        // as the shared parser's accept-set edges.)
15548        for bad_req in ["", "v0.1.0", "^bad-version", "^^0.1", "v0.1"] {
15549            let s = SupervisorSpec {
15550                children: vec![ChildSpec {
15551                    caixa: "worker".into(),
15552                    versao: bad_req.into(),
15553                    restart: RestartPolicy::Permanent,
15554                }],
15555                ..SupervisorSpec::default()
15556            };
15557            let err = s.validate().unwrap_err();
15558            assert!(
15559                matches!(
15560                    err,
15561                    SupervisorError::EmptyChildVersion { .. }
15562                        | SupervisorError::ChildVersaoInvalid { .. }
15563                ),
15564                "SupervisorSpec::validate must reject :children :versao {bad_req:?} \
15565                 via the versao-requirement gate: got {err:?}",
15566            );
15567            let c = ChildSpec {
15568                caixa: "worker".into(),
15569                versao: bad_req.into(),
15570                restart: RestartPolicy::Permanent,
15571            };
15572            assert!(
15573                crate::render::require_valid_versao_requirement(
15574                    c.versao_requirement(),
15575                    || (),
15576                    |_reason| (),
15577                )
15578                .is_err(),
15579                "require_valid_versao_requirement must reject the accessor-projected \
15580                 :children :versao {bad_req:?}",
15581            );
15582        }
15583    }
15584
15585    // ── per-`:children` `:restart` typed-accessor coherence pins ──────────
15586    //
15587    // The [`ChildSpec::restart`] accessor lift closes the last unlifted
15588    // per-`:children` axis (the pair `nome()` + `versao_requirement()`
15589    // already project the `String`-carry `(caixa, versao)` fields; the
15590    // `Copy`-composite-enum `restart` field is the third and final axis).
15591    // Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
15592    // (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
15593    // scalar accessor and the M3 mesh-slot [`crate::Placement::estrategia`]
15594    // (921fe1b) `Copy`-return [`crate::PlacementStrategy`] distribution-
15595    // strategy scalar accessor — same "one typed dispatch on the substrate
15596    // primitive, `Copy`-projected closed-set enum-arm discriminator" shape
15597    // extended onto the M2 supervisor-slot per-`:children` restart-decision
15598    // axis. The pin below covers the accessor's byte-equal projection
15599    // against the raw field access across every variant in the closed
15600    // accept-set (`Permanent`, `Transient`, `Temporary`).
15601
15602    #[test]
15603    fn child_spec_restart_returns_restart_verbatim_across_permutations() {
15604        // The canonical per-`:children` restart-decision-policy-scalar
15605        // pin: [`ChildSpec::restart`] must return the `:children :restart`
15606        // field verbatim as a [`RestartPolicy`], `Copy`-projected from the
15607        // typed slot's own [`RestartPolicy`] storage across every variant
15608        // in the closed accept-set (`Permanent`, `Transient`, `Temporary`).
15609        // Pins against a future silent detour that re-derived the policy
15610        // from a peer axis (an accidental fallback to
15611        // `if is_supervisor_child { Permanent } else { Temporary }` that
15612        // collapsed the child's kind axis into the restart discriminator),
15613        // a variant remap the operator authors on one consumer without the
15614        // other, or a stale-derive detour that substituted
15615        // [`RestartPolicy::default`] when the field held any explicit
15616        // variant (which would silently collapse the distinction between
15617        // "author explicitly declared `:restart Permanent`" and "author
15618        // omitted the slot and inherited the default" the future
15619        // per-cluster restart-decision override slot depends on).
15620        //
15621        // Peer of the sibling per-`:supervisor`
15622        // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
15623        // (eafb619) pin on the M2 supervisor-slot sibling-restart-strategy
15624        // axis and the M3
15625        // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
15626        // (921fe1b) pin on the per-`:placement` distribution-strategy axis
15627        // — same "the substrate-primitive accessor must byte-equal the raw
15628        // field access verbatim across every author-declared value"
15629        // discipline extended onto the M2 supervisor-slot per-`:children`
15630        // restart-decision-policy axis, closing the last unlifted axis on
15631        // the per-`:children` [`ChildSpec`] type.
15632        for restart in [
15633            RestartPolicy::Permanent,
15634            RestartPolicy::Transient,
15635            RestartPolicy::Temporary,
15636        ] {
15637            let c = ChildSpec {
15638                caixa: "worker".into(),
15639                versao: "^0.1".into(),
15640                restart,
15641            };
15642            assert_eq!(
15643                c.restart(),
15644                restart,
15645                "ChildSpec::restart must return :children :restart \
15646                 verbatim (got {:?}, expected {restart:?})",
15647                c.restart(),
15648            );
15649            assert_eq!(
15650                c.restart(),
15651                c.restart,
15652                "ChildSpec::restart accessor and .restart field access \
15653                 must byte-equal — the accessor is the substrate-primitive \
15654                 typed dispatch every downstream per-child restart-\
15655                 decision consumer must route through",
15656            );
15657        }
15658    }
15659
15660    // ── per-`:supervisor` `:estrategia` typed-accessor coherence pins ─────
15661    //
15662    // The [`SupervisorSpec::estrategia`] accessor lift extends the peer M3
15663    // [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
15664    // distribution-strategy accessor discipline onto the M2 supervisor-slot
15665    // per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
15666    // scalar axis. The two pins below cover (1) the accessor's byte-equal
15667    // projection against the raw field access across every variant in the
15668    // closed accept-set, and (2) the two-consumer coherence between the
15669    // [`SupervisorSpec::validate`] partition-dispatch `match` arm and the
15670    // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
15671    // carrier's `estrategia:` field — peer of the sibling M3
15672    // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
15673    // / `validate_placement_reads_through_lifted_estrategia_accessor` pin
15674    // pair on the per-`:placement` distribution-strategy axis.
15675
15676    #[test]
15677    fn supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations() {
15678        // The canonical per-`:supervisor` sibling-restart-strategy-scalar
15679        // pin: [`SupervisorSpec::estrategia`] must return the
15680        // `:supervisor :estrategia` field verbatim as a
15681        // [`RestartStrategy`], `Copy`-projected from the typed slot's own
15682        // [`RestartStrategy`] storage across every variant in the closed
15683        // accept-set (`OneForOne`, `OneForAll`, `RestForOne`,
15684        // `SimpleOneForOne`). Pins against a future silent detour that
15685        // re-derived the strategy from a peer axis (an accidental
15686        // fallback to `if children.is_empty() { SimpleOneForOne } else {
15687        // OneForOne }` collapse that read the children-count axis into
15688        // the strategy discriminator), a variant remap the operator
15689        // authors on one consumer without the other, or a stale-derive
15690        // detour that substituted [`RestartStrategy::default`] when the
15691        // field held any explicit variant (which would silently collapse
15692        // the distinction between "author explicitly declared
15693        // `:estrategia OneForOne`" and "author omitted the slot and
15694        // inherited the default" the future per-cluster strategy override
15695        // slot depends on). Peer of the sibling M3
15696        // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
15697        // (921fe1b) pin on the M3 mesh-slot `Copy`-composite-enum scalar
15698        // axis — same "the substrate-primitive accessor must byte-equal
15699        // the raw field access verbatim across every author-declared
15700        // value" discipline extended onto the M2 supervisor-slot
15701        // per-`:supervisor` sibling-restart-strategy axis.
15702        for &estrategia in RestartStrategy::ALL {
15703            // `SimpleOneForOne` requires `children.is_empty()`; the peer
15704            // three strategies require a non-empty static children list.
15705            // Build each shape coherently so the pin's fixture would
15706            // itself pass [`SupervisorSpec::validate`] once fed through
15707            // the sibling coherence pin below — the byte-equal projection
15708            // asserted here is a strictly weaker property (a `Copy` field
15709            // read) that does not depend on `validate` running, but
15710            // keeping the fixture validate-clean means a future extension
15711            // of the pin to exercise `validate` end-to-end does not have
15712            // to re-author the children shape.
15713            //
15714            // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
15715            // shape partition through the [`gen_platform::IsVariant`]
15716            // derive-generated
15717            // [`RestartStrategy::is_simple_one_for_one`] predicate rather
15718            // than the raw `matches!(estrategia, RestartStrategy::
15719            // SimpleOneForOne)` open-coded pattern-match — same closed-
15720            // set-typed-enum arm-discriminator dispatch discipline the
15721            // sibling [`crate::upgrade::UpgradeInstruction::is_restart`]
15722            // convergence (915a934) extended onto its two paired positive
15723            // / negated `matches!` sites and the peer
15724            // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
15725            // predicate convergence (766ec63) extended onto the M3 mesh-
15726            // slot per-`:placement` distribution-strategy discriminator
15727            // axis. See the sibling `round_trip_all_strategies` and the
15728            // peer `manifest::tests::
15729            // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
15730            // fixture for the two peer sites the same lift closes on.
15731            let children = if estrategia.is_simple_one_for_one() {
15732                Vec::new()
15733            } else {
15734                vec![ChildSpec {
15735                    caixa: "worker".into(),
15736                    versao: "^0.1".into(),
15737                    restart: RestartPolicy::Permanent,
15738                }]
15739            };
15740            let s = SupervisorSpec {
15741                estrategia,
15742                children,
15743                ..SupervisorSpec::default()
15744            };
15745            assert_eq!(
15746                s.estrategia(),
15747                estrategia,
15748                "SupervisorSpec::estrategia must return :supervisor :estrategia \
15749                 verbatim (got {:?}, expected {estrategia:?})",
15750                s.estrategia(),
15751            );
15752            assert_eq!(
15753                s.estrategia(),
15754                s.estrategia,
15755                "SupervisorSpec::estrategia accessor and .estrategia field \
15756                 access must byte-equal — the accessor is the substrate-\
15757                 primitive typed dispatch every downstream sibling-restart-\
15758                 strategy consumer must route through",
15759            );
15760        }
15761    }
15762
15763    #[test]
15764    fn validate_reads_through_lifted_estrategia_accessor() {
15765        // Two-consumer coherence pin: the [`SupervisorSpec::validate`]
15766        // `SimpleOneForOne ↔ non-SimpleOneForOne` `match` partition
15767        // dispatch (which reads through [`SupervisorSpec::estrategia`]
15768        // to fan across the strategy-arm shape-gate cascades) and the
15769        // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
15770        // error carrier's `estrategia:` field (which reads through
15771        // [`SupervisorSpec::estrategia`] to name the strategy the empty
15772        // `:children` list was declared against) must both key off the
15773        // lifted accessor, so any future rebrand on the typed slot's
15774        // reader shape lands at exactly one place. Pins the two-site
15775        // coherence by exercising the `NoChildren` error surface end-to-
15776        // end across every non-`SimpleOneForOne` variant and asserting
15777        // the surfaced `estrategia:` field byte-equals the accessor's
15778        // return. Peer of the sibling M3
15779        // `validate_placement_reads_through_lifted_estrategia_accessor`
15780        // (921fe1b) three-consumer coherence pin on the per-`:placement`
15781        // distribution-strategy axis.
15782        for estrategia in [
15783            RestartStrategy::OneForOne,
15784            RestartStrategy::OneForAll,
15785            RestartStrategy::RestForOne,
15786        ] {
15787            let s = SupervisorSpec {
15788                estrategia,
15789                children: Vec::new(),
15790                ..SupervisorSpec::default()
15791            };
15792            let err = s.validate().unwrap_err();
15793            match err {
15794                SupervisorError::NoChildren { estrategia: e } => {
15795                    assert_eq!(
15796                        e,
15797                        s.estrategia(),
15798                        "NoChildren.estrategia must byte-equal \
15799                         SupervisorSpec::estrategia() — the empty-`:children` \
15800                         refusal reads through the lifted accessor",
15801                    );
15802                    assert_eq!(
15803                        e, estrategia,
15804                        "NoChildren.estrategia must carry the author-declared \
15805                         :supervisor :estrategia variant verbatim (got {e:?}, \
15806                         expected {estrategia:?})",
15807                    );
15808                }
15809                other => panic!("expected NoChildren, got {other:?} for estrategia={estrategia:?}"),
15810            }
15811        }
15812    }
15813
15814    // ── per-`:supervisor` `:max-restarts` typed-accessor coherence pins ────
15815    //
15816    // The [`SupervisorSpec::max_restarts`] accessor lift extends the peer M3
15817    // [`crate::CircuitBreaker::max_failures`] (3a74062) `Copy`-return
15818    // required-`u32` scalar accessor discipline onto the M2 supervisor-slot
15819    // per-`:supervisor` restart-budget-count `Copy`-`u32` scalar axis.
15820    // The two pins below cover (1) the accessor's byte-equal projection
15821    // against the raw field access across every representative value in
15822    // the `u32` accept-set (`1` lower boundary, `SUPERVISOR_MAX_RESTARTS_MAX`
15823    // upper boundary, `0` past-the-guard zero sentinel, `u32::MAX`
15824    // past-the-guard cap sentinel), and (2) the [`SupervisorSpec::validate`]
15825    // zero-floor / cap composition — the validate gate and the accessor
15826    // must route through the same substrate-primitive typed dispatch, so
15827    // any future silent detour that had the accessor perform a
15828    // bounds-collapsing clamp would fail here at caixa-core build time.
15829    // Peer of the sibling M3
15830    // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
15831    // (3a74062) pin on the per-`CircuitBreaker :max-failures` axis.
15832
15833    #[test]
15834    fn supervisor_spec_max_restarts_returns_max_restarts_u32_byte_equal_across_permutations() {
15835        // The canonical per-`:supervisor` restart-budget-count scalar pin:
15836        // [`SupervisorSpec::max_restarts`] must return the `:supervisor
15837        // :max-restarts` typed `u32` verbatim, `Copy`-projected from the
15838        // typed slot's own `u32` storage, byte-equal to the raw field
15839        // access across every representative value in the accept-set —
15840        // `1` (the lower boundary of the `1..=SUPERVISOR_MAX_RESTARTS_MAX`
15841        // accept-set the surrounding [`SupervisorSpec::validate`] gate
15842        // carves out on the sibling `ZeroMaxRestarts` refusal),
15843        // `SUPERVISOR_MAX_RESTARTS_MAX` (the upper boundary the same gate
15844        // carves out on the sibling `MaxRestartsExceedsCap` refusal), `0`
15845        // (a past-the-guard sentinel that pins the accessor doesn't
15846        // perform a silent bounds-collapse into `1` on the zero arm —
15847        // validate rejects zero but the accessor must ship the raw slot
15848        // verbatim so a validate-time gate regression surfaces at the
15849        // emit boundary rather than being silently absorbed), `u32::MAX`
15850        // (a past-the-guard sentinel that pins the accessor doesn't
15851        // perform a silent bounds-collapse through
15852        // `SUPERVISOR_MAX_RESTARTS_MAX` at the return path).
15853        //
15854        // Peer of the sibling M3
15855        // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
15856        // (3a74062) pin on the M3 mesh-slot `Copy`-`u32` sub-struct
15857        // required-scalar axis — same "the substrate-primitive accessor
15858        // must byte-equal the raw field access verbatim across every
15859        // value in the `u32` accept-set" discipline extended onto the M2
15860        // supervisor-slot per-`:supervisor` restart-budget-count axis.
15861        for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX, 0, u32::MAX] {
15862            let s = SupervisorSpec {
15863                max_restarts,
15864                ..SupervisorSpec::default()
15865            };
15866            assert_eq!(
15867                s.max_restarts(),
15868                max_restarts,
15869                "SupervisorSpec::max_restarts must return :supervisor \
15870                 :max-restarts verbatim (got {}, expected {max_restarts})",
15871                s.max_restarts(),
15872            );
15873            assert_eq!(
15874                s.max_restarts(),
15875                s.max_restarts,
15876                "SupervisorSpec::max_restarts accessor and .max_restarts \
15877                 field access must byte-equal — the accessor is the \
15878                 substrate-primitive typed dispatch every downstream \
15879                 restart-budget-count consumer must route through",
15880            );
15881        }
15882    }
15883
15884    #[test]
15885    fn validate_max_restarts_zero_floor_and_cap_arms_route_through_accessor() {
15886        // Composition pin: [`SupervisorSpec::validate`]'s `:max-restarts`
15887        // zero-floor + upper-cap bracket must key off
15888        // [`SupervisorSpec::max_restarts`], not the raw `.max_restarts`
15889        // field access. Structurally: a `SupervisorSpec { max_restarts:
15890        // 0, .. }` must surface the `ZeroMaxRestarts` refusal exactly, a
15891        // `SupervisorSpec { max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
15892        // .. }` must surface the `MaxRestartsExceedsCap` refusal exactly
15893        // (with the offending count carried verbatim from the accessor
15894        // return), and a `SupervisorSpec { max_restarts: 1, .. }` (the
15895        // lower boundary of the accept-set) plus a `SupervisorSpec {
15896        // max_restarts: SUPERVISOR_MAX_RESTARTS_MAX, .. }` (the upper
15897        // boundary) must pass validate. The four together jointly pin the
15898        // accessor + validate-gate composition: any future silent detour
15899        // that had the accessor return a fresh `1` on the zero arm (a
15900        // `.max_restarts().max(1)` collapse) would silently absorb the
15901        // `ZeroMaxRestarts` refusal at the accessor boundary and the
15902        // validate gate would accept a struct-literal `SupervisorSpec {
15903        // max_restarts: 0, .. }` — the composition pin catches that at
15904        // caixa-core build time.
15905        //
15906        // Peer of the sibling M3
15907        // `validate_politicas_max_failures_zero_floor_arm_routes_through_accessor`
15908        // (3a74062) pin on the sibling per-`CircuitBreaker :max-failures`
15909        // composition axis — same "the validate / shape-gate predicate
15910        // must route through the substrate-primitive typed dispatch"
15911        // discipline extended onto the peer M2 supervisor-slot
15912        // required-`u32` composition axis.
15913        let child = ChildSpec {
15914            caixa: "worker".into(),
15915            versao: "^0.1".into(),
15916            restart: RestartPolicy::Permanent,
15917        };
15918        // Zero-floor arm.
15919        let s = SupervisorSpec {
15920            max_restarts: 0,
15921            children: vec![child.clone()],
15922            ..SupervisorSpec::default()
15923        };
15924        assert_eq!(
15925            s.validate().unwrap_err(),
15926            SupervisorError::ZeroMaxRestarts,
15927            "validate must reject max_restarts == 0 with ZeroMaxRestarts \
15928             — the accessor and the validate gate must route through the \
15929             same substrate-primitive typed dispatch on the zero-floor arm",
15930        );
15931        // Cap arm — the surfaced `max_restarts:` field must byte-equal
15932        // the accessor's return so a future rebrand on the accessor
15933        // lands in the diagnostic without a coordinated rewrite.
15934        let over_cap = SUPERVISOR_MAX_RESTARTS_MAX + 1;
15935        let s = SupervisorSpec {
15936            max_restarts: over_cap,
15937            children: vec![child.clone()],
15938            ..SupervisorSpec::default()
15939        };
15940        match s.validate().unwrap_err() {
15941            SupervisorError::MaxRestartsExceedsCap { max_restarts } => {
15942                assert_eq!(
15943                    max_restarts,
15944                    s.max_restarts(),
15945                    "MaxRestartsExceedsCap.max_restarts must byte-equal \
15946                     SupervisorSpec::max_restarts() — the cap-arm refusal \
15947                     reads through the lifted accessor",
15948                );
15949                assert_eq!(
15950                    max_restarts, over_cap,
15951                    "MaxRestartsExceedsCap.max_restarts must carry the \
15952                     author-declared :supervisor :max-restarts value \
15953                     verbatim (got {max_restarts}, expected {over_cap})",
15954                );
15955            }
15956            other => panic!("expected MaxRestartsExceedsCap, got {other:?}"),
15957        }
15958        // Lower + upper accept-set boundaries.
15959        for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX] {
15960            let s = SupervisorSpec {
15961                max_restarts,
15962                children: vec![child.clone()],
15963                ..SupervisorSpec::default()
15964            };
15965            assert!(
15966                s.validate().is_ok(),
15967                "validate must accept max_restarts == {max_restarts} \
15968                 (an accept-set boundary of \
15969                 1..=SUPERVISOR_MAX_RESTARTS_MAX)",
15970            );
15971        }
15972    }
15973
15974    // ── per-`:supervisor` `:restart-window` typed-accessor coherence pins ─
15975    //
15976    // The [`SupervisorSpec::restart_window`] accessor lift extends the peer
15977    // M2 [`crate::LimitsSpec::wall_clock`] (8cb717b) `Option<Duration>`
15978    // accessor discipline and the peer M3 [`crate::MeshPolicy::timeout`]
15979    // (7073d0f) `Option<Duration>` accessor discipline onto the M2
15980    // supervisor-slot per-`:supervisor` restart-intensity-denominator
15981    // `Option<Duration>` scalar axis — third `Copy`-return accessor on the
15982    // M2 supervisor-slot `SupervisorSpec` type, closing the last unlifted
15983    // per-`:supervisor` scalar-value axis. The three pins below cover
15984    // (1) the accessor's byte-equal projection against the raw field
15985    // access across every representative value in the `Option<Duration>`
15986    // accept-set (`None` never-reset sentinel, `Some(Duration::from_millis(1))`
15987    // lower boundary, `Some(SUPERVISOR_RESTART_WINDOW_MAX)` upper boundary,
15988    // `Some(Duration::ZERO)` past-the-guard zero sentinel, `Some(Duration::MAX)`
15989    // past-the-guard above-cap sentinel), (2) the [`SupervisorSpec::validate`]
15990    // `if let Some(w) = self.restart_window() { … }` bracket-arm
15991    // composition — the validate gate and the accessor must route through
15992    // the same substrate-primitive typed dispatch, so any future silent
15993    // detour that had the accessor perform a bounds-collapsing clamp
15994    // would fail here at caixa-core build time, and (3) the accessor's
15995    // by-copy idempotence pin — the returned `Option<Duration>` must
15996    // outlive `&self` and two successive calls must return byte-equal
15997    // values. Peer of the sibling M2
15998    // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
15999    // (8cb717b) pin on the per-`:limits :wall-clock` axis and the sibling
16000    // M3 `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
16001    // (7073d0f) pin on the per-`:politicas :timeout` axis.
16002
16003    #[test]
16004    fn supervisor_spec_restart_window_returns_option_duration_byte_equal_across_permutations() {
16005        // The canonical per-`:supervisor` restart-intensity-denominator
16006        // scalar pin: [`SupervisorSpec::restart_window`] must return the
16007        // `:supervisor :restart-window` typed [`Duration`] verbatim as an
16008        // `Option<Duration>`, `Copy`-projected from the typed slot's own
16009        // `Option<Duration>` storage, byte-equal to the raw field access
16010        // across every representative value in the accept-set — `None`
16011        // (the "never reset — every restart across the supervisor's
16012        // lifetime counts against the sibling `:max-restarts` budget"
16013        // sentinel the field's own docstring names and the peer
16014        // `validate_accepts_none_restart_window` pin locks in on the
16015        // [`SupervisorSpec::validate`] entry-side),
16016        // `Some(Duration::from_millis(1))` (the structural minimum a
16017        // validated `:restart-window` may carry, the integer-millisecond
16018        // floor [`SupervisorError::RestartWindowNotCanonical`] rejects
16019        // everything sub-ms; `Duration::ZERO` is separately rejected by
16020        // [`SupervisorError::RestartWindowZero`]),
16021        // `Some(SUPERVISOR_RESTART_WINDOW_MAX)` (the upper boundary the
16022        // surrounding [`SupervisorSpec::validate`] gate carves out on the
16023        // sibling [`SupervisorError::RestartWindowExceedsCap`] refusal),
16024        // `Some(Duration::ZERO)` (a past-the-guard sentinel that pins the
16025        // accessor doesn't perform a silent bounds-collapse into `None` on
16026        // the zero-Duration arm — validate rejects zero but the accessor
16027        // must ship the raw slot verbatim so a validate-time gate
16028        // regression surfaces at the emit boundary rather than being
16029        // silently absorbed), and `Some(Duration::MAX)` (a past-the-guard
16030        // sentinel that pins the accessor doesn't perform a silent
16031        // bounds-collapse through [`SUPERVISOR_RESTART_WINDOW_MAX`] at the
16032        // return path).
16033        //
16034        // Peer of the sibling M2
16035        // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
16036        // (8cb717b) pin on the per-`:limits :wall-clock` axis and the
16037        // sibling M3
16038        // `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
16039        // (7073d0f) pin on the per-`:politicas :timeout` axis — same "the
16040        // substrate-primitive accessor must byte-equal the raw field
16041        // access verbatim across every value in the `Option<Duration>`
16042        // accept-set" discipline extended onto the M2 supervisor-slot
16043        // per-`:supervisor` `Option<Duration>` axis. Pins against a future
16044        // silent detour that re-derived the restart-window from a peer
16045        // axis (an accidental `.max_restarts.into()` collapse that read
16046        // the restart-budget-count as a duration — the two axes serve
16047        // different halves of the `MaxIntensity / Period` restart-
16048        // intensity ratio, and confusing them silently inverts the
16049        // ratio's numerator and denominator), a `None → Some(Duration::ZERO)`
16050        // "zero means never reset" collapse (the canonical
16051        // `Option<Duration>` → `Duration` collapse footgun the
16052        // [`SupervisorError::RestartWindowZero`] validate arm guards on
16053        // the peer zero-floor axis; a zero period either trips on the
16054        // first failure or never trips depending on operator
16055        // interpretation, neither of which is the author's "never reset"
16056        // intent that `None` expresses structurally), or a per-arm
16057        // variant swap that landed on one consumer without the other.
16058        for restart_window in [
16059            None,
16060            Some(Duration::from_millis(1)),
16061            Some(SUPERVISOR_RESTART_WINDOW_MAX),
16062            Some(Duration::ZERO),
16063            Some(Duration::MAX),
16064        ] {
16065            let s = SupervisorSpec {
16066                restart_window,
16067                ..SupervisorSpec::default()
16068            };
16069            assert_eq!(
16070                s.restart_window(),
16071                restart_window,
16072                "SupervisorSpec::restart_window must return :supervisor \
16073                 :restart-window verbatim (got {:?}, expected {restart_window:?})",
16074                s.restart_window(),
16075            );
16076            assert_eq!(
16077                s.restart_window(),
16078                s.restart_window,
16079                "SupervisorSpec::restart_window accessor and \
16080                 .restart_window field access must byte-equal — the \
16081                 accessor is the substrate-primitive typed dispatch every \
16082                 downstream restart-intensity-denominator consumer must \
16083                 route through",
16084            );
16085        }
16086    }
16087
16088    #[test]
16089    fn validate_restart_window_bracket_arm_routes_through_accessor() {
16090        // Composition pin: [`SupervisorSpec::validate`]'s
16091        // `:restart-window` `if let Some(w) = self.restart_window() { … }`
16092        // zero-floor + integer-millisecond canonical-form + upper-cap
16093        // bracket-arm must key off [`SupervisorSpec::restart_window`], not
16094        // the raw `.restart_window` field access. Structurally: a
16095        // `SupervisorSpec { restart_window: None, .. }` must pass the
16096        // arm gate structurally (the `if let Some(_)` shape returns
16097        // early on the `None` arm — the accessor and the validate gate
16098        // must agree on `None → skip the bracket cascade` so an authored
16099        // `:restart-window ()` structurally routes through the "never
16100        // reset" sentinel path), a `SupervisorSpec { restart_window:
16101        // Some(Duration::ZERO), .. }` must surface the `RestartWindowZero`
16102        // refusal exactly, a `SupervisorSpec { restart_window:
16103        // Some(Duration::from_micros(1500)), .. }` must surface the
16104        // `RestartWindowNotCanonical` refusal exactly (with the offending
16105        // duration carried verbatim from the accessor return), a
16106        // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX
16107        // + Duration::from_millis(1)), .. }` must surface the
16108        // `RestartWindowExceedsCap` refusal exactly (with the offending
16109        // duration carried verbatim from the accessor return), and a
16110        // `SupervisorSpec { restart_window: Some(Duration::from_millis(1)),
16111        // .. }` (the lower boundary of the accept-set) plus a
16112        // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
16113        // .. }` (the upper boundary) must pass validate. The six together
16114        // jointly pin the accessor + validate-gate composition: any future
16115        // silent detour that had the accessor return a fresh `None` on any
16116        // `Some` arm (a `.restart_window().filter(|w| !w.is_zero())`
16117        // collapse) would silently absorb the `RestartWindowZero` refusal
16118        // at the accessor boundary and the validate gate would accept a
16119        // struct-literal `SupervisorSpec { restart_window:
16120        // Some(Duration::ZERO), .. }` — the composition pin catches that
16121        // at caixa-core build time.
16122        //
16123        // Peer of the sibling M2 [`crate::LimitsSpec::wall_clock`]
16124        // (8cb717b) validate-arm-route pin on the per-`:limits :wall-clock`
16125        // axis and the peer M3 [`crate::MeshPolicy::timeout`] (7073d0f)
16126        // accessor-composition pin on the per-`:politicas :timeout` axis —
16127        // same "the validate / shape-gate predicate must route through
16128        // the substrate-primitive typed dispatch" discipline extended
16129        // onto the peer M2 supervisor-slot optional-`Duration` axis.
16130        let child = ChildSpec {
16131            caixa: "worker".into(),
16132            versao: "^0.1".into(),
16133            restart: RestartPolicy::Permanent,
16134        };
16135        // None arm — must not surface any :restart-window-shaped refusal;
16136        // the `if let Some(_)` bracket returns early on `None` structurally.
16137        let s = SupervisorSpec {
16138            restart_window: None,
16139            children: vec![child.clone()],
16140            ..SupervisorSpec::default()
16141        };
16142        assert!(
16143            s.validate().is_ok(),
16144            "validate must accept restart_window: None (the never-reset \
16145             sentinel) — the `if let Some(_)` bracket returns early on \
16146             the None arm and the accessor must agree",
16147        );
16148        // Zero-floor arm.
16149        let s = SupervisorSpec {
16150            restart_window: Some(Duration::ZERO),
16151            children: vec![child.clone()],
16152            ..SupervisorSpec::default()
16153        };
16154        assert_eq!(
16155            s.validate().unwrap_err(),
16156            SupervisorError::RestartWindowZero,
16157            "validate must reject restart_window == Some(Duration::ZERO) \
16158             with RestartWindowZero — the accessor and the validate gate \
16159             must route through the same substrate-primitive typed \
16160             dispatch on the zero-floor arm",
16161        );
16162        // Non-canonical (sub-ms) arm — the surfaced `window:` field must
16163        // byte-equal the accessor's return so a future rebrand on the
16164        // accessor lands in the diagnostic without a coordinated rewrite.
16165        let sub_ms = Duration::from_micros(1500);
16166        let s = SupervisorSpec {
16167            restart_window: Some(sub_ms),
16168            children: vec![child.clone()],
16169            ..SupervisorSpec::default()
16170        };
16171        match s.validate().unwrap_err() {
16172            SupervisorError::RestartWindowNotCanonical { window } => {
16173                assert_eq!(
16174                    Some(window),
16175                    s.restart_window(),
16176                    "RestartWindowNotCanonical.window must byte-equal \
16177                     SupervisorSpec::restart_window().unwrap() — the \
16178                     non-canonical-arm refusal reads through the lifted \
16179                     accessor",
16180                );
16181                assert_eq!(
16182                    window, sub_ms,
16183                    "RestartWindowNotCanonical.window must carry the \
16184                     author-declared :supervisor :restart-window value \
16185                     verbatim (got {window:?}, expected {sub_ms:?})",
16186                );
16187            }
16188            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
16189        }
16190        // Cap arm — the surfaced `window:` field must byte-equal the
16191        // accessor's return.
16192        let over_cap = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
16193        let s = SupervisorSpec {
16194            restart_window: Some(over_cap),
16195            children: vec![child.clone()],
16196            ..SupervisorSpec::default()
16197        };
16198        match s.validate().unwrap_err() {
16199            SupervisorError::RestartWindowExceedsCap { window } => {
16200                assert_eq!(
16201                    Some(window),
16202                    s.restart_window(),
16203                    "RestartWindowExceedsCap.window must byte-equal \
16204                     SupervisorSpec::restart_window().unwrap() — the \
16205                     cap-arm refusal reads through the lifted accessor",
16206                );
16207                assert_eq!(
16208                    window, over_cap,
16209                    "RestartWindowExceedsCap.window must carry the \
16210                     author-declared :supervisor :restart-window value \
16211                     verbatim (got {window:?}, expected {over_cap:?})",
16212                );
16213            }
16214            other => panic!("expected RestartWindowExceedsCap, got {other:?}"),
16215        }
16216        // Lower + upper accept-set boundaries.
16217        for restart_window in [Duration::from_millis(1), SUPERVISOR_RESTART_WINDOW_MAX] {
16218            let s = SupervisorSpec {
16219                restart_window: Some(restart_window),
16220                children: vec![child.clone()],
16221                ..SupervisorSpec::default()
16222            };
16223            assert!(
16224                s.validate().is_ok(),
16225                "validate must accept restart_window == Some({restart_window:?}) \
16226                 (an accept-set boundary of \
16227                 1ms..=SUPERVISOR_RESTART_WINDOW_MAX)",
16228            );
16229        }
16230    }
16231
16232    #[test]
16233    fn supervisor_spec_restart_window_projects_option_duration_by_copy() {
16234        // The by-copy pin: [`SupervisorSpec::restart_window`] returns
16235        // `Option<Duration>` by copy — `Duration` is `Copy` (so
16236        // `Option<Duration>` is `Copy`) and the accessor must return by
16237        // value, not by reference. Peer of the sibling M2
16238        // [`crate::LimitsSpec::wall_clock`] (8cb717b) by-copy pin on the
16239        // per-`:limits :wall-clock` axis and the sibling M3
16240        // [`crate::MeshPolicy::timeout`] (7073d0f) by-copy pin on the
16241        // per-`:politicas :timeout` axis, extended onto the peer M2
16242        // supervisor-slot `Option<Duration>` copy-invariant shape — the
16243        // accessor's returned `Option<Duration>` must outlive `&self`
16244        // (multiple calls must return equal values from a dropped-`&self`
16245        // copy, since the returned Option carries no borrow), and calling
16246        // the accessor twice on the same SupervisorSpec must yield the
16247        // same `Option<Duration>` verbatim (idempotent, no side effects
16248        // on `&self`).
16249        //
16250        // Pins against a future silent detour that returned
16251        // `Option<&Duration>` (which would type-check but silently break
16252        // every downstream caller — the future wasm-operator's
16253        // per-supervisor restart-intensity counter consumes `Duration` by
16254        // value and `&Duration` would fold to a detached copy at the call
16255        // site), an accidental `Option::as_ref()` projection
16256        // (`self.restart_window.as_ref()` would also type-check but
16257        // return `Option<&Duration>`), or a one-arm-only accessor that
16258        // reads `Some(*w)` in the Some arm but reads a fresh
16259        // `Default::default()` (which would collapse to `Duration::ZERO`,
16260        // not `None`) in the None arm — a footgun the
16261        // [`SupervisorError::RestartWindowZero`] validate arm explicitly
16262        // closes since Erlang/OTP's `MaxIntensity / Period` invariant
16263        // requires `Period > 0` and `None` structurally expresses "never
16264        // reset" instead.
16265        for restart_window in [
16266            None,
16267            Some(Duration::from_millis(1)),
16268            Some(Duration::from_secs(60)),
16269            Some(SUPERVISOR_RESTART_WINDOW_MAX),
16270        ] {
16271            let s = SupervisorSpec {
16272                restart_window,
16273                ..SupervisorSpec::default()
16274            };
16275            let first = s.restart_window();
16276            let second = s.restart_window();
16277            assert_eq!(
16278                first, second,
16279                "SupervisorSpec::restart_window must be idempotent — two \
16280                 successive calls on the same &self must return the \
16281                 same Option<Duration>",
16282            );
16283            assert_eq!(
16284                first, restart_window,
16285                "SupervisorSpec::restart_window must return :supervisor \
16286                 :restart-window verbatim by copy — got {first:?}, \
16287                 expected {restart_window:?}",
16288            );
16289        }
16290    }
16291
16292    // ── per-`:supervisor` `:children` typed-accessor coherence pins ─────────
16293    //
16294    // The [`SupervisorSpec::children`] accessor lift is the seed of the
16295    // slice-return (`&[T]`) accessor discipline on the substrate — the four
16296    // peer `Vec`-carry axes ([`crate::Placement::clusters`],
16297    // [`crate::AplicacaoSpec::membros`], [`crate::AplicacaoSpec::contratos`],
16298    // [`crate::UpgradeFromEntry::instructions`]) still key off the raw field
16299    // access at the time of this seed, and inherit this pin family's
16300    // discipline as future compounding runs migrate their consumers. The
16301    // three pins below cover (1) the accessor's byte-equal projection
16302    // against the raw field access across the empty / singleton / cohort
16303    // fixtures the [`SupervisorSpec::validate`] partition-dispatch fans
16304    // between, (2) the [`SupervisorSpec::validate`] `SimpleOneForOne ↔
16305    // non-SimpleOneForOne` partition dispatch's paired `.is_empty()`
16306    // consumer routing through the accessor on both arms, and (3) the
16307    // per-child validate loop's traversal reading the same slice-view the
16308    // accessor projects. Peer of the sibling M2
16309    // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
16310    // two-consumer coherence pin on the per-`:supervisor`
16311    // sibling-restart-strategy `Copy`-composite-enum scalar axis, extended
16312    // onto the per-`:supervisor` static-child-list `Vec`-carry axis.
16313
16314    #[test]
16315    fn supervisor_spec_children_returns_children_slice_byte_equal_across_permutations() {
16316        // The canonical per-`:supervisor` static-child-list scalar-shape
16317        // pin: [`SupervisorSpec::children`] must return the `:supervisor
16318        // :children` typed `Vec<ChildSpec>` verbatim as a `&[ChildSpec]`
16319        // slice-view over the same backing buffer the raw
16320        // `self.children.as_slice()` field access borrows from, byte-
16321        // equal across every representative fixture in the accept-set —
16322        // the empty slice (the `SimpleOneForOne`-arm sentinel),
16323        // the singleton slice (the minimal non-`SimpleOneForOne` shape),
16324        // and a two-child cohort (a peer non-`SimpleOneForOne` shape
16325        // with the peer three restart-policy variants in play).
16326        //
16327        // Pins against a future silent detour that returned
16328        // `&Vec<ChildSpec>` (which would type-check but leak the
16329        // storage-side `Vec`'s grow/push/reserve surface no consumer of
16330        // the typed view reaches for), a fresh-allocated
16331        // `Vec<ChildSpec>` copy (which would type-check via a coercion
16332        // but silently break every downstream caller that relied on the
16333        // slice sharing the backing buffer's identity), or an
16334        // out-of-order or length-drifted projection (which would silently
16335        // split the per-child validate loop's traversal input from the
16336        // paired partition-dispatch `.is_empty()` probe's input).
16337        //
16338        // Peer of the sibling
16339        // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
16340        // (eafb619) `Copy`-composite-enum byte-equal pin on the
16341        // per-`:supervisor` sibling-restart-strategy axis, extended onto
16342        // the per-`:supervisor` static-child-list `Vec`-carry axis.
16343        let fixtures: Vec<Vec<ChildSpec>> = vec![
16344            Vec::new(),
16345            vec![child("worker", "^0.1", RestartPolicy::Permanent)],
16346            vec![
16347                child("worker", "^0.1", RestartPolicy::Permanent),
16348                child("cache-server", "^0.1", RestartPolicy::Transient),
16349            ],
16350            vec![
16351                child("worker", "^0.1", RestartPolicy::Permanent),
16352                child("cache-server", "^0.1", RestartPolicy::Transient),
16353                child("scratch-job", "^0.1", RestartPolicy::Temporary),
16354            ],
16355        ];
16356        for children in fixtures {
16357            let s = SupervisorSpec {
16358                children: children.clone(),
16359                ..SupervisorSpec::default()
16360            };
16361            assert_eq!(
16362                s.children(),
16363                children.as_slice(),
16364                "SupervisorSpec::children must return :supervisor \
16365                 :children verbatim (got {:?}, expected {:?})",
16366                s.children(),
16367                children.as_slice(),
16368            );
16369            assert_eq!(
16370                s.children(),
16371                s.children.as_slice(),
16372                "SupervisorSpec::children accessor and \
16373                 .children.as_slice() field access must byte-equal — \
16374                 the accessor is the substrate-primitive typed \
16375                 dispatch every downstream static-child-list consumer \
16376                 must route through",
16377            );
16378            assert_eq!(
16379                s.children().len(),
16380                s.children.len(),
16381                "SupervisorSpec::children().len() must byte-equal \
16382                 self.children.len() — a length-drift would silently \
16383                 split the paired partition-dispatch `.is_empty()` \
16384                 probe input from the per-child validate loop's \
16385                 traversal input",
16386            );
16387        }
16388    }
16389
16390    #[test]
16391    fn validate_reads_through_lifted_children_accessor() {
16392        // Three-consumer coherence pin: the [`SupervisorSpec::validate`]
16393        // `SimpleOneForOne`-arm `!self.children().is_empty()` refusal
16394        // probe (which must trip [`SupervisorError::SimpleOneForOneWithStaticChildren`]
16395        // when the accessor projects a non-empty slice under a
16396        // `SimpleOneForOne` estrategia), the peer non-`SimpleOneForOne`-arm
16397        // `self.children().is_empty()` refusal probe (which must trip
16398        // [`SupervisorError::NoChildren`] when the accessor projects the
16399        // empty slice under any peer estrategia), and the per-child
16400        // validate loop's `for child in self.children()` traversal
16401        // (which must reach every entry in the same order the accessor
16402        // projects) must all key off the lifted accessor, so any future
16403        // rebrand on the typed slot's reader shape lands at exactly one
16404        // place. Pins the three-site coherence by exercising each
16405        // production consumer end-to-end: (1) the
16406        // `SimpleOneForOneWithStaticChildren` refusal under a non-empty
16407        // slice + `SimpleOneForOne` estrategia, (2) the `NoChildren`
16408        // refusal under the empty slice + non-`SimpleOneForOne`
16409        // estrategia across every peer variant, and (3) the per-child
16410        // duplicate-detection surface fires on the second entry of a
16411        // two-child cohort that shares a `:caixa` name (which requires
16412        // the loop to reach both entries — a first-entry-only projection
16413        // would silently pass since the dedup HashSet has room for the
16414        // first insert).
16415        //
16416        // Peer of the sibling M2
16417        // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
16418        // two-consumer coherence pin on the per-`:supervisor`
16419        // sibling-restart-strategy axis, extended onto the
16420        // per-`:supervisor` static-child-list `Vec`-carry axis.
16421
16422        // (1) `SimpleOneForOne`-arm probe: a non-empty slice under a
16423        // `SimpleOneForOne` estrategia must trip
16424        // `SimpleOneForOneWithStaticChildren`.
16425        let s = SupervisorSpec {
16426            estrategia: RestartStrategy::SimpleOneForOne,
16427            children: vec![child("worker", "^0.1", RestartPolicy::Permanent)],
16428            ..SupervisorSpec::default()
16429        };
16430        assert_eq!(
16431            s.validate().unwrap_err(),
16432            SupervisorError::SimpleOneForOneWithStaticChildren,
16433            "SimpleOneForOne + non-empty children must trip \
16434             SimpleOneForOneWithStaticChildren — the accessor projects \
16435             a non-empty slice, and the SimpleOneForOne-arm refusal \
16436             probe reads through the lifted accessor",
16437        );
16438        assert!(
16439            !s.children().is_empty(),
16440            "the SimpleOneForOne-arm refusal input must be a non-empty \
16441             slice per the accessor's projection",
16442        );
16443
16444        // (2) Peer non-`SimpleOneForOne`-arm probe: the empty slice
16445        // under any peer estrategia must trip `NoChildren`.
16446        for estrategia in [
16447            RestartStrategy::OneForOne,
16448            RestartStrategy::OneForAll,
16449            RestartStrategy::RestForOne,
16450        ] {
16451            let s = SupervisorSpec {
16452                estrategia,
16453                children: Vec::new(),
16454                ..SupervisorSpec::default()
16455            };
16456            match s.validate().unwrap_err() {
16457                SupervisorError::NoChildren { estrategia: e } => {
16458                    assert_eq!(
16459                        e, estrategia,
16460                        "NoChildren.estrategia must carry the author-\
16461                         declared :supervisor :estrategia variant \
16462                         verbatim (got {e:?}, expected {estrategia:?})",
16463                    );
16464                }
16465                other => panic!(
16466                    "expected NoChildren, got {other:?} for \
16467                     estrategia={estrategia:?}"
16468                ),
16469            }
16470            assert!(
16471                s.children().is_empty(),
16472                "the non-SimpleOneForOne-arm refusal input must be the \
16473                 empty slice per the accessor's projection",
16474            );
16475        }
16476
16477        // (3) Per-child validate loop: a two-child cohort that shares a
16478        // `:caixa` name must trip `DuplicateChildCaixa` — the loop must
16479        // reach both entries through the accessor.
16480        let s = SupervisorSpec {
16481            estrategia: RestartStrategy::OneForOne,
16482            children: vec![
16483                child("worker", "^0.1", RestartPolicy::Permanent),
16484                child("worker", "^0.2", RestartPolicy::Transient),
16485            ],
16486            ..SupervisorSpec::default()
16487        };
16488        match s.validate().unwrap_err() {
16489            SupervisorError::DuplicateChildCaixa { caixa } => {
16490                assert_eq!(
16491                    caixa, "worker",
16492                    "DuplicateChildCaixa.caixa must carry the shared \
16493                     child `:caixa` name verbatim",
16494                );
16495            }
16496            other => panic!("expected DuplicateChildCaixa, got {other:?}"),
16497        }
16498        assert_eq!(
16499            s.children().len(),
16500            2,
16501            "the per-child validate loop's traversal input must be a \
16502             two-element slice per the accessor's projection",
16503        );
16504    }
16505
16506    // Shared helper for the M2 per-`:children` per-slot-gate ≡
16507    // `validate` equivalence pins: builds an `OneForOne`-estrategia
16508    // one-cohort spec whose peer `:estrategia`↔`:children.is_empty()`
16509    // partition, `:max-restarts` zero-floor/cap, and `:restart-window`
16510    // bracket all pass cleanly so the sole failing surface is the
16511    // per-child cascade [`SupervisorSpec::validate_children`] owns, and
16512    // pins the two-altitude equivalence on the paired probe.
16513    fn assert_validate_children_matches_gate(children: Vec<ChildSpec>, expected: &SupervisorError) {
16514        let s = SupervisorSpec {
16515            estrategia: RestartStrategy::OneForOne,
16516            children,
16517            ..SupervisorSpec::default()
16518        };
16519        let via_gate = s.validate_children().unwrap_err();
16520        let via_validate = s.validate().unwrap_err();
16521        assert_eq!(&via_gate, expected, "validate_children direct dispatch",);
16522        assert_eq!(&via_validate, expected, "validate() end-to-end dispatch",);
16523        assert_eq!(
16524            via_gate, via_validate,
16525            "per-slot gate ≡ validate() must discriminate the same \
16526             refusal shape",
16527        );
16528    }
16529
16530    #[test]
16531    fn validate_children_matches_gate_on_per_axis_refusal_shapes() {
16532        // Fail-before-pass-after equivalence pin on the M2
16533        // per-`:children` per-slot gate ≡ [`SupervisorSpec::validate`]
16534        // convergence — sibling of the M3 mesh-slot
16535        // `validate_membros_*` / `validate_contratos_*` /
16536        // `validate_entrada_*` per-slot-gate ≡ `validate` pins on the
16537        // peer per-entry axes. Sweeps four of the five refusal shapes
16538        // the per-slot gate owns: (1) `EmptyChildName` on an empty-
16539        // `:caixa` child, (2) `ChildCaixaInvalid` on a structurally
16540        // invalid `:caixa` DNS-1123 label, (3) `EmptyChildVersion` on
16541        // an empty-`:versao` child, (4) `DuplicateChildCaixa` on a
16542        // duplicate-`:caixa` fan-out. Companion pin
16543        // `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
16544        // covers `ChildVersaoInvalid` (whose parser-owned reason string
16545        // needs pattern-matching, not equality) and the clean-pass
16546        // canonical fixture; together the two pins guarantee the
16547        // per-slot gate and `validate` discriminate the same set on
16548        // every per-child-covered input.
16549        assert_validate_children_matches_gate(
16550            vec![child("", "^0.1", RestartPolicy::Permanent)],
16551            &SupervisorError::EmptyChildName,
16552        );
16553        assert_validate_children_matches_gate(
16554            vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
16555            &SupervisorError::ChildCaixaInvalid {
16556                caixa: "Worker".into(),
16557                reason: "contains uppercase character 'W' (K8s DNS-1123 label names are lowercase-only; use \"worker\")".into(),
16558            },
16559        );
16560        assert_validate_children_matches_gate(
16561            vec![child("worker", "", RestartPolicy::Permanent)],
16562            &SupervisorError::EmptyChildVersion {
16563                caixa: "worker".into(),
16564            },
16565        );
16566        assert_validate_children_matches_gate(
16567            vec![
16568                child("worker", "^0.1", RestartPolicy::Permanent),
16569                child("worker", "^0.2", RestartPolicy::Transient),
16570            ],
16571            &SupervisorError::DuplicateChildCaixa {
16572                caixa: "worker".into(),
16573            },
16574        );
16575    }
16576
16577    #[test]
16578    fn validate_children_matches_gate_on_versao_invalid_and_clean_pass() {
16579        // Second half of the two-altitude equivalence pin — covers the
16580        // one refusal shape whose reason string is parser-owned
16581        // (`ChildVersaoInvalid`, whose reason comes from the shared
16582        // [`crate::version::parse_requirement`] impl and may drift) and
16583        // the clean-pass canonical fixture. Sibling pin
16584        // `validate_children_matches_gate_on_per_axis_refusal_shapes`
16585        // covers the four equality-comparable refusal shapes.
16586        let s_bad_versao = SupervisorSpec {
16587            estrategia: RestartStrategy::OneForOne,
16588            children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
16589            ..SupervisorSpec::default()
16590        };
16591        let via_gate = s_bad_versao.validate_children().unwrap_err();
16592        let via_validate = s_bad_versao.validate().unwrap_err();
16593        match (&via_gate, &via_validate) {
16594            (
16595                SupervisorError::ChildVersaoInvalid {
16596                    caixa: cg,
16597                    versao: vg,
16598                    ..
16599                },
16600                SupervisorError::ChildVersaoInvalid {
16601                    caixa: cv,
16602                    versao: vv,
16603                    ..
16604                },
16605            ) => {
16606                assert_eq!(cg, "worker", "per-slot gate :caixa carrier");
16607                assert_eq!(vg, "not-a-req", "per-slot gate :versao carrier");
16608                assert_eq!(cv, "worker", "validate() :caixa carrier");
16609                assert_eq!(vv, "not-a-req", "validate() :versao carrier");
16610            }
16611            other => panic!("expected ChildVersaoInvalid on both altitudes, got {other:?}"),
16612        }
16613        assert_eq!(
16614            via_gate, via_validate,
16615            "per-slot gate ≡ validate() on ChildVersaoInvalid full envelope",
16616        );
16617
16618        let s_ok = SupervisorSpec {
16619            estrategia: RestartStrategy::OneForOne,
16620            children: vec![
16621                child("worker-a", "^0.1", RestartPolicy::Permanent),
16622                child("worker-b", "~0.2.3", RestartPolicy::Transient),
16623                child("collector", "*", RestartPolicy::Temporary),
16624            ],
16625            ..SupervisorSpec::default()
16626        };
16627        s_ok.validate_children()
16628            .expect("per-slot gate must accept the clean-pass fixture");
16629        s_ok.validate()
16630            .expect("validate() must accept the clean-pass fixture");
16631    }
16632
16633    #[test]
16634    fn validate_children_is_self_contained_on_children_slot() {
16635        // Self-containment pin: [`SupervisorSpec::validate_children`]
16636        // resolves the per-child cascade against `&self` alone, without
16637        // depending on the peer `:estrategia`/`:max-restarts`/
16638        // `:restart-window` gates having run first — same posture the M3
16639        // peer per-slot gates carry (`validate_membros`,
16640        // `validate_contratos`, `validate_entrada`, `validate_placement`,
16641        // routing through their own oracles rather than borrowing state
16642        // threaded down from `validate`). A future consumer that reaches
16643        // the per-slot gate directly on a spec whose peer slots would
16644        // fail `validate` still surfaces the per-child refusal, not the
16645        // peer refusal.
16646        //
16647        // Construct a spec whose `:max-restarts` is `0` (which would
16648        // trip [`SupervisorError::ZeroMaxRestarts`] at `validate` after
16649        // the partition-dispatch) and whose `:children` carries a
16650        // `DuplicateChildCaixa` shape: the per-slot gate called directly
16651        // must surface `DuplicateChildCaixa`, proving it does not depend
16652        // on the peer `:max-restarts` gate running first.
16653        let s = SupervisorSpec {
16654            estrategia: RestartStrategy::OneForOne,
16655            max_restarts: 0,
16656            restart_window: Some(Duration::from_secs(60)),
16657            children: vec![
16658                child("worker", "^0.1", RestartPolicy::Permanent),
16659                child("worker", "^0.2", RestartPolicy::Transient),
16660            ],
16661        };
16662        assert_eq!(
16663            s.validate_children().unwrap_err(),
16664            SupervisorError::DuplicateChildCaixa {
16665                caixa: "worker".into(),
16666            },
16667            "per-slot gate must resolve per-child refusal directly against \
16668             `&self` — a dependency on the peer `:max-restarts` gate \
16669             running first would surface ZeroMaxRestarts here instead",
16670        );
16671        // The peer gate is still the surface `validate` reaches — pin
16672        // the ordering to establish that `validate_children` truly runs
16673        // last in `validate`'s dispatch, so a direct call bypasses the
16674        // peer gates on any spec whose per-child cascade would fail.
16675        assert_eq!(
16676            s.validate().unwrap_err(),
16677            SupervisorError::ZeroMaxRestarts,
16678            "validate() must surface the peer `:max-restarts` gate before \
16679             reaching the per-child cascade — this pins the dispatch \
16680             ordering the per-slot gate's self-containment complements",
16681        );
16682    }
16683
16684    #[test]
16685    fn child_spec_restart_accessor_is_const_fn() {
16686        // The [`ChildSpec::restart`] per-`:children` restart-decision-
16687        // policy `Copy`-return scalar accessor is declared
16688        // `#[must_use] pub const fn` — matching the sibling M2
16689        // per-`:supervisor` [`SupervisorSpec::estrategia`] (pinned by
16690        // [`supervisor_spec_estrategia_accessor_is_const_fn`] below,
16691        // both converted in this commit), the sibling M2
16692        // per-`:supervisor` [`SupervisorSpec::max_restarts`] (b698ec0)
16693        // `Copy`-`u32` accessor already `pub const fn`, and the peer M3
16694        // mesh-slot per-`:entrada` [`crate::Entrada::port`] (bafa004) /
16695        // per-`:placement` [`crate::Placement::estrategia`] (bafa004)
16696        // `Copy`-return `pub const fn` scalar accessors on the sibling
16697        // M3 surface. Pin the `const`-eval posture here so a future
16698        // accidental downgrade to non-`const` (an added runtime helper
16699        // reachable only from a non-`const` context, an
16700        // `Option<RestartPolicy>`-shape migration on the per-child
16701        // restart-decision axis once heterogeneous per-cluster
16702        // restart-policy overlays land that would silently drop the
16703        // `const` qualifier, a manual hand-rolled shadow) trips at
16704        // caixa-core build time rather than surfacing as a downstream
16705        // `const`-context regression far from the declaration.
16706        //
16707        // Same shape as the sibling M3
16708        // [`crate::aplicacao::tests::placement_estrategia_accessor_is_const_fn`]
16709        // and [`crate::aplicacao::tests::entrada_port_accessor_is_const_fn`]
16710        // (bafa004) pins on the peer M3 mesh-slot `Copy`-return scalar
16711        // accessor axis — the load-bearing witness lives in the
16712        // module-scope `const fn` wrapper `restart_via_const_fn` below:
16713        // a body that calls [`ChildSpec::restart`] under a `const fn`
16714        // signature is well-formed only when the callee is itself
16715        // `const fn`, so any future accidental downgrade of
16716        // [`ChildSpec::restart`] to non-`const` fails at caixa-core
16717        // build time (const-eval E0015 `cannot call non-const method`),
16718        // strictly stronger than a runtime `assert!(CONST)` and
16719        // side-stepping the destructor-in-const restriction that
16720        // blocks direct `const _: RestartPolicy = FIXTURE.restart()`
16721        // items on `ChildSpec`'s `String` carriers.
16722        //
16723        // The runtime body sweeps every closed-set [`RestartPolicy`]
16724        // arm and asserts the wrapped and direct dispatches agree.
16725        const fn restart_via_const_fn(c: &ChildSpec) -> RestartPolicy {
16726            c.restart()
16727        }
16728        for restart in [
16729            RestartPolicy::Permanent,
16730            RestartPolicy::Transient,
16731            RestartPolicy::Temporary,
16732        ] {
16733            let c = ChildSpec {
16734                caixa: "worker".into(),
16735                versao: "^0.1".into(),
16736                restart,
16737            };
16738            assert_eq!(
16739                restart_via_const_fn(&c),
16740                c.restart(),
16741                "const-fn-wrapped and direct dispatch on \
16742                 ChildSpec::restart must agree for {restart:?}",
16743            );
16744            assert_eq!(
16745                c.restart(),
16746                restart,
16747                "ChildSpec::restart must return the storage-side \
16748                 RestartPolicy verbatim for {restart:?} (a violation \
16749                 means the accessor stopped being a raw field-return \
16750                 copy)",
16751            );
16752        }
16753    }
16754
16755    #[test]
16756    fn supervisor_spec_estrategia_accessor_is_const_fn() {
16757        // The [`SupervisorSpec::estrategia`] per-`:supervisor`
16758        // sibling-restart-strategy `Copy`-return scalar accessor is
16759        // declared `#[must_use] pub const fn` — matching the sibling M2
16760        // per-`:children` [`ChildSpec::restart`] (pinned by
16761        // [`child_spec_restart_accessor_is_const_fn`] above, both
16762        // converted in this commit), the sibling M2 per-`:supervisor`
16763        // [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32`
16764        // accessor already `pub const fn`, and mirroring the peer M3
16765        // mesh-slot per-`:placement`
16766        // [`crate::Placement::estrategia`] (bafa004) `Copy`-return
16767        // `pub const fn` scalar accessor whose method-name discipline
16768        // the [`SupervisorSpec::estrategia`] method was authored to
16769        // match. Pin the `const`-eval posture here so a future
16770        // accidental downgrade to non-`const` (an added runtime helper
16771        // reachable only from a non-`const` context, an
16772        // `Option<RestartStrategy>`-shape migration once the substrate
16773        // grows per-cluster strategy overlays that would silently drop
16774        // the `const` qualifier, a manual hand-rolled shadow) trips at
16775        // caixa-core build time rather than surfacing as a downstream
16776        // `const`-context regression far from the declaration.
16777        //
16778        // Same shape as the sibling
16779        // [`child_spec_restart_accessor_is_const_fn`] pin above — the
16780        // load-bearing witness lives in the module-scope `const fn`
16781        // wrapper `estrategia_via_const_fn` below: a body that calls
16782        // [`SupervisorSpec::estrategia`] under a `const fn` signature
16783        // is well-formed only when the callee is itself `const fn`,
16784        // side-stepping the destructor-in-const restriction that would
16785        // otherwise block a direct
16786        // `const _: RestartStrategy = FIXTURE.estrategia()` item on
16787        // `SupervisorSpec`'s `Vec<ChildSpec>` / `Option<Duration>`
16788        // carriers.
16789        //
16790        // The runtime body sweeps every closed-set [`RestartStrategy`]
16791        // arm via [`RestartStrategy::ALL`] and asserts the wrapped and
16792        // direct dispatches agree.
16793        const fn estrategia_via_const_fn(s: &SupervisorSpec) -> RestartStrategy {
16794            s.estrategia()
16795        }
16796        for &estrategia in RestartStrategy::ALL {
16797            let s = SupervisorSpec {
16798                estrategia,
16799                max_restarts: 5,
16800                restart_window: Some(Duration::from_secs(60)),
16801                children: Vec::new(),
16802            };
16803            assert_eq!(
16804                estrategia_via_const_fn(&s),
16805                s.estrategia(),
16806                "const-fn-wrapped and direct dispatch on \
16807                 SupervisorSpec::estrategia must agree for {estrategia:?}",
16808            );
16809            assert_eq!(
16810                s.estrategia(),
16811                estrategia,
16812                "SupervisorSpec::estrategia must return the storage-side \
16813                 RestartStrategy verbatim for {estrategia:?} (a violation \
16814                 means the accessor stopped being a raw field-return \
16815                 copy)",
16816            );
16817        }
16818    }
16819
16820    // Per-variant equivalence pins for the [`supervisor_caixa_only_ctors!`]
16821    // macro definition (see the paired doc-block above the macro
16822    // definition) — every generated `<ctor>(caixa: &str) -> Self`
16823    // constructor folds the uniform `Self::<Variant> { caixa:
16824    // caixa.to_string() }` one-field struct-literal onto one substrate
16825    // primitive. The three per-variant equivalence pins below
16826    // (fail-before-pass-after by construction — a byte-mismatched macro
16827    // arm would trip its equivalence pin first) lock each generated
16828    // constructor to its struct-literal peer under `PartialEq`, so
16829    // every wire-up in [`SupervisorSpec::validate_children`] and
16830    // [`validate_no_self_supervision`] on that variant produces a
16831    // byte-equal `SupervisorError` to the pre-lift open-coded
16832    // struct-literal. The cross-axis pin that follows (non-default
16833    // caixa name) routes the sole constructor input axis through
16834    // `.to_string()`, so the fold does not silently collapse onto a
16835    // fixed name.
16836    //
16837    // Peer of the sibling `<slot>_ctor_matches_tuple_literal_wrap` /
16838    // `<slot>_violation_ctor_matches_struct_literal_wrap` /
16839    // `<slot>_slots_on_non_<owner>_ctor_matches_struct_literal_wrap` /
16840    // `missing_entry_ctor_matches_struct_literal_wrap` /
16841    // `entrada_host_invalid_ctor_matches_struct_literal_wrap` /
16842    // `contrato_wrong_target_ctor_matches_struct_literal_wrap` /
16843    // `contrato_missing_target_ctor_matches_struct_literal_wrap` /
16844    // `<variant>_ctor_matches_struct_literal_wrap` equivalence pins
16845    // on the six sibling ctor families the recent trajectory closed
16846    // on the peer `LayoutError` / `AplicacaoError` envelopes.
16847
16848    #[test]
16849    fn empty_child_version_ctor_matches_struct_literal_wrap() {
16850        assert_eq!(
16851            SupervisorError::empty_child_version("worker"),
16852            SupervisorError::EmptyChildVersion {
16853                caixa: "worker".to_string(),
16854            },
16855            "generated empty_child_version ctor must produce byte-equal \
16856             SupervisorError to the open-coded struct-literal wrap on the \
16857             same &str fixture",
16858        );
16859    }
16860
16861    #[test]
16862    fn duplicate_child_caixa_ctor_matches_struct_literal_wrap() {
16863        assert_eq!(
16864            SupervisorError::duplicate_child_caixa("worker"),
16865            SupervisorError::DuplicateChildCaixa {
16866                caixa: "worker".to_string(),
16867            },
16868            "generated duplicate_child_caixa ctor must produce byte-equal \
16869             SupervisorError to the open-coded struct-literal wrap on the \
16870             same &str fixture",
16871        );
16872    }
16873
16874    #[test]
16875    fn child_supervises_self_ctor_matches_struct_literal_wrap() {
16876        assert_eq!(
16877            SupervisorError::child_supervises_self("orquestra"),
16878            SupervisorError::ChildSupervisesSelf {
16879                caixa: "orquestra".to_string(),
16880            },
16881            "generated child_supervises_self ctor must produce byte-equal \
16882             SupervisorError to the open-coded struct-literal wrap on the \
16883             same &str fixture",
16884        );
16885    }
16886
16887    // Per-variant equivalence pins for the two lifted
16888    // [`SupervisorError::child_caixa_invalid`] /
16889    // [`SupervisorError::child_versao_invalid`] inherent constructors
16890    // (fail-before-pass-after by construction — a byte-mismatched ctor body
16891    // would trip its equivalence pin first). Each pins the ctor output to
16892    // its pre-lift struct-literal peer under `PartialEq`, so every wire-up
16893    // in [`SupervisorSpec::validate_children`] on the two variants
16894    // produces a byte-equal `SupervisorError` to the pre-lift open-coded
16895    // struct-literal on the same scalar fixtures. Peers of the sibling
16896    // `membro_caixa_invalid_ctor_matches_struct_literal_wrap` /
16897    // `entrada_para_invalid_ctor_matches_struct_literal_wrap` / … pins on
16898    // the peer `AplicacaoError` envelope's
16899    // [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold.
16900
16901    #[test]
16902    fn child_caixa_invalid_ctor_matches_struct_literal_wrap() {
16903        let caixa = "Worker";
16904        let reason = "sample reason text";
16905        assert_eq!(
16906            SupervisorError::child_caixa_invalid(caixa, reason),
16907            SupervisorError::ChildCaixaInvalid {
16908                caixa: caixa.to_string(),
16909                reason: reason.to_string(),
16910            },
16911            "lifted child_caixa_invalid ctor must produce byte-equal \
16912             SupervisorError to the open-coded struct-literal wrap on the \
16913             same (&str, reason) fixture",
16914        );
16915    }
16916
16917    #[test]
16918    fn child_versao_invalid_ctor_matches_struct_literal_wrap() {
16919        let caixa = "worker";
16920        let versao = "not-a-req";
16921        let reason = "sample reason text";
16922        assert_eq!(
16923            SupervisorError::child_versao_invalid(caixa, versao, reason),
16924            SupervisorError::ChildVersaoInvalid {
16925                caixa: caixa.to_string(),
16926                versao: versao.to_string(),
16927                reason: reason.to_string(),
16928            },
16929            "lifted child_versao_invalid ctor must produce byte-equal \
16930             SupervisorError to the open-coded struct-literal wrap on the \
16931             same (&str, &str, reason) fixture",
16932        );
16933    }
16934
16935    #[test]
16936    fn supervisor_child_reason_ctors_route_reason_through_into_uniformly() {
16937        // Cross-axis pin: sweep the two lifted `{ …, reason }` ctors
16938        // against a `&str`-literal vs. `format!(…)` reason input to pin
16939        // both constructors accept the `impl Into<String>` bound
16940        // uniformly, so neither wire-up site drifts under a per-arm
16941        // wrapper transformation on the caller-side `reason` axis. Peer
16942        // of the sibling
16943        // `aplicacao_field_reason_ctors_route_reason_through_into_uniformly`
16944        // sweep on the peer `AplicacaoError` envelope.
16945        let via_literal = "literal reason text";
16946        let via_format = format!("{} reason text", "literal");
16947        assert_eq!(
16948            SupervisorError::child_caixa_invalid("Worker", via_literal),
16949            SupervisorError::child_caixa_invalid("Worker", via_format.clone()),
16950        );
16951        assert_eq!(
16952            SupervisorError::child_versao_invalid("worker", "not-a-req", via_literal),
16953            SupervisorError::child_versao_invalid("worker", "not-a-req", via_format),
16954        );
16955    }
16956
16957    #[test]
16958    fn supervisor_caixa_only_ctors_route_caixa_through_to_string() {
16959        // Cross-axis pin: sweep the sole constructor input axis (`caixa:
16960        // &str`) through a non-default fixture name against every
16961        // generated arm in the [`supervisor_caixa_only_ctors!`] macro,
16962        // so any wrapper-side lowercase / trim / truncate / re-order on
16963        // the `caixa.to_string()` sole-field construction surfaces
16964        // here rather than at a downstream diagnostic-shape mismatch.
16965        // Peer of the sibling `nome_only_ctor_routes_caixa_through_
16966        // nome_accessor` / `entrada_host_invalid_ctor_routes_host_
16967        // through_to_string` / `contrato_target_ctors_route_edge_
16968        // triple_through_verbatim` / `contrato_empty_pair_ctors_
16969        // route_edge_pair_through_verbatim` cross-axis routing pins on
16970        // the peer `LayoutError` / `AplicacaoError` envelopes; extended
16971        // here onto the `SupervisorError` `{ caixa: String }` envelope
16972        // so every substrate-primitive ctor family in caixa-core
16973        // guarantees the sole-field construction routes the caller's
16974        // `&str` through `.to_string()` verbatim.
16975        let name = "cache-v2";
16976        assert_eq!(
16977            SupervisorError::empty_child_version(name),
16978            SupervisorError::EmptyChildVersion {
16979                caixa: name.to_string(),
16980            },
16981        );
16982        assert_eq!(
16983            SupervisorError::duplicate_child_caixa(name),
16984            SupervisorError::DuplicateChildCaixa {
16985                caixa: name.to_string(),
16986            },
16987        );
16988        assert_eq!(
16989            SupervisorError::child_supervises_self(name),
16990            SupervisorError::ChildSupervisesSelf {
16991                caixa: name.to_string(),
16992            },
16993        );
16994    }
16995
16996    // ── supervisor_scalar_ctors! per-variant + cross-axis pins ──────────────
16997    //
16998    // Per-variant byte-equality pins guaranteeing every generated ctor arm in
16999    // the [`supervisor_scalar_ctors!`] macro produces a `SupervisorError`
17000    // structurally identical to the pre-lift `Self::<variant> { <field>: <val> }`
17001    // one-line struct-literal on the same `Copy`-`RestartStrategy | u32 |
17002    // Duration` fixture, plus one cross-axis sweep that routes each per-variant
17003    // `<field>: <ty>` scalar through the sole `$field:ident: $ty:ty` axis the
17004    // macro exposes so any wrapper-side truncation / re-order / silent `.into()`
17005    // / silent constant-substitution on any one variant surfaces here rather
17006    // than at a downstream per-`:supervisor` diagnostic-shape drift. Peer of the
17007    // sibling per-variant pins on `aplicacao_policy_scalar_ctors!` (7ef425e,
17008    // the 8-variant `AplicacaoError` `{ <field>: Duration | u32 }` fold on the
17009    // per-`:politicas` per-axis cap / canonical-form arms), plus the sibling
17010    // `supervisor_caixa_only_ctors!` (db09650), `SupervisorError::
17011    // {child_caixa_invalid,child_versao_invalid}` (d2ef2ec), and the peer
17012    // `DepError` / `AplicacaoError` / `LayoutError` / `LimitsError` /
17013    // `BehaviorError` / `UpgradeError` per-envelope ctor-macro pins.
17014    #[test]
17015    fn no_children_ctor_matches_struct_literal_wrap() {
17016        let estrategia = RestartStrategy::OneForAll;
17017        assert_eq!(
17018            SupervisorError::no_children(estrategia),
17019            SupervisorError::NoChildren { estrategia },
17020            "generated no_children ctor must produce byte-equal \
17021             `SupervisorError::NoChildren` to the pre-lift struct-literal wrap \
17022             on the same `Copy`-`RestartStrategy` fixture",
17023        );
17024    }
17025
17026    #[test]
17027    fn max_restarts_exceeds_cap_ctor_matches_struct_literal_wrap() {
17028        let max_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 1;
17029        assert_eq!(
17030            SupervisorError::max_restarts_exceeds_cap(max_restarts),
17031            SupervisorError::MaxRestartsExceedsCap { max_restarts },
17032            "generated max_restarts_exceeds_cap ctor must produce byte-equal \
17033             `SupervisorError::MaxRestartsExceedsCap` to the pre-lift \
17034             struct-literal wrap on the same `Copy`-`u32` fixture",
17035        );
17036    }
17037
17038    #[test]
17039    fn restart_window_not_canonical_ctor_matches_struct_literal_wrap() {
17040        let window = Duration::from_micros(1_500);
17041        assert_eq!(
17042            SupervisorError::restart_window_not_canonical(window),
17043            SupervisorError::RestartWindowNotCanonical { window },
17044            "generated restart_window_not_canonical ctor must produce \
17045             byte-equal `SupervisorError::RestartWindowNotCanonical` to the \
17046             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
17047        );
17048    }
17049
17050    #[test]
17051    fn restart_window_exceeds_cap_ctor_matches_struct_literal_wrap() {
17052        let window = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
17053        assert_eq!(
17054            SupervisorError::restart_window_exceeds_cap(window),
17055            SupervisorError::RestartWindowExceedsCap { window },
17056            "generated restart_window_exceeds_cap ctor must produce \
17057             byte-equal `SupervisorError::RestartWindowExceedsCap` to the \
17058             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
17059        );
17060    }
17061
17062    #[test]
17063    fn supervisor_scalar_ctors_route_field_through_copy_uniformly() {
17064        // Cross-axis routing pin: sweep each generated `<field>: <ty>`
17065        // constructor input axis through a non-default `Copy` fixture against
17066        // every arm in the [`supervisor_scalar_ctors!`] macro, so any wrapper-
17067        // side silent `.into()` / silent constant-substitution / silent field
17068        // re-name away from the canonical `estrategia | max_restarts | window`
17069        // axes on any one variant, or a `RestartStrategy | u32 | Duration`
17070        // axis silently rerouted through some other `Copy` coercion, surfaces
17071        // here rather than at a downstream per-`:supervisor` diagnostic-shape
17072        // drift. Peer of the sibling
17073        // `aplicacao_policy_scalar_ctors_route_field_through_copy_uniformly`
17074        // (7ef425e) cross-axis routing pin on the peer `AplicacaoError`
17075        // envelope's per-`:politicas` per-axis ctor family, extended here onto
17076        // the last M2 per-`:supervisor` `Copy`-scalar `SupervisorError`
17077        // variant family folded onto a substrate primitive.
17078        //
17079        // Fixtures picked out of each variant's accept-set boundary rather
17080        // than the default value so a silent constant-substitution to a per-
17081        // variant sentinel surfaces here on the structural-equality assertion.
17082        // The `RestartStrategy` fixture picks `RestForOne` (a non-default arm
17083        // that isn't the `OneForOne` [`SUPERVISOR_ESTRATEGIA_DEFAULT`] and
17084        // isn't the `SimpleOneForOne` arm the sibling
17085        // `SimpleOneForOneWithStaticChildren` unit variant intercepts). The
17086        // `max_restarts` fixture picks an above-cap magnitude the cap arm
17087        // rejects; the two `Duration` fixtures pick the sub-millisecond and
17088        // above-cap ends of the `:restart-window` canonical-form + cap
17089        // bracket respectively.
17090        let estrategia = RestartStrategy::RestForOne;
17091        let above_cap_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 137;
17092        let sub_ms = Duration::from_micros(1_500);
17093        let above_hour = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
17094        assert_eq!(
17095            SupervisorError::no_children(estrategia),
17096            SupervisorError::NoChildren { estrategia },
17097        );
17098        assert_eq!(
17099            SupervisorError::max_restarts_exceeds_cap(above_cap_restarts),
17100            SupervisorError::MaxRestartsExceedsCap {
17101                max_restarts: above_cap_restarts,
17102            },
17103        );
17104        assert_eq!(
17105            SupervisorError::restart_window_not_canonical(sub_ms),
17106            SupervisorError::RestartWindowNotCanonical { window: sub_ms },
17107        );
17108        assert_eq!(
17109            SupervisorError::restart_window_exceeds_cap(above_hour),
17110            SupervisorError::RestartWindowExceedsCap { window: above_hour },
17111        );
17112    }
17113
17114    #[test]
17115    fn restart_strategy_try_from_bytes_routes_through_from_wire_accessor() {
17116        // Fail-before-pass-after byte-parity pin on the newly lifted
17117        // `impl TryFrom<&[u8]> for RestartStrategy` — asserts the trait-
17118        // idiomatic byte-view reverse-projection standard-library impl
17119        // and the substrate-primitive [`RestartStrategy::from_wire`]
17120        // `Option<Self>` accessor resolve to the same four-arm
17121        // `PascalCase` wire accept-set across every arm the exhaustive
17122        // [`RestartStrategy::ALL`] slice enumerates. Extends the
17123        // substrate-wide trait-idiomatic byte-view reverse-projection
17124        // axis onto the first M2-OTP-shape supervisor-slot closed-set
17125        // fieldless typed enum peer — mirror of the paired
17126        // [`TryFrom<&str> for RestartStrategy`] str-view reverse-
17127        // projection axis on the same enum, and the byte-view companion
17128        // of the pre-existing byte-owned reverse-projection family
17129        // ([`AsRef<[u8]>`], [`From<RestartStrategy> for Vec<u8>`],
17130        // [`From<&RestartStrategy> for Vec<u8>`]) on this same enum.
17131        // Peer of the sibling
17132        // [`crate::kind::tests::caixa_kind_try_from_bytes_routes_through_from_wire_accessor`]
17133        // (18d1940),
17134        // [`crate::dialeto::tests::caixa_dialeto_try_from_bytes_routes_through_from_wire_accessor`]
17135        // (d102cb8), and
17136        // [`crate::dep::tests::dep_list_try_from_bytes_routes_through_from_wire_accessor`]
17137        // (b8f25d5) — tracks the "route through `from_wire` via
17138        // `std::str::from_utf8`" discipline the first-mover established.
17139        //
17140        // Rust's standard library carries no blanket
17141        // `impl<T: for<'a> TryFrom<&'a str>> TryFrom<&[u8]> for T`, so
17142        // a two-hop composition through [`std::str::from_utf8`] + the
17143        // paired [`TryFrom<&str>`] axis is reachable through the pre-
17144        // existing str-view reverse-projection axis alone. But that
17145        // two-hop shape has no compile-time link back to the byte-view
17146        // reverse-projection axis, forces every downstream
17147        // `<T: for<'a> TryFrom<&'a [u8]>>`-bound consumer to open-code
17148        // the composition at every call site, and admits a silent split
17149        // whenever a future call site takes a sibling byte-projection
17150        // axis whose parse arm-set carries no compile-time byte-view
17151        // surface. This impl closes the byte-view reverse-projection
17152        // axis at the substrate-primitive [`RestartStrategy::from_wire`]
17153        // accessor so every future `<T: for<'a> TryFrom<&'a [u8]>>`-
17154        // bound consumer reaches the same four-arm `PascalCase` wire
17155        // accept-set through one trait dispatch.
17156        for &variant in RestartStrategy::ALL {
17157            let wire_bytes: &[u8] = variant.as_str().as_bytes();
17158            assert_eq!(
17159                <RestartStrategy as TryFrom<&[u8]>>::try_from(wire_bytes),
17160                Ok(variant),
17161                "TryFrom<&[u8]> impl on RestartStrategy must round-trip \
17162                 RestartStrategy::{variant:?}.as_str().as_bytes() back to \
17163                 Ok(RestartStrategy::{variant:?}) — divergence from \
17164                 RestartStrategy::from_wire signals a silent detour off \
17165                 the substrate-primitive accessor"
17166            );
17167            assert_eq!(
17168                <RestartStrategy as TryFrom<&[u8]>>::try_from(wire_bytes).ok(),
17169                RestartStrategy::from_wire(variant.as_str()),
17170                "TryFrom<&[u8]> ok()-projection on \
17171                 RestartStrategy::{variant:?}.as_str().as_bytes() must \
17172                 byte-equal RestartStrategy::from_wire on the paired \
17173                 &str input"
17174            );
17175            // Cross-axis witness: the byte-view reverse-projection axis
17176            // must agree with the paired str-view reverse-projection
17177            // axis ([`TryFrom<&str>`]) on every accepted arm — the two
17178            // reverse paths share one `PascalCase` accept-set through
17179            // the substrate-primitive `from_wire` accessor.
17180            let via_str: Result<RestartStrategy, ()> =
17181                <RestartStrategy as TryFrom<&str>>::try_from(variant.as_str());
17182            let via_bytes: Result<RestartStrategy, ()> =
17183                <RestartStrategy as TryFrom<&[u8]>>::try_from(wire_bytes);
17184            assert_eq!(
17185                via_bytes, via_str,
17186                "TryFrom<&[u8]> and TryFrom<&str> reverse-projection \
17187                 axes on RestartStrategy must agree on \
17188                 RestartStrategy::{variant:?} — divergence signals the \
17189                 byte-view and str-view reverse paths have drifted off \
17190                 the same substrate-primitive from_wire accessor"
17191            );
17192            // Forward/reverse byte-view cross-axis witness: feed the
17193            // paired [`AsRef<[u8]>`] byte-tail back through the new
17194            // impl and assert it round-trips to the originating arm.
17195            let via_asref: &[u8] = <RestartStrategy as AsRef<[u8]>>::as_ref(&variant);
17196            assert_eq!(
17197                <RestartStrategy as TryFrom<&[u8]>>::try_from(via_asref),
17198                Ok(variant),
17199                "TryFrom<&[u8]> ∘ AsRef<[u8]> must round-trip \
17200                 RestartStrategy::{variant:?} — divergence signals the \
17201                 forward and reverse byte-view axes have drifted off \
17202                 the same substrate-primitive as_str/from_wire pair"
17203            );
17204        }
17205    }
17206
17207    #[test]
17208    fn restart_strategy_try_from_bytes_rejects_unknown_and_non_utf8_bytes() {
17209        // Rejection witness on the `impl TryFrom<&[u8]> for
17210        // RestartStrategy` — sweeps two rejection paths the byte-view
17211        // reverse-projection axis collapses onto the single unit-error
17212        // `Err(())` return: the invalid-UTF-8 rejection path
17213        // ([`std::str::from_utf8`] returns `Err` before
17214        // [`RestartStrategy::from_wire`] runs) and the valid-UTF-8-but-
17215        // unknown-wire rejection path ([`RestartStrategy::from_wire`]
17216        // returns `None` on a byte-string outside the four-arm
17217        // `PascalCase` accept-set). Both must reject, so a future
17218        // accidental widening of the trait impl's accept-set (a case-
17219        // fold path, a silent acceptance of the kebab-case dispatcher-
17220        // catalog byte-strings on this axis — which would collide the
17221        // two-axis wire/catalog split the sibling
17222        // [`RestartStrategy::from_wire`] doc block makes load-bearing —
17223        // a `#[serde(rename_all = "…")]` attribute drift that widens
17224        // the parse arm-set silently, a stray fallback that maps
17225        // invalid UTF-8 onto a default arm rather than the trait-
17226        // idiomatic `Err(())`) trips at caixa-core test time. Peer of
17227        // the sibling
17228        // [`crate::kind::tests::caixa_kind_try_from_bytes_rejects_unknown_and_non_utf8_bytes`]
17229        // (18d1940),
17230        // [`crate::dialeto::tests::caixa_dialeto_try_from_bytes_rejects_unknown_and_non_utf8_bytes`]
17231        // (d102cb8), and
17232        // [`crate::dep::tests::dep_list_try_from_bytes_rejects_unknown_and_non_utf8_bytes`]
17233        // (b8f25d5) rejection witnesses.
17234        //
17235        // Non-UTF-8 candidates:
17236        //   - a lone 0xFF byte (never valid as a UTF-8 leading byte)
17237        //   - a lone 0x80 continuation byte with no leading byte
17238        //   - a truncated multi-byte sequence (0xC3 without its continuation)
17239        //   - a UTF-16 BOM-style byte pair the UTF-8 validator rejects
17240        //   - a UTF-16 surrogate half rejected by UTF-8
17241        let non_utf8_rejected: &[&[u8]] = &[
17242            &[0xFF],
17243            &[0x80],
17244            &[0xC3],
17245            &[0xFF, 0xFE],
17246            &[0xED, 0xA0, 0x80],
17247        ];
17248        for &input in non_utf8_rejected {
17249            assert_eq!(
17250                <RestartStrategy as TryFrom<&[u8]>>::try_from(input),
17251                Err(()),
17252                "TryFrom<&[u8]> impl on RestartStrategy must reject the \
17253                 non-UTF-8 byte-sequence {input:?} with Err(()) — \
17254                 silent acceptance signals the UTF-8 validation path \
17255                 collapsed onto a default arm rather than the trait-\
17256                 idiomatic unit-error"
17257            );
17258        }
17259        // Valid-UTF-8-but-unknown-wire candidates mirror the corpus
17260        // the sibling `restart_strategy_try_from_str_rejects_unknown_byte_strings`
17261        // (5b828ed) str-view rejection witness already pins on the
17262        // paired [`TryFrom<&str>`] axis: the empty byte-string,
17263        // whitespace-only padding, the kebab-case dispatcher-catalog
17264        // byte-strings on the sibling axis the pre-existing
17265        // [`std::str::FromStr`] impl the [`gen_platform::FromStrKind`]
17266        // derive installs parses onto (a caller who confuses the two
17267        // axes trips here rather than at a downstream K8s-CR round-
17268        // trip miss), lowercase / uppercase / mixed-case folds of each
17269        // `PascalCase` arm, whitespace-padded / trailing-newline /
17270        // quote-wrapped forms, and plausible-but-wrong English rebrand
17271        // candidates.
17272        let unknown_wire_rejected: &[&[u8]] = &[
17273            b"",
17274            b" ",
17275            b"\n",
17276            b"\t",
17277            b"one-for-one",
17278            b"one-for-all",
17279            b"rest-for-one",
17280            b"simple-one-for-one",
17281            b"oneforone",
17282            b"one_for_one",
17283            b"OneForOnes",
17284            b"ONEFORONE",
17285            b"oneforall",
17286            b"restforone",
17287            b"simpleoneforone",
17288            b"OneForOne ",
17289            b" OneForOne",
17290            b" OneForAll ",
17291            b"OneForOne\n",
17292            b"RestForOne\t",
17293            b"OneForEach",
17294            b"AllForOne",
17295            b"one for one",
17296            b"\"OneForOne\"",
17297            b"?",
17298        ];
17299        for &input in unknown_wire_rejected {
17300            assert_eq!(
17301                <RestartStrategy as TryFrom<&[u8]>>::try_from(input),
17302                Err(()),
17303                "TryFrom<&[u8]> impl on RestartStrategy must reject the \
17304                 valid-UTF-8-but-unknown-wire byte-string {input:?} \
17305                 with Err(()) — silent acceptance signals an accept-\
17306                 set widening off the paired RestartStrategy::from_wire \
17307                 resolver"
17308            );
17309            // Cross-axis witness: on a byte-string that is valid UTF-8,
17310            // the byte-view reverse-projection axis must agree with the
17311            // paired str-view reverse-projection axis
17312            // ([`TryFrom<&str>`]) — both route through the same
17313            // [`RestartStrategy::from_wire`] resolver, so the two
17314            // rejection paths align by construction.
17315            if let Ok(s) = std::str::from_utf8(input) {
17316                assert_eq!(
17317                    <RestartStrategy as TryFrom<&[u8]>>::try_from(input),
17318                    <RestartStrategy as TryFrom<&str>>::try_from(s),
17319                    "TryFrom<&[u8]> and TryFrom<&str> reverse-\
17320                     projection axes on RestartStrategy must agree on \
17321                     the valid-UTF-8 input {input:?} — divergence \
17322                     signals the two reverse paths have drifted off \
17323                     the same substrate-primitive from_wire accessor"
17324                );
17325            }
17326        }
17327    }
17328
17329    #[test]
17330    fn restart_strategy_try_from_vec_bytes_routes_through_borrowed_byte_view_axis() {
17331        // Fail-before-pass-after byte-parity pin on the newly lifted
17332        // `impl TryFrom<Vec<u8>> for RestartStrategy` — asserts the trait-
17333        // idiomatic owned-byte-vec reverse-projection standard-library
17334        // impl and the sibling borrowed-input [`TryFrom<&[u8]>`] axis
17335        // resolve to the same four-arm `PascalCase` wire accept-set
17336        // across every arm the exhaustive [`RestartStrategy::ALL`] slice
17337        // enumerates. Extends the substrate-wide trait-idiomatic byte-
17338        // owned reverse-projection axis onto the first M2-OTP-shape
17339        // supervisor-slot closed-set fieldless typed enum peer — owned-
17340        // input mirror of the paired [`TryFrom<&[u8]>`] byte-view
17341        // reverse-projection axis (c699a83), and byte-owned reverse
17342        // companion of the pre-existing byte-owned *forward*-projection
17343        // pair ([`From<RestartStrategy> for Vec<u8>`],
17344        // [`From<&RestartStrategy> for Vec<u8>`]) on this same enum.
17345        // Peer of the sibling first-mover
17346        // [`crate::kind::tests::caixa_kind_try_from_vec_bytes_routes_through_borrowed_byte_view_axis`]
17347        // (99c2849) on the [`crate::CaixaKind`] closed-set typed-enum
17348        // peer, the sibling second-mover
17349        // [`crate::dialeto::tests::caixa_dialeto_try_from_vec_bytes_routes_through_borrowed_byte_view_axis`]
17350        // (83a1526) on the [`crate::CaixaDialeto`] peer, and the sibling
17351        // third-mover
17352        // [`crate::dep::tests::dep_list_try_from_vec_bytes_routes_through_borrowed_byte_view_axis`]
17353        // (42091cb) on the [`crate::dep::DepList`] peer — tracks the
17354        // "delegate through `TryFrom<&[u8]>` on the `Vec<u8>::as_slice`
17355        // borrow" discipline the first-mover established.
17356        //
17357        // Rust's standard library carries no blanket
17358        // `impl<T: for<'a> TryFrom<&'a [u8]>> TryFrom<Vec<u8>> for T`,
17359        // so an owned-byte-vec caller otherwise picks between an open-
17360        // coded `<T as TryFrom<&[u8]>>::try_from(bytes.as_slice())` at
17361        // every call site whose type bounds have no compile-time link
17362        // back to the byte-owned reverse-projection axis, or a
17363        // `String::from_utf8(bytes)` two-hop shape whose error surface
17364        // leaks the standard-library `FromUtf8Error` type. This impl
17365        // closes the byte-owned reverse-projection axis at the
17366        // substrate-primitive [`RestartStrategy::from_wire`] accessor so
17367        // every future `<T: TryFrom<Vec<u8>>>`-bound owned-byte-vec
17368        // consumer reaches the same four-arm `PascalCase` wire accept-
17369        // set through one trait dispatch.
17370        for &variant in RestartStrategy::ALL {
17371            let wire_bytes: Vec<u8> = variant.as_str().as_bytes().to_vec();
17372            assert_eq!(
17373                <RestartStrategy as TryFrom<Vec<u8>>>::try_from(wire_bytes.clone()),
17374                Ok(variant),
17375                "TryFrom<Vec<u8>> impl on RestartStrategy must round-trip \
17376                 RestartStrategy::{variant:?}.as_str().as_bytes().to_vec() \
17377                 back to Ok(RestartStrategy::{variant:?}) — divergence \
17378                 from the sibling TryFrom<&[u8]> axis signals a silent \
17379                 detour off the substrate-primitive from_wire accessor"
17380            );
17381            // Cross-axis witness: the owned-byte-vec reverse-projection
17382            // axis must agree with the borrowed byte-slice reverse-
17383            // projection axis on every accepted arm — the two axes share
17384            // one `PascalCase` wire vocabulary through the substrate-
17385            // primitive `from_wire` accessor, and the owned-input axis
17386            // delegates to the borrowed peer by design.
17387            let via_owned: Result<RestartStrategy, ()> =
17388                <RestartStrategy as TryFrom<Vec<u8>>>::try_from(wire_bytes.clone());
17389            let via_borrowed: Result<RestartStrategy, ()> =
17390                <RestartStrategy as TryFrom<&[u8]>>::try_from(wire_bytes.as_slice());
17391            assert_eq!(
17392                via_owned, via_borrowed,
17393                "TryFrom<Vec<u8>> and TryFrom<&[u8]> reverse-projection \
17394                 axes on RestartStrategy must agree on \
17395                 RestartStrategy::{variant:?} — divergence signals the \
17396                 owned-input and borrowed-input byte-view reverse paths \
17397                 have drifted off the same substrate-primitive \
17398                 from_wire accessor"
17399            );
17400            // Cross-axis witness against the paired str-view reverse
17401            // axis ([`TryFrom<&str>`]) — the three reverse paths (str-
17402            // view, byte-view borrowed, byte-view owned) share one
17403            // substrate primitive.
17404            let via_str: Result<RestartStrategy, ()> =
17405                <RestartStrategy as TryFrom<&str>>::try_from(variant.as_str());
17406            assert_eq!(
17407                via_owned, via_str,
17408                "TryFrom<Vec<u8>> and TryFrom<&str> reverse-projection \
17409                 axes on RestartStrategy must agree on \
17410                 RestartStrategy::{variant:?} — divergence signals the \
17411                 byte-owned and str-view reverse paths have drifted off \
17412                 the same substrate-primitive from_wire accessor"
17413            );
17414            // Four-corner witness: because [`RestartStrategy`] carries
17415            // no wire-vs-diagnostic split (as_str and from_wire share
17416            // one `PascalCase` byte-vocabulary — unlike the sibling
17417            // [`crate::CaixaKind`] whose peer test deliberately declines
17418            // this witness), the byte-owned reverse-projection axis on
17419            // this enum *does* round-trip against the paired byte-owned
17420            // forward-projection pair. Pin every corner of the {owned-
17421            // input, borrowed-input} × {From<Self> → Vec<u8>,
17422            // From<&Self> → Vec<u8>} square onto the same Ok(variant)
17423            // return so a future accident that drops one corner off the
17424            // substrate-primitive accessor trips here.
17425            let owned_forward: Vec<u8> = <Vec<u8> as From<RestartStrategy>>::from(variant);
17426            let borrowed_forward: Vec<u8> = <Vec<u8> as From<&RestartStrategy>>::from(&variant);
17427            assert_eq!(
17428                owned_forward, wire_bytes,
17429                "From<RestartStrategy> for Vec<u8> forward projection on \
17430                 RestartStrategy::{variant:?} must byte-equal \
17431                 variant.as_str().as_bytes().to_vec() — divergence \
17432                 signals the paired forward pair drifted off the \
17433                 substrate-primitive as_str accessor"
17434            );
17435            assert_eq!(
17436                borrowed_forward, wire_bytes,
17437                "From<&RestartStrategy> for Vec<u8> forward projection \
17438                 on &RestartStrategy::{variant:?} must byte-equal \
17439                 variant.as_str().as_bytes().to_vec() — divergence \
17440                 signals the paired forward pair drifted off the \
17441                 substrate-primitive as_str accessor"
17442            );
17443            assert_eq!(
17444                <RestartStrategy as TryFrom<Vec<u8>>>::try_from(owned_forward.clone()),
17445                Ok(variant),
17446                "Four-corner round-trip on RestartStrategy::{variant:?} \
17447                 through From<RestartStrategy> for Vec<u8> then \
17448                 TryFrom<Vec<u8>> for RestartStrategy must return \
17449                 Ok(variant) — divergence signals the byte-owned \
17450                 forward pair and the byte-owned reverse axis have \
17451                 drifted apart"
17452            );
17453            assert_eq!(
17454                <RestartStrategy as TryFrom<Vec<u8>>>::try_from(borrowed_forward),
17455                Ok(variant),
17456                "Four-corner round-trip on RestartStrategy::{variant:?} \
17457                 through From<&RestartStrategy> for Vec<u8> then \
17458                 TryFrom<Vec<u8>> for RestartStrategy must return \
17459                 Ok(variant) — divergence signals the borrowed-input \
17460                 forward corner and the owned-input reverse corner have \
17461                 drifted apart"
17462            );
17463        }
17464    }
17465
17466    #[test]
17467    fn restart_strategy_try_from_vec_bytes_rejects_unknown_and_non_utf8_bytes() {
17468        // Rejection witness on the `impl TryFrom<Vec<u8>> for
17469        // RestartStrategy` — sweeps the same two rejection paths the
17470        // sibling borrowed `TryFrom<&[u8]>` axis collapses onto the
17471        // single unit-error return: the invalid-UTF-8 rejection path
17472        // (`std::str::from_utf8` on the underlying byte-slice returns
17473        // `Err` before [`RestartStrategy::from_wire`] runs) and the
17474        // valid-UTF-8-but-unknown-wire rejection path
17475        // ([`RestartStrategy::from_wire`] returns `None` on a byte-
17476        // string outside the four-arm `PascalCase` accept-set). Both
17477        // must reject so a future accidental widening of the trait
17478        // impl's accept-set (a case-fold path, a silent acceptance of
17479        // the kebab-case dispatcher-catalog byte-strings on this axis —
17480        // which would collide the two-axis wire/catalog split the
17481        // sibling [`RestartStrategy::from_wire`] doc block makes load-
17482        // bearing — a `#[serde(rename_all = "…")]` attribute drift that
17483        // widens the parse arm-set silently, a stray
17484        // `String::from_utf8_lossy` detour that widens the input
17485        // surface with the U+FFFD replacement character, an
17486        // `Option::unwrap_or_default`-shape fallback that maps invalid
17487        // UTF-8 onto a default arm rather than the trait-idiomatic
17488        // `Err(())`) trips at caixa-core test time. Peer of the sibling
17489        // first-mover
17490        // [`crate::kind::tests::caixa_kind_try_from_vec_bytes_rejects_unknown_and_non_utf8_bytes`]
17491        // (99c2849) on the [`crate::CaixaKind`] peer, the sibling
17492        // second-mover
17493        // [`crate::dialeto::tests::caixa_dialeto_try_from_vec_bytes_rejects_unknown_and_non_utf8_bytes`]
17494        // (83a1526) on the [`crate::CaixaDialeto`] peer, and the
17495        // sibling third-mover
17496        // [`crate::dep::tests::dep_list_try_from_vec_bytes_rejects_unknown_and_non_utf8_bytes`]
17497        // (42091cb) on the [`crate::dep::DepList`] peer rejection
17498        // witnesses.
17499        let non_utf8_rejected: &[&[u8]] = &[
17500            &[0xFF],
17501            &[0x80],
17502            &[0xC3],
17503            &[0xFF, 0xFE],
17504            &[0xED, 0xA0, 0x80], // UTF-16 surrogate half — rejected by UTF-8
17505        ];
17506        for &input in non_utf8_rejected {
17507            let owned: Vec<u8> = input.to_vec();
17508            assert_eq!(
17509                <RestartStrategy as TryFrom<Vec<u8>>>::try_from(owned),
17510                Err(()),
17511                "TryFrom<Vec<u8>> impl on RestartStrategy must reject \
17512                 the non-UTF-8 byte-sequence {input:?} with Err(()) — \
17513                 silent acceptance signals the UTF-8 validation path \
17514                 collapsed onto a default arm rather than the trait-\
17515                 idiomatic unit-error"
17516            );
17517            // Cross-axis witness: the owned-input axis must agree with
17518            // the borrowed-input axis on every rejected input.
17519            assert_eq!(
17520                <RestartStrategy as TryFrom<Vec<u8>>>::try_from(input.to_vec()),
17521                <RestartStrategy as TryFrom<&[u8]>>::try_from(input),
17522                "TryFrom<Vec<u8>> and TryFrom<&[u8]> reverse-projection \
17523                 axes on RestartStrategy must agree on the non-UTF-8 \
17524                 input {input:?} — divergence signals the owned-input \
17525                 and borrowed-input byte-view reverse paths have drifted \
17526                 off the same substrate-primitive from_wire accessor"
17527            );
17528        }
17529        // Valid-UTF-8-but-unknown-wire candidates mirror the corpus the
17530        // sibling borrowed-input rejection witness
17531        // [`restart_strategy_try_from_bytes_rejects_unknown_and_non_utf8_bytes`]
17532        // (c699a83) already pins on the paired byte-view axis: the
17533        // empty byte-string, whitespace-only padding, the kebab-case
17534        // dispatcher-catalog byte-strings on the sibling axis the pre-
17535        // existing [`std::str::FromStr`] impl the
17536        // [`gen_platform::FromStrKind`] derive installs parses onto (a
17537        // caller who confuses the two axes trips here rather than at a
17538        // downstream K8s-CR round-trip miss), lowercase / uppercase /
17539        // mixed-case folds of each `PascalCase` arm, whitespace-padded
17540        // / trailing-newline / quote-wrapped forms, and plausible-but-
17541        // wrong English rebrand candidates.
17542        let unknown_wire_rejected: &[&[u8]] = &[
17543            b"",
17544            b" ",
17545            b"\n",
17546            b"\t",
17547            b"one-for-one",
17548            b"one-for-all",
17549            b"rest-for-one",
17550            b"simple-one-for-one",
17551            b"oneforone",
17552            b"one_for_one",
17553            b"OneForOnes",
17554            b"ONEFORONE",
17555            b"oneforall",
17556            b"restforone",
17557            b"simpleoneforone",
17558            b"OneForOne ",
17559            b" OneForOne",
17560            b" OneForAll ",
17561            b"OneForOne\n",
17562            b"RestForOne\t",
17563            b"OneForEach",
17564            b"AllForOne",
17565            b"one for one",
17566            b"\"OneForOne\"",
17567            b"?",
17568        ];
17569        for &input in unknown_wire_rejected {
17570            let owned: Vec<u8> = input.to_vec();
17571            assert_eq!(
17572                <RestartStrategy as TryFrom<Vec<u8>>>::try_from(owned),
17573                Err(()),
17574                "TryFrom<Vec<u8>> impl on RestartStrategy must reject \
17575                 the valid-UTF-8-but-unknown-wire byte-string {input:?} \
17576                 with Err(()) — silent acceptance signals an accept-\
17577                 set widening off the paired RestartStrategy::from_wire \
17578                 resolver"
17579            );
17580            // Cross-axis witness against the borrowed byte-view axis:
17581            // the two paths must agree by construction, since the owned
17582            // axis delegates to the borrowed peer.
17583            assert_eq!(
17584                <RestartStrategy as TryFrom<Vec<u8>>>::try_from(input.to_vec()),
17585                <RestartStrategy as TryFrom<&[u8]>>::try_from(input),
17586                "TryFrom<Vec<u8>> and TryFrom<&[u8]> reverse-projection \
17587                 axes on RestartStrategy must agree on the valid-UTF-8-\
17588                 but-unknown-wire input {input:?} — divergence signals \
17589                 the owned-input and borrowed-input byte-view reverse \
17590                 paths have drifted off the same substrate-primitive \
17591                 from_wire accessor"
17592            );
17593        }
17594    }
17595
17596    #[test]
17597    fn restart_policy_try_from_bytes_routes_through_from_wire_accessor() {
17598        // Fail-before-pass-after byte-parity pin on the newly lifted
17599        // `impl TryFrom<&[u8]> for RestartPolicy` — asserts the trait-
17600        // idiomatic byte-view reverse-projection standard-library impl
17601        // and the substrate-primitive [`RestartPolicy::from_wire`]
17602        // `Option<Self>` accessor resolve to the same three-arm
17603        // `PascalCase` wire accept-set across every arm the exhaustive
17604        // [`RestartPolicy::ALL`] slice enumerates. Closes the substrate-
17605        // wide trait-idiomatic byte-view reverse-projection axis on the
17606        // M2-OTP-shape `:supervisor :estrategia` + `:children :restart`
17607        // slot pair the sibling [`RestartStrategy`] first-mover
17608        // (c699a83) opened one commit prior — mirror of the paired
17609        // [`TryFrom<&str> for RestartPolicy`] str-view reverse-
17610        // projection axis on the same enum, and the byte-view companion
17611        // of the pre-existing byte-owned reverse-projection family
17612        // ([`AsRef<[u8]>`], [`From<RestartPolicy> for Vec<u8>`],
17613        // [`From<&RestartPolicy> for Vec<u8>`]) on this same enum. Peer
17614        // of the sibling
17615        // [`restart_strategy_try_from_bytes_routes_through_from_wire_accessor`]
17616        // (c699a83),
17617        // [`crate::kind::tests::caixa_kind_try_from_bytes_routes_through_from_wire_accessor`]
17618        // (18d1940),
17619        // [`crate::dialeto::tests::caixa_dialeto_try_from_bytes_routes_through_from_wire_accessor`]
17620        // (d102cb8), and
17621        // [`crate::dep::tests::dep_list_try_from_bytes_routes_through_from_wire_accessor`]
17622        // (b8f25d5) — tracks the "route through `from_wire` via
17623        // `std::str::from_utf8`" discipline the first-mover established.
17624        //
17625        // Rust's standard library carries no blanket
17626        // `impl<T: for<'a> TryFrom<&'a str>> TryFrom<&[u8]> for T`, so a
17627        // two-hop composition through [`std::str::from_utf8`] + the
17628        // paired [`TryFrom<&str>`] axis is reachable through the pre-
17629        // existing str-view reverse-projection axis alone. But that
17630        // two-hop shape has no compile-time link back to the byte-view
17631        // reverse-projection axis, forces every downstream
17632        // `<T: for<'a> TryFrom<&'a [u8]>>`-bound consumer to open-code
17633        // the composition at every call site, and admits a silent split
17634        // whenever a future call site takes a sibling byte-projection
17635        // axis whose parse arm-set carries no compile-time byte-view
17636        // surface. This impl closes the byte-view reverse-projection
17637        // axis at the substrate-primitive [`RestartPolicy::from_wire`]
17638        // accessor so every future `<T: for<'a> TryFrom<&'a [u8]>>`-
17639        // bound consumer reaches the same three-arm `PascalCase` wire
17640        // accept-set through one trait dispatch.
17641        for &variant in RestartPolicy::ALL {
17642            let wire_bytes: &[u8] = variant.as_str().as_bytes();
17643            assert_eq!(
17644                <RestartPolicy as TryFrom<&[u8]>>::try_from(wire_bytes),
17645                Ok(variant),
17646                "TryFrom<&[u8]> impl on RestartPolicy must round-trip \
17647                 RestartPolicy::{variant:?}.as_str().as_bytes() back to \
17648                 Ok(RestartPolicy::{variant:?}) — divergence from \
17649                 RestartPolicy::from_wire signals a silent detour off \
17650                 the substrate-primitive accessor"
17651            );
17652            assert_eq!(
17653                <RestartPolicy as TryFrom<&[u8]>>::try_from(wire_bytes).ok(),
17654                RestartPolicy::from_wire(variant.as_str()),
17655                "TryFrom<&[u8]> ok()-projection on \
17656                 RestartPolicy::{variant:?}.as_str().as_bytes() must \
17657                 byte-equal RestartPolicy::from_wire on the paired \
17658                 &str input"
17659            );
17660            // Cross-axis witness: the byte-view reverse-projection axis
17661            // must agree with the paired str-view reverse-projection
17662            // axis ([`TryFrom<&str>`]) on every accepted arm — the two
17663            // reverse paths share one `PascalCase` accept-set through
17664            // the substrate-primitive `from_wire` accessor.
17665            let via_str: Result<RestartPolicy, ()> =
17666                <RestartPolicy as TryFrom<&str>>::try_from(variant.as_str());
17667            let via_bytes: Result<RestartPolicy, ()> =
17668                <RestartPolicy as TryFrom<&[u8]>>::try_from(wire_bytes);
17669            assert_eq!(
17670                via_bytes, via_str,
17671                "TryFrom<&[u8]> and TryFrom<&str> reverse-projection \
17672                 axes on RestartPolicy must agree on \
17673                 RestartPolicy::{variant:?} — divergence signals the \
17674                 byte-view and str-view reverse paths have drifted off \
17675                 the same substrate-primitive from_wire accessor"
17676            );
17677            // Forward/reverse byte-view cross-axis witness: feed the
17678            // paired [`AsRef<[u8]>`] byte-tail back through the new
17679            // impl and assert it round-trips to the originating arm.
17680            let via_asref: &[u8] = <RestartPolicy as AsRef<[u8]>>::as_ref(&variant);
17681            assert_eq!(
17682                <RestartPolicy as TryFrom<&[u8]>>::try_from(via_asref),
17683                Ok(variant),
17684                "TryFrom<&[u8]> ∘ AsRef<[u8]> must round-trip \
17685                 RestartPolicy::{variant:?} — divergence signals the \
17686                 forward and reverse byte-view axes have drifted off \
17687                 the same substrate-primitive as_str/from_wire pair"
17688            );
17689        }
17690    }
17691
17692    #[test]
17693    fn restart_policy_try_from_bytes_rejects_unknown_and_non_utf8_bytes() {
17694        // Rejection witness on the `impl TryFrom<&[u8]> for RestartPolicy`
17695        // — sweeps two rejection paths the byte-view reverse-projection
17696        // axis collapses onto the single unit-error `Err(())` return: the
17697        // invalid-UTF-8 rejection path ([`std::str::from_utf8`] returns
17698        // `Err` before [`RestartPolicy::from_wire`] runs) and the
17699        // valid-UTF-8-but-unknown-wire rejection path
17700        // ([`RestartPolicy::from_wire`] returns `None` on a byte-string
17701        // outside the three-arm `PascalCase` accept-set). Both must
17702        // reject, so a future accidental widening of the trait impl's
17703        // accept-set (a case-fold path, a silent acceptance of the
17704        // kebab-case dispatcher-catalog byte-strings on this axis — which
17705        // would collide the two-axis wire/catalog split the sibling
17706        // [`RestartPolicy::from_wire`] doc block makes load-bearing — a
17707        // `#[serde(rename_all = "…")]` attribute drift that widens the
17708        // parse arm-set silently, a stray fallback that maps invalid
17709        // UTF-8 onto a default arm rather than the trait-idiomatic
17710        // `Err(())`) trips at caixa-core test time. Peer of the sibling
17711        // [`restart_strategy_try_from_bytes_rejects_unknown_and_non_utf8_bytes`]
17712        // (c699a83),
17713        // [`crate::kind::tests::caixa_kind_try_from_bytes_rejects_unknown_and_non_utf8_bytes`]
17714        // (18d1940),
17715        // [`crate::dialeto::tests::caixa_dialeto_try_from_bytes_rejects_unknown_and_non_utf8_bytes`]
17716        // (d102cb8), and
17717        // [`crate::dep::tests::dep_list_try_from_bytes_rejects_unknown_and_non_utf8_bytes`]
17718        // (b8f25d5) rejection witnesses.
17719        //
17720        // Non-UTF-8 candidates:
17721        //   - a lone 0xFF byte (never valid as a UTF-8 leading byte)
17722        //   - a lone 0x80 continuation byte with no leading byte
17723        //   - a truncated multi-byte sequence (0xC3 without its continuation)
17724        //   - a UTF-16 BOM-style byte pair the UTF-8 validator rejects
17725        //   - a UTF-16 surrogate half rejected by UTF-8
17726        let non_utf8_rejected: &[&[u8]] = &[
17727            &[0xFF],
17728            &[0x80],
17729            &[0xC3],
17730            &[0xFF, 0xFE],
17731            &[0xED, 0xA0, 0x80],
17732        ];
17733        for &input in non_utf8_rejected {
17734            assert_eq!(
17735                <RestartPolicy as TryFrom<&[u8]>>::try_from(input),
17736                Err(()),
17737                "TryFrom<&[u8]> impl on RestartPolicy must reject the \
17738                 non-UTF-8 byte-sequence {input:?} with Err(()) — \
17739                 silent acceptance signals the UTF-8 validation path \
17740                 collapsed onto a default arm rather than the trait-\
17741                 idiomatic unit-error"
17742            );
17743        }
17744        // Valid-UTF-8-but-unknown-wire candidates mirror the corpus the
17745        // sibling `restart_policy_try_from_str_rejects_unknown_byte_strings`
17746        // str-view rejection witness already pins on the paired
17747        // [`TryFrom<&str>`] axis: the empty byte-string, whitespace-only
17748        // padding, the kebab-case dispatcher-catalog byte-strings on the
17749        // sibling axis the pre-existing [`std::str::FromStr`] impl the
17750        // [`gen_platform::FromStrKind`] derive installs parses onto (a
17751        // caller who confuses the two axes trips here rather than at a
17752        // downstream K8s-CR round-trip miss), lowercase / uppercase /
17753        // mixed-case folds of each `PascalCase` arm, whitespace-padded /
17754        // trailing-newline / quote-wrapped forms, and plausible-but-wrong
17755        // English rebrand candidates (`Ephemeral`, `Always`, `Never`,
17756        // `OnAbnormalExit`, `intrinsic`).
17757        let unknown_wire_rejected: &[&[u8]] = &[
17758            b"",
17759            b" ",
17760            b"\n",
17761            b"\t",
17762            b"permanent",
17763            b"temporary",
17764            b"transient",
17765            b"PERMANENT",
17766            b"TEMPORARY",
17767            b"TRANSIENT",
17768            b"Permanents",
17769            b"Permanent ",
17770            b" Permanent",
17771            b" Temporary ",
17772            b"Permanent\n",
17773            b"Transient\t",
17774            b"\"Permanent\"",
17775            b"Ephemeral",
17776            b"Always",
17777            b"Never",
17778            b"OnAbnormalExit",
17779            b"intrinsic",
17780            b"?",
17781        ];
17782        for &input in unknown_wire_rejected {
17783            assert_eq!(
17784                <RestartPolicy as TryFrom<&[u8]>>::try_from(input),
17785                Err(()),
17786                "TryFrom<&[u8]> impl on RestartPolicy must reject the \
17787                 valid-UTF-8-but-unknown-wire byte-string {input:?} \
17788                 with Err(()) — silent acceptance signals an accept-\
17789                 set widening off the paired RestartPolicy::from_wire \
17790                 resolver"
17791            );
17792            // Cross-axis witness: on a byte-string that is valid UTF-8,
17793            // the byte-view reverse-projection axis must agree with the
17794            // paired str-view reverse-projection axis
17795            // ([`TryFrom<&str>`]) — both route through the same
17796            // [`RestartPolicy::from_wire`] resolver, so the two
17797            // rejection paths align by construction.
17798            if let Ok(s) = std::str::from_utf8(input) {
17799                assert_eq!(
17800                    <RestartPolicy as TryFrom<&[u8]>>::try_from(input),
17801                    <RestartPolicy as TryFrom<&str>>::try_from(s),
17802                    "TryFrom<&[u8]> and TryFrom<&str> reverse-\
17803                     projection axes on RestartPolicy must agree on \
17804                     the valid-UTF-8 input {input:?} — divergence \
17805                     signals the two reverse paths have drifted off \
17806                     the same substrate-primitive from_wire accessor"
17807                );
17808            }
17809        }
17810    }
17811
17812    #[test]
17813    fn supervisor_scalar_ctors_are_const_zero_runtime_work() {
17814        // Const-eval pin: the [`supervisor_scalar_ctors!`] macro spells every
17815        // generated ctor `const fn` so a caller can pin a `SupervisorError`
17816        // at compile time — the same zero-runtime-work property the pre-lift
17817        // `|<slot>| SupervisorError::<Variant> { <slot> }` closure carried on
17818        // its `Copy`-pass-through construction path (no `.to_string()` /
17819        // `.into()` allocation, no branching). If any future edit silently
17820        // drops the `const` qualifier from the macro body the per-arm `const`
17821        // bindings below fail to compile, which surfaces the regression at
17822        // the substrate-primitive definition rather than at some downstream
17823        // consumer that had come to rely on the `const`-constructibility.
17824        // Peer of the sibling
17825        // `aplicacao_policy_scalar_ctors_are_const_zero_runtime_work`
17826        // (7ef425e) const-eval pin on the peer `AplicacaoError` envelope's
17827        // per-`:politicas` per-axis ctor family.
17828        const NO_CHILDREN: SupervisorError =
17829            SupervisorError::no_children(RestartStrategy::OneForAll);
17830        const MAX_RESTARTS_CAP: SupervisorError = SupervisorError::max_restarts_exceeds_cap(1_337);
17831        const WINDOW_NC: SupervisorError =
17832            SupervisorError::restart_window_not_canonical(Duration::from_micros(1));
17833        const WINDOW_CAP: SupervisorError =
17834            SupervisorError::restart_window_exceeds_cap(Duration::from_secs(3_601));
17835        assert!(matches!(NO_CHILDREN, SupervisorError::NoChildren { .. }));
17836        assert!(matches!(
17837            MAX_RESTARTS_CAP,
17838            SupervisorError::MaxRestartsExceedsCap { .. }
17839        ));
17840        assert!(matches!(
17841            WINDOW_NC,
17842            SupervisorError::RestartWindowNotCanonical { .. }
17843        ));
17844        assert!(matches!(
17845            WINDOW_CAP,
17846            SupervisorError::RestartWindowExceedsCap { .. }
17847        ));
17848    }
17849
17850    #[test]
17851    fn restart_policy_try_from_vec_bytes_routes_through_borrowed_byte_view_axis() {
17852        // Fail-before-pass-after byte-parity pin on the newly lifted
17853        // `impl TryFrom<Vec<u8>> for RestartPolicy` — asserts the trait-
17854        // idiomatic owned-byte-vec reverse-projection standard-library
17855        // impl and the sibling borrowed-input [`TryFrom<&[u8]>`] axis
17856        // resolve to the same three-arm `PascalCase` wire accept-set
17857        // across every arm the exhaustive [`RestartPolicy::ALL`] slice
17858        // enumerates. Closes the substrate-wide trait-idiomatic byte-
17859        // owned reverse-projection axis on the M2-OTP-shape
17860        // `:supervisor :estrategia` + `:children :restart` slot pair the
17861        // sibling [`RestartStrategy`] first-mover
17862        // [`restart_strategy_try_from_vec_bytes_routes_through_borrowed_byte_view_axis`]
17863        // (34951fe) opened one commit-window prior — owned-input mirror
17864        // of the paired [`TryFrom<&[u8]>`] byte-view reverse-projection
17865        // axis on this same enum (d9ef5f0), and byte-owned reverse
17866        // companion of the pre-existing byte-owned *forward*-projection
17867        // pair ([`From<RestartPolicy> for Vec<u8>`],
17868        // [`From<&RestartPolicy> for Vec<u8>`]) on this same enum. Peer
17869        // of the sibling first-mover
17870        // [`crate::kind::tests::caixa_kind_try_from_vec_bytes_routes_through_borrowed_byte_view_axis`]
17871        // (99c2849) on the [`crate::CaixaKind`] closed-set typed-enum
17872        // peer, the sibling second-mover
17873        // [`crate::dialeto::tests::caixa_dialeto_try_from_vec_bytes_routes_through_borrowed_byte_view_axis`]
17874        // (83a1526) on the [`crate::CaixaDialeto`] peer, the sibling
17875        // third-mover
17876        // [`crate::dep::tests::dep_list_try_from_vec_bytes_routes_through_borrowed_byte_view_axis`]
17877        // (42091cb) on the [`crate::dep::DepList`] peer, and the sibling
17878        // fourth-mover
17879        // [`restart_strategy_try_from_vec_bytes_routes_through_borrowed_byte_view_axis`]
17880        // (34951fe) on the [`RestartStrategy`] peer — tracks the
17881        // "delegate through `TryFrom<&[u8]>` on the `Vec<u8>::as_slice`
17882        // borrow" discipline the first-mover established.
17883        //
17884        // Rust's standard library carries no blanket
17885        // `impl<T: for<'a> TryFrom<&'a [u8]>> TryFrom<Vec<u8>> for T`,
17886        // so an owned-byte-vec caller otherwise picks between an open-
17887        // coded `<T as TryFrom<&[u8]>>::try_from(bytes.as_slice())` at
17888        // every call site whose type bounds have no compile-time link
17889        // back to the byte-owned reverse-projection axis, or a
17890        // `String::from_utf8(bytes)` two-hop shape whose error surface
17891        // leaks the standard-library `FromUtf8Error` type. This impl
17892        // closes the byte-owned reverse-projection axis at the
17893        // substrate-primitive [`RestartPolicy::from_wire`] accessor so
17894        // every future `<T: TryFrom<Vec<u8>>>`-bound owned-byte-vec
17895        // consumer reaches the same three-arm `PascalCase` wire accept-
17896        // set through one trait dispatch.
17897        for &variant in RestartPolicy::ALL {
17898            let wire_bytes: Vec<u8> = variant.as_str().as_bytes().to_vec();
17899            assert_eq!(
17900                <RestartPolicy as TryFrom<Vec<u8>>>::try_from(wire_bytes.clone()),
17901                Ok(variant),
17902                "TryFrom<Vec<u8>> impl on RestartPolicy must round-trip \
17903                 RestartPolicy::{variant:?}.as_str().as_bytes().to_vec() \
17904                 back to Ok(RestartPolicy::{variant:?}) — divergence \
17905                 from the sibling TryFrom<&[u8]> axis signals a silent \
17906                 detour off the substrate-primitive from_wire accessor"
17907            );
17908            // Cross-axis witness: the owned-byte-vec reverse-projection
17909            // axis must agree with the borrowed byte-slice reverse-
17910            // projection axis on every accepted arm — the two axes share
17911            // one `PascalCase` wire vocabulary through the substrate-
17912            // primitive `from_wire` accessor, and the owned-input axis
17913            // delegates to the borrowed peer by design.
17914            let via_owned: Result<RestartPolicy, ()> =
17915                <RestartPolicy as TryFrom<Vec<u8>>>::try_from(wire_bytes.clone());
17916            let via_borrowed: Result<RestartPolicy, ()> =
17917                <RestartPolicy as TryFrom<&[u8]>>::try_from(wire_bytes.as_slice());
17918            assert_eq!(
17919                via_owned, via_borrowed,
17920                "TryFrom<Vec<u8>> and TryFrom<&[u8]> reverse-projection \
17921                 axes on RestartPolicy must agree on \
17922                 RestartPolicy::{variant:?} — divergence signals the \
17923                 owned-input and borrowed-input byte-view reverse paths \
17924                 have drifted off the same substrate-primitive \
17925                 from_wire accessor"
17926            );
17927            // Cross-axis witness against the paired str-view reverse
17928            // axis ([`TryFrom<&str>`]) — the three reverse paths (str-
17929            // view, byte-view borrowed, byte-view owned) share one
17930            // substrate primitive.
17931            let via_str: Result<RestartPolicy, ()> =
17932                <RestartPolicy as TryFrom<&str>>::try_from(variant.as_str());
17933            assert_eq!(
17934                via_owned, via_str,
17935                "TryFrom<Vec<u8>> and TryFrom<&str> reverse-projection \
17936                 axes on RestartPolicy must agree on \
17937                 RestartPolicy::{variant:?} — divergence signals the \
17938                 byte-owned and str-view reverse paths have drifted off \
17939                 the same substrate-primitive from_wire accessor"
17940            );
17941            // Four-corner witness: because [`RestartPolicy`] carries
17942            // no wire-vs-diagnostic split (as_str and from_wire share
17943            // one `PascalCase` byte-vocabulary — like the sibling
17944            // [`RestartStrategy`] and unlike the sibling
17945            // [`crate::CaixaKind`] whose peer test deliberately declines
17946            // this witness), the byte-owned reverse-projection axis on
17947            // this enum *does* round-trip against the paired byte-owned
17948            // forward-projection pair. Pin every corner of the {owned-
17949            // input, borrowed-input} × {From<Self> → Vec<u8>,
17950            // From<&Self> → Vec<u8>} square onto the same Ok(variant)
17951            // return so a future accident that drops one corner off the
17952            // substrate-primitive accessor trips here.
17953            let owned_forward: Vec<u8> = <Vec<u8> as From<RestartPolicy>>::from(variant);
17954            let borrowed_forward: Vec<u8> = <Vec<u8> as From<&RestartPolicy>>::from(&variant);
17955            assert_eq!(
17956                owned_forward, wire_bytes,
17957                "From<RestartPolicy> for Vec<u8> forward projection on \
17958                 RestartPolicy::{variant:?} must byte-equal \
17959                 variant.as_str().as_bytes().to_vec() — divergence \
17960                 signals the paired forward pair drifted off the \
17961                 substrate-primitive as_str accessor"
17962            );
17963            assert_eq!(
17964                borrowed_forward, wire_bytes,
17965                "From<&RestartPolicy> for Vec<u8> forward projection \
17966                 on &RestartPolicy::{variant:?} must byte-equal \
17967                 variant.as_str().as_bytes().to_vec() — divergence \
17968                 signals the paired forward pair drifted off the \
17969                 substrate-primitive as_str accessor"
17970            );
17971            assert_eq!(
17972                <RestartPolicy as TryFrom<Vec<u8>>>::try_from(owned_forward.clone()),
17973                Ok(variant),
17974                "Four-corner round-trip on RestartPolicy::{variant:?} \
17975                 through From<RestartPolicy> for Vec<u8> then \
17976                 TryFrom<Vec<u8>> for RestartPolicy must return \
17977                 Ok(variant) — divergence signals the byte-owned \
17978                 forward pair and the byte-owned reverse axis have \
17979                 drifted apart"
17980            );
17981            assert_eq!(
17982                <RestartPolicy as TryFrom<Vec<u8>>>::try_from(borrowed_forward),
17983                Ok(variant),
17984                "Four-corner round-trip on RestartPolicy::{variant:?} \
17985                 through From<&RestartPolicy> for Vec<u8> then \
17986                 TryFrom<Vec<u8>> for RestartPolicy must return \
17987                 Ok(variant) — divergence signals the borrowed-input \
17988                 forward corner and the owned-input reverse corner have \
17989                 drifted apart"
17990            );
17991        }
17992    }
17993
17994    #[test]
17995    fn restart_policy_try_from_vec_bytes_rejects_unknown_and_non_utf8_bytes() {
17996        // Rejection witness on the `impl TryFrom<Vec<u8>> for
17997        // RestartPolicy` — sweeps the same two rejection paths the
17998        // sibling borrowed `TryFrom<&[u8]>` axis collapses onto the
17999        // single unit-error return: the invalid-UTF-8 rejection path
18000        // (`std::str::from_utf8` on the underlying byte-slice returns
18001        // `Err` before [`RestartPolicy::from_wire`] runs) and the
18002        // valid-UTF-8-but-unknown-wire rejection path
18003        // ([`RestartPolicy::from_wire`] returns `None` on a byte-
18004        // string outside the three-arm `PascalCase` accept-set). Both
18005        // must reject so a future accidental widening of the trait
18006        // impl's accept-set (a case-fold path, a silent acceptance of
18007        // the kebab-case dispatcher-catalog byte-strings on this axis —
18008        // which would collide the two-axis wire/catalog split the
18009        // sibling [`RestartPolicy::from_wire`] doc block makes load-
18010        // bearing — a `#[serde(rename_all = "…")]` attribute drift that
18011        // widens the parse arm-set silently, a stray
18012        // `String::from_utf8_lossy` detour that widens the input
18013        // surface with the U+FFFD replacement character, an
18014        // `Option::unwrap_or_default`-shape fallback that maps invalid
18015        // UTF-8 onto a default arm rather than the trait-idiomatic
18016        // `Err(())`) trips at caixa-core test time. Peer of the sibling
18017        // first-mover
18018        // [`crate::kind::tests::caixa_kind_try_from_vec_bytes_rejects_unknown_and_non_utf8_bytes`]
18019        // (99c2849) on the [`crate::CaixaKind`] peer, the sibling
18020        // second-mover
18021        // [`crate::dialeto::tests::caixa_dialeto_try_from_vec_bytes_rejects_unknown_and_non_utf8_bytes`]
18022        // (83a1526) on the [`crate::CaixaDialeto`] peer, the sibling
18023        // third-mover
18024        // [`crate::dep::tests::dep_list_try_from_vec_bytes_rejects_unknown_and_non_utf8_bytes`]
18025        // (42091cb) on the [`crate::dep::DepList`] peer, and the
18026        // sibling fourth-mover
18027        // [`restart_strategy_try_from_vec_bytes_rejects_unknown_and_non_utf8_bytes`]
18028        // (34951fe) on the [`RestartStrategy`] peer rejection
18029        // witnesses.
18030        let non_utf8_rejected: &[&[u8]] = &[
18031            &[0xFF],
18032            &[0x80],
18033            &[0xC3],
18034            &[0xFF, 0xFE],
18035            &[0xED, 0xA0, 0x80], // UTF-16 surrogate half — rejected by UTF-8
18036        ];
18037        for &input in non_utf8_rejected {
18038            let owned: Vec<u8> = input.to_vec();
18039            assert_eq!(
18040                <RestartPolicy as TryFrom<Vec<u8>>>::try_from(owned),
18041                Err(()),
18042                "TryFrom<Vec<u8>> impl on RestartPolicy must reject \
18043                 the non-UTF-8 byte-sequence {input:?} with Err(()) — \
18044                 silent acceptance signals the UTF-8 validation path \
18045                 collapsed onto a default arm rather than the trait-\
18046                 idiomatic unit-error"
18047            );
18048            // Cross-axis witness: the owned-input axis must agree with
18049            // the borrowed-input axis on every rejected input.
18050            assert_eq!(
18051                <RestartPolicy as TryFrom<Vec<u8>>>::try_from(input.to_vec()),
18052                <RestartPolicy as TryFrom<&[u8]>>::try_from(input),
18053                "TryFrom<Vec<u8>> and TryFrom<&[u8]> reverse-projection \
18054                 axes on RestartPolicy must agree on the non-UTF-8 \
18055                 input {input:?} — divergence signals the owned-input \
18056                 and borrowed-input byte-view reverse paths have drifted \
18057                 off the same substrate-primitive from_wire accessor"
18058            );
18059        }
18060        // Valid-UTF-8-but-unknown-wire candidates mirror the corpus the
18061        // sibling borrowed-input rejection witness
18062        // [`restart_policy_try_from_bytes_rejects_unknown_and_non_utf8_bytes`]
18063        // (d9ef5f0) already pins on the paired byte-view axis: the
18064        // empty byte-string, whitespace-only padding, the kebab-case
18065        // dispatcher-catalog byte-strings on the sibling axis the pre-
18066        // existing [`std::str::FromStr`] impl the
18067        // [`gen_platform::FromStrKind`] derive installs parses onto (a
18068        // caller who confuses the two axes trips here rather than at a
18069        // downstream K8s-CR round-trip miss), lowercase / uppercase /
18070        // mixed-case folds of each `PascalCase` arm, whitespace-padded /
18071        // trailing-newline / quote-wrapped forms, and plausible-but-
18072        // wrong English rebrand candidates (`Ephemeral`, `Always`,
18073        // `Never`, `OnAbnormalExit`, `intrinsic`).
18074        let unknown_wire_rejected: &[&[u8]] = &[
18075            b"",
18076            b" ",
18077            b"\n",
18078            b"\t",
18079            b"permanent",
18080            b"temporary",
18081            b"transient",
18082            b"PERMANENT",
18083            b"TEMPORARY",
18084            b"TRANSIENT",
18085            b"Permanents",
18086            b"Permanent ",
18087            b" Permanent",
18088            b" Temporary ",
18089            b"Permanent\n",
18090            b"Transient\t",
18091            b"\"Permanent\"",
18092            b"Ephemeral",
18093            b"Always",
18094            b"Never",
18095            b"OnAbnormalExit",
18096            b"intrinsic",
18097            b"?",
18098        ];
18099        for &input in unknown_wire_rejected {
18100            let owned: Vec<u8> = input.to_vec();
18101            assert_eq!(
18102                <RestartPolicy as TryFrom<Vec<u8>>>::try_from(owned),
18103                Err(()),
18104                "TryFrom<Vec<u8>> impl on RestartPolicy must reject \
18105                 the valid-UTF-8-but-unknown-wire byte-string {input:?} \
18106                 with Err(()) — silent acceptance signals an accept-\
18107                 set widening off the paired RestartPolicy::from_wire \
18108                 resolver"
18109            );
18110            // Cross-axis witness against the borrowed byte-view axis:
18111            // the two paths must agree by construction, since the owned
18112            // axis delegates to the borrowed peer.
18113            assert_eq!(
18114                <RestartPolicy as TryFrom<Vec<u8>>>::try_from(input.to_vec()),
18115                <RestartPolicy as TryFrom<&[u8]>>::try_from(input),
18116                "TryFrom<Vec<u8>> and TryFrom<&[u8]> reverse-projection \
18117                 axes on RestartPolicy must agree on the valid-UTF-8-\
18118                 but-unknown-wire input {input:?} — divergence signals \
18119                 the owned-input and borrowed-input byte-view reverse \
18120                 paths have drifted off the same substrate-primitive \
18121                 from_wire accessor"
18122            );
18123        }
18124    }
18125
18126    #[test]
18127    fn restart_strategy_try_from_owned_string_routes_through_borrowed_str_view_axis() {
18128        // Fail-before-pass-after byte-parity pin on the newly lifted
18129        // `impl TryFrom<String> for RestartStrategy` — asserts the
18130        // trait-idiomatic string-owned reverse-projection standard-
18131        // library impl and the sibling borrowed-input [`TryFrom<&str>`]
18132        // axis resolve to the same four-arm `PascalCase` wire accept-set
18133        // across every arm the exhaustive [`RestartStrategy::ALL`] slice
18134        // enumerates. Extends the substrate-wide trait-idiomatic string-
18135        // owned reverse-projection axis onto the first M2-OTP-shape
18136        // supervisor-slot closed-set fieldless typed-enum peer — owned-
18137        // input mirror of the paired [`TryFrom<&str>`] str-view reverse-
18138        // projection axis, and string-owned reverse companion of the
18139        // pre-existing string-owned *forward*-projection pair
18140        // ([`From<RestartStrategy> for String`],
18141        // [`From<&RestartStrategy> for String`]) on this same enum. Peer
18142        // of the sibling opener
18143        // [`crate::aplicacao::tests::rate_limit_try_from_owned_string_routes_through_borrowed_str_view_axis`]
18144        // (a2e6f02) on the compound [`crate::aplicacao::RateLimit`]
18145        // primitive, the sibling first-mover
18146        // [`crate::aplicacao::tests::wit_shape_try_from_owned_string_routes_through_borrowed_str_view_axis`]
18147        // (e6aac29) on the [`crate::aplicacao::WitShape`] closed-set peer,
18148        // the sibling second-mover
18149        // [`crate::aplicacao::tests::rate_limit_unit_try_from_owned_string_routes_through_borrowed_str_view_axis`]
18150        // (94a9c5e) on the [`crate::aplicacao::RateLimitUnit`] peer, and
18151        // the sibling third-mover
18152        // [`crate::aplicacao::tests::placement_strategy_try_from_owned_string_routes_through_borrowed_str_view_axis`]
18153        // (d81a70a) on the [`crate::aplicacao::PlacementStrategy`] peer —
18154        // tracks the "delegate through `TryFrom<&str>` on the
18155        // `String::as_str` borrow" discipline the compound-primitive
18156        // opener and closed-set-peer first-mover established.
18157        //
18158        // Rust's standard library carries no blanket
18159        // `impl<T: for<'a> TryFrom<&'a str>> TryFrom<String> for T`, so
18160        // an owned-`String` caller otherwise picks between an open-coded
18161        // `<T as TryFrom<&str>>::try_from(s.as_str())` at every call
18162        // site (whose type bounds have no compile-time link back to the
18163        // string-owned reverse-projection axis) or a `let s: &str = &s;
18164        // T::try_from(s)` two-step whose borrow arithmetic leaks a per-
18165        // call-site lifetime dance. This impl closes the string-owned
18166        // reverse-projection axis at the substrate-primitive
18167        // [`RestartStrategy::from_wire`] accessor so every future
18168        // `<T: TryFrom<String>>`-bound owned-string consumer reaches the
18169        // same four-arm `PascalCase` accept-set through one trait
18170        // dispatch.
18171        for &variant in RestartStrategy::ALL {
18172            let wire_string: String = variant.as_str().to_string();
18173            assert_eq!(
18174                <RestartStrategy as TryFrom<String>>::try_from(wire_string.clone()),
18175                Ok(variant),
18176                "TryFrom<String> impl on RestartStrategy must round-trip \
18177                 RestartStrategy::{variant:?}.as_str().to_string() back \
18178                 to Ok(RestartStrategy::{variant:?}) — divergence from \
18179                 the sibling TryFrom<&str> axis signals a silent detour \
18180                 off the substrate-primitive from_wire accessor"
18181            );
18182            // Cross-axis witness: the string-owned reverse-projection
18183            // axis must agree with the borrowed `&str` reverse-projection
18184            // axis on every accepted arm — the two axes share one
18185            // `PascalCase` wire vocabulary through the substrate-primitive
18186            // `from_wire` accessor, and the owned-input axis delegates to
18187            // the borrowed peer by design.
18188            let via_owned: Result<RestartStrategy, ()> =
18189                <RestartStrategy as TryFrom<String>>::try_from(wire_string.clone());
18190            let via_borrowed: Result<RestartStrategy, ()> =
18191                <RestartStrategy as TryFrom<&str>>::try_from(wire_string.as_str());
18192            assert_eq!(
18193                via_owned, via_borrowed,
18194                "TryFrom<String> and TryFrom<&str> reverse-projection \
18195                 axes on RestartStrategy must agree on \
18196                 RestartStrategy::{variant:?} — divergence signals the \
18197                 owned-`String` and borrowed-`&str` reverse paths have \
18198                 drifted off the same substrate-primitive from_wire \
18199                 accessor"
18200            );
18201            // Cross-axis witness against the paired byte-view and byte-
18202            // owned reverse axes — the four reverse paths (str-view
18203            // borrowed, string-owned, byte-view borrowed, byte-owned)
18204            // share one substrate primitive.
18205            let via_bytes_borrowed: Result<RestartStrategy, ()> =
18206                <RestartStrategy as TryFrom<&[u8]>>::try_from(wire_string.as_bytes());
18207            let via_bytes_owned: Result<RestartStrategy, ()> =
18208                <RestartStrategy as TryFrom<Vec<u8>>>::try_from(wire_string.as_bytes().to_vec());
18209            assert_eq!(
18210                via_owned, via_bytes_borrowed,
18211                "TryFrom<String> and TryFrom<&[u8]> reverse-projection \
18212                 axes on RestartStrategy must agree on \
18213                 RestartStrategy::{variant:?} — divergence signals the \
18214                 string-owned and byte-view reverse paths have drifted \
18215                 off the same substrate-primitive from_wire accessor"
18216            );
18217            assert_eq!(
18218                via_owned, via_bytes_owned,
18219                "TryFrom<String> and TryFrom<Vec<u8>> reverse-projection \
18220                 axes on RestartStrategy must agree on \
18221                 RestartStrategy::{variant:?} — divergence signals the \
18222                 string-owned and byte-owned reverse paths have drifted \
18223                 off the same substrate-primitive from_wire accessor"
18224            );
18225            // Closed-cycle witness against the paired string-owned
18226            // forward-projection pair: `Self → String → TryFrom<String>
18227            // → Self` round-trips to the originating arm on every
18228            // canonical `PascalCase` scalar. Both the owned-input
18229            // `From<RestartStrategy> for String` and the borrowed-input
18230            // `From<&RestartStrategy> for String` corners must feed back
18231            // through the new impl to `Ok(variant)`.
18232            let owned_forward: String = <String as From<RestartStrategy>>::from(variant);
18233            let borrowed_forward: String = <String as From<&RestartStrategy>>::from(&variant);
18234            assert_eq!(
18235                owned_forward, wire_string,
18236                "From<RestartStrategy> for String forward projection on \
18237                 RestartStrategy::{variant:?} must byte-equal \
18238                 variant.as_str().to_string() — divergence signals the \
18239                 paired forward pair drifted off the substrate-primitive \
18240                 as_str accessor"
18241            );
18242            assert_eq!(
18243                borrowed_forward, wire_string,
18244                "From<&RestartStrategy> for String forward projection on \
18245                 &RestartStrategy::{variant:?} must byte-equal \
18246                 variant.as_str().to_string() — divergence signals the \
18247                 paired forward pair drifted off the substrate-primitive \
18248                 as_str accessor"
18249            );
18250            assert_eq!(
18251                <RestartStrategy as TryFrom<String>>::try_from(owned_forward.clone()),
18252                Ok(variant),
18253                "Closed-cycle round-trip on RestartStrategy::{variant:?} \
18254                 through From<RestartStrategy> for String then \
18255                 TryFrom<String> for RestartStrategy must return \
18256                 Ok(variant) — divergence signals the string-owned \
18257                 forward pair and the string-owned reverse axis have \
18258                 drifted apart"
18259            );
18260            assert_eq!(
18261                <RestartStrategy as TryFrom<String>>::try_from(borrowed_forward),
18262                Ok(variant),
18263                "Closed-cycle round-trip on RestartStrategy::{variant:?} \
18264                 through From<&RestartStrategy> for String then \
18265                 TryFrom<String> for RestartStrategy must return \
18266                 Ok(variant) — divergence signals the borrowed-input \
18267                 forward corner and the owned-input string reverse \
18268                 corner have drifted apart"
18269            );
18270        }
18271    }
18272
18273    #[test]
18274    fn restart_strategy_try_from_owned_string_rejects_unknown_wire_strings() {
18275        // Rejection witness on the `impl TryFrom<String> for
18276        // RestartStrategy` — sweeps the corpus of valid-UTF-8-but-
18277        // unknown-wire byte-strings the sibling borrowed [`TryFrom<&str>`]
18278        // axis already rejects and asserts every one lands on `Err(())`,
18279        // so a future accidental widening of the trait impl's accept-set
18280        // (a case-fold path, a silent inclusion of the kebab-case
18281        // dispatcher-catalog byte-strings on the sibling axis that would
18282        // collide the two-axis wire/catalog split the sibling
18283        // [`RestartStrategy::from_wire`] doc block makes load-bearing, a
18284        // stray fallback that maps whitespace-padded canonical scalars
18285        // onto their unpadded arm rather than the trait-idiomatic
18286        // `Err(())`) trips at caixa-core test time. Peer of the sibling
18287        // borrowed-input rejection witness
18288        // [`restart_strategy_try_from_str_rejects_unknown_byte_strings`]
18289        // on the same enum, and the sibling byte-view / byte-owned
18290        // rejection witnesses
18291        // [`restart_strategy_try_from_bytes_rejects_unknown_and_non_utf8_bytes`]
18292        // (c699a83) /
18293        // [`restart_strategy_try_from_vec_bytes_rejects_unknown_and_non_utf8_bytes`]
18294        // (34951fe) on the same enum.
18295        let unknown_wire_rejected: &[&str] = &[
18296            "",
18297            " ",
18298            "\n",
18299            "\t",
18300            "one-for-one",
18301            "one-for-all",
18302            "rest-for-one",
18303            "simple-one-for-one",
18304            "oneforone",
18305            "one_for_one",
18306            "OneForOnes",
18307            "ONEFORONE",
18308            "oneforall",
18309            "restforone",
18310            "simpleoneforone",
18311            "OneForOne ",
18312            " OneForOne",
18313            " OneForAll ",
18314            "OneForOne\n",
18315            "RestForOne\t",
18316            "OneForEach",
18317            "AllForOne",
18318            "one for one",
18319            "\"OneForOne\"",
18320            "?",
18321        ];
18322        for &input in unknown_wire_rejected {
18323            let owned: String = input.to_string();
18324            assert_eq!(
18325                <RestartStrategy as TryFrom<String>>::try_from(owned),
18326                Err(()),
18327                "TryFrom<String> impl on RestartStrategy must reject the \
18328                 valid-UTF-8-but-unknown-wire byte-string {input:?} with \
18329                 Err(()) — silent acceptance signals an accept-set \
18330                 widening off the paired RestartStrategy::from_wire \
18331                 resolver"
18332            );
18333            // Cross-axis witness against the borrowed str-view axis:
18334            // the two paths must agree by construction, since the owned
18335            // axis delegates to the borrowed peer.
18336            assert_eq!(
18337                <RestartStrategy as TryFrom<String>>::try_from(input.to_string()),
18338                <RestartStrategy as TryFrom<&str>>::try_from(input),
18339                "TryFrom<String> and TryFrom<&str> reverse-projection \
18340                 axes on RestartStrategy must agree on the valid-UTF-8-\
18341                 but-unknown-wire input {input:?} — divergence signals \
18342                 the owned-`String` and borrowed-`&str` reverse paths \
18343                 have drifted off the same substrate-primitive from_wire \
18344                 accessor"
18345            );
18346        }
18347    }
18348
18349    #[test]
18350    fn restart_policy_try_from_owned_string_routes_through_borrowed_str_view_axis() {
18351        // Fail-before-pass-after byte-parity pin on the newly lifted
18352        // `impl TryFrom<String> for RestartPolicy` — asserts the trait-
18353        // idiomatic string-owned reverse-projection standard-library impl
18354        // and the sibling borrowed-input [`TryFrom<&str>`] axis resolve
18355        // to the same three-arm `PascalCase` wire accept-set across every
18356        // arm the exhaustive [`RestartPolicy::ALL`] slice enumerates.
18357        // Extends the substrate-wide trait-idiomatic string-owned reverse-
18358        // projection axis onto the second (and final) M2-OTP-shape
18359        // supervisor-slot closed-set fieldless typed-enum peer — owned-
18360        // input mirror of the paired [`TryFrom<&str>`] str-view reverse-
18361        // projection axis, and string-owned reverse companion of the
18362        // pre-existing string-owned *forward*-projection pair
18363        // ([`From<RestartPolicy> for String`],
18364        // [`From<&RestartPolicy> for String`]) on this same enum. Peer
18365        // of the sibling first-mover
18366        // [`crate::aplicacao::tests::rate_limit_try_from_owned_string_routes_through_borrowed_str_view_axis`]
18367        // (a2e6f02) on the compound [`crate::aplicacao::RateLimit`]
18368        // primitive, and the sibling
18369        // [`restart_strategy_try_from_owned_string_routes_through_borrowed_str_view_axis`]
18370        // (78fe8c8) on the sibling first M2-OTP-shape supervisor-slot
18371        // [`RestartStrategy`] peer — tracks the "delegate through
18372        // `TryFrom<&str>` on the `String::as_str` borrow" discipline the
18373        // compound-primitive opener and closed-set-peer first-mover
18374        // established. This closes the string-owned reverse-projection
18375        // axis on the M2-OTP-shape `:supervisor :estrategia` +
18376        // `:children :restart` slot pair.
18377        for &variant in RestartPolicy::ALL {
18378            let wire_string: String = variant.as_str().to_string();
18379            assert_eq!(
18380                <RestartPolicy as TryFrom<String>>::try_from(wire_string.clone()),
18381                Ok(variant),
18382                "TryFrom<String> impl on RestartPolicy must round-trip \
18383                 RestartPolicy::{variant:?}.as_str().to_string() back \
18384                 to Ok(RestartPolicy::{variant:?}) — divergence from \
18385                 the sibling TryFrom<&str> axis signals a silent detour \
18386                 off the substrate-primitive from_wire accessor"
18387            );
18388            // Cross-axis witness: the string-owned reverse-projection
18389            // axis must agree with the borrowed `&str` reverse-projection
18390            // axis on every accepted arm — the two axes share one
18391            // `PascalCase` wire vocabulary through the substrate-
18392            // primitive `from_wire` accessor, and the owned-input axis
18393            // delegates to the borrowed peer by design.
18394            let via_owned: Result<RestartPolicy, ()> =
18395                <RestartPolicy as TryFrom<String>>::try_from(wire_string.clone());
18396            let via_borrowed: Result<RestartPolicy, ()> =
18397                <RestartPolicy as TryFrom<&str>>::try_from(wire_string.as_str());
18398            assert_eq!(
18399                via_owned, via_borrowed,
18400                "TryFrom<String> and TryFrom<&str> reverse-projection \
18401                 axes on RestartPolicy must agree on \
18402                 RestartPolicy::{variant:?} — divergence signals the \
18403                 owned-`String` and borrowed-`&str` reverse paths have \
18404                 drifted off the same substrate-primitive from_wire \
18405                 accessor"
18406            );
18407            // Cross-axis witness against the paired byte-view and byte-
18408            // owned reverse axes — the four reverse paths (str-view
18409            // borrowed, string-owned, byte-view borrowed, byte-owned)
18410            // share one substrate primitive.
18411            let via_bytes_borrowed: Result<RestartPolicy, ()> =
18412                <RestartPolicy as TryFrom<&[u8]>>::try_from(wire_string.as_bytes());
18413            let via_bytes_owned: Result<RestartPolicy, ()> =
18414                <RestartPolicy as TryFrom<Vec<u8>>>::try_from(wire_string.as_bytes().to_vec());
18415            assert_eq!(
18416                via_owned, via_bytes_borrowed,
18417                "TryFrom<String> and TryFrom<&[u8]> reverse-projection \
18418                 axes on RestartPolicy must agree on \
18419                 RestartPolicy::{variant:?} — divergence signals the \
18420                 string-owned and byte-view reverse paths have drifted \
18421                 off the same substrate-primitive from_wire accessor"
18422            );
18423            assert_eq!(
18424                via_owned, via_bytes_owned,
18425                "TryFrom<String> and TryFrom<Vec<u8>> reverse-projection \
18426                 axes on RestartPolicy must agree on \
18427                 RestartPolicy::{variant:?} — divergence signals the \
18428                 string-owned and byte-owned reverse paths have drifted \
18429                 off the same substrate-primitive from_wire accessor"
18430            );
18431            // Closed-cycle witness against the paired string-owned
18432            // forward-projection pair: `Self → String → TryFrom<String>
18433            // → Self` round-trips to the originating arm on every
18434            // canonical `PascalCase` scalar. Both the owned-input
18435            // `From<RestartPolicy> for String` and the borrowed-input
18436            // `From<&RestartPolicy> for String` corners must feed back
18437            // through the new impl to `Ok(variant)`.
18438            let owned_forward: String = <String as From<RestartPolicy>>::from(variant);
18439            let borrowed_forward: String = <String as From<&RestartPolicy>>::from(&variant);
18440            assert_eq!(
18441                owned_forward, wire_string,
18442                "From<RestartPolicy> for String forward projection on \
18443                 RestartPolicy::{variant:?} must byte-equal \
18444                 variant.as_str().to_string() — divergence signals the \
18445                 paired forward pair drifted off the substrate-primitive \
18446                 as_str accessor"
18447            );
18448            assert_eq!(
18449                borrowed_forward, wire_string,
18450                "From<&RestartPolicy> for String forward projection on \
18451                 &RestartPolicy::{variant:?} must byte-equal \
18452                 variant.as_str().to_string() — divergence signals the \
18453                 paired forward pair drifted off the substrate-primitive \
18454                 as_str accessor"
18455            );
18456            assert_eq!(
18457                <RestartPolicy as TryFrom<String>>::try_from(owned_forward.clone()),
18458                Ok(variant),
18459                "Closed-cycle round-trip on RestartPolicy::{variant:?} \
18460                 through From<RestartPolicy> for String then \
18461                 TryFrom<String> for RestartPolicy must return \
18462                 Ok(variant) — divergence signals the string-owned \
18463                 forward pair and the string-owned reverse axis have \
18464                 drifted apart"
18465            );
18466            assert_eq!(
18467                <RestartPolicy as TryFrom<String>>::try_from(borrowed_forward),
18468                Ok(variant),
18469                "Closed-cycle round-trip on RestartPolicy::{variant:?} \
18470                 through From<&RestartPolicy> for String then \
18471                 TryFrom<String> for RestartPolicy must return \
18472                 Ok(variant) — divergence signals the borrowed-input \
18473                 forward corner and the owned-input string reverse \
18474                 corner have drifted apart"
18475            );
18476        }
18477    }
18478
18479    #[test]
18480    fn restart_policy_try_from_owned_string_rejects_unknown_wire_strings() {
18481        // Rejection witness on the `impl TryFrom<String> for
18482        // RestartPolicy` — sweeps the corpus of valid-UTF-8-but-
18483        // unknown-wire byte-strings the sibling borrowed [`TryFrom<&str>`]
18484        // axis already rejects and asserts every one lands on `Err(())`,
18485        // so a future accidental widening of the trait impl's accept-set
18486        // (a case-fold path, a silent inclusion of the kebab-case
18487        // dispatcher-catalog byte-strings on the sibling axis that would
18488        // collide the two-axis wire/catalog split the sibling
18489        // [`RestartPolicy::from_wire`] doc block makes load-bearing, a
18490        // stray fallback that maps whitespace-padded canonical scalars
18491        // onto their unpadded arm rather than the trait-idiomatic
18492        // `Err(())`) trips at caixa-core test time. Peer of the sibling
18493        // borrowed-input rejection witness
18494        // [`restart_policy_try_from_str_rejects_unknown_byte_strings`]
18495        // on the same enum, and the sibling byte-view / byte-owned
18496        // rejection witnesses
18497        // [`restart_policy_try_from_bytes_rejects_unknown_and_non_utf8_bytes`]
18498        // (d9ef5f0) /
18499        // [`restart_policy_try_from_vec_bytes_rejects_unknown_and_non_utf8_bytes`]
18500        // (7592085) on the same enum.
18501        let unknown_wire_rejected: &[&str] = &[
18502            "",
18503            " ",
18504            "\n",
18505            "\t",
18506            "permanent",
18507            "temporary",
18508            "transient",
18509            "PERMANENT",
18510            "TEMPORARY",
18511            "TRANSIENT",
18512            "Permanents",
18513            "Permanent ",
18514            " Permanent",
18515            " Temporary ",
18516            "Permanent\n",
18517            "Transient\t",
18518            "\"Permanent\"",
18519            "Ephemeral",
18520            "Always",
18521            "Never",
18522            "OnAbnormalExit",
18523            "intrinsic",
18524            "?",
18525        ];
18526        for &input in unknown_wire_rejected {
18527            let owned: String = input.to_string();
18528            assert_eq!(
18529                <RestartPolicy as TryFrom<String>>::try_from(owned),
18530                Err(()),
18531                "TryFrom<String> impl on RestartPolicy must reject the \
18532                 valid-UTF-8-but-unknown-wire byte-string {input:?} with \
18533                 Err(()) — silent acceptance signals an accept-set \
18534                 widening off the paired RestartPolicy::from_wire \
18535                 resolver"
18536            );
18537            // Cross-axis witness against the borrowed str-view axis:
18538            // the two paths must agree by construction, since the owned
18539            // axis delegates to the borrowed peer.
18540            assert_eq!(
18541                <RestartPolicy as TryFrom<String>>::try_from(input.to_string()),
18542                <RestartPolicy as TryFrom<&str>>::try_from(input),
18543                "TryFrom<String> and TryFrom<&str> reverse-projection \
18544                 axes on RestartPolicy must agree on the valid-UTF-8-\
18545                 but-unknown-wire input {input:?} — divergence signals \
18546                 the owned-`String` and borrowed-`&str` reverse paths \
18547                 have drifted off the same substrate-primitive from_wire \
18548                 accessor"
18549            );
18550        }
18551    }
18552
18553    #[test]
18554    fn restart_strategy_from_into_owned_box_bytes_routes_through_as_str_accessor() {
18555        // Fail-before-pass-after byte-parity pin on the newly lifted
18556        // `impl From<RestartStrategy> for Box<[u8]>` — asserts the
18557        // owned-input byte-owned reverse projection routes through the
18558        // substrate-primitive [`super::RestartStrategy::as_str`]
18559        // `pub const fn` accessor's `.as_bytes()` byte-view via
18560        // [`Box::<[u8]>::from`] on the returned `&'static [u8]` and
18561        // resolves to the same four-arm PascalCase wire byte-string
18562        // emit-set across every arm the exhaustive
18563        // [`super::RestartStrategy::ALL`] slice enumerates. Refuses any
18564        // future silent detour that would swap
18565        // `Box::<[u8]>::from(strategy.as_str().as_bytes())` for a
18566        // `Vec::<u8>::from(strategy).into_boxed_slice()` double-hop, a
18567        // routing through the sibling `fmt::Display` emitter, or a stray
18568        // normalization step that would drop or rebrand a canonical
18569        // PascalCase arm ahead of the boxed byte-emit. Cross-axis
18570        // partition against the paired owned-input byte-owned reverse-
18571        // projection axes ([`Vec<u8>`], [`Cow<'static, [u8]>`]) and the
18572        // paired string-side [`Box<str>`] forward-projection axis on the
18573        // same primitive — all four routes must byte-agree on every arm,
18574        // otherwise the byte-owned reverse-projection matrix has drifted
18575        // off the shared substrate-primitive `as_str` accessor.
18576        for &variant in RestartStrategy::ALL {
18577            let via_owned_from: Box<[u8]> = <Box<[u8]> as From<RestartStrategy>>::from(variant);
18578            let via_method_bytes: &'static [u8] = variant.as_str().as_bytes();
18579            assert_eq!(
18580                via_owned_from.as_ref(),
18581                via_method_bytes,
18582                "From<RestartStrategy> for Box<[u8]> impl must byte-\
18583                 equal RestartStrategy::as_str().as_bytes() on \
18584                 RestartStrategy::{variant:?} — divergence signals a \
18585                 silent detour off the substrate-primitive accessor"
18586            );
18587            // Cross-axis partition against the paired owned-input
18588            // `Vec<u8>` (98d38ed) and `Cow<'static, [u8]>` (7f81539)
18589            // byte-owned reverse-projection axes on the same enum — all
18590            // three axes must byte-agree on every arm.
18591            let via_vec_bytes: Vec<u8> = <Vec<u8> as From<RestartStrategy>>::from(variant);
18592            let via_cow_bytes: std::borrow::Cow<'static, [u8]> =
18593                <std::borrow::Cow<'static, [u8]> as From<RestartStrategy>>::from(variant);
18594            assert_eq!(
18595                via_owned_from.as_ref(),
18596                via_vec_bytes.as_slice(),
18597                "From<RestartStrategy> for Box<[u8]> and \
18598                 From<RestartStrategy> for Vec<u8> must byte-agree on \
18599                 RestartStrategy::{variant:?} — divergence signals the \
18600                 owned-input byte-owned reverse-projection axes have \
18601                 drifted off the same substrate-primitive as_str \
18602                 accessor"
18603            );
18604            assert_eq!(
18605                via_owned_from.as_ref(),
18606                via_cow_bytes.as_ref(),
18607                "From<RestartStrategy> for Box<[u8]> and \
18608                 From<RestartStrategy> for Cow<'static, [u8]> must \
18609                 byte-agree on RestartStrategy::{variant:?} — \
18610                 divergence signals the owned-input byte-owned reverse-\
18611                 projection axes have drifted off the same substrate-\
18612                 primitive as_str accessor"
18613            );
18614            // Cross-axis partition against the paired string-side
18615            // `Box<str>` (69ef45c) forward-projection axis on the same
18616            // enum — the byte-side and str-side `Box<_>` axes must byte-
18617            // agree on every arm (both route through Self::as_str's
18618            // `&'static str` return).
18619            let via_box_str: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
18620            assert_eq!(
18621                via_owned_from.as_ref(),
18622                via_box_str.as_bytes(),
18623                "From<RestartStrategy> for Box<[u8]> and \
18624                 From<RestartStrategy> for Box<str> must byte-agree on \
18625                 RestartStrategy::{variant:?} — divergence signals a \
18626                 silent detour off the shared substrate-primitive \
18627                 as_str accessor"
18628            );
18629        }
18630    }
18631
18632    #[test]
18633    fn restart_strategy_from_borrowed_into_owned_box_bytes_routes_through_as_str_accessor() {
18634        // Fail-before-pass-after byte-parity pin on the newly lifted
18635        // `impl From<&RestartStrategy> for Box<[u8]>` — asserts the
18636        // borrowed-input byte-owned reverse projection routes byte-for-
18637        // byte through the substrate-primitive
18638        // [`super::RestartStrategy::as_str`] `pub const fn` accessor's
18639        // `.as_bytes()` byte-view via [`Box::<[u8]>::from`] on the
18640        // returned `&'static [u8]` on every arm the exhaustive
18641        // [`super::RestartStrategy::ALL`] slice enumerates, preserving
18642        // the source [`super::RestartStrategy`] intact (no move-out).
18643        // Additionally asserts the paired owned-input and borrowed-input
18644        // corners byte-agree on the same arm, closing the
18645        // `{Self, &Self} → Box<[u8]>` byte-owned reverse-projection
18646        // family on this primitive.
18647        //
18648        // Generic `<T: Into<Box<[u8]>>>`-bound consumer witness helper:
18649        // a future per-supervisor byte-writer that accepts a
18650        // [`Box<[u8]>`] composes on both owned and borrowed input shapes
18651        // without an open-coded `Box::<[u8]>::from(strategy.as_str().
18652        // as_bytes())` at every call site. Lifted to the top of the
18653        // function per `clippy::items_after_statements`.
18654        fn generic_box_bytes_sink<T: Into<Box<[u8]>>>(t: T) -> Box<[u8]> {
18655            t.into()
18656        }
18657        for &variant in RestartStrategy::ALL {
18658            let via_borrowed_from: Box<[u8]> =
18659                <Box<[u8]> as From<&RestartStrategy>>::from(&variant);
18660            let via_method_bytes: &'static [u8] = variant.as_str().as_bytes();
18661            assert_eq!(
18662                via_borrowed_from.as_ref(),
18663                via_method_bytes,
18664                "From<&RestartStrategy> for Box<[u8]> impl must byte-\
18665                 equal RestartStrategy::as_str().as_bytes() on \
18666                 &RestartStrategy::{variant:?} — divergence signals a \
18667                 silent detour off the substrate-primitive accessor"
18668            );
18669            // The borrowed-input impl must not move out of the source —
18670            // the source RestartStrategy must survive the projection.
18671            let survivor: &'static str = variant.as_str();
18672            assert_eq!(
18673                survivor.as_bytes(),
18674                via_method_bytes,
18675                "source &RestartStrategy::{variant:?} must survive \
18676                 borrowed-input projection — a move-out here signals \
18677                 the impl silently dereferences past the borrowed \
18678                 handle"
18679            );
18680            // Cross-corner partition against the paired owned-input
18681            // `Box<[u8]>` axis on the same enum — the two corners must
18682            // byte-agree on every arm, closing the "owned-input move
18683            // vs. borrowed-input clone" bifurcation on the same wire
18684            // byte-string through the `Box<[u8]>` axis.
18685            let via_owned_from: Box<[u8]> = <Box<[u8]> as From<RestartStrategy>>::from(variant);
18686            assert_eq!(
18687                via_borrowed_from.as_ref(),
18688                via_owned_from.as_ref(),
18689                "From<&RestartStrategy> for Box<[u8]> and \
18690                 From<RestartStrategy> for Box<[u8]> must byte-agree on \
18691                 RestartStrategy::{variant:?} — divergence signals the \
18692                 paired owned-input and borrowed-input corners have \
18693                 drifted off the same substrate-primitive as_str \
18694                 accessor"
18695            );
18696            let owned_via_generic = generic_box_bytes_sink(variant);
18697            let variant_ref: &RestartStrategy = &variant;
18698            let borrowed_via_generic = generic_box_bytes_sink(variant_ref);
18699            assert_eq!(
18700                owned_via_generic.as_ref(),
18701                via_method_bytes,
18702                "<T: Into<Box<[u8]>>>-bound composition on \
18703                 RestartStrategy::{variant:?} must fold the same byte-\
18704                 tail RestartStrategy::as_str().as_bytes() returns"
18705            );
18706            assert_eq!(
18707                borrowed_via_generic.as_ref(),
18708                via_method_bytes,
18709                "<T: Into<Box<[u8]>>>-bound composition on \
18710                 &RestartStrategy::{variant:?} must fold the same byte-\
18711                 tail RestartStrategy::as_str().as_bytes() returns"
18712            );
18713        }
18714    }
18715}