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/// Substrate-canonical [`AsRef<[u8]>`] byte-view projection on the M2
1327/// OTP-shape sibling-restart [`RestartStrategy`] closed-set fieldless
1328/// typed enum — routes byte-for-byte through the substrate-primitive
1329/// [`RestartStrategy::as_str`] `pub const fn` accessor via
1330/// [`str::as_bytes`] on the returned `&'static str`, so any future
1331/// consumer that binds a [`RestartStrategy`] through a standard-library
1332/// `<T: AsRef<[u8]>>` trait bound reaches the same four-arm lifted
1333/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
1334/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
1335/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
1336/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
1337/// `PascalCase` wire byte-string emit-set the paired sibling
1338/// [`AsRef<str>`] (5b828ed) / [`std::fmt::Display`] /
1339/// [`RestartStrategy::as_str`] str-view surfaces and every
1340/// `{Self, &Self} × {&'static str, String, Cow<'static, str>, Box<str>,
1341/// std::sync::Arc<str>}` reverse-projection corner already return —
1342/// through the byte-view axis, which the str-view axes cannot express.
1343///
1344/// Rust's standard library carries `impl AsRef<[u8]> for str` and
1345/// `impl AsRef<[u8]> for String`, so the two-hop composition
1346/// `strategy.as_str().as_bytes()` (or, equivalently,
1347/// `AsRef::<str>::as_ref(&strategy).as_bytes()`) is reachable through
1348/// the pre-existing str-view axis alone. But that two-hop shape has no
1349/// compile-time link back to the byte-projection axis, forces every
1350/// downstream `<T: AsRef<[u8]>>`-bound consumer to open-code the
1351/// two-hop composition at every call site, and admits a silent split
1352/// whenever a future call site takes a sibling reverse-projection axis
1353/// whose `.as_bytes()` byte-tail carries no compile-time byte-view
1354/// surface (`Display` returns a formatter, `String` / `Box<str>` /
1355/// `Arc<str>` allocate). The lifted single-hop impl closes the
1356/// byte-view axis so every future `<T: AsRef<[u8]>>`-bound consumer
1357/// reaches the substrate primitive through one trait dispatch, and
1358/// every future arm addition (an OTP-`rest_for_all` fifth arm the
1359/// theory
1360/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1361/// might reach for once the four canonical OTP strategies stop covering
1362/// the substrate's discovered load-shape) grows the byte-view axis
1363/// through one edit on the substrate-primitive `as_str` accessor, not a
1364/// coordinated rewrite across every future `<T: AsRef<[u8]>>`-bound
1365/// consumer's arm-set.
1366///
1367/// The primary compounding target is the same `caixa-lacre` BLAKE3
1368/// content-address closure the peer [`crate::CaixaKind`] (69d8d86),
1369/// [`crate::dialeto::CaixaDialeto`] (8151347),
1370/// [`crate::dep::DepList`] (05ffaca),
1371/// [`crate::aplicacao::PlacementStrategy`] (daa8705), and
1372/// [`crate::aplicacao::RateLimitUnit`] (4867e0f) `AsRef<[u8]>` impls
1373/// open onto: [`blake3::hash`] and [`blake3::Hasher::update`] both bind
1374/// their input through `impl AsRef<[u8]>`, so any future per-supervisor
1375/// content-address tag that folds an `:estrategia` discriminator
1376/// byte-tag into the [`crate::Lacre`] closure (a hypothetical
1377/// `hasher.update(estrategia);`-shape composition partitioning the
1378/// four OTP restart-topology closures at content-address time so
1379/// downstream `Lacre` consumers key per-strategy reconciliation caches
1380/// off the typed discriminator rather than the sibling `&'static str`
1381/// wire scalar) reaches the substrate-primitive `as_str` accessor
1382/// through this impl and no other.
1383///
1384/// Opens the trait-idiomatic byte-view axis on the first M2 OTP-shape
1385/// closed-set fieldless typed enum peer on the caixa surface
1386/// (`:supervisor :estrategia`), extending the substrate-wide byte-view
1387/// campaign the sibling [`crate::CaixaKind`] first-mover (69d8d86)
1388/// opened onto the fifth in-caixa-core enum peer. The remaining
1389/// in-caixa-core closed-set fieldless typed-enum peers
1390/// ([`RestartPolicy`], [`crate::aplicacao::WitShape`],
1391/// [`crate::upgrade::UpgradeInstruction`],
1392/// [`crate::render::PathShapeViolation`]) each carry the same
1393/// [`AsRef<str>`] + `pub const fn as_str` substrate-primitive accessor
1394/// discipline, so a future extension of the byte-view axis onto each
1395/// peer reaches through one impl per enum keyed to that peer's
1396/// substrate-primitive accessor.
1397///
1398/// Pinned load-bearing by
1399/// [`tests::restart_strategy_as_ref_bytes_routes_through_as_str_accessor`]
1400/// (fail-before-pass-after byte-parity pin against
1401/// [`RestartStrategy::as_str`] `.as_bytes()` across the four-arm
1402/// [`RestartStrategy::ALL`] emit-set, cross-axis witness against the
1403/// paired str-view [`AsRef<str>`] / [`std::fmt::Display`] /
1404/// [`RestartStrategy::as_str`] axes' `.as_bytes()` byte-tails,
1405/// cross-axis witness against the paired reverse-projection
1406/// `{&'static str, String, Cow<'static, str>, Box<str>,
1407/// std::sync::Arc<str>}` return-shape axes' `.as_bytes()` byte-tails,
1408/// a `<T: AsRef<[u8]>>`-bound-consumer witness that a generic
1409/// byte-input function accepts a [`RestartStrategy`] directly through
1410/// the trait bound, and a `blake3::Hasher::update`-shape byte-input
1411/// surface witness routed through the `<T: AsRef<[u8]>>`-bound
1412/// consumer axis to reach the caixa-lacre compounding target). Any
1413/// future silent detour that routes the byte-view impl off the
1414/// substrate-primitive [`RestartStrategy::as_str`] accessor (a per-arm
1415/// inline `b"OneForOne".as_slice()`-shaped re-inlining that opens a
1416/// compile-time link to the un-lifted arm-literal, a swap onto the
1417/// kebab-case [`gen_platform::Discriminant`] catalog identity that
1418/// would collide the wire axis with the dispatcher-catalog axis) trips
1419/// at caixa-core test time rather than at a downstream byte-consumer's
1420/// silent split.
1421impl AsRef<[u8]> for RestartStrategy {
1422    fn as_ref(&self) -> &[u8] {
1423        self.as_str().as_bytes()
1424    }
1425}
1426
1427/// Trait-idiomatic *owned-input, owned-`Vec<u8>` output* byte-owned
1428/// reverse projection on the first M2 OTP-shape closed-set fieldless
1429/// typed enum peer on the caixa surface ([`RestartStrategy`]) — the
1430/// byte-mirror of the [`From<RestartStrategy> for String`] str-owned
1431/// reverse-projection axis and the owned-`Vec<u8>` reverse-projection
1432/// sibling of the paired [`AsRef<[u8]>`] borrowed byte-view axis
1433/// (cd4c4e0) lifted on this same enum. Routes byte-for-byte through
1434/// the substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
1435/// accessor via [`str::as_bytes`] + [`slice::to_vec`] so every
1436/// consumer that binds a [`RestartStrategy`] through the standard-
1437/// library `impl From<RestartStrategy> for Vec<u8>` axis
1438/// (equivalently `<T: Into<Vec<u8>>>`) — a future
1439/// [`std::io::Write::write_all`]-shape per-supervisor audit-log byte-
1440/// sink whose input parameter is an owned [`Vec<u8>`] payload, a
1441/// future `bytes::Bytes::from(Vec::<u8>::from(strategy))` composer
1442/// folding the per-arm sibling-restart-topology byte-tag into the
1443/// [`bytes::Bytes`] framing surface, a future
1444/// `hasher.update(&Vec::<u8>::from(strategy))`-shape BLAKE3 content-
1445/// address closure that needs the owned byte-tail buffered before
1446/// folding into the [`crate::Lacre`] closure body, a future per-
1447/// strategy protobuf/CBOR/msgpack payload composer whose framer takes
1448/// an owned [`Vec<u8>`] rather than a borrowed byte-slice — reaches
1449/// the substrate primitive through one trait dispatch rather than an
1450/// open-coded per-call-site `strategy.as_str().as_bytes().to_vec()`
1451/// composition whose type bounds have no compile-time link back to
1452/// the substrate primitive.
1453///
1454/// Extends the substrate-wide trait-idiomatic byte-owned reverse-
1455/// projection axis onto the first M2-OTP-shape closed-set fieldless
1456/// typed-enum peer, matching the trajectory the first-mover
1457/// [`crate::CaixaKind`] `From<{Self, &Self}> for Vec<u8>` lift
1458/// (b245fd6), the second-mover [`crate::dialeto::CaixaDialeto`] lift
1459/// (4cceaf5), and the third-mover [`crate::dep::DepList`] lift
1460/// (e974ca2) established across the caixa-core-internal tier. Every
1461/// future arm addition (an OTP-`rest_for_all` fifth arm the theory
1462/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1463/// might reach for once the four canonical OTP strategies stop
1464/// covering the substrate's discovered load-shape) grows the byte-
1465/// owned axis through one edit on the substrate-primitive
1466/// [`RestartStrategy::as_str`] accessor, mirroring the discipline the
1467/// paired [`AsRef<[u8]>`] borrowed byte-view axis campaign already
1468/// tracked across every closed-set fieldless typed enum peer on the
1469/// substrate.
1470///
1471/// Pinned load-bearing by
1472/// [`tests::restart_strategy_from_into_owned_vec_bytes_routes_through_as_str_accessor`]
1473/// (byte-parity pin against [`RestartStrategy::as_str`] across the
1474/// four-arm [`RestartStrategy::ALL`] emit-set binding the byte-owned
1475/// reverse-projection axis against the paired [`AsRef<[u8]>`]
1476/// borrowed byte-view axis and the str-owned reverse-projection
1477/// family (`String`, `Cow<'static, str>`, `Box<str>`,
1478/// `std::sync::Arc<str>`) `.into_bytes()` / `.as_bytes().to_vec()`
1479/// byte-tails, a `<T: Into<Vec<u8>>>`-bound generic-consumer witness,
1480/// and a `std::io::Write::write_all`-shape owned-byte-sink surface
1481/// witness on both owned and borrowed input shapes).
1482impl From<RestartStrategy> for Vec<u8> {
1483    fn from(strategy: RestartStrategy) -> Vec<u8> {
1484        strategy.as_str().as_bytes().to_vec()
1485    }
1486}
1487
1488/// Trait-idiomatic *borrowed-input, owned-`Vec<u8>` output* byte-
1489/// owned reverse projection on the first M2 OTP-shape closed-set
1490/// fieldless typed enum peer on the caixa surface
1491/// ([`RestartStrategy`]) — the borrowed-input peer of
1492/// [`From<RestartStrategy> for Vec<u8>`], closing the
1493/// `{Self, &Self} → Vec<u8>` pair on the byte-owned reverse-projection
1494/// axis in one lift. Routes byte-for-byte through the substrate-
1495/// primitive [`RestartStrategy::as_str`] `pub const fn` accessor so
1496/// every consumer that holds a borrowed [`&RestartStrategy`] and
1497/// needs an owned [`Vec<u8>`] — a future
1498/// `.iter().map(Vec::<u8>::from).collect()` pipe over
1499/// `&[RestartStrategy]` (whose iterator yields `&RestartStrategy`,
1500/// not `RestartStrategy`, so the owned-input axis alone forces every
1501/// call site through an explicit `.copied()` / spurious [`Copy`]
1502/// deref restatement rather than the direct trait-idiomatic
1503/// projection), a future admission-webhook rejection body composer
1504/// that walks [`RestartStrategy::ALL`] through an `Into<Vec<u8>>`-
1505/// bound per-arm byte-writer to surface the accepted `:estrategia`
1506/// set — reaches the substrate primitive through one trait dispatch
1507/// rather than a `Vec::<u8>::from(*strategy)` spurious-`Copy`-deref
1508/// restatement.
1509impl From<&RestartStrategy> for Vec<u8> {
1510    fn from(strategy: &RestartStrategy) -> Vec<u8> {
1511        strategy.as_str().as_bytes().to_vec()
1512    }
1513}
1514
1515/// Trait-idiomatic *borrowed byte-slice input* reverse projection on the
1516/// first M2-OTP-shape closed-set fieldless typed enum peer on the caixa
1517/// surface ([`RestartStrategy`]) — the byte-view mirror of the str-view
1518/// reverse-projection axis carried by the paired
1519/// [`TryFrom<&str> for RestartStrategy`] impl (which routes through the
1520/// substrate-primitive [`RestartStrategy::from_wire`] `Option<Self>`
1521/// accessor on the four-arm `PascalCase` accept-set the sibling
1522/// [`RestartStrategy::as_str`] emitter returns). Routes byte-for-byte
1523/// through the standard-library [`std::str::from_utf8`] UTF-8 validator
1524/// and then through [`RestartStrategy::from_wire`] so every consumer that
1525/// holds a borrowed [`&[u8]`] and needs to project it back into a typed
1526/// [`RestartStrategy`] — a future `bytes::Bytes::as_ref()`-fed reader
1527/// that parses a per-supervisor `:estrategia` `PascalCase` wire scalar
1528/// from an already-borrowed framing byte-tail (a
1529/// `tracing::field::valuable::Value::Bytes` recorder on the future
1530/// wasm-operator's per-supervisor sibling-restart-strategy diagnostic
1531/// emission path, a future audit-report re-loader binding a prior
1532/// [`RestartStrategy::as_str`] output from a mmap'd byte-slice back
1533/// through the typed enum for cross-run comparison), a future M4
1534/// `mesh.pleme.io/v1alpha1/Supervisor` CR admission-webhook rejection
1535/// body that reads a `spec.estrategia` field off a raw HTTP body byte-
1536/// slice before UTF-8 validation commits allocation, a future generic
1537/// `<T: for<'a> TryFrom<&'a [u8]>>`-bound loader over any of the
1538/// substrate's closed-set typed enums — reaches the same four-arm
1539/// `PascalCase` wire accept-set the sibling method-named
1540/// [`RestartStrategy::from_wire`] resolver and the paired trait-idiomatic
1541/// [`TryFrom<&str>`] axis already resolve against, rather than an open-
1542/// coded per-call-site
1543/// `std::str::from_utf8(bytes).ok().and_then(RestartStrategy::from_wire)`
1544/// composition or a
1545/// `<RestartStrategy as TryFrom<&str>>::try_from(std::str::from_utf8(bytes)?)`
1546/// two-hop shape whose type bounds have no compile-time link to the
1547/// substrate primitive.
1548///
1549/// Extends the substrate-wide trait-idiomatic *byte-view reverse-
1550/// projection* family — opened on the structurally most fundamental
1551/// closed-set fieldless typed enum peer ([`crate::CaixaKind`], commit
1552/// 18d1940), extended onto the second caixa-core-internal peer
1553/// ([`crate::CaixaDialeto`], commit d102cb8) and the third
1554/// ([`crate::dep::DepList`], commit b8f25d5) — onto the first
1555/// M2-OTP-shape supervisor-slot closed-set fieldless typed enum peer,
1556/// tracking the "route through `from_wire` via `std::str::from_utf8`"
1557/// discipline the first-mover established. Rust's standard library
1558/// carries no blanket
1559/// `impl<T: for<'a> TryFrom<&'a str>> TryFrom<&[u8]> for T`, so a two-
1560/// hop composition through [`std::str::from_utf8`] + the paired
1561/// [`TryFrom<&str>`] axis is reachable at every call site but has no
1562/// compile-time link back to the byte-view reverse-projection axis.
1563/// Every remaining closed-set fieldless typed enum peer on the substrate
1564/// ([`RestartPolicy`], [`crate::aplicacao::PlacementStrategy`],
1565/// [`crate::aplicacao::RateLimitUnit`], [`crate::aplicacao::WitShape`],
1566/// and the outside-`caixa-core` peers `PathShapeViolation`,
1567/// `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`,
1568/// `FerriteRuntime`) is a future target of the campaign, mirroring the
1569/// trajectory the closed byte-owned reverse-projection family walked
1570/// arm-by-arm onto each peer.
1571///
1572/// `type Error = ()` matches the sibling [`RestartStrategy::from_wire`]'s
1573/// `Option<Self>` return-shape's deliberate deferral of error typing and
1574/// the paired trait-idiomatic [`TryFrom<&str>`] axis's unit-error shape —
1575/// the caller picks the diagnostic form appropriate for its use site (a
1576/// future `feira supervisor --estrategia …` arg-parse composes its own
1577/// per-verb "unknown strategy: <arg> — accepted: {…}" message enumerating
1578/// [`RestartStrategy::WIRE_NAMES`]; a future admission-webhook rejection
1579/// body wraps the `Err(())` outcome with the accepted-set enumeration for
1580/// operator diagnostics; a `Result::map_err` at the call site lifts the
1581/// unit-error to a per-verb error type). Two rejection paths route
1582/// through the single unit-error: an invalid UTF-8 byte-sequence
1583/// ([`std::str::from_utf8`] returns `Err`) and a valid UTF-8 byte-string
1584/// that falls outside the four-arm `PascalCase` accept-set
1585/// ([`RestartStrategy::from_wire`] returns `None`) — both collapse onto
1586/// `Err(())` so the trait signature stays consistent with the sibling
1587/// str-view reverse axis, and a caller that needs to distinguish the two
1588/// failure modes composes [`std::str::from_utf8`] +
1589/// [`RestartStrategy::from_wire`] explicitly.
1590///
1591/// Pinned load-bearing by
1592/// [`tests::restart_strategy_try_from_bytes_routes_through_from_wire_accessor`]
1593/// (byte-parity pin against [`RestartStrategy::from_wire`] across the
1594/// four-arm [`RestartStrategy::ALL`] accept-set on the borrowed byte-
1595/// slice surface, plus a cross-axis witness that the byte-view reverse
1596/// projection agrees with the paired [`TryFrom<&str>`] str-view reverse
1597/// axis on every accepted arm) and
1598/// [`tests::restart_strategy_try_from_bytes_rejects_unknown_and_non_utf8_bytes`]
1599/// (rejection witness against silent accept-set widening on both the
1600/// non-UTF-8 byte-sequence rejection path and the unknown-wire-vocabulary
1601/// rejection path — the latter includes the sibling kebab-case
1602/// dispatcher-catalog byte-strings on the two-axis wire/catalog split so
1603/// a caller that confuses the two axes trips here rather than at a
1604/// downstream K8s-CR round-trip miss).
1605impl TryFrom<&[u8]> for RestartStrategy {
1606    type Error = ();
1607
1608    fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
1609        std::str::from_utf8(bytes)
1610            .ok()
1611            .and_then(Self::from_wire)
1612            .ok_or(())
1613    }
1614}
1615
1616/// Trait-idiomatic *owned byte-vec input* reverse projection on the first
1617/// M2-OTP-shape supervisor-slot closed-set fieldless typed enum peer on the
1618/// caixa surface ([`RestartStrategy`]) — the owned-input peer of
1619/// [`TryFrom<&[u8]> for RestartStrategy`], mirroring the closed
1620/// [`From<RestartStrategy> for Vec<u8>`] + [`From<&RestartStrategy> for
1621/// Vec<u8>`] byte-owned *forward*-projection pair on this same enum onto
1622/// the byte-owned *reverse*-projection axis. Routes byte-for-byte through
1623/// [`<Self as TryFrom<&[u8]>>::try_from`] on the [`Vec<u8>::as_slice`]
1624/// borrow, so the owned-input surface reaches the same
1625/// [`std::str::from_utf8`] + [`RestartStrategy::from_wire`] resolution
1626/// chain the borrowed-input peer already carries — one substrate-primitive
1627/// accessor, one trait dispatch, no per-consumer detour.
1628///
1629/// Rust's standard library carries no blanket
1630/// `impl<T: for<'a> TryFrom<&'a [u8]>> TryFrom<Vec<u8>> for T`, so a
1631/// consumer that holds an owned [`Vec<u8>`] and needs a typed
1632/// [`RestartStrategy`] otherwise picks between (a) an open-coded
1633/// `<RestartStrategy as TryFrom<&[u8]>>::try_from(bytes.as_slice())` at
1634/// every call site (whose type bounds have no compile-time link to the
1635/// byte-owned reverse-projection axis), (b) a two-hop
1636/// `String::from_utf8(bytes)` + [`RestartStrategy::from_wire`] composition
1637/// whose error surface leaks the standard-library
1638/// [`std::string::FromUtf8Error`] (widening the sibling [`TryFrom<&[u8]>`]
1639/// axis's unit-error) and silently allocates a [`String`] on inputs that
1640/// will never make it past the wire vocabulary, or (c) an intermediate
1641/// `<RestartStrategy as TryFrom<&str>>::try_from(std::str::from_utf8(&bytes)?)`
1642/// three-hop shape. This impl closes the owned-byte-vec reverse-projection
1643/// axis at the substrate-primitive [`RestartStrategy::from_wire`] accessor
1644/// so every future `<T: TryFrom<Vec<u8>>>`-bound owned-byte-vec consumer —
1645/// a future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR admission-webhook
1646/// body reader that hands the `spec.estrategia` byte-tail off as a
1647/// [`Vec<u8>`] before UTF-8 validation commits allocation, a
1648/// `bytes::Bytes::to_vec()`-shape wire-body composer walking a prior
1649/// audit's per-supervisor rejection payload back to the typed enum, a
1650/// `std::io::Read::read_to_end`-shape audit-log source whose framing
1651/// yields an owned byte-vec per per-strategy scalar, an
1652/// `<T: TryFrom<Vec<u8>>>`-bound generic loader over any of the
1653/// substrate's closed-set typed enums — reaches the same four-arm
1654/// `PascalCase` wire accept-set through one trait dispatch.
1655///
1656/// Extends the substrate-wide trait-idiomatic *byte-owned reverse-
1657/// projection* family — opened on the structurally most fundamental
1658/// closed-set fieldless typed enum peer ([`crate::CaixaKind`], commit
1659/// 99c2849), extended onto the second caixa-core-internal peer
1660/// ([`crate::CaixaDialeto`], commit 83a1526) and the third
1661/// ([`crate::dep::DepList`], commit 42091cb) — onto the first M2-OTP-shape
1662/// supervisor-slot closed-set fieldless typed enum peer, tracking the
1663/// "delegate through `TryFrom<&[u8]>` on the `Vec<u8>::as_slice` borrow"
1664/// discipline the first-mover established. Every remaining closed-set
1665/// fieldless typed enum peer on the substrate ([`RestartPolicy`],
1666/// [`crate::aplicacao::PlacementStrategy`],
1667/// [`crate::aplicacao::RateLimitUnit`], [`crate::aplicacao::WitShape`],
1668/// [`crate::render::PathShapeViolation`], and the outside-`caixa-core`
1669/// peers `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`,
1670/// `Semantic`, `FerriteRuntime`) is a future target of the campaign,
1671/// mirroring the trajectory the closed byte-view reverse-projection
1672/// family (`TryFrom<&[u8]>`) and the closed byte-owned forward-projection
1673/// family (`From<{Self, &Self}> for Vec<u8>`) already walked.
1674///
1675/// `type Error = ()` matches the sibling [`TryFrom<&[u8]> for
1676/// RestartStrategy`] unit-error shape, preserving the trait-family
1677/// consistency across the borrowed-and-owned byte-view reverse-projection
1678/// pair. The owned [`Vec<u8>`] input is dropped on the error path (the
1679/// standard-library `String::from_utf8` convention of returning the input
1680/// in the error deliberately declined — a caller that needs the bytes
1681/// back holds a clone before the call, and the closed-set-enum use site
1682/// rarely wants the raw bytes back past a "did you mean" diagnostic that
1683/// operates on the wire vocabulary rather than the input).
1684///
1685/// Pinned load-bearing by
1686/// [`tests::restart_strategy_try_from_vec_bytes_routes_through_borrowed_byte_view_axis`]
1687/// (byte-parity pin against the paired borrowed [`TryFrom<&[u8]>`] axis
1688/// across the four-arm [`RestartStrategy::ALL`] accept-set on the owned
1689/// byte-vec surface, cross-axis witness that the byte-owned reverse
1690/// projection agrees with the paired str-view reverse-projection axis
1691/// ([`TryFrom<&str>`]) on every accepted arm through the shared
1692/// substrate-primitive [`RestartStrategy::from_wire`] accessor, and a
1693/// four-corner {owned-input, borrowed-input} × {`From<Self>` → `Vec<u8>`,
1694/// `From<&Self>` → `Vec<u8>`} round-trip witness available on this enum
1695/// because [`RestartStrategy::as_str`] and [`RestartStrategy::from_wire`]
1696/// share one `PascalCase` byte-vocabulary — unlike the sibling
1697/// [`crate::CaixaKind`] which its peer test deliberately declines the
1698/// four-corner witness on because the wire/diagnostic split makes the
1699/// forward and reverse pairs speak different byte-strings) and
1700/// [`tests::restart_strategy_try_from_vec_bytes_rejects_unknown_and_non_utf8_bytes`]
1701/// (rejection witness against silent accept-set widening on both the
1702/// non-UTF-8 byte-sequence rejection path and the unknown-wire-vocabulary
1703/// rejection path — the latter includes the sibling kebab-case
1704/// dispatcher-catalog byte-strings on the two-axis wire/catalog split so
1705/// a caller that confuses the two axes trips here rather than at a
1706/// downstream K8s-CR round-trip miss, plus a cross-axis witness that the
1707/// owned byte-vec reverse-projection axis agrees with the borrowed byte-
1708/// slice reverse-projection axis on every rejected input).
1709impl TryFrom<Vec<u8>> for RestartStrategy {
1710    type Error = ();
1711
1712    fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
1713        <Self as TryFrom<&[u8]>>::try_from(bytes.as_slice())
1714    }
1715}
1716
1717/// Per-child restart policy.
1718///
1719/// Permanent / Temporary / Transient match Erlang/OTP semantics 1:1.
1720#[derive(
1721    Serialize,
1722    Deserialize,
1723    Debug,
1724    Clone,
1725    Copy,
1726    PartialEq,
1727    Eq,
1728    Hash,
1729    gen_platform::TypedDispatcher,
1730    gen_platform::Discriminant,
1731    gen_platform::IsVariant,
1732    gen_platform::FromStrKind,
1733)]
1734pub enum RestartPolicy {
1735    /// Always restart the child, regardless of how it died. Used for
1736    /// long-running services that must always be up.
1737    Permanent,
1738    /// Never restart. Used for one-shot work whose completion is
1739    /// itself the success signal (`oneShot` triggers map here).
1740    Temporary,
1741    /// Restart only when the child died *abnormally* (non-zero exit
1742    /// or unhandled exception). A clean exit completes the child.
1743    Transient,
1744}
1745
1746impl Default for RestartPolicy {
1747    fn default() -> Self {
1748        // Route the [`Default for RestartPolicy`] impl's return arm through
1749        // the substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed
1750        // `pub const` rather than a raw `Self::Permanent` arm — one source
1751        // of truth for the Erlang/OTP-canonical `permanent` worker-child
1752        // default across the two production consumers that currently
1753        // dispatch on it (this impl at the [`RestartPolicy::default`] call
1754        // and the serde-side `#[serde(default)]` on
1755        // [`ChildSpec::restart`] that resolves an author-omitted
1756        // `:children :restart` slot through `RestartPolicy::default()`).
1757        // Peer of the sibling per-`:supervisor` axis
1758        // [`Default for RestartStrategy`] → [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
1759        // route (95ffacc) — the two impls now share one substrate-primitive
1760        // lift discipline, so any future coherent rebrand of the OTP-shape
1761        // supervisor+child default set migrates through typed constants in
1762        // lockstep instead of splitting a lifted supervisor half against
1763        // an open-coded child half. Pinned by
1764        // `restart_policy_default_routes_through_lifted_default` +
1765        // `child_spec_serde_default_restart_routes_through_lifted_default`
1766        // in the tests module.
1767        SUPERVISOR_CHILD_RESTART_DEFAULT
1768    }
1769}
1770
1771impl RestartPolicy {
1772    /// Exhaustive iteration surface for every consumer that walks the
1773    /// closed three-arm [`RestartPolicy`] discriminator set (the future
1774    /// M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
1775    /// per-child admission-webhook rejection body naming the accepted-
1776    /// `:restart` list, a future `feira supervisor --restart …` CLI
1777    /// arg-parse's "did you mean" hint via a [`Self::from_wire`]-scan
1778    /// over the slice, the future `feira app graph` per-child restart
1779    /// column, any future round-trip fuzz harness that sweeps every
1780    /// arm). A future arm addition (an OTP-`intrinsic` fourth arm the
1781    /// theory
1782    /// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1783    /// might reach for once the three canonical OTP restart policies
1784    /// stop covering the substrate's discovered load-shape) extends
1785    /// this slice as one edit and every consumer picks up the new entry
1786    /// by construction; the compiler-checked exhaustiveness on the
1787    /// sibling method `match` arms ([`Self::as_str`] / [`Self::from_wire`])
1788    /// is the build-time guarantee that no arm forgets to grow.
1789    ///
1790    /// Peer of the sibling closed-set typed enums'
1791    /// [`RestartStrategy::ALL`] (4eec29c) /
1792    /// [`crate::CaixaKind::ALL`] (6b1f4fb) /
1793    /// [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
1794    /// [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
1795    /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
1796    /// surfaces — the sixth (and the third and final M2 OTP-shape)
1797    /// closed-set typed enum on the caixa surface to converge onto the
1798    /// same one-canonical-arm-list-per-enum discipline. Sibling axis to
1799    /// the peer [`RestartStrategy::ALL`] on the per-supervisor
1800    /// sibling-restart-strategy axis; this closes the per-child
1801    /// restart-decision-policy axis on the same M2 `:supervisor` slot.
1802    pub const ALL: &'static [Self] = &[Self::Permanent, Self::Temporary, Self::Transient];
1803
1804    /// Substrate-canonical exhaustive accept-set on the [`RestartPolicy`]
1805    /// `PascalCase` wire byte-string axis — the closed three-arm roster
1806    /// of every byte-string [`Self::as_str`] returns, routed byte-for-byte
1807    /// through the paired
1808    /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1809    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1810    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] lifted
1811    /// `pub const` roster the [`Self::as_str`] emitter (and the
1812    /// [`std::fmt::Display`] impl / `Serialize` derive routed through it)
1813    /// walks — and byte-for-byte the same three strings the un-`rename`d
1814    /// `Serialize` derive emits under the paired
1815    /// [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] tag key on every
1816    /// JSON / YAML CR round-trip.
1817    ///
1818    /// Peer of the sibling [`crate::CaixaKind::WIRE_NAMES`] (bd708bd)
1819    /// roster on the top-level typed-kind discriminator's `PascalCase`
1820    /// wire byte-string axis, the sibling
1821    /// [`RestartStrategy::WIRE_NAMES`] (3033f45) roster on the per-
1822    /// supervisor sibling-restart-strategy axis (the first M2 OTP-shape
1823    /// closed-set typed enum to converge onto the paired-roster
1824    /// discipline), the sibling
1825    /// [`crate::aplicacao::PlacementStrategy::WIRE_NAMES`] (3e5b194)
1826    /// roster on the first M3 mesh-shape distribution-strategy closed-
1827    /// set typed enum, and the sibling
1828    /// [`crate::upgrade::UpgradeInstruction::WIRE_FORMS`] (cc42c0e) /
1829    /// [`crate::upgrade::UpgradeInstruction::LISP_FORMS`] (1898d77)
1830    /// rosters on the OTP-appup discriminator's two-axis roster split —
1831    /// the same closed-set exhaustive-accept-set roster discipline
1832    /// extended here onto the second and final M2 OTP-shape sibling-
1833    /// enum on the caixa surface, closing the per-child restart-decision-
1834    /// policy axis paired with the peer [`RestartStrategy::WIRE_NAMES`]
1835    /// per-supervisor sibling-restart-strategy axis on the same M2
1836    /// `:supervisor` slot.
1837    ///
1838    /// Downstream consumers of the closed accepted-wire-form set — a
1839    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR admission-
1840    /// webhook rejection body enumerating the accepted JSON `:restart`
1841    /// values verbatim (as distinct from the kebab-case dispatcher-
1842    /// catalog enumeration [`Self::discriminant`] serves, whose per-arm
1843    /// form `"permanent"` / `"temporary"` / `"transient"` structurally
1844    /// disagrees with the wire byte-string these `PascalCase` entries
1845    /// carry — the split the sibling
1846    /// [`tests::restart_policy_display_matches_serialized_wire_byte_string`]
1847    /// pin already makes load-bearing), a future `feira supervisor
1848    /// --restart …` CLI-side "did you mean" hint whose candidate-list
1849    /// must byte-match the wire form the operator's per-child dispatch
1850    /// keys off, a future `feira app graph` per-child `:restart`-
1851    /// histogram column that renders zero-count arms, a future
1852    /// `caixa-operator` per-reconcile-step diagnostic log line
1853    /// enumerating accepted wire forms on an unknown-policy rejection,
1854    /// a future
1855    /// `tracing::field::valuable::Value::List` structured-log accepted-
1856    /// wire-form emit — now reach for one lifted substrate-primitive
1857    /// roster rather than open-coding a three-string array-literal
1858    /// (`["Permanent", "Temporary", "Transient"]`) whose arm-set has no
1859    /// compile-time link back to the typed [`RestartPolicy`] enum. A
1860    /// future arm addition (an OTP-`intrinsic` fourth arm the theory
1861    /// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1862    /// might reach for once the three canonical OTP restart policies
1863    /// stop covering the substrate's discovered load-shape) extends
1864    /// this roster as a single edit — paired with the [`Self::as_str`]
1865    /// match's compiler-checked exhaustiveness on the new arm — and
1866    /// every consumer picks up the new wire form by construction rather
1867    /// than a coordinated array-literal rewrite across every downstream
1868    /// site.
1869    ///
1870    /// Length is pinned load-bearing at `RestartPolicy::ALL.len()`
1871    /// (three) by
1872    /// [`tests::restart_policy_wire_names_covers_every_arm`], every
1873    /// variant's [`Self::as_str`] projection is pinned to a member of
1874    /// the roster so a silent skew between the emitter's arm-set and
1875    /// this const's arm-set trips at caixa-core test time rather than at
1876    /// a downstream consumer's accepted-set enumeration miss, and every
1877    /// entry is further pinned to open with an ASCII uppercase byte so
1878    /// a silent collapse of the `PascalCase` wire-form axis with the
1879    /// peer kebab-case dispatcher-catalog axis (an entry byte-identical
1880    /// to a sibling [`Self::discriminant`] kebab byte-string that would
1881    /// let a wire-axis consumer accept the dispatcher-catalog
1882    /// vocabulary) trips here rather than at a downstream K8s-CR round-
1883    /// trip miss.
1884    pub const WIRE_NAMES: &'static [&'static str] = &[
1885        crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
1886        crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
1887        crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
1888    ];
1889
1890    /// Canonical PascalCase discriminator scalar this variant serializes
1891    /// as under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`]. The three
1892    /// arms return the paired
1893    /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1894    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1895    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] lifted
1896    /// constants so every substrate consumer that dispatches on the
1897    /// per-child restart-decision policy (the future wasm-operator's
1898    /// per-child post-exit restart-decision branch, the future M4
1899    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
1900    /// admission-time enum-arm bind, the `caixa-operator`'s hierarchical
1901    /// reconciliation scheduler's per-child-policy fan-out) reads the
1902    /// same byte-string the `Serialize` derive emits — the pin test in
1903    /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
1904    /// asserts the two paths agree, peer of the M2
1905    /// [`RestartStrategy::as_str`] (09ffb2d) on the sibling per-supervisor
1906    /// sibling-restart-strategy axis and the M3
1907    /// [`crate::aplicacao::PlacementStrategy::as_str`] (cc8f749) on the
1908    /// per-Aplicacao distribution-strategy axis — the third of three
1909    /// OTP-shaped closed-enum discriminator axes on the caixa typed
1910    /// surface to converge onto the same three-path-convergence
1911    /// (`Serialize` derive → `as_str` helper → lifted constant)
1912    /// drift-detection posture.
1913    #[must_use]
1914    pub const fn as_str(self) -> &'static str {
1915        match self {
1916            Self::Permanent => crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
1917            Self::Temporary => crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
1918            Self::Transient => crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
1919        }
1920    }
1921
1922    /// Substrate-canonical reverse projection on the `:children :restart`
1923    /// closed-set axis — parses the `PascalCase` discriminator scalar
1924    /// back to the typed variant, or `None` when `s` is outside the
1925    /// closed-set arm-string set [`Self::as_str`] emits. Dispatches on
1926    /// the same lifted
1927    /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1928    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1929    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] constants
1930    /// the [`Self::as_str`] emitter walks, so the parse and emit halves
1931    /// of the round-trip migrate through one caixa-core edit on any
1932    /// future arm addition.
1933    ///
1934    /// Prior to this lift the substrate carried only the forward
1935    /// `Self → &str` projection on the OTP per-child restart-policy
1936    /// axis (the [`Self::as_str`] emitter, the [`std::fmt::Display`]
1937    /// impl routed through it, the `Serialize` derive that emits the
1938    /// same byte-string under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`])
1939    /// plus the kebab-case dispatcher-catalog identity via
1940    /// [`Self::discriminant`] — every non-serde consumer that wanted to
1941    /// parse a wire-form `PascalCase` policy scalar had to re-inline a
1942    /// three-arm `match s { "Permanent" => …, "Temporary" => …,
1943    /// "Transient" => …, _ => … }` cascade that expressed no
1944    /// compile-time link back to the typed variant's canonical lifted
1945    /// constant. A future variant rename or per-arm serde-attribute
1946    /// drift would silently split the wire byte-string one non-serde
1947    /// consumer parsed from the one the emitter wrote, with the failure
1948    /// surfacing at the operator's reconcile posture (a `:temporary`
1949    /// `oneShot` child being restarted on clean exit, treating the
1950    /// successful-completion signal as failure and re-running the
1951    /// completion-terminal one-shot indefinitely; a `:transient` child
1952    /// that clean-exited being restarted, masking the clean-completion
1953    /// contract) far from the rebrand commit and with no field naming
1954    /// the drift.
1955    ///
1956    /// Distinct axis from the [`std::str::FromStr`] impl the
1957    /// [`gen_platform::FromStrKind`] derive already installs on this
1958    /// enum by design, not by drift: `FromStr` parses the *kebab-case*
1959    /// dispatcher-catalog identity (`"permanent"` / `"temporary"` /
1960    /// `"transient"` — the inverse of [`Self::discriminant`]), while
1961    /// this method inverts the `PascalCase` wire byte-string
1962    /// [`Self::as_str`] emits. The two-axis split lets the dispatcher-
1963    /// catalog identity live in kebab-case (where every peer catalog
1964    /// identifier already lives) without forcing a wire-format rename
1965    /// on the tatara-lisp author surface (`:restart Permanent`,
1966    /// `PascalCase`) — the same two-axis distinction the sibling
1967    /// [`RestartStrategy::from_wire`] (4eec29c) /
1968    /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
1969    /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
1970    /// carry on their peer closed-set typed-enum wire round-trips.
1971    ///
1972    /// Same closed-set-reverse-projection discipline the sibling
1973    /// [`RestartStrategy::from_wire`] (4eec29c) /
1974    /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
1975    /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342) /
1976    /// [`crate::aplicacao::RateLimitUnit::from_suffix`] typed enums
1977    /// carry on the peer wire-side `str → Self` axes — extended onto
1978    /// the M2 OTP-shape per-child restart-policy closed-set axis, the
1979    /// sixth substrate-side closed-set typed enum (and the third and
1980    /// final OTP-shape closed-enum discriminator axis) to converge on
1981    /// the two-way `str ↔ Self` round-trip. Method-named `from_wire`
1982    /// (not `from_str`) to match the peer [`RestartStrategy::from_wire`]
1983    /// shape verbatim and side-step the [`std::str::FromStr`] impl the
1984    /// derive already installs on the sibling kebab-case axis. Returns
1985    /// `Option<Self>` (rather than `Result<Self, _>`) to match the peer
1986    /// shapes: the caller picks the diagnostic form appropriate for
1987    /// its use site.
1988    #[must_use]
1989    pub fn from_wire(s: &str) -> Option<Self> {
1990        match s {
1991            crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT => Some(Self::Permanent),
1992            crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY => Some(Self::Temporary),
1993            crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT => Some(Self::Transient),
1994            _ => None,
1995        }
1996    }
1997}
1998
1999/// [`std::fmt::Display`] routed through [`RestartPolicy::as_str`], so the
2000/// pretty-printed byte-string every consumer that formats the policy as
2001/// user-facing text lands on (the future wasm-operator's per-child
2002/// post-exit restart-decision diagnostic line, the future `feira app
2003/// graph` per-child restart column, the future M4
2004/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
2005/// admission-webhook rejection body) reaches for the same lifted
2006/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2007/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2008/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2009/// wire-format `Serialize` derive already emits under
2010/// [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
2011/// [`RestartPolicy::as_str`] helper already returns.
2012///
2013/// Pre-convergence the two paths structurally disagreed — the
2014/// `#[derive(gen_platform::Discriminant)]` + `#[discriminant(also_display)]`
2015/// route (now retired here) sent [`std::fmt::Display`] through the
2016/// gen-platform discriminant catalog string, which arrives kebab-case as
2017/// `"permanent"` / `"temporary"` / `"transient"` on this three-arm enum
2018/// (whose variant names each collapse to their own lowercase form under
2019/// the kebab-case transform), while the wire format ran as `PascalCase`
2020/// `"Permanent"` / `"Temporary"` / `"Transient"` through the un-`rename`d
2021/// serde derive. Every consumer that formatted the policy for a
2022/// diagnostic line, a graph column, or a rejection body under
2023/// `format!("{v}")` therefore landed under a different byte-string than
2024/// the wire format the operator's per-child-policy dispatch keyed off —
2025/// a silent split whose apply-time symptom (a `format!("{v}")`-carrying
2026/// diagnostic quoting `"permanent"` while the wire scalar the operator
2027/// probed was `"Permanent"`) surfaced as a confused correlate at
2028/// operator-log time far from the two-declaration site.
2029///
2030/// Routing `Display` through [`RestartPolicy::as_str`] closes the third
2031/// path: every `format!("{v}")` call reaches the same lifted
2032/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the wire format
2033/// and the [`RestartPolicy::as_str`] helper route through — `Debug` (the
2034/// compiler-derived variant name), `Display` (via `as_str`), and `Serialize`
2035/// (via the un-`rename`d derive) all resolve to the same `PascalCase`
2036/// byte-string per variant. A future variant rename or
2037/// `#[serde(rename_all = "kebab-case")]` attribute reaches every path at
2038/// exactly one place, structurally.
2039///
2040/// The dispatcher-catalog identity remains kebab-case — [`Self::discriminant`]
2041/// (from `#[derive(gen_platform::Discriminant)]`) still returns
2042/// `"permanent"` / `"temporary"` / `"transient"`, and the fleet-wide
2043/// [`gen_platform::register_dispatcher!("caixa.restart-policy", …)`]
2044/// registration keys the catalog off the same kebab identity. The two
2045/// naming worlds now live on separate typed methods (`Display` /
2046/// `as_str` for the wire byte-string, `discriminant` for the catalog
2047/// identity) rather than sharing one `Display` route that structurally
2048/// disagrees with the wire format.
2049///
2050/// Pin tests
2051/// [`tests::restart_policy_display_routes_through_as_str_helper`]
2052/// and
2053/// [`tests::restart_policy_display_matches_serialized_wire_byte_string`]
2054/// assert the three paths agree byte-for-byte on every variant, so a
2055/// future variant rename or per-arm serde attribute drift is a build
2056/// error visible at caixa-core test time, not a silent per-consumer
2057/// dispatch miss at apply / reconcile time.
2058///
2059/// Mirrors the M3 [`crate::aplicacao::PlacementStrategy`] `Display` impl
2060/// (aplicacao.rs:2306) on the per-Aplicacao distribution-strategy axis
2061/// and the sibling [`RestartStrategy`] `Display` impl on the
2062/// per-supervisor sibling-restart-strategy axis — same three-path-
2063/// convergence discipline, extended to close the third and final of
2064/// three OTP-shaped closed-enum discriminator axes on the caixa typed
2065/// surface.
2066impl std::fmt::Display for RestartPolicy {
2067    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2068        f.write_str(self.as_str())
2069    }
2070}
2071
2072/// Substrate-canonical [`AsRef<str>`] projection on the M2
2073/// per-child-restart-policy [`RestartPolicy`] closed-set typed enum —
2074/// routes through the same [`RestartPolicy::as_str`] `pub const fn`
2075/// scalar accessor the paired [`std::fmt::Display`] impl and the
2076/// un-`rename`d [`serde::Serialize`] derive already key off, so any
2077/// future consumer that binds a [`RestartPolicy`] through the
2078/// standard-library `impl AsRef<str>` bound (a future
2079/// [`caixa-feira`] `feira supervisor --restart <arm>` verb that
2080/// composes the emitted `PascalCase` wire scalar into a
2081/// [`std::process::Command::arg`] shell-out of the future
2082/// wasm-operator's per-child admission gate, a per-child structured-
2083/// log recorder on the future `caixa-operator`'s hierarchical
2084/// reconciliation surface that accepts `impl AsRef<str>` at the
2085/// `tracing::field::Value` `Str`-arm, a [`std::collections::HashMap`]
2086/// lookup keyed on the restart-policy wire byte through
2087/// `map.get::<str>(policy.as_ref())` on a future per-policy
2088/// dispatch table) reaches the paired
2089/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2090/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2091/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
2092/// lifted-const through one substrate-primitive dispatch rather
2093/// than an open-coded `.as_str()` projection at every wire-up.
2094///
2095/// Peer of the sibling [`std::fmt::Display`] impl on the same
2096/// primitive — both delegate to the shared [`RestartPolicy::as_str`]
2097/// `pub const fn` accessor, so [`format!("{v}")`], `v.as_str()`, and
2098/// `<RestartPolicy as AsRef<str>>::as_ref(&v)` resolve to the same
2099/// byte-string per instance by construction. A future variant rename
2100/// or `#[serde(rename_all = "kebab-case")]` attribute-drift on the
2101/// enum reaches every one of the three paths (plus the wire-format
2102/// `Serialize` derive that already routes through the same lifted
2103/// const) through exactly one caixa-core edit.
2104///
2105/// Same "route the trait impl through the substrate-primitive
2106/// accessor" discipline the sibling [`crate::CaixaVersion`]
2107/// [`AsRef<str>`] impl (16d5c7e) and the paired M2
2108/// [`RestartStrategy`] [`AsRef<str>`] impl (63eb1a4) carry — extends
2109/// the axis onto the paired per-child-restart-decision-policy
2110/// sibling on the same M2 `:supervisor` slot (the second M2
2111/// OTP-shape closed-set typed enum to converge onto the standard-
2112/// library [`AsRef<str>`] projection). Rust-side newtype/typed-enum
2113/// convention pairs [`AsRef<str>`] and [`fmt::Display`] on the same
2114/// primitive so a caller who has one has both; before this lift,
2115/// [`RestartPolicy`] carried [`fmt::Display`] but not the paired
2116/// [`AsRef<str>`] impl the convention names.
2117///
2118/// Pinned load-bearing by
2119/// [`tests::restart_policy_as_ref_str_routes_through_as_str_accessor`]
2120/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2121/// three-arm closed set) and
2122/// [`tests::restart_policy_as_ref_str_routes_through_display_via_shared_accessor`]
2123/// (three-path convergence: `AsRef<str>` + `Display` + `as_str` all
2124/// resolve to the same lifted `SUPERVISOR_CHILD_RESTART_*` const per
2125/// arm) — any future silent detour that routes the impl through a
2126/// divergent projection (a per-arm inline `match self { … }`
2127/// re-inlining that opens a compile-time link to the un-lifted
2128/// arm-literal, a swap onto the kebab-case
2129/// [`gen_platform::Discriminant`] catalog identity that would
2130/// collide the wire axis with the dispatcher-catalog axis) trips at
2131/// caixa-core test time under `assert_eq!` rather than at a
2132/// downstream `impl AsRef<str>`-bound consumer's silent split.
2133impl AsRef<str> for RestartPolicy {
2134    fn as_ref(&self) -> &str {
2135        self.as_str()
2136    }
2137}
2138
2139/// Trait-idiomatic reverse projection on the M2-OTP-shape per-child
2140/// restart-policy [`RestartPolicy`] closed-set typed enum — routes
2141/// byte-for-byte through the paired substrate-primitive
2142/// [`RestartPolicy::from_wire`] `Option<Self>` accessor so every future
2143/// consumer that binds a `PascalCase` `:children :restart` wire
2144/// byte-string through the standard-library `.try_into()` / [`TryFrom`]
2145/// axis (a future [`caixa-feira`] `feira supervisor --restart
2146/// <Permanent|Temporary|Transient>` CLI arg-parse that composes into
2147/// `let restart: RestartPolicy = s.try_into()?`, a future
2148/// `mesh.pleme.io/v1alpha1/Supervisor` CR admission-webhook that folds a
2149/// `spec.children[*].restart: String` field through
2150/// `RestartPolicy::try_from(&s)?`, a generic
2151/// `<T: TryFrom<&str>>`-bound loader over any of the substrate's closed-
2152/// set typed enums) reaches the same three-arm accept-set the sibling
2153/// [`RestartPolicy::from_wire`] resolver parses through and the sibling
2154/// [`RestartPolicy::as_str`] emits, rather than an open-coded per-arm
2155/// `match s { "Permanent" => …, "Temporary" => …, "Transient" => …, _ =>
2156/// … }` cascade whose arm-set has no compile-time link back to the
2157/// substrate primitive.
2158///
2159/// Complements the pre-existing forward-projection triple
2160/// ([`std::fmt::Display`], [`AsRef<str>`], [`RestartPolicy::as_str`])
2161/// with the paired trait-idiomatic reverse-projection axis: Rust-side
2162/// newtype/typed-enum convention pairs [`AsRef<str>`] with either
2163/// [`std::str::FromStr`] or [`TryFrom<&str>`] on the same primitive so a
2164/// caller who can project *out to* a `&str` can also project *in from*
2165/// one. The [`TryFrom<&str>`] axis is deliberately chosen over
2166/// [`std::str::FromStr`] to sidestep the `clippy::should_implement_trait`
2167/// lint the sibling method-named [`RestartPolicy::from_wire`] would
2168/// trigger under a `FromStr` impl and to avoid colliding with the
2169/// [`std::str::FromStr`] impl the [`gen_platform::FromStrKind`] derive
2170/// already installs on the paired *kebab-case dispatcher-catalog* axis
2171/// (which parses `"permanent"` / `"temporary"` / `"transient"`, the
2172/// inverse of [`Self::discriminant`]) — this impl closes the trait-
2173/// idiomatic reverse axis on the *`PascalCase` wire* half without
2174/// disturbing either the method-named `from_wire` shape every sibling
2175/// closed-set typed enum on the substrate already carries or the
2176/// pre-existing `FromStr` on the dispatcher-catalog half, keeping the
2177/// two-axis split the sibling [`Self::from_wire`] doc block motivates.
2178///
2179/// `type Error = ()` matches the sibling [`RestartPolicy::from_wire`]'s
2180/// `Option<Self>` return-shape's deliberate deferral of error typing: the
2181/// caller picks the diagnostic form appropriate for its use site (a
2182/// future `feira supervisor --restart` arg-parse composes its own
2183/// per-verb "unknown restart: <arg> — accepted: {…}" message enumerating
2184/// [`RestartPolicy::ALL`], a future M4 admission-webhook rejection body
2185/// wraps the `Err(())` outcome with the accepted-set enumeration for
2186/// operator diagnostics, a `Result::map_err` at the call site lifts the
2187/// unit-error to a per-verb error type). Same shape the peer
2188/// [`RestartStrategy`] (5b828ed) on the sibling per-supervisor axis,
2189/// [`crate::CaixaKind`] (3c83606), [`crate::CaixaDialeto`] (bf33136), and
2190/// [`crate::aplicacao::PlacementStrategy`] (6fd00cd) blocks motivate on
2191/// their peer closed-set typed enums' reverse projections.
2192///
2193/// The paired [`TryFrom<&str>`] impl reaches the same three-arm accept-
2194/// set the [`RestartPolicy::from_wire`] resolver dispatches through, so
2195/// any future arm addition (an OTP-`intrinsic` fourth arm the theory
2196/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
2197/// might reach for once the three canonical OTP restart policies stop
2198/// covering the substrate's discovered load-shape) grows the trait-
2199/// idiomatic axis by construction — one caixa-core edit on
2200/// [`RestartPolicy::from_wire`] extends both the method-named reverse
2201/// projection every existing consumer keys off and the trait-idiomatic
2202/// reverse projection this impl exposes, without a coordinated rewrite
2203/// across every future `TryFrom<&str>`-bound consumer's arm-set.
2204///
2205/// Extends the substrate-wide closed-set-enum reverse-projection family
2206/// ([`crate::CaixaKind`] via 3c83606, [`crate::CaixaDialeto`] via
2207/// bf33136, [`crate::aplicacao::PlacementStrategy`] via 6fd00cd, and
2208/// [`RestartStrategy`] via 5b828ed) onto the third and final OTP-shape
2209/// closed-enum discriminator axis on the caixa surface — the paired
2210/// per-child `:children :restart` closed set the future wasm-operator's
2211/// hierarchical reconciliation scheduler's per-child post-exit
2212/// restart-decision branch keys off end-to-end.
2213///
2214/// Pinned load-bearing by
2215/// [`tests::restart_policy_try_from_str_routes_through_from_wire_accessor`]
2216/// (byte-parity pin against [`RestartPolicy::from_wire`] across the
2217/// three-arm accept-set),
2218/// [`tests::restart_policy_try_from_str_rejects_unknown_byte_strings`]
2219/// (rejection witness against silent accept-set widening), and
2220/// [`tests::restart_policy_try_from_str_and_from_wire_partition_the_accept_set`]
2221/// (cross-axis partition pin locking the trait and method-named
2222/// projections onto one accept-set).
2223impl TryFrom<&str> for RestartPolicy {
2224    type Error = ();
2225
2226    fn try_from(s: &str) -> Result<Self, Self::Error> {
2227        Self::from_wire(s).ok_or(())
2228    }
2229}
2230
2231/// Trait-idiomatic forward projection on the M2-OTP-shape per-child
2232/// restart-policy [`RestartPolicy`] closed-set typed enum — routes
2233/// byte-for-byte through the paired substrate-primitive
2234/// [`RestartPolicy::as_str`] `pub const fn` accessor. Return type is
2235/// `&'static str` by construction — every [`RestartPolicy::as_str`] arm
2236/// resolves to a [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const
2237/// &str` with `'static` lifetime, so the trait's return-type promise is
2238/// upheld structurally without a [`String::leak`] cast or a per-arm inline
2239/// literal.
2240///
2241/// Every future consumer that specifically needs `&'static str` lifetime
2242/// bytes on the per-child restart-decision axis (a
2243/// [`tracing::field::valuable::Value::Str`] recording where the `Str`
2244/// arm's typing demands `&'static str`, a
2245/// [`std::borrow::Cow::Borrowed`]`::<'static, str>(policy.into())` composer
2246/// on the future M4 admission-webhook rejection body where the
2247/// `Cow<'static, str>` typing rules out the sibling [`AsRef<str>`]
2248/// borrowed return, a generic `<T: Into<&'static str>>`-bound serializer
2249/// or error formatter that requires the `'static` bound) reaches the same
2250/// lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2251/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2252/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] substrate-
2253/// primitive dispatch rather than an open-coded per-arm literal cascade
2254/// whose arm-set has no compile-time link back to the substrate primitive.
2255///
2256/// Peer of the sibling M2-OTP-shape [`RestartStrategy`] forward-projection
2257/// impl (523157d) on the per-supervisor sibling-restart-strategy axis —
2258/// the second (and second-of-two-in-M2) closed-set typed enum on the
2259/// caixa surface to converge onto the paired trait-idiomatic forward-
2260/// projection axis. With this lift the paired per-child
2261/// `:children :restart` closed-set typed enum carries the full sibling
2262/// quintet ([`std::fmt::Display`], [`AsRef<str>`], [`Self::as_str`],
2263/// [`TryFrom<&str>`] via 6fdd0d9, `From<Self> for &'static str` via this
2264/// lift) plus the round-trip witness through both the trait-idiomatic
2265/// (`From<Self> for &'static str` + `TryFrom<&str>`) and the method-named
2266/// (`as_str` + `from_wire`) axis pairs — mirrors the sibling
2267/// [`RestartStrategy`] surface arm-for-arm, so every future arm addition
2268/// (an OTP-`intrinsic` fourth arm the theory
2269/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
2270/// might reach for once the three canonical OTP restart policies stop
2271/// covering the substrate's discovered load-shape) grows the trait-
2272/// idiomatic forward axis by construction: one caixa-core edit on
2273/// [`RestartPolicy::as_str`] extends every one of the five sibling
2274/// forward-projection paths ([`std::fmt::Display`], [`AsRef<str>`],
2275/// [`Self::as_str`] itself, this `From<Self> for &'static str`, and the
2276/// un-`rename`d [`serde::Serialize`] derive that also emits `as_str`'s
2277/// bytes) without a coordinated rewrite across every future
2278/// `Into<&'static str>`-bound consumer's arm-set.
2279///
2280/// Pinned load-bearing by
2281/// [`tests::restart_policy_from_into_static_str_routes_through_as_str_accessor`]
2282/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2283/// three-arm emit-set, plus a `const`-context materialization witness for
2284/// the `&'static str` lifetime promise) and
2285/// [`tests::restart_policy_from_into_static_str_and_as_str_partition_the_emit_set`]
2286/// (partition pin asserting `<&'static str as From<RestartPolicy>>::from`
2287/// and [`RestartPolicy::as_str`] agree on every arm, plus a two-way
2288/// round-trip witness through the paired trait-idiomatic reverse-
2289/// projection axis [`TryFrom<&str>`] (6fdd0d9): every
2290/// `policy.into::<&'static str>()` output re-parses back through
2291/// [`RestartPolicy::try_from`] to the original variant, closing the two-
2292/// way `Self ↔ &'static str` round-trip on the trait-idiomatic axis pair).
2293impl From<RestartPolicy> for &'static str {
2294    fn from(policy: RestartPolicy) -> &'static str {
2295        policy.as_str()
2296    }
2297}
2298
2299/// Trait-idiomatic *forward* projection on [`RestartPolicy`] from a
2300/// *borrowed* input onto the `&'static str` axis — the borrowed-input
2301/// companion to the paired owned-input [`From<RestartPolicy> for
2302/// &'static str`] impl immediately above. Routes byte-for-byte through
2303/// the same substrate-primitive [`RestartPolicy::as_str`] `pub const
2304/// fn` accessor so every consumer that binds a `&RestartPolicy`
2305/// through the standard-library `.into()` / [`From<&Self> for &'static
2306/// str`] axis (a `RestartPolicy::ALL.iter().map(<&'static
2307/// str>::from).collect::<Vec<_>>()` per-arm accept-set materializer —
2308/// whose iterator over `&'static [RestartPolicy]` yields
2309/// `&RestartPolicy`, not `RestartPolicy`, so the owned-input
2310/// [`From<RestartPolicy>`] axis alone forces every call site through
2311/// an explicit `.copied()` / dereference / [`Copy`]-bound restatement
2312/// rather than the direct trait-idiomatic projection; a future generic
2313/// `<T: Copy + for<'a> Into<&'static str>>`-bound diagnostic column
2314/// that walks the `iter().map(Into::into)` shape verbatim across every
2315/// substrate-wide closed-set typed enum; the future wasm-operator's
2316/// per-child post-exit restart-decision diagnostic line that composes
2317/// the accepted-set enumeration from an iterated
2318/// `RestartPolicy::ALL.iter().map(|p| p.into())` pipe rather than a
2319/// per-arm `match p { … }` cascade; a future
2320/// `HashMap::<&'static str, RestartPolicy>::from_iter(
2321///     RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))`-style
2322/// per-policy reverse-lookup table the sibling [`TryFrom<&str>`] impl
2323/// cannot compose without this borrowed-input axis in place) reaches
2324/// the same three-arm lifted
2325/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2326/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2327/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2328/// paired owned-input [`From<RestartPolicy> for &'static str`], the
2329/// sibling [`std::fmt::Display`], [`AsRef<str>`], and
2330/// [`RestartPolicy::as_str`] surfaces already return.
2331///
2332/// Fifth peer on the substrate-wide trait-idiomatic *borrowed-input*
2333/// forward-projection family opened on [`crate::dep::DepList`]
2334/// (64aa742) and extended onto [`crate::CaixaKind`] (5ab993a),
2335/// [`crate::CaixaDialeto`] (807b0b5), and the paired
2336/// per-supervisor sibling-restart-strategy [`RestartStrategy`]
2337/// (e941836). Rust's `From` trait does not auto-derive the
2338/// `From<&Self>` sibling from a `From<Self>` impl (the blanket
2339/// `impl<T, U> From<&T> for U where T: Copy, U: From<T>` does not
2340/// exist in `core`), so every closed-set typed enum that carries the
2341/// owned-input axis but not the borrowed-input axis forces every
2342/// borrowed-input call site through a `.copied()` /
2343/// `<&'static str>::from(*policy)` / `policy.as_str()` detour whose
2344/// type bounds have no compile-time link to the substrate primitive.
2345/// [`RestartPolicy`] is the second (and second-of-two-in-M2)
2346/// OTP-shape peer to converge onto this campaign — sibling of the
2347/// paired per-supervisor [`RestartStrategy`] borrowed-input axis, so
2348/// with this lift both closed-set typed enums on the M2 `:supervisor`
2349/// slot now carry the full sibling quintet ([`std::fmt::Display`],
2350/// [`AsRef<str>`], [`Self::as_str`], `From<Self> for &'static str`,
2351/// `From<&Self> for &'static str`) plus the paired trait-idiomatic
2352/// reverse projection [`TryFrom<&str>`], closing the borrowed-input
2353/// forward-projection axis on the M2 OTP-shape slot as a unit.
2354///
2355/// Same three-path convergence discipline as the paired owned-input
2356/// impl (this borrowed-input axis, the paired owned-input
2357/// [`From<RestartPolicy> for &'static str`], and
2358/// [`RestartPolicy::as_str`] all route through the same lifted
2359/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const), so a future
2360/// variant rename or per-arm serde-attribute drift reaches every one
2361/// of the six sibling forward-projection paths
2362/// ([`std::fmt::Display`], [`AsRef<str>`], [`Self::as_str`],
2363/// [`From<Self> for &'static str`], this [`From<&Self> for &'static
2364/// str`], and the un-`rename`d [`serde::Serialize`] derive that also
2365/// emits [`Self::as_str`]'s bytes) through exactly one caixa-core
2366/// edit.
2367///
2368/// The [`RestartPolicy::as_str`] emit and [`RestartPolicy::from_wire`]
2369/// parse share the same `PascalCase` vocabulary by construction, so
2370/// the borrowed-input forward axis and the reverse axis compose
2371/// directly — the round-trip witness pin below locks this direct
2372/// composition without the intermediate wire-vocab hop the peer
2373/// [`crate::CaixaKind`] axis pair requires.
2374///
2375/// Pinned load-bearing by
2376/// [`tests::restart_policy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
2377/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2378/// three-arm emit-set via a borrowed input, plus a `const`-context
2379/// materialization witness for the `&'static str` lifetime promise,
2380/// plus a blanket `.into()` shape) and
2381/// [`tests::restart_policy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
2382/// (cross-axis partition pin against the paired owned-input
2383/// [`From<RestartPolicy> for &'static str`] impl, plus a
2384/// `.iter().map(Into::into)` pipe witness over
2385/// [`RestartPolicy::ALL`], plus a direct round-trip witness through
2386/// [`TryFrom<&str>`] that closes the two-way `&Self → &'static str →
2387/// Self` round-trip without the wire-vocab intermediate the peer
2388/// [`crate::CaixaKind`] axis pair requires).
2389impl From<&RestartPolicy> for &'static str {
2390    fn from(policy: &RestartPolicy) -> &'static str {
2391        policy.as_str()
2392    }
2393}
2394
2395/// Trait-idiomatic *owned-`String`* forward projection on the second
2396/// M2 OTP-shape closed-set typed enum ([`RestartPolicy`]) — the
2397/// owned-heap-string companion to the paired `&'static str`-returning
2398/// [`From<RestartPolicy> for &'static str`] / [`From<&RestartPolicy>
2399/// for &'static str`] impls immediately above. Routes byte-for-byte
2400/// through the substrate-primitive [`RestartPolicy::as_str`] `pub
2401/// const fn` accessor (via [`str::to_owned`]) so every consumer that
2402/// binds a [`RestartPolicy`] through the standard-library `.into()` /
2403/// [`From<Self> for String`] (equivalently [`Into<String>`]) axis — a
2404/// future `serde_json::Value::String(policy.into())` structured-payload
2405/// composer where the `Value::String` arm typing demands an owned
2406/// [`String`] and the sibling [`&'static str`]-returning axis forces
2407/// an explicit `.to_owned()` / `String::from` restatement at every
2408/// call site, a future `HashMap::<String, RestartPolicy>::from_iter(
2409/// RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))` per-policy
2410/// lookup where the map's key type is owned [`String`] rather than
2411/// [`&'static str`], a future `Cow::<'static, str>::Owned(policy.into())`
2412/// composer on the future M4 admission-webhook rejection body's
2413/// owned-arm, the future wasm-operator's per-child post-exit
2414/// diagnostic emit `serde_json::json!({ "restart": policy })` where the
2415/// JSON serializer's `Serialize` impl on [`String`] owns the emit-path
2416/// — reaches the same three-arm lifted
2417/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2418/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2419/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2420/// paired [`std::fmt::Display`], [`AsRef<str>`],
2421/// [`RestartPolicy::as_str`], and the two `&'static str`-returning
2422/// forward-projection impls already return.
2423///
2424/// Extends the trait-idiomatic *owned-`String`* forward-projection
2425/// axis onto the second-of-two M2 OTP-shape closed-set typed enums on
2426/// the caixa surface — mirror of the first-mover
2427/// [`From<RestartStrategy> for String`] (7baa18a) that opened this
2428/// axis on the sibling supervisor-level strategy enum. Rust's standard
2429/// library does not carry a blanket `impl<T: AsRef<str>> From<T> for
2430/// String` (nor an `impl<T: fmt::Display> From<T> for String`), so
2431/// every closed-set typed enum that carries the paired `AsRef<str>` /
2432/// `Display` / `From<Self> for &'static str` triple but not the
2433/// owned-[`String`] axis forces every owned-string call site through a
2434/// `.to_string()` / `.as_str().to_owned()` / `String::from(policy.as_str())`
2435/// detour whose type bounds have no compile-time link to the
2436/// substrate primitive.
2437///
2438/// Deliberately routes through the human-readable
2439/// [`RestartPolicy::as_str`] axis — for this enum the wire format
2440/// (`PascalCase`, tatara-lisp author surface `:restart Permanent`) and
2441/// the diagnostic byte-string share the same vocabulary by
2442/// construction (unlike the sibling [`crate::CaixaKind`] enum whose
2443/// two axes diverge), so the owned-[`String`] projection lands
2444/// byte-identically on both the wire vocabulary the paired
2445/// [`serde::Serialize`] derive emits and the diagnostic vocabulary the
2446/// [`RestartPolicy::as_str`] helper returns, and — because the paired
2447/// [`TryFrom<&str>`] / [`RestartPolicy::from_wire`] reverse-projection
2448/// axis parses the same `PascalCase` vocabulary — the direct two-way
2449/// `Self → String → Self` round-trip composes without the wire-vocab
2450/// intermediate hop the peer [`crate::CaixaKind`] owned-[`String`]
2451/// axis pair requires.
2452///
2453/// Pinned load-bearing by
2454/// [`tests::restart_policy_from_into_owned_string_routes_through_as_str_accessor`]
2455/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2456/// three-arm emit-set, plus a blanket `.into::<String>()` shape
2457/// witness) and
2458/// [`tests::restart_policy_from_into_owned_string_and_static_str_agree_on_every_arm`]
2459/// (cross-axis partition pin against the paired owned-input
2460/// [`From<RestartPolicy> for &'static str`] impl and the sibling
2461/// [`ToString::to_string`] surface routed through [`std::fmt::Display`],
2462/// plus a `.iter().copied().map(String::from)` pipe witness over
2463/// [`RestartPolicy::ALL`], plus a direct round-trip witness through
2464/// [`TryFrom<&str>`] on the owned-[`String`]'s [`String::as_str`]
2465/// borrow that closes the two-way `Self → String → Self` round-trip
2466/// on the trait-idiomatic owned-[`String`] forward + reverse axis
2467/// pair).
2468impl From<RestartPolicy> for String {
2469    fn from(policy: RestartPolicy) -> String {
2470        policy.as_str().to_owned()
2471    }
2472}
2473
2474/// Trait-idiomatic *borrowed-input, owned-`String` output* forward
2475/// projection on the second-of-two M2 OTP-shape closed-set typed enum
2476/// ([`RestartPolicy`]) — the fourth (and closing) corner of the
2477/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
2478/// projection family on this enum, mirror of the first-mover
2479/// [`From<&RestartStrategy> for String`] (579385f) that opened the
2480/// 2×2-completion corner on the sibling supervisor-level strategy
2481/// enum. Routes byte-for-byte through the substrate-primitive
2482/// [`RestartPolicy::as_str`] `pub const fn` accessor (via
2483/// [`str::to_owned`]) so every consumer that holds a borrowed
2484/// [`&RestartPolicy`] and needs an owned [`String`] — a future
2485/// `serde_json::Value::String(String::from(&policy))` structured-payload
2486/// composer over a borrowed field, a future `Iterator::map` over
2487/// `&[RestartPolicy]` that projects to owned keys through
2488/// `.iter().map(String::from)`, a future `HashMap::<String,
2489/// RestartPolicy>::from_iter` that keys off a borrowed-iteration axis
2490/// where dereferencing the policy would force an unnecessary `Copy` at
2491/// every step, the future wasm-operator's per-supervisor
2492/// `child_policies.iter().map(String::from).collect()` per-child post-
2493/// exit restart-decision diagnostic emit whose iteration axis is
2494/// borrowed by construction — reaches the same three-arm lifted
2495/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2496/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2497/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2498/// paired [`std::fmt::Display`], [`AsRef<str>`],
2499/// [`RestartPolicy::as_str`], and the three other trait-idiomatic
2500/// forward-projection impls
2501/// ([`From<RestartPolicy> for &'static str`],
2502/// [`From<&RestartPolicy> for &'static str`],
2503/// [`From<RestartPolicy> for String`]) already return.
2504///
2505/// Second peer on the substrate-wide trait-idiomatic *borrowed-input,
2506/// owned-`String` output* forward-projection family opened on
2507/// [`crate::supervisor::RestartStrategy`] (579385f) — closes the
2508/// `{Self, &Self} × {&'static str, String}` 2×2 projection corner on
2509/// both M2 OTP-shape sibling peers (the paired supervisor-level
2510/// sibling-restart-strategy axis and the per-child restart-decision-
2511/// policy axis), so the whole M2 OTP-shape axis pair now carries the
2512/// full four-corner family by construction. Rust's standard library
2513/// does not carry a blanket `impl<T: AsRef<str>> From<&T> for String`
2514/// (nor an `impl<T: fmt::Display> From<&T> for String`), so every
2515/// closed-set typed enum that carries the paired `AsRef<str>` /
2516/// `Display` / `From<Self> for &'static str` / `From<&Self> for
2517/// &'static str` / `From<Self> for String` quintuple but not the
2518/// borrowed-input owned-[`String`] axis forces every borrowed-input
2519/// owned-string call site through a `policy.as_str().to_owned()` /
2520/// `String::from(*policy)` (with a spurious `Copy`) /
2521/// `policy.to_string()` (through `Display`) detour whose type bounds
2522/// have no compile-time link to the substrate primitive.
2523///
2524/// Deliberately routes through the human-readable
2525/// [`RestartPolicy::as_str`] axis — for this enum the wire format
2526/// (`PascalCase`, tatara-lisp author surface `:restart Permanent`) and
2527/// the diagnostic byte-string share the same vocabulary by
2528/// construction (unlike the sibling [`crate::CaixaKind`] enum whose
2529/// two axes diverge), so the borrowed-input owned-[`String`]
2530/// projection lands byte-identically on both the wire vocabulary the
2531/// paired [`serde::Serialize`] derive emits and the diagnostic
2532/// vocabulary the [`RestartPolicy::as_str`] helper returns, and —
2533/// because the paired [`TryFrom<&str>`] / [`RestartPolicy::from_wire`]
2534/// reverse-projection axis parses the same `PascalCase` vocabulary —
2535/// the direct two-way `&Self → String → Self` round-trip composes
2536/// without the wire-vocab intermediate hop the peer
2537/// [`crate::CaixaKind`] axis pair requires.
2538///
2539/// The remaining thirteen closed-set typed enums on the caixa
2540/// substrate surface (`CaixaKind`, `CaixaDialeto`, `DepList`,
2541/// `PlacementStrategy`, `WitShape`, `RateLimitUnit`,
2542/// `PathShapeViolation`, `InvariantKind`, `ArchVerdict`, `Severity`,
2543/// `FixSafety`, `Semantic`, `FerriteRuntime`) are the future targets
2544/// of this 2×2-completion campaign — each carries the same paired
2545/// quintuple that this borrowed-input owned-[`String`] axis extends
2546/// onto.
2547///
2548/// Pinned load-bearing by
2549/// [`tests::restart_policy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
2550/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2551/// three-arm emit-set through the borrowed-input surface) and
2552/// [`tests::restart_policy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
2553/// (cross-axis partition pin against the paired owned-input owned-
2554/// [`String`] [`From<RestartPolicy> for String`] impl, the paired
2555/// borrowed-input owned-[`&'static str`] [`From<&RestartPolicy> for
2556/// &'static str`] impl, and the sibling [`ToString::to_string`]
2557/// surface routed through [`std::fmt::Display`], plus a direct round-
2558/// trip witness through [`TryFrom<&str>`] on the owned-[`String`]'s
2559/// [`String::as_str`] borrow that closes the two-way
2560/// `&Self → String → Self` round-trip on the trait-idiomatic
2561/// borrowed-input owned-[`String`] forward + reverse axis pair).
2562impl From<&RestartPolicy> for String {
2563    fn from(policy: &RestartPolicy) -> String {
2564        policy.as_str().to_owned()
2565    }
2566}
2567
2568/// Trait-idiomatic *owned-input, [`std::borrow::Cow<'static, str>`]
2569/// output* forward projection on the M2 OTP-shape per-child-restart
2570/// [`RestartPolicy`] closed-set typed enum — extends the substrate-
2571/// wide [`std::borrow::Cow<'static, str>`] forward-projection family
2572/// opened on [`crate::CaixaKind`] (99c1735 owned-input, d45c409
2573/// borrowed-input) and first extended off it onto the sibling M2
2574/// OTP-shape sibling-restart [`RestartStrategy`] (7dd28b3 owned-input,
2575/// 9b3e4b3 borrowed-input) onto the second (and second-of-two-in-M2)
2576/// M2 OTP-shape closed-set fieldless typed enum peer on the caixa
2577/// surface (`:children :restart`). Routes byte-for-byte through the
2578/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
2579/// accessor (via [`std::borrow::Cow::Borrowed`]) so every consumer
2580/// that binds a [`RestartPolicy`] through the trait-idiomatic
2581/// [`std::borrow::Cow<'static, str>`] axis — a future
2582/// `axum::response::IntoResponse` composer whose per-policy
2583/// diagnostic-body typing rules out the sibling [`AsRef<str>`]
2584/// borrowed return, a future M4 admission-webhook rejection body
2585/// that composes the accepted-policy enumeration through the same
2586/// `RestartPolicy::ALL.iter().map(Cow::from)` shape [`crate::CaixaKind`]
2587/// and [`RestartStrategy`] already route through, a generic `<T: for<'a>
2588/// Into<std::borrow::Cow<'static, str>>>`-bound structured-log
2589/// emitter on a per-child-policy diagnostic column — reaches the same
2590/// three-arm lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`]
2591/// / [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2592/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2593/// paired [`std::fmt::Display`], [`AsRef<str>`],
2594/// [`RestartPolicy::as_str`], and the four
2595/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
2596/// forward-projection corners already return.
2597///
2598/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
2599/// [`std::borrow::Cow::Owned`] — the substrate-primitive
2600/// [`RestartPolicy::as_str`] accessor's return carries the `&'static
2601/// str` lifetime by construction (each `match` arm resolves to a
2602/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const &str`
2603/// with static lifetime), so the zero-alloc borrowed arm is the
2604/// type-correct projection with no runtime allocation.
2605///
2606/// Rust's standard library carries no blanket `impl<T: AsRef<str>>
2607/// From<T> for Cow<'static, str>` (nor an `impl<T: fmt::Display>
2608/// From<T> for Cow<'static, str>`), so the paired sibling
2609/// [`From<RestartPolicy> for &'static str`] (9fb37d0),
2610/// [`From<RestartPolicy> for String`] (7851725), [`AsRef<str>`], and
2611/// [`std::fmt::Display`] surfaces do not implicitly extend to a
2612/// [`Cow<'static, str>`]-bound call site — every such site is forced
2613/// through a `Cow::Borrowed(policy.as_str())` /
2614/// `Cow::Owned(policy.to_string())` open-code whose type bounds have
2615/// no compile-time link back to the substrate primitive until this
2616/// lift.
2617///
2618/// Second peer to extend the substrate-wide trait-idiomatic
2619/// [`std::borrow::Cow<'static, str>`] forward-projection axis off the
2620/// top-level [`crate::CaixaKind`] enum (99c1735 owned-input, d45c409
2621/// borrowed-input) onto the wider substrate — closes the M2 OTP-shape
2622/// tier of the campaign (both sibling peers, `RestartStrategy` and
2623/// `RestartPolicy`, now carry the owned-input Cow<'static, str>
2624/// forward projection) so the remaining eleven peers
2625/// (`PlacementStrategy`, `RateLimitUnit`, `DepList`, `CaixaDialeto`,
2626/// and the outside-`caixa-core` peers `WitShape`, `PathShapeViolation`,
2627/// `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`,
2628/// `FerriteRuntime`) are the future targets. Every future arm addition
2629/// (an OTP-`intrinsic` fourth restart policy the ABSORPTION-ROADMAP
2630/// might reach for once the three canonical OTP restart policies stop
2631/// covering the substrate's discovered load-shape) grows the
2632/// Cow<'static, str> axis by construction through one caixa-core edit
2633/// on [`RestartPolicy::as_str`] — rather than a coordinated rewrite
2634/// across every future Cow<'static, str>-bound consumer site.
2635///
2636/// Pinned load-bearing by
2637/// [`tests::restart_policy_from_into_static_cow_str_routes_through_as_str_accessor`]
2638/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
2639/// against [`RestartPolicy::as_str`] across the three-arm
2640/// [`RestartPolicy::ALL`]) and
2641/// [`tests::restart_policy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
2642/// (cross-axis partition pin against the paired [`From<RestartPolicy>
2643/// for &'static str`], [`From<RestartPolicy> for String`], and
2644/// [`ToString`]-through-[`std::fmt::Display`] axes, plus a
2645/// `.iter().copied().map(Cow::from)` pipe witness over
2646/// [`RestartPolicy::ALL`] that materializes the three-arm accept-set
2647/// through the [`Cow<'static, str>`] axis alone and pins the
2648/// zero-alloc discipline on every element).
2649impl From<RestartPolicy> for std::borrow::Cow<'static, str> {
2650    fn from(policy: RestartPolicy) -> std::borrow::Cow<'static, str> {
2651        std::borrow::Cow::Borrowed(policy.as_str())
2652    }
2653}
2654
2655/// Trait-idiomatic *borrowed-input, [`std::borrow::Cow<'static, str>`]
2656/// output* forward projection on the M2 OTP-shape per-child-restart
2657/// [`RestartPolicy`] closed-set typed enum — the borrowed-input
2658/// companion to the paired owned-input
2659/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] impl
2660/// immediately above (0612398). Routes byte-for-byte through the same
2661/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
2662/// accessor (via [`std::borrow::Cow::Borrowed`]) so every consumer
2663/// that holds a `&RestartPolicy` and needs a
2664/// [`std::borrow::Cow<'static, str>`] — a
2665/// `RestartPolicy::ALL.iter().map(std::borrow::Cow::from).collect::<Vec<_>>()`
2666/// per-arm accept-set materializer (whose iterator over
2667/// `&'static [RestartPolicy]` yields `&RestartPolicy`, not
2668/// `RestartPolicy`, so the paired owned-input
2669/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] axis
2670/// alone forces every call site through an explicit `.copied()` /
2671/// dereference / [`Copy`]-bound restatement rather than the direct
2672/// trait-idiomatic projection), a future generic
2673/// `<T: for<'a> Into<std::borrow::Cow<'static, str>>>`-bound emitter
2674/// on a per-child-policy diagnostic column that walks the
2675/// `iter().map(Into::into)` shape verbatim, the future M4 admission-
2676/// webhook rejection body that composes the accepted-policy
2677/// enumeration from an iterated
2678/// `RestartPolicy::ALL.iter().map(|p| p.into())` pipe rather than a
2679/// per-arm `match p { … }` cascade — reaches the same three-arm
2680/// lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2681/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2682/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2683/// paired [`std::fmt::Display`], [`AsRef<str>`],
2684/// [`RestartPolicy::as_str`], the four
2685/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
2686/// forward-projection corners, and the paired owned-input
2687/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] impl
2688/// already return.
2689///
2690/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
2691/// [`std::borrow::Cow::Owned`] — the substrate-primitive
2692/// [`RestartPolicy::as_str`] accessor's return carries the
2693/// `&'static str` lifetime by construction (each `match` arm resolves
2694/// to a [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const &str`
2695/// with static lifetime), so the zero-alloc borrowed arm is the
2696/// type-correct projection with no runtime allocation.
2697///
2698/// Closes the `{Self, &Self}` input-shape corner on the M2 OTP-shape
2699/// per-child-restart [`std::borrow::Cow<'static, str>`] axis opened
2700/// one commit prior (0612398) on the paired owned-input
2701/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] impl —
2702/// second-of-two-in-M2 closed-set fieldless typed enum peer on the
2703/// caixa surface (paired with the sibling-restart [`RestartStrategy`]
2704/// which carries both {Self, &Self} × Cow<'static, str> corners since
2705/// 7dd28b3 owned-input, 9b3e4b3 borrowed-input), exactly as d45c409
2706/// closed it on the top-level [`crate::CaixaKind`] one commit after
2707/// the owning half (99c1735) landed. This lift closes the whole M2
2708/// OTP-shape tier of the substrate-wide [`Cow<'static, str>`]
2709/// forward-projection campaign on both input-shape corners
2710/// ({Self, &Self}) of both M2 OTP-shape sibling peers
2711/// ([`RestartStrategy`] and [`RestartPolicy`]), so the remaining
2712/// eleven substrate-wide peers (`PlacementStrategy`, `RateLimitUnit`,
2713/// `DepList`, `CaixaDialeto`, `WitShape`, `PathShapeViolation`,
2714/// `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`,
2715/// `FerriteRuntime`) become the future targets of the campaign. Rust's
2716/// standard library does not carry a blanket
2717/// `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor an
2718/// `impl<T: fmt::Display> From<&T> for Cow<'static, str>`), so every
2719/// closed-set fieldless typed enum peer on the substrate that carries
2720/// the paired owned-input [`Cow<'static, str>`] axis but not the
2721/// borrowed-input axis forces every borrowed-input
2722/// [`Cow<'static, str>`]-parameterized call site through a spurious
2723/// [`Copy`] deref (`std::borrow::Cow::from(*policy)`) or a
2724/// `std::borrow::Cow::Borrowed(policy.as_str())` open-code whose type
2725/// bounds have no compile-time link to the substrate primitive.
2726///
2727/// Pinned load-bearing by
2728/// [`tests::restart_policy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor`]
2729/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
2730/// against [`RestartPolicy::as_str`] across the three-arm
2731/// [`RestartPolicy::ALL`] through the borrowed-input surface) and
2732/// [`tests::restart_policy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
2733/// (cross-axis partition pin against the paired owned-input
2734/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`], the
2735/// paired borrowed-input owned-`&'static str`
2736/// [`From<&RestartPolicy> for &'static str`], and the paired
2737/// borrowed-input owned-`String` [`From<&RestartPolicy> for String`]
2738/// impls, plus a `.iter().map(std::borrow::Cow::from)` pipe witness
2739/// over [`RestartPolicy::ALL`] — whose iterator yields
2740/// `&RestartPolicy` by construction, so the borrowed-input
2741/// [`Cow<'static, str>`] axis is what routes the pipe through the
2742/// substrate-primitive [`RestartPolicy::as_str`] accessor with the
2743/// zero-alloc [`Cow::Borrowed`] arm by construction and without a
2744/// spurious [`Copy`] deref).
2745impl From<&RestartPolicy> for std::borrow::Cow<'static, str> {
2746    fn from(policy: &RestartPolicy) -> std::borrow::Cow<'static, str> {
2747        std::borrow::Cow::Borrowed(policy.as_str())
2748    }
2749}
2750
2751/// Trait-idiomatic *owned-input, [`Box<str>`] output* forward
2752/// projection on the M2 OTP-shape per-child-restart [`RestartPolicy`]
2753/// closed-set fieldless typed enum — extends the substrate-wide
2754/// `Box<str>` forward-projection campaign tier opened one commit prior
2755/// (69ef45c) on the paired sibling-restart [`RestartStrategy`] onto
2756/// the second (and third-and-final) M2 OTP-shape closed-set fieldless
2757/// typed enum peer on the caixa surface (`:children :restart`),
2758/// immediately after the paired `Cow<'static, str>` axis (0612398 /
2759/// b4dc55c) closed the
2760/// `{Self, &Self} × {&'static str, String, Cow<'static, str>}` 2×3
2761/// corner on this enum. Routes byte-for-byte through the
2762/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
2763/// accessor via [`Box::<str>::from`] on the returned `&'static str`,
2764/// so every consumer that binds a
2765/// `let key: Box<str> = policy.into();`-shaped call site — a
2766/// per-child metric-key materializer that stashes the policy
2767/// discriminator in a `Box<str>`-typed heap-owned scalar for cheap
2768/// clone (a shared-nothing per-policy accept-set the `caixa-operator`
2769/// hierarchical reconciliation scheduler's per-child restart-decision
2770/// fan-out carries), a future admission-webhook rejection body whose
2771/// per-arm `Box<str>` field composes from an owned `RestartPolicy`
2772/// handle — reaches the same three-arm lifted
2773/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2774/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2775/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2776/// sibling
2777/// `{Self, &Self} × {&'static str, String, Cow<'static, str>}`
2778/// forward-projection corner already returns. Rust's standard library
2779/// carries `impl From<&str> for Box<str>` and
2780/// `impl From<String> for Box<str>` but no blanket
2781/// `impl<T: AsRef<str>> From<T> for Box<str>` (nor any
2782/// `impl<T: Copy, U: From<T>> From<T> for U` route from the enum), so
2783/// this axis is a distinct trait-idiomatic surface that a downstream
2784/// `RestartPolicy → Box<str>` `.into()` reaches through this impl and
2785/// no other — without a `Box::from(policy.as_str())` open-code whose
2786/// type bounds have no compile-time link back to the substrate
2787/// primitive.
2788///
2789/// Second peer on the substrate-wide trait-idiomatic [`Box<str>`]
2790/// forward-projection family opened on the sibling-restart
2791/// [`RestartStrategy`] (69ef45c / 59ae5dc) — closes the whole M2
2792/// OTP-shape tier of the substrate-wide [`Box<str>`] forward-
2793/// projection campaign's owned-input corner on both M2 OTP-shape
2794/// sibling peers ([`RestartStrategy`] and [`RestartPolicy`]), the
2795/// paired borrowed-input `From<&RestartPolicy> for Box<str>` closer
2796/// and the remaining fieldless-enum peers on the M3 mesh-shape /
2797/// outside-M3 caixa-core / render-side / outside-caixa-core tiers
2798/// are the future targets of the campaign.
2799///
2800/// Pinned load-bearing by
2801/// [`tests::restart_policy_from_into_box_str_routes_through_as_str_accessor`]
2802/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2803/// three-arm [`RestartPolicy::ALL`] emit-set on the owned-input
2804/// surface, plus a blanket-derived [`Into`] shape witness).
2805impl From<RestartPolicy> for Box<str> {
2806    fn from(policy: RestartPolicy) -> Box<str> {
2807        Box::<str>::from(policy.as_str())
2808    }
2809}
2810
2811/// Trait-idiomatic *borrowed-input, [`Box<str>`] output* forward
2812/// projection on the M2 OTP-shape per-child-restart [`RestartPolicy`]
2813/// closed-set fieldless typed enum — the borrowed-input companion to
2814/// the paired owned-input [`From<RestartPolicy> for Box<str>`] impl
2815/// (0a1b313, one commit prior) that closes the `{Self, &Self}`
2816/// input-shape corner of the substrate-wide [`Box<str>`] forward-
2817/// projection axis on the second (and third-and-final) M2 OTP-shape
2818/// closed-set fieldless typed enum peer on the caixa surface
2819/// (`:children :restart`), routing byte-for-byte through the
2820/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
2821/// accessor via [`Box::<str>::from`] on the returned `&'static str`.
2822/// Every consumer that holds a `&RestartPolicy` and needs a
2823/// [`Box<str>`] — a
2824/// `RestartPolicy::ALL.iter().map(Box::<str>::from).collect::<Vec<_>>()`
2825/// per-arm accept-set materializer (whose iterator over
2826/// `&'static [RestartPolicy]` yields `&RestartPolicy`, not
2827/// `RestartPolicy`, so the paired owned-input
2828/// [`From<RestartPolicy> for Box<str>`] axis alone forces every
2829/// call site through an explicit [`Copy`] deref or a
2830/// `.copied()` restatement rather than the direct trait-idiomatic
2831/// projection), a per-child metric-key materializer holding
2832/// `&RestartPolicy` through a `caixa-operator` hierarchical
2833/// reconciliation scheduler's borrow lifetime, a future admission-
2834/// webhook rejection body whose per-arm `Box<str>` field composes
2835/// from a borrowed `&RestartPolicy` handle — reaches the
2836/// substrate-primitive [`RestartPolicy::as_str`] accessor through
2837/// this impl and no other, without a
2838/// `Box::<str>::from(policy.as_str())` open-code whose type bounds
2839/// have no compile-time link back to the substrate primitive.
2840///
2841/// Rust's standard library carries `impl From<&str> for Box<str>`
2842/// and `impl From<String> for Box<str>` but no blanket
2843/// `impl<T: AsRef<str>> From<&T> for Box<str>` (nor a
2844/// `Copy`-based `impl<T: Copy, U: From<&T> for U`), so every closed-
2845/// set fieldless typed enum peer on the substrate that carries the
2846/// paired owned-input `Box<str>` axis but not the borrowed-input
2847/// axis forces every borrowed-input `Box<str>`-parameterized call
2848/// site through a spurious [`Copy`] deref
2849/// (`Box::<str>::from((*policy).as_str())`) or a
2850/// `Box::<str>::from(policy.as_str())` open-code whose type bounds
2851/// have no compile-time link back to the substrate primitive.
2852///
2853/// Fourth (and closing) peer on the substrate-wide trait-idiomatic
2854/// [`Box<str>`] forward-projection family on the M2 OTP-shape tier
2855/// — closes the whole `{Self, &Self}` input-shape corner of the
2856/// [`Box<str>`] axis on both M2 OTP-shape sibling peers
2857/// ([`RestartStrategy`] and [`RestartPolicy`]), exactly as b4dc55c
2858/// closed the paired [`Cow<'static, str>`] axis one commit after
2859/// its owning half (0612398) landed on this enum. The remaining
2860/// fieldless-enum peers on the M3 mesh-shape / outside-M3 caixa-
2861/// core / render-side / outside-caixa-core tiers are the future
2862/// targets of the [`Box<str>`] campaign.
2863///
2864/// Pinned load-bearing by
2865/// [`tests::restart_policy_from_borrowed_into_box_str_routes_through_as_str_accessor`]
2866/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2867/// three-arm [`RestartPolicy::ALL`] emit-set on the borrowed-input
2868/// surface, plus a blanket-derived [`Into`] shape witness, a
2869/// cross-axis partition pin against the paired owned-input
2870/// [`From<RestartPolicy> for Box<str>`] and the sibling borrowed-
2871/// input `{&'static str, String, Cow<'static, str>}` return-shape
2872/// axes, and a `.iter().map(Box::<str>::from)` pipe witness over
2873/// [`RestartPolicy::ALL`] — whose iterator yields `&RestartPolicy`
2874/// by construction, so the borrowed-input [`Box<str>`] axis is
2875/// what routes the pipe through the substrate-primitive
2876/// [`RestartPolicy::as_str`] accessor without a spurious [`Copy`]
2877/// deref).
2878impl From<&RestartPolicy> for Box<str> {
2879    fn from(policy: &RestartPolicy) -> Box<str> {
2880        Box::<str>::from(policy.as_str())
2881    }
2882}
2883
2884/// Trait-idiomatic *owned-input, [`std::sync::Arc<str>`] output*
2885/// forward projection on the M2 OTP-shape per-child-restart
2886/// [`RestartPolicy`] closed-set fieldless typed enum — routes byte-
2887/// for-byte through the substrate-primitive [`RestartPolicy::as_str`]
2888/// `pub const fn` accessor via [`std::sync::Arc::<str>::from`] on the
2889/// returned `&'static str`, so every consumer that binds a
2890/// [`RestartPolicy`] through the standard-library `.into()` /
2891/// [`From<Self> for std::sync::Arc<str>`] (equivalently
2892/// [`Into<std::sync::Arc<str>>`]) axis — a future admission-webhook's
2893/// per-request `Sync` + `Send`-safe structured-log field composed
2894/// across an `.await` boundary through a
2895/// `<T: Into<std::sync::Arc<str>>>`-bound diagnostic-column dispatch,
2896/// a future wasm-operator's per-child post-exit restart-decision
2897/// pipeline holding a shared-ownership per-arm cache key, a
2898/// `<T: Into<std::sync::Arc<str>>>`-bound `tracing`-span attributes
2899/// collector recording a per-child-policy field onto the parent
2900/// span's shared-ownership context — reaches the same three-arm
2901/// lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2902/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2903/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2904/// sibling
2905/// `{Self, &Self} × {&'static str, String, Cow<'static, str>, Box<str>}`
2906/// forward-projection corner already returns.
2907///
2908/// Second peer on the substrate-wide trait-idiomatic
2909/// [`std::sync::Arc<str>`] forward-projection family opened one
2910/// projection tier prior (bca2ec8) on the paired sibling-restart
2911/// [`RestartStrategy`] owned-input first-mover — extends the tier
2912/// onto the second (and third-and-final) M2 OTP-shape closed-set
2913/// fieldless typed enum peer on the caixa surface
2914/// (`:children :restart`), immediately after the paired [`Box<str>`]
2915/// axis (0a1b313 / cb1d068) closed the whole
2916/// `{Self, &Self} × {&'static str, String, Cow<'static, str>, Box<str>}`
2917/// 2×4 corner on this enum. Rust's standard library carries
2918/// `impl From<&str> for std::sync::Arc<str>` and
2919/// `impl From<String> for std::sync::Arc<str>` but no blanket
2920/// `impl<T: AsRef<str>> From<T> for std::sync::Arc<str>` (nor an
2921/// `impl<T: fmt::Display> From<T> for std::sync::Arc<str>`), so this
2922/// axis is a distinct trait-idiomatic surface that a
2923/// `let key: std::sync::Arc<str> = policy.into();`-shaped call site
2924/// reaches through this impl and no other — a paired
2925/// `std::sync::Arc::<str>::from(policy.as_str())` open-code has no
2926/// compile-time link back to the substrate primitive, and a two-step
2927/// `std::sync::Arc::<str>::from(String::from(policy))` composition
2928/// through the owned-`String` axis allocates twice (once into the
2929/// intermediate `String`, once into the [`Arc<str>`] on the
2930/// `From<String>` conversion) where the single-step trait impl
2931/// allocates once.
2932///
2933/// Peer of the sibling [`Box<str>`] second-tier extender (0a1b313) —
2934/// same "extends the substrate-wide projection tier onto the next
2935/// M2 OTP-shape peer" discipline, extended onto the
2936/// [`std::sync::Arc<str>`] axis whose shared-ownership + [`Sync`] +
2937/// [`Send`] contract is the distinct value the [`Box<str>`] axis's
2938/// owned-move return-shape cannot provide.
2939///
2940/// Pinned load-bearing by
2941/// [`tests::restart_policy_from_into_arc_str_routes_through_as_str_accessor`]
2942/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2943/// three-arm [`RestartPolicy::ALL`] emit-set on the owned-input
2944/// surface, plus a blanket-derived [`Into`] shape witness and cross-
2945/// axis byte-parity pins against the sibling owned-input
2946/// `{&'static str, String, Cow<'static, str>, Box<str>}` return-shape
2947/// axes).
2948impl From<RestartPolicy> for std::sync::Arc<str> {
2949    fn from(policy: RestartPolicy) -> std::sync::Arc<str> {
2950        std::sync::Arc::<str>::from(policy.as_str())
2951    }
2952}
2953
2954/// Trait-idiomatic *borrowed-input, [`std::sync::Arc<str>`] output*
2955/// forward projection on the M2 OTP-shape per-child-restart
2956/// [`RestartPolicy`] closed-set fieldless typed enum — closes the
2957/// `{Self, &Self}` input-shape corner of the [`std::sync::Arc<str>`]
2958/// forward-projection axis on the second (and third-and-final) M2
2959/// OTP-shape closed-set fieldless typed enum peer on the caixa
2960/// surface (`:children :restart`), companion to the paired
2961/// owned-input [`From<RestartPolicy> for std::sync::Arc<str>`] impl
2962/// one commit prior (b05724e). Routes byte-for-byte through the
2963/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
2964/// accessor (via [`std::sync::Arc::<str>::from`] on the returned
2965/// `&'static str`), so every consumer that binds a
2966/// [`&RestartPolicy`] through the standard-library `.into()` /
2967/// [`From<&Self> for std::sync::Arc<str>`] (equivalently
2968/// [`Into<std::sync::Arc<str>>`]) axis — a future admission-webhook's
2969/// per-request borrowed-`&RestartPolicy` handle rendering a per-arm
2970/// `Sync` + `Send`-safe structured-log field across an `.await`
2971/// boundary through a `<T: Into<std::sync::Arc<str>>>`-bound
2972/// diagnostic-column dispatch, a future wasm-operator's per-child
2973/// post-exit restart-decision pipeline whose
2974/// `.iter().map(std::sync::Arc::<str>::from)` collector reaches
2975/// into the shared-ownership per-arm key without a spurious [`Copy`]
2976/// deref (which would only be reachable through the owned-input
2977/// [`From<RestartPolicy> for std::sync::Arc<str>`] axis by first
2978/// calling `.copied()` on the iterator), a future
2979/// `<T: Into<std::sync::Arc<str>>>`-bound `tracing`-span attributes
2980/// collector recording a borrowed-`&RestartPolicy` per-arm field
2981/// onto the parent span's shared-ownership context — reaches the
2982/// same three-arm lifted
2983/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2984/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2985/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2986/// paired owned-input [`From<RestartPolicy> for std::sync::Arc<str>`]
2987/// impl and the sibling `{&'static str, String, Cow<'static, str>,
2988/// Box<str>}` forward-projection corner already return.
2989///
2990/// Closes the substrate-wide trait-idiomatic
2991/// [`std::sync::Arc<str>`] forward-projection family opened one
2992/// commit prior (b05724e) on the paired owned-input
2993/// [`From<RestartPolicy> for std::sync::Arc<str>`] impl — closes
2994/// the `{Self, &Self}` input-shape corner of the
2995/// [`std::sync::Arc<str>`] axis on the second (and third-and-final)
2996/// M2 OTP-shape closed-set fieldless typed enum peer on the caixa
2997/// surface, exactly as b3e72d7 closed the paired
2998/// [`std::sync::Arc<str>`] corner on the sibling-restart
2999/// [`RestartStrategy`] first-mover one commit after its owning half
3000/// (bca2ec8) landed, and as cb1d068 closed the paired [`Box<str>`]
3001/// corner on this enum one commit after its owning half (0a1b313)
3002/// landed. Rust's standard library carries `impl From<&str> for
3003/// std::sync::Arc<str>` and `impl From<String> for
3004/// std::sync::Arc<str>` but no blanket `impl<T: AsRef<str>> From<&T>
3005/// for std::sync::Arc<str>` (nor a `Copy`-based `impl<T: Copy,
3006/// U: From<T>> From<&T> for U`), so every closed-set fieldless typed
3007/// enum peer on the substrate that carries the paired owned-input
3008/// [`std::sync::Arc<str>`] axis but not the borrowed-input axis
3009/// forces every borrowed-input [`std::sync::Arc<str>`]-parameterized
3010/// call site through a spurious [`Copy`] deref
3011/// (`std::sync::Arc::<str>::from((*policy).as_str())`) or a
3012/// `std::sync::Arc::<str>::from(policy.as_str())` open-code whose
3013/// type bounds have no compile-time link back to the substrate
3014/// primitive.
3015///
3016/// Pinned load-bearing by
3017/// [`tests::restart_policy_from_borrowed_into_arc_str_routes_through_as_str_accessor`]
3018/// (byte-parity pin against [`RestartPolicy::as_str`] across the
3019/// three-arm [`RestartPolicy::ALL`] emit-set on the borrowed-input
3020/// surface, plus a blanket-derived [`Into`] shape witness, a
3021/// cross-axis pin against the paired owned-input
3022/// [`From<RestartPolicy> for std::sync::Arc<str>`] and the sibling
3023/// borrowed-input `{&'static str, String, Cow<'static, str>,
3024/// Box<str>}` return-shape axes, and a
3025/// `.iter().map(std::sync::Arc::<str>::from)` pipe witness over
3026/// [`RestartPolicy::ALL`]).
3027impl From<&RestartPolicy> for std::sync::Arc<str> {
3028    fn from(policy: &RestartPolicy) -> std::sync::Arc<str> {
3029        std::sync::Arc::<str>::from(policy.as_str())
3030    }
3031}
3032
3033/// Trait-idiomatic byte-view surface on the per-child restart-decision
3034/// policy typed enum.
3035///
3036/// Every consumer that binds its input through the standard-library
3037/// [`AsRef<[u8]>`] trait bound — a byte-keyed
3038/// `HashMap<K: AsRef<[u8]>, V>` per-policy reconciliation-decision
3039/// table lookup on the future wasm-operator supervisor scheduler; a
3040/// `blake3::Hasher::update` / `ring::digest::Context::update` /
3041/// `sha2::Sha256::update` byte-input surface on any future per-child
3042/// content-address digest folded into the [`crate::Lacre`] closure so
3043/// downstream cache-keys partition on the three OTP restart policies
3044/// (`Permanent`, `Temporary`, `Transient`) at content-address time; an
3045/// `std::io::Write::write_all`-bound structured-log per-arm byte-sink —
3046/// reaches the substrate primitive through one trait dispatch rather
3047/// than open-coding the two-hop `restart.as_str().as_bytes()`
3048/// composition at every call site. Routed byte-for-byte through the
3049/// [`RestartPolicy::as_str`] `pub const fn` accessor the paired
3050/// str-view ([`AsRef<str>`], [`std::fmt::Display`],
3051/// [`RestartPolicy::as_str`]) and the five reverse-projection
3052/// (`&'static str`, `String`, `Cow<'static, str>`, `Box<str>`,
3053/// `std::sync::Arc<str>`) return-shape axes already resolve through,
3054/// so any future divergence between the byte-view and str-view axes
3055/// trips at caixa-core test time rather than at a downstream byte-
3056/// consumer's silent split.
3057///
3058/// Peer of the sibling per-supervisor-restart-strategy axis
3059/// [`AsRef<[u8]> for RestartStrategy`] (cd4c4e0, the first M2-OTP-
3060/// shape supervisor slot enum to open this axis) — the sixth
3061/// closed-set fieldless typed enum on the caixa surface to converge
3062/// onto the trait-idiomatic byte-view discipline, and the second (and
3063/// final) M2-OTP-shape sibling to pick it up, closing the byte-view
3064/// axis across the paired `:supervisor :estrategia` +
3065/// `:children :restart` M2 slot pair. Pin load-bearing by the paired
3066/// [`tests::restart_policy_as_ref_bytes_routes_through_as_str_accessor`]
3067/// (fail-before-pass-after byte-parity pin against
3068/// [`RestartPolicy::as_str`] `.as_bytes()` across the three-arm
3069/// [`RestartPolicy::ALL`] emit-set, cross-axis witness against the
3070/// paired str-view [`AsRef<str>`] / [`std::fmt::Display`] /
3071/// [`RestartPolicy::as_str`] axes' `.as_bytes()` byte-tails,
3072/// cross-axis witness against the paired reverse-projection
3073/// `{&'static str, String, Cow<'static, str>, Box<str>,
3074/// std::sync::Arc<str>}` return-shape axes' `.as_bytes()` byte-tails,
3075/// a `<T: AsRef<[u8]>>`-bound-consumer witness that a generic
3076/// byte-input function accepts a [`RestartPolicy`] directly through
3077/// the trait bound, and a `blake3::Hasher::update`-shape byte-input
3078/// surface witness routed through the `<T: AsRef<[u8]>>`-bound
3079/// consumer axis to reach the caixa-lacre compounding target). Any
3080/// future silent detour that routes the byte-view impl off the
3081/// substrate-primitive [`RestartPolicy::as_str`] accessor (a per-arm
3082/// inline `b"Permanent".as_slice()`-shaped re-inlining that opens a
3083/// compile-time link to the un-lifted arm-literal, a swap onto the
3084/// kebab-case [`gen_platform::Discriminant`] catalog identity that
3085/// would collide the wire axis with the dispatcher-catalog axis) trips
3086/// at caixa-core test time rather than at a downstream byte-consumer's
3087/// silent split.
3088impl AsRef<[u8]> for RestartPolicy {
3089    fn as_ref(&self) -> &[u8] {
3090        self.as_str().as_bytes()
3091    }
3092}
3093
3094/// Trait-idiomatic *owned-input, owned-`Vec<u8>` output* byte-owned
3095/// reverse projection on the second (and final) M2 OTP-shape closed-set
3096/// fieldless typed enum peer on the caixa surface ([`RestartPolicy`]) —
3097/// the byte-mirror of the [`From<RestartPolicy> for String`] str-owned
3098/// reverse-projection axis and the owned-`Vec<u8>` reverse-projection
3099/// sibling of the paired [`AsRef<[u8]>`] borrowed byte-view axis
3100/// (98b08fa) lifted on this same enum. Routes byte-for-byte through
3101/// the substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
3102/// accessor via [`str::as_bytes`] + [`slice::to_vec`] so every
3103/// consumer that binds a [`RestartPolicy`] through the standard-
3104/// library `impl From<RestartPolicy> for Vec<u8>` axis
3105/// (equivalently `<T: Into<Vec<u8>>>`) — a future
3106/// [`std::io::Write::write_all`]-shape per-child audit-log byte-sink
3107/// whose input parameter is an owned [`Vec<u8>`] payload, a future
3108/// `bytes::Bytes::from(Vec::<u8>::from(restart))` composer folding
3109/// the per-arm restart-decision-policy byte-tag into the
3110/// [`bytes::Bytes`] framing surface, a future
3111/// `hasher.update(&Vec::<u8>::from(restart))`-shape BLAKE3 content-
3112/// address closure that needs the owned byte-tail buffered before
3113/// folding into the [`crate::Lacre`] closure body, a future per-child
3114/// protobuf/CBOR/msgpack payload composer whose framer takes an owned
3115/// [`Vec<u8>`] rather than a borrowed byte-slice — reaches the
3116/// substrate primitive through one trait dispatch rather than an
3117/// open-coded per-call-site `restart.as_str().as_bytes().to_vec()`
3118/// composition whose type bounds have no compile-time link back to
3119/// the substrate primitive.
3120///
3121/// Closes the substrate-wide trait-idiomatic byte-owned reverse-
3122/// projection axis on the M2-OTP-shape `:supervisor :estrategia` +
3123/// `:children :restart` slot pair the sibling
3124/// [`RestartStrategy`] first-mover (63e5dd0) opened one commit prior,
3125/// matching the discipline the paired [`AsRef<[u8]>`] borrowed byte-
3126/// view axis campaign already carried across the same slot pair
3127/// (cd4c4e0 → 98b08fa). Every future arm addition (an OTP-
3128/// `intrinsic` fourth arm the theory
3129/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
3130/// might reach for once the three canonical OTP restart policies
3131/// stop covering the substrate's discovered load-shape) grows the
3132/// byte-owned axis through one edit on the substrate-primitive
3133/// [`RestartPolicy::as_str`] accessor.
3134///
3135/// Pinned load-bearing by
3136/// [`tests::restart_policy_from_into_owned_vec_bytes_routes_through_as_str_accessor`]
3137/// (byte-parity pin against [`RestartPolicy::as_str`] across the
3138/// three-arm [`RestartPolicy::ALL`] emit-set binding the byte-owned
3139/// reverse-projection axis against the paired [`AsRef<[u8]>`]
3140/// borrowed byte-view axis and the str-owned reverse-projection
3141/// family (`String`, `Cow<'static, str>`, `Box<str>`,
3142/// `std::sync::Arc<str>`) `.into_bytes()` / `.as_bytes().to_vec()`
3143/// byte-tails, a `<T: Into<Vec<u8>>>`-bound generic-consumer witness,
3144/// and a `std::io::Write::write_all`-shape owned-byte-sink surface
3145/// witness on both owned and borrowed input shapes).
3146impl From<RestartPolicy> for Vec<u8> {
3147    fn from(policy: RestartPolicy) -> Vec<u8> {
3148        policy.as_str().as_bytes().to_vec()
3149    }
3150}
3151
3152/// Trait-idiomatic *borrowed-input, owned-`Vec<u8>` output* byte-
3153/// owned reverse projection on the second (and final) M2 OTP-shape
3154/// closed-set fieldless typed enum peer on the caixa surface
3155/// ([`RestartPolicy`]) — the borrowed-input peer of
3156/// [`From<RestartPolicy> for Vec<u8>`], closing the
3157/// `{Self, &Self} → Vec<u8>` pair on the byte-owned reverse-projection
3158/// axis in one lift. Routes byte-for-byte through the substrate-
3159/// primitive [`RestartPolicy::as_str`] `pub const fn` accessor so
3160/// every consumer that holds a borrowed [`&RestartPolicy`] and needs
3161/// an owned [`Vec<u8>`] — a future
3162/// `.iter().map(Vec::<u8>::from).collect()` pipe over
3163/// `&[RestartPolicy]` (whose iterator yields `&RestartPolicy`,
3164/// not `RestartPolicy`, so the owned-input axis alone forces every
3165/// call site through an explicit `.copied()` / spurious [`Copy`]
3166/// deref restatement rather than the direct trait-idiomatic
3167/// projection), a future admission-webhook rejection body composer
3168/// that walks [`RestartPolicy::ALL`] through an `Into<Vec<u8>>`-
3169/// bound per-arm byte-writer to surface the accepted `:children
3170/// :restart` set — reaches the substrate primitive through one
3171/// trait dispatch rather than a `Vec::<u8>::from(*policy)` spurious-
3172/// [`Copy`]-deref restatement.
3173impl From<&RestartPolicy> for Vec<u8> {
3174    fn from(policy: &RestartPolicy) -> Vec<u8> {
3175        policy.as_str().as_bytes().to_vec()
3176    }
3177}
3178
3179/// Trait-idiomatic *borrowed byte-slice input* reverse projection on the
3180/// second (and final) M2-OTP-shape closed-set fieldless typed enum peer on
3181/// the caixa surface ([`RestartPolicy`]) — the byte-view mirror of the
3182/// str-view reverse-projection axis carried by the paired
3183/// [`TryFrom<&str> for RestartPolicy`] impl (which routes through the
3184/// substrate-primitive [`RestartPolicy::from_wire`] `Option<Self>` accessor
3185/// on the three-arm `PascalCase` accept-set the sibling
3186/// [`RestartPolicy::as_str`] emitter returns). Routes byte-for-byte through
3187/// the standard-library [`std::str::from_utf8`] UTF-8 validator and then
3188/// through [`RestartPolicy::from_wire`] so every consumer that holds a
3189/// borrowed [`&[u8]`] and needs to project it back into a typed
3190/// [`RestartPolicy`] — a future `bytes::Bytes::as_ref()`-fed reader that
3191/// parses a per-child `:restart` `PascalCase` wire scalar from an
3192/// already-borrowed framing byte-tail (a
3193/// `tracing::field::valuable::Value::Bytes` recorder on the future
3194/// wasm-operator's per-child restart-decision diagnostic emission path, a
3195/// future audit-report re-loader binding a prior
3196/// [`RestartPolicy::as_str`] output from a mmap'd byte-slice back through
3197/// the typed enum for cross-run comparison), a future M4
3198/// `mesh.pleme.io/v1alpha1/Supervisor` CR admission-webhook rejection body
3199/// that reads a `spec.children[].restart` field off a raw HTTP body
3200/// byte-slice before UTF-8 validation commits allocation, a future generic
3201/// `<T: for<'a> TryFrom<&'a [u8]>>`-bound loader over any of the
3202/// substrate's closed-set typed enums — reaches the same three-arm
3203/// `PascalCase` wire accept-set the sibling method-named
3204/// [`RestartPolicy::from_wire`] resolver and the paired trait-idiomatic
3205/// [`TryFrom<&str>`] axis already resolve against, rather than an open-
3206/// coded per-call-site
3207/// `std::str::from_utf8(bytes).ok().and_then(RestartPolicy::from_wire)`
3208/// composition or a
3209/// `<RestartPolicy as TryFrom<&str>>::try_from(std::str::from_utf8(bytes)?)`
3210/// two-hop shape whose type bounds have no compile-time link to the
3211/// substrate primitive.
3212///
3213/// Closes the substrate-wide trait-idiomatic *byte-view reverse-projection*
3214/// family on the M2-OTP-shape `:supervisor :estrategia` + `:children
3215/// :restart` slot pair the sibling [`RestartStrategy`] first-mover
3216/// (c699a83) opened one commit prior — extends the family from
3217/// [`crate::CaixaKind`] (18d1940), [`crate::CaixaDialeto`] (d102cb8),
3218/// [`crate::dep::DepList`] (b8f25d5), and [`RestartStrategy`] (c699a83)
3219/// onto the second (and final) M2-OTP-shape closed-set fieldless typed
3220/// enum peer on the caixa surface, matching the trajectory the paired
3221/// byte-owned reverse-projection axis campaign already walked across the
3222/// same slot pair (63e5dd0 → 96a522a). Rust's standard library carries no
3223/// blanket `impl<T: for<'a> TryFrom<&'a str>> TryFrom<&[u8]> for T`, so a
3224/// two-hop composition through [`std::str::from_utf8`] + the paired
3225/// [`TryFrom<&str>`] axis is reachable at every call site but has no
3226/// compile-time link back to the byte-view reverse-projection axis. Every
3227/// remaining closed-set fieldless typed enum peer on the substrate
3228/// ([`crate::aplicacao::PlacementStrategy`],
3229/// [`crate::aplicacao::RateLimitUnit`], [`crate::aplicacao::WitShape`],
3230/// and the outside-`caixa-core` peers `PathShapeViolation`,
3231/// `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`,
3232/// `FerriteRuntime`) is a future target of the campaign.
3233///
3234/// `type Error = ()` matches the sibling [`RestartPolicy::from_wire`]'s
3235/// `Option<Self>` return-shape's deliberate deferral of error typing and
3236/// the paired trait-idiomatic [`TryFrom<&str>`] axis's unit-error shape —
3237/// the caller picks the diagnostic form appropriate for its use site (a
3238/// future `feira supervisor --restart …` arg-parse composes its own
3239/// per-verb "unknown restart policy: <arg> — accepted: {…}" message
3240/// enumerating [`RestartPolicy::WIRE_NAMES`]; a future admission-webhook
3241/// rejection body wraps the `Err(())` outcome with the accepted-set
3242/// enumeration for operator diagnostics; a `Result::map_err` at the call
3243/// site lifts the unit-error to a per-verb error type). Two rejection
3244/// paths route through the single unit-error: an invalid UTF-8
3245/// byte-sequence ([`std::str::from_utf8`] returns `Err`) and a valid UTF-8
3246/// byte-string that falls outside the three-arm `PascalCase` accept-set
3247/// ([`RestartPolicy::from_wire`] returns `None`) — both collapse onto
3248/// `Err(())` so the trait signature stays consistent with the sibling
3249/// str-view reverse axis, and a caller that needs to distinguish the two
3250/// failure modes composes [`std::str::from_utf8`] +
3251/// [`RestartPolicy::from_wire`] explicitly.
3252///
3253/// Pinned load-bearing by
3254/// [`tests::restart_policy_try_from_bytes_routes_through_from_wire_accessor`]
3255/// (byte-parity pin against [`RestartPolicy::from_wire`] across the
3256/// three-arm [`RestartPolicy::ALL`] accept-set on the borrowed byte-slice
3257/// surface, plus a cross-axis witness that the byte-view reverse
3258/// projection agrees with the paired [`TryFrom<&str>`] str-view reverse
3259/// axis on every accepted arm, and a forward/reverse byte-view cross-axis
3260/// witness that feeding the paired [`AsRef<[u8]>`] byte-tail back through
3261/// the new impl round-trips to the originating arm) and
3262/// [`tests::restart_policy_try_from_bytes_rejects_unknown_and_non_utf8_bytes`]
3263/// (rejection witness against silent accept-set widening on both the
3264/// non-UTF-8 byte-sequence rejection path and the unknown-wire-vocabulary
3265/// rejection path — the latter includes the sibling kebab-case
3266/// dispatcher-catalog byte-strings on the two-axis wire/catalog split so
3267/// a caller that confuses the two axes trips here rather than at a
3268/// downstream K8s-CR round-trip miss).
3269impl TryFrom<&[u8]> for RestartPolicy {
3270    type Error = ();
3271
3272    fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
3273        std::str::from_utf8(bytes)
3274            .ok()
3275            .and_then(Self::from_wire)
3276            .ok_or(())
3277    }
3278}
3279
3280/// Trait-idiomatic *owned byte-vec input* reverse projection on the second
3281/// (and final) M2-OTP-shape supervisor-slot closed-set fieldless typed enum
3282/// peer on the caixa surface ([`RestartPolicy`]) — the owned-input peer of
3283/// [`TryFrom<&[u8]> for RestartPolicy`], closing the byte-view reverse-
3284/// projection *square* ({owned-input, borrowed-input} × {owned-output
3285/// byte-vec, borrowed-output byte-slice}) on the M2-OTP-shape
3286/// `:supervisor :estrategia` + `:children :restart` slot pair the sibling
3287/// [`RestartStrategy`] first-mover (34951fe) opened on the byte-owned
3288/// reverse-input axis one commit-window prior. Routes byte-for-byte through
3289/// [`<Self as TryFrom<&[u8]>>::try_from`] on the [`Vec<u8>::as_slice`]
3290/// borrow so the owned-input surface reaches the same
3291/// [`std::str::from_utf8`] + [`RestartPolicy::from_wire`] resolution chain
3292/// the borrowed-input peer already carries — one substrate-primitive
3293/// accessor, one trait dispatch, no per-consumer detour.
3294///
3295/// Rust's standard library carries no blanket
3296/// `impl<T: for<'a> TryFrom<&'a [u8]>> TryFrom<Vec<u8>> for T`, so a
3297/// consumer that holds an owned [`Vec<u8>`] and needs a typed
3298/// [`RestartPolicy`] otherwise picks between (a) an open-coded
3299/// `<RestartPolicy as TryFrom<&[u8]>>::try_from(bytes.as_slice())` at every
3300/// call site (whose type bounds have no compile-time link to the byte-
3301/// owned reverse-projection axis), (b) a two-hop
3302/// `String::from_utf8(bytes)` + [`RestartPolicy::from_wire`] composition
3303/// whose error surface leaks the standard-library
3304/// [`std::string::FromUtf8Error`] (widening the sibling [`TryFrom<&[u8]>`]
3305/// axis's unit-error) and silently allocates a [`String`] on inputs that
3306/// will never make it past the wire vocabulary, or (c) an intermediate
3307/// `<RestartPolicy as TryFrom<&str>>::try_from(std::str::from_utf8(&bytes)?)`
3308/// three-hop shape. This impl closes the owned-byte-vec reverse-projection
3309/// axis at the substrate-primitive [`RestartPolicy::from_wire`] accessor so
3310/// every future `<T: TryFrom<Vec<u8>>>`-bound owned-byte-vec consumer — a
3311/// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR admission-webhook body
3312/// reader that hands the `spec.children[].restart` byte-tail off as a
3313/// [`Vec<u8>`] before UTF-8 validation commits allocation, a
3314/// `bytes::Bytes::to_vec()`-shape wire-body composer walking a prior
3315/// audit's per-child rejection payload back to the typed enum, a
3316/// `std::io::Read::read_to_end`-shape audit-log source whose framing yields
3317/// an owned byte-vec per per-policy scalar, an
3318/// `<T: TryFrom<Vec<u8>>>`-bound generic loader over any of the
3319/// substrate's closed-set typed enums — reaches the same three-arm
3320/// `PascalCase` wire accept-set through one trait dispatch.
3321///
3322/// Extends the substrate-wide trait-idiomatic *byte-owned reverse-
3323/// projection* family — opened on the structurally most fundamental
3324/// closed-set fieldless typed enum peer ([`crate::CaixaKind`], commit
3325/// 99c2849), extended onto the second caixa-core-internal peer
3326/// ([`crate::CaixaDialeto`], commit 83a1526), the third
3327/// ([`crate::dep::DepList`], commit 42091cb), and the first M2-OTP-shape
3328/// supervisor-slot peer ([`RestartStrategy`], commit 34951fe) — onto the
3329/// second (and final) M2-OTP-shape supervisor-slot closed-set fieldless
3330/// typed enum peer, tracking the "delegate through `TryFrom<&[u8]>` on the
3331/// `Vec<u8>::as_slice` borrow" discipline the first-mover established.
3332/// Every remaining closed-set fieldless typed enum peer on the substrate
3333/// ([`crate::aplicacao::PlacementStrategy`],
3334/// [`crate::aplicacao::RateLimitUnit`], [`crate::aplicacao::WitShape`],
3335/// [`crate::render::PathShapeViolation`], and the outside-`caixa-core`
3336/// peers `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`,
3337/// `Semantic`, `FerriteRuntime`) is a future target of the campaign,
3338/// mirroring the trajectory the closed byte-view reverse-projection
3339/// family (`TryFrom<&[u8]>`) and the closed byte-owned forward-projection
3340/// family (`From<{Self, &Self}> for Vec<u8>`) already walked across the
3341/// same slot pair.
3342///
3343/// `type Error = ()` matches the sibling [`TryFrom<&[u8]> for
3344/// RestartPolicy`] unit-error shape, preserving the trait-family
3345/// consistency across the borrowed-and-owned byte-view reverse-projection
3346/// pair. The owned [`Vec<u8>`] input is dropped on the error path (the
3347/// standard-library `String::from_utf8` convention of returning the input
3348/// in the error deliberately declined — a caller that needs the bytes back
3349/// holds a clone before the call, and the closed-set-enum use site rarely
3350/// wants the raw bytes back past a "did you mean" diagnostic that operates
3351/// on the wire vocabulary rather than the input).
3352///
3353/// Pinned load-bearing by
3354/// [`tests::restart_policy_try_from_vec_bytes_routes_through_borrowed_byte_view_axis`]
3355/// (byte-parity pin against the paired borrowed [`TryFrom<&[u8]>`] axis
3356/// across the three-arm [`RestartPolicy::ALL`] accept-set on the owned
3357/// byte-vec surface, cross-axis witness that the byte-owned reverse
3358/// projection agrees with the paired str-view reverse-projection axis
3359/// ([`TryFrom<&str>`]) on every accepted arm through the shared substrate-
3360/// primitive [`RestartPolicy::from_wire`] accessor, and a four-corner
3361/// {owned-input, borrowed-input} × {`From<Self>` → `Vec<u8>`,
3362/// `From<&Self>` → `Vec<u8>`} round-trip witness available on this enum
3363/// because [`RestartPolicy::as_str`] and [`RestartPolicy::from_wire`]
3364/// share one `PascalCase` byte-vocabulary — like the sibling
3365/// [`RestartStrategy`] and unlike the sibling [`crate::CaixaKind`] which
3366/// its peer test deliberately declines the four-corner witness on because
3367/// the wire/diagnostic split makes the forward and reverse pairs speak
3368/// different byte-strings) and
3369/// [`tests::restart_policy_try_from_vec_bytes_rejects_unknown_and_non_utf8_bytes`]
3370/// (rejection witness against silent accept-set widening on both the
3371/// non-UTF-8 byte-sequence rejection path and the unknown-wire-vocabulary
3372/// rejection path — the latter includes the sibling kebab-case
3373/// dispatcher-catalog byte-strings on the two-axis wire/catalog split so
3374/// a caller that confuses the two axes trips here rather than at a
3375/// downstream K8s-CR round-trip miss, plus a cross-axis witness that the
3376/// owned byte-vec reverse-projection axis agrees with the borrowed byte-
3377/// slice reverse-projection axis on every rejected input).
3378impl TryFrom<Vec<u8>> for RestartPolicy {
3379    type Error = ();
3380
3381    fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
3382        <Self as TryFrom<&[u8]>>::try_from(bytes.as_slice())
3383    }
3384}
3385
3386// Fleet-wide dispatcher-catalog registrations for caixa's OTP
3387// supervisor surface — two more typed shadows over Erlang/OTP
3388// primitives the substrate now mechanically tracks (see
3389// theory/UNIFIED-COMPUTING-MODEL.md §VI for the roadmap +
3390// theory/TYPED-ABSORPTION.md for the absorption arc).
3391gen_platform::register_dispatcher!("caixa.restart-strategy", RestartStrategy);
3392gen_platform::register_dispatcher!("caixa.restart-policy", RestartPolicy);
3393
3394/// One child entry in the supervisor's `:children` list.
3395///
3396/// Every child references another caixa by `:caixa <nome>` + version
3397/// constraint. The supervisor materializes one ComputeUnit per entry.
3398#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
3399#[serde(rename_all = "camelCase")]
3400pub struct ChildSpec {
3401    /// The child caixa's `:nome`. Must resolve via the same dependency
3402    /// resolution path as `:deps` (caixa-resolver).
3403    pub caixa: String,
3404
3405    /// Semver constraint (`"^0.1"`, `"~0.1.2"`, etc.) — same shape as
3406    /// [`crate::dep::Dep::versao`].
3407    pub versao: String,
3408
3409    /// Restart policy — an author-omitted slot degrades onto the
3410    /// substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`]
3411    /// (`permanent`, the Erlang/OTP worker-child default) through the
3412    /// [`Default for RestartPolicy`] impl this `#[serde(default)]` routes
3413    /// to.
3414    #[serde(default)]
3415    pub restart: RestartPolicy,
3416}
3417
3418impl ChildSpec {
3419    /// Substrate-canonical per-`:children` child-caixa `:nome` scalar
3420    /// accessor every consumer that reads the OTP-shape supervised
3421    /// child's identity keys off — returns the author-declared
3422    /// `:children :caixa` byte-string verbatim as a `&str`, borrowed
3423    /// from the typed slot's own [`String`] storage.
3424    ///
3425    /// The `:children :caixa` slot carries the DNS-1123 label — the
3426    /// child caixa's `:nome` — that every emitted cluster artifact
3427    /// derives its `metadata.name` from verbatim: the rendered
3428    /// `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name` per child, the
3429    /// [`crate::LABEL_PROGRAM`] label value on every child's pod
3430    /// identity, and the per-child K8s Service `metadata.name` the
3431    /// future wasm-operator (M3) provisions for inter-child supervision-
3432    /// tree wiring. Every downstream consumer that fans on the child's
3433    /// caixa-name keys off this scalar (the [`SupervisorSpec::validate`]
3434    /// per-child DNS-1123 gate at
3435    /// `require_valid_dns_1123_label(child.nome(), …)`, the per-child
3436    /// duplicate-detection [`crate::render::insert_first_seen`] key, the
3437    /// [`validate_no_self_supervision`] cross-slot equality check
3438    /// against the parent's `:nome`, every `SupervisorError` variant
3439    /// carrying the offending child caixa verbatim for `feira lint`
3440    /// rendering, the future wasm-operator's hierarchical reconciliation
3441    /// scheduler's per-child ComputeUnit-name projection, the future M4
3442    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
3443    /// admission webhook).
3444    ///
3445    /// Prior to this lift the `.caixa` byte-string was accessed inline
3446    /// at seven sites in `supervisor.rs` — the DNS-1123 gate's
3447    /// `&child.caixa`, the four `SupervisorError::{ChildCaixaInvalid,
3448    /// EmptyChildVersion, ChildVersaoInvalid, DuplicateChildCaixa}`
3449    /// carriers' `child.caixa.clone()`, the dedup key's
3450    /// `child.caixa.as_str()`, and the [`validate_no_self_supervision`]
3451    /// `child.caixa == parent_nome` cross-slot check — seven open-coded
3452    /// field-accesses that expressed no compile-time link back to the
3453    /// typed slot. A future extension of the `:children :caixa` axis to
3454    /// a richer author surface (a per-cluster alias table the operator
3455    /// pins through a future `:placement`-scoped slot on the supervisor
3456    /// tree, a namespace-qualified rewrite the M4 CR materializer
3457    /// applies per-CR, a per-child overlay from the future `:children
3458    /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
3459    /// acknowledges) would have had to be threaded through every
3460    /// open-coded copy in lockstep or one consumer would silently
3461    /// disagree with the peers on which caixa a given child resolves to
3462    /// — a child-set lookup that treated the name as `"cart-worker"`
3463    /// while the peer duplicate-detector treated it as
3464    /// `"tenant-a/cart-worker"` would silently split the
3465    /// `DuplicateChildCaixa` membership-lookup diagnostic from the
3466    /// self-supervision detector's parent-equality check, a two-consumer
3467    /// split at the validator far from the source `caixa.lisp` with no
3468    /// field naming the identity-drift root cause. Lifting the resolution
3469    /// rule to a typed method on the substrate primitive means every
3470    /// downstream consumer of the Supervisor's per-`:children` identity
3471    /// surface reaches for exactly one typed dispatch — the resolver's
3472    /// accept-set migrates as a unit on any future axis addition.
3473    ///
3474    /// Sibling of the peer per-`:membros` [`crate::Membro::nome`]
3475    /// (4a32abf) member-caixa `:nome` scalar accessor on the M3
3476    /// mesh-slot surface — same "one typed dispatch on the substrate
3477    /// primitive, thin projections at each consumer" discipline extended
3478    /// onto the M2 supervisor-tree per-`:children` child-identity axis.
3479    /// The two typed axes (`Membro::nome` on the M3 Aplicacao side,
3480    /// `ChildSpec::nome` on the M2 Supervisor side) now share one
3481    /// accessor discipline for the shared substrate concept "another
3482    /// caixa referenced by `:nome`". Peer of the second M2 slot scalar
3483    /// accessor [`crate::UpgradeFromEntry::prior_versao`] (75d27a8) on
3484    /// the sibling per-`:upgrade-from :from` OTP-appup axis — the M2
3485    /// slot family's typed-accessor discipline now spans both the
3486    /// upgrade axis (`:upgrade-from`) and the supervision axis
3487    /// (`:children`), matching the closed M3 mesh-slot accessor family's
3488    /// shape. Named `nome()` to match the tatara-lisp author-surface
3489    /// term the field's docstring already reaches for ("The child
3490    /// caixa's `:nome`") and the peer [`crate::Membro::nome`] /
3491    /// [`crate::Caixa::nome`] / [`crate::dep::Dep::nome`] field-name
3492    /// discipline the substrate already carries — the accessor's name
3493    /// maps directly onto the canonical caixa-identity vocabulary rather
3494    /// than shadowing the field's storage-side `caixa` label.
3495    #[must_use]
3496    pub const fn nome(&self) -> &str {
3497        self.caixa.as_str()
3498    }
3499
3500    /// Substrate-canonical per-`:children` child-caixa `:versao` semver-
3501    /// requirement scalar accessor every consumer that reads the OTP-shape
3502    /// supervised child's version pin keys off — returns the author-declared
3503    /// `:children :versao` byte-string verbatim as a `&str`, borrowed from
3504    /// the typed slot's own [`String`] storage.
3505    ///
3506    /// The `:children :versao` slot carries the Cargo-shaped semver
3507    /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that pins
3508    /// which release of the supervised child caixa the OTP-shape supervisor
3509    /// tree materializes against — the same requirement grammar the peer
3510    /// `:deps :versao` / `:membros :versao` axes carry, resolved through the
3511    /// shared [`crate::render::require_valid_versao_requirement`] cascade
3512    /// and the shared [`crate::version::parse_requirement`] parser. Every
3513    /// downstream consumer that fans on the child's version pin keys off
3514    /// this scalar (the [`SupervisorSpec::validate`] per-child requirement
3515    /// gate at `require_valid_versao_requirement(child.versao_requirement(),
3516    /// …)`, the [`SupervisorError::ChildVersaoInvalid`] variant's carrier
3517    /// for `feira lint` rendering, every future per-cluster version-lock
3518    /// overlay the caixa-operator's hierarchical reconciliation scheduler
3519    /// pins through a future `:placement`-scoped supervisor-tree slot, the
3520    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
3521    /// per-child version resolver, the future wasm-operator's per-child
3522    /// lacre BLAKE3-closure lookup at `ComputeUnit` materialization time).
3523    ///
3524    /// Prior to this lift the `.versao` byte-string was accessed inline at
3525    /// two `&str`-shaped sites in `caixa-core/src/supervisor.rs` — the
3526    /// [`SupervisorSpec::validate`] requirement-gate call
3527    /// `require_valid_versao_requirement(&child.versao, …)` and the
3528    /// [`SupervisorError::ChildVersaoInvalid`] carrier at
3529    /// `versao: child.versao.clone()` — two open-coded field-accesses that
3530    /// expressed no compile-time link back to the typed slot. A future
3531    /// extension of the `:children :versao` axis to a richer author surface
3532    /// (a per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
3533    /// flow, a lacre-projected concrete-version rewrite the operator
3534    /// materializes at CR-admission time, a future `:children :versao-lock`
3535    /// per-cluster override slot the wasm-operator's hierarchical
3536    /// reconciliation scheduler authors per-CR) would have had to be
3537    /// threaded through both open-coded copies in lockstep or one consumer
3538    /// would silently disagree with the peer on which release constraint a
3539    /// given child resolves to — the requirement-gate call reading
3540    /// `"^0.1"` while the error-body carrier read `"tenant-a-pin/^0.1"`
3541    /// would silently split the `ChildVersaoInvalid` diagnostic quote from
3542    /// the actual gate rejection input, a two-consumer split at the
3543    /// validator far from the source `caixa.lisp` with no field naming the
3544    /// version-pin drift root cause. Lifting the resolution rule to a typed
3545    /// method on the substrate primitive means every downstream
3546    /// requirement-facing consumer of the Supervisor's per-`:children`
3547    /// version-pin surface reaches for exactly one typed dispatch — the
3548    /// resolver's accept-set migrates as a unit on any future axis addition.
3549    ///
3550    /// Sibling of the peer per-`:membros` [`crate::Membro::versao_requirement`]
3551    /// (a40b0e3) member-caixa `:versao` scalar accessor on the M3 mesh-slot
3552    /// surface — same "one typed dispatch on the substrate primitive, thin
3553    /// projections at each consumer" discipline extended onto the M2
3554    /// supervisor-tree per-`:children` child-version-pin axis. The two typed
3555    /// axes (`Membro::versao_requirement` on the M3 Aplicacao side,
3556    /// `ChildSpec::versao_requirement` on the M2 Supervisor side) now share
3557    /// one accessor discipline for the shared substrate concept "another
3558    /// caixa referenced by a Cargo-shaped semver requirement". Peer of the
3559    /// sibling per-`:children` [`ChildSpec::nome`] (57c61d0) child-caixa
3560    /// `:nome` scalar accessor — the pair
3561    /// `(nome(), versao_requirement())` jointly projects the
3562    /// `(caixa, versao)` field pair every OTP-shape supervisor-tree consumer
3563    /// that fans on per-child identity + version pin keys off, closing the
3564    /// last unlifted per-`:children` `String`-carry axis so every downstream
3565    /// per-`:children` reader now routes through a typed dispatch on the
3566    /// substrate primitive. Named `versao_requirement()` rather than
3567    /// `versao()` because the field's storage-side `.versao` label is
3568    /// already the author-surface term (`:versao`); the accessor's name
3569    /// carries the semantic role — the semver *requirement* string the
3570    /// shared [`crate::version::parse_requirement`] entry-point consumes —
3571    /// so a raw field access and a typed dispatch read differently at every
3572    /// consumer site. Matches the peer [`crate::Membro::versao_requirement`]
3573    /// naming discipline verbatim.
3574    #[must_use]
3575    pub const fn versao_requirement(&self) -> &str {
3576        self.versao.as_str()
3577    }
3578
3579    /// Substrate-canonical per-`:children` `:restart` OTP-shaped
3580    /// per-child post-exit restart-decision policy scalar accessor every
3581    /// consumer that dispatches on the supervised child's post-exit
3582    /// reconcile posture keys off — returns the author-declared
3583    /// `:children :restart` variant verbatim as a [`RestartPolicy`],
3584    /// `Copy`-projected from the typed slot's own [`RestartPolicy`]
3585    /// storage.
3586    ///
3587    /// The `:children :restart` slot carries the closed-set OTP-shaped
3588    /// per-child restart-decision policy discriminator
3589    /// ([`RestartPolicy::Permanent`] — always restart, the OTP `permanent`
3590    /// worker-child default; [`RestartPolicy::Transient`] — restart only
3591    /// on abnormal exit, the OTP `transient` clean-completion-aware
3592    /// default; [`RestartPolicy::Temporary`] — never restart, the OTP
3593    /// `temporary` one-shot default) that every downstream consumer of
3594    /// the Supervisor's per-child post-exit reconcile branch keys off.
3595    /// Every future downstream consumer that fans on the per-child
3596    /// restart-decision keys off this scalar (the future `feira app
3597    /// graph` per-child restart column, the future wasm-operator's
3598    /// per-child post-exit restart-decision branch, the future M4
3599    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
3600    /// admission webhook, the `caixa-operator`'s hierarchical
3601    /// reconciliation scheduler's per-child post-exit reconcile branch,
3602    /// the [`RestartPolicy::as_str`] `Serialize`-derive-pinning path the
3603    /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
3604    /// pin threads through).
3605    ///
3606    /// Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
3607    /// (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
3608    /// scalar accessor and the M3 mesh-slot
3609    /// [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
3610    /// [`crate::PlacementStrategy`] distribution-strategy scalar accessor
3611    /// — same "one typed dispatch on the substrate primitive,
3612    /// `Copy`-projected closed-set enum-arm discriminator that partitions
3613    /// the downstream renderer's per-arm fan-out" discipline extended
3614    /// onto the M2 supervisor-slot per-`:children` restart-decision-policy
3615    /// `Copy`-composite-enum scalar axis. Third axis on the per-`:children`
3616    /// [`ChildSpec`] type — companion to the sibling per-`:children`
3617    /// [`ChildSpec::nome`] (57c61d0) child-caixa `:nome` scalar accessor
3618    /// and the per-`:children` [`ChildSpec::versao_requirement`]
3619    /// (2c053c8) child-caixa `:versao` semver-requirement scalar accessor
3620    /// on the sibling `String`-carry axes. The triple
3621    /// `(nome(), versao_requirement(), restart())` jointly projects the
3622    /// `(caixa, versao, restart)` field trio every OTP-shape supervisor-
3623    /// tree consumer that fans on per-child identity + version pin +
3624    /// restart-decision keys off, closing the last unlifted per-`:children`
3625    /// axis so every downstream per-`:children` reader now routes through
3626    /// a typed dispatch on the substrate primitive. Named `restart()` to
3627    /// match the storage field's name and the author-surface
3628    /// `:children :restart` slot term verbatim; the accessor's identity
3629    /// name maps onto the canonical OTP-shape per-child restart-decision-
3630    /// policy vocabulary the [`RestartPolicy`] enum's docstring already
3631    /// carries.
3632    ///
3633    /// Declared `pub const fn` to close the last non-`const`
3634    /// `Copy`-return raw-field-getter posture on the M2
3635    /// per-`:children` [`ChildSpec`] substrate-primitive surface — peer
3636    /// of the sibling M2 per-`:supervisor`
3637    /// [`SupervisorSpec::estrategia`] (converted in this commit)
3638    /// `Copy`-composite-enum accessor, the sibling M2 per-`:supervisor`
3639    /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
3640    /// already lifted, and the peer M3 mesh-slot per-`:entrada`
3641    /// [`crate::Entrada::port`] (bafa004) / per-`:placement`
3642    /// [`crate::Placement::estrategia`] (bafa004) `Copy`-return
3643    /// `pub const fn` scalar accessors on the sibling M3 surface. Every
3644    /// downstream substrate-side `const`-context consumer of the
3645    /// per-`:children` restart-decision-policy scalar (a future
3646    /// module-scope `const _:() = assert!(matches!(child.restart(),
3647    /// RestartPolicy::Permanent))` invariant pin on a typed fixture, a
3648    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
3649    /// admission-webhook `const fn` per-child restart-decision floor
3650    /// over a typed [`ChildSpec`], any future `const fn` supervisor-tree
3651    /// composer over the substrate primitive that fans on the per-child
3652    /// restart-decision policy at compile time) now reaches through the
3653    /// same typed dispatch on the substrate primitive at const-eval
3654    /// time as at runtime. A future non-`Copy`-return promotion of the
3655    /// scalar (an `Option<RestartPolicy>`-shape migration on the
3656    /// per-child restart-decision axis once heterogeneous per-cluster
3657    /// restart-policy overlays land, a per-tenant restart-policy-alias
3658    /// table the M4 CR materializer resolves per-CR) that would drop
3659    /// the `const` qualifier fails the fail-before-pass-after pin
3660    /// [`tests::child_spec_restart_accessor_is_const_fn`] at caixa-core
3661    /// build time rather than surfacing as a downstream consumer
3662    /// regression.
3663    #[must_use]
3664    pub const fn restart(&self) -> RestartPolicy {
3665        self.restart
3666    }
3667}
3668
3669/// Supervisor-typed slots that live alongside the standard Caixa
3670/// fields when `:kind Supervisor`. Held flat in [`crate::Caixa`] so
3671/// the manifest stays a single typed form; this struct exists for
3672/// validation + conversion.
3673#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
3674#[serde(rename_all = "camelCase")]
3675pub struct SupervisorSpec {
3676    /// Restart strategy. Defaults to [`RestartStrategy::OneForOne`].
3677    #[serde(default)]
3678    pub estrategia: RestartStrategy,
3679
3680    /// Max restarts within [`Self::restart_window`] before the
3681    /// supervisor itself terminates (and its parent supervisor decides
3682    /// what to do). Default 5.
3683    #[serde(default = "default_max_restarts")]
3684    pub max_restarts: u32,
3685
3686    /// Sliding window for `max_restarts`. Authored as a duration
3687    /// string (`"60s"`, `"5m"`); absent = "never reset". A `Some(0s)`
3688    /// is rejected by [`Self::validate`] — Erlang/OTP's
3689    /// `MaxIntensity / Period` invariant requires a positive window
3690    /// (a zero-period supervisor either trips on the first failure or
3691    /// never trips, depending on operator interpretation, neither of
3692    /// which is the author's intent). Omit the slot to express "no
3693    /// reset"; carry a positive duration to express the sliding window.
3694    #[serde(
3695        default,
3696        skip_serializing_if = "Option::is_none",
3697        with = "duration_codec"
3698    )]
3699    pub restart_window: Option<Duration>,
3700
3701    /// Static children. Empty for `SimpleOneForOne` (children added
3702    /// dynamically); required for the other three strategies.
3703    #[serde(default)]
3704    pub children: Vec<ChildSpec>,
3705}
3706
3707const fn default_max_restarts() -> u32 {
3708    // Route the private serde-`#[serde(default = "…")]` helper through
3709    // the substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] typed
3710    // `pub const` rather than the raw `5` literal — one source of truth
3711    // for the Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
3712    // default across the two production consumers that currently
3713    // dispatch on it (this helper via `#[serde(default = "…")]` on
3714    // `SupervisorSpec::max_restarts` and the [`Default for SupervisorSpec`]
3715    // impl at line 962). Pinned by
3716    // `default_max_restarts_helper_routes_through_lifted_default` +
3717    // `supervisor_spec_default_max_restarts_routes_through_lifted_default`
3718    // in the tests module; peer of the sibling caixa-core
3719    // [`crate::manifest::Caixa::supervisor_view`] `unwrap_or(…)` fold
3720    // that now routes its author-omitted `:max-restarts` arm through
3721    // the same lifted constant.
3722    SUPERVISOR_MAX_RESTARTS_DEFAULT
3723}
3724
3725/// Substrate-canonical Erlang/OTP-shaped `MaxIntensity` restart-budget-
3726/// count default for the `:supervisor :max-restarts` axis — the
3727/// canonical `{intensity, 5, 60}` `MaxIntensity` half of Learn You Some
3728/// Erlang's worker-supervisor default, extracted as a typed `pub const`
3729/// so every substrate-side consumer that resolves "what
3730/// [`SupervisorSpec::max_restarts`] value does an author-omitted
3731/// `:max-restarts` slot degrade onto?" reaches for exactly one
3732/// substrate-primitive `u32`.
3733///
3734/// The `:max-restarts` default axis has two production consumers on the
3735/// substrate side today (both prior to this lift folded onto raw `5`
3736/// literals with no compile-time link back to a shared truth): the
3737/// serde-`#[serde(default = "default_max_restarts")]` helper on
3738/// [`SupervisorSpec::max_restarts`] that every author-omitted
3739/// `:supervisor :max-restarts` slot lands in past the derive-macro's
3740/// wire-format compose, and the [`crate::manifest::Caixa::supervisor_view`]
3741/// `.max_restarts().unwrap_or(5)` fold that every downstream consumer of
3742/// the composed [`SupervisorSpec`] altitude reaches through
3743/// (`feira app graph`, the future wasm-operator's per-supervisor
3744/// restart-intensity counter, the future M4
3745/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
3746/// webhook, the caixa-operator's hierarchical reconciliation scheduler).
3747/// A pair of open-coded `5`s across two files that expressed no
3748/// compile-time link back to the shared OTP-canonical default — a
3749/// future rebrand of the default (a tightening to Elixir's
3750/// `Supervisor.max_restarts: 3`, a widening to a per-cluster overlay
3751/// the operator pins through a future
3752/// `:supervisor :max-restarts-overrides` slot the MESH-COMPOSITION
3753/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
3754/// plain `u32` count to a richer `{MaxR, MaxT}` per-child-cohort
3755/// restart-budget-partition once the INSPIRATIONS §II.2 Erlang/OTP
3756/// per-child-cohort roadmap lands) would have had to be threaded
3757/// through both open-coded copies in lockstep or the wire-format
3758/// author-omitted arm and the view-construction author-omitted arm
3759/// would silently disagree on which restart-budget an omitted
3760/// `:max-restarts` resolves to (an author writing `:supervisor
3761/// (:max-restarts ())` would round-trip through serde with the new
3762/// default while `supervisor_view` silently continued to compose the
3763/// stale `5`, or vice versa), a two-consumer split at the composition
3764/// boundary far from the source `caixa.lisp` with no field naming the
3765/// default-drift root cause. Lifting the resolution rule to a typed
3766/// `pub const` on the substrate primitive means every downstream
3767/// consumer of the per-Supervisor default-restart-budget-count surface
3768/// reaches for exactly one substrate-primitive `u32` — the resolver's
3769/// accepted value migrates as a unit on any future axis change.
3770///
3771/// The `5` value pins Learn You Some Erlang's `{intensity, 5, 60}`
3772/// worker-supervisor default (the closest canonical OTP-shape
3773/// production reference the substrate carries, matching the sibling
3774/// `60s` `Period` default the [`Default for SupervisorSpec`] impl pairs
3775/// this constant with on the paired sliding-window axis). Two orders of
3776/// magnitude below the [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` ceiling
3777/// (the upper bracket on the same axis, sibling of this lower default;
3778/// both are typed `u32` const bounds on the `:supervisor :max-restarts`
3779/// axis and now share one accessor discipline on the substrate) and
3780/// above the OTP-`supervisor` callback-module `MaxR = 1` minimum-
3781/// restart floor — the "one restart, then escalate" default is
3782/// deliberately loose enough to absorb a short burst of transient
3783/// child failures without escalating past the supervisor's parent
3784/// while remaining tight enough to trip the `MaxIntensity / Period`
3785/// ratio's escalation on a genuinely-stuck child within the sibling
3786/// `60s` sliding window.
3787///
3788/// Lifted as a typed `pub const` so the bound has exactly one source
3789/// of truth — the serde-side wire-format author-omitted arm at
3790/// [`default_max_restarts`], the [`Default for SupervisorSpec`] impl's
3791/// struct-literal default field, and the caixa-core
3792/// [`crate::manifest::Caixa::supervisor_view`] fold's author-omitted
3793/// arm all read from one place. Same shape every other typed default
3794/// in this crate carries (the sibling
3795/// [`SUPERVISOR_MAX_RESTARTS_MAX`] upper cap on the same axis, the
3796/// paired [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the
3797/// sibling `:restart-window` axis, and the peer
3798/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
3799/// per-renderer defaults on the caixa-flux / caixa-helm rendering
3800/// axes).
3801pub const SUPERVISOR_MAX_RESTARTS_DEFAULT: u32 = 5;
3802
3803/// Upper-bound ceiling on the `:supervisor :max-restarts` axis — every
3804/// validated [`SupervisorSpec::max_restarts`] past
3805/// [`SupervisorSpec::validate`] lies in `1..=SUPERVISOR_MAX_RESTARTS_MAX`.
3806///
3807/// The typed field is `u32` (the zero-floor arm
3808/// [`SupervisorError::ZeroMaxRestarts`] already brackets the bottom edge),
3809/// so a programmatic struct literal
3810/// (`SupervisorSpec { max_restarts: u32::MAX, .. }`) and the equivalent
3811/// author-surface form (`:max-restarts 4294967295` or any
3812/// `:max-restarts 100000`-shape typo landing in the slot) both round-trip
3813/// cleanly through serde — a structurally unbounded `u32` ceiling. The
3814/// runtime substrate consuming the value (Erlang/OTP's
3815/// `MaxIntensity / Period` ratio, the future wasm-operator's
3816/// per-supervisor restart-intensity counter, the M4
3817/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook)
3818/// then turned a typed `:max-restarts` policy into a no-op supervisor: the
3819/// escalation threshold is structurally so high that no realistic
3820/// restarts-per-`:restart-window` traffic shape can reach it, the
3821/// supervisor never escalates to its parent, and a bad child can loop
3822/// inside the window indefinitely with the parent supervisor structurally
3823/// never receiving the "this subtree has exceeded its restart budget"
3824/// signal the typed slot is meant to express — the canonical
3825/// "supervisor intensity declared, no escalation" footgun, exactly the
3826/// peer of the [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap
3827/// on the `:politicas :circuit-breaker :max-failures` axis (both are
3828/// "trip the next-higher protection layer after N events in a rolling
3829/// window" counters with identical degenerate-at-the-high-end shape).
3830///
3831/// The `1000` ceiling matches the sibling
3832/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] (the closest
3833/// peer — same "events-per-window trip threshold" semantics, same `u32`
3834/// type, same no-op-at-the-high-end failure mode) so the M4
3835/// `mesh.pleme.io/v1alpha1/Supervisor` / `.../Aplicacao` CR materializers
3836/// and the future wasm-operator's per-supervisor restart-intensity
3837/// counter reach for either field knowing the value is in `1..=1000`
3838/// without re-validating at the reconciler layer. The cap sits two
3839/// orders of magnitude above every documented Erlang/OTP production
3840/// playbook recommendation (Learn You Some Erlang's
3841/// `{intensity, 5, 60}` worker-supervisor default, Elixir's `Supervisor`
3842/// `max_restarts: 3` default, OTP's `supervisor` callback module
3843/// `MaxR = 1` / `MaxT = 5` "minimal-restart" default, Riak Core's
3844/// typical `MaxR ∈ 5..=100`, RabbitMQ's broker-supervisor `MaxR = 5`
3845/// default) and below the clearly-pathological "effectively no
3846/// escalation" floor (`10_000`, `100_000`, `u32::MAX`): a value the
3847/// author can plausibly want at hyperscale (a long-running supervisor
3848/// over a very-flaky pool tolerating thousands of transient restarts
3849/// before escalating), but a hard wall above which the typed policy is
3850/// structurally a no-op carried verbatim on every emitted child-restart
3851/// reconciliation contract.
3852///
3853/// Lifted as a typed `pub const` so the bound has exactly one source of
3854/// truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
3855/// materializer's admission webhook and the wasm-operator-side
3856/// per-supervisor restart-intensity reconciler read from one place. Same
3857/// shape every other typed upper bound in this crate carries
3858/// ([`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
3859/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
3860/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
3861/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3862/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3863/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3864pub const SUPERVISOR_MAX_RESTARTS_MAX: u32 = 1000;
3865
3866/// Upper-bound ceiling on the `:supervisor :restart-window` axis —
3867/// every validated `Some(`[`SupervisorSpec::restart_window`]`)` past
3868/// [`SupervisorSpec::validate`] lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
3869/// (inclusive on both ends, integer-millisecond magnitudes by the
3870/// canonical-form gate immediately preceding).
3871///
3872/// The typed field is `Option<Duration>` (the zero-floor arm
3873/// [`SupervisorError::RestartWindowZero`] already rejects
3874/// `Some(Duration::ZERO)`, and the canonical-form arm
3875/// [`SupervisorError::RestartWindowNotCanonical`] already rejects
3876/// sub-millisecond residue), so a programmatic struct literal
3877/// (`SupervisorSpec { restart_window: Some(Duration::from_secs(86_400)),
3878/// .. }` — 24h) and the equivalent author-surface form
3879/// (`(:supervisor (:restart-window "24h"))` — the shared duration codec
3880/// emits `"<n>h"` for any integer-hour magnitude) both round-trip
3881/// cleanly through serde — a structurally unbounded `Duration` ceiling.
3882/// A `:restart-window` value far above the documented Erlang/OTP
3883/// `MaxIntensity / Period` production-playbook band (Learn You Some
3884/// Erlang's `{intensity, 5, 60}` worker-supervisor `Period = 60s`
3885/// default, Elixir's `Supervisor` `max_seconds: 5` default, OTP's
3886/// `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's
3887/// `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default)
3888/// degenerates the supervisor's restart-intensity counter into a
3889/// lifetime counter: the rolling failure-counting window is structurally
3890/// so long that transient restarts are never forgotten, so the
3891/// `MaxIntensity / Period` ratio degenerates from "trip the parent
3892/// supervisor when the child has exceeded its restart budget *within
3893/// the recent window*" to "trip the parent when the child has exceeded
3894/// its restart budget *over its lifetime*" — every transient restart
3895/// counts against the budget forever, the supervisor's reset semantic
3896/// never reaches the child, and the typed `:restart-window` slot
3897/// becomes a no-op rolling window carried on every emitted hierarchical
3898/// reconciliation contract. The canonical
3899/// rolling-window-degenerates-to-lifetime-counter footgun the sibling
3900/// [`crate::POLICY_BREAKER_WINDOW_MAX`] cap closes on the peer
3901/// `:politicas :circuit-breaker :window` axis with identical shape (both
3902/// are "rolling failure-counting window with a per-`Period` reset" Duration
3903/// axes whose lifetime-counter degenerate at the high end is the same
3904/// "the reset semantic never fires" CSE invariant violation).
3905///
3906/// The `1h` (3600s = `3_600_000` ms) ceiling matches the largest unit
3907/// the shared duration codec emits (`"<n>h"` for any integer-hour
3908/// magnitude) — every value in the canonical authoring form's
3909/// `<integer><unit>` grammar at or below this cap renders to a clean
3910/// canonical string — and matches the three sibling typed-`Duration`
3911/// caps already lifted to this surface
3912/// ([`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
3913/// [`crate::POLICY_BREAKER_WINDOW_MAX`]). All four typed-`Duration`
3914/// axes — per-process `:limits :wall-clock`, per-edge `:politicas
3915/// :timeout`, per-breaker `:politicas :circuit-breaker :window`, and
3916/// per-supervisor `:supervisor :restart-window` — now share a single
3917/// uniform top edge at the codec's largest emitted unit so the next
3918/// typed-slot wiring (the future wasm-operator's per-supervisor
3919/// `MaxIntensity / Period` reconciler, the M4
3920/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
3921/// webhook, the `caixa-operator`'s hierarchical reconciliation
3922/// scheduler) reaches for any of the four knowing the value is in
3923/// `1ms..=1h` without re-validating at the renderer layer. The cap sits
3924/// two orders of magnitude above every documented Erlang/OTP / Elixir /
3925/// Riak Core / RabbitMQ production-playbook recommendation band
3926/// (`5s..=300s`) and below the clearly-pathological "rolling window
3927/// degenerates to lifetime counter" floor (`24h`, `7d`, `Duration::MAX`):
3928/// a value the author can plausibly want for a very-low-traffic
3929/// long-tail failure-restart window over a hyperscale-flaky child pool,
3930/// but a hard wall above which the rolling-window contract is
3931/// structurally a lifetime-counter contract.
3932///
3933/// Lifted as a typed `pub const` so the bound has exactly one source
3934/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
3935/// materializer's admission webhook, the wasm-operator-side
3936/// per-supervisor `MaxIntensity / Period` reconciler, and the
3937/// `caixa-operator`'s hierarchical reconciliation scheduler all read
3938/// from one place. Same shape every other typed upper bound in this
3939/// crate carries ([`SUPERVISOR_MAX_RESTARTS_MAX`],
3940/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
3941/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
3942/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
3943/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3944/// [`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
3945/// [`crate::POLICY_BREAKER_WINDOW_MAX`],
3946/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3947/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3948pub const SUPERVISOR_RESTART_WINDOW_MAX: Duration = Duration::from_secs(3600);
3949
3950/// Substrate-canonical Erlang/OTP-shaped `Period` sliding-window-duration
3951/// default for the `:supervisor :restart-window` axis — the canonical
3952/// `{intensity, 5, 60}` `Period` half of Learn You Some Erlang's
3953/// worker-supervisor default, extracted as a typed `pub const` so every
3954/// substrate-side consumer that resolves "what
3955/// [`SupervisorSpec::restart_window`] value does an author-omitted
3956/// `:restart-window` slot degrade onto?" reaches for exactly one
3957/// substrate-primitive [`Duration`].
3958///
3959/// The `:restart-window` default axis has one production consumer on the
3960/// substrate side today: the [`Default for SupervisorSpec`] impl's
3961/// struct-literal `restart_window` field, which prior to this lift folded
3962/// onto a raw `Duration::from_secs(60)` literal with no compile-time link
3963/// back to the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity`
3964/// half of the same `{intensity, 5, 60}` OTP-canonical default. The
3965/// [`crate::manifest::Caixa::supervisor_view`] fold deliberately does
3966/// *not* fall back to this default on the sibling `:restart-window` axis
3967/// — an author-omitted `:supervisor :restart-window` composes to
3968/// `restart_window: None` (the shared codec's soft-swallow shape),
3969/// keeping author-declared intent ("no reset — never escalate on rolling
3970/// window") distinct from the [`Default for SupervisorSpec`] "canonical
3971/// 60s Period" arm every programmatic `SupervisorSpec::default()` caller
3972/// resolves to. Prior to this lift the paired `{intensity, 5, 60}` OTP
3973/// default was split across two files with no compile-time link between
3974/// the halves: [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] pinned the
3975/// `MaxIntensity` half at the substrate primitive while the `Period`
3976/// half rode as an open-coded literal at the composition site, so a
3977/// future coherent rebrand of the paired canonical (a tightening to
3978/// Elixir's `{max_restarts: 3, max_seconds: 5}`, a widening to a
3979/// per-cluster overlay the operator pins through a future
3980/// `:supervisor :restart-window-overrides` slot the MESH-COMPOSITION
3981/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
3982/// paired constants to a per-child-cohort `{MaxR, MaxT}` restart-budget-
3983/// partition once the INSPIRATIONS §II.2 Erlang/OTP per-child-cohort
3984/// roadmap lands) would have had to migrate the `MaxIntensity` half
3985/// through the lifted constant and the `Period` half through a raw
3986/// literal in lockstep or the two halves of the same OTP-canonical
3987/// default would silently drift out of pairing. Lifting the resolution
3988/// rule to a typed `pub const` on the substrate primitive means the
3989/// paired OTP-canonical default migrates as one unit on any future
3990/// axis change.
3991///
3992/// The `60s` value pins Learn You Some Erlang's `{intensity, 5, 60}`
3993/// worker-supervisor default (the closest canonical OTP-shape
3994/// production reference the substrate carries, matching the paired
3995/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5` `MaxIntensity` half this
3996/// constant is the `Period` denominator of on the same
3997/// `MaxIntensity / Period` restart-intensity ratio). Two orders of
3998/// magnitude below the [`SUPERVISOR_RESTART_WINDOW_MAX`] `3600s`
3999/// (`1h`) ceiling (the upper bracket on the same axis, sibling of
4000/// this lower default; both are typed [`Duration`] const bounds on the
4001/// `:supervisor :restart-window` axis and now share one accessor
4002/// discipline on the substrate) and above the OTP-`supervisor`
4003/// callback-module `MaxT = 5` seconds "minimal-window" floor — the "60s
4004/// rolling window" default is deliberately loose enough to absorb a
4005/// short burst of transient child failures without escalating past the
4006/// supervisor's parent while remaining tight enough for the paired
4007/// `MaxIntensity / Period` ratio's escalation to trip on a genuinely-
4008/// stuck child within a human-scale observation window.
4009///
4010/// Lifted as a typed `pub const` so the paired OTP-canonical default has
4011/// exactly one source of truth on each half — the sibling
4012/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half and this
4013/// `Period` `60s` half now share the same substrate-primitive lift
4014/// discipline. Same shape every other typed default in this crate
4015/// carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] paired
4016/// `MaxIntensity` half on the same OTP-canonical `{intensity, 5, 60}`,
4017/// the sibling [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the same
4018/// axis, and the peer [`crate::render::DEFAULT_NAMESPACE`] /
4019/// [`crate::render::DEFAULT_LIBRARY_NAME`] per-renderer defaults on the
4020/// caixa-flux / caixa-helm rendering axes).
4021pub const SUPERVISOR_RESTART_WINDOW_DEFAULT: Duration = Duration::from_secs(60);
4022
4023/// Substrate-canonical Erlang/OTP-shaped sibling-restart-strategy default
4024/// for the `:supervisor :estrategia` axis — the canonical `one_for_one`
4025/// half of Learn You Some Erlang's `{one_for_one, intensity, 5, 60}`
4026/// worker-supervisor default, extracted as a typed `pub const` so every
4027/// substrate-side consumer that resolves "what
4028/// [`SupervisorSpec::estrategia`] variant does an author-omitted
4029/// `:estrategia` slot degrade onto?" reaches for exactly one substrate-
4030/// primitive [`RestartStrategy`].
4031///
4032/// The `:estrategia` default axis has three production consumers on the
4033/// substrate side today: the [`Default for RestartStrategy`] impl's
4034/// return arm, the [`Default for SupervisorSpec`] impl's struct-literal
4035/// `estrategia` field, and the
4036/// [`crate::manifest::Caixa::supervisor_view`] fold's
4037/// `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)` `Option<RestartStrategy>`
4038/// collapse arm — three entry points onto the same OTP-canonical
4039/// `one_for_one` value that prior to this lift folded onto a raw
4040/// `Self::OneForOne` arm at the [`Default for RestartStrategy`] impl and
4041/// implicit `RestartStrategy::default()` routes at the sibling consumers,
4042/// with no compile-time link back to the paired
4043/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` half + the paired
4044/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` half of the same
4045/// `{one_for_one, intensity, 5, 60}` OTP-canonical default. The paired
4046/// triple was split across three altitudes with no compile-time link
4047/// between the halves: the `MaxIntensity` half rode through the lifted
4048/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant (b698ec0) and the `Period`
4049/// half rode through the lifted [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
4050/// constant (f7dcd0e) while the `one_for_one` half rode as an open-coded
4051/// discriminator at the [`Default for RestartStrategy`] impl, so a future
4052/// coherent rebrand of the triple (Elixir's `{:one_for_one,
4053/// max_restarts: 3, max_seconds: 5}` — same strategy, different
4054/// intensity/period; an OTP `rest_for_one` widening once the substrate
4055/// discovers startup-order-coupled child cohorts as the more common
4056/// worker-supervisor default; a per-cluster overlay the operator pins
4057/// through a future `:estrategia-overrides` slot the MESH-COMPOSITION
4058/// §III.2 supervision-canary roadmap acknowledges) would have had to
4059/// migrate the `MaxIntensity` + `Period` halves through the lifted
4060/// constants and the `one_for_one` half through an open-coded arm in
4061/// lockstep or the three halves of the same OTP-canonical default would
4062/// silently drift out of pairing. Lifting the resolution rule to a typed
4063/// `pub const` on the substrate primitive means the paired OTP-canonical
4064/// worker-supervisor default migrates as one unit on any future axis
4065/// change.
4066///
4067/// The [`RestartStrategy::OneForOne`] value pins Learn You Some Erlang's
4068/// `{one_for_one, intensity, 5, 60}` worker-supervisor default (the
4069/// closest canonical OTP-shape production reference the substrate
4070/// carries, matching the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5`
4071/// `MaxIntensity` half and the paired [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
4072/// `60s` `Period` half). The `one_for_one` strategy — restart only the
4073/// failed child, leaving siblings untouched — is the default for tree-of-
4074/// independent-workers use cases the substrate's [`RestartStrategy`]
4075/// discriminator's own docstring already carries as the default arm; it
4076/// composes with the `{5, 60}` restart-intensity ratio to name the same
4077/// substrate-canonical "canonical worker-supervisor" shape the paired
4078/// halves close on their respective axes.
4079///
4080/// Lifted as a typed `pub const` so the paired OTP-canonical default has
4081/// exactly one source of truth on each of its three halves — the sibling
4082/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half, the
4083/// sibling [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` `60s` half, and
4084/// this `one_for_one` strategy half now share the same substrate-
4085/// primitive lift discipline. Same shape every other typed default in
4086/// this crate carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] +
4087/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] paired halves on the same OTP-
4088/// canonical `{one_for_one, intensity, 5, 60}`, the sibling
4089/// [`SUPERVISOR_MAX_RESTARTS_MAX`] + [`SUPERVISOR_RESTART_WINDOW_MAX`]
4090/// upper caps on the paired sibling axes, and the peer
4091/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
4092/// per-renderer defaults on the caixa-flux / caixa-helm rendering axes).
4093pub const SUPERVISOR_ESTRATEGIA_DEFAULT: RestartStrategy = RestartStrategy::OneForOne;
4094
4095/// Substrate-canonical Erlang/OTP-shaped per-child restart-decision-policy
4096/// default for the `:children :restart` axis — the OTP `permanent`
4097/// worker-child default (`{ChildId, StartFunc, permanent, …}` in a
4098/// `supervisor`'s `init/1` child-spec tuple), extracted as a typed
4099/// `pub const` so every substrate-side consumer that resolves "what
4100/// [`ChildSpec::restart`] variant does an author-omitted `:children
4101/// :restart` slot degrade onto?" reaches for exactly one substrate-
4102/// primitive [`RestartPolicy`].
4103///
4104/// Completes the OTP-shape supervisor-tree default set at the substrate
4105/// primitive. The per-`:supervisor` axis already carries all three of its
4106/// halves as lifted typed constants — [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
4107/// (`one_for_one`, 95ffacc), [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
4108/// (`MaxIntensity` `5`, b698ec0), [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
4109/// (`Period` `60s`, f7dcd0e) — while the per-`:children` axis's own
4110/// OTP-canonical default rode as an open-coded `Self::Permanent` arm in
4111/// the [`Default for RestartPolicy`] impl, the last un-lifted default on
4112/// the M2 `:supervisor` slot family. The split mattered because the two
4113/// axes resolve *together* on every author-omitted supervisor: a
4114/// `(defcaixa :kind Supervisor :children ((:caixa "worker" :versao
4115/// "^0.1")))` with no `:estrategia` and no per-child `:restart` degrades
4116/// onto `{one_for_one, 5, 60}` through three lifted constants and onto
4117/// `permanent` through an open-coded enum arm, so a future coherent
4118/// rebrand of the OTP-shape default set (an Elixir-shaped
4119/// `{:one_for_one, max_restarts: 3, max_seconds: 5}` tightening, a
4120/// per-cluster overlay the operator pins through the MESH-COMPOSITION
4121/// §III.2 supervision-canary roadmap slots, an OTP-`transient` widening
4122/// once the substrate discovers clean-completion-aware children as the
4123/// more common child shape) would have had to migrate three halves
4124/// through typed constants and the fourth through a raw enum arm in
4125/// lockstep or the supervisor-level and child-level defaults would
4126/// silently drift apart.
4127///
4128/// The `:children :restart` default axis has two production consumers on
4129/// the substrate side today: the [`Default for RestartPolicy`] impl's
4130/// return arm, and the serde-side `#[serde(default)]` on
4131/// [`ChildSpec::restart`] that resolves an author-omitted `:children
4132/// :restart` slot through that same impl. Both now key off this one
4133/// substrate primitive, so the future wasm-operator's per-child post-exit
4134/// restart-decision branch, the future M4
4135/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
4136/// admission webhook, and the `caixa-operator`'s hierarchical
4137/// reconciliation scheduler's per-child fan-out all reach for one typed
4138/// identifier when they resolve an omitted per-child restart posture.
4139///
4140/// The [`RestartPolicy::Permanent`] value pins Erlang/OTP's `permanent`
4141/// worker-child restart type — always restart the child regardless of how
4142/// it died, the canonical posture for long-running services that must
4143/// always be up, matching the sibling [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
4144/// `one_for_one` tree-of-independent-workers strategy this constant pairs
4145/// with under the same `{one_for_one, intensity, 5, 60}` worker-supervisor
4146/// shape. The two alternatives the closed [`RestartPolicy::ALL`] accept-set
4147/// carries ([`RestartPolicy::Transient`] — restart only on abnormal exit;
4148/// [`RestartPolicy::Temporary`] — never restart) express deliberate
4149/// one-shot / clean-completion-aware postures an author declares
4150/// explicitly, never a posture an omitted slot should silently assume.
4151pub const SUPERVISOR_CHILD_RESTART_DEFAULT: RestartPolicy = RestartPolicy::Permanent;
4152
4153/// Route the manually-authored [`Default`] impl on [`SupervisorSpec`]
4154/// through the substrate-canonical [`SupervisorSpec::otp_canonical`]
4155/// `pub const fn` constructor rather than a struct-literal cascade over
4156/// the paired [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
4157/// [`default_max_restarts`] / [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
4158/// lifted consts — one source of truth for the Erlang/OTP-canonical
4159/// `{one_for_one, 5, 60}` worker-supervisor baseline across the two
4160/// paths every downstream consumer already reaches through (the
4161/// hand-authored-until-now [`Default::default`] the
4162/// `..SupervisorSpec::default()` struct-update-syntax on every
4163/// one-axis-under-test fixture in this crate's test module rests on,
4164/// and the `pub const fn` [`SupervisorSpec::otp_canonical`] constructor
4165/// every `const`-context consumer reaches through).
4166///
4167/// Extends the [`Default`]-through-const-ctor fold discipline the
4168/// [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
4169/// (abd52c2), [`crate::aplicacao::MeshPolicy`]
4170/// [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`] (91641a4),
4171/// and [`crate::BehaviorSpec`]
4172/// [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c) folds
4173/// closed on the M2 / M3 `Option`-only "canonical unset baseline"
4174/// typed-slot spec family — extended here onto the M2 supervisor-slot
4175/// [`SupervisorSpec`] whose canonical baseline is not "everything
4176/// `None`" but the OTP-canonical `{one_for_one, 5, 60}` worker-
4177/// supervisor triple. The `empty()` peer's naming did not fit
4178/// (`SupervisorSpec` carries a discriminator-shaped `estrategia` field
4179/// and a non-zero `max_restarts`/`restart_window` pair whose canonical
4180/// shape is Erlang/OTP-descended, not the "no axis declared" bottom
4181/// the sibling `Option`-only slots fold to), so this peer is named
4182/// [`SupervisorSpec::otp_canonical`] instead — the same phrasing the
4183/// existing per-arm pin tests
4184/// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`] /
4185/// [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`] /
4186/// [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
4187/// already reach for. Pinned load-bearing by
4188/// [`tests::supervisor_spec_default_routes_through_otp_canonical_ctor`]
4189/// (byte-parity pin against [`SupervisorSpec::otp_canonical`] under
4190/// [`PartialEq`], sharpening the sibling
4191/// `supervisor_spec_default_*_routes_through_lifted_default` per-arm
4192/// pins from a per-field lift into a whole-struct one-source-of-truth
4193/// pin — the derived-until-now [`Default::default`] and the
4194/// [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
4195/// construction, not by coincidence).
4196impl Default for SupervisorSpec {
4197    #[inline]
4198    fn default() -> Self {
4199        Self::otp_canonical()
4200    }
4201}
4202
4203impl SupervisorSpec {
4204    /// `const`-context peer of the [`Default for SupervisorSpec`]
4205    /// impl (which routes through this constructor) — returns the
4206    /// Erlang/OTP-canonical `{one_for_one, 5, 60}` worker-supervisor
4207    /// baseline this crate reaches for in every fixture-builder
4208    /// `..SupervisorSpec::default()` struct-update expression and
4209    /// every downstream `SupervisorSpec::default()` seed.
4210    ///
4211    /// Each field routes through the same substrate-canonical
4212    /// [`SUPERVISOR_ESTRATEGIA_DEFAULT`] / [`default_max_restarts`] /
4213    /// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] lifted consts the
4214    /// per-arm pin tests
4215    /// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`]
4216    /// / [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`]
4217    /// / [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
4218    /// already assert, so a future coherent rebrand of the OTP-canonical
4219    /// triple (Elixir's `{max_restarts: 3, max_seconds: 5}`, a per-
4220    /// cluster overlay via a future `:restart-window-overrides` slot, a
4221    /// per-child-cohort promotion the INSPIRATIONS.md §II.2 Erlang/OTP
4222    /// absorption roadmap acknowledges) migrates through three typed
4223    /// constants in lockstep, and the paired [`Default`] impl inherits
4224    /// every future extension by construction.
4225    ///
4226    /// `pub const fn` rather than the derived-style `Default::default`
4227    /// or a `pub const SUPERVISOR_SPEC_DEFAULT: SupervisorSpec` item —
4228    /// [`Default::default`] is not `const` on stable Rust, and
4229    /// `SupervisorSpec` is non-`Copy` so a `pub const` item would force
4230    /// every consumer through a [`Clone::clone`]. The `pub const fn`
4231    /// discipline lets `const`-context callers construct the OTP-
4232    /// canonical baseline at compile time without runtime dispatch on
4233    /// the derived [`Default::default`], the same posture the sibling
4234    /// [`crate::LimitsSpec::empty`] (9739971) /
4235    /// [`crate::aplicacao::MeshPolicy::empty`] (6df969b) /
4236    /// [`crate::BehaviorSpec::empty`] (f9b18e3) `Option`-only typed-slot
4237    /// spec `pub const fn` constructors carry on the sibling
4238    /// "everything `None`" baseline axis.
4239    ///
4240    /// Fourth peer on the M2 / M3 typed-slot-spec "const-context peer
4241    /// of the derived-style [`Default`]" family — sibling of the
4242    /// [`crate::LimitsSpec::empty`] / [`crate::aplicacao::MeshPolicy::empty`]
4243    /// / [`crate::BehaviorSpec::empty`] `Option`-only "canonical unset
4244    /// baseline" trio, extended here onto the M2 supervisor-slot
4245    /// [`SupervisorSpec`] whose canonical baseline is not "everything
4246    /// `None`" but the Erlang/OTP-canonical `{one_for_one, 5, 60}`
4247    /// worker-supervisor triple. Named [`Self::otp_canonical`] rather
4248    /// than `empty()` to name the actual invariant the return value
4249    /// pins — the same phrasing already used in the per-arm pin tests
4250    /// on this file. Pinned load-bearing by
4251    /// [`tests::supervisor_spec_otp_canonical_byte_equals_default`] and
4252    /// [`tests::supervisor_spec_otp_canonical_is_usable_in_const_context`].
4253    #[must_use]
4254    pub const fn otp_canonical() -> Self {
4255        Self {
4256            estrategia: SUPERVISOR_ESTRATEGIA_DEFAULT,
4257            max_restarts: default_max_restarts(),
4258            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
4259            children: Vec::new(),
4260        }
4261    }
4262
4263    /// Substrate-canonical per-`:supervisor` `:estrategia` OTP-shaped
4264    /// sibling-restart-strategy scalar accessor every consumer that
4265    /// dispatches on the supervisor's per-sibling restart-decision shape
4266    /// keys off — returns the author-declared `:supervisor :estrategia`
4267    /// variant verbatim as a [`RestartStrategy`], `Copy`-projected from
4268    /// the typed slot's own [`RestartStrategy`] storage.
4269    ///
4270    /// The `:supervisor :estrategia` slot carries the closed-set
4271    /// OTP-shaped sibling-restart-strategy discriminator ([`RestartStrategy::OneForOne`]
4272    /// — restart only the failed child, the Erlang/OTP `one_for_one` default;
4273    /// [`RestartStrategy::OneForAll`] — restart every child on any child
4274    /// failure, the Erlang/OTP `one_for_all` shared-state cohort default;
4275    /// [`RestartStrategy::RestForOne`] — restart the failed child and
4276    /// every child started after it, the Erlang/OTP `rest_for_one`
4277    /// startup-order default; [`RestartStrategy::SimpleOneForOne`] —
4278    /// dynamic children of the same shape, the Erlang/OTP
4279    /// `simple_one_for_one` per-session default) that every downstream
4280    /// consumer of the Supervisor's per-sibling restart-decision fan-out
4281    /// shape keys off. Validated by [`SupervisorSpec::validate`] to be
4282    /// paired coherently with the sibling `:children` axis
4283    /// (`SimpleOneForOne ↔ children.is_empty()` — the cross-slot
4284    /// partition the strategy-arm's [`SupervisorError::SimpleOneForOneWithStaticChildren`]
4285    /// / [`SupervisorError::NoChildren`] refusal cascade pins), and every
4286    /// downstream consumer that reads the strategy keys off this scalar
4287    /// (the [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
4288    /// partition-dispatch `match` arm, the non-`SimpleOneForOne`-arm
4289    /// declared-but-empty [`SupervisorError::NoChildren`] error carrier's
4290    /// `estrategia:` field, the future `feira app graph` per-Supervisor
4291    /// strategy print line, the future wasm-operator's per-supervisor
4292    /// sibling-restart-strategy branch, the future M4
4293    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-strategy
4294    /// admission-webhook resolver, the `caixa-operator`'s hierarchical
4295    /// reconciliation scheduler's per-strategy fan-out).
4296    ///
4297    /// Prior to this lift the `.estrategia` field was accessed inline at
4298    /// two production sites in `caixa-core/src/supervisor.rs` — the
4299    /// [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
4300    /// `match self.estrategia { … }` partition dispatch, and the
4301    /// non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
4302    /// carrier at `estrategia: self.estrategia` — two open-coded
4303    /// field-accesses that expressed no compile-time link back to the
4304    /// typed slot. A future extension of the `:supervisor :estrategia`
4305    /// axis to a richer author surface (a per-cluster strategy override
4306    /// the operator pins through a future `:supervisor :estrategia-overrides`
4307    /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
4308    /// acknowledges, a per-tenant strategy-alias table the M4 CR
4309    /// materializer resolves per-CR, a per-Supervisor dynamic strategy
4310    /// derivation the future adaptive-supervision engine computes from
4311    /// child-failure-history topology, a per-child-cohort strategy split
4312    /// the future `RestForCohort` extension acknowledged by the
4313    /// INSPIRATIONS.md §II.2 Erlang/OTP absorption roadmap acknowledges)
4314    /// would have had to be threaded through every open-coded copy in
4315    /// lockstep — one consumer reading the raw variant while a peer read
4316    /// the operator-resolved variant would silently split the
4317    /// [`SupervisorError::NoChildren`] diagnostic's quoted strategy from
4318    /// the actual partition-dispatch input the empty-children refusal
4319    /// arm reached under, a two-consumer split at the validator far from
4320    /// the source `caixa.lisp` with no field naming the strategy-drift
4321    /// root cause. Lifting the resolution rule to a typed method on the
4322    /// substrate primitive means every downstream consumer of the
4323    /// Supervisor's per-`:supervisor` sibling-restart-strategy surface
4324    /// reaches for exactly one typed dispatch — the resolver's accept-set
4325    /// migrates as a unit on any future axis addition.
4326    ///
4327    /// Peer of the sibling M3 mesh-slot [`crate::Placement::estrategia`]
4328    /// (921fe1b) `Copy`-return `PlacementStrategy` scalar accessor on the
4329    /// per-`:placement` distribution-strategy axis — same "one typed
4330    /// dispatch on the substrate primitive, thin projections at each
4331    /// consumer" discipline extended onto the M2 supervisor-slot
4332    /// per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
4333    /// scalar axis. The two typed axes (`Placement::estrategia` on the
4334    /// M3 Aplicacao side, `SupervisorSpec::estrategia` on the M2
4335    /// Supervisor side) now share one accessor discipline for the shared
4336    /// substrate concept "a `Copy`-projected closed-set enum-arm
4337    /// discriminator that partitions the downstream renderer's per-arm
4338    /// fan-out". First `Copy`-return accessor on the M2 supervisor-slot
4339    /// `SupervisorSpec` type — companion to the sibling per-`:children`
4340    /// [`crate::ChildSpec::nome`] (57c61d0) /
4341    /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
4342    /// scalar accessors on the sibling per-`:children` `String`-carry
4343    /// axes. Named `estrategia()` to match the storage field's name and
4344    /// the peer [`crate::Placement::estrategia`] method-name discipline
4345    /// verbatim; the accessor's identity name maps onto the canonical
4346    /// OTP-shape supervision vocabulary the [`RestartStrategy`] enum's
4347    /// docstring already carries.
4348    ///
4349    /// Declared `pub const fn` to close the M2 supervisor-slot
4350    /// `Copy`-return raw-field-getter `const`-eval-surface pass —
4351    /// sibling of the peer M2 per-`:children` [`ChildSpec::restart`]
4352    /// (converted in this commit) `Copy`-composite-enum accessor, peer
4353    /// of the sibling M2 per-`:supervisor`
4354    /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
4355    /// already lifted, and mirror of the peer M3 mesh-slot
4356    /// per-`:placement` [`crate::Placement::estrategia`] (bafa004)
4357    /// `Copy`-return `pub const fn` scalar accessor whose method-name
4358    /// discipline this accessor was authored to match. Every downstream
4359    /// substrate-side `const`-context consumer of the per-`:supervisor`
4360    /// sibling-restart-strategy scalar (a future module-scope `const
4361    /// _:() = assert!(matches!(sup.estrategia(),
4362    /// RestartStrategy::OneForOne))` invariant pin on a typed fixture,
4363    /// a future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
4364    /// admission-webhook `const fn` per-supervisor strategy-arm floor
4365    /// over a typed [`SupervisorSpec`], any future `const fn`
4366    /// supervisor-tree composer over the substrate primitive that fans
4367    /// on the sibling-restart-strategy at compile time) now reaches
4368    /// through the same typed dispatch on the substrate primitive at
4369    /// const-eval time as at runtime. A future non-`Copy`-return
4370    /// promotion of the scalar (an `Option<RestartStrategy>`-shape
4371    /// migration once the substrate grows per-cluster strategy overlays
4372    /// the [`SupervisorSpec`] docstring already anticipates, a
4373    /// per-tenant strategy-alias table the M4 CR materializer resolves
4374    /// per-CR) that would drop the `const` qualifier fails the
4375    /// fail-before-pass-after pin
4376    /// [`tests::supervisor_spec_estrategia_accessor_is_const_fn`] at
4377    /// caixa-core build time rather than surfacing as a downstream
4378    /// consumer regression.
4379    #[must_use]
4380    pub const fn estrategia(&self) -> RestartStrategy {
4381        self.estrategia
4382    }
4383
4384    /// Substrate-canonical per-`:supervisor` `:max-restarts` OTP-shaped
4385    /// `MaxIntensity` restart-budget scalar accessor every consumer that
4386    /// reads the supervisor's per-`:restart-window` restart-budget count
4387    /// keys off — returns the author-declared `:supervisor :max-restarts`
4388    /// typed `u32` verbatim, `Copy`-projected from the typed slot's own
4389    /// `u32` storage (`u32` is `Copy`, so the accessor returns by value; no
4390    /// borrow of `&self` past the call). Non-optional (the `u32` field
4391    /// carries the restart-budget count as a required axis with a
4392    /// [`default_max_restarts`]-supplied default; the zero-floor arm
4393    /// [`SupervisorError::ZeroMaxRestarts`] and the cap arm
4394    /// [`SupervisorError::MaxRestartsExceedsCap`] jointly bracket the
4395    /// accept-set to `1..=SUPERVISOR_MAX_RESTARTS_MAX`).
4396    ///
4397    /// The `:supervisor :max-restarts` slot carries the Erlang/OTP
4398    /// `MaxIntensity` restart-budget count that pairs with the sibling
4399    /// `:restart-window` `Period` to form the `MaxIntensity / Period`
4400    /// restart-intensity ratio the supervisor trips its own escalation on
4401    /// (`theory/RUNTIME-PATTERNS.md` §II.2, Learn You Some Erlang's
4402    /// `{intensity, 5, 60}` worker-supervisor default). Every downstream
4403    /// consumer of the Supervisor's per-`:supervisor` restart-budget count
4404    /// keys off this scalar (the [`SupervisorSpec::validate`] zero-floor +
4405    /// upper-cap bracket at
4406    /// `require_positive_bounded_u32(self.max_restarts(), …)`, the future
4407    /// wasm-operator's per-supervisor restart-intensity counter's
4408    /// budget-vs-count comparator, the future M4
4409    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
4410    /// webhook, the `caixa-operator`'s hierarchical reconciliation
4411    /// scheduler's per-supervisor escalation-decision branch, every
4412    /// `SupervisorError::MaxRestartsExceedsCap` variant carrying the
4413    /// offending count verbatim for `feira lint` rendering).
4414    ///
4415    /// Prior to this lift the `.max_restarts` field was accessed inline at
4416    /// one production site in `caixa-core/src/supervisor.rs` — the
4417    /// [`SupervisorSpec::validate`] `require_positive_bounded_u32(self
4418    /// .max_restarts, …)` bracket-gate call — one open-coded field-access
4419    /// that expressed no compile-time link back to the typed slot. A
4420    /// future extension of the `:max-restarts` axis to a richer author
4421    /// surface (a per-cluster restart-budget override the operator pins
4422    /// through a future `:supervisor :max-restarts-overrides` slot the
4423    /// MESH-COMPOSITION §III.2 supervision-canary roadmap acknowledges,
4424    /// a per-tenant restart-budget-alias table the M4 CR materializer
4425    /// resolves per-CR, a per-supervisor dynamic restart-budget derivation
4426    /// the future adaptive-supervision engine computes from child-failure-
4427    /// history topology, a promotion of the plain `u32` count to a richer
4428    /// `{MaxR, MaxT}` tuple once Erlang/OTP's per-child-cohort restart-
4429    /// budget-partition slot comes into scope) would have had to be
4430    /// threaded through every open-coded copy in lockstep or the validate
4431    /// gate and the future M4 emit path would silently disagree on which
4432    /// restart-budget count a given supervisor resolves to — an author's
4433    /// `:max-restarts 5` would satisfy validate while the emit path
4434    /// silently read a drifted other value (a `:max-restarts 10000`
4435    /// no-op supervisor at the emit boundary would carry the author's
4436    /// declared `5` verbatim in `feira lint` output while the future
4437    /// wasm-operator's restart-intensity counter operated under the
4438    /// drifted count), a two-consumer split at the validator far from the
4439    /// source `caixa.lisp` with no field naming the restart-budget-drift
4440    /// root cause. Lifting the resolution rule to a typed method on the
4441    /// substrate primitive means every downstream consumer of the
4442    /// Supervisor's per-`:supervisor` restart-budget-count surface reaches
4443    /// for exactly one typed dispatch — the resolver's accept-set migrates
4444    /// as a unit on any future axis addition.
4445    ///
4446    /// Peer of the sibling M3 mesh-slot [`crate::CircuitBreaker::max_failures`]
4447    /// (3a74062) `Copy`-return `u32` sub-struct required-scalar accessor
4448    /// on the per-`:politicas :circuit-breaker :max-failures` Envoy-
4449    /// outlier-detection trip-threshold axis — same "one typed dispatch on
4450    /// the substrate primitive, thin projections at each consumer"
4451    /// discipline extended onto the M2 supervisor-slot per-`:supervisor`
4452    /// restart-budget-count `Copy`-`u32` scalar axis. The two typed axes
4453    /// (`CircuitBreaker::max_failures` on the M3 Aplicacao side,
4454    /// `SupervisorSpec::max_restarts` on the M2 Supervisor side) now share
4455    /// one accessor discipline for the shared substrate concept "a
4456    /// `Copy`-projected required `u32` count that trips the next-higher
4457    /// protection layer after N events in a rolling window" — both are
4458    /// counters with identical degenerate-at-the-high-end shape and share
4459    /// the paired [`crate::POLICY_BREAKER_MAX_FAILURES_MAX`] /
4460    /// [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` cap. Second `Copy`-return
4461    /// accessor on the M2 supervisor-slot `SupervisorSpec` type, sibling
4462    /// to the [`SupervisorSpec::estrategia`] (eafb619) `Copy`-composite-
4463    /// enum `RestartStrategy` accessor. Named `max_restarts()` to match
4464    /// the storage field's name verbatim and the peer
4465    /// [`crate::CircuitBreaker::max_failures`] method-name discipline; the
4466    /// accessor's identity maps onto the canonical OTP-shape supervision
4467    /// vocabulary the [`SupervisorSpec::max_restarts`] field's docstring
4468    /// already carries.
4469    #[must_use]
4470    pub const fn max_restarts(&self) -> u32 {
4471        self.max_restarts
4472    }
4473
4474    /// Substrate-canonical per-`:supervisor` `:restart-window` OTP-shaped
4475    /// `Period` sliding-window scalar accessor every consumer of the
4476    /// supervisor's `MaxIntensity / Period` restart-intensity denominator
4477    /// keys off — returns the author-declared `:supervisor :restart-window`
4478    /// typed [`Duration`] verbatim as an `Option<Duration>`, copied out of
4479    /// the typed slot's own `Option<Duration>` storage (`Duration` is
4480    /// `Copy`, so `Option<Duration>` is `Copy` and the accessor returns by
4481    /// value; no borrow of `&self` past the call). `None` when the slot is
4482    /// absent (the canonical "never reset — every restart across the
4483    /// supervisor's lifetime counts against the sibling `:max-restarts`
4484    /// budget" sentinel the field's own docstring names and the peer
4485    /// `validate_accepts_none_restart_window` pin locks in on the
4486    /// [`SupervisorSpec::validate`] entry-side).
4487    ///
4488    /// The `:supervisor :restart-window` slot carries the Erlang/OTP
4489    /// `Period` sliding-observation-interval that pairs with the sibling
4490    /// `:max-restarts` `MaxIntensity` restart-budget count to form the
4491    /// `MaxIntensity / Period` restart-intensity ratio the supervisor
4492    /// trips its own escalation on (`theory/RUNTIME-PATTERNS.md` §II.2,
4493    /// Learn You Some Erlang's `{intensity, 5, 60}` worker-supervisor
4494    /// default). The typed slot's `Option<Duration>` accept-set —
4495    /// zero-floor rejected through [`SupervisorError::RestartWindowZero`]
4496    /// (Erlang/OTP's `MaxIntensity / Period` invariant requires
4497    /// `Period > 0`; a zero period either trips on the first failure or
4498    /// never trips depending on operator interpretation, neither of which
4499    /// is the author's intent — omit the slot to express "no reset";
4500    /// carry a positive duration to express the sliding window),
4501    /// integer-millisecond canonical form enforced through
4502    /// [`SupervisorError::RestartWindowNotCanonical`] (the duration
4503    /// codec's canonical form emits `"1500ms"` not `"1.5s"` and the
4504    /// future wasm-operator's per-supervisor restart-intensity counter
4505    /// quantizes at milliseconds), upper-bounded by
4506    /// [`SUPERVISOR_RESTART_WINDOW_MAX`] (1h — the coarsest per-
4507    /// supervisor rolling window any operationally-reachable supervisor
4508    /// can honor without spanning multiple scheduler epochs the
4509    /// hierarchical-reconciliation scheduler treats as independent) —
4510    /// maps onto the future wasm-operator (M3) per-supervisor
4511    /// restart-intensity counter's rolling-observation-interval, the
4512    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
4513    /// per-`spec.restartWindow` admission webhook, and the sibling
4514    /// `duration_codec`-serialized wire scalar every downstream consumer
4515    /// of the supervisor's per-`:supervisor` restart-intensity denominator
4516    /// keys off.
4517    ///
4518    /// Prior to this lift the `.restart_window` field was accessed inline
4519    /// at one production site in `caixa-core/src/supervisor.rs` — the
4520    /// [`SupervisorSpec::validate`] `if let Some(w) = self.restart_window {
4521    /// … }` zero-floor + canonical-form + upper-cap bracket arm — one
4522    /// open-coded field-access that expressed no compile-time link back to
4523    /// the typed slot. A future extension of the `:restart-window` axis to
4524    /// a richer author surface (a per-cluster restart-window override the
4525    /// operator pins through a future `:supervisor :restart-window-overrides`
4526    /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
4527    /// acknowledges, a per-tenant restart-window-alias table the M4 CR
4528    /// materializer resolves per-CR, a per-supervisor dynamic
4529    /// restart-window derivation the future adaptive-supervision engine
4530    /// computes from child-failure-history topology, a promotion of the
4531    /// plain `Option<Duration>` window to a richer `{observation, cooldown}`
4532    /// pair once Erlang/OTP's per-child-cohort observation-interval-
4533    /// partition slot comes into scope) would have had to be threaded
4534    /// through every open-coded copy in lockstep or the validate gate and
4535    /// the future M4 emit path would silently disagree on which
4536    /// restart-window a given supervisor resolves to — an author's
4537    /// `:restart-window "60s"` would satisfy validate while the emit path
4538    /// silently read a drifted other value (a `Some(Duration::from_secs(60))`
4539    /// authored slot at the emit boundary would carry the author's
4540    /// declared window verbatim in `feira lint` output while the future
4541    /// wasm-operator's restart-intensity counter operated under a
4542    /// drifted window, or vice versa: an author's `:restart-window ()`
4543    /// would carry the "never reset" sentinel through validate while the
4544    /// emit path silently substituted a default sliding window), a
4545    /// two-consumer split at the validator far from the source
4546    /// `caixa.lisp` with no field naming the restart-window-drift root
4547    /// cause. Lifting the resolution rule to a typed method on the
4548    /// substrate primitive means every downstream consumer of the
4549    /// Supervisor's per-`:supervisor` restart-intensity-denominator
4550    /// surface reaches for exactly one typed dispatch — the resolver's
4551    /// accept-set migrates as a unit on any future axis addition.
4552    ///
4553    /// Third `Copy`-return accessor on the M2 supervisor-slot
4554    /// `SupervisorSpec` type, closing the last unlifted per-`:supervisor`
4555    /// scalar-value axis (`children: Vec<ChildSpec>` carries a `Vec`
4556    /// payload rather than a `Copy`-scalar, and the per-`:children`
4557    /// [`crate::ChildSpec::nome`] (57c61d0) /
4558    /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
4559    /// scalar accessors already close the per-element `String`-carry
4560    /// axes). Sibling to the peer M2 [`crate::LimitsSpec::wall_clock`]
4561    /// (8cb717b) `Option<Duration>` accessor on the `:limits` slot's
4562    /// per-outermost-call wall-clock-deadline axis and the peer M3
4563    /// [`crate::MeshPolicy::timeout`] (7073d0f) `Option<Duration>`
4564    /// accessor on the `:politicas` slot's per-call-deadline axis — all
4565    /// three share the shared substrate concept "a `Copy`-projected
4566    /// optional `Duration` that carries a positive integer-millisecond
4567    /// canonical value with a `1ms..=<axis-specific>_MAX` accept-set and
4568    /// the paired zero-floor / non-canonical / above-cap refusal cascade"
4569    /// through the same [`crate::render::require_positive_canonical_bounded_duration`]
4570    /// bracket-helper the three axes each route through. Named
4571    /// `restart_window()` to match the storage field's name verbatim and
4572    /// the peer [`crate::LimitsSpec::wall_clock`] /
4573    /// [`crate::MeshPolicy::timeout`] method-name discipline; the
4574    /// accessor's identity maps onto the canonical OTP-shape supervision
4575    /// vocabulary the [`SupervisorSpec::restart_window`] field's docstring
4576    /// already carries.
4577    #[must_use]
4578    pub const fn restart_window(&self) -> Option<Duration> {
4579        self.restart_window
4580    }
4581
4582    /// Substrate-canonical per-`:supervisor` `:children` OTP-shaped
4583    /// static-child-list slice accessor every consumer that walks the
4584    /// supervisor's declared child set keys off — returns the author-
4585    /// declared `:supervisor :children` `Vec<ChildSpec>` verbatim as a
4586    /// `&[ChildSpec]` slice-view, borrowed from the typed slot's own
4587    /// `Vec<ChildSpec>` storage (a zero-copy slice-view over the same
4588    /// backing buffer the `Serialize`/`Deserialize` derives round-trip
4589    /// through). Non-optional: an empty slice is the load-bearing
4590    /// "author declared `:children ()`" sentinel every consumer of the
4591    /// cross-slot `SimpleOneForOne ↔ children.is_empty()` partition
4592    /// keys off (`SimpleOneForOne` requires the empty slice; the peer
4593    /// three strategies require a non-empty slice — the paired
4594    /// [`SupervisorError::SimpleOneForOneWithStaticChildren`] /
4595    /// [`SupervisorError::NoChildren`] refusal cascade pins the
4596    /// partition on both arms).
4597    ///
4598    /// The `:supervisor :children` slot carries the OTP-shaped static
4599    /// child list the supervisor materializes one ComputeUnit per
4600    /// entry from — the Erlang/OTP `supervisor:init/1`'s
4601    /// `{ok, {SupFlags, ChildSpecs}}` `ChildSpecs` list, projected
4602    /// through the tatara-lisp `:children` author surface onto a typed
4603    /// `Vec<ChildSpec>` whose per-element `(nome(),
4604    /// versao_requirement(), restart)` triple the per-child
4605    /// [`SupervisorSpec::validate`] loop already gates through the
4606    /// lifted [`ChildSpec::nome`] (57c61d0) /
4607    /// [`ChildSpec::versao_requirement`] (2c053c8) scalar accessors.
4608    /// Every downstream consumer that fans on the static child list
4609    /// keys off this slice (the [`SupervisorSpec::validate`]
4610    /// `SimpleOneForOne ↔ non-SimpleOneForOne` partition dispatch's
4611    /// `.is_empty()` probe on both arms, the [`SupervisorSpec::validate`]
4612    /// per-child DNS-1123 / semver-requirement / duplicate-detection
4613    /// fan-out loop, every future wasm-operator (M3) per-supervisor
4614    /// hierarchical-reconciliation scheduler's per-child ComputeUnit
4615    /// materialization loop, the future M4
4616    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
4617    /// admission-webhook fan-out, the future `feira app graph`
4618    /// per-supervisor tree-print traversal).
4619    ///
4620    /// Prior to this lift the `.children` `Vec<ChildSpec>` was accessed
4621    /// inline at three production sites in `caixa-core/src/supervisor.rs`
4622    /// — the [`SupervisorSpec::validate`] `SimpleOneForOne`-arm
4623    /// `!self.children.is_empty()` cross-slot refusal probe, the peer
4624    /// non-`SimpleOneForOne`-arm `self.children.is_empty()`
4625    /// [`SupervisorError::NoChildren`] refusal probe, and the per-child
4626    /// validate loop's `for child in &self.children` traversal head —
4627    /// three open-coded field-accesses that expressed no compile-time
4628    /// link back to the typed slot. A future extension of the
4629    /// `:supervisor :children` axis to a richer author surface (a
4630    /// per-cluster child-set overlay the operator pins through a future
4631    /// `:supervisor :children-overrides` slot the MESH-COMPOSITION §III.2
4632    /// supervision-canary roadmap acknowledges, a per-tenant
4633    /// child-set-alias table the M4 CR materializer resolves per-CR,
4634    /// a per-supervisor dynamic-child derivation the future adaptive-
4635    /// supervision engine computes from child-failure-history topology,
4636    /// a promotion of the plain `Vec<ChildSpec>` to a richer
4637    /// `{static, dynamic}` partition once Erlang/OTP's
4638    /// `simple_one_for_one` dynamic-child slot comes into typed scope)
4639    /// would have had to be threaded through all three open-coded copies
4640    /// in lockstep or one consumer would silently disagree with the
4641    /// peers on which child-set a given supervisor resolves to — the
4642    /// `SimpleOneForOne`-arm probe reading the raw slot while the peer
4643    /// non-`SimpleOneForOne`-arm probe read an operator-resolved slot
4644    /// would silently split the partition-dispatch's two-arm coherence
4645    /// (a supervisor that satisfies neither arm's precondition, or that
4646    /// satisfies both, at the cost of the paired
4647    /// `SimpleOneForOneWithStaticChildren`/`NoChildren` refusal cascade
4648    /// silently drifting from the per-child validate loop's actual
4649    /// traversal input), a three-consumer split at the validator far
4650    /// from the source `caixa.lisp` with no field naming the
4651    /// child-set-drift root cause. Lifting the resolution rule to a
4652    /// typed method on the substrate primitive means every downstream
4653    /// consumer of the Supervisor's per-`:supervisor` static-child-list
4654    /// surface reaches for exactly one typed dispatch — the resolver's
4655    /// accept-set migrates as a unit on any future axis addition.
4656    ///
4657    /// First slice-return (`&[T]`) accessor on any M2 or M3 typed slot
4658    /// — the seed for the same "one typed dispatch on the substrate
4659    /// primitive, thin projections at each consumer" discipline the
4660    /// closed [`crate::LimitsSpec`] / [`BehaviorSpec`] /
4661    /// [`crate::UpgradeFromEntry`] scalar-accessor families each carry
4662    /// on their `Copy` / `Option<Copy>` / `Option<&str>` axes, extended
4663    /// onto the first `Vec`-carry axis on the substrate. The four peer
4664    /// `Vec`-carry axes still unlifted at the time of this seed —
4665    /// [`crate::Placement::clusters`] (`Vec<String>` per-cluster
4666    /// distribution-target list), [`crate::AplicacaoSpec::membros`]
4667    /// (`Vec<Membro>` per-Aplicacao member list),
4668    /// [`crate::AplicacaoSpec::contratos`] (`Vec<WitContract>`
4669    /// per-Aplicacao WIT-typed edge list),
4670    /// [`crate::UpgradeFromEntry::instructions`]
4671    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
4672    /// — inherit this accessor's discipline as future compounding runs
4673    /// migrate their consumers onto the shared slice-return shape.
4674    /// Fourth (and final) accessor on the M2 supervisor-slot
4675    /// `SupervisorSpec` type, sibling to the three `Copy`-return
4676    /// [`SupervisorSpec::estrategia`] (eafb619) /
4677    /// [`SupervisorSpec::max_restarts`] (7844f4e) /
4678    /// [`SupervisorSpec::restart_window`] (7e7b32f) accessors — closes
4679    /// the last unlifted per-`:supervisor` field axis (the
4680    /// `Vec<ChildSpec>` static-child-list carrier) so every downstream
4681    /// per-`:supervisor` reader now routes through a typed dispatch on
4682    /// the substrate primitive. Named `children()` to match the storage
4683    /// field's name verbatim and the tatara-lisp author-surface term
4684    /// (`:children`) the field's own docstring already carries; the
4685    /// accessor's identity maps onto the canonical OTP-shape
4686    /// supervision vocabulary the [`SupervisorSpec::children`] field's
4687    /// docstring already reaches for ("Static children ..."). Returns
4688    /// `&[ChildSpec]` (not `&Vec<ChildSpec>`) because every downstream
4689    /// consumer of the child list treats it as a read-only sequence —
4690    /// the slice-view is the narrowest borrow that supports every
4691    /// present + roadmapped consumer (`.is_empty()`, `.iter()`,
4692    /// index, `.len()`) without leaking the backing `Vec`'s
4693    /// grow/push/reserve surface that no consumer of the typed view
4694    /// reaches for (the storage-side `Vec` remains reachable through
4695    /// the `pub children` field for the mutation-carrying
4696    /// `Caixa::supervisor_view` fold-in path in
4697    /// `manifest.rs:supervisor_view`).
4698    #[must_use]
4699    pub const fn children(&self) -> &[ChildSpec] {
4700        self.children.as_slice()
4701    }
4702
4703    /// Validate the supervisor's typed shape — strategy ↔ children
4704    /// invariants, max_restarts > 0, restart_window > 0 when set,
4705    /// per-child non-empty + duplicate-free names.
4706    ///
4707    /// Mirrors the value-shape discipline applied to every other
4708    /// typed slot:
4709    ///
4710    ///   - `Some(Duration::ZERO)` on a Duration-bearing axis is the
4711    ///     same "0 means the opposite of what you think" footgun
4712    ///     closed for `:politicas :timeout` (Envoy interprets a zero
4713    ///     timeout as `infinite`), `:politicas :circuit-breaker
4714    ///     :window`, and `:limits :wall-clock`. The
4715    ///     `MaxIntensity / Period` ratio in Erlang/OTP's
4716    ///     `supervisor` requires `Period > 0`; a zero period either
4717    ///     trips on the first failure or never trips depending on
4718    ///     operator interpretation, neither of which is the
4719    ///     author's intent. Omit `:restart-window` to express "no
4720    ///     reset"; carry a positive duration to express the window.
4721    ///   - duplicate `:children` `:caixa` names are the same
4722    ///     graph-node-set / multiset distinction closed for
4723    ///     `:membros` (4bb3f3d), `:placement :clusters` (c7c7799),
4724    ///     and `:entrada :paths` (eb3456d). Two children with the
4725    ///     same `:caixa` materialize as two ComputeUnits with the
4726    ///     same name in the cluster's HelmRelease values, one
4727    ///     silently overwriting the other. Erlang/OTP's
4728    ///     `child_spec.id` is required-unique per supervisor;
4729    ///     pleme-io enforces the same set-not-multiset shape on
4730    ///     `:caixa` (the load-bearing identity in our renderer).
4731    pub fn validate(&self) -> Result<(), SupervisorError> {
4732        // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition
4733        // dispatch and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
4734        // error carrier's `estrategia:` field through the lifted
4735        // [`SupervisorSpec::estrategia`] accessor rather than the raw
4736        // `self.estrategia` field access — the two production consumers
4737        // of the per-`:supervisor` sibling-restart-strategy scalar now
4738        // key off exactly one typed dispatch on the substrate primitive,
4739        // so any future rebrand on the axis (a per-cluster strategy
4740        // override the operator pins through a future `:supervisor
4741        // :estrategia-overrides` slot, a per-tenant strategy-alias table
4742        // the M4 CR materializer resolves per-CR) migrates as a single
4743        // caixa-core edit rather than a coordinated rewrite of the two
4744        // call sites — sibling of the peer M3 [`crate::Placement::estrategia`]
4745        // (921fe1b) four-consumer migration on the per-`:placement`
4746        // distribution-strategy axis.
4747        // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition-
4748        // dispatch's paired `.is_empty()` cross-slot refusal probes
4749        // (the `SimpleOneForOne`-arm
4750        // [`SupervisorError::SimpleOneForOneWithStaticChildren`] refusal
4751        // and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
4752        // refusal) through the lifted [`SupervisorSpec::children`]
4753        // slice-return accessor rather than the raw `self.children`
4754        // field access — the two paired production consumers of the
4755        // per-`:supervisor` static-child-list scalar-shape now key off
4756        // exactly one typed dispatch on the substrate primitive, so any
4757        // future rebrand on the axis (a per-cluster child-set overlay
4758        // the operator pins through a future `:supervisor
4759        // :children-overrides` slot, a per-tenant child-set-alias table
4760        // the M4 CR materializer resolves per-CR) migrates as a single
4761        // caixa-core edit rather than a coordinated rewrite of the
4762        // paired arms — first slice-return migration on any typed slot,
4763        // seed for the peer per-`:placement :clusters`,
4764        // per-`:membros`, per-`:contratos`, and per-`:upgrade-from
4765        // :instructions` `Vec`-carry axes.
4766        match self.estrategia() {
4767            RestartStrategy::SimpleOneForOne => {
4768                // SimpleOneForOne: children added at runtime. Static
4769                // list must be empty (one shape declared elsewhere).
4770                if !self.children().is_empty() {
4771                    return Err(SupervisorError::SimpleOneForOneWithStaticChildren);
4772                }
4773            }
4774            _ => {
4775                if self.children().is_empty() {
4776                    return Err(SupervisorError::no_children(self.estrategia()));
4777                }
4778            }
4779        }
4780        // Zero-floor + upper-cap bracket on the typed `:max-restarts`
4781        // axis. See [`crate::render::require_positive_bounded_u32`] for
4782        // the ordering discipline (zero-floor arm strictly precedes cap
4783        // arm so `0` surfaces the self-locating `ZeroMaxRestarts`
4784        // diagnostic with its counter-axis remediation directly named,
4785        // not the misleading `0 > SUPERVISOR_MAX_RESTARTS_MAX == false`
4786        // cap-arm miss). Until this bracket landed the top edge ran all
4787        // the way to `u32::MAX` and a struct-literal
4788        // `SupervisorSpec { max_restarts: 100_000, .. }` (or the
4789        // equivalent author-surface `:max-restarts 100000` /
4790        // `:max-restarts 4294967295` typo landing in the slot) silently
4791        // passed validate. The runtime substrate consuming the value
4792        // (Erlang/OTP's `MaxIntensity / Period` ratio, the future
4793        // wasm-operator's per-supervisor restart-intensity counter, the
4794        // M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
4795        // admission webhook) then turned a typed `:max-restarts`
4796        // policy into a no-op supervisor: the escalation threshold is
4797        // structurally so high that no realistic
4798        // restarts-per-`:restart-window` traffic shape can reach it,
4799        // the supervisor never escalates to its parent, and a bad
4800        // child can loop inside the window indefinitely with the
4801        // parent supervisor structurally never receiving the "this
4802        // subtree has exceeded its restart budget" signal the typed
4803        // slot is meant to express. The bracket set is
4804        // `1..=SUPERVISOR_MAX_RESTARTS_MAX`, peer with the
4805        // [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap on
4806        // the sibling `:politicas :circuit-breaker :max-failures` axis:
4807        // both are "trip the next-higher protection layer after N
4808        // events in a rolling window" counters with identical
4809        // degenerate-at-the-high-end shape and now share one canonical
4810        // bracket helper. The bracket precedes the sibling
4811        // `:restart-window` zero-floor / canonical-millisecond arms so
4812        // an over-cap `max_restarts` paired with a structurally invalid
4813        // window surfaces the bracket diagnostic first, mirroring the
4814        // `PolicyBreakerMaxFailuresExceedsCap` / window-axis cross-arm
4815        // ordering on the peer `:politicas :circuit-breaker` slot.
4816        // Route the [`SupervisorSpec::validate`] `:max-restarts` zero-floor +
4817        // upper-cap bracket-gate through the lifted [`SupervisorSpec::max_restarts`]
4818        // accessor rather than the raw `self.max_restarts` field access —
4819        // the one production consumer of the per-`:supervisor`
4820        // restart-budget-count scalar now keys off exactly one typed
4821        // dispatch on the substrate primitive, so any future rebrand on
4822        // the axis (a per-cluster restart-budget override the operator
4823        // pins through a future `:supervisor :max-restarts-overrides`
4824        // slot, a per-tenant restart-budget-alias table the M4 CR
4825        // materializer resolves per-CR) migrates as a single caixa-core
4826        // edit rather than a coordinated rewrite — sibling of the peer M3
4827        // [`crate::CircuitBreaker::max_failures`] (3a74062) migration on
4828        // the per-`:politicas :circuit-breaker :max-failures` axis.
4829        crate::render::require_positive_bounded_u32(
4830            self.max_restarts(),
4831            SUPERVISOR_MAX_RESTARTS_MAX,
4832            || SupervisorError::ZeroMaxRestarts,
4833            SupervisorError::max_restarts_exceeds_cap,
4834        )?;
4835        // Route the [`SupervisorSpec::validate`] `:restart-window`
4836        // zero-floor + integer-millisecond canonical-form + upper-cap
4837        // bracket-gate through the lifted [`SupervisorSpec::restart_window`]
4838        // accessor rather than the raw `self.restart_window` field access —
4839        // the one production consumer of the per-`:supervisor`
4840        // restart-intensity-denominator scalar now keys off exactly one
4841        // typed dispatch on the substrate primitive, so any future rebrand
4842        // on the axis (a per-cluster restart-window override the operator
4843        // pins through a future `:supervisor :restart-window-overrides`
4844        // slot, a per-tenant restart-window-alias table the M4 CR
4845        // materializer resolves per-CR) migrates as a single caixa-core
4846        // edit rather than a coordinated rewrite — sibling of the peer M2
4847        // [`crate::LimitsSpec::wall_clock`] (8cb717b) validate-arm-route
4848        // on the per-`:limits :wall-clock` axis and the peer M3
4849        // [`crate::MeshPolicy::timeout`] (7073d0f) accessor-route on the
4850        // per-`:politicas :timeout` axis.
4851        if let Some(w) = self.restart_window() {
4852            // Zero-floor + integer-millisecond canonical-form +
4853            // upper-cap bracket on the typed `:restart-window` axis.
4854            // See
4855            // [`crate::render::require_positive_canonical_bounded_duration`]
4856            // for the full three-arm ordering discipline (zero-floor
4857            // strictly precedes canonical-form so `Duration::ZERO`
4858            // surfaces the self-locating `RestartWindowZero`
4859            // diagnostic; canonical-form strictly precedes the cap arm
4860            // so a sub-millisecond above-cap value surfaces the more
4861            // fundamental round-trip-shape diagnostic first) and the
4862            // three peer typed-`Duration` sites that share this
4863            // canonical bracket ([`crate::MeshPolicy::timeout`],
4864            // [`crate::CircuitBreaker::window`],
4865            // [`crate::LimitsSpec::wall_clock`]). Every validated
4866            // value lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
4867            // (1ms..=1h), integer-millisecond granularity.
4868            crate::render::require_positive_canonical_bounded_duration(
4869                w,
4870                SUPERVISOR_RESTART_WINDOW_MAX,
4871                || SupervisorError::RestartWindowZero,
4872                SupervisorError::restart_window_not_canonical,
4873                SupervisorError::restart_window_exceeds_cap,
4874            )?;
4875        }
4876        // Route the per-child DNS-1123 / semver-requirement / duplicate-
4877        // detection fan-out loop through the lifted named per-slot gate
4878        // [`SupervisorSpec::validate_children`] rather than an inline
4879        // three-per-child cascade — every future consumer that wants to
4880        // re-check only the `:children` slot's per-entry axes (the M4
4881        // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
4882        // admission webhook re-validating one added/renamed child, the
4883        // future wasm-operator's per-child dynamic-add re-validator on
4884        // the `SimpleOneForOne` runtime-add path once dynamic-children
4885        // graduate to a typed slot, a future partial re-validator on a
4886        // per-`:children`-entry patch) reaches every per-entry axis
4887        // through one dispatch rather than re-inlining the three-arm
4888        // cascade in lockstep with `validate` or paying the peer
4889        // `:estrategia`/`:max-restarts`/`:restart-window` gates to
4890        // reach one entry check. Sibling of the peer M3 mesh-slot
4891        // per-slot gate family (`validate_membros` — the exact peer on
4892        // the M3 side, [`crate::AplicacaoSpec::validate_membros`];
4893        // `validate_contratos` — 906a5c6; `validate_entrada` — 20cd523;
4894        // `validate_placement`; `validate_politicas` routing through
4895        // `MeshPolicy::validate` — f03a154) — the M2 supervisor-slot
4896        // per-slot gate discipline now spans both the M3 mesh-slot
4897        // family and the M2 `:children` per-child-cascade axis on one
4898        // shape: one named per-slot gate per typed per-entry loop.
4899        self.validate_children()?;
4900        Ok(())
4901    }
4902
4903    /// Named per-slot gate on the M2 `:supervisor :children` per-entry
4904    /// axis — folds the per-child DNS-1123 name gate, semver-requirement
4905    /// gate, and duplicate-`:caixa` dedup arm into one call every
4906    /// consumer that wants to re-validate one `:children` entry (or the
4907    /// whole list) against the same accept-set [`SupervisorSpec::validate`]
4908    /// admits reaches through.
4909    ///
4910    /// Peer of the M3 mesh-slot [`crate::AplicacaoSpec::validate_membros`]
4911    /// per-slot gate on the analogous per-entry axis (`:membros`) — same
4912    /// three-per-entry shape (DNS-1123 name + semver-requirement +
4913    /// duplicate-`:caixa` dedup), lifted to one named substrate
4914    /// primitive per slot. The M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
4915    /// materializer's admission webhook re-checking one added or renamed
4916    /// child, the future wasm-operator's per-child dynamic-add
4917    /// re-validator on the `SimpleOneForOne` runtime-add path once
4918    /// dynamic-children graduate to a typed slot, a future partial
4919    /// re-validator on a per-`:children`-entry patch — each reaches the
4920    /// three per-entry axes through this one dispatch rather than
4921    /// re-inlining the three-arm cascade in lockstep with `validate`
4922    /// (the duplication the PRIME DIRECTIVE names as a bug) or paying
4923    /// the peer `:estrategia`/`:max-restarts`/`:restart-window` gates to
4924    /// reach one entry check.
4925    ///
4926    /// Self-contained on `&self` — resolves its own dedup `HashSet`
4927    /// through [`SupervisorSpec::children`] rather than borrowing one
4928    /// threaded down from `validate`, the same posture the peer M3
4929    /// mesh-slot per-slot gates ([`crate::AplicacaoSpec::validate_membros`],
4930    /// [`crate::AplicacaoSpec::validate_contratos`],
4931    /// [`crate::AplicacaoSpec::validate_entrada`],
4932    /// [`crate::AplicacaoSpec::validate_placement`]) each carry, so a
4933    /// consumer that reaches this gate directly (without first calling
4934    /// `validate`) still runs the full per-child cascade — pinned by
4935    /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
4936    /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
4937    /// + `validate_children_is_self_contained_on_children_slot`.
4938    ///
4939    /// The three per-entry arms run in the same canonical order the
4940    /// pre-lift inline cascade encoded (DNS-1123 → semver → dedup), so
4941    /// the diagnostic every author-declared per-`:children` entry surfaces
4942    /// through `validate` is byte-equal to the diagnostic this gate
4943    /// surfaces when called directly — the equivalence-pin pair
4944    /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
4945    /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
4946    /// asserts the two altitudes discriminate the same set on every
4947    /// per-entry-covered input.
4948    pub fn validate_children(&self) -> Result<(), SupervisorError> {
4949        let mut seen = std::collections::HashSet::new();
4950        for child in self.children() {
4951            // Every emitted cluster artifact's `metadata.name` for a
4952            // supervised child derives from this `:children :caixa` value
4953            // verbatim — the rendered `wasm.pleme.io/v1alpha1/ComputeUnit
4954            // .metadata.name` per child, the [`crate::LABEL_PROGRAM`]
4955            // label value on every child's pod identity, and the per-
4956            // child K8s [`Service`][svc] `metadata.name` the future
4957            // wasm-operator (M3) provisions for inter-child supervision
4958            // tree wiring. Each apiserver-side schema on each landing
4959            // site enforces the DNS-1123 label rule on admission; a
4960            // structurally invalid child name (`"Worker"`, `"my_worker"`,
4961            // `"team.worker"`, `"-worker"`, `"worker-"`, the >63-byte
4962            // UUID-shaped mistaken-identity slug) silently passes the
4963            // prior empty-/duplicate-only gate and the failure surfaces
4964            // at `kubectl apply` time as a `metadata.name: Invalid value`
4965            // rejection, far from the source caixa.lisp, with no field
4966            // naming the offending `:children` entry. Lifting the gate
4967            // to caixa-build time mirrors the `:membros :caixa` value-
4968            // shape trajectory (3f9d7a0) and the `:placement :clusters`
4969            // trajectory (6cbb900) onto the third DNS-1123-label-shaped
4970            // identifier axis — the supervisor tree's child names —
4971            // through the lifted
4972            // [`crate::render::require_valid_dns_1123_label`] gate the
4973            // seven peer name axes (`:membros :caixa`, `:placement
4974            // :clusters`, `:placement :affinity`, `:contratos :de`/`:para`,
4975            // `:entrada :para`, `:nome`, `:upgrade-from :module`) each
4976            // route through, so drift between the eight axes' accepted
4977            // DNS-1123-label sets is structurally impossible.
4978            //
4979            // [svc]: https://kubernetes.io/docs/concepts/services-networking/service/
4980            crate::render::require_valid_dns_1123_label(
4981                child.nome(),
4982                || SupervisorError::EmptyChildName,
4983                |reason| SupervisorError::child_caixa_invalid(child.nome(), reason),
4984            )?;
4985            // The author surface for `:children :versao` is the same
4986            // Cargo-shaped semver requirement string `:deps :versao` and
4987            // `:membros :versao` carry — and the lacre pipeline resolves
4988            // all three axes through the same
4989            // [`crate::version::parse_requirement`] entry-point. The
4990            // shared [`crate::render::require_valid_versao_requirement`]
4991            // helper brackets the empty-first + parse cascade both peer
4992            // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
4993            // [`crate::AplicacaoSpec::validate_membros`] on `:membros
4994            // :versao`) route through, so drift between the three axes'
4995            // accepted requirement sets is structurally impossible and
4996            // the parse-side no-op the empty-first arm closes (semver's
4997            // empty parse yields an implicit `*`) lives in exactly one
4998            // predicate. Every `ChildSpec::versao` past validate is
4999            // round-trippable through [`crate::parse_requirement`]
5000            // without re-checking at the resolver layer, and the three
5001            // `:versao` typed surfaces (`:deps`, `:membros`, `:children`)
5002            // are now structurally equivalent by construction.
5003            crate::render::require_valid_versao_requirement(
5004                child.versao_requirement(),
5005                || SupervisorError::empty_child_version(child.nome()),
5006                |reason| {
5007                    SupervisorError::child_versao_invalid(
5008                        child.nome(),
5009                        child.versao_requirement(),
5010                        reason,
5011                    )
5012                },
5013            )?;
5014            crate::render::insert_first_seen(&mut seen, child.nome(), || {
5015                SupervisorError::duplicate_child_caixa(child.nome())
5016            })?;
5017        }
5018        Ok(())
5019    }
5020}
5021
5022/// Cross-slot coherence gate on the supervision tree: no
5023/// `:children :caixa` entry may name the supervisor's own `:nome`.
5024///
5025/// A supervisor that lists itself as a child is a degenerate self-parent
5026/// — the supervision tree is a DAG rooted at the supervisor (OTP child
5027/// specs reference *distinct* child processes; a supervisor is never its
5028/// own child), and the wasm-operator's hierarchical reconciliation would
5029/// otherwise be handed a node that is its own parent: a one-node cycle it
5030/// either rejects far from the source `caixa.lisp` or recurses on. Because
5031/// every `:nome` is a globally-unique substrate identity (DNS-1123 label +
5032/// lacre closure root), a child whose `:caixa` equals the supervisor's
5033/// `:nome` *is* the supervisor itself, not a coincidentally-named peer.
5034///
5035/// Lives outside [`SupervisorSpec::validate`] because the typed view
5036/// carries the children but not the parent `:nome`; mirrors the
5037/// cross-slot precedence gate `validate_upgrade_from_against_versao`
5038/// (which likewise reads one slot against another at the
5039/// [`crate::layout`] wire-up site) and the mesh self-edge gate
5040/// `AplicacaoSpec`'s `ContratoSelfLoop` — the same "an edge from a graph
5041/// node to itself is structurally not a tree/mesh edge" discipline, here
5042/// on the supervision-tree axis.
5043pub fn validate_no_self_supervision(
5044    children: &[ChildSpec],
5045    parent_nome: &str,
5046) -> Result<(), SupervisorError> {
5047    for child in children {
5048        if child.nome() == parent_nome {
5049            return Err(SupervisorError::child_supervises_self(parent_nome));
5050        }
5051    }
5052    Ok(())
5053}
5054
5055#[derive(Debug, Error, PartialEq, Eq)]
5056pub enum SupervisorError {
5057    #[error("supervisor :estrategia {estrategia:?} requires at least one :children entry")]
5058    NoChildren { estrategia: RestartStrategy },
5059    #[error(
5060        "SimpleOneForOne supervisors must declare zero static children (children spawn dynamically)"
5061    )]
5062    SimpleOneForOneWithStaticChildren,
5063    #[error(":max-restarts must be > 0")]
5064    ZeroMaxRestarts,
5065    #[error(
5066        ":supervisor :max-restarts ({max_restarts}) exceeds the supervisor-policy ceiling \
5067         (SUPERVISOR_MAX_RESTARTS_MAX = 1000) — a value above this cap turns the typed \
5068         restart-intensity policy into a no-op supervisor: the escalation threshold is \
5069         structurally so high that no realistic restarts-per-:restart-window traffic shape \
5070         can reach it, so the supervisor never escalates to its parent and a bad child can \
5071         loop inside the window indefinitely. Every typed-slot consumer (Erlang/OTP's \
5072         MaxIntensity/Period ratio, the future wasm-operator's per-supervisor \
5073         restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
5074         materializer's admission webhook) emits a `:max-restarts` declaration that is \
5075         structurally never reached. Pin a value in 1..=1000 (Erlang/OTP / Elixir / Riak \
5076         Core / RabbitMQ production playbooks recommend 3..=100; the OTP `supervisor` \
5077         callback module's `MaxR = 1` minimal-restart default sits at the bottom of the \
5078         band) or restructure the supervision tree (split the flaky child into its own \
5079         sub-supervisor with a tighter budget) if you need a higher restart tolerance."
5080    )]
5081    MaxRestartsExceedsCap { max_restarts: u32 },
5082    #[error(
5083        ":restart-window must be > 0 when set — Erlang/OTP's MaxIntensity/Period \
5084         requires Period > 0; a zero window either trips on the first failure or \
5085         never trips depending on operator interpretation. Omit :restart-window to \
5086         express `never reset`; carry a positive duration to express the window."
5087    )]
5088    RestartWindowZero,
5089    #[error(
5090        ":supervisor :restart-window ({window:?}) carries a sub-millisecond residue the shared `duration_codec` cannot round-trip — \
5091         the codec truncates to `as_millis()` before picking the canonical unit, so a value with `subsec_nanos() % 1_000_000 != 0` either \
5092         truncates on first serialize (e.g. `Duration::from_micros(1500)` → \"1ms\" → `Duration::from_millis(1)` ≠ original) or renders \
5093         as \"0s\" the `RestartWindowZero` arm then rejects on re-validate. Pin an integer-millisecond magnitude in the canonical authoring form \
5094         (`<integer><unit>` for unit ∈ {{ms, s, m, h}}, e.g. `\"500ms\"`, `\"30s\"`, `\"2m\"`, `\"1h\"`) or omit the field for `never reset`"
5095    )]
5096    RestartWindowNotCanonical { window: Duration },
5097    #[error(
5098        ":supervisor :restart-window ({window:?}) exceeds the supervisor-policy ceiling \
5099         (SUPERVISOR_RESTART_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
5100         per-supervisor rolling-window restart-intensity counter into a lifetime counter: the \
5101         failure-counting window is structurally so long that transient restarts are never \
5102         forgotten, the MaxIntensity/Period ratio degenerates from `trip the parent supervisor \
5103         when the child has exceeded its restart budget within the recent window` to `trip the \
5104         parent when the child has exceeded its restart budget over its lifetime`, and the \
5105         supervisor's reset semantic never reaches the child — every typed-slot consumer \
5106         (Erlang/OTP's MaxIntensity/Period reconciler, the future wasm-operator's \
5107         per-supervisor restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
5108         materializer's admission webhook, the caixa-operator's hierarchical reconciliation \
5109         scheduler) emits a `:restart-window` declaration that is structurally a no-op rolling \
5110         window. Pin a value in 1ms..=1h (Learn You Some Erlang's `{{intensity, 5, 60}}` \
5111         worker-supervisor `Period = 60s` default, Elixir's `Supervisor` `max_seconds: 5` \
5112         default, OTP's `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's \
5113         `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default — every Erlang/OTP \
5114         / Elixir production playbook sits in the 5s..=300s band; the longest documented \
5115         per-supervisor restart-window any pleme-io substrate playbook recommends maxes at \
5116         ~30m) or omit :restart-window to express `never reset` (the supervisor's restart \
5117         budget then becomes a strict lifetime counter by design, not a degenerate one — the \
5118         author surfaces the lifetime-counter semantic explicitly at the slot, rather than \
5119         hiding it behind a rolling-window declaration the cap arm rejects)"
5120    )]
5121    RestartWindowExceedsCap { window: Duration },
5122    #[error("child entry has empty :caixa name")]
5123    EmptyChildName,
5124    #[error(
5125        "child :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
5126         (the K8s apiserver enforces this rule on every `metadata.name` / Service \
5127         name / label value the child name lands in — the per-child \
5128         `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name`, the `LABEL_PROGRAM` \
5129         label value, and the future wasm-operator per-child Service `metadata.name` \
5130         — each apiserver-side schema rejects names that don't match; use a \
5131         lowercase alphanumeric + hyphen identifier like `\"worker\"` or `\"cache-v2\"`)"
5132    )]
5133    ChildCaixaInvalid { caixa: String, reason: String },
5134    #[error("child {caixa:?} has empty :versao constraint")]
5135    EmptyChildVersion { caixa: String },
5136    #[error(
5137        "child {caixa:?} :versao {versao:?} is not a valid semver requirement: \
5138         {reason} (use Cargo-shaped forms like `\"^0.1\"`, `\"~0.1.2\"`, \
5139         `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` and \
5140         `:membros :versao` carry; the lacre pipeline resolves all three \
5141         through the same parser)"
5142    )]
5143    ChildVersaoInvalid {
5144        caixa: String,
5145        versao: String,
5146        reason: String,
5147    },
5148    #[error(
5149        "child {caixa:?} appears more than once (Erlang/OTP requires unique \
5150         child_spec.id per supervisor; duplicate children materialize as duplicate \
5151         ComputeUnits in the rendered chart, one silently overwriting the other)"
5152    )]
5153    DuplicateChildCaixa { caixa: String },
5154    #[error(
5155        "supervisor {caixa:?} lists itself as a :children entry — a supervisor is \
5156         never its own child (the supervision tree is a DAG rooted at the supervisor; \
5157         OTP child specs reference distinct child processes). Since every :nome is a \
5158         globally-unique substrate identity, a child naming the supervisor's own :nome \
5159         is a one-node reconciliation cycle, not a coincidentally-named peer; drop the \
5160         self-referential :children entry or rename it to the actual child caixa."
5161    )]
5162    ChildSupervisesSelf { caixa: String },
5163}
5164
5165// Fold the three `SupervisorError::<Variant> { caixa: <&str>.to_string() }`
5166// caixa-only struct-variant wire-up sites at [`SupervisorSpec::validate_children`]
5167// and [`validate_no_self_supervision`] onto one substrate primitive per
5168// typed variant — the sibling on `SupervisorError` of the four uniform-shape
5169// `LayoutError`-envelope constructor families the peer
5170// [`crate::layout::layout_violation_ctors!`] macro closed (131ca0d, 16
5171// variants on `{ caixa, issue }`), the [`crate::layout::layout_slot_kind_ctors!`]
5172// macro closed (0419438, 4 variants on `{ caixa, kind, slots }`), the
5173// [`crate::LayoutError::missing_entry`] one-variant ctor closed (1b09f9d,
5174// on `{ kind, path }`), and the [`crate::layout::layout_nome_only_ctors!`]
5175// macro closed (3fe3dd7, 6 variants on `<Variant>(String)`), plus the
5176// [`crate::AplicacaoError::entrada_host_invalid`] one-variant ctor
5177// (17dd504, `{ host, reason }`), the [`crate::aplicacao::contrato_target_ctors!`]
5178// macro (14b81d5, 2 variants on `{ de, para, wit, expected }`), and the
5179// [`crate::aplicacao::contrato_empty_pair_ctors!`] macro (8580068, 4
5180// variants on `{ de, para }`) already at that discipline on the peer
5181// `AplicacaoError` envelopes.
5182//
5183// Each of the three wire-up sites on this shape (`EmptyChildVersion` at
5184// the per-`:children` semver-requirement empty-first arm, `DuplicateChildCaixa`
5185// at the per-`:children` dedup arm, `ChildSupervisesSelf` at the cross-slot
5186// self-supervision arm) opened the identical
5187// `SupervisorError::<Variant> { caixa: <&str>.to_string() }` struct-literal —
5188// the exact "same block re-inlined at every consumer" shape the PRIME
5189// DIRECTIVE names as a bug, on the same altitude the peer `LayoutError` /
5190// `AplicacaoError` families each closed on their sibling envelopes. The
5191// three variants share one `{ caixa: String }` shape, so the fold routes
5192// each wire-up site through one dispatch per typed variant.
5193//
5194// The macro below generates one static constructor per variant of shape
5195// `fn <slot>(caixa: &str) -> SupervisorError`, so every wire-up site
5196// collapses onto one dispatch:
5197// `SupervisorError::<slot>(<&str>)`, byte-equal to the pre-lift
5198// struct-literal on the same `&str` fixture. The uniform one-field
5199// construction (`caixa: caixa.to_string()`) is spelled once — inside the
5200// macro — rather than at every wire-up site. Every constructor is
5201// `#[must_use]` so a caller who mistakenly discards the constructed error
5202// trips a compile warning at the wire-up site.
5203//
5204// Every future consumer that wants to construct one of these three
5205// variants outside `SupervisorSpec::validate_children` /
5206// `validate_no_self_supervision` — a deferred
5207// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
5208// webhook re-checking one added/renamed child, a future
5209// `feira validate --supervisor` per-caixa admission verb, a per-child
5210// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path
5211// once dynamic-children graduate to a typed slot, a per-Supervisor
5212// overlay resolver rejecting a duplicate/self-supervising child against
5213// a cluster-local snapshot — now reaches each variant through one call
5214// rather than re-inlining the three-line struct-literal in lockstep
5215// with the three in-crate wire-up sites.
5216macro_rules! supervisor_caixa_only_ctors {
5217    ($($ctor:ident => $variant:ident),* $(,)?) => {
5218        impl SupervisorError {
5219            $(
5220                #[doc = concat!(
5221                    "Construct a [`SupervisorError::",
5222                    stringify!($variant),
5223                    "`] naming the offending `:children :caixa` (or ",
5224                    "supervisor `:nome`, on the self-supervision arm). ",
5225                    "Folds the uniform `Self::",
5226                    stringify!($variant),
5227                    " { caixa: caixa.to_string() }` one-field ",
5228                    "struct-literal onto one substrate primitive so ",
5229                    "every [`SupervisorSpec::validate_children`] / ",
5230                    "[`validate_no_self_supervision`] wire-up on this ",
5231                    "variant reads through one dispatch rather than the ",
5232                    "pre-lift open-coded struct-literal block."
5233                )]
5234                #[must_use]
5235                pub fn $ctor(caixa: &str) -> Self {
5236                    Self::$variant { caixa: caixa.to_string() }
5237                }
5238            )*
5239        }
5240    };
5241}
5242
5243supervisor_caixa_only_ctors! {
5244    empty_child_version => EmptyChildVersion,
5245    duplicate_child_caixa => DuplicateChildCaixa,
5246    child_supervises_self => ChildSupervisesSelf,
5247}
5248
5249// Fold the two `SupervisorError::{ChildCaixaInvalid, ChildVersaoInvalid}`
5250// struct-variant wire-up sites at [`SupervisorSpec::validate_children`] onto
5251// one substrate primitive per typed variant — the M2 supervisor-side siblings
5252// of the peer [`crate::AplicacaoError::membro_caixa_invalid`] two-slot ctor
5253// already lifted through the sibling
5254// [`crate::aplicacao::aplicacao_field_reason_ctors!`] macro (981060b) on the
5255// peer `AplicacaoError { caixa: String, reason: String }` envelope. The
5256// `ChildCaixaInvalid` variant carries the same `{ <name>: String, reason:
5257// String }` two-slot shape the peer seven-variant
5258// [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold closed on the
5259// `AplicacaoError` envelope (`MembroCaixaInvalid`, `EntradaParaInvalid`,
5260// `EntradaHostInvalid`, `EntradaPathInvalid`, `PlacementClusterInvalid`,
5261// `PlacementAffinityInvalid`, `ShardKeyInvalid`); the `ChildVersaoInvalid`
5262// variant carries the `{ caixa: String, versao: String, reason: String }`
5263// three-slot shape the sibling `AplicacaoError::MembroVersaoInvalid` axis
5264// carries on the same `:versao` value-shape.
5265//
5266// Each of the two wire-up sites opened the same closure-shaped
5267// `|reason| SupervisorError::<Variant> { caixa: child.nome().to_string(),
5268// [versao: child.versao_requirement().to_string(),] reason }` block inside
5269// the paired [`crate::render::require_valid_dns_1123_label`] and
5270// [`crate::render::require_valid_versao_requirement`] callbacks — the exact
5271// "same block re-inlined at every consumer" shape the PRIME DIRECTIVE names
5272// as a bug, on the same altitude the peer `AplicacaoError` /
5273// `SupervisorError` / `LayoutError` / `DepError` / `LimitsError` ctor
5274// families already closed on their sibling envelopes.
5275//
5276// The two `#[must_use]` inherent constructors below fold each wire-up onto
5277// one dispatch: `SupervisorError::child_caixa_invalid(<name>, <reason>)`
5278// and `SupervisorError::child_versao_invalid(<name>, <versao>, <reason>)`,
5279// byte-equal to the pre-lift struct-literal on the same scalar fixtures.
5280// The uniform per-field `.to_string()` / `.into()` construction is spelled
5281// once — inside each ctor body — rather than at every wire-up site. The
5282// `reason: impl Into<String>` bound accepts both `&str` literals and
5283// `format!(…)` outputs verbatim so no wire-up site changes its per-arm
5284// diagnostic shape at the lift, matching the peer
5285// [`aplicacao_field_reason_ctors!`] and
5286// [`crate::aplicacao::contrato_pair_value_reason_ctors!`] bounds on the
5287// sibling envelopes.
5288//
5289// Every future consumer that wants to construct one of these two variants
5290// outside `SupervisorSpec::validate_children` — a deferred
5291// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook
5292// re-checking one added/renamed child's `:caixa` or `:versao`, a future
5293// `feira validate --supervisor` per-caixa admission verb, a per-child
5294// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path once
5295// dynamic-children graduate to a typed slot, a per-Supervisor overlay
5296// resolver rejecting a shape-invalid child `:caixa`/`:versao` against a
5297// cluster-local snapshot — now reaches each variant through one call rather
5298// than re-inlining the per-shape struct-literal block in lockstep with the
5299// two in-crate wire-up sites.
5300impl SupervisorError {
5301    /// Construct a [`SupervisorError::ChildCaixaInvalid`] naming the
5302    /// offending `:children :caixa` value under the given `reason`. Folds
5303    /// the uniform `Self::ChildCaixaInvalid { caixa: caixa.to_string(),
5304    /// reason: reason.into() }` two-slot struct-literal onto one substrate
5305    /// primitive so every wire-up on this variant reads through one
5306    /// dispatch, matching the peer
5307    /// [`crate::AplicacaoError::membro_caixa_invalid`] ctor's shape on the
5308    /// sibling `AplicacaoError { caixa: String, reason: String }`
5309    /// envelope. `reason` accepts both `&str` literals and `format!(…)`
5310    /// outputs through the `impl Into<String>` bound.
5311    #[must_use]
5312    pub fn child_caixa_invalid(caixa: &str, reason: impl Into<String>) -> Self {
5313        Self::ChildCaixaInvalid {
5314            caixa: caixa.to_string(),
5315            reason: reason.into(),
5316        }
5317    }
5318
5319    /// Construct a [`SupervisorError::ChildVersaoInvalid`] naming the
5320    /// offending `:children :caixa` and its `:versao` requirement under
5321    /// the given `reason`. Folds the uniform `Self::ChildVersaoInvalid {
5322    /// caixa: caixa.to_string(), versao: versao.to_string(), reason:
5323    /// reason.into() }` three-slot struct-literal onto one substrate
5324    /// primitive so every wire-up on this variant reads through one
5325    /// dispatch, matching the sibling `AplicacaoError::MembroVersaoInvalid
5326    /// { caixa, versao, reason }` three-slot axis on the peer
5327    /// `AplicacaoError` envelope. `reason` accepts both `&str` literals
5328    /// and `format!(…)` outputs through the `impl Into<String>` bound.
5329    #[must_use]
5330    pub fn child_versao_invalid(caixa: &str, versao: &str, reason: impl Into<String>) -> Self {
5331        Self::ChildVersaoInvalid {
5332            caixa: caixa.to_string(),
5333            versao: versao.to_string(),
5334            reason: reason.into(),
5335        }
5336    }
5337}
5338
5339// Fold the four `SupervisorError::<Variant> { <field>: <Copy> }` one-field
5340// Copy-scalar struct-variant wire-up sites at [`SupervisorSpec::validate`]'s
5341// three bracket-arms — one struct-literal at the `:children`-empty
5342// non-`SimpleOneForOne` refusal cascade (`NoChildren { estrategia }`) plus
5343// three `impl FnOnce(<ty>) -> SupervisorError` bracket-closures at the
5344// [`crate::render::require_positive_bounded_u32`] `:max-restarts` cap arm
5345// (`MaxRestartsExceedsCap { max_restarts }`) and the paired
5346// [`crate::render::require_positive_canonical_bounded_duration`]
5347// `:restart-window` canonical-form + cap arms (`RestartWindowNotCanonical
5348// { window }`, `RestartWindowExceedsCap { window }`) — onto one substrate
5349// primitive per typed variant, matching the sibling
5350// [`crate::aplicacao::aplicacao_policy_scalar_ctors!`] macro (7ef425e, 8
5351// variants on the same `{ <field>: Duration | u32 }` shape) at that
5352// discipline on the peer `AplicacaoError` envelope's per-`:politicas`
5353// scalar axis. Every variant is a one-field `Copy`-pass-through struct-
5354// literal — `RestartStrategy | u32 | Duration` — so the fold routes each
5355// wire-up site through one dispatch per typed variant without a runtime-
5356// work delta.
5357//
5358// Each of the four wire-up sites opened the identical
5359// `SupervisorError::<Variant> { <field>: <val> }` struct-literal — the
5360// exact "same block re-inlined at every consumer" shape the PRIME
5361// DIRECTIVE names as a bug, on the same altitude the peer
5362// `aplicacao_policy_scalar_ctors!` fold closed on the sibling
5363// `AplicacaoError` envelope's per-`:politicas` per-axis cap / canonical-
5364// form arms. The four variants share one `{ <field>: <Copy> }` shape, so
5365// the fold routes each wire-up site through one dispatch per typed
5366// variant.
5367//
5368// The macro below generates one static constructor per variant of shape
5369// `const fn <ctor>(<field>: <ty>) -> SupervisorError`, so every wire-up
5370// site collapses onto one dispatch: `SupervisorError::<ctor>(<val>)`,
5371// byte-equal to the pre-lift struct-literal on the same `Copy`-`<ty>`
5372// fixture — as a direct call at the [`SupervisorSpec::validate`]
5373// `:children`-empty refusal, or as a bare function pointer in the
5374// `impl FnOnce(<ty>) -> SupervisorError` bracket-closure slot every
5375// [`crate::render::require_positive_bounded_u32`] /
5376// [`crate::render::require_positive_canonical_bounded_duration`] gate
5377// carries — rather than the pre-lift open-coded one-line closure over
5378// the same one-field struct-literal. `const fn` preserves the `Copy`-
5379// pass-through's zero-runtime-work property verbatim. Every constructor
5380// is `#[must_use]` so a caller who mistakenly discards the constructed
5381// error trips a compile warning at the wire-up site.
5382//
5383// Every future consumer that wants to construct one of these four
5384// variants outside `SupervisorSpec::validate` — a deferred
5385// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
5386// webhook re-checking one edited `:estrategia` / `:max-restarts` /
5387// `:restart-window` slot against the cap + canonical-form cascade, a
5388// future `feira validate --supervisor` per-caixa admission verb re-
5389// running the shape gates on demand, a per-Supervisor overlay resolver
5390// rejecting an author-supplied slot against a cluster-local snapshot —
5391// now reaches each variant through one call rather than re-inlining the
5392// per-shape struct-literal block in lockstep with the four in-crate
5393// wire-up sites.
5394macro_rules! supervisor_scalar_ctors {
5395    ($($ctor:ident => $variant:ident { $field:ident: $ty:ty }),* $(,)?) => {
5396        impl SupervisorError {
5397            $(
5398                #[doc = concat!(
5399                    "Construct a [`SupervisorError::",
5400                    stringify!($variant),
5401                    "`] naming the offending per-`:supervisor` `",
5402                    stringify!($field),
5403                    "` scalar. Folds the uniform `Self::",
5404                    stringify!($variant),
5405                    " { ",
5406                    stringify!($field),
5407                    " }` one-field `Copy`-pass-through struct-literal onto ",
5408                    "one substrate primitive so every per-axis wire-up on ",
5409                    "this variant reads through one dispatch — as a direct ",
5410                    "call (`SupervisorError::",
5411                    stringify!($ctor),
5412                    "(<val>)`, byte-equal to the pre-lift struct-literal on ",
5413                    "the same `Copy`-`",
5414                    stringify!($ty),
5415                    "` fixture) or as a bare function pointer in the ",
5416                    "`impl FnOnce(",
5417                    stringify!($ty),
5418                    ") -> SupervisorError` bracket-closure slot every ",
5419                    "`crate::render::require_positive_bounded_*` / ",
5420                    "`crate::render::require_positive_canonical_bounded_*` ",
5421                    "gate carries — rather than the pre-lift open-coded ",
5422                    "one-line closure over the same one-field struct-",
5423                    "literal. `const fn` preserves the `Copy`-pass-through's ",
5424                    "zero-runtime-work property verbatim."
5425                )]
5426                #[must_use]
5427                pub const fn $ctor($field: $ty) -> Self {
5428                    Self::$variant { $field }
5429                }
5430            )*
5431        }
5432    };
5433}
5434
5435supervisor_scalar_ctors! {
5436    no_children => NoChildren { estrategia: RestartStrategy },
5437    max_restarts_exceeds_cap => MaxRestartsExceedsCap { max_restarts: u32 },
5438    restart_window_not_canonical => RestartWindowNotCanonical { window: Duration },
5439    restart_window_exceeds_cap => RestartWindowExceedsCap { window: Duration },
5440}
5441
5442/// Shared duration string codec for the typed slots that take a
5443/// duration (`restart_window`, `MeshPolicy::timeout`,
5444/// `CircuitBreaker::window`, …). Public so [`crate::aplicacao`] can
5445/// reuse it without duplicating the parser.
5446pub mod duration_codec {
5447    use super::Duration;
5448    use serde::{Deserializer, Serializer};
5449
5450    pub fn serialize<S: Serializer>(v: &Option<Duration>, s: S) -> Result<S::Ok, S::Error> {
5451        // Route through the canonical [`crate::render::serialize_option_via_str`]
5452        // — the substrate-side single-owner primitive for the forward
5453        // arm of the typed-magnitude codec family. See its docstring
5454        // for the full sibling roster.
5455        crate::render::serialize_option_via_str(v, s, render)
5456    }
5457
5458    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Duration>, D::Error> {
5459        // Route through the canonical [`crate::render::deserialize_option_via_str`]
5460        // — the substrate-side single-owner primitive for the reverse
5461        // arm of the typed-magnitude codec family. See its docstring
5462        // for the full sibling roster.
5463        crate::render::deserialize_option_via_str(d, parse)
5464    }
5465
5466    pub(crate) fn parse(s: &str) -> Result<Duration, String> {
5467        // Paired whitespace-rejection arm — same canonical-form
5468        // render-determinism discipline as the peer
5469        // `limits::parse_byte_size` / `limits::parse_duration` /
5470        // `limits::parse_millicores` /
5471        // `aplicacao::rate_limit_codec::parse` sites: the ASCII
5472        // byte-scan closes the WhatWG-conformant whitespace bytes
5473        // (`0x20`, `0x09`, `0x0A`, `0x0C`, `0x0D`), the non-ASCII
5474        // `char::is_whitespace` scan closes the strictly-complementary
5475        // Unicode `White_Space` class (NBSP `\u{00A0}`, LINE SEPARATOR
5476        // `\u{2028}`, EM-SPACE `\u{2003}`, and the peer typography
5477        // codepoints) that `str::trim` at parse entry silently strips.
5478        // Either drift class would round-trip through `render` to a
5479        // *different* canonical form on next emit — breaking the
5480        // THEORY.md Part V render-determinism contract on three typed-
5481        // duration slots at once (`:supervisor :restart-window`,
5482        // `:politicas :timeout`, `:politicas :circuit-breaker :window`)
5483        // via the shared codec.
5484        //
5485        // Routed through the lifted [`crate::render::reject_whitespace`]
5486        // primitive — the substrate-side single-owner paired-arm gate
5487        // every typed-magnitude codec in caixa-core shares.
5488        crate::render::reject_whitespace::<String, _, _>(
5489            s,
5490            |b| {
5491                format!(
5492                    "duration: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
5493                 authoring form for the typed duration slots routed through this shared codec \
5494                 (`:supervisor :restart-window`, `:politicas :timeout`, \
5495                 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
5496                 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no whitespace bytes \
5497                 anywhere. A whitespace-carrying shape (`\" 30s\"`, `\"30s \"`, `\"30 s\"`, \
5498                 `\"\\t30s\"`, `\"30s\\n\"`) round-trips through `render` to a *different* \
5499                 canonical form (`\"30s\"`) on first serialize — breaking the THEORY.md \
5500                 Part V render-determinism contract every typed slot carries. Strip every \
5501                 whitespace byte (write `\"30s\"` verbatim)"
5502                )
5503            },
5504            |ch| {
5505                format!(
5506                    "duration: value {s:?} contains non-ASCII Unicode whitespace character \
5507                 {ch:?} (U+{cp:04X}) — the canonical authoring form for the typed \
5508                 duration slots routed through this shared codec (`:supervisor \
5509                 :restart-window`, `:politicas :timeout`, `:politicas :circuit-breaker \
5510                 :window`) is `<integer><unit>` (e.g. `\"30s\"`, `\"500ms\"`, `\"2m\"`, \
5511                 `\"1h\"`) with no whitespace characters anywhere (ASCII or Unicode). A \
5512                 non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}30s\"`, \
5513                 `\"30s\\u{{2028}}\"`, `\"30\\u{{2003}}s\"`) survives the ASCII byte-scan \
5514                 but `str::trim` (which uses `char::is_whitespace` — the Unicode \
5515                 `White_Space` property, strictly wider than the ASCII byte set) silently \
5516                 strips it at parse entry, and the value round-trips through `render` to \
5517                 a *different* canonical form (`\"30s\"`) on first serialize — breaking \
5518                 the THEORY.md Part V render-determinism contract every typed slot \
5519                 carries. Strip every non-ASCII whitespace character (write `\"30s\"` \
5520                 verbatim with only ASCII bytes)",
5521                    cp = ch as u32
5522                )
5523            },
5524        )?;
5525        let s = s.trim();
5526        // Routed through the lifted
5527        // [`crate::render::split_magnitude_and_alpha_unit`] primitive —
5528        // the single-owner split every ASCII-alphabetic-unit typed-
5529        // magnitude codec in caixa-core (`limits::parse_byte_size` /
5530        // `limits::parse_duration` / this shared duration codec) shares.
5531        // See its docstring for the full sibling roster on the same
5532        // primitive altitude.
5533        let (num_part, unit) = crate::render::split_magnitude_and_alpha_unit(s);
5534        let num_trim = num_part.trim();
5535        // The canonical authoring form for every typed slot routed
5536        // through this shared codec — `:supervisor :restart-window`,
5537        // `:politicas :timeout`, `:politicas :circuit-breaker :window`
5538        // — is `<integer><unit>`. Every magnitude [`render`] emits is a
5539        // non-negative integer with no decimal point and no leading
5540        // sign, so the parser's accepted set must match for
5541        // serialize/deserialize to round-trip without canonical-form
5542        // drift. Until this gate landed the parser accepted any
5543        // `f64`-shaped magnitude (`"1.5s"` → 1500ms, `"1.0s"` → 1s,
5544        // `"0.5m"` → 30s, `"+30s"` → 30s) and serde silently round-
5545        // tripped the value to a *different* canonical string on the
5546        // next emit (`"1.5s"` → 1500ms → `"1500ms"`, `"1.0s"` → 1s →
5547        // `"1s"`, `"0.5m"` → 30s → `"30s"`, `"+30s"` → 30s → `"30s"`)
5548        // — breaking the THEORY.md Part V render-determinism contract
5549        // on three typed slots at once. Same canonical-form discipline
5550        // `crate::limits::parse_duration` (818dd38, the immediate
5551        // predecessor on the peer `:limits :wall-clock` codec) applies;
5552        // this gate lifts the discipline onto the shared codec that
5553        // backs the remaining three typed-duration slots in caixa-core.
5554        //
5555        // Strict canonical form: every byte of the magnitude is an
5556        // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
5557        // inputs the gate distinguishes "non-canonical-but-numeric"
5558        // (parses as f64 or i64 — surfaced with a self-locating
5559        // diagnostic naming the canonical authoring form, the
5560        // round-trip drift each rejected shape would produce on first
5561        // serialize, and the canonical-form remediation) from
5562        // "garbage" (parses as neither — surfaced with the existing
5563        // narrower "bad duration magnitude" wording so its diagnostic
5564        // shape remains stable for the parser-shape footgun case).
5565        // The pre-existing `num < 0.0` arm is now unreachable — the
5566        // digit-only gate strictly precedes magnitude parsing, and a
5567        // leading `-` is not an ASCII digit, so `"-30s"` lands on the
5568        // non-canonical-but-numeric branch with the `-30` named
5569        // verbatim in the diagnostic rather than the prior
5570        // value-laundered "negative duration in \"-30s\"" wording.
5571        //
5572        // Routed through the lifted
5573        // [`crate::render::is_digit_only_magnitude`] predicate — the
5574        // same source of truth the four peer typed-magnitude codec
5575        // sites share.
5576        let digit_only = crate::render::is_digit_only_magnitude(num_trim);
5577        if !digit_only {
5578            let numeric = num_trim.parse::<f64>().is_ok() || num_trim.parse::<i64>().is_ok();
5579            if numeric {
5580                return Err(format!(
5581                    "duration: magnitude {num_trim:?} is not a non-negative integer — the \
5582                     canonical authoring form for the typed duration slots routed through \
5583                     this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
5584                     `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
5585                     `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no decimal point and \
5586                     no leading `+` / `-` sign. A fractional / decimal-shaped magnitude \
5587                     (`\"1.5s\"`, `\"1.0s\"`, `\"0.5m\"`, `\"+30s\"`, `\"-30s\"`) round-trips \
5588                     through `render` to a *different* canonical form (`\"1500ms\"`, `\"1s\"`, \
5589                     `\"30s\"`, `\"30s\"`, `\"30s\"`) on first serialize — breaking the \
5590                     THEORY.md Part V render-determinism contract every typed slot carries. \
5591                     Pick an integer magnitude in the unit that divides cleanly (write \
5592                     `\"1500ms\"` instead of `\"1.5s\"`; `\"30s\"` instead of `\"0.5m\"`)"
5593                ));
5594            }
5595            return Err(format!("bad duration magnitude in {s:?}"));
5596        }
5597        // Leading-zero arm — peer with the `rate_limit_codec` leading-
5598        // zero arm (4f46830) on the same canonical-form render-
5599        // determinism axis. The digit-only gate accepts `"030s"`,
5600        // `"00s"`, `"01h"`, `"0500ms"` as `u64::from_str` parses them
5601        // losslessly (= 30, 0, 1, 500), but `render` emits the leading-
5602        // zero-stripped form (`"30s"`, `"0s"`, `"1h"`, `"500ms"`) — a
5603        // *different* canonical string on the next emit, breaking the
5604        // THEORY.md Part V render-determinism contract the same way
5605        // `"+30s"` did before the leading-`+` arm landed. The single-
5606        // byte magnitude `"0"` (or `"0s"` / `"0ms"`) round-trips
5607        // losslessly through `render` (`render(Duration::ZERO)` emits
5608        // `"0s"`) — the downstream semantic-zero gates (e.g.
5609        // `SupervisorError::ZeroRestartWindow` on
5610        // `:supervisor :restart-window`,
5611        // `AplicacaoError::PolicyTimeoutZero` /
5612        // `PolicyCircuitBreakerWindowZero` on the typed `:politicas`
5613        // duration slots) refuse zero-magnitude authoring at the typed-
5614        // validate layer above, so the single-byte `"0"` stays in the
5615        // accepted set at this codec layer and the diagnostic
5616        // partitioning between canonical-form drift (this arm) and
5617        // semantic-zero (the downstream gates) remains stable.
5618        // Peer with the future leading-zero arms on the two remaining
5619        // typed-magnitude codecs the trajectory acknowledges:
5620        // `limits::parse_duration` backing `:limits :wall-clock`,
5621        // `limits::parse_byte_size` backing `:limits :memory` — each
5622        // carries the same canonical-form-drift class today; this
5623        // gate lands the discipline on the shared duration codec
5624        // first because the `rate_limit_codec` predecessor on the
5625        // same canonical-form-drift axis is the closest peer on the
5626        // trajectory.
5627        //
5628        // Routed through the lifted
5629        // [`crate::render::is_leading_zero_padded_magnitude`]
5630        // predicate — the same source of truth the four peer
5631        // typed-magnitude codec sites share.
5632        if crate::render::is_leading_zero_padded_magnitude(num_trim) {
5633            return Err(format!(
5634                "duration: magnitude {num_trim:?} has a non-canonical leading zero — the \
5635                 canonical authoring form for the typed duration slots routed through \
5636                 this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
5637                 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
5638                 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no leading-zero padding \
5639                 on the magnitude. A leading-zero magnitude (`\"030s\"`, `\"00s\"`, \
5640                 `\"01h\"`, `\"0500ms\"`) round-trips through `render` to a *different* \
5641                 canonical form (`\"30s\"`, `\"0s\"`, `\"1h\"`, `\"500ms\"`) on first \
5642                 serialize — breaking the THEORY.md Part V render-determinism contract \
5643                 every typed slot carries. Strip the leading zeros (write \
5644                 `\"30s\"` instead of `\"030s\"`)"
5645            ));
5646        }
5647        // The digit-only gate guarantees every byte is `[0-9]`, and
5648        // the leading-zero arm above guarantees the magnitude is
5649        // either the single byte `"0"` or starts with `[1-9]`, so
5650        // the only way `u64::from_str` can fail here is overflow (the
5651        // magnitude exceeds `u64::MAX`). Surface that with an
5652        // overflow-shaped wording so the diagnostic names the offending
5653        // magnitude verbatim rather than collapsing onto the
5654        // non-canonical arm. The codec now operates on `u64` end-to-end
5655        // — every accepted magnitude is integer-exact; no f64 mantissa
5656        // drift between author-supplied magnitude and the consumer's
5657        // `Duration` value. Same shape `crate::limits::parse_duration`
5658        // (818dd38) carries on the peer `:limits :wall-clock` axis.
5659        let num: u64 = num_trim.parse::<u64>().map_err(|_| {
5660            format!("bad duration magnitude in {s:?} (digit-only magnitude overflows u64)")
5661        })?;
5662        // Route the `{"ms" | "s" | "" | "m" | "h"} → Duration`
5663        // unit-arm dispatch through the canonical
5664        // [`crate::render::duration_from_integer_magnitude_and_unit`]
5665        // primitive — the substrate-side single-owner unit-dispatch
5666        // table every typed-duration codec in caixa-core routes
5667        // through (peer: `crate::limits::parse_duration` backing
5668        // `:limits :wall-clock`). Every unit conversion is integer-
5669        // exact for an integer magnitude; overflow surfaces via the
5670        // typed `DurationUnitError::Overflow { multiplier }`
5671        // discriminant so this arm reconstructs the pre-lift
5672        // `"duration <num><unit> overflows u64 (magnitude × 60 …)"`
5673        // wording verbatim from `num` / `unit_trim` / the returned
5674        // `multiplier`, and the unknown-unit arm reconstructs the
5675        // pre-lift `"unknown duration unit \"<other>\""` wording from
5676        // the caller-scoped `unit_trim`. Load-bearing pinned by
5677        // `crate::render::tests::duration_from_integer_magnitude_and_unit_matches_pre_lift_unit_dispatch_table`.
5678        let unit_trim = unit.trim();
5679        let dur = crate::render::duration_from_integer_magnitude_and_unit(num, unit_trim).map_err(
5680            |e| match e {
5681                crate::render::DurationUnitError::Overflow { multiplier } => format!(
5682                    "duration {num}{unit_trim} overflows u64 (magnitude × {multiplier} > 2^64-1)"
5683                ),
5684                crate::render::DurationUnitError::UnknownUnit => {
5685                    format!("unknown duration unit {unit_trim:?}")
5686                }
5687            },
5688        )?;
5689        Ok(dur)
5690    }
5691
5692    /// Render a [`Duration`] in the canonical pleme-io duration string
5693    /// form (`"30s"`, `"1m"`, `"1h"`, `"500ms"`). The same form every
5694    /// caixa typed-duration slot serializes to and the same form K8s
5695    /// Gateway API HTTPRoute `timeouts` / `backendRequest` and Cilium
5696    /// EnvoyConfig per-route timeouts both expect (an integer
5697    /// followed by `s`/`m`/`h`/`ms`, no fractional values, no leading
5698    /// `+`). Lifted to `pub` so caixa-side renderers
5699    /// (`caixa-mesh::gateway_routes`'s :politicas :timeout overlay,
5700    /// the future per-:politicas `CiliumClusterwideEnvoyConfig`
5701    /// emitter, the future caixa-otel collector pipeline emitter) can
5702    /// consume the same canonical formatter without re-inlining the
5703    /// magnitude/unit decision tree (and inheriting the same drift
5704    /// footguns: a subtly different `300ms` vs `0.3s` rendering breaks
5705    /// downstream apply-time parsing in non-obvious ways).
5706    pub fn render(d: Duration) -> String {
5707        let total_ms = d.as_millis();
5708        if total_ms == 0 {
5709            return "0s".into();
5710        }
5711        if total_ms.is_multiple_of(3600 * 1000) {
5712            return format!("{}h", total_ms / (3600 * 1000));
5713        }
5714        if total_ms.is_multiple_of(60 * 1000) {
5715            return format!("{}m", total_ms / (60 * 1000));
5716        }
5717        if total_ms.is_multiple_of(1000) {
5718            return format!("{}s", total_ms / 1000);
5719        }
5720        format!("{total_ms}ms")
5721    }
5722
5723    /// True iff `d` round-trips losslessly through [`render`] + [`parse`].
5724    ///
5725    /// [`render`] truncates a `Duration` to `as_millis()` before picking the
5726    /// largest divisor unit, so any sub-millisecond residue
5727    /// (`d.subsec_nanos() % 1_000_000 != 0`) silently breaks the THEORY.md
5728    /// §V.2.7 render-determinism contract:
5729    ///
5730    ///   - `Duration::from_micros(1500)` (= `1_500_000` ns) → `as_millis() == 1`
5731    ///     → renders `"1ms"` → parses back to `Duration::from_millis(1)` =
5732    ///     `1_000_000` ns ≠ original `1_500_000` ns;
5733    ///   - `Duration::from_nanos(1)` (= 1 ns) → `as_millis() == 0` →
5734    ///     renders the literal `"0s"`, which the per-axis zero-floor gate
5735    ///     on every typed-`Duration` slot then rejects on re-validate.
5736    ///
5737    /// Lifted to a `pub` predicate next to the [`render`] / [`parse`] pair so
5738    /// the codec's round-trippable accepted set lives in exactly one place —
5739    /// every typed-`Duration` slot that routes through this shared codec
5740    /// (`SupervisorSpec::restart_window` via [`super::duration_codec`],
5741    /// [`crate::MeshPolicy::timeout`] / [`crate::CircuitBreaker::window`] via
5742    /// `supervisor::duration_codec` + [`super::duration_codec_required`]) and
5743    /// every typed-`Duration` slot whose own codec shares the same
5744    /// `as_millis()`-truncation shape ([`crate::LimitsSpec::wall_clock`] via
5745    /// [`crate::limits`]'s in-module `parse_duration` / `render_duration`
5746    /// pair) calls this predicate from its `validate()` to bracket the
5747    /// accepted set against the codec's accepted set, structurally. Drift
5748    /// between the codec's granularity and any typed slot's accepted set is
5749    /// then a single-source-of-truth edit at this predicate rather than a
5750    /// silent round-trip break the next consumer discovers at apply time.
5751    ///
5752    /// Peer of [`crate::aplicacao::POLICY_RETRIES_MAX`] /
5753    /// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] and the
5754    /// `is_dns_1123_label` / `is_canonical_rate_limit_window` predicate
5755    /// family — same "typed-slot's valid set matches its codec's accepted
5756    /// set, structurally" discipline carried at the codec layer.
5757    #[must_use]
5758    pub fn is_integer_millisecond_duration(d: Duration) -> bool {
5759        d.subsec_nanos().is_multiple_of(1_000_000)
5760    }
5761}
5762
5763/// Required-Duration variant for fields that aren't Option<Duration>.
5764pub mod duration_codec_required {
5765    use super::Duration;
5766    use serde::{Deserialize, Deserializer, Serializer};
5767
5768    pub fn serialize<S: Serializer>(v: &Duration, s: S) -> Result<S::Ok, S::Error> {
5769        s.serialize_str(&super::duration_codec::render(*v))
5770    }
5771
5772    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Duration, D::Error> {
5773        let s = String::deserialize(d)?;
5774        super::duration_codec::parse(&s).map_err(serde::de::Error::custom)
5775    }
5776}
5777
5778#[cfg(test)]
5779mod tests {
5780    use super::*;
5781
5782    fn child(name: &str, ver: &str, restart: RestartPolicy) -> ChildSpec {
5783        ChildSpec {
5784            caixa: name.into(),
5785            versao: ver.into(),
5786            restart,
5787        }
5788    }
5789
5790    #[test]
5791    fn child_spec_string_scalar_accessor_pair_is_const_fn() {
5792        // Fail-before-pass-after pin on [`ChildSpec::nome`] +
5793        // [`ChildSpec::versao_requirement`]'s `const`-eval-surface
5794        // posture. Each accessor projects the per-`:children :caixa`
5795        // / per-`:children :versao` [`String`] storage through the
5796        // `pub const fn` [`String::as_str`] (const-stable since Rust
5797        // 1.87, well within the workspace MSRV) — any future
5798        // accidental downgrade to non-`const` fails the corresponding
5799        // `<name>_via_const_fn` wrapper at caixa-core build time with
5800        // E0015 (`cannot call non-const method`), strictly stronger
5801        // than a runtime `assert!`. Sibling of the peer
5802        // per-M2/M3/universal-axis `String → &str` scalar-accessor
5803        // family pins on the sibling `const`-eval-surface passes
5804        // ([`crate::Caixa::nome`] / [`crate::Caixa::versao`] at the
5805        // top-level manifest, [`crate::CaixaVersion::as_str`] at the
5806        // typed-newtype wrapper, [`crate::aplicacao::Membro::nome`] /
5807        // [`crate::aplicacao::Membro::versao_requirement`] at the M3
5808        // membership axis, [`crate::aplicacao::Entrada::hostname`] /
5809        // [`crate::aplicacao::Entrada::destination`] at the M3
5810        // ingress axis,
5811        // [`crate::upgrade::UpgradeFromEntry::prior_versao`] at the
5812        // M2 upgrade axis, [`crate::dep::Dep::nome`] /
5813        // [`crate::dep::Dep::versao_requirement`] at the dep-graph
5814        // axis, and the per-`:contratos`
5815        // [`crate::aplicacao::WitContract::source`] /
5816        // [`crate::aplicacao::WitContract::destination`] /
5817        // [`crate::aplicacao::WitContract::world_ref`] trio the
5818        // sibling pin at 279823b already anchors).
5819        const fn nome_via_const_fn(c: &ChildSpec) -> &str {
5820            c.nome()
5821        }
5822        const fn versao_via_const_fn(c: &ChildSpec) -> &str {
5823            c.versao_requirement()
5824        }
5825        for (caixa, versao) in [
5826            ("worker-a", "^0.1"),
5827            ("worker-b", "~0.2.3"),
5828            ("collector", "*"),
5829        ] {
5830            let c = child(caixa, versao, RestartPolicy::Permanent);
5831            assert_eq!(nome_via_const_fn(&c), c.nome());
5832            assert_eq!(versao_via_const_fn(&c), c.versao_requirement());
5833            assert_eq!(c.nome(), caixa);
5834            assert_eq!(c.versao_requirement(), versao);
5835        }
5836    }
5837
5838    #[test]
5839    fn supervisor_children_slice_return_accessor_is_const_fn() {
5840        // Fail-before-pass-after pin on [`SupervisorSpec::children`]'s
5841        // `const`-eval-surface posture. The accessor destructures the
5842        // per-`:children` `Vec<ChildSpec>` storage through the
5843        // `pub const fn` [`Vec::as_slice`] (const-stable since Rust
5844        // 1.66, well within the workspace MSRV) — any future
5845        // accidental downgrade to non-`const` fails
5846        // `children_via_const_fn` at caixa-core build time with E0015
5847        // (`cannot call non-const method`), strictly stronger than a
5848        // runtime `assert!`. Sibling of the peer per-M3-mesh-slot
5849        // `Vec → &[T]` slice-return accessor family pin
5850        // [`crate::aplicacao::tests::m3_reference_return_accessor_family_is_const_fn`]
5851        // on the M3 mesh-slot per-`:clusters` / per-`:paths` /
5852        // per-`:membros` / per-`:contratos` slice-return axes, and of
5853        // the peer M2 upgrade-appup axis pin
5854        // [`crate::upgrade::tests::upgrade_from_entry_instructions_slice_return_accessor_is_const_fn`]
5855        // on the per-`:upgrade-from :instructions` slice-return axis.
5856        const fn children_via_const_fn(s: &SupervisorSpec) -> &[ChildSpec] {
5857            s.children()
5858        }
5859        // Sweep both the empty-children (leaf-supervisor with no
5860        // static children — the `SimpleOneForOne` dynamic-child
5861        // arm's canonical shape) and the populated-children
5862        // (`OneForOne` / `OneForAll` / `RestForOne` static-child
5863        // arm's canonical shape) axes so the accessor carries a
5864        // const-dispatch pin on both arms.
5865        let s_empty = SupervisorSpec {
5866            estrategia: RestartStrategy::SimpleOneForOne,
5867            max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
5868            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
5869            children: vec![],
5870        };
5871        assert!(children_via_const_fn(&s_empty).is_empty());
5872        assert_eq!(children_via_const_fn(&s_empty), s_empty.children());
5873        let s_full = SupervisorSpec {
5874            estrategia: RestartStrategy::OneForOne,
5875            max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
5876            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
5877            children: vec![
5878                child("worker-a", "^0.1", RestartPolicy::Permanent),
5879                child("worker-b", "~0.2.3", RestartPolicy::Transient),
5880                child("collector", "*", RestartPolicy::Temporary),
5881            ],
5882        };
5883        assert_eq!(children_via_const_fn(&s_full).len(), 3);
5884        assert_eq!(children_via_const_fn(&s_full), s_full.children());
5885    }
5886
5887    #[test]
5888    fn default_has_one_for_one_and_5_restarts_in_60s() {
5889        let s = SupervisorSpec::default();
5890        assert_eq!(s.estrategia, RestartStrategy::OneForOne);
5891        assert_eq!(s.max_restarts, 5);
5892        assert_eq!(s.restart_window, Some(Duration::from_secs(60)));
5893        assert!(s.children.is_empty());
5894    }
5895
5896    #[test]
5897    fn validate_one_for_one_requires_children() {
5898        // Explicit-empty via struct-update rather than `let mut s = default(); s.children = vec![];`
5899        // — the peer `validate_simple_one_for_one_forbids_static_children` below already uses
5900        // struct-update to name the axis under test at construction, and this shape matches
5901        // it. Also keeps the "empty children is the axis under test" intent visible at the
5902        // binding site rather than one line down, and side-steps `clippy::field_reassign_with_default`.
5903        let mut s = SupervisorSpec {
5904            children: vec![],
5905            ..SupervisorSpec::default()
5906        };
5907        assert!(matches!(
5908            s.validate().unwrap_err(),
5909            SupervisorError::NoChildren { .. }
5910        ));
5911        s.children = vec![child("worker", "^0.1", RestartPolicy::Permanent)];
5912        s.validate().unwrap();
5913    }
5914
5915    #[test]
5916    fn validate_simple_one_for_one_forbids_static_children() {
5917        let mut s = SupervisorSpec {
5918            estrategia: RestartStrategy::SimpleOneForOne,
5919            ..SupervisorSpec::default()
5920        };
5921        s.children
5922            .push(child("w", "^0.1", RestartPolicy::Permanent));
5923        assert_eq!(
5924            s.validate().unwrap_err(),
5925            SupervisorError::SimpleOneForOneWithStaticChildren
5926        );
5927        s.children.clear();
5928        s.validate().unwrap();
5929    }
5930
5931    #[test]
5932    fn validate_rejects_zero_max_restarts() {
5933        let s = SupervisorSpec {
5934            max_restarts: 0,
5935            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5936            ..SupervisorSpec::default()
5937        };
5938        assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
5939    }
5940
5941    // ── upper-cap: SUPERVISOR_MAX_RESTARTS_MAX brackets the typed slot ─────
5942    //
5943    // The cap arm lifts the `:politicas :circuit-breaker :max-failures` /
5944    // `POLICY_BREAKER_MAX_FAILURES_MAX` (2b51ace) discipline onto the peer
5945    // `:supervisor :max-restarts` axis — both fields are "trip the
5946    // next-higher protection layer after N events in a rolling window"
5947    // counters with identical degenerate-at-the-high-end shape, so the
5948    // typed-slot's accepted set lies in `1..=1000` on the supervisor side
5949    // exactly as it lies in `1..=1000` on the breaker side.
5950
5951    #[test]
5952    fn validate_rejects_max_restarts_above_cap() {
5953        // The fail-before-pass-after pin: `SUPERVISOR_MAX_RESTARTS_MAX +
5954        // 1` is structurally one past the cap and silently passed
5955        // validate on every pre-gate codebase because the typed slot's
5956        // only check was the zero-floor arm. The no-op-supervisor vector
5957        // only surfaced at the runtime substrate (Erlang/OTP
5958        // MaxIntensity/Period ratio, the future wasm-operator's
5959        // per-supervisor restart-intensity counter) far from the source
5960        // caixa.lisp with no field naming the offending supervisor.
5961        let s = SupervisorSpec {
5962            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5963            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5964            ..SupervisorSpec::default()
5965        };
5966        assert_eq!(
5967            s.validate().unwrap_err(),
5968            SupervisorError::MaxRestartsExceedsCap {
5969                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5970            }
5971        );
5972    }
5973
5974    #[test]
5975    fn validate_rejects_max_restarts_far_above_cap() {
5976        // The `u32::MAX` worst case — the four-billion-restart
5977        // threshold a typo (`:max-restarts 4294967295`) or a
5978        // struct-literal copy-paste lands in the slot. Pin the cap
5979        // arm's coverage explicitly across the full `u32` overflow so
5980        // a future relaxation that drops the upper bound surfaces
5981        // here. Same shape every other typed-cap arm on this surface
5982        // carries (POLICY_BREAKER_MAX_FAILURES_MAX,
5983        // POLICY_RETRIES_MAX, POLICY_RATE_LIMIT_MAX).
5984        let s = SupervisorSpec {
5985            max_restarts: u32::MAX,
5986            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5987            ..SupervisorSpec::default()
5988        };
5989        assert_eq!(
5990            s.validate().unwrap_err(),
5991            SupervisorError::MaxRestartsExceedsCap {
5992                max_restarts: u32::MAX,
5993            }
5994        );
5995    }
5996
5997    #[test]
5998    fn validate_accepts_max_restarts_at_cap() {
5999        // The boundary value — exactly SUPERVISOR_MAX_RESTARTS_MAX —
6000        // must validate. The cap is inclusive on the top edge,
6001        // matching the POLICY_BREAKER_MAX_FAILURES_MAX /
6002        // POLICY_RETRIES_MAX / LIMITS_MEMORY_WASM32_MAX_BYTES
6003        // discipline on the sibling capped axes. Pin the boundary
6004        // explicitly so a future off-by-one tightening
6005        // (`>= SUPERVISOR_MAX_RESTARTS_MAX` instead of `>`) surfaces
6006        // here as a test failure rather than a silent contract
6007        // narrowing.
6008        let s = SupervisorSpec {
6009            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX,
6010            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6011            ..SupervisorSpec::default()
6012        };
6013        s.validate()
6014            .expect("max_restarts == SUPERVISOR_MAX_RESTARTS_MAX must validate");
6015    }
6016
6017    #[test]
6018    fn validate_accepts_max_restarts_typical_values() {
6019        // The documented production-playbook band positive-control
6020        // sweep — every value Erlang/OTP / Elixir / Riak Core /
6021        // RabbitMQ recommend (1..=100) must pass, plus a sweep
6022        // through the hyperscale band (200, 500, 1000) the cap
6023        // accepts. Pin the inclusive validated set explicitly so a
6024        // future tightening of the ceiling surfaces here.
6025        for n in [1u32, 3, 5, 10, 20, 50, 100, 200, 500, 1000] {
6026            let s = SupervisorSpec {
6027                max_restarts: n,
6028                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6029                ..SupervisorSpec::default()
6030            };
6031            s.validate()
6032                .unwrap_or_else(|e| panic!("max_restarts={n} must validate; got {e:?}"));
6033        }
6034    }
6035
6036    #[test]
6037    fn zero_max_restarts_takes_precedence_over_cap() {
6038        // The cross-arm ordering pin: `0` is structurally outside
6039        // both `1..` (zero-floor) and `..=SUPERVISOR_MAX_RESTARTS_MAX`
6040        // (cap), but the zero-floor diagnostic is the more
6041        // self-locating one (it directly names the counter-axis
6042        // remediation), so the validate gate must fire on zero first.
6043        // Same shape every other zero-then-shape ordering on this
6044        // surface uses (PolicyRetriesZero then
6045        // PolicyRetriesExceedsCap; PolicyBreakerZeroFailures then
6046        // PolicyBreakerMaxFailuresExceedsCap).
6047        let s = SupervisorSpec {
6048            max_restarts: 0,
6049            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6050            ..SupervisorSpec::default()
6051        };
6052        assert_eq!(
6053            s.validate().unwrap_err(),
6054            SupervisorError::ZeroMaxRestarts,
6055            "max_restarts == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
6056        );
6057    }
6058
6059    #[test]
6060    fn max_restarts_cap_takes_precedence_over_restart_window_gates() {
6061        // The cross-arm ordering pin between the cap and the sibling
6062        // `:restart-window` gates (zero-window, canonical-window). A
6063        // supervisor carrying both an over-cap `max_restarts` AND a
6064        // structurally invalid window (zero, sub-ms) must surface the
6065        // cap diagnostic first — the cap arm is wired immediately
6066        // after the zero-restart arm and strictly before the window
6067        // arms, so the offending value the diagnostic names matches
6068        // the order the author would discover the gates by reading
6069        // top-to-bottom through `SupervisorSpec::validate`. Pin the
6070        // order so a future refactor that reorders the arms surfaces
6071        // here as a test failure rather than a silent diagnostic
6072        // regression. Peer of
6073        // `circuit_breaker_max_failures_cap_takes_precedence_over_window_gates`
6074        // on the sibling `:politicas :circuit-breaker` slot.
6075        let s = SupervisorSpec {
6076            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
6077            restart_window: Some(Duration::ZERO),
6078            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6079            ..SupervisorSpec::default()
6080        };
6081        assert_eq!(
6082            s.validate().unwrap_err(),
6083            SupervisorError::MaxRestartsExceedsCap {
6084                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
6085            },
6086            "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
6087        );
6088    }
6089
6090    #[test]
6091    fn max_restarts_cap_diagnostic_carries_offending_value() {
6092        // The diagnostic-shape pin: the offending `u32` is carried
6093        // verbatim into the `SupervisorError::MaxRestartsExceedsCap`
6094        // variant so the surfaced error message names the value the
6095        // author wrote (`":supervisor :max-restarts (50000) exceeds the
6096        // supervisor-policy ceiling …"`), not just the cap. Same
6097        // self-locating diagnostic shape every other typed-cap arm on
6098        // this surface carries
6099        // (`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap` carries
6100        // the offending failure count verbatim,
6101        // `AplicacaoError::PolicyRetriesExceedsCap` carries the offending
6102        // retries count verbatim).
6103        let s = SupervisorSpec {
6104            max_restarts: 50_000,
6105            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6106            ..SupervisorSpec::default()
6107        };
6108        let err = s.validate().unwrap_err();
6109        assert!(
6110            matches!(
6111                err,
6112                SupervisorError::MaxRestartsExceedsCap {
6113                    max_restarts: 50_000
6114                }
6115            ),
6116            "got {err:?}"
6117        );
6118        let msg = err.to_string();
6119        assert!(
6120            msg.contains("50000"),
6121            ":supervisor :max-restarts cap diagnostic must carry the offending value verbatim (got: {msg})"
6122        );
6123    }
6124
6125    #[test]
6126    fn supervisor_max_restarts_default_pins_otp_canonical_value() {
6127        // Pin [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] at `5` — the
6128        // Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
6129        // half of Learn You Some Erlang's worker-supervisor default,
6130        // sibling of the `60s` `Period` half that the paired
6131        // [`Default for SupervisorSpec`] impl already pins on the
6132        // sibling `restart_window` axis. Pinning the literal here
6133        // surfaces a future rebrand (a tightening to Elixir's `3`,
6134        // a widening to a per-cluster overlay the operator pins
6135        // through a future `:max-restarts-overrides` slot) as a
6136        // deliberate test edit, not a silent contract migration.
6137        // Peer of the sibling
6138        // [`supervisor_max_restarts_cap_pins_canonical_value`]
6139        // upper-bracket pin on the same axis.
6140        assert_eq!(SUPERVISOR_MAX_RESTARTS_DEFAULT, 5);
6141    }
6142
6143    #[test]
6144    fn default_max_restarts_helper_routes_through_lifted_default() {
6145        // Composition pin: the private `default_max_restarts()`
6146        // serde-`#[serde(default = "…")]` helper on
6147        // [`SupervisorSpec::max_restarts`] must route through the
6148        // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
6149        // typed `pub const` rather than a raw `5` literal. Prior to
6150        // the lift the helper carried an inline `5` with no compile-
6151        // time link back to the shared default, so the wire-format
6152        // author-omitted arm and the caixa-core
6153        // [`crate::manifest::Caixa::supervisor_view`] fold's `unwrap_or(5)`
6154        // arm could silently split on any future default rebrand.
6155        // Byte-parity against the lifted constant closes the split.
6156        assert_eq!(default_max_restarts(), SUPERVISOR_MAX_RESTARTS_DEFAULT);
6157    }
6158
6159    #[test]
6160    fn supervisor_spec_default_max_restarts_routes_through_lifted_default() {
6161        // Composition pin: the [`Default for SupervisorSpec`] impl's
6162        // struct-literal `max_restarts` field must route through the
6163        // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
6164        // typed `pub const` (via the private helper this test's
6165        // sibling `default_max_restarts_helper_routes_through_lifted_default`
6166        // already pins onto the constant). Structurally: every
6167        // `SupervisorSpec::default()` call must yield a
6168        // `max_restarts` field byte-equal to the lifted constant
6169        // (the two paired defaults — the serde-side wire-format arm
6170        // and the struct-literal default arm — cannot silently split
6171        // on any future default rebrand). Peer of the sibling
6172        // `default_has_one_for_one_and_5_restarts_in_60s` shape pin
6173        // — this pin closes the byte-parity arm on the two paired
6174        // altitude entry points onto the shared substrate constant.
6175        assert_eq!(
6176            SupervisorSpec::default().max_restarts(),
6177            SUPERVISOR_MAX_RESTARTS_DEFAULT,
6178        );
6179    }
6180
6181    #[test]
6182    fn supervisor_restart_window_default_pins_otp_canonical_value() {
6183        // Pin [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] at `60s` — the
6184        // Erlang/OTP-canonical `{intensity, 5, 60}` `Period` half of
6185        // Learn You Some Erlang's worker-supervisor default, paired
6186        // with the sibling `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5`
6187        // `MaxIntensity` half this constant is the sliding-window
6188        // denominator of on the same `MaxIntensity / Period`
6189        // restart-intensity ratio. Pinning the literal here surfaces a
6190        // future coherent rebrand of the paired default (Elixir's
6191        // `{max_restarts: 3, max_seconds: 5}`, a per-cluster overlay
6192        // the operator pins through a future
6193        // `:restart-window-overrides` slot) as a deliberate test edit,
6194        // not a silent contract migration. Peer of the sibling
6195        // [`supervisor_max_restarts_default_pins_otp_canonical_value`]
6196        // paired-half pin on the same OTP-canonical default and the
6197        // [`supervisor_restart_window_cap_pins_canonical_value`]
6198        // upper-bracket pin on the same axis.
6199        assert_eq!(SUPERVISOR_RESTART_WINDOW_DEFAULT, Duration::from_secs(60),);
6200    }
6201
6202    #[test]
6203    fn supervisor_spec_default_restart_window_routes_through_lifted_default() {
6204        // Composition pin: the [`Default for SupervisorSpec`] impl's
6205        // struct-literal `restart_window` field must route through the
6206        // substrate-canonical [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
6207        // typed `pub const` rather than a raw
6208        // `Duration::from_secs(60)` literal. Prior to this lift the
6209        // paired `{intensity, 5, 60}` OTP-canonical default was split
6210        // across two altitudes with no compile-time link between the
6211        // halves — the `MaxIntensity` half rode through the lifted
6212        // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant while the
6213        // `Period` half rode as an open-coded literal at the
6214        // composition site, so a future coherent rebrand of the paired
6215        // canonical would have had to migrate one half through the
6216        // constant and the other through a raw literal in lockstep.
6217        // Byte-parity against the lifted constant on the `Period` half
6218        // closes the split — the paired OTP-canonical default now
6219        // migrates as one unit on any future axis change. Peer of the
6220        // sibling
6221        // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
6222        // byte-parity pin on the paired `MaxIntensity` half.
6223        assert_eq!(
6224            SupervisorSpec::default().restart_window(),
6225            Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
6226        );
6227    }
6228
6229    #[test]
6230    fn supervisor_estrategia_default_pins_otp_canonical_value() {
6231        // Pin [`SUPERVISOR_ESTRATEGIA_DEFAULT`] at [`RestartStrategy::OneForOne`]
6232        // — the Erlang/OTP-canonical `one_for_one` half of Learn You Some
6233        // Erlang's `{one_for_one, intensity, 5, 60}` worker-supervisor
6234        // canonical default, paired with the sibling
6235        // `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5` `MaxIntensity` half and the
6236        // sibling `SUPERVISOR_RESTART_WINDOW_DEFAULT` `60s` `Period` half
6237        // this constant is the strategy discriminator of on the same
6238        // OTP-canonical worker-supervisor default. Pinning the arm here
6239        // surfaces a future coherent rebrand of the paired triple (Elixir's
6240        // `{:one_for_one, max_restarts: 3, max_seconds: 5}` on the sibling
6241        // intensity/period axes leaving this strategy arm untouched, an OTP
6242        // `rest_for_one` widening once the substrate discovers startup-
6243        // order-coupled child cohorts as the more common worker-supervisor
6244        // shape, a per-cluster overlay the operator pins through a future
6245        // `:estrategia-overrides` slot the MESH-COMPOSITION §III.2
6246        // supervision-canary roadmap acknowledges) as a deliberate test
6247        // edit, not a silent contract migration. Peer of the sibling
6248        // [`supervisor_max_restarts_default_pins_otp_canonical_value`] +
6249        // [`supervisor_restart_window_default_pins_otp_canonical_value`]
6250        // paired-half pins on the same OTP-canonical default.
6251        assert_eq!(SUPERVISOR_ESTRATEGIA_DEFAULT, RestartStrategy::OneForOne);
6252    }
6253
6254    #[test]
6255    fn restart_strategy_default_routes_through_lifted_default() {
6256        // Composition pin: the [`Default for RestartStrategy`] impl's
6257        // return arm must route through the substrate-canonical
6258        // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
6259        // a raw `Self::OneForOne` arm. Prior to the lift the impl carried
6260        // an inline `Self::OneForOne` with no compile-time link back to
6261        // the shared OTP-canonical `one_for_one` strategy the paired
6262        // [`Default for SupervisorSpec`] impl's struct-literal `estrategia`
6263        // field and the [`crate::manifest::Caixa::supervisor_view`] fold's
6264        // `.unwrap_or_default()` (now
6265        // `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)`) arm both key off —
6266        // so a future rebrand of the OTP-canonical strategy default (an
6267        // OTP `rest_for_one` widening once the substrate discovers
6268        // startup-order-coupled child cohorts as the more common worker-
6269        // supervisor shape, a per-cluster overlay the operator pins
6270        // through a future `:estrategia-overrides` slot) would have had to
6271        // be threaded through the `Default` impl and the two peer routes
6272        // in lockstep or the three consumers would silently split. Byte-
6273        // parity against the lifted constant closes the split. Peer of
6274        // the sibling
6275        // [`default_max_restarts_helper_routes_through_lifted_default`] +
6276        // [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
6277        // composition pins on the paired `MaxIntensity` + `Period` halves.
6278        assert_eq!(RestartStrategy::default(), SUPERVISOR_ESTRATEGIA_DEFAULT,);
6279    }
6280
6281    #[test]
6282    fn supervisor_spec_default_estrategia_routes_through_lifted_default() {
6283        // Composition pin: the [`Default for SupervisorSpec`] impl's
6284        // struct-literal `estrategia` field must route through the
6285        // substrate-canonical [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed
6286        // `pub const` (either directly, or via the
6287        // [`RestartStrategy::default`] impl that the sibling
6288        // `restart_strategy_default_routes_through_lifted_default` pin
6289        // already routes onto the constant). Structurally: every
6290        // `SupervisorSpec::default()` call must yield an `estrategia`
6291        // field byte-equal to the lifted constant (the three paired
6292        // defaults — the [`Default for RestartStrategy`] impl arm, the
6293        // struct-literal default arm here, and the
6294        // [`crate::manifest::Caixa::supervisor_view`] fold arm — cannot
6295        // silently split on any future default rebrand). Peer of the
6296        // sibling
6297        // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
6298        // + [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
6299        // byte-parity pins on the paired `MaxIntensity` + `Period` halves
6300        // of the same `SupervisorSpec::default()` composed altitude.
6301        assert_eq!(
6302            SupervisorSpec::default().estrategia(),
6303            SUPERVISOR_ESTRATEGIA_DEFAULT,
6304        );
6305    }
6306
6307    #[test]
6308    fn supervisor_spec_default_routes_through_otp_canonical_ctor() {
6309        // Composition pin: the [`Default for SupervisorSpec`] impl must
6310        // route through the substrate-canonical
6311        // [`SupervisorSpec::otp_canonical`] `pub const fn` constructor
6312        // rather than a re-hand-authored struct-literal cascade. Sharpens
6313        // the sibling per-arm
6314        // `supervisor_spec_default_*_routes_through_lifted_default` pins
6315        // from a per-field lift into a whole-struct one-source-of-truth
6316        // pin — the derived-until-now [`Default::default`] and the
6317        // [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
6318        // construction, not by coincidence.
6319        //
6320        // A future extension of the OTP-canonical baseline (a fifth
6321        // `restart_intensity` field the Erlang/OTP `#supervisor` record
6322        // grows, a per-child-cohort split of the `restart_window` /
6323        // `max_restarts` pair, an M4 `mesh.pleme.io/v1alpha1/Supervisor`
6324        // CR materializer's admission-time overlay pass) reaches both
6325        // paths through exactly one edit on
6326        // [`SupervisorSpec::otp_canonical`] — the derived path could
6327        // silently disagree with the constructor's shape on any new
6328        // field whose [`Default::default`] resolves to a different arm
6329        // than the OTP-canonical baseline the constructor names, while
6330        // this delegated impl reaches the constructor directly and
6331        // picks up every future extension by construction.
6332        //
6333        // Fourth peer on the M2 / M3 typed-slot-spec
6334        // [`Default`]-through-const-ctor fold family — sibling of the
6335        // [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
6336        // (abd52c2), [`crate::aplicacao::MeshPolicy`]
6337        // [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`]
6338        // (91641a4), and [`crate::BehaviorSpec`]
6339        // [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c)
6340        // per-`Option`-only-typed-slot folds — extended here onto the
6341        // M2 supervisor-slot [`SupervisorSpec`] whose canonical baseline
6342        // is not "everything `None`" but the Erlang/OTP-canonical
6343        // `{one_for_one, 5, 60}` worker-supervisor triple.
6344        assert_eq!(SupervisorSpec::default(), SupervisorSpec::otp_canonical());
6345    }
6346
6347    #[test]
6348    fn supervisor_spec_otp_canonical_byte_equals_default() {
6349        // Value pin: [`SupervisorSpec::otp_canonical`] must byte-equal
6350        // the hand-authored `{one_for_one, 5, 60, []}` OTP-canonical
6351        // baseline the sibling `default_has_one_for_one_and_5_restarts_in_60s`
6352        // pin already asserts against the [`Default::default`] path.
6353        // Sharpens the pair-invariant into a per-constructor pin so a
6354        // future extension of [`SupervisorSpec`] with a fifth field
6355        // whose OTP-canonical shape is non-`Default::default`-equivalent
6356        // trips at caixa-core test time rather than at a downstream
6357        // consumer that composed [`SupervisorSpec::otp_canonical`] with
6358        // [`SupervisorSpec::validate`] as its "canonical baseline
6359        // seed".
6360        let canonical = SupervisorSpec::otp_canonical();
6361        assert_eq!(canonical.estrategia, RestartStrategy::OneForOne);
6362        assert_eq!(canonical.max_restarts, 5);
6363        assert_eq!(canonical.restart_window, Some(Duration::from_secs(60)));
6364        assert!(canonical.children.is_empty());
6365    }
6366
6367    #[test]
6368    fn supervisor_spec_otp_canonical_is_usable_in_const_context() {
6369        // Const-context pin: [`SupervisorSpec::otp_canonical`] must
6370        // remain callable from a `const`-bound position so downstream
6371        // `const`-context callers wanting a canonical OTP-baseline seed
6372        // can construct one at compile time without runtime dispatch on
6373        // the derived [`Default::default`]. Peer of the sibling
6374        // `pub const fn` [`crate::LimitsSpec::empty`] /
6375        // [`crate::aplicacao::MeshPolicy::empty`] /
6376        // [`crate::BehaviorSpec::empty`] constructors on the sibling
6377        // typed-slot-spec `pub const fn` axis. If a future edit breaks
6378        // the `const`-eligibility of [`SupervisorSpec::otp_canonical`]
6379        // (a non-`const` field-default helper, a non-`const`-stable
6380        // container type promotion), this evaluation fails at
6381        // build time on this file rather than at a downstream
6382        // `const`-context call site.
6383        const CANONICAL: SupervisorSpec = SupervisorSpec::otp_canonical();
6384        assert_eq!(CANONICAL.estrategia, SUPERVISOR_ESTRATEGIA_DEFAULT);
6385        assert_eq!(CANONICAL.max_restarts, SUPERVISOR_MAX_RESTARTS_DEFAULT);
6386        assert_eq!(
6387            CANONICAL.restart_window,
6388            Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
6389        );
6390        assert!(CANONICAL.children.is_empty());
6391    }
6392
6393    #[test]
6394    fn supervisor_child_restart_default_pins_otp_canonical_value() {
6395        // Pin [`SUPERVISOR_CHILD_RESTART_DEFAULT`] at
6396        // [`RestartPolicy::Permanent`] — Erlang/OTP's `permanent`
6397        // worker-child restart type (`{ChildId, StartFunc, permanent, …}`
6398        // in a `supervisor`'s `init/1` child-spec tuple), the per-child
6399        // half of the same OTP-shape supervisor-tree default set whose
6400        // per-`:supervisor` halves the sibling
6401        // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
6402        // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] /
6403        // [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] constants pin. Pinning the
6404        // arm here surfaces a future rebrand of the per-child default (an
6405        // OTP-`transient` widening once the substrate discovers clean-
6406        // completion-aware children as the more common child shape, a
6407        // per-cluster overlay the operator pins through a future
6408        // `:restart-overrides` slot the MESH-COMPOSITION §III.2
6409        // supervision-canary roadmap acknowledges) as a deliberate test
6410        // edit, not a silent contract migration. Peer of the sibling
6411        // [`supervisor_estrategia_default_pins_otp_canonical_value`] /
6412        // [`supervisor_max_restarts_default_pins_otp_canonical_value`] /
6413        // [`supervisor_restart_window_default_pins_otp_canonical_value`]
6414        // value pins on the per-`:supervisor` halves.
6415        assert_eq!(SUPERVISOR_CHILD_RESTART_DEFAULT, RestartPolicy::Permanent);
6416    }
6417
6418    #[test]
6419    fn restart_policy_default_routes_through_lifted_default() {
6420        // Composition pin: the [`Default for RestartPolicy`] impl's return
6421        // arm must route through the substrate-canonical
6422        // [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const` rather
6423        // than a raw `Self::Permanent` arm. Prior to the lift the impl
6424        // carried an inline `Self::Permanent` with no compile-time link
6425        // back to the OTP-shape supervisor-tree default set whose three
6426        // per-`:supervisor` halves already rode through lifted constants
6427        // — so a future coherent rebrand of the set would have had to
6428        // migrate three halves through typed constants and this fourth
6429        // through a raw enum arm in lockstep or the supervisor-level and
6430        // child-level defaults would silently drift apart. Byte-parity
6431        // against the lifted constant closes the split. Peer of the
6432        // sibling
6433        // [`restart_strategy_default_routes_through_lifted_default`]
6434        // composition pin on the per-`:supervisor` `:estrategia` axis.
6435        assert_eq!(RestartPolicy::default(), SUPERVISOR_CHILD_RESTART_DEFAULT);
6436    }
6437
6438    #[test]
6439    fn child_spec_serde_default_restart_routes_through_lifted_default() {
6440        // Composition pin: the serde-side `#[serde(default)]` on
6441        // [`ChildSpec::restart`] — the wire-format author-omitted
6442        // `:children :restart` arm — must resolve onto the substrate-
6443        // canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const`
6444        // (via the [`Default for RestartPolicy`] impl the sibling
6445        // `restart_policy_default_routes_through_lifted_default` pin
6446        // already routes onto the constant). Structurally: a `ChildSpec`
6447        // deserialized from a payload that omits the `restart` key must
6448        // yield a `restart` field byte-equal to the lifted constant, so
6449        // the wire-format author-omitted arm and the
6450        // [`RestartPolicy::default`] impl arm cannot silently split on any
6451        // future default rebrand. Peer of the sibling
6452        // [`supervisor_spec_default_estrategia_routes_through_lifted_default`]
6453        // / [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
6454        // / [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
6455        // byte-parity pins on the per-`:supervisor` halves of the same
6456        // author-omitted-slot resolution surface.
6457        let omitted: ChildSpec = serde_json::from_str(r#"{"caixa":"worker","versao":"^0.1"}"#)
6458            .expect("ChildSpec must deserialize with the restart key omitted");
6459        assert_eq!(
6460            omitted.restart(),
6461            SUPERVISOR_CHILD_RESTART_DEFAULT,
6462            "an author-omitted :children :restart slot must degrade onto \
6463             the SUPERVISOR_CHILD_RESTART_DEFAULT typed pub const (got \
6464             {:?}, expected {:?})",
6465            omitted.restart(),
6466            SUPERVISOR_CHILD_RESTART_DEFAULT,
6467        );
6468    }
6469
6470    #[test]
6471    fn supervisor_max_restarts_cap_pins_canonical_value() {
6472        // The SUPERVISOR_MAX_RESTARTS_MAX constant pins the value at
6473        // 1000 — the same ceiling the peer
6474        // POLICY_BREAKER_MAX_FAILURES_MAX cap carries on the
6475        // `:politicas :circuit-breaker :max-failures` axis (both are
6476        // "trip the next-higher protection layer after N events in a
6477        // rolling window" counters with identical
6478        // degenerate-at-the-high-end shape; uniform top edge so the
6479        // M4 CR materializers and the wasm-operator reconciler reach
6480        // for either field knowing the value is in `1..=1000`). Two
6481        // orders of magnitude above every documented Erlang/OTP /
6482        // Elixir / Riak Core / RabbitMQ production-playbook
6483        // recommendation band and below the clearly-pathological
6484        // "effectively no escalation" floor (10_000, 100_000,
6485        // u32::MAX). Pinning the literal value here surfaces a future
6486        // drift (a relaxation to 10_000, a tightening to 100) as a
6487        // deliberate test edit, not a silent contract narrowing.
6488        assert_eq!(SUPERVISOR_MAX_RESTARTS_MAX, 1000);
6489    }
6490
6491    #[test]
6492    fn validate_rejects_empty_child_name() {
6493        let s = SupervisorSpec {
6494            children: vec![child("", "^0.1", RestartPolicy::Permanent)],
6495            ..SupervisorSpec::default()
6496        };
6497        assert_eq!(s.validate().unwrap_err(), SupervisorError::EmptyChildName);
6498    }
6499
6500    #[test]
6501    fn validate_rejects_empty_child_version() {
6502        let s = SupervisorSpec {
6503            children: vec![child("w", "", RestartPolicy::Permanent)],
6504            ..SupervisorSpec::default()
6505        };
6506        assert!(matches!(
6507            s.validate().unwrap_err(),
6508            SupervisorError::EmptyChildVersion { .. }
6509        ));
6510    }
6511
6512    // ── value-shape: parse-as-VersionReq on :children :versao ─────────────
6513
6514    #[test]
6515    fn validate_rejects_invalid_child_versao_requirement() {
6516        // The fail-before-pass-after pin: a non-empty but malformed
6517        // semver requirement (`"^bad-version"`) silently passed
6518        // `validate()` on every pre-gate codebase because the prior
6519        // shape only refused the empty string. The parse failure
6520        // surfaced far downstream at lacre-resolve time with a
6521        // `semver::Error` that didn't name which `:children` entry
6522        // carried the typo. The new gate moves the check to caixa-build
6523        // time at the source caixa.lisp — the third `:versao` typed
6524        // axis (`:children`) joins `:deps` and `:membros` (9888b13) at
6525        // structural parity.
6526        let s = SupervisorSpec {
6527            children: vec![
6528                child("worker", "^0.1", RestartPolicy::Permanent),
6529                child("cache", "^bad-version", RestartPolicy::Transient),
6530            ],
6531            ..SupervisorSpec::default()
6532        };
6533        let err = s.validate().unwrap_err();
6534        assert!(
6535            matches!(
6536                err,
6537                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
6538                    if caixa == "cache" && versao == "^bad-version"
6539            ),
6540            "got {err:?}"
6541        );
6542    }
6543
6544    #[test]
6545    fn validate_rejects_child_versao_with_double_caret_typo() {
6546        // `"^^0.1"` is the canonical doubled-caret typo — looks
6547        // Cargo-shaped on first glance but fails the parser because
6548        // semver doesn't accept stacked operators. Pin this
6549        // adjacent-shape footgun explicitly so a future relaxation that
6550        // accepts "looks-canonical-but-isn't" forms surfaces here.
6551        let s = SupervisorSpec {
6552            children: vec![child("worker", "^^0.1", RestartPolicy::Permanent)],
6553            ..SupervisorSpec::default()
6554        };
6555        let err = s.validate().unwrap_err();
6556        assert!(
6557            matches!(
6558                err,
6559                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
6560                    if caixa == "worker" && versao == "^^0.1"
6561            ),
6562            "got {err:?}"
6563        );
6564    }
6565
6566    #[test]
6567    fn validate_rejects_child_versao_with_v_prefixed_tag() {
6568        // `"v0.1"` is the canonical "git-tag-shape leaking into the
6569        // semver requirement slot" typo — an author copies the
6570        // publish-side git-tag string verbatim into `:versao`, but
6571        // Cargo's semver parser rejects the leading `v`. Same
6572        // adjacent-shape footgun pinned for `:membros :versao`
6573        // (9888b13).
6574        let s = SupervisorSpec {
6575            children: vec![child("worker", "v0.1", RestartPolicy::Permanent)],
6576            ..SupervisorSpec::default()
6577        };
6578        let err = s.validate().unwrap_err();
6579        assert!(
6580            matches!(
6581                err,
6582                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
6583                    if caixa == "worker" && versao == "v0.1"
6584            ),
6585            "got {err:?}"
6586        );
6587    }
6588
6589    #[test]
6590    fn validate_accepts_canonical_child_versao_forms() {
6591        // The Cargo-shaped requirement forms `:deps :versao` and
6592        // `:membros :versao` already accept via
6593        // `crate::parse_requirement` must pass the children gate
6594        // without re-validating at the resolver layer. Pin every leg so
6595        // a future tightening of the canonical set surfaces here as a
6596        // test failure.
6597        for form in [
6598            "^0.1",      // caret — minor-range pin (the most common shape)
6599            "~0.1.2",    // tilde — patch-range pin
6600            "0.1.0",     // exact — single-version pin
6601            "*",         // wildcard — any version (semver::VersionReq::STAR)
6602            ">=0.1, <2", // multi-range — comma-separated comparators
6603        ] {
6604            let s = SupervisorSpec {
6605                children: vec![child("worker", form, RestartPolicy::Permanent)],
6606                ..SupervisorSpec::default()
6607            };
6608            s.validate()
6609                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
6610        }
6611    }
6612
6613    #[test]
6614    fn child_versao_empty_takes_precedence_over_invalid() {
6615        // Order pin: the existing `EmptyChildVersion` diagnostic (which
6616        // doesn't try to parse) fires before the new
6617        // `ChildVersaoInvalid` parse-side diagnostic, so an empty
6618        // `:versao` keeps its narrower error message —
6619        // `parse_requirement` would also reject `""`, but the
6620        // empty-string arm is the more self-locating diagnostic for the
6621        // author. Same ordering discipline as
6622        // `membro_versao_empty_takes_precedence_over_invalid` in
6623        // aplicacao.rs.
6624        let s = SupervisorSpec {
6625            children: vec![child("worker", "", RestartPolicy::Permanent)],
6626            ..SupervisorSpec::default()
6627        };
6628        let err = s.validate().unwrap_err();
6629        assert!(
6630            matches!(err, SupervisorError::EmptyChildVersion { ref caixa } if caixa == "worker"),
6631            "got {err:?}"
6632        );
6633    }
6634
6635    #[test]
6636    fn child_versao_invalid_fires_before_duplicate_check() {
6637        // Order pin: a malformed requirement on a non-duplicate entry
6638        // surfaces *its own* diagnostic (which names the offending
6639        // `:versao` string), even when a later entry would otherwise
6640        // collapse onto an earlier name. The per-entry shape gate runs
6641        // inline before the duplicate-key insert — parallel to
6642        // `membro_versao_invalid_fires_before_duplicate_check` in
6643        // aplicacao.rs and the b0c8389 / c4213a4 ordering discipline.
6644        let s = SupervisorSpec {
6645            children: vec![
6646                child("worker", "^bad", RestartPolicy::Permanent),
6647                child("cache", "^0.1", RestartPolicy::Transient),
6648                child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
6649            ],
6650            ..SupervisorSpec::default()
6651        };
6652        let err = s.validate().unwrap_err();
6653        assert!(
6654            matches!(
6655                err,
6656                SupervisorError::ChildVersaoInvalid { ref caixa, .. } if caixa == "worker"
6657            ),
6658            "got {err:?}"
6659        );
6660    }
6661
6662    #[test]
6663    fn child_versao_invalid_diagnostic_carries_offending_versao() {
6664        // The diagnostic-shape pin: the error names the offending
6665        // `:versao` value verbatim so the author can grep their
6666        // caixa.lisp without re-running the build, and carries a
6667        // non-empty `reason` from `semver::VersionReq::parse` so the
6668        // parser's own wording flows through to the diagnostic.
6669        let s = SupervisorSpec {
6670            children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
6671            ..SupervisorSpec::default()
6672        };
6673        let err = s.validate().unwrap_err();
6674        let SupervisorError::ChildVersaoInvalid {
6675            caixa,
6676            versao,
6677            reason,
6678        } = err
6679        else {
6680            panic!("expected ChildVersaoInvalid, got other variant");
6681        };
6682        assert_eq!(caixa, "worker");
6683        assert_eq!(versao, "not-a-req");
6684        assert!(
6685            !reason.is_empty(),
6686            "ChildVersaoInvalid `reason` must carry the parser's wording verbatim"
6687        );
6688    }
6689
6690    // ── value-shape: DNS-1123 label rule on :children :caixa ──────────────
6691
6692    #[test]
6693    fn validate_rejects_child_caixa_with_uppercase() {
6694        // The canonical "I copied the Servico's display name verbatim"
6695        // typo — child caixa names are lowercase per K8s DNS-1123 label
6696        // rule. The diagnostic names the offending name and suggests the
6697        // lower-cased fix in one edit, mirroring the
6698        // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0).
6699        let s = SupervisorSpec {
6700            children: vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
6701            ..SupervisorSpec::default()
6702        };
6703        let err = s.validate().unwrap_err();
6704        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
6705            panic!("expected ChildCaixaInvalid, got other variant");
6706        };
6707        assert_eq!(caixa, "Worker");
6708        assert!(
6709            reason.contains("uppercase"),
6710            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
6711        );
6712        assert!(
6713            reason.contains("\"worker\""),
6714            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
6715        );
6716    }
6717
6718    #[test]
6719    fn validate_rejects_child_caixa_with_underscore() {
6720        // The canonical "I'm thinking of a Python module / Postgres
6721        // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
6722        // label schema. K8s rejects `metadata.name: my_worker` at
6723        // admission time with an opaque `field is invalid` (no source-
6724        // citing diagnostic). The gate moves it to caixa-build time.
6725        let s = SupervisorSpec {
6726            children: vec![child("my_worker", "^0.1", RestartPolicy::Permanent)],
6727            ..SupervisorSpec::default()
6728        };
6729        let err = s.validate().unwrap_err();
6730        assert!(
6731            matches!(
6732                err,
6733                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
6734                    if caixa == "my_worker" && reason.contains('_')
6735            ),
6736            "got {err:?}"
6737        );
6738    }
6739
6740    #[test]
6741    fn validate_rejects_child_caixa_with_dot() {
6742        // A `:children :caixa` entry is a single DNS-1123 label, not a
6743        // subdomain. The K8s Service / ComputeUnit `metadata.name` rules
6744        // forbid dots. Same shape as `rejects_membro_caixa_with_dot`
6745        // (3f9d7a0) on the peer name axis.
6746        let s = SupervisorSpec {
6747            children: vec![child("team.worker", "^0.1", RestartPolicy::Permanent)],
6748            ..SupervisorSpec::default()
6749        };
6750        let err = s.validate().unwrap_err();
6751        assert!(
6752            matches!(
6753                err,
6754                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
6755                    if caixa == "team.worker" && reason.contains('.')
6756            ),
6757            "got {err:?}"
6758        );
6759    }
6760
6761    #[test]
6762    fn validate_rejects_child_caixa_with_leading_hyphen() {
6763        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
6764        // with an alphanumeric. The K8s apiserver rejects `-worker`
6765        // outright; the renderer would emit a `metadata.name: "-worker"`
6766        // that fails admission far from the source caixa.lisp.
6767        let s = SupervisorSpec {
6768            children: vec![child("-worker", "^0.1", RestartPolicy::Permanent)],
6769            ..SupervisorSpec::default()
6770        };
6771        let err = s.validate().unwrap_err();
6772        assert!(
6773            matches!(
6774                err,
6775                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
6776                    if caixa == "-worker" && reason.contains("start and end")
6777            ),
6778            "got {err:?}"
6779        );
6780    }
6781
6782    #[test]
6783    fn validate_rejects_child_caixa_with_trailing_hyphen() {
6784        // The symmetric arm of the boundary rule. Pin separately so
6785        // both ends of the label are covered against a future relaxation
6786        // that only checks one boundary.
6787        let s = SupervisorSpec {
6788            children: vec![child("worker-", "^0.1", RestartPolicy::Permanent)],
6789            ..SupervisorSpec::default()
6790        };
6791        let err = s.validate().unwrap_err();
6792        assert!(
6793            matches!(
6794                err,
6795                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
6796                    if caixa == "worker-"
6797            ),
6798            "got {err:?}"
6799        );
6800    }
6801
6802    #[test]
6803    fn validate_rejects_child_caixa_with_unicode() {
6804        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
6805        // (`xn--…`) by the author before it reaches K8s. The byte-by-
6806        // byte ASCII validity check rejects multi-byte UTF-8 sequences
6807        // by the first byte that fails the `[a-z0-9-]` predicate.
6808        let s = SupervisorSpec {
6809            children: vec![child("café", "^0.1", RestartPolicy::Permanent)],
6810            ..SupervisorSpec::default()
6811        };
6812        let err = s.validate().unwrap_err();
6813        assert!(
6814            matches!(
6815                err,
6816                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
6817                    if caixa == "café"
6818            ),
6819            "got {err:?}"
6820        );
6821    }
6822
6823    #[test]
6824    fn validate_rejects_child_caixa_with_whitespace() {
6825        // Whitespace is the canonical "I pasted from a sketch / doc"
6826        // footgun. The apiserver rejects every `metadata.name` value
6827        // carrying whitespace; pin the gate fires at the right boundary.
6828        let s = SupervisorSpec {
6829            children: vec![child("my worker", "^0.1", RestartPolicy::Permanent)],
6830            ..SupervisorSpec::default()
6831        };
6832        let err = s.validate().unwrap_err();
6833        assert!(
6834            matches!(
6835                err,
6836                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
6837                    if caixa == "my worker"
6838            ),
6839            "got {err:?}"
6840        );
6841    }
6842
6843    #[test]
6844    fn validate_rejects_child_caixa_too_long() {
6845        // The 64-byte boundary pin. DNS-1123 / DNS-1035 cap labels at
6846        // 63 bytes; the K8s apiserver rejects every `metadata.name`
6847        // axis over the limit at admission time. The diagnostic names
6848        // both the cap and the actual length so the author can shorten
6849        // in one edit, mirroring `rejects_membro_caixa_too_long`
6850        // (3f9d7a0) and `rejects_placement_cluster_too_long` (6cbb900).
6851        let too_long = "a".repeat(64);
6852        let s = SupervisorSpec {
6853            children: vec![child(&too_long, "^0.1", RestartPolicy::Permanent)],
6854            ..SupervisorSpec::default()
6855        };
6856        let err = s.validate().unwrap_err();
6857        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
6858            panic!("expected ChildCaixaInvalid, got other variant");
6859        };
6860        assert_eq!(caixa, too_long);
6861        assert!(
6862            reason.contains("63"),
6863            "diagnostic must name the 63-byte cap (got: {reason:?})"
6864        );
6865        assert!(
6866            reason.contains("64"),
6867            "diagnostic must name the actual length (got: {reason:?})"
6868        );
6869    }
6870
6871    #[test]
6872    fn child_caixa_max_length_validates() {
6873        // The 63-byte boundary control pin — exactly-at-the-cap is
6874        // accepted, mirroring `membro_caixa_max_length_validates`
6875        // (3f9d7a0) and `placement_cluster_max_length_validates`
6876        // (6cbb900). Pinned separately so a future off-by-one tightening
6877        // surfaces here.
6878        let max_label = "a".repeat(63);
6879        let s = SupervisorSpec {
6880            children: vec![child(&max_label, "^0.1", RestartPolicy::Permanent)],
6881            ..SupervisorSpec::default()
6882        };
6883        s.validate().unwrap();
6884    }
6885
6886    #[test]
6887    fn validate_accepts_canonical_child_caixa_forms() {
6888        // The realistic shapes a supervised child's `:caixa` carries —
6889        // single-word `worker`, version-suffixed `cache-v2`, single-char
6890        // `a`, two-char `db`, digit-start `2-pool`, longer hyphen-joined
6891        // `payment-retry`, all-digit `0`. Pin every leg so a future
6892        // tightening (e.g. requiring a leading lowercase letter) surfaces
6893        // here as a test failure. Mirrors `accepts_canonical_membro_caixa_forms`
6894        // (3f9d7a0) and `accepts_canonical_placement_cluster_forms`
6895        // (6cbb900).
6896        for form in [
6897            "worker",
6898            "cache-v2",
6899            "a",
6900            "db",
6901            "2-pool",
6902            "payment-retry",
6903            "0",
6904        ] {
6905            let s = SupervisorSpec {
6906                children: vec![child(form, "^0.1", RestartPolicy::Permanent)],
6907                ..SupervisorSpec::default()
6908            };
6909            s.validate()
6910                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
6911        }
6912    }
6913
6914    #[test]
6915    fn child_caixa_empty_takes_precedence_over_invalid() {
6916        // Order pin: the existing `EmptyChildName` diagnostic (which
6917        // doesn't try to parse the DNS-1123 shape) fires before the new
6918        // `ChildCaixaInvalid` per-axis gate, so an empty `:caixa` keeps
6919        // its narrower error message — `is_dns_1123_label` would reject
6920        // the empty string too (boundary check on the first byte), but
6921        // the empty-string arm is the more self-locating diagnostic for
6922        // the author. Same ordering discipline as
6923        // `membro_caixa_empty_takes_precedence_over_invalid` in
6924        // aplicacao.rs.
6925        let s = SupervisorSpec {
6926            children: vec![child("", "^0.1", RestartPolicy::Permanent)],
6927            ..SupervisorSpec::default()
6928        };
6929        let err = s.validate().unwrap_err();
6930        assert_eq!(err, SupervisorError::EmptyChildName);
6931    }
6932
6933    #[test]
6934    fn child_caixa_invalid_fires_before_versao_check() {
6935        // Order pin: the per-axis shape gate runs inline before the
6936        // per-entry versao check, so a malformed `:caixa` on an entry
6937        // whose `:versao` would also fail surfaces the more self-
6938        // locating name-axis diagnostic first. Parallel to
6939        // `membro_versao_invalid_fires_before_duplicate_check` (9888b13)
6940        // and `placement_cluster_invalid_fires_before_duplicate_check`
6941        // (6cbb900).
6942        let s = SupervisorSpec {
6943            children: vec![child("My_Worker", "", RestartPolicy::Permanent)],
6944            ..SupervisorSpec::default()
6945        };
6946        let err = s.validate().unwrap_err();
6947        assert!(
6948            matches!(
6949                err,
6950                SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "My_Worker"
6951            ),
6952            "got {err:?}"
6953        );
6954    }
6955
6956    #[test]
6957    fn child_caixa_invalid_fires_before_duplicate_check() {
6958        // Order pin: a malformed name on a non-duplicate entry surfaces
6959        // its own diagnostic, even when a later entry would otherwise
6960        // collapse onto an earlier name. The per-entry shape gate runs
6961        // inline before the duplicate-key HashSet insert, mirroring
6962        // `placement_cluster_invalid_fires_before_duplicate_check`
6963        // (6cbb900).
6964        let s = SupervisorSpec {
6965            children: vec![
6966                child("Worker", "^0.1", RestartPolicy::Permanent),
6967                child("cache", "^0.1", RestartPolicy::Transient),
6968                child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
6969            ],
6970            ..SupervisorSpec::default()
6971        };
6972        let err = s.validate().unwrap_err();
6973        assert!(
6974            matches!(
6975                err,
6976                SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "Worker"
6977            ),
6978            "got {err:?}"
6979        );
6980    }
6981
6982    #[test]
6983    fn child_caixa_invalid_diagnostic_carries_offending_caixa() {
6984        // The diagnostic-shape pin: the error names the offending
6985        // `:caixa` verbatim plus a non-empty parser-shaped `reason` so
6986        // the author can grep their caixa.lisp without re-running the
6987        // build. Mirrors the diagnostic-shape sweep on every prior
6988        // value-shape gate (3f9d7a0, 6cbb900, c7d05ec).
6989        let s = SupervisorSpec {
6990            children: vec![child("My_Worker", "^0.1", RestartPolicy::Permanent)],
6991            ..SupervisorSpec::default()
6992        };
6993        let err = s.validate().unwrap_err();
6994        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
6995            panic!("expected ChildCaixaInvalid, got other variant");
6996        };
6997        assert_eq!(caixa, "My_Worker");
6998        assert!(
6999            !reason.is_empty(),
7000            "ChildCaixaInvalid `reason` must carry the parser's wording verbatim"
7001        );
7002    }
7003
7004    // ── value-shape: zero restart_window + duplicate child names ──────────
7005
7006    #[test]
7007    fn validate_accepts_none_restart_window() {
7008        // Omitted `:restart-window` is the "never reset" sentinel —
7009        // valid by design. Mirrors :limits axes where None = unbounded.
7010        let s = SupervisorSpec {
7011            restart_window: None,
7012            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7013            ..SupervisorSpec::default()
7014        };
7015        s.validate().unwrap();
7016    }
7017
7018    #[test]
7019    fn validate_rejects_zero_restart_window() {
7020        // Same "0 means the opposite of what you think" footgun closed
7021        // for :politicas :timeout (Envoy treats 0s as infinite) and
7022        // :limits :wall-clock (wasmtime traps before the call starts).
7023        // Erlang/OTP's MaxIntensity/Period requires Period > 0.
7024        let s = SupervisorSpec {
7025            restart_window: Some(Duration::ZERO),
7026            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7027            ..SupervisorSpec::default()
7028        };
7029        assert_eq!(
7030            s.validate().unwrap_err(),
7031            SupervisorError::RestartWindowZero
7032        );
7033    }
7034
7035    // ── value-shape: integer-ms canonical-form on :restart-window ─────────
7036    //
7037    // The fourth (and last) typed-`Duration` axis in caixa-core to get
7038    // the integer-millisecond canonical-form gate — peer with
7039    // `:limits :wall-clock` (82fc3ef), `:politicas :timeout` (a4ae535),
7040    // and `:politicas :circuit-breaker :window` (a4ae535). The serde
7041    // path is already gated at the shared codec layer (see
7042    // `restart_window_serde_rejects_fractional_seconds`); this arm
7043    // closes the programmatic-struct-literal path the codec gate can't
7044    // see.
7045
7046    #[test]
7047    fn validate_rejects_sub_millisecond_restart_window() {
7048        // The fail-before-pass-after pin: a programmatic
7049        // `Duration::from_micros(1500)` (= 1_500_000 ns) silently passed
7050        // `validate` on every pre-gate codebase, then truncated to
7051        // `as_millis() == 1` on first serialize — the shared codec
7052        // emits `"1ms"`, parses it back to `Duration::from_millis(1)` =
7053        // 1_000_000 ns, the typed `restart_window` no longer matches
7054        // its rendered form.
7055        let s = SupervisorSpec {
7056            restart_window: Some(Duration::from_micros(1500)),
7057            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7058            ..SupervisorSpec::default()
7059        };
7060        match s.validate().unwrap_err() {
7061            SupervisorError::RestartWindowNotCanonical { window } => {
7062                assert_eq!(window, Duration::from_micros(1500));
7063            }
7064            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
7065        }
7066    }
7067
7068    #[test]
7069    fn validate_rejects_one_nanosecond_restart_window() {
7070        // The far-sub-ms case: `Duration::from_nanos(1)` is non-zero
7071        // (so `RestartWindowZero` doesn't fire) but `as_millis() == 0`,
7072        // so the shared codec emits the literal `"0s"` — the next
7073        // serde round-trip would parse back to `Duration::ZERO`, which
7074        // the `RestartWindowZero` arm then rejects on re-validate. The
7075        // canonical-form gate at this layer surfaces a self-locating
7076        // diagnostic naming the offending Duration verbatim rather
7077        // than a downstream `RestartWindowZero` whose remediation
7078        // points at omitting the slot.
7079        let s = SupervisorSpec {
7080            restart_window: Some(Duration::from_nanos(1)),
7081            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7082            ..SupervisorSpec::default()
7083        };
7084        match s.validate().unwrap_err() {
7085            SupervisorError::RestartWindowNotCanonical { window } => {
7086                assert_eq!(window, Duration::from_nanos(1));
7087            }
7088            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
7089        }
7090    }
7091
7092    #[test]
7093    fn validate_rejects_nanosecond_past_canonical_boundary_restart_window() {
7094        // The 1-ns-past-1ms boundary case: a `Duration` carrying
7095        // 1_000_001 ns is structurally past the integer-ms granularity
7096        // floor — `subsec_nanos() % 1_000_000 == 1`. The codec round-
7097        // trip would truncate to `1ms` and the consumer would observe
7098        // a 1-ns drift on every emit. Same boundary the peer
7099        // `validate_rejects_nanosecond_past_canonical_boundary` test
7100        // in limits.rs pins for the `:limits :wall-clock` axis.
7101        let w = Duration::from_nanos(1_000_001);
7102        let s = SupervisorSpec {
7103            restart_window: Some(w),
7104            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7105            ..SupervisorSpec::default()
7106        };
7107        assert_eq!(
7108            s.validate().unwrap_err(),
7109            SupervisorError::RestartWindowNotCanonical { window: w }
7110        );
7111    }
7112
7113    #[test]
7114    fn validate_accepts_integer_millisecond_restart_window_values() {
7115        // The positive-control sweep: every `Duration` the shared
7116        // codec can round-trip losslessly — the canonical
7117        // `<integer>{ms,s,m,h}` set the codec's `render` / `parse`
7118        // pair emits and accepts — passes `validate` without
7119        // surfacing the new canonical-form arm. Mirrors
7120        // `validate_accepts_integer_millisecond_wall_clock_values` on
7121        // the sibling `:limits :wall-clock` axis.
7122        for w in [
7123            Duration::from_millis(1),
7124            Duration::from_millis(500),
7125            Duration::from_millis(1500),
7126            Duration::from_secs(1),
7127            Duration::from_secs(30),
7128            Duration::from_secs(60),
7129            Duration::from_secs(120),
7130            Duration::from_secs(3600),
7131        ] {
7132            let s = SupervisorSpec {
7133                restart_window: Some(w),
7134                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7135                ..SupervisorSpec::default()
7136            };
7137            s.validate()
7138                .unwrap_or_else(|e| panic!("integer-ms {w:?} must validate, got {e:?}"));
7139        }
7140    }
7141
7142    #[test]
7143    fn validate_restart_window_zero_takes_precedence_over_canonical_gate() {
7144        // Cross-arm ordering pin: `Duration::ZERO` has
7145        // `subsec_nanos() == 0` and would otherwise pass the
7146        // canonical-form arm — the zero-floor arm must fire first so
7147        // the more self-locating `RestartWindowZero` diagnostic (with
7148        // its omit-axis remediation directly named) leads. Same
7149        // posture every peer zero-then-shape gate uses
7150        // (`WallClockZero` → `WallClockNotCanonical`,
7151        // `PolicyTimeoutZero` → `PolicyTimeoutNotCanonical`,
7152        // `PolicyBreakerZeroWindow` → `PolicyBreakerWindowNotCanonical`).
7153        let s = SupervisorSpec {
7154            restart_window: Some(Duration::ZERO),
7155            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7156            ..SupervisorSpec::default()
7157        };
7158        assert_eq!(
7159            s.validate().unwrap_err(),
7160            SupervisorError::RestartWindowZero
7161        );
7162    }
7163
7164    #[test]
7165    fn restart_window_canonical_diagnostic_carries_offending_duration() {
7166        // Diagnostic-shape pin: the canonical-form arm names the
7167        // offending `Duration` verbatim so the author's grep lands on
7168        // the field's value, not a generic "duration not canonical"
7169        // message. Same shape every other typed-canonical-form arm
7170        // on this surface carries (`WallClockNotCanonical` carries
7171        // the offending `Duration` verbatim,
7172        // `PolicyTimeoutNotCanonical` carries the offending
7173        // `Duration` verbatim).
7174        let w = Duration::from_micros(500);
7175        let s = SupervisorSpec {
7176            restart_window: Some(w),
7177            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7178            ..SupervisorSpec::default()
7179        };
7180        let err = s.validate().unwrap_err();
7181        let msg = err.to_string();
7182        assert!(
7183            msg.contains("500"),
7184            "diagnostic must carry the offending magnitude verbatim (got {msg:?})"
7185        );
7186        assert!(
7187            msg.contains("sub-millisecond"),
7188            "diagnostic must name the sub-millisecond residue class (got {msg:?})"
7189        );
7190    }
7191
7192    #[test]
7193    fn restart_window_validated_value_round_trips_through_codec() {
7194        // The structural property the canonical-ms gate enforces:
7195        // every `SupervisorSpec::restart_window` past
7196        // `SupervisorSpec::validate` round-trips losslessly through
7197        // the shared duration codec (serialize → string →
7198        // deserialize → equal value). Pin this end-to-end so a future
7199        // change to either side (the validate gate's accepted
7200        // granularity, the codec's parse/render unit set) that breaks
7201        // the alignment surfaces here. Peer of
7202        // `wall_clock_validated_value_round_trips_through_codec` on
7203        // the sibling `:limits :wall-clock` axis.
7204        for w in [
7205            Duration::from_millis(1),
7206            Duration::from_millis(1500),
7207            Duration::from_secs(30),
7208            Duration::from_secs(3600),
7209        ] {
7210            let s = SupervisorSpec {
7211                restart_window: Some(w),
7212                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7213                ..SupervisorSpec::default()
7214            };
7215            s.validate().unwrap();
7216            let json = serde_json::to_string(&s).unwrap();
7217            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
7218            assert_eq!(back.restart_window, Some(w));
7219        }
7220    }
7221
7222    // ── value-shape: upper cap on :restart-window ─────────────────────────
7223    //
7224    // The fourth (and last) typed-`Duration` axis in caixa-core to get
7225    // the 1h upper cap — peer with `:limits :wall-clock` (51e0dbd),
7226    // `:politicas :timeout` (2e8ee7e), and `:politicas
7227    // :circuit-breaker :window` (379a814). Brackets the typed
7228    // `:restart-window` axis structurally: every validated value lies
7229    // in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`, integer-millisecond
7230    // granularity, closing the
7231    // rolling-window-degenerates-to-lifetime-counter footgun the prior
7232    // zero-floor-and-canonical-form-only checks left open.
7233
7234    #[test]
7235    fn validate_rejects_restart_window_above_cap() {
7236        // The fail-before-pass-after pin: 3601s = 1h + 1s is
7237        // structurally one canonical-tick past the
7238        // [`SUPERVISOR_RESTART_WINDOW_MAX`] ceiling (1h = 3600s) — an
7239        // integer-millisecond magnitude the canonical-form arm above
7240        // accepts cleanly, that the shared duration codec round-trips
7241        // losslessly as `"3601s"`, and that silently passed validate on
7242        // every pre-gate codebase because the typed slot's only checks
7243        // were the zero-floor and canonical-form arms. The runtime
7244        // substrate consuming the value (Erlang/OTP's MaxIntensity/
7245        // Period reconciler, the future wasm-operator's per-supervisor
7246        // restart-intensity counter) reaches for a `Duration` so long
7247        // no realistic restart-recovery pattern resets the counter,
7248        // far from the source caixa.lisp.
7249        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
7250        let s = SupervisorSpec {
7251            restart_window: Some(w),
7252            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7253            ..SupervisorSpec::default()
7254        };
7255        assert_eq!(
7256            s.validate().unwrap_err(),
7257            SupervisorError::RestartWindowExceedsCap { window: w }
7258        );
7259    }
7260
7261    #[test]
7262    fn validate_rejects_restart_window_one_millisecond_above_cap() {
7263        // Boundary case: exactly 1ms past the cap (the granularity the
7264        // canonical-form gate enforces). Catches a future "strictly
7265        // less than" half-measure and pins the diagnostic to name the
7266        // offending `Duration` verbatim. Peer of
7267        // `validate_rejects_wall_clock_one_millisecond_above_cap` /
7268        // `rejects_policy_timeout_one_millisecond_above_cap` /
7269        // `rejects_circuit_breaker_window_one_millisecond_above_cap`
7270        // on the sibling typed-`Duration` axes' top edges.
7271        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
7272        let s = SupervisorSpec {
7273            restart_window: Some(w),
7274            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7275            ..SupervisorSpec::default()
7276        };
7277        assert_eq!(
7278            s.validate().unwrap_err(),
7279            SupervisorError::RestartWindowExceedsCap { window: w }
7280        );
7281    }
7282
7283    #[test]
7284    fn validate_rejects_restart_window_far_above_cap() {
7285        // The "obvious authoring footgun" case: a `(:restart-window "24h")`,
7286        // `(:restart-window "7d")`, or any "I want a lifetime counter
7287        // but wrote a `<integer>h` magnitude anyway" typo — values the
7288        // canonical-form arm accepts as integer-millisecond magnitudes,
7289        // the codec round-trips losslessly through serde, but the
7290        // operator's `MaxIntensity / Period` reconciler cannot honor
7291        // as a meaningful rolling window. Until this gate landed
7292        // validate accepted them. Pin the common above-cap values (24h,
7293        // 7d, ~11.5d) so a future relaxation that drops the upper bound
7294        // surfaces here.
7295        for w in [
7296            Duration::from_secs(86_400),    // 24h
7297            Duration::from_secs(604_800),   // 7d
7298            Duration::from_secs(1_000_000), // ~11.5 days
7299        ] {
7300            let s = SupervisorSpec {
7301                restart_window: Some(w),
7302                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7303                ..SupervisorSpec::default()
7304            };
7305            assert_eq!(
7306                s.validate().unwrap_err(),
7307                SupervisorError::RestartWindowExceedsCap { window: w }
7308            );
7309        }
7310    }
7311
7312    #[test]
7313    fn validate_accepts_restart_window_at_cap() {
7314        // The boundary value — exactly [`SUPERVISOR_RESTART_WINDOW_MAX`]
7315        // (1h) — must validate. The cap is inclusive on the top edge,
7316        // matching the [`crate::LIMITS_WALL_CLOCK_MAX`] /
7317        // [`crate::POLICY_TIMEOUT_MAX`] /
7318        // [`crate::POLICY_BREAKER_WINDOW_MAX`] discipline on the sibling
7319        // capped axes. Pin the boundary explicitly so a future
7320        // off-by-one tightening (`>= SUPERVISOR_RESTART_WINDOW_MAX`
7321        // instead of `>`) surfaces here as a test failure rather than a
7322        // silent contract narrowing.
7323        let s = SupervisorSpec {
7324            restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
7325            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7326            ..SupervisorSpec::default()
7327        };
7328        s.validate()
7329            .expect("restart_window == SUPERVISOR_RESTART_WINDOW_MAX must validate");
7330    }
7331
7332    #[test]
7333    fn validate_accepts_restart_window_typical_values() {
7334        // The documented Erlang/OTP / Elixir / Riak Core / RabbitMQ
7335        // per-supervisor production-playbook band positive-control
7336        // sweep — every value Learn You Some Erlang's `{intensity, 5,
7337        // 60}` worker-supervisor `Period = 60s` default, Elixir's
7338        // `Supervisor` `max_seconds: 5` default, OTP's `supervisor`
7339        // callback module `MaxT = 5..=60` typical, Riak Core's `MaxT ∈
7340        // 10s..=300s`, and RabbitMQ broker-supervisor `MaxT = 5s`
7341        // default recommend (5s..=300s) must pass, plus a sweep
7342        // through the long-tail-flaky-pool band (5m, 15m, 30m, 1h) the
7343        // cap accepts. Mirrors `validate_accepts_wall_clock_typical_values`
7344        // on the sibling `:limits :wall-clock` axis.
7345        for w in [
7346            Duration::from_millis(1),
7347            Duration::from_millis(500),
7348            Duration::from_secs(1),
7349            Duration::from_secs(5),  // RabbitMQ broker-supervisor default
7350            Duration::from_secs(10), // Riak Core lower
7351            Duration::from_secs(30),
7352            Duration::from_secs(60),  // Learn You Some Erlang default
7353            Duration::from_secs(120), // OTP supervisor MaxT typical
7354            Duration::from_secs(300), // Riak Core upper
7355            Duration::from_secs(900), // 15m
7356            Duration::from_secs(1800),
7357            Duration::from_secs(3600), // exactly 1h, the cap
7358        ] {
7359            let s = SupervisorSpec {
7360                restart_window: Some(w),
7361                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7362                ..SupervisorSpec::default()
7363            };
7364            s.validate()
7365                .unwrap_or_else(|e| panic!("restart_window={w:?} must validate; got {e:?}"));
7366        }
7367    }
7368
7369    #[test]
7370    fn restart_window_zero_takes_precedence_over_cap() {
7371        // The cross-arm ordering pin: `Duration::ZERO` is structurally
7372        // outside both `>= 1ms` (zero-floor) and `<=
7373        // SUPERVISOR_RESTART_WINDOW_MAX` (cap), but the zero-floor
7374        // diagnostic is the more self-locating one (it directly names
7375        // the omit-axis remediation), so the validate gate must fire
7376        // on zero first. Same shape every other zero-then-cap ordering
7377        // on this surface uses (`WallClockZero` then
7378        // `WallClockExceedsCap`, `PolicyTimeoutZero` then
7379        // `PolicyTimeoutExceedsCap`, `PolicyBreakerZeroWindow` then
7380        // `PolicyBreakerWindowExceedsCap`).
7381        let s = SupervisorSpec {
7382            restart_window: Some(Duration::ZERO),
7383            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7384            ..SupervisorSpec::default()
7385        };
7386        assert_eq!(
7387            s.validate().unwrap_err(),
7388            SupervisorError::RestartWindowZero,
7389            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
7390        );
7391    }
7392
7393    #[test]
7394    fn restart_window_canonical_takes_precedence_over_cap() {
7395        // The cross-arm ordering pin: a `Duration` that is *both*
7396        // sub-millisecond (non-canonical-form) and structurally above
7397        // the cap surfaces the canonical-form diagnostic first,
7398        // because the round-trip-shape break is the more fundamental
7399        // issue (the value can't even round-trip through the codec,
7400        // so the cap diagnostic naming `1ms..=1h` would be misleading
7401        // — there's no integer-ms form of the offending value). Pin
7402        // the order so a future refactor that reorders the arms
7403        // surfaces here as a test failure rather than a silent
7404        // diagnostic regression. Peer of
7405        // `wall_clock_canonical_takes_precedence_over_cap` /
7406        // `policy_timeout_canonical_takes_precedence_over_cap`.
7407        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_nanos(1);
7408        let s = SupervisorSpec {
7409            restart_window: Some(w),
7410            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7411            ..SupervisorSpec::default()
7412        };
7413        assert_eq!(
7414            s.validate().unwrap_err(),
7415            SupervisorError::RestartWindowNotCanonical { window: w },
7416            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
7417        );
7418    }
7419
7420    #[test]
7421    fn max_restarts_cap_takes_precedence_over_restart_window_cap() {
7422        // The cross-arm ordering pin between the `:max-restarts` cap
7423        // and the sibling `:restart-window` cap. A supervisor carrying
7424        // both an over-cap `max_restarts` AND an over-cap window must
7425        // surface the `MaxRestartsExceedsCap` diagnostic first — the
7426        // cap arm is wired immediately after the zero-restart arm and
7427        // strictly before every window-axis arm (zero / canonical /
7428        // cap), so the offending value the diagnostic names matches
7429        // the order the author would discover the gates by reading
7430        // top-to-bottom through `SupervisorSpec::validate`. Pin the
7431        // order so a future refactor that reorders the arms surfaces
7432        // here as a test failure rather than a silent diagnostic
7433        // regression. Peer of
7434        // `max_restarts_cap_takes_precedence_over_restart_window_gates`
7435        // on the sibling zero / canonical window arms.
7436        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
7437        let s = SupervisorSpec {
7438            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
7439            restart_window: Some(w),
7440            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7441            ..SupervisorSpec::default()
7442        };
7443        assert_eq!(
7444            s.validate().unwrap_err(),
7445            SupervisorError::MaxRestartsExceedsCap {
7446                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
7447            },
7448            "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
7449        );
7450    }
7451
7452    #[test]
7453    fn restart_window_cap_diagnostic_carries_offending_value() {
7454        // The diagnostic-shape pin: the offending `Duration` is
7455        // carried verbatim into the
7456        // [`SupervisorError::RestartWindowExceedsCap`] variant so the
7457        // surfaced error message names the value the author wrote,
7458        // not just the cap. Same self-locating diagnostic shape every
7459        // other typed-cap arm on this surface carries
7460        // (`WallClockExceedsCap` carries the offending `Duration`
7461        // verbatim, `PolicyTimeoutExceedsCap` carries the offending
7462        // `Duration` verbatim, `PolicyBreakerWindowExceedsCap` carries
7463        // the offending `Duration` verbatim).
7464        let w = Duration::from_secs(7200); // 2h
7465        let s = SupervisorSpec {
7466            restart_window: Some(w),
7467            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7468            ..SupervisorSpec::default()
7469        };
7470        let err = s.validate().unwrap_err();
7471        assert!(
7472            matches!(err, SupervisorError::RestartWindowExceedsCap { window } if window == w),
7473            "got {err:?}"
7474        );
7475        let msg = err.to_string();
7476        assert!(
7477            msg.contains("7200"),
7478            ":supervisor :restart-window cap diagnostic must carry the offending value verbatim (got: {msg})"
7479        );
7480    }
7481
7482    #[test]
7483    fn supervisor_restart_window_cap_pins_canonical_value() {
7484        // The SUPERVISOR_RESTART_WINDOW_MAX constant pins the value at
7485        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
7486        // shared duration codec emits as a clean canonical string
7487        // (`"<n>h"`). Pinning the literal value here surfaces a future
7488        // drift (a relaxation to 24h, a tightening to 5m) as a
7489        // deliberate test edit, not a silent contract narrowing.
7490        //
7491        // The four typed-`Duration` caps on the validation surface
7492        // (`LIMITS_WALL_CLOCK_MAX` per-process, `POLICY_TIMEOUT_MAX`
7493        // per-edge, `POLICY_BREAKER_WINDOW_MAX` per-breaker,
7494        // `SUPERVISOR_RESTART_WINDOW_MAX` per-supervisor) share a
7495        // single uniform top edge at the codec's largest emitted unit
7496        // — a structural-property invariant the equality assertions
7497        // here enshrine, so a future drift on any of the four
7498        // surfaces as a deliberate test edit. Same shape every other
7499        // typed-cap value pin uses
7500        // (`wall_clock_cap_pins_canonical_value`,
7501        // `policy_timeout_cap_pins_canonical_value`,
7502        // `circuit_breaker_window_cap_pins_canonical_value`).
7503        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, Duration::from_secs(3600));
7504        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX.as_millis(), 3_600_000);
7505        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::LIMITS_WALL_CLOCK_MAX);
7506        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::POLICY_TIMEOUT_MAX);
7507        assert_eq!(
7508            SUPERVISOR_RESTART_WINDOW_MAX,
7509            crate::POLICY_BREAKER_WINDOW_MAX
7510        );
7511    }
7512
7513    #[test]
7514    fn restart_window_cap_value_round_trips_through_codec() {
7515        // The codec round-trip property the cap arm preserves: the
7516        // [`SUPERVISOR_RESTART_WINDOW_MAX`] constant itself round-trips
7517        // through the shared duration codec — every value at the cap
7518        // serializes to the canonical `"1h"` form and parses back
7519        // identically. Pin the round-trip so a future change to the
7520        // codec's unit set or to the cap's magnitude that breaks the
7521        // round-trip property surfaces here. Peer of
7522        // `wall_clock_cap_value_round_trips_through_codec` on the
7523        // sibling `:limits :wall-clock` axis.
7524        let s = SupervisorSpec {
7525            restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
7526            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7527            ..SupervisorSpec::default()
7528        };
7529        s.validate().unwrap();
7530        let json = serde_json::to_string(&s).unwrap();
7531        assert!(
7532            json.contains("\"1h\""),
7533            "SUPERVISOR_RESTART_WINDOW_MAX must serialize to the canonical `\"1h\"` form (got {json})"
7534        );
7535        let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
7536        assert_eq!(back.restart_window, Some(SUPERVISOR_RESTART_WINDOW_MAX));
7537    }
7538
7539    #[test]
7540    fn validate_rejects_duplicate_child_caixa() {
7541        // Two children with the same :caixa render to two ComputeUnits
7542        // with the same name in the cluster's HelmRelease values —
7543        // one silently overwrites the other. Erlang/OTP's child_spec.id
7544        // is required-unique per supervisor; same set-not-multiset
7545        // discipline applied here as for :membros / :placement
7546        // :clusters / :entrada :paths.
7547        let s = SupervisorSpec {
7548            children: vec![
7549                child("worker", "^0.1", RestartPolicy::Permanent),
7550                child("cache", "^0.1", RestartPolicy::Transient),
7551                child("worker", "^0.2", RestartPolicy::Permanent),
7552            ],
7553            ..SupervisorSpec::default()
7554        };
7555        let err = s.validate().unwrap_err();
7556        assert!(
7557            matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "worker"),
7558            "got {err:?}"
7559        );
7560    }
7561
7562    #[test]
7563    fn validate_duplicate_child_diagnostic_names_first_collision() {
7564        // Iteration walks the :children list in declaration order —
7565        // the diagnostic names the first repeat, deterministically,
7566        // even when multiple names duplicate.
7567        let s = SupervisorSpec {
7568            children: vec![
7569                child("a", "^0.1", RestartPolicy::Permanent),
7570                child("b", "^0.1", RestartPolicy::Permanent),
7571                child("a", "^0.1", RestartPolicy::Permanent),
7572                child("b", "^0.1", RestartPolicy::Permanent),
7573            ],
7574            ..SupervisorSpec::default()
7575        };
7576        let err = s.validate().unwrap_err();
7577        assert!(
7578            matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "a"),
7579            "got {err:?}"
7580        );
7581    }
7582
7583    // ── self-supervision cross-slot gate ──────────────────────────
7584
7585    #[test]
7586    fn validate_no_self_supervision_rejects_self_referential_child() {
7587        // A supervisor whose `:children` lists its own `:nome` is a
7588        // one-node reconciliation cycle — rejected, naming the parent.
7589        let children = vec![
7590            child("worker", "^0.1", RestartPolicy::Permanent),
7591            child("orquestra", "^0.1", RestartPolicy::Permanent),
7592        ];
7593        let err = validate_no_self_supervision(&children, "orquestra").unwrap_err();
7594        assert!(
7595            matches!(err, SupervisorError::ChildSupervisesSelf { ref caixa } if caixa == "orquestra"),
7596            "got {err:?}"
7597        );
7598    }
7599
7600    #[test]
7601    fn validate_no_self_supervision_accepts_distinct_children() {
7602        // Positive control: distinct child names (including a child that
7603        // is itself a supervisor — nested trees are valid OTP) pass.
7604        let children = vec![
7605            child("worker", "^0.1", RestartPolicy::Permanent),
7606            child("sub-tree", "^0.1", RestartPolicy::Permanent),
7607        ];
7608        validate_no_self_supervision(&children, "orquestra").unwrap();
7609    }
7610
7611    #[test]
7612    fn validate_no_self_supervision_empty_children_is_ok() {
7613        // SimpleOneForOne / no-static-children supervisors have nothing
7614        // to self-reference — the gate is vacuously satisfied.
7615        validate_no_self_supervision(&[], "orquestra").unwrap();
7616    }
7617
7618    #[test]
7619    fn validate_simple_one_for_one_skips_uniqueness_check() {
7620        // SimpleOneForOne supervisors carry no static children — the
7621        // duplicate-child loop never runs. A zero-window declaration
7622        // on a SimpleOneForOne supervisor still trips the window check
7623        // (window applies to dynamic children too).
7624        let s = SupervisorSpec {
7625            estrategia: RestartStrategy::SimpleOneForOne,
7626            restart_window: None,
7627            children: vec![],
7628            ..SupervisorSpec::default()
7629        };
7630        s.validate().unwrap();
7631        let s_zero = SupervisorSpec {
7632            estrategia: RestartStrategy::SimpleOneForOne,
7633            restart_window: Some(Duration::ZERO),
7634            children: vec![],
7635            ..SupervisorSpec::default()
7636        };
7637        assert_eq!(
7638            s_zero.validate().unwrap_err(),
7639            SupervisorError::RestartWindowZero
7640        );
7641    }
7642
7643    #[test]
7644    fn validate_zero_window_runs_after_max_restarts_check() {
7645        // Pin the order: max_restarts == 0 fires before
7646        // restart_window == 0s, so an author with both wrong sees the
7647        // counter-axis diagnostic first (matches the order in the
7648        // struct and in the doc comment).
7649        let s = SupervisorSpec {
7650            max_restarts: 0,
7651            restart_window: Some(Duration::ZERO),
7652            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7653            ..SupervisorSpec::default()
7654        };
7655        assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
7656    }
7657
7658    #[test]
7659    fn round_trip_all_strategies() {
7660        for &strat in RestartStrategy::ALL {
7661            // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
7662            // shape partition through the [`gen_platform::IsVariant`]
7663            // derive-generated [`RestartStrategy::is_simple_one_for_one`]
7664            // predicate rather than the raw
7665            // `matches!(strat, RestartStrategy::SimpleOneForOne)`
7666            // open-coded pattern-match — same closed-set-typed-enum
7667            // arm-discriminator dispatch discipline the sibling
7668            // [`crate::upgrade::UpgradeInstruction::is_restart`] convergence
7669            // (915a934) extended onto its two paired positive / negated
7670            // `matches!` filter sites, and the sibling
7671            // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
7672            // predicate convergence (766ec63) extended onto the M3 mesh-
7673            // slot per-`:placement` distribution-strategy `matches!`
7674            // discriminator axis. See the sibling
7675            // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
7676            // fixture and the peer `manifest::tests::
7677            // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
7678            // fixture — all three sites (the last unlifted
7679            // `matches!`-based arm-discriminator axis on the OTP-shape
7680            // supervisor sibling-restart-strategy closed-set typed enum,
7681            // acknowledged in 915a934's Prior-commits footnote as the
7682            // outstanding follow-up) now consult one typed dispatch on
7683            // the substrate primitive.
7684            let s = SupervisorSpec {
7685                estrategia: strat,
7686                children: if strat.is_simple_one_for_one() {
7687                    vec![]
7688                } else {
7689                    vec![child("w", "^0.1", RestartPolicy::Permanent)]
7690                },
7691                ..SupervisorSpec::default()
7692            };
7693            let json = serde_json::to_string(&s).unwrap();
7694            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
7695            assert_eq!(s, back);
7696        }
7697    }
7698
7699    #[test]
7700    fn round_trip_all_restart_policies() {
7701        for policy in [
7702            RestartPolicy::Permanent,
7703            RestartPolicy::Temporary,
7704            RestartPolicy::Transient,
7705        ] {
7706            let c = child("w", "^0.1", policy);
7707            let json = serde_json::to_string(&c).unwrap();
7708            let back: ChildSpec = serde_json::from_str(&json).unwrap();
7709            assert_eq!(c, back);
7710        }
7711    }
7712
7713    #[test]
7714    fn restart_strategy_is_simple_one_for_one_predicate_partitions_the_arm_set() {
7715        // The fail-before-pass-after pin on the `gen_platform::IsVariant`
7716        // derive's [`RestartStrategy::is_simple_one_for_one`] arm-
7717        // discriminator predicate: [`RestartStrategy::SimpleOneForOne`]
7718        // is the only variant that satisfies `.is_simple_one_for_one()`;
7719        // every static-children-bearing arm (`OneForOne` / `OneForAll`
7720        // / `RestForOne`) returns `false`. This pin makes the partition
7721        // invariant load-bearing at caixa-core test time so a future
7722        // derive regression (a hole that returns `false` for
7723        // `SimpleOneForOne` too, or a byte-collision that flips a second
7724        // variant to `true`) trips here rather than laundering the arm
7725        // at the three test-fixture builder sites (a hole flips the
7726        // `SimpleOneForOne` fixture to carry a non-empty children list
7727        // and the subsequent `SupervisorSpec::validate` would refuse the
7728        // fixture with [`SupervisorError::SimpleOneForOneWithStaticChildren`];
7729        // a collision flips a peer strategy's fixture to carry an empty
7730        // children list and the subsequent `validate` would refuse with
7731        // [`SupervisorError::NoChildren`] — either way, the pin fires
7732        // here, at the derive site, rather than at the fixture-refusal
7733        // site far away). Peer of the sibling
7734        // [`crate::upgrade::tests::upgrade_instruction_is_restart_predicate_partitions_the_arm_set`]
7735        // (915a934) pin on the M2 OTP-appup axis and the sibling
7736        // [`crate::kind::tests::caixa_kind_is_variant_predicates_partition_the_arm_set`]
7737        // pin on the M0 `:kind` axis.
7738        let cases: &[(RestartStrategy, bool)] = &[
7739            (RestartStrategy::OneForOne, false),
7740            (RestartStrategy::OneForAll, false),
7741            (RestartStrategy::RestForOne, false),
7742            (RestartStrategy::SimpleOneForOne, true),
7743        ];
7744        for (variant, expected) in cases {
7745            assert_eq!(
7746                variant.is_simple_one_for_one(),
7747                *expected,
7748                "RestartStrategy::{variant:?}.is_simple_one_for_one() must \
7749                 return {expected} (partition invariant on the \
7750                 IsVariant-derived arm-discriminator predicate — every \
7751                 test-fixture site that partitions the `:children` slot \
7752                 shape on `SimpleOneForOne ↔ non-SimpleOneForOne` keys \
7753                 off this typed dispatch, so a derive regression must \
7754                 surface here rather than at the fixture-refusal site)"
7755            );
7756        }
7757    }
7758
7759    #[test]
7760    fn restart_strategy_fixture_partition_routes_through_is_simple_one_for_one_predicate() {
7761        // Byte-identity pin on the `SimpleOneForOne ↔ non-SimpleOneForOne`
7762        // fixture-shape partition against the pre-lift
7763        // `matches!(strat, RestartStrategy::SimpleOneForOne)` open-coded
7764        // pattern-match every test-fixture builder site previously
7765        // coupled to inline. Asserts the two projections agree byte-for-
7766        // byte on every arm of the enum, so a future derive regression
7767        // that flipped either predicate's arm-set would surface here at
7768        // caixa-core test time rather than at the three fixture-builder
7769        // sites (`supervisor::tests::round_trip_all_strategies`,
7770        // `supervisor::tests::supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`,
7771        // `manifest::tests::caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`)
7772        // far from the derive site. Same peer-shape byte-identity pin
7773        // every sibling `IsVariant`-derive-routed convergence carries on
7774        // the substrate's closed-set typed-enum surface (peer of
7775        // [`crate::upgrade::tests::validate_restart_exclusive_routes_through_is_restart_predicate`]
7776        // on the M2 OTP-appup axis).
7777        for &strat in RestartStrategy::ALL {
7778            let via_predicate = strat.is_simple_one_for_one();
7779            let via_matches = matches!(strat, RestartStrategy::SimpleOneForOne);
7780            assert_eq!(
7781                via_predicate, via_matches,
7782                "RestartStrategy::{strat:?}: is_simple_one_for_one() must \
7783                 byte-equal matches!(_, RestartStrategy::SimpleOneForOne) — \
7784                 the pre-lift open-coded pattern and the \
7785                 IsVariant-derived predicate are the same axis, \
7786                 one typed dispatch"
7787            );
7788        }
7789    }
7790
7791    #[test]
7792    fn duration_codec_round_trip_canonical_units() {
7793        // Note the canonical-form rule: durations serialize to the
7794        // *largest* unit that divides cleanly, so 60s ↔ "1m" and not
7795        // "60s" — but the round-trip preserves the underlying Duration.
7796        let cases = [
7797            ("30s", Duration::from_secs(30)),
7798            ("5m", Duration::from_secs(300)),
7799            ("1h", Duration::from_secs(3600)),
7800            ("500ms", Duration::from_millis(500)),
7801        ];
7802        for (lit, dur) in cases {
7803            let s = SupervisorSpec {
7804                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7805                restart_window: Some(dur),
7806                ..SupervisorSpec::default()
7807            };
7808            let json = serde_json::to_string(&s).unwrap();
7809            assert!(
7810                json.contains(&format!("\"{lit}\"")),
7811                "expected \"{lit}\" in {json}"
7812            );
7813            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
7814            assert_eq!(back.restart_window, Some(dur));
7815        }
7816    }
7817
7818    #[test]
7819    fn duration_canonicalizes_to_largest_unit() {
7820        // 60 seconds → "1m" (largest cleanly-divisible unit), but the
7821        // typed Duration still equals 60s on the way back.
7822        let s = SupervisorSpec {
7823            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7824            restart_window: Some(Duration::from_secs(60)),
7825            ..SupervisorSpec::default()
7826        };
7827        let json = serde_json::to_string(&s).unwrap();
7828        assert!(json.contains("\"1m\""), "{json}");
7829        let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
7830        assert_eq!(back.restart_window, Some(Duration::from_secs(60)));
7831    }
7832
7833    #[test]
7834    fn three_child_one_for_one_validates() {
7835        let s = SupervisorSpec {
7836            estrategia: RestartStrategy::OneForOne,
7837            max_restarts: 5,
7838            restart_window: Some(Duration::from_secs(60)),
7839            children: vec![
7840                child("worker", "^0.1", RestartPolicy::Permanent),
7841                child("cache", "^0.1", RestartPolicy::Transient),
7842                child("scratch", "^0.1", RestartPolicy::Temporary),
7843            ],
7844        };
7845        s.validate().unwrap();
7846    }
7847
7848    #[test]
7849    fn json_uses_pascal_case_for_strategy_and_policy() {
7850        // Variant names are PascalCase by default in serde, matching
7851        // tatara-lisp's enum convention (`:estrategia OneForOne`).
7852        let c = child("w", "^0.1", RestartPolicy::Permanent);
7853        let json = serde_json::to_string(&c).unwrap();
7854        assert!(json.contains("\"Permanent\""));
7855        assert!(!json.contains("\"permanent\""));
7856
7857        let s = SupervisorSpec {
7858            estrategia: RestartStrategy::OneForOne,
7859            children: vec![c],
7860            ..SupervisorSpec::default()
7861        };
7862        let json = serde_json::to_string(&s).unwrap();
7863        assert!(json.contains("\"estrategia\":\"OneForOne\""));
7864    }
7865
7866    // ── shared duration codec: integer-magnitude canonical-form gate ──
7867    //
7868    // The gate lifts the discipline `crate::limits::parse_duration`
7869    // (818dd38) carries on the peer `:limits :wall-clock` codec onto
7870    // the shared codec backing the remaining three typed-duration
7871    // slots: `:supervisor :restart-window`, `:politicas :timeout`, and
7872    // `:politicas :circuit-breaker :window`. Every magnitude `render`
7873    // emits is a non-negative integer with no decimal point and no
7874    // leading sign, so the codec's accepted set must match for
7875    // serialize/deserialize to round-trip without canonical-form
7876    // drift.
7877
7878    #[test]
7879    fn parse_accepts_integer_canonical_units() {
7880        // Pin the happy-path: every canonical author shape `render`
7881        // ever emits parses to the same `Duration` value, so the
7882        // codec's accepted set is at least a superset of its emitted
7883        // set on the canonical-unit axis.
7884        for (lit, dur) in [
7885            ("30s", Duration::from_secs(30)),
7886            ("500ms", Duration::from_millis(500)),
7887            ("2m", Duration::from_secs(120)),
7888            ("1h", Duration::from_secs(3600)),
7889            ("0s", Duration::ZERO),
7890        ] {
7891            assert_eq!(
7892                duration_codec::parse(lit).unwrap(),
7893                dur,
7894                "parse({lit:?}) should be {dur:?}"
7895            );
7896        }
7897    }
7898
7899    #[test]
7900    fn parse_accepts_bare_integer_as_seconds() {
7901        // The `"s" | ""` arm: a bare integer with no unit is read as
7902        // seconds. Pin this so the unit-empty form keeps parsing (it
7903        // renders to `"<n>s"` on serialize — that's a unit-choice
7904        // drift the integer-magnitude gate does NOT close, matching
7905        // the `parse_byte_size` `"1024"` → `"1KiB"` scope decision in
7906        // the peer `:limits :memory` codec).
7907        assert_eq!(
7908            duration_codec::parse("30").unwrap(),
7909            Duration::from_secs(30)
7910        );
7911    }
7912
7913    #[test]
7914    fn parse_rejects_fractional_seconds_with_canonical_form_diagnostic() {
7915        // `"1.5s"` parses as f64 to 1.5 → renders back as `"1500ms"`
7916        // on first serialize — DRIFT. The integer-magnitude gate names
7917        // the offending `"1.5"` verbatim and points at the canonical
7918        // remediation `"1500ms"`.
7919        let err = duration_codec::parse("1.5s").unwrap_err();
7920        assert!(err.contains("\"1.5\""), "missing magnitude in {err:?}");
7921        assert!(
7922            err.contains("not a non-negative integer"),
7923            "missing canonical-form reason in {err:?}"
7924        );
7925        assert!(
7926            err.contains("\"1500ms\""),
7927            "missing canonical-form remediation in {err:?}"
7928        );
7929    }
7930
7931    #[test]
7932    fn parse_rejects_decimal_shaped_integer_seconds() {
7933        // `"1.0s"` is the trickiest drift class: numerically `1.0s` is
7934        // `1s` exactly, so the round-trip looks correct — but the
7935        // emitted canonical form is `"1s"`, not `"1.0s"`. Gate the
7936        // decimal-shape-with-integer-value form so author intent is
7937        // never silently rewritten.
7938        let err = duration_codec::parse("1.0s").unwrap_err();
7939        assert!(err.contains("\"1.0\""), "missing magnitude in {err:?}");
7940        assert!(
7941            err.contains("not a non-negative integer"),
7942            "missing canonical-form reason in {err:?}"
7943        );
7944    }
7945
7946    #[test]
7947    fn parse_rejects_half_unit_minute() {
7948        // `"0.5m"` is the unit-fraction footgun — author writes a
7949        // human-readable half-minute, serde silently rewrites to
7950        // `"30s"` on next emit. The gate names the offending
7951        // magnitude `"0.5"` and points at the integer-in-smaller-unit
7952        // form.
7953        let err = duration_codec::parse("0.5m").unwrap_err();
7954        assert!(err.contains("\"0.5\""), "missing magnitude in {err:?}");
7955        assert!(
7956            err.contains("\"30s\""),
7957            "missing canonical-form remediation in {err:?}"
7958        );
7959    }
7960
7961    #[test]
7962    fn parse_rejects_leading_plus_sign() {
7963        // `u64::from_str` rejects `"+30"` but `f64::from_str` accepts
7964        // it as `30.0` — the prior parser used f64 so `"+30s"` parsed
7965        // cleanly to 30s and round-tripped to `"30s"` on next emit
7966        // (DRIFT). The digit-only gate closes the leading-sign class
7967        // first; the diagnostic names `"+30"` verbatim.
7968        let err = duration_codec::parse("+30s").unwrap_err();
7969        assert!(err.contains("\"+30\""), "missing magnitude in {err:?}");
7970        assert!(
7971            err.contains("not a non-negative integer"),
7972            "missing canonical-form reason in {err:?}"
7973        );
7974    }
7975
7976    #[test]
7977    fn parse_rejects_leading_minus_sign() {
7978        // The former `num < 0.0` arm: `"-30s"` parsed as f64 to -30,
7979        // rejected with `"negative duration in \"-30s\""`. Under the
7980        // integer-magnitude gate the diagnostic is unified — `-30` is
7981        // non-digit-only, f64-numeric, and surfaces with the canonical-
7982        // form reason (no leading `+` / `-` sign) naming the offending
7983        // `"-30"` verbatim. Same diagnostic shape as every other
7984        // rejected non-integer magnitude.
7985        let err = duration_codec::parse("-30s").unwrap_err();
7986        assert!(err.contains("\"-30\""), "missing magnitude in {err:?}");
7987        assert!(
7988            err.contains("not a non-negative integer"),
7989            "missing canonical-form reason in {err:?}"
7990        );
7991    }
7992
7993    #[test]
7994    fn parse_garbage_still_falls_through_to_bad_magnitude() {
7995        // Non-digit-only AND non-numeric (`"--1s"`, `"abc"`) falls
7996        // through to the narrower "bad duration magnitude" arm — the
7997        // canonical-form diagnostic is reserved for the parser-shape
7998        // footgun case, not the "not a number at all" case. Same
7999        // shape `parse_byte_size`'s `BadByteMagnitude` arm carries on
8000        // the peer `:limits :memory` codec.
8001        let err = duration_codec::parse("--1s").unwrap_err();
8002        assert!(
8003            err.contains("bad duration magnitude"),
8004            "expected bad-magnitude wording in {err:?}"
8005        );
8006    }
8007
8008    #[test]
8009    fn parse_digit_only_magnitude_carries_zero_f64_drift() {
8010        // The accepted set is now closed under `u64`-exact integer
8011        // arithmetic: `"500ms"` → `Duration::from_millis(500)` exactly,
8012        // `"3600s"` → `Duration::from_secs(3600)` exactly, `"1h"` →
8013        // `Duration::from_secs(3600)` exactly, no f64 mantissa drift
8014        // possible. Pin the integer-exact arms across the four unit
8015        // suffixes so a future refactor that reaches back for f64
8016        // (`from_secs_f64`, `mul_f64`) surfaces here.
8017        assert_eq!(
8018            duration_codec::parse("3600s").unwrap(),
8019            Duration::from_secs(3600)
8020        );
8021        assert_eq!(
8022            duration_codec::parse("60m").unwrap(),
8023            Duration::from_secs(3600)
8024        );
8025        assert_eq!(
8026            duration_codec::parse("1h").unwrap(),
8027            Duration::from_secs(3600)
8028        );
8029        assert_eq!(
8030            duration_codec::parse("999ms").unwrap(),
8031            Duration::from_millis(999)
8032        );
8033    }
8034
8035    #[test]
8036    fn restart_window_serde_rejects_fractional_seconds() {
8037        // The shared codec backs `SupervisorSpec::restart_window`
8038        // (`with = "duration_codec"`) — so the gate applies on serde
8039        // deserialize for the typed Supervisor slot. A
8040        // `{"restartWindow":"1.5s"}` payload that previously round-
8041        // tripped to a different canonical string on next serialize
8042        // is now refused at deserialize with the integer-magnitude
8043        // diagnostic.
8044        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
8045            "restartWindow":"1.5s",
8046            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
8047        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
8048        let msg = err.to_string();
8049        assert!(
8050            msg.contains("not a non-negative integer"),
8051            "expected integer-magnitude diagnostic in {msg:?}"
8052        );
8053        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
8054    }
8055
8056    #[test]
8057    fn restart_window_serde_rejects_leading_plus() {
8058        // The `u64::from_str` leading-`+` permissiveness gap that
8059        // motivated the digit-only gate (the `f64`-side accepted
8060        // `"+30"`, the prior parser silently round-tripped to `"30s"`)
8061        // is now closed on the shared codec — surfaces as a structured
8062        // diagnostic at the serde layer for every typed-duration slot.
8063        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
8064            "restartWindow":"+30s",
8065            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
8066        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
8067        let msg = err.to_string();
8068        assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
8069        assert!(
8070            msg.contains("not a non-negative integer"),
8071            "missing canonical-form reason in {msg:?}"
8072        );
8073    }
8074
8075    #[test]
8076    fn parse_rejects_leading_zero_magnitude() {
8077        // `"030s"` is digit-only, so the existing non-digit-only / sign
8078        // / fractional arm doesn't catch it — `u64::from_str("030")`
8079        // returns `Ok(30)`, so before this gate `"030s"` parsed to
8080        // `Duration::from_secs(30)` and round-tripped through `render`
8081        // to `"30s"` — a *different* canonical string on the next emit,
8082        // breaking the THEORY.md Part V render-determinism contract
8083        // exactly the way `"+30s"` did before the leading-`+` arm
8084        // landed. Peer with the `rate_limit_codec` leading-zero arm
8085        // (4f46830) on the same canonical-form-drift axis.
8086        let err = duration_codec::parse("030s").unwrap_err();
8087        assert!(
8088            err.contains("non-canonical leading zero"),
8089            "expected leading-zero diagnostic in {err:?}"
8090        );
8091        assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
8092        assert!(
8093            err.contains("\"30s\""),
8094            "missing canonical-form remediation in {err:?}"
8095        );
8096        assert!(
8097            err.contains("THEORY.md"),
8098            "missing render-determinism citation in {err:?}"
8099        );
8100    }
8101
8102    #[test]
8103    fn parse_rejects_multi_digit_zero_magnitude() {
8104        // `"00s"` and `"00ms"` are the all-zero leading-zero footgun —
8105        // digit-only, parse losslessly to `Duration::ZERO`, but render
8106        // back to `"0s"` (the single-byte canonical form) on the next
8107        // emit. The leading-zero arm refuses the drift class at the
8108        // codec layer; the semantic-zero gate downstream
8109        // (`SupervisorError::ZeroRestartWindow`, etc.) would refuse
8110        // the single-byte canonical form `"0s"` separately on the
8111        // typed-validate layer.
8112        let err = duration_codec::parse("00s").unwrap_err();
8113        assert!(
8114            err.contains("non-canonical leading zero"),
8115            "expected leading-zero diagnostic in {err:?}"
8116        );
8117        assert!(err.contains("\"00\""), "missing magnitude in {err:?}");
8118    }
8119
8120    #[test]
8121    fn parse_rejects_leading_zero_per_hour_window() {
8122        // `"01h"` is the per-hour-window footgun — multi-byte magnitude
8123        // starting with `0`, parses losslessly to `Duration::from_secs(3600)`,
8124        // renders to `"1h"` (DRIFT). The arm is unit-agnostic: every
8125        // canonical unit suffix the codec accepts (`ms` / `s` / `m` /
8126        // `h` / bare-integer-as-seconds) inherits the same gate.
8127        let err = duration_codec::parse("01h").unwrap_err();
8128        assert!(
8129            err.contains("non-canonical leading zero"),
8130            "expected leading-zero diagnostic in {err:?}"
8131        );
8132        assert!(err.contains("\"01\""), "missing magnitude in {err:?}");
8133    }
8134
8135    #[test]
8136    fn parse_rejects_leading_zero_bare_integer_as_seconds() {
8137        // The `parse_accepts_bare_integer_as_seconds` happy-path
8138        // (`"30"` → 30s) inherits the leading-zero arm: `"030"` is
8139        // multi-byte starts-with-`0`, parses losslessly to
8140        // `Duration::from_secs(30)`, renders to `"30s"` (DRIFT). The
8141        // bare-integer surface accepts permissive unit-empty
8142        // shorthand but still must reject leading-zero padding.
8143        let err = duration_codec::parse("030").unwrap_err();
8144        assert!(
8145            err.contains("non-canonical leading zero"),
8146            "expected leading-zero diagnostic in {err:?}"
8147        );
8148        assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
8149    }
8150
8151    #[test]
8152    fn parse_accepts_single_zero_magnitude_at_codec_layer() {
8153        // The codec-layer / typed-validate-layer boundary: `"0s"` /
8154        // `"0ms"` / `"0"` are the single-byte canonical-zero forms —
8155        // each round-trips losslessly through `render`
8156        // (`render(Duration::ZERO)` → `"0s"`), so the codec layer
8157        // accepts them. The downstream semantic-zero gates
8158        // (`SupervisorError::ZeroRestartWindow`,
8159        // `AplicacaoError::PolicyTimeoutZero`,
8160        // `AplicacaoError::PolicyCircuitBreakerWindowZero`) refuse
8161        // zero-magnitude authoring at the typed-validate layer above,
8162        // peer with the `rate_limit_codec` codec-layer / typed-
8163        // validate-layer partition for `"0/s"`.
8164        assert_eq!(duration_codec::parse("0s").unwrap(), Duration::ZERO);
8165        assert_eq!(duration_codec::parse("0ms").unwrap(), Duration::ZERO);
8166        assert_eq!(duration_codec::parse("0").unwrap(), Duration::ZERO);
8167    }
8168
8169    #[test]
8170    fn parse_accepts_canonical_magnitude_with_leading_one() {
8171        // The complementary boundary: a future tightening cannot
8172        // drift into rejecting valid canonical magnitudes that
8173        // happen to start with `1` (or any digit `[1-9]`). Pin
8174        // every canonical-unit suffix so the leading-zero arm
8175        // remains strictly narrower than the digit-only arm.
8176        assert_eq!(
8177            duration_codec::parse("100ms").unwrap(),
8178            Duration::from_millis(100)
8179        );
8180        assert_eq!(
8181            duration_codec::parse("100s").unwrap(),
8182            Duration::from_secs(100)
8183        );
8184        assert_eq!(
8185            duration_codec::parse("10m").unwrap(),
8186            Duration::from_secs(600)
8187        );
8188        assert_eq!(
8189            duration_codec::parse("10h").unwrap(),
8190            Duration::from_secs(36_000)
8191        );
8192    }
8193
8194    #[test]
8195    fn restart_window_serde_rejects_leading_zero() {
8196        // The shared codec backs `SupervisorSpec::restart_window`
8197        // (`with = "duration_codec"`) — so the leading-zero arm
8198        // applies on serde deserialize for the typed Supervisor slot.
8199        // A `{"restartWindow":"030s"}` payload that previously round-
8200        // tripped to a different canonical string on next serialize
8201        // is now refused at deserialize with the leading-zero
8202        // diagnostic. Peer with `restart_window_serde_rejects_leading_plus`
8203        // / `restart_window_serde_rejects_fractional_seconds` on the
8204        // same canonical-form-drift axis.
8205        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
8206            "restartWindow":"030s",
8207            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
8208        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
8209        let msg = err.to_string();
8210        assert!(
8211            msg.contains("non-canonical leading zero"),
8212            "expected leading-zero diagnostic in {msg:?}"
8213        );
8214        assert!(msg.contains("\"030\""), "missing magnitude in {msg:?}");
8215    }
8216
8217    #[test]
8218    fn parse_rejects_leading_whitespace() {
8219        // `" 30s"` — the canonical paste-from-aligned-doc /
8220        // paste-from-YAML-quoted-plain-scalar footgun. Before this
8221        // gate the top-level `s.trim()` at parse entry silently ate
8222        // the leading space and parsed the value to
8223        // `Duration::from_secs(30)`, which then round-tripped through
8224        // `render` to `"30s"` (a *different* canonical string on the
8225        // next emit) — the exact canonical-form-drift class the
8226        // leading-`+` / leading-zero arms already close, extended
8227        // to the whitespace-byte class. Peer with the sibling
8228        // `rate_limit_codec` whitespace-rejection arm (1ad7755) on
8229        // the M3 `:politicas` axis.
8230        let err = duration_codec::parse(" 30s").unwrap_err();
8231        assert!(
8232            err.contains("contains whitespace byte"),
8233            "expected whitespace diagnostic in {err:?}"
8234        );
8235        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
8236        assert!(
8237            err.contains("THEORY.md"),
8238            "missing render-determinism contract citation in {err:?}"
8239        );
8240    }
8241
8242    #[test]
8243    fn parse_rejects_trailing_whitespace() {
8244        // `"30s "` — the canonical shell-history / trailing-space
8245        // paste footgun. Before this gate the top-level `s.trim()`
8246        // silently ate the trailing space and parsed to
8247        // `Duration::from_secs(30)`, round-tripping to `"30s"` on the
8248        // next emit — same canonical-form drift as the leading-space
8249        // sibling, closed on the same whitespace-byte arm.
8250        let err = duration_codec::parse("30s ").unwrap_err();
8251        assert!(
8252            err.contains("contains whitespace byte"),
8253            "expected whitespace diagnostic in {err:?}"
8254        );
8255        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
8256    }
8257
8258    #[test]
8259    fn parse_rejects_internal_whitespace_between_magnitude_and_unit() {
8260        // `"30 s"` — the canonical typographically-spaced author
8261        // shape (the same idiom every prose reference to a duration
8262        // renders as, mistakenly retained when the value is pasted
8263        // into a codec-shaped slot). Before this gate the per-part
8264        // `num_part.trim()` / `unit.trim()` calls silently ate the
8265        // whitespace between the magnitude and the unit and parsed
8266        // the value to `Duration::from_secs(30)`, round-tripping to
8267        // `"30s"` — the codec's *internal* whitespace-tolerance
8268        // vector, orthogonal to the leading / trailing surface but
8269        // the same canonical-form-drift class. Pins the arm as
8270        // strictly stronger than the pre-existing top-level
8271        // `s.trim()` behavior: it fires on whitespace anywhere in
8272        // the value, not just at the string boundary.
8273        let err = duration_codec::parse("30 s").unwrap_err();
8274        assert!(
8275            err.contains("contains whitespace byte"),
8276            "expected whitespace diagnostic in {err:?}"
8277        );
8278        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
8279    }
8280
8281    #[test]
8282    fn parse_rejects_tab_byte() {
8283        // `"\t30s"` — the canonical paste-from-indented-doc /
8284        // paste-from-YAML-block-scalar footgun where a tab byte leads
8285        // the magnitude. Pins that the gate covers tab (`0x09`) as
8286        // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
8287        // members and both would be silently swallowed by `s.trim()`
8288        // pre-gate. The `is_ascii_whitespace` coverage extends beyond
8289        // space alone to the full ASCII-whitespace set (space `0x20`,
8290        // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
8291        // the tab arm as a representative of the non-space members.
8292        let err = duration_codec::parse("\t30s").unwrap_err();
8293        assert!(
8294            err.contains("contains whitespace byte"),
8295            "expected whitespace diagnostic in {err:?}"
8296        );
8297        assert!(
8298            err.contains("0x09"),
8299            "missing offending tab byte in {err:?}"
8300        );
8301    }
8302
8303    #[test]
8304    fn restart_window_serde_rejects_whitespace() {
8305        // The shared codec backs `SupervisorSpec::restart_window`
8306        // (`with = "duration_codec"`) — so the whitespace arm
8307        // applies on serde deserialize for the typed Supervisor slot.
8308        // A `{"restartWindow":" 30s"}` payload that previously round-
8309        // tripped to a different canonical string on next serialize
8310        // is now refused at deserialize with the whitespace-byte
8311        // diagnostic. Peer with `restart_window_serde_rejects_leading_zero`
8312        // / `restart_window_serde_rejects_leading_plus` /
8313        // `restart_window_serde_rejects_fractional_seconds` on the
8314        // same canonical-form-drift axis.
8315        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
8316            "restartWindow":" 30s",
8317            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
8318        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
8319        let msg = err.to_string();
8320        assert!(
8321            msg.contains("contains whitespace byte"),
8322            "expected whitespace diagnostic in {msg:?}"
8323        );
8324        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
8325    }
8326
8327    // ── canonical-form: non-ASCII Unicode `White_Space` duration gate ─────
8328    //
8329    // Successor to the ASCII-whitespace arm (a7ae622) on the shared
8330    // duration codec — closes the strictly-complementary class the
8331    // byte-scan cannot see, through the lifted
8332    // [`crate::render::find_non_ascii_whitespace_char`] predicate.
8333    // Applies to `:supervisor :restart-window`, `:politicas :timeout`,
8334    // and `:politicas :circuit-breaker :window` simultaneously via
8335    // this shared codec.
8336
8337    #[test]
8338    fn duration_codec_parse_rejects_leading_nbsp() {
8339        // NBSP prefix — the strictly-complementary drift class the
8340        // ASCII byte-scan cannot see. `str::trim` strips it silently
8341        // and the value drifts to `"30s"` on next serialize.
8342        let err = duration_codec::parse("\u{00A0}30s").unwrap_err();
8343        assert!(
8344            err.contains("non-ASCII Unicode whitespace character"),
8345            "expected non-ASCII whitespace diagnostic in {err:?}"
8346        );
8347        assert!(err.contains("U+00A0"), "missing codepoint in {err:?}");
8348    }
8349
8350    #[test]
8351    fn duration_codec_parse_rejects_trailing_line_separator() {
8352        // LINE SEPARATOR (`\u{2028}`) trailing — paste-from-web-doc
8353        // footgun.
8354        let err = duration_codec::parse("30s\u{2028}").unwrap_err();
8355        assert!(
8356            err.contains("non-ASCII Unicode whitespace character"),
8357            "expected non-ASCII whitespace diagnostic in {err:?}"
8358        );
8359        assert!(err.contains("U+2028"), "missing codepoint in {err:?}");
8360    }
8361
8362    #[test]
8363    fn duration_codec_parse_accepts_ascii_only_forms_after_unicode_arm() {
8364        // Positive-control pin: every ASCII-only canonical form the
8365        // renderer emits stays accepted through the new arm.
8366        assert_eq!(
8367            duration_codec::parse("30s").unwrap(),
8368            Duration::from_secs(30)
8369        );
8370        assert_eq!(
8371            duration_codec::parse("500ms").unwrap(),
8372            Duration::from_millis(500)
8373        );
8374        assert_eq!(
8375            duration_codec::parse("1h").unwrap(),
8376            Duration::from_secs(3600)
8377        );
8378    }
8379
8380    #[test]
8381    fn restart_window_serde_rejects_non_ascii_whitespace() {
8382        // The shared codec backs `SupervisorSpec::restart_window` — so
8383        // the new non-ASCII Unicode whitespace arm applies on serde
8384        // deserialize for the typed Supervisor slot. A
8385        // `{"restartWindow":" 30s"}` payload that previously
8386        // survived the ASCII byte-scan (only ASCII whitespace was
8387        // refused) is now refused at deserialize with the
8388        // non-ASCII-whitespace-and-codepoint diagnostic.
8389        let payload = "{\"estrategia\":\"OneForOne\",\"maxRestarts\":5,\
8390            \"restartWindow\":\"\u{00A0}30s\",\
8391            \"children\":[{\"caixa\":\"w\",\"versao\":\"^0.1\",\"restart\":\"Permanent\"}]}";
8392        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
8393        let msg = err.to_string();
8394        assert!(
8395            msg.contains("non-ASCII Unicode whitespace character"),
8396            "expected non-ASCII whitespace diagnostic in {msg:?}"
8397        );
8398        assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
8399    }
8400
8401    // ── drift-detection: serde-derive-to-SUPERVISOR_KEY_* identity ────────
8402
8403    #[test]
8404    fn supervisor_spec_serde_keys_match_lifted_supervisor_key_consts() {
8405        // Load-bearing invariant: the four `SUPERVISOR_KEY_*` consts
8406        // (`SUPERVISOR_KEY_ESTRATEGIA` / `SUPERVISOR_KEY_MAX_RESTARTS` /
8407        // `SUPERVISOR_KEY_RESTART_WINDOW` / `SUPERVISOR_KEY_CHILDREN`)
8408        // name the exact camelCase JSON keys the
8409        // `#[serde(rename_all = "camelCase")]` attribute on
8410        // `SupervisorSpec` emits. Serialize a fully-populated spec (each
8411        // field carries `Some(_)` / non-empty) and pin that each canonical
8412        // byte-sequence appears verbatim in the JSON — a future accidental
8413        // `rename_all = "snake_case"` / `"kebab-case"` / verbatim-field-
8414        // name flip at the derive attribute (any of which would silently
8415        // break every downstream JSON consumer that reaches for one of the
8416        // four consts via `Value::get(...)`) surfaces here as a build-time
8417        // test failure at `supervisor.rs`, not as an apply-time
8418        // `.get(<stale-canonical-const>)` returning `None` far from the
8419        // derive-attr drift's commit. Peer with the sibling
8420        // `limits_spec_serde_keys_match_lifted_m2_limits_key_consts`
8421        // (d8b8b4f) pin on the M2 `:limits` axis — same discipline the
8422        // M2 typed-slot family established, extended here to close the
8423        // top-level Supervisor axis.
8424        let spec = SupervisorSpec {
8425            estrategia: RestartStrategy::OneForOne,
8426            max_restarts: 5,
8427            restart_window: Some(Duration::from_secs(60)),
8428            children: vec![ChildSpec {
8429                caixa: "w".into(),
8430                versao: "^0.1".into(),
8431                restart: RestartPolicy::Permanent,
8432            }],
8433        };
8434        let json = serde_json::to_string(&spec).unwrap();
8435        for key in [
8436            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
8437            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
8438            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
8439            crate::render::SUPERVISOR_KEY_CHILDREN,
8440        ] {
8441            let quoted = format!("\"{key}\"");
8442            assert!(
8443                json.contains(&quoted),
8444                "serialized SupervisorSpec must carry the lifted \
8445                 SUPERVISOR_KEY_* byte-sequence {quoted} verbatim in \
8446                 the JSON emission (got: {json})",
8447            );
8448        }
8449    }
8450
8451    #[test]
8452    fn supervisor_key_consts_are_pairwise_distinct() {
8453        // Cross-axis drift-detection pin: a future collapse of two
8454        // canonical top-level byte-strings onto the same value (e.g. an
8455        // accidental copy-paste flip of `SUPERVISOR_KEY_CHILDREN` to
8456        // also read `"estrategia"`) would silently reroute every
8457        // downstream probe on one axis onto the sibling axis's overlay
8458        // entry and pass every propagation-probe test that expected only
8459        // the stale axis's value. Peer of the sibling four-way distinct
8460        // pin on the `M2_LIMITS_KEY_*` tetrad (d8b8b4f).
8461        let all = [
8462            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
8463            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
8464            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
8465            crate::render::SUPERVISOR_KEY_CHILDREN,
8466        ];
8467        for (i, a) in all.iter().enumerate() {
8468            for b in all.iter().skip(i + 1) {
8469                assert_ne!(
8470                    a, b,
8471                    "SUPERVISOR_KEY_* consts must be pairwise-distinct \
8472                     canonical byte-sequences — got `{a}` == `{b}`",
8473                );
8474            }
8475        }
8476    }
8477
8478    #[test]
8479    fn supervisor_key_consts_are_lower_camel_case_shape() {
8480        // Shape-pin: every `SUPERVISOR_KEY_*` const must be a
8481        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
8482        // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
8483        // capital, no whitespace / dots) — the canonical shape the
8484        // `#[serde(rename_all = "camelCase")]` derive produces on
8485        // `SupervisorSpec`. A future flip to a non-camelCase attribute
8486        // at the derive surfaces both here (this test fails on the
8487        // stale-constant shape) and at
8488        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
8489        // (that test fails on the mismatch between const and derive).
8490        // Peer with `m2_limits_key_consts_are_lower_camel_case_shape`
8491        // (d8b8b4f) on the sibling M2 `:limits` axis.
8492        for key in [
8493            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
8494            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
8495            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
8496            crate::render::SUPERVISOR_KEY_CHILDREN,
8497        ] {
8498            assert!(
8499                !key.is_empty(),
8500                "SUPERVISOR_KEY_* must be non-empty (got {key:?})"
8501            );
8502            let first = key.chars().next().unwrap();
8503            assert!(
8504                first.is_ascii_lowercase(),
8505                "SUPERVISOR_KEY_* must lead with an ASCII-lowercase byte \
8506                 (got {key:?}, leads with {first:?})",
8507            );
8508            assert!(
8509                key.chars().all(|c| c.is_ascii_alphanumeric()),
8510                "SUPERVISOR_KEY_* must be ASCII-alphanumeric only \
8511                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
8512            );
8513        }
8514    }
8515
8516    #[test]
8517    fn supervisor_key_consts_are_byte_distinct_from_supervisor_author_key_peers() {
8518        // Cross-axis drift pin: the four `SUPERVISOR_KEY_*` consts
8519        // (camelCase JSON keys, no leading colon) must never collide
8520        // byte-for-byte with the four peer `SUPERVISOR_AUTHOR_KEY_*`
8521        // consts (kebab-case author-facing labels with leading colon)
8522        // that sit next to them at `caixa_core::render`. Both families
8523        // cover the same four typed Supervisor slots on two distinct
8524        // axes (author-side kebab vs renderer-side camelCase);
8525        // collapsing either family onto the other's byte-shape would
8526        // silently reroute the render-side probe onto the author-facing
8527        // surface, or vice versa. Peer of the byte-distinctness
8528        // discipline the `M3_PLACEMENT_KEY_ESTRATEGIA` docstring names
8529        // against the peer `M3_AUTHOR_KEY_PLACEMENT`.
8530        let pairs = [
8531            (
8532                crate::render::SUPERVISOR_KEY_ESTRATEGIA,
8533                crate::render::SUPERVISOR_AUTHOR_KEY_ESTRATEGIA,
8534            ),
8535            (
8536                crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
8537                crate::render::SUPERVISOR_AUTHOR_KEY_MAX_RESTARTS,
8538            ),
8539            (
8540                crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
8541                crate::render::SUPERVISOR_AUTHOR_KEY_RESTART_WINDOW,
8542            ),
8543            (
8544                crate::render::SUPERVISOR_KEY_CHILDREN,
8545                crate::render::SUPERVISOR_AUTHOR_KEY_CHILDREN,
8546            ),
8547        ];
8548        for (json_key, author_key) in pairs {
8549            assert_ne!(
8550                json_key, author_key,
8551                "SUPERVISOR_KEY_* (JSON side) must differ byte-for-byte \
8552                 from the peer SUPERVISOR_AUTHOR_KEY_* (author side); \
8553                 got JSON `{json_key}` == author `{author_key}`",
8554            );
8555        }
8556    }
8557
8558    // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_KEY_* identity ──
8559
8560    #[test]
8561    fn child_spec_serde_keys_match_lifted_supervisor_child_key_consts() {
8562        // Load-bearing invariant: the three `SUPERVISOR_CHILD_KEY_*` consts
8563        // (`SUPERVISOR_CHILD_KEY_CAIXA` / `SUPERVISOR_CHILD_KEY_VERSAO` /
8564        // `SUPERVISOR_CHILD_KEY_RESTART`) name the exact camelCase JSON
8565        // keys the `#[serde(rename_all = "camelCase")]` attribute on
8566        // `ChildSpec` emits. Serialize a fully-populated `ChildSpec` and
8567        // pin that each canonical byte-sequence appears verbatim in the
8568        // JSON — a future accidental `rename_all = "snake_case"` /
8569        // `"kebab-case"` / verbatim-field-name flip at the derive
8570        // attribute (any of which would silently break every downstream
8571        // JSON consumer that reaches for one of the three consts via
8572        // `Value::get(...)`) surfaces here as a build-time test failure at
8573        // `supervisor.rs`, not as an apply-time
8574        // `.get(<stale-canonical-const>)` returning `None` far from the
8575        // derive-attr drift's commit. Peer with the enclosing
8576        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
8577        // (40cc4e5) pin on the M2 supervision-tree top-level axis — same
8578        // discipline the SupervisorSpec top-level lift established,
8579        // extended here to the sibling per-`:children` entry `ChildSpec`
8580        // derive so the last M2 typed-struct sub-block
8581        // `#[serde(rename_all = "camelCase")]` axis on the Supervisor
8582        // surface without a lifted serde-key peer joins the substrate's
8583        // "one canonical byte-string per typed serialized-key axis"
8584        // discipline.
8585        let c = ChildSpec {
8586            caixa: "worker".into(),
8587            versao: "^0.1".into(),
8588            restart: RestartPolicy::Permanent,
8589        };
8590        let json = serde_json::to_string(&c).unwrap();
8591        for key in [
8592            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
8593            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
8594            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
8595        ] {
8596            let quoted = format!("\"{key}\"");
8597            assert!(
8598                json.contains(&quoted),
8599                "serialized ChildSpec must carry the lifted \
8600                 SUPERVISOR_CHILD_KEY_* byte-sequence {quoted} verbatim \
8601                 in the JSON emission (got: {json})",
8602            );
8603        }
8604    }
8605
8606    #[test]
8607    fn supervisor_child_key_consts_are_pairwise_distinct() {
8608        // Cross-axis drift-detection pin: a future collapse of two
8609        // canonical `ChildSpec` per-entry byte-strings onto the same
8610        // value (e.g. an accidental copy-paste flip of
8611        // `SUPERVISOR_CHILD_KEY_RESTART` to also read `"caixa"`) would
8612        // silently reroute every downstream probe on one axis onto the
8613        // sibling axis's overlay entry and pass every propagation-probe
8614        // test that expected only the stale axis's value. Peer of the
8615        // sibling three-way distinct pin on the `CONTRATO_KEY_*` triad
8616        // (ca463a4) and the two-way distinct pin on the `MEMBRO_KEY_*`
8617        // pair (ce80ca0).
8618        let all = [
8619            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
8620            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
8621            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
8622        ];
8623        for (i, a) in all.iter().enumerate() {
8624            for b in all.iter().skip(i + 1) {
8625                assert_ne!(
8626                    a, b,
8627                    "SUPERVISOR_CHILD_KEY_* consts must be pairwise-\
8628                     distinct canonical byte-sequences — got `{a}` == `{b}`",
8629                );
8630            }
8631        }
8632    }
8633
8634    #[test]
8635    fn supervisor_child_key_consts_are_lower_camel_case_shape() {
8636        // Shape-pin: every `SUPERVISOR_CHILD_KEY_*` const must be a
8637        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
8638        // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
8639        // capital, no whitespace / dots) — the canonical shape the
8640        // `#[serde(rename_all = "camelCase")]` derive produces on
8641        // `ChildSpec`. A future flip to a non-camelCase attribute at the
8642        // derive surfaces both here (this test fails on the
8643        // stale-constant shape) and at
8644        // `child_spec_serde_keys_match_lifted_supervisor_child_key_consts`
8645        // (that test fails on the mismatch between const and derive).
8646        // Peer with `supervisor_key_consts_are_lower_camel_case_shape`
8647        // (40cc4e5) on the sibling `SupervisorSpec` top-level axis.
8648        for key in [
8649            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
8650            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
8651            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
8652        ] {
8653            assert!(
8654                !key.is_empty(),
8655                "SUPERVISOR_CHILD_KEY_* must be non-empty (got {key:?})"
8656            );
8657            let first = key.chars().next().unwrap();
8658            assert!(
8659                first.is_ascii_lowercase(),
8660                "SUPERVISOR_CHILD_KEY_* must lead with an ASCII-lowercase \
8661                 byte (got {key:?}, leads with {first:?})",
8662            );
8663            assert!(
8664                key.chars().all(|c| c.is_ascii_alphanumeric()),
8665                "SUPERVISOR_CHILD_KEY_* must be ASCII-alphanumeric only \
8666                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
8667            );
8668        }
8669    }
8670
8671    // ── drift-detection: serde-derive-to-SUPERVISOR_ESTRATEGIA_* identity ────
8672
8673    #[test]
8674    fn restart_strategy_variants_serialize_to_lifted_scalar_values() {
8675        // The fail-before-pass-after pin: pre-lift there was no
8676        // single-source binding between the [`RestartStrategy`] variant
8677        // name the un-`rename`d `Serialize` derive emits under
8678        // [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`] and the byte-string
8679        // every downstream cluster-side dispatcher (the future
8680        // wasm-operator's per-supervisor sibling-restart branch, the
8681        // future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
8682        // admission-time enum-arm bind, the `caixa-operator`'s
8683        // hierarchical reconciliation scheduler's per-strategy fan-out)
8684        // probes verbatim. A future `#[serde(rename_all = "kebab-case")]`
8685        // attribute on the enum — or a per-variant `#[serde(rename = "…")]`
8686        // override, or a variant rename in the source — would silently
8687        // rebrand the emitted scalar under one spelling while every
8688        // downstream dispatcher still probed the other, with the failure
8689        // surfacing at the operator's reconcile posture (subtrees coming
8690        // up under the `default()` `OneForOne` arm rather than the typed
8691        // slot's declared strategy — a bad child would then only take
8692        // itself down instead of the sibling set the author intended, so
8693        // shared-state children fall out of sync) far from the source
8694        // rebrand commit and with no field naming the drift. Pinning the
8695        // two paths (the `Serialize` derive's serialized string AND the
8696        // [`RestartStrategy::as_str`] helper) to the same four lifted
8697        // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
8698        // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
8699        // [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
8700        // [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
8701        // byte-strings makes any future drift on either endpoint fail
8702        // here at caixa-core build time. Peer of the M3
8703        // `placement_strategy_variants_serialize_to_lifted_scalar_values`
8704        // (3f0e21c) on the sibling `PlacementStrategy` axis — same
8705        // three-path-convergence discipline, extended to close the
8706        // OTP-shaped per-supervisor sibling-restart axis.
8707        for (variant, expected) in [
8708            (
8709                RestartStrategy::OneForOne,
8710                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
8711            ),
8712            (
8713                RestartStrategy::OneForAll,
8714                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
8715            ),
8716            (
8717                RestartStrategy::RestForOne,
8718                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
8719            ),
8720            (
8721                RestartStrategy::SimpleOneForOne,
8722                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
8723            ),
8724        ] {
8725            let json = serde_json::to_string(&variant).unwrap();
8726            assert_eq!(
8727                json,
8728                format!("\"{expected}\""),
8729                "RestartStrategy::{variant:?} must serialize to {expected:?}"
8730            );
8731            assert_eq!(
8732                variant.as_str(),
8733                expected,
8734                "RestartStrategy::{variant:?}.as_str() must return the lifted \
8735                 SUPERVISOR_ESTRATEGIA_* constant"
8736            );
8737        }
8738    }
8739
8740    #[test]
8741    fn supervisor_estrategia_consts_are_pairwise_distinct() {
8742        // Cross-arm drift-detection pin: a future collapse of two
8743        // canonical variant byte-strings onto the same value (e.g. an
8744        // accidental copy-paste flip of `SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`
8745        // to also read `"OneForOne"`) would silently reroute every
8746        // downstream operator's per-strategy dispatch onto the sibling
8747        // arm's reconcile branch and pass every propagation-probe test
8748        // that expected only the stale arm's value — the mis-strategied
8749        // subtree would come up with the wrong sibling-restart posture
8750        // on every subsequent failure. Peer of the sibling four-way
8751        // distinct pin `supervisor_key_consts_are_pairwise_distinct`
8752        // (40cc4e5) on the top-level `SUPERVISOR_KEY_*` axis.
8753        let all = [
8754            crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
8755            crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
8756            crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
8757            crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
8758        ];
8759        for (i, a) in all.iter().enumerate() {
8760            for (j, b) in all.iter().enumerate() {
8761                if i != j {
8762                    assert_ne!(
8763                        a, b,
8764                        "SUPERVISOR_ESTRATEGIA_* consts must be pairwise distinct \
8765                         — got duplicate {a:?} at indices {i} and {j}",
8766                    );
8767                }
8768            }
8769        }
8770    }
8771
8772    #[test]
8773    fn restart_strategy_display_routes_through_as_str_helper() {
8774        // The fail-before-pass-after pin on the first half of the
8775        // three-path convergence: pre-convergence the sibling
8776        // OTP-shape typed enum [`RestartStrategy`] carried a
8777        // [`std::fmt::Display`] surface via its
8778        // `#[discriminant(also_display)]` gen-platform derive route,
8779        // which arrived kebab-case as `"one-for-one"` /
8780        // `"one-for-all"` / `"rest-for-one"` /
8781        // `"simple-one-for-one"` while the wire format ran as
8782        // PascalCase `"OneForOne"` / `"OneForAll"` / `"RestForOne"` /
8783        // `"SimpleOneForOne"` through the un-`rename`d serde derive.
8784        // Every consumer reaching for a strategy byte-string past the
8785        // wire format had to pick between three paths
8786        // ([`RestartStrategy::as_str`], the `Serialize` derive's
8787        // serialized string, or `format!("{v}")` on the
8788        // discriminant-Display route), any two of which a future
8789        // variant rename or `#[serde(rename_all = "kebab-case")]`
8790        // attribute would silently desynchronize. Wiring
8791        // [`std::fmt::Display`] through [`RestartStrategy::as_str`]
8792        // closes the third path: every `format!("{v}")` call reaches
8793        // the same lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
8794        // const the wire format and the [`RestartStrategy::as_str`]
8795        // helper already route through, so a future variant rename
8796        // lands at exactly one place. Pin the routing here so a future
8797        // `impl std::fmt::Display for RestartStrategy`
8798        // reimplementation that hand-rolls the arms instead of
8799        // delegating to [`RestartStrategy::as_str`] fails at
8800        // caixa-core build time. Peer of the M3
8801        // `placement_strategy_display_routes_through_as_str_helper`
8802        // (cc8f749) which the M3 axis converged first.
8803        for &variant in RestartStrategy::ALL {
8804            assert_eq!(
8805                variant.to_string(),
8806                variant.as_str(),
8807                "RestartStrategy::{variant:?} Display must route through \
8808                 RestartStrategy::as_str (single source of truth: the lifted \
8809                 SUPERVISOR_ESTRATEGIA_* const the wire format also emits)"
8810            );
8811        }
8812    }
8813
8814    #[test]
8815    fn restart_strategy_display_matches_serialized_wire_byte_string() {
8816        // The fail-before-pass-after pin on the second half of the
8817        // three-path convergence: `Display` (user-facing text) agrees
8818        // byte-for-byte with the `Serialize` derive's wire format
8819        // (canonical camelCase-schema `SUPERVISOR_KEY_ESTRATEGIA`
8820        // scalar) on every variant. Pre-convergence the two paths
8821        // were structurally independent — a future
8822        // `#[serde(rename_all = "kebab-case")]` attribute on the
8823        // enum would silently rebrand the emitted wire scalar
8824        // (`one-for-one`, `one-for-all`, `rest-for-one`,
8825        // `simple-one-for-one`) while every consumer that
8826        // pretty-prints the strategy (the future wasm-operator's
8827        // per-supervisor sibling-restart-strategy diagnostic line,
8828        // the future `feira app graph` per-supervisor strategy line,
8829        // the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
8830        // materializer's admission-webhook rejection body) would
8831        // still emit the PascalCase form the `as_str` / `Display`
8832        // route returns, with the mismatch surfacing at consumer
8833        // parse time / operator dispatch time far from the source
8834        // rebrand commit. Pin the two paths byte-for-byte here so any
8835        // future serde-attribute or variant-rename drift is a
8836        // caixa-core-build-time test failure at this call, not a
8837        // silent per-consumer dispatch miss. Peer of the M3
8838        // `placement_strategy_display_matches_serialized_wire_byte_string`
8839        // (cc8f749) which the M3 axis converged first.
8840        for &variant in RestartStrategy::ALL {
8841            let wire = serde_json::to_string(&variant).unwrap();
8842            let unquoted = wire
8843                .strip_prefix('"')
8844                .and_then(|s| s.strip_suffix('"'))
8845                .expect("serialized RestartStrategy is a JSON string");
8846            assert_eq!(
8847                variant.to_string(),
8848                unquoted,
8849                "RestartStrategy::{variant:?} Display byte-string must match the \
8850                 Serialize derive's wire byte-string (three-path convergence: \
8851                 Display + as_str + Serialize all resolve to the same \
8852                 SUPERVISOR_ESTRATEGIA_* const)"
8853            );
8854        }
8855    }
8856
8857    #[test]
8858    fn restart_strategy_as_ref_str_routes_through_as_str_accessor() {
8859        // Fail-before-pass-after byte-parity pin on the lifted
8860        // `impl AsRef<str> for RestartStrategy` — asserts the
8861        // standard-library trait impl and the substrate-primitive
8862        // [`RestartStrategy::as_str`] `pub const fn` accessor resolve
8863        // to the same `&str` per instance across the four-arm
8864        // closed set, so any future silent detour that routes the
8865        // impl through a divergent projection (a per-arm inline
8866        // `match self { RestartStrategy::OneForOne => "OneForOne", … }`
8867        // re-inlining that opens a compile-time link to the un-lifted
8868        // arm-literal, a swap onto the kebab-case
8869        // [`gen_platform::Discriminant`] catalog identity that would
8870        // collide the wire axis with the dispatcher-catalog axis) trips
8871        // at caixa-core test time under `PartialEq` rather than at a
8872        // downstream `impl AsRef<str>`-bound consumer's silent split.
8873        // Sweeps every one of the four arms
8874        // [`RestartStrategy::ALL`] carries so no arm's projection is
8875        // covered only by the sibling wire-format `Serialize` derive
8876        // path. Peer of the sibling
8877        // [`crate::version::tests::caixa_version_as_ref_str_routes_through_as_str_accessor`]
8878        // (16d5c7e) `AsRef<str>`-byte-parity pin on the paired
8879        // top-level `:versao` typed newtype — the two pins together
8880        // cover the substrate primitive's `AsRef<str>` projection axis
8881        // on the paired newtype + closed-set-typed-enum surface.
8882        for &variant in RestartStrategy::ALL {
8883            assert_eq!(
8884                <RestartStrategy as AsRef<str>>::as_ref(&variant),
8885                variant.as_str(),
8886                "AsRef<str> impl on RestartStrategy::{variant:?} must \
8887                 byte-equal RestartStrategy::as_str on the same instance \
8888                 — divergence signals a silent detour off the substrate-\
8889                 primitive accessor"
8890            );
8891        }
8892    }
8893
8894    #[test]
8895    fn restart_strategy_as_ref_str_routes_through_display_via_shared_accessor() {
8896        // Fail-before-pass-after byte-parity pin on the three-path
8897        // convergence discipline the M2 sibling-restart primitive now
8898        // carries on the `&str`-projection axis:
8899        // `<RestartStrategy as AsRef<str>>::as_ref(&s)` (the newly
8900        // lifted impl), `format!("{s}")` (the pre-existing
8901        // [`fmt::Display`] impl), and `s.as_str()` (the substrate-
8902        // primitive `pub const fn` accessor both trait impls delegate
8903        // through) must resolve to the same byte-string on every
8904        // instance across the four-arm closed set. Refuses any future
8905        // divergence between the two trait impls (a stray
8906        // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
8907        // rather than delegating through the shared accessor; a
8908        // hypothetical `AsRef<str>` rewrite that inlines a per-arm
8909        // literal cascade) that would silently split the two
8910        // projection paths of the same closed-set typed enum. Mirrors
8911        // the sibling three-path-convergence discipline the peer
8912        // [`crate::CaixaVersion`] typed newtype carries on its
8913        // `AsRef<str>` / `Display` / `as_str` triple
8914        // (version.rs pin
8915        // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
8916        // 16d5c7e).
8917        for &variant in RestartStrategy::ALL {
8918            let via_as_ref: &str = <RestartStrategy as AsRef<str>>::as_ref(&variant);
8919            let via_display: String = format!("{variant}");
8920            let via_accessor: &str = variant.as_str();
8921            assert_eq!(via_as_ref, via_accessor);
8922            assert_eq!(via_display, via_accessor);
8923            assert_eq!(via_as_ref, via_display.as_str());
8924        }
8925    }
8926
8927    #[test]
8928    fn restart_strategy_all_enumerates_every_variant_exactly_once() {
8929        // Fail-before-pass-after pin on the [`RestartStrategy::ALL`]
8930        // exhaustive-iteration surface: every variant appears exactly
8931        // once, and the slice length matches the arm count of the
8932        // closed set. Every consumer that walks the accepted-strategy
8933        // set (a future `feira supervisor --estrategia …` CLI-side
8934        // arg-parse's "did you mean" hint, a future M4 admission-
8935        // webhook's rejection body naming the accepted-`:estrategia`
8936        // list, the [`RestartStrategy::from_wire`] reverse-projection
8937        // consumers that iterate the accept-set for diagnostic
8938        // rendering) reads through this slice, so a future arm addition
8939        // that grows the enum but forgets to grow [`Self::ALL`]
8940        // silently truncates every downstream consumer's accept-set at
8941        // the same pre-addition boundary — this pin fails at caixa-core
8942        // build time on the pairwise-distinct + arm-count invariants.
8943        //
8944        // Peer of the sibling [`crate::CaixaKind::ALL`] (6b1f4fb) /
8945        // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
8946        // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
8947        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
8948        // pins on the peer closed-set typed-enum axes.
8949        let all: &[RestartStrategy] = RestartStrategy::ALL;
8950        assert_eq!(
8951            all.len(),
8952            4,
8953            "RestartStrategy::ALL must enumerate every variant of the \
8954             four-arm closed set (OneForOne, OneForAll, RestForOne, \
8955             SimpleOneForOne); got {all:?}"
8956        );
8957        for (i, a) in all.iter().enumerate() {
8958            for (j, b) in all.iter().enumerate() {
8959                if i != j {
8960                    assert_ne!(
8961                        a, b,
8962                        "RestartStrategy::ALL must carry every variant exactly \
8963                         once — got duplicate {a:?} at indices {i} and {j}"
8964                    );
8965                }
8966            }
8967        }
8968        for variant in [
8969            RestartStrategy::OneForOne,
8970            RestartStrategy::OneForAll,
8971            RestartStrategy::RestForOne,
8972            RestartStrategy::SimpleOneForOne,
8973        ] {
8974            assert!(
8975                all.contains(&variant),
8976                "RestartStrategy::ALL must contain {variant:?} — a future arm \
8977                 addition that grows the enum but forgets to grow the ALL slice \
8978                 silently truncates every downstream consumer's accept-set at \
8979                 the pre-addition boundary"
8980            );
8981        }
8982    }
8983
8984    #[test]
8985    fn restart_strategy_wire_names_covers_every_arm() {
8986        // Load-bearing pin on the substrate-canonical
8987        // [`RestartStrategy::WIRE_NAMES`] exhaustive accept-set roster
8988        // on the `PascalCase` wire byte-string axis: every variant of
8989        // the sibling [`RestartStrategy::ALL`] exhaustive-iteration
8990        // surface must project through [`RestartStrategy::as_str`] onto
8991        // an entry the [`RestartStrategy::WIRE_NAMES`] roster carries,
8992        // and the roster's length must byte-equal
8993        // `RestartStrategy::ALL.len()` so a silent skew between the
8994        // [`RestartStrategy::as_str`] match's arm-set and the roster's
8995        // arm-set trips here at caixa-core test time rather than at a
8996        // downstream M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
8997        // admission-webhook rejection body's wire-form `:estrategia`
8998        // accepted-set enumeration miss / a `feira supervisor
8999        // --estrategia …` "did you mean" hint drift / a future
9000        // wasm-operator per-reconcile-step diagnostic log line's
9001        // accepted-wire-form enumeration miss. A future arm addition
9002        // (an OTP-`rest_for_all` arm the theory
9003        // [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
9004        // might reach for once the four canonical OTP strategies stop
9005        // covering the substrate's discovered load-shape) extends
9006        // [`RestartStrategy::ALL`] as a single edit and this pin
9007        // sweeps the new arm by iteration; the paired
9008        // [`RestartStrategy::WIRE_NAMES`] roster must grow in lockstep
9009        // or this assertion trips. Every entry is further pinned to
9010        // open with an ASCII uppercase byte so a silent collapse of
9011        // the wire-form axis with the peer kebab-case
9012        // dispatcher-catalog axis (an entry byte-identical to a
9013        // sibling [`Self::discriminant`] kebab byte-string that would
9014        // let a wire-axis consumer accept the dispatcher-catalog
9015        // vocabulary) trips here rather than at a downstream K8s-CR
9016        // round-trip miss.
9017        //
9018        // Peer of the sibling
9019        // [`crate::kind::tests::caixa_kind_wire_names_covers_every_arm`]
9020        // (bd708bd) pin on the top-level typed-kind discriminator's
9021        // `PascalCase` wire byte-string axis, and of the sibling
9022        // [`crate::upgrade::tests::upgrade_instruction_wire_forms_covers_every_arm`]
9023        // (cc42c0e) /
9024        // [`crate::upgrade::tests::upgrade_instruction_lisp_forms_covers_every_arm`]
9025        // (1898d77) pins on the OTP-appup discriminator's two-axis
9026        // roster split — the same closed-set exhaustive-roster
9027        // coverage discipline extended here onto the first M2
9028        // OTP-shape sibling-restart closed-set typed enum.
9029        //
9030        // Fail-before-pass-after locally verified by mutating one arm
9031        // of the paired [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
9032        // const family (e.g. dropping the trailing `e` from
9033        // `"OneForOne"` → `"OneForOn"`) — the length pin still passes
9034        // but the `contains` check fires on the mutated arm; and by
9035        // shortening the roster to three entries — the length pin
9036        // fires first.
9037        assert_eq!(
9038            RestartStrategy::WIRE_NAMES.len(),
9039            RestartStrategy::ALL.len(),
9040            "RestartStrategy::WIRE_NAMES.len() must byte-equal \
9041             RestartStrategy::ALL.len() — a mismatch means the roster \
9042             and the enum's arm-set have drifted; downstream consumers \
9043             that fan through both will silently disagree on the \
9044             accepted arm-set"
9045        );
9046        for &variant in RestartStrategy::ALL {
9047            let wire = variant.as_str();
9048            assert!(
9049                RestartStrategy::WIRE_NAMES.contains(&wire),
9050                "RestartStrategy::{variant:?}.as_str() = {wire:?} must \
9051                 be a member of RestartStrategy::WIRE_NAMES — the \
9052                 emitter and the roster have drifted out of lockstep"
9053            );
9054        }
9055        for tag in RestartStrategy::WIRE_NAMES {
9056            let first = tag.chars().next().unwrap_or_else(|| {
9057                panic!(
9058                    "RestartStrategy::WIRE_NAMES entry {tag:?} must be \
9059                     a non-empty PascalCase byte-string"
9060                )
9061            });
9062            assert!(
9063                first.is_ascii_uppercase(),
9064                "RestartStrategy::WIRE_NAMES entry {tag:?} must open \
9065                 with an ASCII uppercase byte (PascalCase wire form) — \
9066                 a lowercase entry would collide the wire-form axis \
9067                 with the peer kebab-case dispatcher-catalog axis \
9068                 [`RestartStrategy::discriminant`] serves"
9069            );
9070        }
9071    }
9072
9073    #[test]
9074    fn restart_strategy_from_wire_accepts_every_lifted_constant() {
9075        // Fail-before-pass-after pin on the forward accept-set of the
9076        // [`RestartStrategy::from_wire`] reverse projection: every
9077        // canonical [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
9078        // constant the [`RestartStrategy::as_str`] emitter walks parses
9079        // back to its paired variant. Any future arm addition that
9080        // grows the emitter's `as_str` match but forgets to grow the
9081        // parser's `from_wire` match silently splits the two halves of
9082        // the round-trip — the wire byte-string one non-serde consumer
9083        // parses from the one the emitter wrote — with the failure
9084        // surfacing at parse time far from the rebrand commit. Pinning
9085        // the four-arm accept-set here catches the drift at caixa-core
9086        // build time.
9087        //
9088        // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
9089        // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
9090        // accept-set pins on the peer closed-set typed-enum `str → Self`
9091        // axes.
9092        for (wire, expected) in [
9093            (
9094                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
9095                RestartStrategy::OneForOne,
9096            ),
9097            (
9098                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
9099                RestartStrategy::OneForAll,
9100            ),
9101            (
9102                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
9103                RestartStrategy::RestForOne,
9104            ),
9105            (
9106                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
9107                RestartStrategy::SimpleOneForOne,
9108            ),
9109        ] {
9110            let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
9111                panic!(
9112                    "RestartStrategy::from_wire({wire:?}) must accept every \
9113                     SUPERVISOR_ESTRATEGIA_* constant — got None for the \
9114                     lifted canonical byte-string that RestartStrategy::{expected:?} \
9115                     serializes as under SUPERVISOR_KEY_ESTRATEGIA"
9116                )
9117            });
9118            assert_eq!(
9119                parsed, expected,
9120                "RestartStrategy::from_wire({wire:?}) must return \
9121                 RestartStrategy::{expected:?}; got RestartStrategy::{parsed:?}"
9122            );
9123        }
9124    }
9125
9126    #[test]
9127    fn restart_strategy_from_wire_round_trips_through_as_str() {
9128        // Fail-before-pass-after pin on the closed round-trip between
9129        // the forward [`RestartStrategy::as_str`] emitter and the
9130        // reverse [`RestartStrategy::from_wire`] parser: for every
9131        // variant in [`RestartStrategy::ALL`], parsing the emitter's
9132        // output must return exactly the same variant. Any per-arm
9133        // divergence — a future arm added to `as_str` but not
9134        // `from_wire`, an accidental copy-paste flip in one but not
9135        // the other — silently splits the emit and parse halves and
9136        // the failure surfaces at consumer parse time far from the
9137        // drift site. The `ALL`-iterating shape means a future arm
9138        // addition picks up the coverage by construction.
9139        //
9140        // Peer of the sibling
9141        // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
9142        // (18c7342) round-trip pin on
9143        // [`crate::aplicacao::PlacementStrategy::from_wire`] and
9144        // [`crate::kind::tests::caixa_kind_wire_round_trips_through_from_wire`]
9145        // (6b1f4fb) round-trip pin on [`crate::CaixaKind::from_wire`].
9146        for &variant in RestartStrategy::ALL {
9147            let wire = variant.as_str();
9148            let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
9149                panic!(
9150                    "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
9151                     must be Some({variant:?}) — the two halves of the round-trip \
9152                     dispatch on the same lifted SUPERVISOR_ESTRATEGIA_* consts; \
9153                     got None on wire byte-string {wire:?}"
9154                )
9155            });
9156            assert_eq!(
9157                parsed, variant,
9158                "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
9159                 must round-trip to the same variant; got {parsed:?}"
9160            );
9161        }
9162    }
9163
9164    #[test]
9165    fn restart_strategy_from_wire_rejects_unknown_byte_strings() {
9166        // Fail-before-pass-after pin on the closed-set refusal
9167        // discipline of [`RestartStrategy::from_wire`]: every
9168        // byte-string outside the four-arm accept-set returns `None`
9169        // rather than silently collapsing onto the [`Default`]
9170        // (`OneForOne`) arm or an arbitrary neighbor. The refusal set
9171        // exercised here sweeps the load-bearing drift shapes: the
9172        // empty string (a stripped serde-attribute drift), all-
9173        // whitespace strings (the canonical text-editor accidental
9174        // padding shape), the kebab-case dispatcher-catalog identities
9175        // (`"one-for-one"` / `"one-for-all"` / `"rest-for-one"` /
9176        // `"simple-one-for-one"` — the [`gen_platform::FromStrKind`]-
9177        // derived [`std::str::FromStr`] accept-set, which parses the
9178        // *other* axis of this enum's two-axis split and must not leak
9179        // into the `from_wire` PascalCase-wire accept-set), the
9180        // lowercased single-word forms (`"oneforone"`), the padded
9181        // canonical scalar (`" OneForOne "`), the trailing-newline
9182        // shapes (`"OneForOne\n"`), and neighboring-but-unknown arms
9183        // (`"AllForOne"` — the canonical typo direction).
9184        //
9185        // Peer of the sibling
9186        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
9187        // (2aa6d23) +
9188        // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
9189        // (18c7342) refusal pins on the peer closed-set typed-enum
9190        // axes.
9191        for bad in [
9192            "",
9193            " ",
9194            "\n",
9195            "\t",
9196            "one-for-one",
9197            "one-for-all",
9198            "rest-for-one",
9199            "simple-one-for-one",
9200            "oneforone",
9201            "OneForOnes",
9202            "one_for_one",
9203            "one for one",
9204            "ONEFORONE",
9205            "OneForOne ",
9206            " OneForOne",
9207            " SimpleOneForOne ",
9208            "OneForOne\n",
9209            "restforone",
9210            "REST_FOR_ONE",
9211            "AllForOne",
9212            "Simple",
9213            "?",
9214        ] {
9215            assert!(
9216                RestartStrategy::from_wire(bad).is_none(),
9217                "RestartStrategy::from_wire({bad:?}) must return None — the \
9218                 parser's accept-set is exactly the four RestartStrategy::as_str \
9219                 outputs (OneForOne, OneForAll, RestForOne, SimpleOneForOne), \
9220                 and this byte-string is outside that closed set"
9221            );
9222        }
9223    }
9224
9225    #[test]
9226    fn restart_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
9227        // Fail-before-pass-after pin on the fourth path of the four-path
9228        // convergence: `from_wire` (the reverse projection) inverts the
9229        // `Serialize` derive's wire byte-string on every variant.
9230        // Together with the pre-existing three-path convergence
9231        // (`Display` + `as_str` + `Serialize` all resolve to the same
9232        // lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const,
9233        // pinned by
9234        // [`restart_strategy_display_matches_serialized_wire_byte_string`])
9235        // this closes the round-trip: the wire byte-string the
9236        // `Serialize` derive emits parses back to the same variant
9237        // through `from_wire`, so any future serde-attribute or variant-
9238        // rename drift on the emit half now surfaces as a matched drift
9239        // on the parse half at caixa-core build time — the two halves
9240        // migrate as a unit through the lifted consts on any future
9241        // rename, and the round-trip cannot silently split.
9242        //
9243        // Peer of the sibling
9244        // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
9245        // (18c7342) wire-format pin on
9246        // [`crate::aplicacao::PlacementStrategy::from_wire`].
9247        for &variant in RestartStrategy::ALL {
9248            let wire = serde_json::to_string(&variant).unwrap();
9249            let unquoted = wire
9250                .strip_prefix('"')
9251                .and_then(|s| s.strip_suffix('"'))
9252                .expect("serialized RestartStrategy is a JSON string");
9253            let parsed = RestartStrategy::from_wire(unquoted).unwrap_or_else(|| {
9254                panic!(
9255                    "RestartStrategy::from_wire({unquoted:?}) must accept the \
9256                     Serialize derive's wire byte-string for \
9257                     RestartStrategy::{variant:?} — the four-path convergence \
9258                     (Display + as_str + Serialize + from_wire) resolves through \
9259                     the same lifted SUPERVISOR_ESTRATEGIA_* const; got None"
9260                )
9261            });
9262            assert_eq!(
9263                parsed, variant,
9264                "RestartStrategy::from_wire of the Serialize derive's wire \
9265                 byte-string for RestartStrategy::{variant:?} must round-trip \
9266                 to the same variant; got {parsed:?}"
9267            );
9268        }
9269    }
9270
9271    #[test]
9272    fn restart_strategy_try_from_str_routes_through_from_wire_accessor() {
9273        // Fail-before-pass-after byte-parity pin on the newly lifted
9274        // `impl TryFrom<&str> for RestartStrategy` — asserts the standard-
9275        // library trait impl and the substrate-primitive
9276        // [`RestartStrategy::from_wire`] `Option<Self>` accessor resolve to
9277        // the same four-arm accept-set across every arm the exhaustive
9278        // [`RestartStrategy::ALL`] slice enumerates. Any future silent
9279        // detour that routes the trait impl through a divergent projection
9280        // (a per-arm inline `match s { "OneForOne" => Ok(Self::OneForOne),
9281        // … }` re-inlining that opens a compile-time link to the un-
9282        // lifted arm-literal, a hypothetical `#[serde(rename_all = "…")]`
9283        // attribute drift that silently splits the wire byte-string from
9284        // every consumer that reaches for this typed dispatch, an
9285        // accidental swap onto the kebab-case dispatcher-catalog axis the
9286        // pre-existing [`std::str::FromStr`] impl parses through and which
9287        // would collide the two-axis wire/catalog split the sibling
9288        // [`RestartStrategy::from_wire`] doc block makes load-bearing)
9289        // trips at caixa-core test time under `assert_eq!` rather than at
9290        // a downstream `impl TryFrom<&str>`-bound consumer's silent split.
9291        // Sweeps every one of the four arms [`RestartStrategy::ALL`]
9292        // carries so no arm's projection is covered only by the sibling
9293        // method-named `from_wire` path. Peer of the sibling
9294        // [`crate::kind::tests::caixa_kind_try_from_str_routes_through_from_wire_accessor`]
9295        // (3c83606),
9296        // [`crate::dialeto::tests::caixa_dialeto_try_from_str_routes_through_from_wire_accessor`]
9297        // (bf33136), and the M3
9298        // [`crate::aplicacao::tests::placement_strategy_try_from_str_routes_through_from_wire_accessor`]
9299        // (6fd00cd) — extends the trait-idiomatic reverse-projection axis
9300        // onto the first M2-OTP-shape closed-set typed enum on the caixa
9301        // surface.
9302        for &variant in RestartStrategy::ALL {
9303            let wire = variant.as_str();
9304            assert_eq!(
9305                <RestartStrategy as TryFrom<&str>>::try_from(wire),
9306                Ok(variant),
9307                "TryFrom<&str> impl on RestartStrategy must round-trip \
9308                 RestartStrategy::{variant:?}.as_str() = {wire:?} back to \
9309                 Ok(RestartStrategy::{variant:?}) — divergence from \
9310                 RestartStrategy::from_wire signals a silent detour off \
9311                 the substrate-primitive accessor"
9312            );
9313            assert_eq!(
9314                <RestartStrategy as TryFrom<&str>>::try_from(wire).ok(),
9315                RestartStrategy::from_wire(wire),
9316                "TryFrom<&str> ok()-projection on {wire:?} must byte-equal \
9317                 RestartStrategy::from_wire on the same input"
9318            );
9319        }
9320    }
9321
9322    #[test]
9323    fn restart_strategy_try_from_str_rejects_unknown_byte_strings() {
9324        // Rejection witness on the `impl TryFrom<&str> for
9325        // RestartStrategy` — sweeps a candidate set of byte-strings
9326        // outside the four-arm PascalCase wire accept-set the sibling
9327        // [`RestartStrategy::as_str`] emits and asserts every one lands on
9328        // `Err(())`, so a future accidental widening of the trait impl's
9329        // accept-set (a stray additional
9330        // `_ if s.eq_ignore_ascii_case("OneForOne") => Ok(…)` case-fold
9331        // path, a silent inclusion of the kebab-case dispatcher-catalog
9332        // byte-string the pre-existing [`std::str::FromStr`] impl the
9333        // [`gen_platform::FromStrKind`] derive installs parses onto the
9334        // wire axis — which would collide the two-axis
9335        // wire/dispatcher-catalog split the sibling
9336        // [`RestartStrategy::from_wire`] doc block makes load-bearing —
9337        // an English-rebrand or plural-arm silent alias that would
9338        // widen the wire accept-set past the OTP-canonical four) trips at
9339        // caixa-core test time. The candidate set includes the empty
9340        // string, whitespace-only padding, the kebab-case dispatcher-
9341        // catalog byte-strings on the sibling axis (a caller who confuses
9342        // the two axes trips here rather than at a downstream consumer's
9343        // silent reject), a lowercase / uppercase / mixed-case fold of
9344        // each PascalCase arm (a caller who assumes case-fold acceptance
9345        // trips here), leading/trailing whitespace padding, the trailing-
9346        // newline shape, quote-wrapped candidates, and a residual set of
9347        // plausible-but-wrong English rebrand candidates. Peer of the
9348        // sibling
9349        // [`crate::kind::tests::caixa_kind_try_from_str_rejects_unknown_byte_strings`]
9350        // (3c83606) and
9351        // [`crate::aplicacao::tests::placement_strategy_try_from_str_rejects_unknown_byte_strings`]
9352        // (6fd00cd) rejection witnesses.
9353        let rejected: &[&str] = &[
9354            "",
9355            " ",
9356            "\n",
9357            "\t",
9358            "one-for-one",
9359            "one-for-all",
9360            "rest-for-one",
9361            "simple-one-for-one",
9362            "oneforone",
9363            "one_for_one",
9364            "OneForOnes",
9365            "ONEFORONE",
9366            "oneforall",
9367            "restforone",
9368            "simpleoneforone",
9369            "OneForOne ",
9370            " OneForOne",
9371            " OneForAll ",
9372            "OneForOne\n",
9373            "RestForOne\t",
9374            "OneForEach",
9375            "AllForOne",
9376            "one for one",
9377            "\"OneForOne\"",
9378            "?",
9379        ];
9380        for &input in rejected {
9381            assert_eq!(
9382                <RestartStrategy as TryFrom<&str>>::try_from(input),
9383                Err(()),
9384                "TryFrom<&str> impl on RestartStrategy must reject the \
9385                 non-wire byte-string {input:?} — silent acceptance signals \
9386                 an accept-set widening off the paired \
9387                 RestartStrategy::from_wire resolver"
9388            );
9389        }
9390    }
9391
9392    #[test]
9393    fn restart_strategy_try_from_str_and_from_wire_partition_the_accept_set() {
9394        // Cross-axis partition pin: the paired `TryFrom<&str>` and
9395        // `from_wire` reverse projections must resolve identically on
9396        // *every* input, not just the ones [`RestartStrategy::ALL`]
9397        // enumerates. Sweeps a mixed candidate set spanning accepted
9398        // (four-arm PascalCase wire byte-strings) and rejected (kebab-case
9399        // dispatcher-catalog byte-strings, empty, whitespace-padded,
9400        // quoted, English-rebrand candidates) inputs and asserts the
9401        // trait's `Result::ok()` projection byte-equals the method-named
9402        // resolver's `Option<Self>` return-shape on each, locking the two
9403        // paths together by construction so any future detour (a stray
9404        // `try_from` special-case that widens or narrows the accept-set
9405        // outside the paired `from_wire` resolver, an accidental swap
9406        // onto the kebab-case [`std::str::FromStr`] impl the
9407        // [`gen_platform::FromStrKind`] derive installs on the sibling
9408        // dispatcher-catalog axis) trips at caixa-core test time. Peer of
9409        // the sibling
9410        // [`crate::kind::tests::caixa_kind_try_from_str_and_from_wire_partition_the_accept_set`]
9411        // pin — extends the round-trip discipline onto the M2-OTP-shape
9412        // sibling-restart axis.
9413        let candidates: &[&str] = &[
9414            "OneForOne",
9415            "OneForAll",
9416            "RestForOne",
9417            "SimpleOneForOne",
9418            "",
9419            "one-for-one",
9420            "one-for-all",
9421            "rest-for-one",
9422            "simple-one-for-one",
9423            "oneforone",
9424            "unknown",
9425            "OneForOne ",
9426            " OneForOne",
9427            "\"OneForOne\"",
9428            "OneForEach",
9429            "?",
9430        ];
9431        for &input in candidates {
9432            let via_trait: Option<RestartStrategy> =
9433                <RestartStrategy as TryFrom<&str>>::try_from(input).ok();
9434            let via_method: Option<RestartStrategy> = RestartStrategy::from_wire(input);
9435            assert_eq!(
9436                via_trait, via_method,
9437                "TryFrom<&str> and from_wire must resolve identically on \
9438                 input {input:?} — divergence signals the two reverse-\
9439                 projection paths have drifted onto different accept-sets"
9440            );
9441        }
9442    }
9443
9444    #[test]
9445    fn restart_strategy_from_into_static_str_routes_through_as_str_accessor() {
9446        // Fail-before-pass-after byte-parity pin on the newly lifted
9447        // `impl From<RestartStrategy> for &'static str` — asserts the
9448        // standard-library trait impl and the substrate-primitive
9449        // [`RestartStrategy::as_str`] `pub const fn` accessor resolve to
9450        // the same four-arm emit-set across every arm the exhaustive
9451        // [`RestartStrategy::ALL`] slice enumerates. Any future silent
9452        // detour that routes the trait impl through a divergent
9453        // projection (a per-arm inline `match strategy { OneForOne =>
9454        // "OneForOne", … }` re-inlining that opens a compile-time link to
9455        // the un-lifted arm-literal, an accidental swap onto the sibling
9456        // kebab-case [`Self::discriminant`] dispatcher-catalog axis that
9457        // would collide the two-axis wire/catalog split the sibling
9458        // [`RestartStrategy::from_wire`] doc block makes load-bearing) trips
9459        // at caixa-core test time under `assert_eq!` rather than at a
9460        // downstream `impl Into<&'static str>`-bound consumer's silent
9461        // split. Sweeps every one of the four arms
9462        // [`RestartStrategy::ALL`] carries so no arm's projection is
9463        // covered only by the sibling method-named `as_str` /
9464        // [`std::fmt::Display`] / [`AsRef<str>`] paths. Materializes the
9465        // `<&'static str as From<RestartStrategy>>::from` output in a
9466        // `const`-shape binding to make the `'static` lifetime promise a
9467        // build-time invariant — a future accidental downgrade of any of
9468        // the four arms' [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
9469        // constants to a non-`&'static str` (a `String::leak()`-produced
9470        // return, a `Box::leak`-cast) trips at caixa-core build time
9471        // rather than at a downstream `'static`-bound consumer.
9472        const ONE_FOR_ONE: &str = RestartStrategy::OneForOne.as_str();
9473        const ONE_FOR_ALL: &str = RestartStrategy::OneForAll.as_str();
9474        const REST_FOR_ONE: &str = RestartStrategy::RestForOne.as_str();
9475        const SIMPLE_ONE_FOR_ONE: &str = RestartStrategy::SimpleOneForOne.as_str();
9476        for &variant in RestartStrategy::ALL {
9477            let via_trait: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
9478            let via_method: &'static str = variant.as_str();
9479            assert_eq!(
9480                via_trait, via_method,
9481                "From<RestartStrategy> for &'static str impl must round-trip \
9482                 RestartStrategy::{variant:?} to the same lifted \
9483                 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str returns — \
9484                 divergence signals a silent detour off the substrate-primitive \
9485                 accessor"
9486            );
9487            let via_into: &'static str = variant.into();
9488            assert_eq!(
9489                via_into, via_method,
9490                "Into<&'static str>::into on RestartStrategy::{variant:?} must \
9491                 byte-equal RestartStrategy::as_str on the same input — the \
9492                 blanket-derived Into shape must resolve to the same as_str \
9493                 dispatch as the explicit From impl"
9494            );
9495        }
9496        assert_eq!(
9497            [ONE_FOR_ONE, ONE_FOR_ALL, REST_FOR_ONE, SIMPLE_ONE_FOR_ONE],
9498            [
9499                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
9500                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
9501                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
9502                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
9503            ],
9504            "const-context RestartStrategy::as_str must resolve to the four \
9505             lifted SUPERVISOR_ESTRATEGIA_* consts — a future accidental \
9506             downgrade of any arm to a non-const or non-static byte-string \
9507             breaks the `&'static str`-lifetime promise the paired \
9508             From<RestartStrategy> for &'static str impl carries by \
9509             construction"
9510        );
9511    }
9512
9513    #[test]
9514    fn restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set() {
9515        // Cross-axis partition pin: the paired trait-idiomatic
9516        // `From<RestartStrategy> for &'static str` forward projection and
9517        // the method-named [`RestartStrategy::as_str`] forward projection
9518        // must resolve identically on *every* arm, not just the ones
9519        // named in the primary byte-parity pin above. Sweeps every
9520        // [`RestartStrategy::ALL`] arm and asserts the trait's `From::from`
9521        // output byte-equals the method-named accessor's return-value on
9522        // each, locking the two forward-projection paths together by
9523        // construction so any future detour (a stray `From` special-case
9524        // that lands on a divergent per-arm literal outside the paired
9525        // `as_str` dispatch, a hypothetical rebrand touching one axis
9526        // without the other) trips at caixa-core test time. Peer of the
9527        // sibling reverse-projection partition pin
9528        // [`restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
9529        // — extends the round-trip discipline onto the trait-idiomatic
9530        // *forward* axis, closing the two-way `Self ↔ &'static str`
9531        // round-trip on the trait-idiomatic pair
9532        // (`From<Self> for &'static str` + `TryFrom<&str> for Self`) as
9533        // well as the pre-existing method-named pair
9534        // (`as_str` + `from_wire`).
9535        for &variant in RestartStrategy::ALL {
9536            let via_trait: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
9537            let via_method: &'static str = variant.as_str();
9538            assert_eq!(
9539                via_trait, via_method,
9540                "From<RestartStrategy> for &'static str and \
9541                 RestartStrategy::as_str must resolve identically on \
9542                 RestartStrategy::{variant:?} — divergence signals the \
9543                 two forward-projection paths have drifted onto different \
9544                 emit-sets"
9545            );
9546        }
9547        // Round-trip witness: every arm's forward `From` output re-parses
9548        // through the paired trait-idiomatic reverse `TryFrom<&str>` back
9549        // to the original variant. Closes the two-way `RestartStrategy ↔
9550        // &'static str` round-trip on the trait-idiomatic axis pair,
9551        // mirroring the pre-existing method-named `as_str` + `from_wire`
9552        // round-trip on the substrate-primitive axis pair.
9553        for &variant in RestartStrategy::ALL {
9554            let emitted: &'static str = variant.into();
9555            let re_parsed: Result<RestartStrategy, ()> =
9556                <RestartStrategy as TryFrom<&str>>::try_from(emitted);
9557            assert_eq!(
9558                re_parsed,
9559                Ok(variant),
9560                "trait-idiomatic axis pair must round-trip \
9561                 RestartStrategy::{variant:?} through `.into::<&'static \
9562                 str>()` and back through `TryFrom<&str>` — a break signals \
9563                 the forward-emit and reverse-parse axes have drifted onto \
9564                 different vocabularies"
9565            );
9566        }
9567    }
9568
9569    #[test]
9570    fn restart_strategy_from_borrowed_into_static_str_routes_through_as_str_accessor() {
9571        // Fail-before-pass-after byte-parity pin on the newly lifted
9572        // `impl From<&RestartStrategy> for &'static str` — asserts the
9573        // borrowed-input standard-library trait impl and the substrate-
9574        // primitive [`RestartStrategy::as_str`] `pub const fn` accessor
9575        // resolve to the same four-arm emit-set across every arm the
9576        // exhaustive [`RestartStrategy::ALL`] slice enumerates. Rust's
9577        // `From` trait does not auto-derive the borrowed-input sibling
9578        // from a paired owned-input impl (no `impl<T, U> From<&T> for U
9579        // where T: Copy, U: From<T>` blanket in `core`), so the
9580        // borrowed-input axis is a distinct trait-idiomatic surface
9581        // that a `.iter().map(Into::into)` shape over
9582        // [`RestartStrategy::ALL`] (whose iterator yields
9583        // `&RestartStrategy`, not `RestartStrategy`) reaches through
9584        // this impl and no other — the paired owned-input
9585        // [`From<RestartStrategy>`] impl requires an explicit
9586        // `.copied()` / dereference before the trait fires.
9587        // Materializes the `<&'static str as
9588        // From<&RestartStrategy>>::from` output in a `const`-shape
9589        // binding to make the `'static` lifetime promise a build-time
9590        // invariant.
9591        const ONE_FOR_ONE: &str = RestartStrategy::OneForOne.as_str();
9592        const ONE_FOR_ALL: &str = RestartStrategy::OneForAll.as_str();
9593        const REST_FOR_ONE: &str = RestartStrategy::RestForOne.as_str();
9594        const SIMPLE_ONE_FOR_ONE: &str = RestartStrategy::SimpleOneForOne.as_str();
9595        for variant in RestartStrategy::ALL {
9596            let via_trait: &'static str = <&'static str as From<&RestartStrategy>>::from(variant);
9597            let via_method: &'static str = variant.as_str();
9598            assert_eq!(
9599                via_trait, via_method,
9600                "From<&RestartStrategy> for &'static str impl must \
9601                 round-trip &RestartStrategy::{variant:?} to the same \
9602                 lifted SUPERVISOR_ESTRATEGIA_* const \
9603                 RestartStrategy::as_str returns — divergence signals a \
9604                 silent detour off the substrate-primitive accessor"
9605            );
9606            let via_into: &'static str = variant.into();
9607            assert_eq!(
9608                via_into, via_method,
9609                "Into<&'static str>::into on &RestartStrategy::{variant:?} \
9610                 must byte-equal RestartStrategy::as_str on the same input — \
9611                 the blanket-derived Into shape must resolve to the same \
9612                 as_str dispatch as the explicit From impl"
9613            );
9614        }
9615        assert_eq!(
9616            [ONE_FOR_ONE, ONE_FOR_ALL, REST_FOR_ONE, SIMPLE_ONE_FOR_ONE],
9617            [
9618                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
9619                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
9620                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
9621                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
9622            ],
9623            "const-context RestartStrategy::as_str must resolve to the \
9624             four lifted SUPERVISOR_ESTRATEGIA_* consts — the borrowed-\
9625             input From<&RestartStrategy> for &'static str impl inherits \
9626             its `'static` lifetime promise from the same accessor the \
9627             owned-input sibling routes through"
9628        );
9629    }
9630
9631    #[test]
9632    fn restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
9633        // Cross-axis partition pin: the paired trait-idiomatic
9634        // owned-input `From<RestartStrategy> for &'static str` (523157d
9635        // campaign-shape) and borrowed-input `From<&RestartStrategy> for
9636        // &'static str` (this lift) forward projections must resolve
9637        // identically on every arm, locking the two input-shape paths
9638        // together so any future detour trips at caixa-core test time.
9639        // Then a witness that a `.iter().map(Into::into)` pipe over
9640        // [`RestartStrategy::ALL`] (whose iterator yields
9641        // `&RestartStrategy`) materializes the four-arm accept-set
9642        // through the borrowed-input axis alone — the exact shape a
9643        // future wasm-operator per-supervisor sibling-restart-strategy
9644        // diagnostic line, a future substrate-wide per-arm diagnostic
9645        // column, or a
9646        // `HashMap::<&'static str, RestartStrategy>::from_iter(
9647        //     RestartStrategy::ALL.iter().map(|s| (s.into(), *s)))`-style
9648        // per-strategy lookup reaches through — closing the two-way
9649        // owned/borrowed input-shape symmetry on the forward-projection
9650        // trait-idiomatic axis. Peer of the sibling
9651        // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
9652        // (64aa742) /
9653        // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
9654        // (5ab993a) /
9655        // [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
9656        // (807b0b5) partition pins on the sibling closed-set typed-enum
9657        // discriminator axes — extends the borrowed-input axis
9658        // discipline onto the first M2 OTP-shape sibling-restart
9659        // closed-set typed enum on the caixa surface. Also closes the
9660        // direct two-way `&Self → &'static str → Self` round-trip via
9661        // the paired [`TryFrom<&str>`] axis — unlike the peer
9662        // [`crate::CaixaKind`] axis pair (whose forward `From` emits
9663        // lowercase Portuguese diagnostic bytes while the reverse
9664        // `TryFrom` parses `PascalCase` wire bytes, forcing the round-
9665        // trip through an intermediate wire-vocab hop), the
9666        // [`RestartStrategy::as_str`] emit and
9667        // [`RestartStrategy::from_wire`] parse share the same
9668        // `PascalCase` vocabulary by construction, so the borrowed-
9669        // input forward axis and the reverse axis compose directly.
9670        for &variant in RestartStrategy::ALL {
9671            let owned: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
9672            let borrowed: &'static str = <&'static str as From<&RestartStrategy>>::from(&variant);
9673            assert_eq!(
9674                owned, borrowed,
9675                "From<RestartStrategy> and From<&RestartStrategy> for \
9676                 &'static str must resolve identically on \
9677                 RestartStrategy::{variant:?} — divergence signals the \
9678                 owned-input and borrowed-input forward-projection paths \
9679                 have drifted onto different emit-sets"
9680            );
9681        }
9682        let via_iter: Vec<&'static str> = RestartStrategy::ALL.iter().map(Into::into).collect();
9683        let via_method: Vec<&'static str> =
9684            RestartStrategy::ALL.iter().map(|s| s.as_str()).collect();
9685        assert_eq!(
9686            via_iter, via_method,
9687            "`.iter().map(Into::into)` over RestartStrategy::ALL must \
9688             byte-equal `.iter().map(|s| s.as_str())` on every arm — the \
9689             borrowed-input `From<&RestartStrategy> for &'static str` \
9690             axis is what makes the `.iter().map(Into::into)` shape route \
9691             through the substrate-primitive `RestartStrategy::as_str` \
9692             accessor rather than through a per-call-site `.copied()` / \
9693             dereference detour"
9694        );
9695        for variant in RestartStrategy::ALL {
9696            let emitted: &'static str = variant.into();
9697            let re_parsed: Result<RestartStrategy, ()> =
9698                <RestartStrategy as TryFrom<&str>>::try_from(emitted);
9699            assert_eq!(
9700                re_parsed,
9701                Ok(*variant),
9702                "trait-idiomatic borrowed-input forward-projection + \
9703                 reverse-projection axis pair must round-trip \
9704                 &RestartStrategy::{variant:?} through `.into::<&'static \
9705                 str>()` (via the borrowed-input axis) and back through \
9706                 `TryFrom<&str>` — a break signals the borrowed-input \
9707                 forward-emit and reverse-parse axes have drifted onto \
9708                 different vocabularies"
9709            );
9710        }
9711    }
9712
9713    #[test]
9714    fn restart_strategy_from_into_owned_string_routes_through_as_str_accessor() {
9715        // Fail-before-pass-after byte-parity pin on the newly lifted
9716        // `impl From<RestartStrategy> for String` — asserts the
9717        // owned-`String`-returning standard-library trait impl and the
9718        // substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
9719        // accessor resolve to the same four-arm emit-set across every
9720        // arm the exhaustive [`RestartStrategy::ALL`] slice enumerates.
9721        // Rust's standard library does not carry a blanket
9722        // `impl<T: AsRef<str>> From<T> for String` (nor an
9723        // `impl<T: fmt::Display> From<T> for String`), so the
9724        // owned-`String` forward-projection axis is a distinct
9725        // trait-idiomatic surface that a
9726        // `let key: String = strategy.into();`-shaped call site
9727        // reaches through this impl and no other — the paired sibling
9728        // `From<RestartStrategy> for &'static str` impl forces every
9729        // owned-`String` call site through an explicit
9730        // `.to_owned()` / `String::from` restatement.
9731        for &variant in RestartStrategy::ALL {
9732            let via_trait: String = <String as From<RestartStrategy>>::from(variant);
9733            let via_method: &'static str = variant.as_str();
9734            assert_eq!(
9735                via_trait.as_str(),
9736                via_method,
9737                "From<RestartStrategy> for String impl must round-trip \
9738                 RestartStrategy::{variant:?} to the same lifted \
9739                 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
9740                 returns — divergence signals a silent detour off the \
9741                 substrate-primitive accessor"
9742            );
9743            let via_into: String = variant.into();
9744            assert_eq!(
9745                via_into.as_str(),
9746                via_method,
9747                "Into<String>::into on RestartStrategy::{variant:?} must \
9748                 byte-equal RestartStrategy::as_str on the same input — the \
9749                 blanket-derived Into shape must resolve to the same as_str \
9750                 dispatch as the explicit From impl"
9751            );
9752        }
9753    }
9754
9755    #[test]
9756    fn restart_strategy_from_into_owned_string_and_static_str_agree_on_every_arm() {
9757        // Cross-axis partition pin: the paired trait-idiomatic
9758        // owned-`String` `From<RestartStrategy> for String` (this lift)
9759        // and owned-`&'static str` `From<RestartStrategy> for &'static
9760        // str` (523157d) forward projections must resolve identically
9761        // on every arm, locking the two return-type-shape paths
9762        // together so any future detour trips at caixa-core test time.
9763        // Also byte-parity witness against the sibling
9764        // [`ToString::to_string`] surface routed through
9765        // [`std::fmt::Display`] — the three owned-heap-string paths
9766        // (`.into::<String>()`, `String::from`, `.to_string()`) must
9767        // resolve identically on every arm so a future consumer that
9768        // picks any of the three lands on the same lifted
9769        // SUPERVISOR_ESTRATEGIA_* const. Then a direct round-trip
9770        // witness through the paired trait-idiomatic reverse
9771        // [`TryFrom<&str>`] axis on the owned-`String`'s
9772        // [`String::as_str`] borrow that closes the two-way
9773        // `Self → String → Self` round-trip on the trait-idiomatic
9774        // owned-`String` forward + reverse axis pair.
9775        for &variant in RestartStrategy::ALL {
9776            let owned_string: String = <String as From<RestartStrategy>>::from(variant);
9777            let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
9778            assert_eq!(
9779                owned_string.as_str(),
9780                owned_static,
9781                "From<RestartStrategy> for String and From<RestartStrategy> \
9782                 for &'static str must resolve identically on \
9783                 RestartStrategy::{variant:?} — divergence signals the \
9784                 owned-`String` and owned-`&'static str` forward-projection \
9785                 return-type-shape paths have drifted onto different \
9786                 emit-sets"
9787            );
9788            let via_to_string: String = variant.to_string();
9789            assert_eq!(
9790                owned_string, via_to_string,
9791                "From<RestartStrategy> for String must byte-equal \
9792                 RestartStrategy::to_string on RestartStrategy::{variant:?} — \
9793                 divergence signals the trait-idiomatic owned-`String` \
9794                 forward-projection axis and the ToString-through-Display \
9795                 axis have drifted onto different emit-sets"
9796            );
9797        }
9798        let via_iter: Vec<String> = RestartStrategy::ALL
9799            .iter()
9800            .copied()
9801            .map(String::from)
9802            .collect();
9803        let via_method: Vec<String> = RestartStrategy::ALL
9804            .iter()
9805            .map(|s| s.as_str().to_owned())
9806            .collect();
9807        assert_eq!(
9808            via_iter, via_method,
9809            "`.iter().copied().map(String::from)` over RestartStrategy::ALL \
9810             must byte-equal `.iter().map(|s| s.as_str().to_owned())` on \
9811             every arm — the owned-`String` `From<RestartStrategy> for \
9812             String` axis is what makes the `String::from` composition \
9813             route through the substrate-primitive `RestartStrategy::as_str` \
9814             accessor rather than through a per-call-site `.to_owned()` / \
9815             `String::from(strategy.as_str())` detour"
9816        );
9817        for &variant in RestartStrategy::ALL {
9818            let emitted: String = variant.into();
9819            let re_parsed: Result<RestartStrategy, ()> =
9820                <RestartStrategy as TryFrom<&str>>::try_from(emitted.as_str());
9821            assert_eq!(
9822                re_parsed,
9823                Ok(variant),
9824                "trait-idiomatic owned-`String` forward-projection + \
9825                 reverse-projection axis pair must round-trip \
9826                 RestartStrategy::{variant:?} through `.into::<String>()` \
9827                 and back through `TryFrom<&str>` on the owned-`String`'s \
9828                 String::as_str borrow — a break signals the owned-`String` \
9829                 forward-emit and reverse-parse axes have drifted onto \
9830                 different vocabularies"
9831            );
9832        }
9833    }
9834
9835    #[test]
9836    fn restart_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor() {
9837        // Fail-before-pass-after byte-parity pin on the newly lifted
9838        // `impl From<&RestartStrategy> for String` — asserts the
9839        // borrowed-input owned-`String`-returning standard-library trait
9840        // impl and the substrate-primitive [`RestartStrategy::as_str`]
9841        // `pub const fn` accessor resolve to the same four-arm emit-set
9842        // across every arm the exhaustive [`RestartStrategy::ALL`] slice
9843        // enumerates. Rust's standard library does not carry a blanket
9844        // `impl<T: AsRef<str>> From<&T> for String` (nor an
9845        // `impl<T: fmt::Display> From<&T> for String`), so the
9846        // borrowed-input owned-`String` forward-projection axis is a
9847        // distinct trait-idiomatic surface that a
9848        // `let key: String = (&strategy).into();`-shaped call site
9849        // reaches through this impl and no other — the paired sibling
9850        // `From<RestartStrategy> for String` impl forces every
9851        // borrowed-input call site through an explicit `Copy` deref
9852        // (`String::from(*strategy)`) or an `.as_str().to_owned()` /
9853        // `.to_string()` detour.
9854        for &variant in RestartStrategy::ALL {
9855            let via_trait: String = <String as From<&RestartStrategy>>::from(&variant);
9856            let via_method: &'static str = variant.as_str();
9857            assert_eq!(
9858                via_trait.as_str(),
9859                via_method,
9860                "From<&RestartStrategy> for String impl must round-trip \
9861                 &RestartStrategy::{variant:?} to the same lifted \
9862                 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
9863                 returns — divergence signals a silent detour off the \
9864                 substrate-primitive accessor"
9865            );
9866            let via_into: String = (&variant).into();
9867            assert_eq!(
9868                via_into.as_str(),
9869                via_method,
9870                "Into<String>::into on &RestartStrategy::{variant:?} must \
9871                 byte-equal RestartStrategy::as_str on the same input — the \
9872                 blanket-derived Into shape must resolve to the same as_str \
9873                 dispatch as the explicit From impl"
9874            );
9875        }
9876    }
9877
9878    #[test]
9879    fn restart_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm() {
9880        // Cross-axis partition pin: the newly lifted trait-idiomatic
9881        // borrowed-input owned-`String` `From<&RestartStrategy> for
9882        // String` (this lift), the paired owned-input owned-`String`
9883        // `From<RestartStrategy> for String` (7baa18a), the paired
9884        // borrowed-input owned-`&'static str` `From<&RestartStrategy>
9885        // for &'static str` (e941836), and the paired owned-input
9886        // owned-`&'static str` `From<RestartStrategy> for &'static str`
9887        // (523157d) — every corner of the `{Self, &Self} × {&'static
9888        // str, String}` 2×2 trait-idiomatic projection family — must
9889        // resolve identically on every arm, locking the four
9890        // return-shape × input-shape paths together so any future
9891        // detour trips at caixa-core test time. Also byte-parity
9892        // witness against the sibling [`ToString::to_string`] surface
9893        // routed through [`std::fmt::Display`] and a direct round-trip
9894        // witness through the paired trait-idiomatic reverse
9895        // [`TryFrom<&str>`] axis on the owned-`String`'s
9896        // [`String::as_str`] borrow that closes the two-way
9897        // `&Self → String → Self` round-trip on the trait-idiomatic
9898        // borrowed-input owned-`String` forward + reverse axis pair.
9899        for &variant in RestartStrategy::ALL {
9900            let borrowed_string: String = <String as From<&RestartStrategy>>::from(&variant);
9901            let owned_string: String = <String as From<RestartStrategy>>::from(variant);
9902            let borrowed_static: &'static str =
9903                <&'static str as From<&RestartStrategy>>::from(&variant);
9904            let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
9905            assert_eq!(
9906                borrowed_string, owned_string,
9907                "From<&RestartStrategy> for String and From<RestartStrategy> \
9908                 for String must resolve identically on \
9909                 RestartStrategy::{variant:?} — divergence signals the \
9910                 borrowed-input and owned-input owned-`String` \
9911                 forward-projection input-shape paths have drifted onto \
9912                 different emit-sets"
9913            );
9914            assert_eq!(
9915                borrowed_string.as_str(),
9916                borrowed_static,
9917                "From<&RestartStrategy> for String and From<&RestartStrategy> \
9918                 for &'static str must resolve identically on \
9919                 RestartStrategy::{variant:?} — divergence signals the \
9920                 borrowed-input `&'static str` and owned-`String` \
9921                 return-shape paths have drifted onto different emit-sets"
9922            );
9923            assert_eq!(
9924                borrowed_string.as_str(),
9925                owned_static,
9926                "From<&RestartStrategy> for String and From<RestartStrategy> \
9927                 for &'static str must resolve identically on \
9928                 RestartStrategy::{variant:?} — divergence signals a break \
9929                 in the diagonal corner of the {{Self, &Self}} × \
9930                 {{&'static str, String}} 2×2 trait-idiomatic \
9931                 projection family"
9932            );
9933            let via_to_string: String = variant.to_string();
9934            assert_eq!(
9935                borrowed_string, via_to_string,
9936                "From<&RestartStrategy> for String must byte-equal \
9937                 RestartStrategy::to_string on RestartStrategy::{variant:?} — \
9938                 divergence signals the trait-idiomatic borrowed-input \
9939                 owned-`String` forward-projection axis and the \
9940                 ToString-through-Display axis have drifted onto different \
9941                 emit-sets"
9942            );
9943        }
9944        let via_iter: Vec<String> = RestartStrategy::ALL.iter().map(String::from).collect();
9945        let via_method: Vec<String> = RestartStrategy::ALL
9946            .iter()
9947            .map(|s| s.as_str().to_owned())
9948            .collect();
9949        assert_eq!(
9950            via_iter, via_method,
9951            "`.iter().map(String::from)` over RestartStrategy::ALL — a \
9952             call site whose iteration axis holds `&RestartStrategy` by \
9953             construction — must byte-equal `.iter().map(|s| \
9954             s.as_str().to_owned())` on every arm — the borrowed-input \
9955             owned-`String` `From<&RestartStrategy> for String` axis is \
9956             what makes the `String::from` composition route through the \
9957             substrate-primitive `RestartStrategy::as_str` accessor \
9958             without a spurious `Copy` deref (which would only be \
9959             reachable through the owned-input `From<RestartStrategy> for \
9960             String` axis by first calling `.copied()` on the iterator)"
9961        );
9962        for &variant in RestartStrategy::ALL {
9963            let emitted: String = (&variant).into();
9964            let re_parsed: Result<RestartStrategy, ()> =
9965                <RestartStrategy as TryFrom<&str>>::try_from(emitted.as_str());
9966            assert_eq!(
9967                re_parsed,
9968                Ok(variant),
9969                "trait-idiomatic borrowed-input owned-`String` \
9970                 forward-projection + reverse-projection axis pair must \
9971                 round-trip &RestartStrategy::{variant:?} through \
9972                 `.into::<String>()` on the borrowed-input surface and \
9973                 back through `TryFrom<&str>` on the owned-`String`'s \
9974                 String::as_str borrow — a break signals the \
9975                 borrowed-input owned-`String` forward-emit and \
9976                 reverse-parse axes have drifted onto different \
9977                 vocabularies"
9978            );
9979        }
9980    }
9981
9982    #[test]
9983    fn restart_strategy_from_into_static_cow_str_routes_through_as_str_accessor() {
9984        // Fail-before-pass-after byte-parity pin on the newly lifted
9985        // `impl From<RestartStrategy> for std::borrow::Cow<'static, str>` —
9986        // asserts the standard-library trait impl and the substrate-
9987        // primitive [`super::RestartStrategy::as_str`] `pub const fn`
9988        // accessor resolve to the same four-arm emit-set across every
9989        // arm the exhaustive [`super::RestartStrategy::ALL`] slice
9990        // enumerates. Rust's standard library does not carry a blanket
9991        // `impl<T: AsRef<str>> From<T> for Cow<'static, str>` (nor an
9992        // `impl<T: fmt::Display> From<T> for Cow<'static, str>`), so
9993        // the `Cow<'static, str>` forward-projection axis is a
9994        // distinct trait-idiomatic surface that a
9995        // `let key: Cow<'static, str> = strategy.into();`-shaped call
9996        // site reaches through this impl and no other — the paired
9997        // sibling `From<RestartStrategy> for &'static str` and
9998        // `From<RestartStrategy> for String` impls force every
9999        // `Cow<'static, str>`-parameterized call site through a
10000        // `Cow::Borrowed(strategy.as_str())` /
10001        // `Cow::Owned(strategy.to_string())` composition whose type
10002        // bounds have no compile-time link back to the substrate
10003        // primitive.
10004        //
10005        // Also asserts the projection lands on the zero-alloc
10006        // [`std::borrow::Cow::Borrowed`] arm (not the
10007        // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
10008        // [`super::RestartStrategy::as_str`] accessor's `&'static str`
10009        // return lifetime by construction makes the borrowed arm the
10010        // type-correct projection with no runtime allocation. Any
10011        // future silent detour that routes the impl through the owned
10012        // arm (an accidental `Cow::Owned(strategy.to_string())` rewrite
10013        // that would allocate on every call site where the
10014        // `&'static str` return of [`super::RestartStrategy::as_str`]
10015        // makes the zero-alloc borrowed projection type-correct) trips
10016        // at caixa-core test time under the
10017        // [`std::borrow::Cow::Borrowed`] discriminator witness rather
10018        // than at a downstream `Cow<'static, str>`-bound consumer's
10019        // silent allocation.
10020        //
10021        // First peer on the substrate-wide trait-idiomatic
10022        // [`std::borrow::Cow<'static, str>`] forward-projection family
10023        // to extend the axis off the top-level [`super::CaixaKind`]
10024        // enum (99c1735 owned-input, d45c409 borrowed-input) onto the
10025        // first M2 OTP-shape closed-set fieldless typed enum on the
10026        // caixa surface.
10027        for &variant in RestartStrategy::ALL {
10028            let via_trait: std::borrow::Cow<'static, str> =
10029                <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
10030            let via_method: &'static str = variant.as_str();
10031            assert_eq!(
10032                via_trait.as_ref(),
10033                via_method,
10034                "From<RestartStrategy> for Cow<'static, str> impl must \
10035                 round-trip RestartStrategy::{variant:?} to the same \
10036                 lifted SUPERVISOR_ESTRATEGIA_* const \
10037                 RestartStrategy::as_str returns — divergence signals a \
10038                 silent detour off the substrate-primitive accessor"
10039            );
10040            assert!(
10041                matches!(via_trait, std::borrow::Cow::Borrowed(_)),
10042                "From<RestartStrategy> for Cow<'static, str> impl must \
10043                 land on the zero-alloc Cow::Borrowed arm on \
10044                 RestartStrategy::{variant:?} — a Cow::Owned outcome \
10045                 signals the projection has silently allocated where \
10046                 the substrate-primitive RestartStrategy::as_str \
10047                 `&'static str` return makes the borrowed arm the \
10048                 type-correct projection"
10049            );
10050            let via_into: std::borrow::Cow<'static, str> = variant.into();
10051            assert_eq!(
10052                via_into.as_ref(),
10053                via_method,
10054                "Into<Cow<'static, str>>::into on \
10055                 RestartStrategy::{variant:?} must byte-equal \
10056                 RestartStrategy::as_str on the same input — the \
10057                 blanket-derived Into shape must resolve to the same \
10058                 as_str dispatch as the explicit From impl"
10059            );
10060            assert!(
10061                matches!(via_into, std::borrow::Cow::Borrowed(_)),
10062                "Into<Cow<'static, str>>::into on \
10063                 RestartStrategy::{variant:?} must land on the \
10064                 zero-alloc Cow::Borrowed arm — the blanket-derived \
10065                 Into shape must resolve to the same Cow::Borrowed \
10066                 dispatch as the explicit From impl"
10067            );
10068        }
10069    }
10070
10071    #[test]
10072    fn restart_strategy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
10073        // Cross-axis partition pin: the newly lifted trait-idiomatic
10074        // `From<RestartStrategy> for std::borrow::Cow<'static, str>`
10075        // (this lift), the paired owned-input `From<RestartStrategy>
10076        // for &'static str` (523157d), and the paired owned-input
10077        // `From<RestartStrategy> for String` (7baa18a) forward
10078        // projections must resolve identically on every arm, locking
10079        // the three return-shape paths together by construction so any
10080        // future detour trips at caixa-core test time. Also byte-parity
10081        // witness against the sibling [`ToString::to_string`] surface
10082        // routed through [`std::fmt::Display`] — every owned-heap-
10083        // string path (the `Cow::Owned` promotion of this axis's
10084        // `.into_owned()`, `From<RestartStrategy> for String`, and
10085        // `.to_string()`) resolves to the same lifted
10086        // [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const per arm.
10087        //
10088        // Then a `.iter().copied().map(std::borrow::Cow::from)` pipe
10089        // witness over [`super::RestartStrategy::ALL`] that
10090        // materializes the four-arm accept-set through the
10091        // [`std::borrow::Cow<'static, str>`] axis alone — the exact
10092        // shape a future `axum::response::IntoResponse` per-strategy
10093        // rejection-body composer, a future M4 admission-webhook
10094        // per-strategy rejection-reason emitter whose typing rules out
10095        // the sibling [`AsRef<str>`] borrowed return, or a future
10096        // substrate-wide per-strategy diagnostic surface that binds
10097        // through a [`Cow<'static, str>`] boundary reaches through.
10098        // The pipe witness also pins the zero-alloc discipline: every
10099        // element in the collected vector satisfies the
10100        // [`std::borrow::Cow::Borrowed`] arm predicate, so a future
10101        // accidental silent-allocation regression on the pipe's
10102        // iteration axis is a caixa-core-test-time failure.
10103        for &variant in RestartStrategy::ALL {
10104            let via_cow: std::borrow::Cow<'static, str> =
10105                <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
10106            let via_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
10107            let via_string: String = <String as From<RestartStrategy>>::from(variant);
10108            assert_eq!(
10109                via_cow.as_ref(),
10110                via_static,
10111                "From<RestartStrategy> for Cow<'static, str> and \
10112                 From<RestartStrategy> for &'static str must resolve \
10113                 identically on RestartStrategy::{variant:?} — \
10114                 divergence signals the Cow<'static, str> and \
10115                 &'static str return-shape paths have drifted onto \
10116                 different emit-sets"
10117            );
10118            assert_eq!(
10119                via_cow.as_ref(),
10120                via_string.as_str(),
10121                "From<RestartStrategy> for Cow<'static, str> and \
10122                 From<RestartStrategy> for String must resolve \
10123                 identically on RestartStrategy::{variant:?} — \
10124                 divergence signals the Cow<'static, str> and String \
10125                 return-shape paths have drifted onto different \
10126                 emit-sets"
10127            );
10128            let via_to_string: String = variant.to_string();
10129            assert_eq!(
10130                via_cow.as_ref(),
10131                via_to_string.as_str(),
10132                "From<RestartStrategy> for Cow<'static, str> must \
10133                 byte-equal RestartStrategy::to_string on \
10134                 RestartStrategy::{variant:?} — divergence signals the \
10135                 trait-idiomatic Cow<'static, str> forward-projection \
10136                 axis and the ToString-through-Display axis have \
10137                 drifted onto different emit-sets"
10138            );
10139        }
10140        let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
10141            .iter()
10142            .copied()
10143            .map(std::borrow::Cow::from)
10144            .collect();
10145        let via_method: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
10146            .iter()
10147            .map(|s| std::borrow::Cow::Borrowed(s.as_str()))
10148            .collect();
10149        assert_eq!(
10150            via_iter, via_method,
10151            "`.iter().copied().map(Cow::from)` over \
10152             RestartStrategy::ALL must byte-equal `.iter().map(|s| \
10153             Cow::Borrowed(s.as_str()))` on every arm — the \
10154             trait-idiomatic `From<RestartStrategy> for Cow<'static, \
10155             str>` axis is what makes the `Cow::from` composition \
10156             route through the substrate-primitive \
10157             `RestartStrategy::as_str` accessor with the zero-alloc \
10158             Cow::Borrowed arm by construction, rather than a \
10159             per-call-site `Cow::Owned(strategy.to_string())` \
10160             allocation"
10161        );
10162        for cow in &via_iter {
10163            assert!(
10164                matches!(cow, std::borrow::Cow::Borrowed(_)),
10165                "every element of the \
10166                 .iter().copied().map(Cow::from) pipe over \
10167                 RestartStrategy::ALL must land on the zero-alloc \
10168                 Cow::Borrowed arm — a Cow::Owned outcome on any arm \
10169                 signals the pipe's iteration axis has silently \
10170                 allocated where the substrate-primitive \
10171                 RestartStrategy::as_str `&'static str` return makes \
10172                 the borrowed arm the type-correct projection"
10173            );
10174        }
10175    }
10176
10177    #[test]
10178    fn restart_strategy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor() {
10179        // Fail-before-pass-after byte-parity pin on the newly lifted
10180        // `impl From<&RestartStrategy> for std::borrow::Cow<'static, str>` —
10181        // asserts the borrowed-input standard-library trait impl and
10182        // the substrate-primitive [`super::RestartStrategy::as_str`]
10183        // `pub const fn` accessor resolve to the same four-arm emit-
10184        // set across every arm the exhaustive
10185        // [`super::RestartStrategy::ALL`] slice enumerates. Rust's
10186        // standard library does not carry a blanket
10187        // `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor a
10188        // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`), so
10189        // the borrowed-input `Cow<'static, str>` forward-projection
10190        // axis is a distinct trait-idiomatic surface that a
10191        // `let key: Cow<'static, str> = (&strategy).into();`-shaped
10192        // call site or a
10193        // `RestartStrategy::ALL.iter().map(Cow::from)`-shaped pipe
10194        // reaches through this impl and no other — the paired owned-
10195        // input `From<RestartStrategy> for Cow<'static, str>` impl
10196        // (7dd28b3) forces every borrowed-input call site through an
10197        // explicit `Copy` deref (`Cow::from(*strategy)`) or a
10198        // `Cow::Borrowed(strategy.as_str())` open-code whose type
10199        // bounds have no compile-time link back to the substrate
10200        // primitive.
10201        //
10202        // Also asserts the projection lands on the zero-alloc
10203        // [`std::borrow::Cow::Borrowed`] arm (not the
10204        // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
10205        // [`super::RestartStrategy::as_str`] accessor's `&'static str`
10206        // return lifetime by construction makes the borrowed arm the
10207        // type-correct projection with no runtime allocation on the
10208        // borrowed-input surface just as on the paired owned-input
10209        // surface.
10210        //
10211        // Second peer on the substrate-wide trait-idiomatic
10212        // [`std::borrow::Cow<'static, str>`] forward-projection family
10213        // on this enum — closes the `{Self, &Self}` input-shape
10214        // corner of the [`Cow<'static, str>`] axis on the first M2
10215        // OTP-shape closed-set fieldless typed enum peer on the caixa
10216        // surface (`:supervisor :estrategia`), exactly as d45c409
10217        // closed it on the top-level [`super::CaixaKind`] one commit
10218        // after the owning half (99c1735) landed. Every future
10219        // closed-set fieldless typed enum peer on the substrate is a
10220        // future target of the campaign.
10221        for &variant in RestartStrategy::ALL {
10222            let via_trait: std::borrow::Cow<'static, str> =
10223                <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&variant);
10224            let via_method: &'static str = variant.as_str();
10225            assert_eq!(
10226                via_trait.as_ref(),
10227                via_method,
10228                "From<&RestartStrategy> for Cow<'static, str> impl must \
10229                 round-trip &RestartStrategy::{variant:?} to the same \
10230                 lifted SUPERVISOR_ESTRATEGIA_* const \
10231                 RestartStrategy::as_str returns — divergence signals a \
10232                 silent detour off the substrate-primitive accessor"
10233            );
10234            assert!(
10235                matches!(via_trait, std::borrow::Cow::Borrowed(_)),
10236                "From<&RestartStrategy> for Cow<'static, str> impl must \
10237                 land on the zero-alloc Cow::Borrowed arm on \
10238                 &RestartStrategy::{variant:?} — a Cow::Owned outcome \
10239                 signals the projection has silently allocated where \
10240                 the substrate-primitive RestartStrategy::as_str \
10241                 `&'static str` return makes the borrowed arm the \
10242                 type-correct projection"
10243            );
10244            let via_into: std::borrow::Cow<'static, str> = (&variant).into();
10245            assert_eq!(
10246                via_into.as_ref(),
10247                via_method,
10248                "Into<Cow<'static, str>>::into on \
10249                 &RestartStrategy::{variant:?} must byte-equal \
10250                 RestartStrategy::as_str on the same input — the \
10251                 blanket-derived Into shape must resolve to the same \
10252                 as_str dispatch as the explicit From impl"
10253            );
10254            assert!(
10255                matches!(via_into, std::borrow::Cow::Borrowed(_)),
10256                "Into<Cow<'static, str>>::into on \
10257                 &RestartStrategy::{variant:?} must land on the \
10258                 zero-alloc Cow::Borrowed arm — the blanket-derived \
10259                 Into shape must resolve to the same Cow::Borrowed \
10260                 dispatch as the explicit From impl"
10261            );
10262        }
10263    }
10264
10265    #[test]
10266    fn restart_strategy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
10267        // Cross-axis partition pin: the newly lifted trait-idiomatic
10268        // borrowed-input `From<&RestartStrategy> for
10269        // std::borrow::Cow<'static, str>` (this lift), the paired
10270        // owned-input `From<RestartStrategy> for
10271        // std::borrow::Cow<'static, str>` (7dd28b3), the paired
10272        // borrowed-input owned-`&'static str` `From<&RestartStrategy>
10273        // for &'static str`, and the paired borrowed-input owned-
10274        // `String` `From<&RestartStrategy> for String` must resolve
10275        // identically on every arm, locking the four
10276        // return-shape × input-shape paths together by construction so
10277        // any future detour trips at caixa-core test time. Also byte-
10278        // parity witness against the sibling [`ToString::to_string`]
10279        // surface routed through [`std::fmt::Display`] — every owned-
10280        // heap-string path (this axis's `.into_owned()` promotion, the
10281        // paired [`From<&RestartStrategy> for String`], and
10282        // `.to_string()`) resolves to the same lifted
10283        // [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const per arm.
10284        //
10285        // Then a `.iter().map(std::borrow::Cow::from)` pipe witness
10286        // over [`super::RestartStrategy::ALL`] — whose iterator yields
10287        // `&RestartStrategy` by construction, so the borrowed-input
10288        // [`Cow<'static, str>`] axis is what routes the pipe through
10289        // the substrate-primitive [`super::RestartStrategy::as_str`]
10290        // accessor without a spurious [`Copy`] deref (which would only
10291        // be reachable through the owned-input
10292        // [`From<RestartStrategy> for Cow<'static, str>`] axis by
10293        // first calling `.copied()` on the iterator). The pipe witness
10294        // also pins the zero-alloc discipline: every element in the
10295        // collected vector satisfies the [`std::borrow::Cow::Borrowed`]
10296        // arm predicate, so a future accidental silent-allocation
10297        // regression on the pipe's iteration axis is a caixa-core-
10298        // test-time failure.
10299        for &strategy in RestartStrategy::ALL {
10300            let borrowed_cow: std::borrow::Cow<'static, str> =
10301                <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&strategy);
10302            let owned_cow: std::borrow::Cow<'static, str> =
10303                <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(strategy);
10304            let borrowed_static: &'static str =
10305                <&'static str as From<&RestartStrategy>>::from(&strategy);
10306            let borrowed_string: String = <String as From<&RestartStrategy>>::from(&strategy);
10307            assert_eq!(
10308                borrowed_cow, owned_cow,
10309                "From<&RestartStrategy> for Cow<'static, str> and \
10310                 From<RestartStrategy> for Cow<'static, str> must \
10311                 resolve identically on RestartStrategy::{strategy:?} — \
10312                 divergence signals the borrowed-input and owned-input \
10313                 Cow<'static, str> forward-projection input-shape \
10314                 paths have drifted onto different emit-sets"
10315            );
10316            assert_eq!(
10317                borrowed_cow.as_ref(),
10318                borrowed_static,
10319                "From<&RestartStrategy> for Cow<'static, str> and \
10320                 From<&RestartStrategy> for &'static str must resolve \
10321                 identically on RestartStrategy::{strategy:?} — \
10322                 divergence signals the borrowed-input Cow<'static, \
10323                 str> and &'static str return-shape paths have drifted \
10324                 onto different emit-sets"
10325            );
10326            assert_eq!(
10327                borrowed_cow.as_ref(),
10328                borrowed_string.as_str(),
10329                "From<&RestartStrategy> for Cow<'static, str> and \
10330                 From<&RestartStrategy> for String must resolve \
10331                 identically on RestartStrategy::{strategy:?} — \
10332                 divergence signals the borrowed-input Cow<'static, \
10333                 str> and owned-`String` return-shape paths have \
10334                 drifted onto different emit-sets"
10335            );
10336            let via_to_string: String = strategy.to_string();
10337            assert_eq!(
10338                borrowed_cow.as_ref(),
10339                via_to_string.as_str(),
10340                "From<&RestartStrategy> for Cow<'static, str> must \
10341                 byte-equal RestartStrategy::to_string on \
10342                 RestartStrategy::{strategy:?} — divergence signals \
10343                 the trait-idiomatic borrowed-input Cow<'static, str> \
10344                 forward-projection axis and the ToString-through-\
10345                 Display axis have drifted onto different emit-sets"
10346            );
10347        }
10348        let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
10349            .iter()
10350            .map(std::borrow::Cow::from)
10351            .collect();
10352        let via_method: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
10353            .iter()
10354            .map(|s| std::borrow::Cow::Borrowed(s.as_str()))
10355            .collect();
10356        assert_eq!(
10357            via_iter, via_method,
10358            "`.iter().map(Cow::from)` over RestartStrategy::ALL — a \
10359             call site whose iteration axis holds `&RestartStrategy` \
10360             by construction — must byte-equal `.iter().map(|s| \
10361             Cow::Borrowed(s.as_str()))` on every arm — the borrowed-\
10362             input Cow<'static, str> `From<&RestartStrategy> for \
10363             Cow<'static, str>` axis is what makes the `Cow::from` \
10364             composition route through the substrate-primitive \
10365             `RestartStrategy::as_str` accessor with the zero-alloc \
10366             Cow::Borrowed arm by construction and without a spurious \
10367             `Copy` deref (which would only be reachable through the \
10368             owned-input `From<RestartStrategy> for Cow<'static, str>` \
10369             axis by first calling `.copied()` on the iterator)"
10370        );
10371        for cow in &via_iter {
10372            assert!(
10373                matches!(cow, std::borrow::Cow::Borrowed(_)),
10374                "every element of the .iter().map(Cow::from) pipe \
10375                 over RestartStrategy::ALL must land on the zero-\
10376                 alloc Cow::Borrowed arm — a Cow::Owned outcome on \
10377                 any arm signals the pipe's iteration axis has \
10378                 silently allocated where the substrate-primitive \
10379                 RestartStrategy::as_str `&'static str` return makes \
10380                 the borrowed arm the type-correct projection"
10381            );
10382        }
10383    }
10384
10385    #[test]
10386    fn restart_strategy_from_into_box_str_routes_through_as_str_accessor() {
10387        // Fail-before-pass-after byte-parity pin on the newly lifted
10388        // `impl From<RestartStrategy> for Box<str>` — asserts the
10389        // owned-input standard-library trait impl and the
10390        // substrate-primitive [`super::RestartStrategy::as_str`]
10391        // `pub const fn` accessor resolve to the same four-arm emit-
10392        // set across every arm the exhaustive
10393        // [`super::RestartStrategy::ALL`] slice enumerates. Opens the
10394        // substrate-wide `Box<str>` forward-projection campaign tier
10395        // on the first M2 OTP-shape closed-set fieldless typed enum
10396        // peer on the caixa surface (`:supervisor :estrategia`),
10397        // immediately after the paired `Cow<'static, str>` axis
10398        // (7dd28b3 / ee577fd) closed the
10399        // `{Self, &Self} × {&'static str, String, Cow<'static, str>}`
10400        // 2×3 corner on this enum. Rust's standard library carries
10401        // `impl From<&str> for Box<str>` and
10402        // `impl From<String> for Box<str>` but no blanket
10403        // `impl<T: AsRef<str>> From<T> for Box<str>`, so this axis is
10404        // a distinct trait-idiomatic surface that a
10405        // `let key: Box<str> = strategy.into();`-shaped call site
10406        // reaches through this impl and no other — a paired
10407        // `Box::from(strategy.as_str())` open-code has no compile-
10408        // time link back to the substrate primitive.
10409        for &variant in RestartStrategy::ALL {
10410            let via_trait: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
10411            let via_method: &'static str = variant.as_str();
10412            assert_eq!(
10413                via_trait.as_ref(),
10414                via_method,
10415                "From<RestartStrategy> for Box<str> impl must round-\
10416                 trip RestartStrategy::{variant:?} to the same lifted \
10417                 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
10418                 returns — divergence signals a silent detour off the \
10419                 substrate-primitive accessor"
10420            );
10421            let via_into: Box<str> = variant.into();
10422            assert_eq!(
10423                via_into.as_ref(),
10424                via_method,
10425                "Into<Box<str>>::into on RestartStrategy::{variant:?} \
10426                 must byte-equal RestartStrategy::as_str on the same \
10427                 input — the blanket-derived Into shape must resolve \
10428                 to the same as_str dispatch as the explicit From impl"
10429            );
10430        }
10431    }
10432
10433    #[test]
10434    fn restart_strategy_from_borrowed_into_box_str_routes_through_as_str_accessor() {
10435        // Fail-before-pass-after byte-parity pin on the newly lifted
10436        // `impl From<&RestartStrategy> for Box<str>` — asserts the
10437        // borrowed-input standard-library trait impl and the
10438        // substrate-primitive [`super::RestartStrategy::as_str`]
10439        // `pub const fn` accessor resolve to the same four-arm emit-
10440        // set across every arm the exhaustive
10441        // [`super::RestartStrategy::ALL`] slice enumerates. Rust's
10442        // standard library does not carry a blanket
10443        // `impl<T: AsRef<str>> From<&T> for Box<str>` (nor a
10444        // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`),
10445        // so the borrowed-input `Box<str>` forward-projection axis
10446        // is a distinct trait-idiomatic surface that a
10447        // `let key: Box<str> = (&strategy).into();`-shaped call site
10448        // or a `RestartStrategy::ALL.iter().map(Box::<str>::from)`-
10449        // shaped pipe reaches through this impl and no other — the
10450        // paired owned-input `From<RestartStrategy> for Box<str>`
10451        // impl (69ef45c) forces every borrowed-input call site
10452        // through an explicit `Copy` deref
10453        // (`Box::<str>::from((*strategy).as_str())`) or a
10454        // `Box::<str>::from(strategy.as_str())` open-code whose
10455        // type bounds have no compile-time link back to the
10456        // substrate primitive.
10457        //
10458        // Second peer on the substrate-wide trait-idiomatic
10459        // [`Box<str>`] forward-projection family on this enum —
10460        // closes the `{Self, &Self}` input-shape corner of the
10461        // [`Box<str>`] axis on the first M2 OTP-shape closed-set
10462        // fieldless typed enum peer on the caixa surface
10463        // (`:supervisor :estrategia`), exactly as ee577fd closed
10464        // the paired [`Cow<'static, str>`] axis one commit after
10465        // its owning half (7dd28b3) landed. Every future closed-
10466        // set fieldless typed enum peer on the substrate is a
10467        // future target of the campaign.
10468        //
10469        // Also byte-parity witness against the paired owned-input
10470        // [`From<RestartStrategy> for Box<str>`] and the sibling
10471        // borrowed-input [`From<&RestartStrategy> for &'static str`],
10472        // [`From<&RestartStrategy> for String`], and
10473        // [`From<&RestartStrategy> for Cow<'static, str>`]
10474        // return-shape axes — locking the four
10475        // return-shape × input-shape paths together by construction
10476        // so any future detour trips at caixa-core test time. Then a
10477        // `.iter().map(Box::<str>::from)` pipe witness over
10478        // [`super::RestartStrategy::ALL`] — whose iterator yields
10479        // `&RestartStrategy` by construction, so the borrowed-input
10480        // [`Box<str>`] axis is what routes the pipe through the
10481        // substrate-primitive [`super::RestartStrategy::as_str`]
10482        // accessor without a spurious [`Copy`] deref (which would
10483        // only be reachable through the owned-input
10484        // [`From<RestartStrategy> for Box<str>`] axis by first
10485        // calling `.copied()` on the iterator).
10486        for &variant in RestartStrategy::ALL {
10487            let via_trait: Box<str> = <Box<str> as From<&RestartStrategy>>::from(&variant);
10488            let via_method: &'static str = variant.as_str();
10489            assert_eq!(
10490                via_trait.as_ref(),
10491                via_method,
10492                "From<&RestartStrategy> for Box<str> impl must \
10493                 round-trip &RestartStrategy::{variant:?} to the same \
10494                 lifted SUPERVISOR_ESTRATEGIA_* const \
10495                 RestartStrategy::as_str returns — divergence signals \
10496                 a silent detour off the substrate-primitive accessor"
10497            );
10498            let via_into: Box<str> = (&variant).into();
10499            assert_eq!(
10500                via_into.as_ref(),
10501                via_method,
10502                "Into<Box<str>>::into on &RestartStrategy::{variant:?} \
10503                 must byte-equal RestartStrategy::as_str on the same \
10504                 input — the blanket-derived Into shape must resolve \
10505                 to the same as_str dispatch as the explicit From impl"
10506            );
10507            let owned_box: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
10508            assert_eq!(
10509                via_trait, owned_box,
10510                "From<&RestartStrategy> for Box<str> and \
10511                 From<RestartStrategy> for Box<str> must resolve \
10512                 identically on RestartStrategy::{variant:?} — \
10513                 divergence signals the borrowed-input and owned-input \
10514                 Box<str> forward-projection input-shape paths have \
10515                 drifted onto different emit-sets"
10516            );
10517            let borrowed_static: &'static str =
10518                <&'static str as From<&RestartStrategy>>::from(&variant);
10519            assert_eq!(
10520                via_trait.as_ref(),
10521                borrowed_static,
10522                "From<&RestartStrategy> for Box<str> and \
10523                 From<&RestartStrategy> for &'static str must resolve \
10524                 identically on RestartStrategy::{variant:?} — \
10525                 divergence signals the borrowed-input Box<str> and \
10526                 &'static str return-shape paths have drifted onto \
10527                 different emit-sets"
10528            );
10529            let borrowed_string: String = <String as From<&RestartStrategy>>::from(&variant);
10530            assert_eq!(
10531                via_trait.as_ref(),
10532                borrowed_string.as_str(),
10533                "From<&RestartStrategy> for Box<str> and \
10534                 From<&RestartStrategy> for String must resolve \
10535                 identically on RestartStrategy::{variant:?} — \
10536                 divergence signals the borrowed-input Box<str> and \
10537                 owned-`String` return-shape paths have drifted onto \
10538                 different emit-sets"
10539            );
10540            let borrowed_cow: std::borrow::Cow<'static, str> =
10541                <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&variant);
10542            assert_eq!(
10543                via_trait.as_ref(),
10544                borrowed_cow.as_ref(),
10545                "From<&RestartStrategy> for Box<str> and \
10546                 From<&RestartStrategy> for Cow<'static, str> must \
10547                 resolve identically on RestartStrategy::{variant:?} — \
10548                 divergence signals the borrowed-input Box<str> and \
10549                 Cow<'static, str> return-shape paths have drifted \
10550                 onto different emit-sets"
10551            );
10552        }
10553        let via_iter: Vec<Box<str>> = RestartStrategy::ALL.iter().map(Box::<str>::from).collect();
10554        let via_method: Vec<Box<str>> = RestartStrategy::ALL
10555            .iter()
10556            .map(|s| Box::<str>::from(s.as_str()))
10557            .collect();
10558        assert_eq!(
10559            via_iter, via_method,
10560            "`.iter().map(Box::<str>::from)` over \
10561             RestartStrategy::ALL — a call site whose iteration axis \
10562             holds `&RestartStrategy` by construction — must byte-\
10563             equal `.iter().map(|s| Box::<str>::from(s.as_str()))` \
10564             on every arm — the borrowed-input Box<str> \
10565             `From<&RestartStrategy> for Box<str>` axis is what \
10566             makes the `Box::<str>::from` composition route through \
10567             the substrate-primitive `RestartStrategy::as_str` \
10568             accessor without a spurious `Copy` deref (which would \
10569             only be reachable through the owned-input \
10570             `From<RestartStrategy> for Box<str>` axis by first \
10571             calling `.copied()` on the iterator)"
10572        );
10573    }
10574
10575    #[test]
10576    fn restart_strategy_from_into_arc_str_routes_through_as_str_accessor() {
10577        // Fail-before-pass-after byte-parity pin on the newly lifted
10578        // `impl From<RestartStrategy> for std::sync::Arc<str>` — asserts
10579        // the owned-input standard-library trait impl and the
10580        // substrate-primitive [`super::RestartStrategy::as_str`]
10581        // `pub const fn` accessor resolve to the same four-arm emit-
10582        // set across every arm the exhaustive
10583        // [`super::RestartStrategy::ALL`] slice enumerates. Opens the
10584        // substrate-wide [`std::sync::Arc<str>`] forward-projection
10585        // campaign tier on the first M2 OTP-shape closed-set fieldless
10586        // typed enum peer on the caixa surface
10587        // (`:supervisor :estrategia`), immediately after the paired
10588        // [`Box<str>`] axis (69ef45c / 59ae5dc) closed the
10589        // `{Self, &Self} × {&'static str, String, Cow<'static, str>,
10590        // Box<str>}` 2×4 corner on this enum. Rust's standard library
10591        // carries `impl From<&str> for std::sync::Arc<str>` and
10592        // `impl From<String> for std::sync::Arc<str>` but no blanket
10593        // `impl<T: AsRef<str>> From<T> for std::sync::Arc<str>` (nor
10594        // an `impl<T: fmt::Display> From<T> for std::sync::Arc<str>`),
10595        // so this axis is a distinct trait-idiomatic surface that a
10596        // `let key: std::sync::Arc<str> = strategy.into();`-shaped call
10597        // site reaches through this impl and no other — a paired
10598        // `std::sync::Arc::<str>::from(strategy.as_str())` open-code
10599        // has no compile-time link back to the substrate primitive,
10600        // and a two-step `std::sync::Arc::<str>::from(String::from(
10601        // strategy))` composition through the owned-`String` axis
10602        // allocates twice (once into the intermediate `String`, once
10603        // into the [`Arc<str>`] on the `From<String>` conversion)
10604        // where the single-step trait impl allocates once.
10605        //
10606        // Cross-axis byte-parity witness against the sibling owned-
10607        // input `{&'static str, String, Cow<'static, str>, Box<str>}`
10608        // return-shape axes — locking the five return-shape paths on
10609        // the owned-input surface together by construction so any
10610        // future detour off the substrate-primitive
10611        // [`super::RestartStrategy::as_str`] accessor trips at caixa-
10612        // core test time.
10613        for &variant in RestartStrategy::ALL {
10614            let via_trait: std::sync::Arc<str> =
10615                <std::sync::Arc<str> as From<RestartStrategy>>::from(variant);
10616            let via_method: &'static str = variant.as_str();
10617            assert_eq!(
10618                via_trait.as_ref(),
10619                via_method,
10620                "From<RestartStrategy> for std::sync::Arc<str> impl \
10621                 must round-trip RestartStrategy::{variant:?} to the \
10622                 same lifted SUPERVISOR_ESTRATEGIA_* const \
10623                 RestartStrategy::as_str returns — divergence signals \
10624                 a silent detour off the substrate-primitive accessor"
10625            );
10626            let via_into: std::sync::Arc<str> = variant.into();
10627            assert_eq!(
10628                via_into.as_ref(),
10629                via_method,
10630                "Into<std::sync::Arc<str>>::into on \
10631                 RestartStrategy::{variant:?} must byte-equal \
10632                 RestartStrategy::as_str on the same input — the \
10633                 blanket-derived Into shape must resolve to the same \
10634                 as_str dispatch as the explicit From impl"
10635            );
10636            let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
10637            assert_eq!(
10638                via_trait.as_ref(),
10639                owned_static,
10640                "From<RestartStrategy> for std::sync::Arc<str> and \
10641                 From<RestartStrategy> for &'static str must resolve \
10642                 identically on RestartStrategy::{variant:?} — \
10643                 divergence signals the owned-input std::sync::Arc<str> \
10644                 and &'static str return-shape paths have drifted onto \
10645                 different emit-sets"
10646            );
10647            let owned_string: String = <String as From<RestartStrategy>>::from(variant);
10648            assert_eq!(
10649                via_trait.as_ref(),
10650                owned_string.as_str(),
10651                "From<RestartStrategy> for std::sync::Arc<str> and \
10652                 From<RestartStrategy> for String must resolve \
10653                 identically on RestartStrategy::{variant:?} — \
10654                 divergence signals the owned-input std::sync::Arc<str> \
10655                 and owned-`String` return-shape paths have drifted \
10656                 onto different emit-sets"
10657            );
10658            let owned_cow: std::borrow::Cow<'static, str> =
10659                <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
10660            assert_eq!(
10661                via_trait.as_ref(),
10662                owned_cow.as_ref(),
10663                "From<RestartStrategy> for std::sync::Arc<str> and \
10664                 From<RestartStrategy> for Cow<'static, str> must \
10665                 resolve identically on RestartStrategy::{variant:?} — \
10666                 divergence signals the owned-input std::sync::Arc<str> \
10667                 and Cow<'static, str> return-shape paths have drifted \
10668                 onto different emit-sets"
10669            );
10670            let owned_box: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
10671            assert_eq!(
10672                via_trait.as_ref(),
10673                owned_box.as_ref(),
10674                "From<RestartStrategy> for std::sync::Arc<str> and \
10675                 From<RestartStrategy> for Box<str> must resolve \
10676                 identically on RestartStrategy::{variant:?} — \
10677                 divergence signals the owned-input std::sync::Arc<str> \
10678                 and Box<str> return-shape paths have drifted onto \
10679                 different emit-sets"
10680            );
10681        }
10682    }
10683
10684    #[test]
10685    fn restart_strategy_from_borrowed_into_arc_str_routes_through_as_str_accessor() {
10686        // Fail-before-pass-after byte-parity pin on the newly lifted
10687        // `impl From<&RestartStrategy> for std::sync::Arc<str>` —
10688        // asserts the borrowed-input standard-library trait impl and
10689        // the substrate-primitive [`super::RestartStrategy::as_str`]
10690        // `pub const fn` accessor resolve to the same four-arm emit-
10691        // set across every arm the exhaustive
10692        // [`super::RestartStrategy::ALL`] slice enumerates. Rust's
10693        // standard library does not carry a blanket
10694        // `impl<T: AsRef<str>> From<&T> for std::sync::Arc<str>` (nor
10695        // a `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`),
10696        // so the borrowed-input [`std::sync::Arc<str>`] forward-
10697        // projection axis is a distinct trait-idiomatic surface that a
10698        // `let key: std::sync::Arc<str> = (&strategy).into();`-shaped
10699        // call site or a
10700        // `RestartStrategy::ALL.iter().map(std::sync::Arc::<str>::from)`-
10701        // shaped pipe reaches through this impl and no other — the
10702        // paired owned-input
10703        // `From<RestartStrategy> for std::sync::Arc<str>` impl
10704        // (bca2ec8) forces every borrowed-input call site through an
10705        // explicit `Copy` deref
10706        // (`std::sync::Arc::<str>::from((*strategy).as_str())`) or a
10707        // `std::sync::Arc::<str>::from(strategy.as_str())` open-code
10708        // whose type bounds have no compile-time link back to the
10709        // substrate primitive.
10710        //
10711        // Second peer on the substrate-wide trait-idiomatic
10712        // [`std::sync::Arc<str>`] forward-projection family on this
10713        // enum — closes the `{Self, &Self}` input-shape corner of
10714        // the [`std::sync::Arc<str>`] axis on the first M2 OTP-shape
10715        // closed-set fieldless typed enum peer on the caixa surface
10716        // (`:supervisor :estrategia`), exactly as 59ae5dc closed the
10717        // paired [`Box<str>`] axis one commit after its owning half
10718        // (69ef45c) landed. Every future closed-set fieldless typed
10719        // enum peer on the substrate is a future target of the
10720        // campaign.
10721        //
10722        // Also byte-parity witness against the paired owned-input
10723        // [`From<RestartStrategy> for std::sync::Arc<str>`] and the
10724        // sibling borrowed-input
10725        // [`From<&RestartStrategy> for &'static str`],
10726        // [`From<&RestartStrategy> for String`],
10727        // [`From<&RestartStrategy> for Cow<'static, str>`], and
10728        // [`From<&RestartStrategy> for Box<str>`] return-shape axes —
10729        // locking the five return-shape × input-shape paths together
10730        // by construction so any future detour trips at caixa-core
10731        // test time. Then a
10732        // `.iter().map(std::sync::Arc::<str>::from)` pipe witness over
10733        // [`super::RestartStrategy::ALL`] — whose iterator yields
10734        // `&RestartStrategy` by construction, so the borrowed-input
10735        // [`std::sync::Arc<str>`] axis is what routes the pipe
10736        // through the substrate-primitive
10737        // [`super::RestartStrategy::as_str`] accessor without a
10738        // spurious [`Copy`] deref (which would only be reachable
10739        // through the owned-input
10740        // [`From<RestartStrategy> for std::sync::Arc<str>`] axis by
10741        // first calling `.copied()` on the iterator).
10742        for &variant in RestartStrategy::ALL {
10743            let via_trait: std::sync::Arc<str> =
10744                <std::sync::Arc<str> as From<&RestartStrategy>>::from(&variant);
10745            let via_method: &'static str = variant.as_str();
10746            assert_eq!(
10747                via_trait.as_ref(),
10748                via_method,
10749                "From<&RestartStrategy> for std::sync::Arc<str> impl \
10750                 must round-trip &RestartStrategy::{variant:?} to the \
10751                 same lifted SUPERVISOR_ESTRATEGIA_* const \
10752                 RestartStrategy::as_str returns — divergence signals \
10753                 a silent detour off the substrate-primitive accessor"
10754            );
10755            let via_into: std::sync::Arc<str> = (&variant).into();
10756            assert_eq!(
10757                via_into.as_ref(),
10758                via_method,
10759                "Into<std::sync::Arc<str>>::into on \
10760                 &RestartStrategy::{variant:?} must byte-equal \
10761                 RestartStrategy::as_str on the same input — the \
10762                 blanket-derived Into shape must resolve to the same \
10763                 as_str dispatch as the explicit From impl"
10764            );
10765            let owned_arc: std::sync::Arc<str> =
10766                <std::sync::Arc<str> as From<RestartStrategy>>::from(variant);
10767            assert_eq!(
10768                via_trait, owned_arc,
10769                "From<&RestartStrategy> for std::sync::Arc<str> and \
10770                 From<RestartStrategy> for std::sync::Arc<str> must \
10771                 resolve identically on RestartStrategy::{variant:?} — \
10772                 divergence signals the borrowed-input and owned-input \
10773                 std::sync::Arc<str> forward-projection input-shape \
10774                 paths have drifted onto different emit-sets"
10775            );
10776            let borrowed_static: &'static str =
10777                <&'static str as From<&RestartStrategy>>::from(&variant);
10778            assert_eq!(
10779                via_trait.as_ref(),
10780                borrowed_static,
10781                "From<&RestartStrategy> for std::sync::Arc<str> and \
10782                 From<&RestartStrategy> for &'static str must resolve \
10783                 identically on RestartStrategy::{variant:?} — \
10784                 divergence signals the borrowed-input \
10785                 std::sync::Arc<str> and &'static str return-shape \
10786                 paths have drifted onto different emit-sets"
10787            );
10788            let borrowed_string: String = <String as From<&RestartStrategy>>::from(&variant);
10789            assert_eq!(
10790                via_trait.as_ref(),
10791                borrowed_string.as_str(),
10792                "From<&RestartStrategy> for std::sync::Arc<str> and \
10793                 From<&RestartStrategy> for String must resolve \
10794                 identically on RestartStrategy::{variant:?} — \
10795                 divergence signals the borrowed-input \
10796                 std::sync::Arc<str> and owned-`String` return-shape \
10797                 paths have drifted onto different emit-sets"
10798            );
10799            let borrowed_cow: std::borrow::Cow<'static, str> =
10800                <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&variant);
10801            assert_eq!(
10802                via_trait.as_ref(),
10803                borrowed_cow.as_ref(),
10804                "From<&RestartStrategy> for std::sync::Arc<str> and \
10805                 From<&RestartStrategy> for Cow<'static, str> must \
10806                 resolve identically on RestartStrategy::{variant:?} — \
10807                 divergence signals the borrowed-input \
10808                 std::sync::Arc<str> and Cow<'static, str> return-shape \
10809                 paths have drifted onto different emit-sets"
10810            );
10811            let borrowed_box: Box<str> = <Box<str> as From<&RestartStrategy>>::from(&variant);
10812            assert_eq!(
10813                via_trait.as_ref(),
10814                borrowed_box.as_ref(),
10815                "From<&RestartStrategy> for std::sync::Arc<str> and \
10816                 From<&RestartStrategy> for Box<str> must resolve \
10817                 identically on RestartStrategy::{variant:?} — \
10818                 divergence signals the borrowed-input \
10819                 std::sync::Arc<str> and Box<str> return-shape paths \
10820                 have drifted onto different emit-sets"
10821            );
10822        }
10823        let via_iter: Vec<std::sync::Arc<str>> = RestartStrategy::ALL
10824            .iter()
10825            .map(std::sync::Arc::<str>::from)
10826            .collect();
10827        let via_method: Vec<std::sync::Arc<str>> = RestartStrategy::ALL
10828            .iter()
10829            .map(|s| std::sync::Arc::<str>::from(s.as_str()))
10830            .collect();
10831        assert_eq!(
10832            via_iter, via_method,
10833            "`.iter().map(std::sync::Arc::<str>::from)` over \
10834             RestartStrategy::ALL — a call site whose iteration axis \
10835             holds `&RestartStrategy` by construction — must byte-\
10836             equal `.iter().map(|s| std::sync::Arc::<str>::from(s.as_str()))` \
10837             on every arm — the borrowed-input std::sync::Arc<str> \
10838             `From<&RestartStrategy> for std::sync::Arc<str>` axis is \
10839             what makes the `std::sync::Arc::<str>::from` composition \
10840             route through the substrate-primitive \
10841             `RestartStrategy::as_str` accessor without a spurious \
10842             `Copy` deref (which would only be reachable through the \
10843             owned-input `From<RestartStrategy> for std::sync::Arc<str>` \
10844             axis by first calling `.copied()` on the iterator)"
10845        );
10846    }
10847
10848    #[test]
10849    #[allow(
10850        clippy::too_many_lines,
10851        reason = "cross-axis partition pin folds the substrate-primitive \
10852                  as_str accessor's `.as_bytes()` byte-tail plus the \
10853                  paired str-view (AsRef<str>, Display, as_str) and \
10854                  reverse-projection ({&'static str, String, Cow<'static, \
10855                  str>, Box<str>, std::sync::Arc<str>}) return-shape \
10856                  axes' `.as_bytes()` byte-tails plus a <T: AsRef<[u8]>>\
10857                  -bound-consumer witness plus a blake3::Hasher::update-\
10858                  shape byte-input surface witness into one exhaustive \
10859                  round-trip over RestartStrategy::ALL — the accepted \
10860                  line-count cost of opening the byte-view axis keyed \
10861                  to the substrate-primitive as_str accessor at the \
10862                  same test-site"
10863    )]
10864    #[allow(
10865        clippy::needless_borrows_for_generic_args,
10866        reason = "the borrowed-input surface (&variant) is exercised \
10867                  deliberately: the `<T: AsRef<[u8]>>`-bound consumer \
10868                  and the `blake3::Hasher::update`-shape byte-input \
10869                  surface both accept either owned or borrowed input \
10870                  through the standard-library blanket \
10871                  `impl<T: ?Sized + AsRef<[u8]>> AsRef<[u8]> for &T`, \
10872                  and this pin round-trips both input shapes to lock \
10873                  the borrowed-input path load-bearing against a \
10874                  future silent regression"
10875    )]
10876    fn restart_strategy_as_ref_bytes_routes_through_as_str_accessor() {
10877        // `<T: AsRef<[u8]>>`-bound generic-consumer witness: a byte-input
10878        // function that binds its argument through the standard-library
10879        // [`AsRef<[u8]>`] trait bound accepts a [`super::RestartStrategy`]
10880        // directly, without the caller open-coding the two-hop
10881        // `estrategia.as_str().as_bytes()` composition. Lifted to the top
10882        // of the function per `clippy::items_after_statements`.
10883        fn generic_bytes_sink<T: AsRef<[u8]>>(t: T) -> Vec<u8> {
10884            t.as_ref().to_vec()
10885        }
10886        // `blake3::Hasher::update`-shape byte-input surface mock: mirrors
10887        // `blake3::Hasher::update` / `ring::digest::Context::update` /
10888        // `sha2::Sha256::update`'s `impl AsRef<[u8]>`-bound `update`
10889        // signature so a per-supervisor BLAKE3 content-address closure
10890        // that composes `hasher.update(estrategia)` on the
10891        // [`crate::Lacre`] closure builder reaches the substrate-primitive
10892        // `as_str` accessor through the [`super::RestartStrategy`]
10893        // `AsRef<[u8]>` axis and no other. Lifted to the top of the
10894        // function per `clippy::items_after_statements`.
10895        struct MockHasher(Vec<u8>);
10896        impl MockHasher {
10897            fn new() -> Self {
10898                Self(Vec::new())
10899            }
10900            fn update(&mut self, bytes: impl AsRef<[u8]>) -> &mut Self {
10901                self.0.extend_from_slice(bytes.as_ref());
10902                self
10903            }
10904            fn finalize(self) -> Vec<u8> {
10905                self.0
10906            }
10907        }
10908
10909        // Fail-before-pass-after byte-parity pin on the newly lifted
10910        // `impl AsRef<[u8]> for RestartStrategy` — asserts the trait-
10911        // idiomatic byte-view standard-library impl and the substrate-
10912        // primitive [`super::RestartStrategy::as_str`] `pub const fn`
10913        // accessor's `.as_bytes()` byte-tail resolve to the same four-arm
10914        // `PascalCase` wire byte-string emit-set across every arm the
10915        // exhaustive [`super::RestartStrategy::ALL`] slice enumerates.
10916        // Opens the trait-idiomatic byte-view axis onto the first M2
10917        // OTP-shape closed-set fieldless typed enum peer on the caixa
10918        // surface (`:supervisor :estrategia`), extending the substrate-
10919        // wide byte-view campaign the sibling
10920        // [`super::crate::CaixaKind`] first-mover (69d8d86) opened.
10921        //
10922        // Rust's standard library carries `impl AsRef<[u8]> for str` and
10923        // `impl AsRef<[u8]> for String`, so a two-hop composition
10924        // `estrategia.as_str().as_bytes()` (or the equally two-hop
10925        // `AsRef::<str>::as_ref(&estrategia).as_bytes()`) is reachable
10926        // through the pre-existing str-view axis alone. But that two-hop
10927        // shape has no compile-time link back to the byte-projection
10928        // axis, forces every downstream `<T: AsRef<[u8]>>`-bound
10929        // consumer to open-code the two-hop composition at every call
10930        // site, and admits a silent split whenever a future call site
10931        // takes a sibling reverse-projection axis whose `.as_bytes()`
10932        // byte-tail carries no compile-time byte-view surface. This
10933        // impl closes the byte-view axis at the substrate-primitive
10934        // [`super::RestartStrategy::as_str`] accessor so every future
10935        // `<T: AsRef<[u8]>>`-bound consumer reaches the same lifted
10936        // [`super::crate::render::SUPERVISOR_ESTRATEGIA_*`] const roster
10937        // the paired str-view axes already return through — through one
10938        // trait dispatch.
10939        for &variant in RestartStrategy::ALL {
10940            let via_trait: &[u8] = <RestartStrategy as AsRef<[u8]>>::as_ref(&variant);
10941            let via_method_bytes: &[u8] = variant.as_str().as_bytes();
10942            assert_eq!(
10943                via_trait, via_method_bytes,
10944                "AsRef<[u8]> for RestartStrategy impl must byte-equal \
10945                 RestartStrategy::as_str().as_bytes() on \
10946                 RestartStrategy::{variant:?} — divergence signals a \
10947                 silent detour off the substrate-primitive accessor"
10948            );
10949            // Cross-axis witness against the paired str-view axes'
10950            // `.as_bytes()` byte-tails: [`AsRef<str>`] /
10951            // [`std::fmt::Display`] / [`super::RestartStrategy::as_str`]
10952            // all resolve to the same lifted
10953            // [`super::crate::render::SUPERVISOR_ESTRATEGIA_*`] const
10954            // roster, and the byte-view axis must byte-equal each of
10955            // their `.as_bytes()` byte-tails by construction — locking
10956            // the str-view and byte-view axes together at the
10957            // substrate-primitive accessor.
10958            let str_view_ref: &str = <RestartStrategy as AsRef<str>>::as_ref(&variant);
10959            assert_eq!(
10960                via_trait,
10961                str_view_ref.as_bytes(),
10962                "AsRef<[u8]> for RestartStrategy and AsRef<str> for \
10963                 RestartStrategy must resolve to byte-equal byte-tails \
10964                 on RestartStrategy::{variant:?} — divergence signals \
10965                 the byte-view and str-view axes have drifted off the \
10966                 same substrate-primitive as_str accessor"
10967            );
10968            let display_bytes = variant.to_string();
10969            assert_eq!(
10970                via_trait,
10971                display_bytes.as_bytes(),
10972                "AsRef<[u8]> for RestartStrategy and \
10973                 <RestartStrategy as std::fmt::Display>::to_string must \
10974                 resolve to byte-equal byte-tails on \
10975                 RestartStrategy::{variant:?} — divergence signals the \
10976                 byte-view axis and the Display formatter axis have \
10977                 drifted off the same substrate-primitive as_str \
10978                 accessor"
10979            );
10980            // Cross-axis witness against the paired reverse-projection
10981            // axes' `.as_bytes()` byte-tails: every one of `{&'static
10982            // str, String, Cow<'static, str>, Box<str>,
10983            // std::sync::Arc<str>}` allocates (or borrows) the same
10984            // `PascalCase` wire byte-string the substrate-primitive
10985            // accessor emits, so the byte-view axis must byte-equal
10986            // each of their `.as_bytes()` byte-tails by construction.
10987            let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
10988            assert_eq!(
10989                via_trait,
10990                owned_static.as_bytes(),
10991                "AsRef<[u8]> for RestartStrategy and From<RestartStrategy> \
10992                 for &'static str must resolve to byte-equal byte-tails \
10993                 on RestartStrategy::{variant:?}"
10994            );
10995            let owned_string: String = <String as From<RestartStrategy>>::from(variant);
10996            assert_eq!(
10997                via_trait,
10998                owned_string.as_bytes(),
10999                "AsRef<[u8]> for RestartStrategy and From<RestartStrategy> \
11000                 for String must resolve to byte-equal byte-tails on \
11001                 RestartStrategy::{variant:?}"
11002            );
11003            let owned_cow: std::borrow::Cow<'static, str> =
11004                <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
11005            assert_eq!(
11006                via_trait,
11007                owned_cow.as_bytes(),
11008                "AsRef<[u8]> for RestartStrategy and From<RestartStrategy> \
11009                 for Cow<'static, str> must resolve to byte-equal byte-\
11010                 tails on RestartStrategy::{variant:?}"
11011            );
11012            let owned_box: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
11013            assert_eq!(
11014                via_trait,
11015                owned_box.as_bytes(),
11016                "AsRef<[u8]> for RestartStrategy and From<RestartStrategy> \
11017                 for Box<str> must resolve to byte-equal byte-tails on \
11018                 RestartStrategy::{variant:?}"
11019            );
11020            let owned_arc: std::sync::Arc<str> =
11021                <std::sync::Arc<str> as From<RestartStrategy>>::from(variant);
11022            assert_eq!(
11023                via_trait,
11024                owned_arc.as_bytes(),
11025                "AsRef<[u8]> for RestartStrategy and From<RestartStrategy> \
11026                 for std::sync::Arc<str> must resolve to byte-equal byte-\
11027                 tails on RestartStrategy::{variant:?}"
11028            );
11029        }
11030        // `<T: AsRef<[u8]>>`-bound-consumer witness: the generic byte-
11031        // input function `generic_bytes_sink` (lifted above per
11032        // `clippy::items_after_statements`) accepts a
11033        // [`super::RestartStrategy`] directly through the trait bound,
11034        // without the caller open-coding the two-hop
11035        // `estrategia.as_str().as_bytes()` composition. This is the
11036        // shape that reaches the caixa-lacre BLAKE3 content-address
11037        // closure's `blake3::Hasher::update(impl AsRef<[u8]>)` byte-
11038        // input surface through this impl and no other.
11039        for &variant in RestartStrategy::ALL {
11040            let via_generic = generic_bytes_sink(variant);
11041            let via_borrowed_generic = generic_bytes_sink(&variant);
11042            let via_method_bytes = variant.as_str().as_bytes().to_vec();
11043            assert_eq!(
11044                via_generic, via_method_bytes,
11045                "generic `<T: AsRef<[u8]>>`-bound consumer on \
11046                 RestartStrategy::{variant:?} must yield the same byte-\
11047                 tail RestartStrategy::as_str().as_bytes() returns — \
11048                 divergence signals the byte-view axis fails to bridge \
11049                 a generic byte-input trait bound to the substrate-\
11050                 primitive accessor"
11051            );
11052            assert_eq!(
11053                via_borrowed_generic, via_method_bytes,
11054                "generic `<T: AsRef<[u8]>>`-bound consumer on \
11055                 &RestartStrategy::{variant:?} must yield the same byte-\
11056                 tail RestartStrategy::as_str().as_bytes() returns — \
11057                 the borrowed-input surface must resolve to the same \
11058                 as_str dispatch"
11059            );
11060        }
11061        // `blake3::Hasher::update`-shape byte-input surface witness on
11062        // the caixa-lacre compounding target: the `MockHasher` (lifted
11063        // above per `clippy::items_after_statements`) mirrors
11064        // `blake3::Hasher::update` / `ring::digest::Context::update` /
11065        // `sha2::Sha256::update`'s `impl AsRef<[u8]>`-bound update
11066        // signature and accepts a [`super::RestartStrategy`] directly,
11067        // routing its byte-tail through the substrate-primitive
11068        // `as_str` accessor — the shape a future per-supervisor BLAKE3
11069        // content-address closure composes to fold an `:estrategia`
11070        // discriminator byte-tag into the [`crate::Lacre`] closure
11071        // body.
11072        for &variant in RestartStrategy::ALL {
11073            let mut owned_hasher = MockHasher::new();
11074            owned_hasher.update(variant);
11075            let owned_folded = owned_hasher.finalize();
11076            assert_eq!(
11077                owned_folded,
11078                variant.as_str().as_bytes(),
11079                "`hasher.update(estrategia)`-shape composition on \
11080                 RestartStrategy::{variant:?} must fold the same byte-\
11081                 tail RestartStrategy::as_str().as_bytes() returns — \
11082                 the shape a future per-supervisor BLAKE3 content-\
11083                 address closure composes to fold an `:estrategia` \
11084                 discriminator byte-tag into the Lacre closure body"
11085            );
11086            let mut borrowed_hasher = MockHasher::new();
11087            borrowed_hasher.update(&variant);
11088            let borrowed_folded = borrowed_hasher.finalize();
11089            assert_eq!(
11090                borrowed_folded,
11091                variant.as_str().as_bytes(),
11092                "`hasher.update(&estrategia)`-shape composition on \
11093                 &RestartStrategy::{variant:?} must fold the same byte-\
11094                 tail RestartStrategy::as_str().as_bytes() returns — \
11095                 the borrowed-input surface must resolve to the same \
11096                 as_str dispatch"
11097            );
11098        }
11099    }
11100
11101    #[test]
11102    #[expect(
11103        clippy::too_many_lines,
11104        reason = "the byte-owned reverse-projection axis is extended \
11105                  here onto the first M2-OTP-shape closed-set fieldless \
11106                  typed-enum peer, so the pin binds the new impl against \
11107                  every paired byte-view and str-owned axis on the same \
11108                  enum plus a generic <T: Into<Vec<u8>>>-bound consumer \
11109                  witness and a std::io::Write::write_all-shape owned-\
11110                  byte-sink surface witness on both owned and borrowed \
11111                  input shapes to lock the whole family against a future \
11112                  silent regression"
11113    )]
11114    fn restart_strategy_from_into_owned_vec_bytes_routes_through_as_str_accessor() {
11115        // `<T: Into<Vec<u8>>>`-bound-consumer witness helper: a generic
11116        // owned-byte-input function accepts a [`super::RestartStrategy`]
11117        // directly through the trait bound, without the caller open-
11118        // coding the three-hop `strategy.as_str().as_bytes().to_vec()`
11119        // composition. Lifted to the top of the function per
11120        // `clippy::items_after_statements`.
11121        fn generic_owned_bytes_sink<T: Into<Vec<u8>>>(t: T) -> Vec<u8> {
11122            t.into()
11123        }
11124        // `std::io::Write::write_all`-shape owned-byte-sink surface
11125        // mock: mirrors `std::io::Write::write_all` /
11126        // `bytes::BytesMut::extend_from_slice` / any per-arm audit-log
11127        // byte-sink that consumes a `Vec<u8>` payload via
11128        // `Into<Vec<u8>>`, so a future per-supervisor per-`:estrategia`
11129        // audit-log emit reaches the substrate-primitive `as_str`
11130        // accessor through the byte-owned reverse-projection axis and
11131        // no other. Lifted to the top of the function per
11132        // `clippy::items_after_statements`.
11133        struct MockOwnedByteSink(Vec<u8>);
11134        impl MockOwnedByteSink {
11135            fn new() -> Self {
11136                Self(Vec::new())
11137            }
11138            fn write_all(&mut self, bytes: impl Into<Vec<u8>>) -> &mut Self {
11139                self.0.extend_from_slice(&bytes.into());
11140                self
11141            }
11142            fn finalize(self) -> Vec<u8> {
11143                self.0
11144            }
11145        }
11146
11147        // Fail-before-pass-after byte-parity pin on the newly lifted
11148        // `impl From<RestartStrategy> for Vec<u8>` and
11149        // `impl From<&RestartStrategy> for Vec<u8>` — asserts the trait-
11150        // idiomatic byte-owned reverse-projection standard-library
11151        // impls and the substrate-primitive
11152        // [`super::RestartStrategy::as_str`] `pub const fn` accessor's
11153        // `.as_bytes().to_vec()` byte-tail resolve to the same four-arm
11154        // PascalCase wire byte-string emit-set across every arm the
11155        // exhaustive [`super::RestartStrategy::ALL`] slice enumerates.
11156        // Extends the substrate-wide trait-idiomatic byte-owned
11157        // reverse-projection axis onto the first M2-OTP-shape closed-
11158        // set fieldless typed-enum peer on the caixa surface
11159        // (`:supervisor :estrategia`), matching the trajectory the
11160        // first-mover [`super::crate::CaixaKind`] lift (b245fd6), the
11161        // second-mover [`super::crate::dialeto::CaixaDialeto`] lift
11162        // (4cceaf5), and the third-mover
11163        // [`super::crate::dep::DepList`] lift (e974ca2) established
11164        // across the caixa-core-internal tier.
11165        for &variant in RestartStrategy::ALL {
11166            let via_owned_from: Vec<u8> = <Vec<u8> as From<RestartStrategy>>::from(variant);
11167            let via_borrowed_from: Vec<u8> = <Vec<u8> as From<&RestartStrategy>>::from(&variant);
11168            let via_method_bytes: Vec<u8> = variant.as_str().as_bytes().to_vec();
11169            assert_eq!(
11170                via_owned_from, via_method_bytes,
11171                "From<RestartStrategy> for Vec<u8> impl must byte-equal \
11172                 RestartStrategy::as_str().as_bytes().to_vec() on \
11173                 RestartStrategy::{variant:?} — divergence signals a \
11174                 silent detour off the substrate-primitive accessor"
11175            );
11176            assert_eq!(
11177                via_borrowed_from, via_method_bytes,
11178                "From<&RestartStrategy> for Vec<u8> impl must byte-\
11179                 equal RestartStrategy::as_str().as_bytes().to_vec() \
11180                 on RestartStrategy::{variant:?} — divergence signals \
11181                 a silent detour off the substrate-primitive accessor"
11182            );
11183            assert_eq!(
11184                via_owned_from, via_borrowed_from,
11185                "From<RestartStrategy> for Vec<u8> and \
11186                 From<&RestartStrategy> for Vec<u8> must byte-equal \
11187                 each other on RestartStrategy::{variant:?} — \
11188                 divergence signals the owned-input and borrowed-input \
11189                 paths have drifted off the same substrate-primitive \
11190                 as_str accessor"
11191            );
11192            // Cross-axis witness against the paired [`AsRef<[u8]>`]
11193            // borrowed byte-view axis (cd4c4e0): the byte-owned
11194            // reverse-projection axis must byte-equal the paired
11195            // borrowed byte-view axis by construction — locking the
11196            // byte-view and byte-owned axes together at the substrate-
11197            // primitive accessor.
11198            let borrowed_bytes: &[u8] = <RestartStrategy as AsRef<[u8]>>::as_ref(&variant);
11199            assert_eq!(
11200                via_owned_from,
11201                borrowed_bytes.to_vec(),
11202                "From<RestartStrategy> for Vec<u8> and AsRef<[u8]> \
11203                 for RestartStrategy must resolve to byte-equal byte-\
11204                 tails on RestartStrategy::{variant:?} — divergence \
11205                 signals the byte-owned and byte-view axes have \
11206                 drifted off the same substrate-primitive as_str \
11207                 accessor"
11208            );
11209            // Cross-axis witness against the str-owned reverse-
11210            // projection family's `.into_bytes()` / `.as_bytes().to_vec()`
11211            // byte-tails: every one of `{String, Cow<'static, str>,
11212            // Box<str>, std::sync::Arc<str>, std::rc::Rc<str>}`
11213            // allocates (or borrows) the same PascalCase wire byte-
11214            // string the substrate-primitive accessor emits, so the
11215            // byte-owned axis must byte-equal each of their owned
11216            // byte-tails by construction.
11217            let owned_string: String = <String as From<RestartStrategy>>::from(variant);
11218            assert_eq!(
11219                via_owned_from,
11220                owned_string.into_bytes(),
11221                "From<RestartStrategy> for Vec<u8> and \
11222                 String::from(strategy).into_bytes() must resolve to \
11223                 byte-equal byte-tails on RestartStrategy::{variant:?}"
11224            );
11225            let owned_cow: std::borrow::Cow<'static, str> =
11226                <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
11227            assert_eq!(
11228                via_owned_from,
11229                owned_cow.as_bytes().to_vec(),
11230                "From<RestartStrategy> for Vec<u8> and \
11231                 From<RestartStrategy> for Cow<'static, str> must \
11232                 resolve to byte-equal byte-tails on \
11233                 RestartStrategy::{variant:?}"
11234            );
11235            let owned_box: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
11236            assert_eq!(
11237                via_owned_from,
11238                owned_box.as_bytes().to_vec(),
11239                "From<RestartStrategy> for Vec<u8> and \
11240                 From<RestartStrategy> for Box<str> must resolve to \
11241                 byte-equal byte-tails on RestartStrategy::{variant:?}"
11242            );
11243            let owned_arc: std::sync::Arc<str> =
11244                <std::sync::Arc<str> as From<RestartStrategy>>::from(variant);
11245            assert_eq!(
11246                via_owned_from,
11247                owned_arc.as_bytes().to_vec(),
11248                "From<RestartStrategy> for Vec<u8> and \
11249                 From<RestartStrategy> for std::sync::Arc<str> must \
11250                 resolve to byte-equal byte-tails on \
11251                 RestartStrategy::{variant:?}"
11252            );
11253        }
11254        // `<T: Into<Vec<u8>>>`-bound-consumer witness on both owned
11255        // and borrowed input shapes: the generic owned-byte-input
11256        // function `generic_owned_bytes_sink` (lifted above per
11257        // `clippy::items_after_statements`) accepts a
11258        // [`super::RestartStrategy`] and a `&RestartStrategy`
11259        // directly through the trait bound, without the caller open-
11260        // coding the three-hop `strategy.as_str().as_bytes().to_vec()`
11261        // composition.
11262        for &variant in RestartStrategy::ALL {
11263            let via_generic_owned = generic_owned_bytes_sink(variant);
11264            // Bind the borrowed-input path through an explicit
11265            // `&RestartStrategy` local so the generic-consumer witness
11266            // routes through `From<&RestartStrategy> for Vec<u8>` (T
11267            // binds to `&RestartStrategy`) rather than clippy-collapsing
11268            // the borrow onto the owned-input peer.
11269            let variant_ref: &RestartStrategy = &variant;
11270            let via_generic_borrowed = generic_owned_bytes_sink(variant_ref);
11271            let via_method_bytes = variant.as_str().as_bytes().to_vec();
11272            assert_eq!(
11273                via_generic_owned, via_method_bytes,
11274                "generic `<T: Into<Vec<u8>>>`-bound consumer on \
11275                 RestartStrategy::{variant:?} must yield the same byte-\
11276                 tail RestartStrategy::as_str().as_bytes() returns — \
11277                 divergence signals the byte-owned axis fails to bridge \
11278                 a generic owned-byte-input trait bound to the \
11279                 substrate-primitive accessor"
11280            );
11281            assert_eq!(
11282                via_generic_borrowed, via_method_bytes,
11283                "generic `<T: Into<Vec<u8>>>`-bound consumer on \
11284                 &RestartStrategy::{variant:?} must yield the same byte-\
11285                 tail RestartStrategy::as_str().as_bytes() returns — \
11286                 the borrowed-input surface must resolve to the same \
11287                 as_str dispatch"
11288            );
11289        }
11290        // `std::io::Write::write_all`-shape owned-byte-sink surface
11291        // witness: the `MockOwnedByteSink` (lifted above per
11292        // `clippy::items_after_statements`) mirrors
11293        // `std::io::Write::write_all` /
11294        // `bytes::BytesMut::extend_from_slice`'s `impl Into<Vec<u8>>`-
11295        // bound owned-byte input signature and accepts a
11296        // [`super::RestartStrategy`] directly on both owned and
11297        // borrowed input shapes, routing its byte-tail through the
11298        // substrate-primitive `as_str` accessor — the shape a future
11299        // per-supervisor per-`:estrategia` audit-log emit composes to
11300        // fold an `:estrategia` discriminator byte-tag into a
11301        // downstream owned-byte-sink surface.
11302        for &variant in RestartStrategy::ALL {
11303            let mut owned_sink = MockOwnedByteSink::new();
11304            owned_sink.write_all(variant);
11305            let owned_folded = owned_sink.finalize();
11306            assert_eq!(
11307                owned_folded,
11308                variant.as_str().as_bytes(),
11309                "`sink.write_all(strategy)`-shape composition on \
11310                 RestartStrategy::{variant:?} must fold the same byte-\
11311                 tail RestartStrategy::as_str().as_bytes() returns"
11312            );
11313            let mut borrowed_sink = MockOwnedByteSink::new();
11314            let variant_ref: &RestartStrategy = &variant;
11315            borrowed_sink.write_all(variant_ref);
11316            let borrowed_folded = borrowed_sink.finalize();
11317            assert_eq!(
11318                borrowed_folded,
11319                variant.as_str().as_bytes(),
11320                "`sink.write_all(&strategy)`-shape composition on \
11321                 &RestartStrategy::{variant:?} must fold the same byte-\
11322                 tail RestartStrategy::as_str().as_bytes() returns — \
11323                 the borrowed-input surface must resolve to the same \
11324                 as_str dispatch"
11325            );
11326        }
11327    }
11328
11329    #[test]
11330    fn restart_policy_try_from_str_routes_through_from_wire_accessor() {
11331        // Fail-before-pass-after byte-parity pin on the newly lifted
11332        // `impl TryFrom<&str> for RestartPolicy` — asserts the standard-
11333        // library trait impl and the substrate-primitive
11334        // [`RestartPolicy::from_wire`] `Option<Self>` accessor resolve to
11335        // the same three-arm accept-set across every arm the exhaustive
11336        // [`RestartPolicy::ALL`] slice enumerates. Any future silent
11337        // detour that routes the trait impl through a divergent
11338        // projection (a per-arm inline `match s { "Permanent" =>
11339        // Ok(Self::Permanent), … }` re-inlining that opens a compile-time
11340        // link to the un-lifted arm-literal, a hypothetical
11341        // `#[serde(rename_all = "…")]` attribute drift that silently
11342        // splits the wire byte-string from every consumer that reaches
11343        // for this typed dispatch, an accidental swap onto the kebab-case
11344        // dispatcher-catalog axis the pre-existing [`std::str::FromStr`]
11345        // impl parses through and which would collide the two-axis
11346        // wire/catalog split the sibling [`RestartPolicy::from_wire`]
11347        // doc block makes load-bearing) trips at caixa-core test time
11348        // under `assert_eq!` rather than at a downstream
11349        // `impl TryFrom<&str>`-bound consumer's silent split. Sweeps
11350        // every one of the three arms [`RestartPolicy::ALL`] carries so
11351        // no arm's projection is covered only by the sibling method-
11352        // named `from_wire` path. Peer of the sibling
11353        // [`restart_strategy_try_from_str_routes_through_from_wire_accessor`]
11354        // (5b828ed) — extends the trait-idiomatic reverse-projection
11355        // axis onto the third and final M2-OTP-shape closed-set typed
11356        // enum on the caixa surface (the paired per-child restart-
11357        // decision-policy sibling on the same M2 `:supervisor` slot).
11358        for &variant in RestartPolicy::ALL {
11359            let wire = variant.as_str();
11360            assert_eq!(
11361                <RestartPolicy as TryFrom<&str>>::try_from(wire),
11362                Ok(variant),
11363                "TryFrom<&str> impl on RestartPolicy must round-trip \
11364                 RestartPolicy::{variant:?}.as_str() = {wire:?} back to \
11365                 Ok(RestartPolicy::{variant:?}) — divergence from \
11366                 RestartPolicy::from_wire signals a silent detour off \
11367                 the substrate-primitive accessor"
11368            );
11369            assert_eq!(
11370                <RestartPolicy as TryFrom<&str>>::try_from(wire).ok(),
11371                RestartPolicy::from_wire(wire),
11372                "TryFrom<&str> ok()-projection on {wire:?} must byte-\
11373                 equal RestartPolicy::from_wire on the same input"
11374            );
11375        }
11376    }
11377
11378    #[test]
11379    fn restart_policy_try_from_str_rejects_unknown_byte_strings() {
11380        // Rejection witness on the `impl TryFrom<&str> for
11381        // RestartPolicy` — sweeps a candidate set of byte-strings
11382        // outside the three-arm PascalCase wire accept-set the sibling
11383        // [`RestartPolicy::as_str`] emits and asserts every one lands on
11384        // `Err(())`, so a future accidental widening of the trait impl's
11385        // accept-set (a stray additional
11386        // `_ if s.eq_ignore_ascii_case("Permanent") => Ok(…)` case-fold
11387        // path, a silent inclusion of the kebab-case dispatcher-catalog
11388        // byte-string the pre-existing [`std::str::FromStr`] impl the
11389        // [`gen_platform::FromStrKind`] derive installs parses onto the
11390        // wire axis — which would collide the two-axis
11391        // wire/dispatcher-catalog split the sibling
11392        // [`RestartPolicy::from_wire`] doc block makes load-bearing —
11393        // an English-rebrand or plural-arm silent alias that would widen
11394        // the wire accept-set past the OTP-canonical three) trips at
11395        // caixa-core test time. The candidate set includes the empty
11396        // string, whitespace-only padding, the kebab-case dispatcher-
11397        // catalog byte-strings on the sibling axis (a caller who
11398        // confuses the two axes trips here rather than at a downstream
11399        // consumer's silent reject), a lowercase / uppercase / mixed-case
11400        // fold of each PascalCase arm (a caller who assumes case-fold
11401        // acceptance trips here), leading/trailing whitespace padding,
11402        // the trailing-newline shape, quote-wrapped candidates, and a
11403        // residual set of plausible-but-wrong English rebrand
11404        // candidates. Peer of the sibling
11405        // [`restart_strategy_try_from_str_rejects_unknown_byte_strings`]
11406        // (5b828ed) rejection witness.
11407        let rejected: &[&str] = &[
11408            "",
11409            " ",
11410            "\n",
11411            "\t",
11412            "permanent",
11413            "temporary",
11414            "transient",
11415            "PERMANENT",
11416            "TEMPORARY",
11417            "TRANSIENT",
11418            "Permanents",
11419            "Permanent ",
11420            " Permanent",
11421            " Temporary ",
11422            "Permanent\n",
11423            "Transient\t",
11424            "\"Permanent\"",
11425            "Ephemeral",
11426            "Always",
11427            "Never",
11428            "OnAbnormalExit",
11429            "intrinsic",
11430            "?",
11431        ];
11432        for &input in rejected {
11433            assert_eq!(
11434                <RestartPolicy as TryFrom<&str>>::try_from(input),
11435                Err(()),
11436                "TryFrom<&str> impl on RestartPolicy must reject the \
11437                 non-wire byte-string {input:?} — silent acceptance \
11438                 signals an accept-set widening off the paired \
11439                 RestartPolicy::from_wire resolver"
11440            );
11441        }
11442    }
11443
11444    #[test]
11445    fn restart_policy_try_from_str_and_from_wire_partition_the_accept_set() {
11446        // Cross-axis partition pin: the paired `TryFrom<&str>` and
11447        // `from_wire` reverse projections must resolve identically on
11448        // *every* input, not just the ones [`RestartPolicy::ALL`]
11449        // enumerates. Sweeps a mixed candidate set spanning accepted
11450        // (three-arm PascalCase wire byte-strings) and rejected (kebab-
11451        // case dispatcher-catalog byte-strings, empty, whitespace-
11452        // padded, quoted, English-rebrand candidates) inputs and asserts
11453        // the trait's `Result::ok()` projection byte-equals the method-
11454        // named resolver's `Option<Self>` return-shape on each, locking
11455        // the two paths together by construction so any future detour
11456        // (a stray `try_from` special-case that widens or narrows the
11457        // accept-set outside the paired `from_wire` resolver, an
11458        // accidental swap onto the kebab-case [`std::str::FromStr`]
11459        // impl the [`gen_platform::FromStrKind`] derive installs on the
11460        // sibling dispatcher-catalog axis) trips at caixa-core test
11461        // time. Peer of the sibling
11462        // [`restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
11463        // pin — extends the round-trip discipline onto the M2-OTP-shape
11464        // per-child restart-policy axis.
11465        let candidates: &[&str] = &[
11466            "Permanent",
11467            "Temporary",
11468            "Transient",
11469            "",
11470            "permanent",
11471            "temporary",
11472            "transient",
11473            "PERMANENT",
11474            "unknown",
11475            "Permanent ",
11476            " Permanent",
11477            "\"Permanent\"",
11478            "Ephemeral",
11479            "OnAbnormalExit",
11480            "?",
11481        ];
11482        for &input in candidates {
11483            let via_trait: Option<RestartPolicy> =
11484                <RestartPolicy as TryFrom<&str>>::try_from(input).ok();
11485            let via_method: Option<RestartPolicy> = RestartPolicy::from_wire(input);
11486            assert_eq!(
11487                via_trait, via_method,
11488                "TryFrom<&str> and from_wire must resolve identically on \
11489                 input {input:?} — divergence signals the two reverse-\
11490                 projection paths have drifted onto different accept-sets"
11491            );
11492        }
11493    }
11494
11495    #[test]
11496    fn restart_policy_from_into_static_str_routes_through_as_str_accessor() {
11497        // Fail-before-pass-after byte-parity pin on the newly lifted
11498        // `impl From<RestartPolicy> for &'static str` — asserts the
11499        // standard-library trait impl and the substrate-primitive
11500        // [`RestartPolicy::as_str`] `pub const fn` accessor resolve to
11501        // the same three-arm emit-set across every arm the exhaustive
11502        // [`RestartPolicy::ALL`] slice enumerates. Any future silent
11503        // detour that routes the trait impl through a divergent
11504        // projection (a per-arm inline `match policy { Permanent =>
11505        // "Permanent", … }` re-inlining that opens a compile-time link
11506        // to the un-lifted arm-literal, an accidental swap onto the
11507        // sibling kebab-case [`Self::discriminant`] dispatcher-catalog
11508        // axis that would collide the two-axis wire/catalog split the
11509        // sibling [`RestartPolicy::from_wire`] doc block makes
11510        // load-bearing) trips at caixa-core test time under
11511        // `assert_eq!` rather than at a downstream
11512        // `impl Into<&'static str>`-bound consumer's silent split.
11513        // Sweeps every one of the three arms [`RestartPolicy::ALL`]
11514        // carries so no arm's projection is covered only by the sibling
11515        // method-named `as_str` / [`std::fmt::Display`] / [`AsRef<str>`]
11516        // paths. Materializes the `<&'static str as
11517        // From<RestartPolicy>>::from` output in a `const`-shape binding
11518        // to make the `'static` lifetime promise a build-time invariant
11519        // — a future accidental downgrade of any of the three arms'
11520        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] constants to a
11521        // non-`&'static str` (a `String::leak()`-produced return, a
11522        // `Box::leak`-cast) trips at caixa-core build time rather than
11523        // at a downstream `'static`-bound consumer. Peer of the sibling
11524        // [`restart_strategy_from_into_static_str_routes_through_as_str_accessor`]
11525        // (523157d) — extends the trait-idiomatic forward-projection
11526        // axis onto the second (and second-of-two-in-M2) closed-set
11527        // typed enum on the caixa surface (the paired per-child
11528        // restart-decision-policy sibling on the same M2 `:supervisor`
11529        // slot).
11530        const PERMANENT: &str = RestartPolicy::Permanent.as_str();
11531        const TEMPORARY: &str = RestartPolicy::Temporary.as_str();
11532        const TRANSIENT: &str = RestartPolicy::Transient.as_str();
11533        for &variant in RestartPolicy::ALL {
11534            let via_trait: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
11535            let via_method: &'static str = variant.as_str();
11536            assert_eq!(
11537                via_trait, via_method,
11538                "From<RestartPolicy> for &'static str impl must round-trip \
11539                 RestartPolicy::{variant:?} to the same lifted \
11540                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str returns — \
11541                 divergence signals a silent detour off the substrate-primitive \
11542                 accessor"
11543            );
11544            let via_into: &'static str = variant.into();
11545            assert_eq!(
11546                via_into, via_method,
11547                "Into<&'static str>::into on RestartPolicy::{variant:?} must \
11548                 byte-equal RestartPolicy::as_str on the same input — the \
11549                 blanket-derived Into shape must resolve to the same as_str \
11550                 dispatch as the explicit From impl"
11551            );
11552        }
11553        assert_eq!(
11554            [PERMANENT, TEMPORARY, TRANSIENT],
11555            [
11556                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
11557                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
11558                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
11559            ],
11560            "const-context RestartPolicy::as_str must resolve to the three \
11561             lifted SUPERVISOR_CHILD_RESTART_* consts — a future accidental \
11562             downgrade of any arm to a non-const or non-static byte-string \
11563             breaks the `&'static str`-lifetime promise the paired \
11564             From<RestartPolicy> for &'static str impl carries by \
11565             construction"
11566        );
11567    }
11568
11569    #[test]
11570    fn restart_policy_from_into_static_str_and_as_str_partition_the_emit_set() {
11571        // Cross-axis partition pin: the paired trait-idiomatic
11572        // `From<RestartPolicy> for &'static str` forward projection and
11573        // the method-named [`RestartPolicy::as_str`] forward projection
11574        // must resolve identically on *every* arm, not just the ones
11575        // named in the primary byte-parity pin above. Sweeps every
11576        // [`RestartPolicy::ALL`] arm and asserts the trait's `From::from`
11577        // output byte-equals the method-named accessor's return-value on
11578        // each, locking the two forward-projection paths together by
11579        // construction so any future detour (a stray `From` special-case
11580        // that lands on a divergent per-arm literal outside the paired
11581        // `as_str` dispatch, a hypothetical rebrand touching one axis
11582        // without the other) trips at caixa-core test time. Peer of the
11583        // sibling forward-projection partition pin
11584        // [`restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
11585        // (523157d) — extends the round-trip discipline onto the
11586        // second-of-two M2-OTP-shape closed-set typed enum on the caixa
11587        // surface, closing the two-way `Self ↔ &'static str` round-trip
11588        // on the trait-idiomatic pair (`From<Self> for &'static str` +
11589        // `TryFrom<&str> for Self`) as well as the pre-existing method-
11590        // named pair (`as_str` + `from_wire`).
11591        for &variant in RestartPolicy::ALL {
11592            let via_trait: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
11593            let via_method: &'static str = variant.as_str();
11594            assert_eq!(
11595                via_trait, via_method,
11596                "From<RestartPolicy> for &'static str and \
11597                 RestartPolicy::as_str must resolve identically on \
11598                 RestartPolicy::{variant:?} — divergence signals the \
11599                 two forward-projection paths have drifted onto different \
11600                 emit-sets"
11601            );
11602        }
11603        // Round-trip witness: every arm's forward `From` output re-parses
11604        // through the paired trait-idiomatic reverse `TryFrom<&str>` back
11605        // to the original variant. Closes the two-way `RestartPolicy ↔
11606        // &'static str` round-trip on the trait-idiomatic axis pair,
11607        // mirroring the pre-existing method-named `as_str` + `from_wire`
11608        // round-trip on the substrate-primitive axis pair.
11609        for &variant in RestartPolicy::ALL {
11610            let emitted: &'static str = variant.into();
11611            let re_parsed: Result<RestartPolicy, ()> =
11612                <RestartPolicy as TryFrom<&str>>::try_from(emitted);
11613            assert_eq!(
11614                re_parsed,
11615                Ok(variant),
11616                "trait-idiomatic axis pair must round-trip \
11617                 RestartPolicy::{variant:?} through `.into::<&'static \
11618                 str>()` and back through `TryFrom<&str>` — a break signals \
11619                 the forward-emit and reverse-parse axes have drifted onto \
11620                 different vocabularies"
11621            );
11622        }
11623    }
11624
11625    #[test]
11626    fn restart_policy_from_borrowed_into_static_str_routes_through_as_str_accessor() {
11627        // Fail-before-pass-after byte-parity pin on the newly lifted
11628        // `impl From<&RestartPolicy> for &'static str` — asserts the
11629        // borrowed-input standard-library trait impl and the substrate-
11630        // primitive [`RestartPolicy::as_str`] `pub const fn` accessor
11631        // resolve to the same three-arm emit-set across every arm the
11632        // exhaustive [`RestartPolicy::ALL`] slice enumerates. Rust's
11633        // `From` trait does not auto-derive the borrowed-input sibling
11634        // from a paired owned-input impl (no `impl<T, U> From<&T> for U
11635        // where T: Copy, U: From<T>` blanket in `core`), so the
11636        // borrowed-input axis is a distinct trait-idiomatic surface
11637        // that a `.iter().map(Into::into)` shape over
11638        // [`RestartPolicy::ALL`] (whose iterator yields
11639        // `&RestartPolicy`, not `RestartPolicy`) reaches through this
11640        // impl and no other — the paired owned-input
11641        // [`From<RestartPolicy>`] impl requires an explicit `.copied()`
11642        // / dereference before the trait fires. Materializes the
11643        // `<&'static str as From<&RestartPolicy>>::from` output in a
11644        // `const`-shape binding to make the `'static` lifetime promise
11645        // a build-time invariant.
11646        const PERMANENT: &str = RestartPolicy::Permanent.as_str();
11647        const TEMPORARY: &str = RestartPolicy::Temporary.as_str();
11648        const TRANSIENT: &str = RestartPolicy::Transient.as_str();
11649        for variant in RestartPolicy::ALL {
11650            let via_trait: &'static str = <&'static str as From<&RestartPolicy>>::from(variant);
11651            let via_method: &'static str = variant.as_str();
11652            assert_eq!(
11653                via_trait, via_method,
11654                "From<&RestartPolicy> for &'static str impl must round-trip \
11655                 &RestartPolicy::{variant:?} to the same lifted \
11656                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
11657                 returns — divergence signals a silent detour off the \
11658                 substrate-primitive accessor"
11659            );
11660            let via_into: &'static str = variant.into();
11661            assert_eq!(
11662                via_into, via_method,
11663                "Into<&'static str>::into on &RestartPolicy::{variant:?} \
11664                 must byte-equal RestartPolicy::as_str on the same input — \
11665                 the blanket-derived Into shape must resolve to the same \
11666                 as_str dispatch as the explicit From impl"
11667            );
11668        }
11669        assert_eq!(
11670            [PERMANENT, TEMPORARY, TRANSIENT],
11671            [
11672                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
11673                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
11674                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
11675            ],
11676            "const-context RestartPolicy::as_str must resolve to the three \
11677             lifted SUPERVISOR_CHILD_RESTART_* consts — the borrowed-input \
11678             From<&RestartPolicy> for &'static str impl inherits its \
11679             `'static` lifetime promise from the same accessor the \
11680             owned-input sibling routes through"
11681        );
11682    }
11683
11684    #[test]
11685    fn restart_policy_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
11686        // Cross-axis partition pin: the paired trait-idiomatic
11687        // owned-input `From<RestartPolicy> for &'static str` (9fb37d0
11688        // campaign-shape) and borrowed-input `From<&RestartPolicy> for
11689        // &'static str` (this lift) forward projections must resolve
11690        // identically on every arm, locking the two input-shape paths
11691        // together so any future detour trips at caixa-core test time.
11692        // Then a witness that a `.iter().map(Into::into)` pipe over
11693        // [`RestartPolicy::ALL`] (whose iterator yields
11694        // `&RestartPolicy`) materializes the three-arm accept-set
11695        // through the borrowed-input axis alone — the exact shape a
11696        // future wasm-operator per-child post-exit restart-decision
11697        // diagnostic line, a future substrate-wide per-arm diagnostic
11698        // column, or a
11699        // `HashMap::<&'static str, RestartPolicy>::from_iter(
11700        //     RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))`-style
11701        // per-policy lookup reaches through — closing the two-way
11702        // owned/borrowed input-shape symmetry on the forward-projection
11703        // trait-idiomatic axis. Peer of the sibling
11704        // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
11705        // (64aa742) /
11706        // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
11707        // (5ab993a) /
11708        // [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
11709        // (807b0b5) /
11710        // [`restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
11711        // (e941836) partition pins on the sibling closed-set typed-enum
11712        // discriminator axes — extends the borrowed-input axis
11713        // discipline onto the second-of-two M2 OTP-shape closed-set
11714        // typed enum on the caixa surface (per-child restart-decision
11715        // policy). Also closes the direct two-way `&Self → &'static
11716        // str → Self` round-trip via the paired [`TryFrom<&str>`] axis
11717        // — unlike the peer [`crate::CaixaKind`] axis pair (whose
11718        // forward `From` emits lowercase Portuguese diagnostic bytes
11719        // while the reverse `TryFrom` parses `PascalCase` wire bytes,
11720        // forcing the round-trip through an intermediate wire-vocab
11721        // hop), the [`RestartPolicy::as_str`] emit and
11722        // [`RestartPolicy::from_wire`] parse share the same
11723        // `PascalCase` vocabulary by construction, so the borrowed-
11724        // input forward axis and the reverse axis compose directly.
11725        for &variant in RestartPolicy::ALL {
11726            let owned: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
11727            let borrowed: &'static str = <&'static str as From<&RestartPolicy>>::from(&variant);
11728            assert_eq!(
11729                owned, borrowed,
11730                "From<RestartPolicy> and From<&RestartPolicy> for \
11731                 &'static str must resolve identically on \
11732                 RestartPolicy::{variant:?} — divergence signals the \
11733                 owned-input and borrowed-input forward-projection paths \
11734                 have drifted onto different emit-sets"
11735            );
11736        }
11737        let via_iter: Vec<&'static str> = RestartPolicy::ALL.iter().map(Into::into).collect();
11738        let via_method: Vec<&'static str> = RestartPolicy::ALL.iter().map(|p| p.as_str()).collect();
11739        assert_eq!(
11740            via_iter, via_method,
11741            "`.iter().map(Into::into)` over RestartPolicy::ALL must \
11742             byte-equal `.iter().map(|p| p.as_str())` on every arm — the \
11743             borrowed-input `From<&RestartPolicy> for &'static str` axis \
11744             is what makes the `.iter().map(Into::into)` shape route \
11745             through the substrate-primitive `RestartPolicy::as_str` \
11746             accessor rather than through a per-call-site `.copied()` / \
11747             dereference detour"
11748        );
11749        for variant in RestartPolicy::ALL {
11750            let emitted: &'static str = variant.into();
11751            let re_parsed: Result<RestartPolicy, ()> =
11752                <RestartPolicy as TryFrom<&str>>::try_from(emitted);
11753            assert_eq!(
11754                re_parsed,
11755                Ok(*variant),
11756                "trait-idiomatic borrowed-input forward-projection + \
11757                 reverse-projection axis pair must round-trip \
11758                 &RestartPolicy::{variant:?} through `.into::<&'static \
11759                 str>()` (via the borrowed-input axis) and back through \
11760                 `TryFrom<&str>` — a break signals the borrowed-input \
11761                 forward-emit and reverse-parse axes have drifted onto \
11762                 different vocabularies"
11763            );
11764        }
11765    }
11766
11767    #[test]
11768    fn restart_policy_from_into_owned_string_routes_through_as_str_accessor() {
11769        // Fail-before-pass-after byte-parity pin on the newly lifted
11770        // `impl From<RestartPolicy> for String` — asserts the
11771        // owned-`String`-returning standard-library trait impl and the
11772        // substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
11773        // accessor resolve to the same three-arm emit-set across every
11774        // arm the exhaustive [`RestartPolicy::ALL`] slice enumerates.
11775        // Rust's standard library does not carry a blanket
11776        // `impl<T: AsRef<str>> From<T> for String` (nor an
11777        // `impl<T: fmt::Display> From<T> for String`), so the
11778        // owned-`String` forward-projection axis is a distinct
11779        // trait-idiomatic surface that a `let key: String =
11780        // policy.into();`-shaped call site reaches through this impl
11781        // and no other — the paired sibling `From<RestartPolicy> for
11782        // &'static str` impl forces every owned-`String` call site
11783        // through an explicit `.to_owned()` / `String::from`
11784        // restatement. Peer of the first-mover
11785        // [`restart_strategy_from_into_owned_string_routes_through_as_str_accessor`]
11786        // (7baa18a) — extends the trait-idiomatic owned-`String`
11787        // forward-projection axis onto the second-of-two M2 OTP-shape
11788        // closed-set typed enums on the caixa surface (per-child
11789        // restart-decision-policy sibling on the same M2 `:supervisor`
11790        // slot).
11791        for &variant in RestartPolicy::ALL {
11792            let via_trait: String = <String as From<RestartPolicy>>::from(variant);
11793            let via_method: &'static str = variant.as_str();
11794            assert_eq!(
11795                via_trait.as_str(),
11796                via_method,
11797                "From<RestartPolicy> for String impl must round-trip \
11798                 RestartPolicy::{variant:?} to the same lifted \
11799                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
11800                 returns — divergence signals a silent detour off the \
11801                 substrate-primitive accessor"
11802            );
11803            let via_into: String = variant.into();
11804            assert_eq!(
11805                via_into.as_str(),
11806                via_method,
11807                "Into<String>::into on RestartPolicy::{variant:?} must \
11808                 byte-equal RestartPolicy::as_str on the same input — the \
11809                 blanket-derived Into shape must resolve to the same as_str \
11810                 dispatch as the explicit From impl"
11811            );
11812        }
11813    }
11814
11815    #[test]
11816    fn restart_policy_from_into_owned_string_and_static_str_agree_on_every_arm() {
11817        // Cross-axis partition pin: the paired trait-idiomatic
11818        // owned-`String` `From<RestartPolicy> for String` (this lift)
11819        // and owned-`&'static str` `From<RestartPolicy> for &'static
11820        // str` (9fb37d0) forward projections must resolve identically
11821        // on every arm, locking the two return-type-shape paths
11822        // together so any future detour trips at caixa-core test time.
11823        // Also byte-parity witness against the sibling
11824        // [`ToString::to_string`] surface routed through
11825        // [`std::fmt::Display`] — the three owned-heap-string paths
11826        // (`.into::<String>()`, `String::from`, `.to_string()`) must
11827        // resolve identically on every arm so a future consumer that
11828        // picks any of the three lands on the same lifted
11829        // SUPERVISOR_CHILD_RESTART_* const. Then a `.iter().copied()
11830        // .map(String::from)` pipe witness over [`RestartPolicy::ALL`]
11831        // that materializes the three-arm accept-set through the
11832        // owned-`String` axis alone — the exact shape a future
11833        // wasm-operator per-child post-exit restart-decision
11834        // diagnostic line composer or a
11835        // `HashMap::<String, RestartPolicy>::from_iter(
11836        //     RestartPolicy::ALL.iter().copied().map(|p| (p.into(), p)))`-style
11837        // owned-key per-policy lookup reaches through — closing the
11838        // owned-`String` forward-projection axis's iterator-pipe
11839        // shape. Then a direct round-trip witness through the paired
11840        // trait-idiomatic reverse [`TryFrom<&str>`] axis on the
11841        // owned-`String`'s [`String::as_str`] borrow that closes the
11842        // two-way `Self → String → Self` round-trip on the trait-
11843        // idiomatic owned-`String` forward + reverse axis pair —
11844        // unlike the peer [`crate::CaixaKind`] axis pair (whose
11845        // forward `From` emits lowercase Portuguese diagnostic bytes
11846        // while the reverse `TryFrom` parses `PascalCase` wire bytes,
11847        // forcing the round-trip through an intermediate wire-vocab
11848        // hop), the [`RestartPolicy::as_str`] emit and
11849        // [`RestartPolicy::from_wire`] parse share the same
11850        // `PascalCase` vocabulary by construction, so the owned-
11851        // `String` forward axis and the reverse axis compose directly.
11852        for &variant in RestartPolicy::ALL {
11853            let owned_string: String = <String as From<RestartPolicy>>::from(variant);
11854            let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
11855            assert_eq!(
11856                owned_string.as_str(),
11857                owned_static,
11858                "From<RestartPolicy> for String and From<RestartPolicy> \
11859                 for &'static str must resolve identically on \
11860                 RestartPolicy::{variant:?} — divergence signals the \
11861                 owned-`String` and owned-`&'static str` forward-projection \
11862                 return-type-shape paths have drifted onto different \
11863                 emit-sets"
11864            );
11865            let via_to_string: String = variant.to_string();
11866            assert_eq!(
11867                owned_string, via_to_string,
11868                "From<RestartPolicy> for String must byte-equal \
11869                 RestartPolicy::to_string on RestartPolicy::{variant:?} — \
11870                 divergence signals the trait-idiomatic owned-`String` \
11871                 forward-projection axis and the ToString-through-Display \
11872                 axis have drifted onto different emit-sets"
11873            );
11874        }
11875        let via_iter: Vec<String> = RestartPolicy::ALL
11876            .iter()
11877            .copied()
11878            .map(String::from)
11879            .collect();
11880        let via_method: Vec<String> = RestartPolicy::ALL
11881            .iter()
11882            .map(|p| p.as_str().to_owned())
11883            .collect();
11884        assert_eq!(
11885            via_iter, via_method,
11886            "`.iter().copied().map(String::from)` over RestartPolicy::ALL \
11887             must byte-equal `.iter().map(|p| p.as_str().to_owned())` on \
11888             every arm — the owned-`String` `From<RestartPolicy> for \
11889             String` axis is what makes the `String::from` composition \
11890             route through the substrate-primitive `RestartPolicy::as_str` \
11891             accessor rather than through a per-call-site `.to_owned()` / \
11892             `String::from(policy.as_str())` detour"
11893        );
11894        for &variant in RestartPolicy::ALL {
11895            let emitted: String = variant.into();
11896            let re_parsed: Result<RestartPolicy, ()> =
11897                <RestartPolicy as TryFrom<&str>>::try_from(emitted.as_str());
11898            assert_eq!(
11899                re_parsed,
11900                Ok(variant),
11901                "trait-idiomatic owned-`String` forward-projection + \
11902                 reverse-projection axis pair must round-trip \
11903                 RestartPolicy::{variant:?} through `.into::<String>()` \
11904                 and back through `TryFrom<&str>` on the owned-`String`'s \
11905                 String::as_str borrow — a break signals the owned-`String` \
11906                 forward-emit and reverse-parse axes have drifted onto \
11907                 different vocabularies"
11908            );
11909        }
11910    }
11911
11912    #[test]
11913    fn restart_policy_from_into_borrowed_owned_string_routes_through_as_str_accessor() {
11914        // Fail-before-pass-after byte-parity pin on the newly lifted
11915        // `impl From<&RestartPolicy> for String` — asserts the
11916        // borrowed-input owned-`String`-returning standard-library
11917        // trait impl and the substrate-primitive
11918        // [`RestartPolicy::as_str`] `pub const fn` accessor resolve to
11919        // the same three-arm emit-set across every arm the exhaustive
11920        // [`RestartPolicy::ALL`] slice enumerates. Rust's standard
11921        // library does not carry a blanket `impl<T: AsRef<str>>
11922        // From<&T> for String` (nor an `impl<T: fmt::Display> From<&T>
11923        // for String`), so the borrowed-input owned-`String` forward-
11924        // projection axis is a distinct trait-idiomatic surface that a
11925        // `let key: String = (&policy).into();`-shaped call site
11926        // reaches through this impl and no other — the paired sibling
11927        // `From<RestartPolicy> for String` impl forces every borrowed-
11928        // input call site through an explicit `Copy` deref
11929        // (`String::from(*policy)`) or an `.as_str().to_owned()` /
11930        // `.to_string()` detour. Peer of the first-mover
11931        // [`restart_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
11932        // (579385f) — extends the trait-idiomatic borrowed-input
11933        // owned-`String` forward-projection axis onto the second-of-
11934        // two M2 OTP-shape closed-set typed enums on the caixa surface
11935        // (per-child restart-decision-policy sibling on the same M2
11936        // `:supervisor` slot).
11937        for &variant in RestartPolicy::ALL {
11938            let via_trait: String = <String as From<&RestartPolicy>>::from(&variant);
11939            let via_method: &'static str = variant.as_str();
11940            assert_eq!(
11941                via_trait.as_str(),
11942                via_method,
11943                "From<&RestartPolicy> for String impl must round-trip \
11944                 &RestartPolicy::{variant:?} to the same lifted \
11945                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
11946                 returns — divergence signals a silent detour off the \
11947                 substrate-primitive accessor"
11948            );
11949            let via_into: String = (&variant).into();
11950            assert_eq!(
11951                via_into.as_str(),
11952                via_method,
11953                "Into<String>::into on &RestartPolicy::{variant:?} must \
11954                 byte-equal RestartPolicy::as_str on the same input — \
11955                 the blanket-derived Into shape must resolve to the \
11956                 same as_str dispatch as the explicit From impl"
11957            );
11958        }
11959    }
11960
11961    #[test]
11962    fn restart_policy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm() {
11963        // Cross-axis partition pin: the newly lifted trait-idiomatic
11964        // borrowed-input owned-`String` `From<&RestartPolicy> for
11965        // String` (this lift), the paired owned-input owned-`String`
11966        // `From<RestartPolicy> for String` (7851725), the paired
11967        // borrowed-input owned-`&'static str` `From<&RestartPolicy>
11968        // for &'static str` (842c7f3), and the paired owned-input
11969        // owned-`&'static str` `From<RestartPolicy> for &'static str`
11970        // (9fb37d0) — every corner of the `{Self, &Self} × {&'static
11971        // str, String}` 2×2 trait-idiomatic projection family — must
11972        // resolve identically on every arm, locking the four
11973        // return-shape × input-shape paths together so any future
11974        // detour trips at caixa-core test time. Also byte-parity
11975        // witness against the sibling [`ToString::to_string`] surface
11976        // routed through [`std::fmt::Display`] and a direct round-trip
11977        // witness through the paired trait-idiomatic reverse
11978        // [`TryFrom<&str>`] axis on the owned-`String`'s
11979        // [`String::as_str`] borrow that closes the two-way
11980        // `&Self → String → Self` round-trip on the trait-idiomatic
11981        // borrowed-input owned-`String` forward + reverse axis pair.
11982        // Peer of the first-mover
11983        // [`restart_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
11984        // (579385f) — closes the whole `{Self, &Self} × {&'static str,
11985        // String}` 2×2 projection corner on both M2 OTP-shape sibling
11986        // peers.
11987        for &variant in RestartPolicy::ALL {
11988            let borrowed_string: String = <String as From<&RestartPolicy>>::from(&variant);
11989            let owned_string: String = <String as From<RestartPolicy>>::from(variant);
11990            let borrowed_static: &'static str =
11991                <&'static str as From<&RestartPolicy>>::from(&variant);
11992            let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
11993            assert_eq!(
11994                borrowed_string, owned_string,
11995                "From<&RestartPolicy> for String and From<RestartPolicy> \
11996                 for String must resolve identically on \
11997                 RestartPolicy::{variant:?} — divergence signals the \
11998                 borrowed-input and owned-input owned-`String` \
11999                 forward-projection input-shape paths have drifted onto \
12000                 different emit-sets"
12001            );
12002            assert_eq!(
12003                borrowed_string.as_str(),
12004                borrowed_static,
12005                "From<&RestartPolicy> for String and From<&RestartPolicy> \
12006                 for &'static str must resolve identically on \
12007                 RestartPolicy::{variant:?} — divergence signals the \
12008                 borrowed-input `&'static str` and owned-`String` \
12009                 return-shape paths have drifted onto different \
12010                 emit-sets"
12011            );
12012            assert_eq!(
12013                borrowed_string.as_str(),
12014                owned_static,
12015                "From<&RestartPolicy> for String and From<RestartPolicy> \
12016                 for &'static str must resolve identically on \
12017                 RestartPolicy::{variant:?} — divergence signals a \
12018                 break in the diagonal corner of the {{Self, &Self}} × \
12019                 {{&'static str, String}} 2×2 trait-idiomatic \
12020                 projection family"
12021            );
12022            let via_to_string: String = variant.to_string();
12023            assert_eq!(
12024                borrowed_string, via_to_string,
12025                "From<&RestartPolicy> for String must byte-equal \
12026                 RestartPolicy::to_string on RestartPolicy::{variant:?} \
12027                 — divergence signals the trait-idiomatic borrowed-input \
12028                 owned-`String` forward-projection axis and the \
12029                 ToString-through-Display axis have drifted onto \
12030                 different emit-sets"
12031            );
12032        }
12033        let via_iter: Vec<String> = RestartPolicy::ALL.iter().map(String::from).collect();
12034        let via_method: Vec<String> = RestartPolicy::ALL
12035            .iter()
12036            .map(|p| p.as_str().to_owned())
12037            .collect();
12038        assert_eq!(
12039            via_iter, via_method,
12040            "`.iter().map(String::from)` over RestartPolicy::ALL — a \
12041             call site whose iteration axis holds `&RestartPolicy` by \
12042             construction — must byte-equal `.iter().map(|p| \
12043             p.as_str().to_owned())` on every arm — the borrowed-input \
12044             owned-`String` `From<&RestartPolicy> for String` axis is \
12045             what makes the `String::from` composition route through \
12046             the substrate-primitive `RestartPolicy::as_str` accessor \
12047             without a spurious `Copy` deref (which would only be \
12048             reachable through the owned-input `From<RestartPolicy> \
12049             for String` axis by first calling `.copied()` on the \
12050             iterator)"
12051        );
12052        for &variant in RestartPolicy::ALL {
12053            let emitted: String = (&variant).into();
12054            let re_parsed: Result<RestartPolicy, ()> =
12055                <RestartPolicy as TryFrom<&str>>::try_from(emitted.as_str());
12056            assert_eq!(
12057                re_parsed,
12058                Ok(variant),
12059                "trait-idiomatic borrowed-input owned-`String` \
12060                 forward-projection + reverse-projection axis pair must \
12061                 round-trip &RestartPolicy::{variant:?} through \
12062                 `.into::<String>()` on the borrowed-input surface and \
12063                 back through `TryFrom<&str>` on the owned-`String`'s \
12064                 String::as_str borrow — a break signals the \
12065                 borrowed-input owned-`String` forward-emit and \
12066                 reverse-parse axes have drifted onto different \
12067                 vocabularies"
12068            );
12069        }
12070    }
12071
12072    #[test]
12073    fn restart_policy_from_into_static_cow_str_routes_through_as_str_accessor() {
12074        // Fail-before-pass-after byte-parity pin on the newly lifted
12075        // `impl From<RestartPolicy> for std::borrow::Cow<'static, str>` —
12076        // asserts the standard-library trait impl and the substrate-
12077        // primitive [`super::RestartPolicy::as_str`] `pub const fn`
12078        // accessor resolve to the same three-arm emit-set across every
12079        // arm the exhaustive [`super::RestartPolicy::ALL`] slice
12080        // enumerates. Rust's standard library does not carry a blanket
12081        // `impl<T: AsRef<str>> From<T> for Cow<'static, str>` (nor an
12082        // `impl<T: fmt::Display> From<T> for Cow<'static, str>`), so
12083        // the `Cow<'static, str>` forward-projection axis is a
12084        // distinct trait-idiomatic surface that a
12085        // `let key: Cow<'static, str> = policy.into();`-shaped call
12086        // site reaches through this impl and no other — the paired
12087        // sibling `From<RestartPolicy> for &'static str` and
12088        // `From<RestartPolicy> for String` impls force every
12089        // `Cow<'static, str>`-parameterized call site through a
12090        // `Cow::Borrowed(policy.as_str())` /
12091        // `Cow::Owned(policy.to_string())` composition whose type
12092        // bounds have no compile-time link back to the substrate
12093        // primitive.
12094        //
12095        // Also asserts the projection lands on the zero-alloc
12096        // [`std::borrow::Cow::Borrowed`] arm (not the
12097        // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
12098        // [`super::RestartPolicy::as_str`] accessor's `&'static str`
12099        // return lifetime by construction makes the borrowed arm the
12100        // type-correct projection with no runtime allocation. Any
12101        // future silent detour that routes the impl through the owned
12102        // arm (an accidental `Cow::Owned(policy.to_string())` rewrite
12103        // that would allocate on every call site where the
12104        // `&'static str` return of [`super::RestartPolicy::as_str`]
12105        // makes the zero-alloc borrowed projection type-correct) trips
12106        // at caixa-core test time under the
12107        // [`std::borrow::Cow::Borrowed`] discriminator witness rather
12108        // than at a downstream `Cow<'static, str>`-bound consumer's
12109        // silent allocation.
12110        //
12111        // Second peer on the substrate-wide trait-idiomatic
12112        // [`std::borrow::Cow<'static, str>`] forward-projection family
12113        // to extend the axis off the top-level [`super::CaixaKind`]
12114        // enum (99c1735 owned-input, d45c409 borrowed-input) onto the
12115        // second (and second-of-two-in-M2) M2 OTP-shape closed-set
12116        // fieldless typed enum peer on the caixa surface — closes the
12117        // M2 OTP-shape tier of the campaign on the owned-input axis
12118        // (both sibling peers, `RestartStrategy` and `RestartPolicy`,
12119        // now carry the owned-input Cow<'static, str> forward
12120        // projection).
12121        for &variant in RestartPolicy::ALL {
12122            let via_trait: std::borrow::Cow<'static, str> =
12123                <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
12124            let via_method: &'static str = variant.as_str();
12125            assert_eq!(
12126                via_trait.as_ref(),
12127                via_method,
12128                "From<RestartPolicy> for Cow<'static, str> impl must \
12129                 round-trip RestartPolicy::{variant:?} to the same \
12130                 lifted SUPERVISOR_CHILD_RESTART_* const \
12131                 RestartPolicy::as_str returns — divergence signals a \
12132                 silent detour off the substrate-primitive accessor"
12133            );
12134            assert!(
12135                matches!(via_trait, std::borrow::Cow::Borrowed(_)),
12136                "From<RestartPolicy> for Cow<'static, str> impl must \
12137                 land on the zero-alloc Cow::Borrowed arm on \
12138                 RestartPolicy::{variant:?} — a Cow::Owned outcome \
12139                 signals the projection has silently allocated where \
12140                 the substrate-primitive RestartPolicy::as_str \
12141                 `&'static str` return makes the borrowed arm the \
12142                 type-correct projection"
12143            );
12144            let via_into: std::borrow::Cow<'static, str> = variant.into();
12145            assert_eq!(
12146                via_into.as_ref(),
12147                via_method,
12148                "Into<Cow<'static, str>>::into on \
12149                 RestartPolicy::{variant:?} must byte-equal \
12150                 RestartPolicy::as_str on the same input — the \
12151                 blanket-derived Into shape must resolve to the same \
12152                 as_str dispatch as the explicit From impl"
12153            );
12154            assert!(
12155                matches!(via_into, std::borrow::Cow::Borrowed(_)),
12156                "Into<Cow<'static, str>>::into on \
12157                 RestartPolicy::{variant:?} must land on the \
12158                 zero-alloc Cow::Borrowed arm — the blanket-derived \
12159                 Into shape must resolve to the same Cow::Borrowed \
12160                 dispatch as the explicit From impl"
12161            );
12162        }
12163    }
12164
12165    #[test]
12166    fn restart_policy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
12167        // Cross-axis partition pin: the newly lifted trait-idiomatic
12168        // `From<RestartPolicy> for std::borrow::Cow<'static, str>`
12169        // (this lift), the paired owned-input `From<RestartPolicy>
12170        // for &'static str` (9fb37d0), and the paired owned-input
12171        // `From<RestartPolicy> for String` (7851725) forward
12172        // projections must resolve identically on every arm, locking
12173        // the three return-shape paths together by construction so any
12174        // future detour trips at caixa-core test time. Also byte-parity
12175        // witness against the sibling [`ToString::to_string`] surface
12176        // routed through [`std::fmt::Display`] — every owned-heap-
12177        // string path (the `Cow::Owned` promotion of this axis's
12178        // `.into_owned()`, `From<RestartPolicy> for String`, and
12179        // `.to_string()`) resolves to the same lifted
12180        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const per arm.
12181        //
12182        // Then a `.iter().copied().map(std::borrow::Cow::from)` pipe
12183        // witness over [`super::RestartPolicy::ALL`] that
12184        // materializes the three-arm accept-set through the
12185        // [`std::borrow::Cow<'static, str>`] axis alone — the exact
12186        // shape a future `axum::response::IntoResponse` per-policy
12187        // rejection-body composer, a future M4 admission-webhook
12188        // per-policy rejection-reason emitter whose typing rules out
12189        // the sibling [`AsRef<str>`] borrowed return, or a future
12190        // substrate-wide per-policy diagnostic surface that binds
12191        // through a [`Cow<'static, str>`] boundary reaches through.
12192        // The pipe witness also pins the zero-alloc discipline: every
12193        // element in the collected vector satisfies the
12194        // [`std::borrow::Cow::Borrowed`] arm predicate, so a future
12195        // accidental silent-allocation regression on the pipe's
12196        // iteration axis is a caixa-core-test-time failure. Peer of
12197        // the first-mover
12198        // [`restart_strategy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
12199        // (7dd28b3) on the sibling M2 OTP-shape sibling-restart axis
12200        // — closes the whole owned-input `Cow<'static, str>` +
12201        // paired `{&'static str, String}` cross-axis-parity corner on
12202        // both M2 OTP-shape sibling peers.
12203        for &variant in RestartPolicy::ALL {
12204            let via_cow: std::borrow::Cow<'static, str> =
12205                <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
12206            let via_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
12207            let via_string: String = <String as From<RestartPolicy>>::from(variant);
12208            assert_eq!(
12209                via_cow.as_ref(),
12210                via_static,
12211                "From<RestartPolicy> for Cow<'static, str> and \
12212                 From<RestartPolicy> for &'static str must resolve \
12213                 identically on RestartPolicy::{variant:?} — \
12214                 divergence signals the Cow<'static, str> and \
12215                 &'static str return-shape paths have drifted onto \
12216                 different emit-sets"
12217            );
12218            assert_eq!(
12219                via_cow.as_ref(),
12220                via_string.as_str(),
12221                "From<RestartPolicy> for Cow<'static, str> and \
12222                 From<RestartPolicy> for String must resolve \
12223                 identically on RestartPolicy::{variant:?} — \
12224                 divergence signals the Cow<'static, str> and String \
12225                 return-shape paths have drifted onto different \
12226                 emit-sets"
12227            );
12228            let via_to_string: String = variant.to_string();
12229            assert_eq!(
12230                via_cow.as_ref(),
12231                via_to_string.as_str(),
12232                "From<RestartPolicy> for Cow<'static, str> must \
12233                 byte-equal RestartPolicy::to_string on \
12234                 RestartPolicy::{variant:?} — divergence signals the \
12235                 trait-idiomatic Cow<'static, str> forward-projection \
12236                 axis and the ToString-through-Display axis have \
12237                 drifted onto different emit-sets"
12238            );
12239        }
12240        let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
12241            .iter()
12242            .copied()
12243            .map(std::borrow::Cow::from)
12244            .collect();
12245        let via_method: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
12246            .iter()
12247            .map(|p| std::borrow::Cow::Borrowed(p.as_str()))
12248            .collect();
12249        assert_eq!(
12250            via_iter, via_method,
12251            "`.iter().copied().map(Cow::from)` over \
12252             RestartPolicy::ALL must byte-equal `.iter().map(|p| \
12253             Cow::Borrowed(p.as_str()))` on every arm — the \
12254             trait-idiomatic `From<RestartPolicy> for Cow<'static, \
12255             str>` axis is what makes the `Cow::from` composition \
12256             route through the substrate-primitive \
12257             `RestartPolicy::as_str` accessor with the zero-alloc \
12258             Cow::Borrowed arm by construction, rather than a \
12259             per-call-site `Cow::Owned(policy.to_string())` \
12260             allocation"
12261        );
12262        for cow in &via_iter {
12263            assert!(
12264                matches!(cow, std::borrow::Cow::Borrowed(_)),
12265                "every element of the \
12266                 .iter().copied().map(Cow::from) pipe over \
12267                 RestartPolicy::ALL must land on the zero-alloc \
12268                 Cow::Borrowed arm — a Cow::Owned outcome on any arm \
12269                 signals the pipe's iteration axis has silently \
12270                 allocated where the substrate-primitive \
12271                 RestartPolicy::as_str `&'static str` return makes \
12272                 the borrowed arm the type-correct projection"
12273            );
12274        }
12275    }
12276
12277    #[test]
12278    fn restart_policy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor() {
12279        // Fail-before-pass-after byte-parity pin on the newly lifted
12280        // `impl From<&RestartPolicy> for std::borrow::Cow<'static, str>` —
12281        // asserts the borrowed-input standard-library trait impl and
12282        // the substrate-primitive [`super::RestartPolicy::as_str`]
12283        // `pub const fn` accessor resolve to the same three-arm emit-
12284        // set across every arm the exhaustive
12285        // [`super::RestartPolicy::ALL`] slice enumerates. Rust's
12286        // standard library does not carry a blanket
12287        // `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor a
12288        // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`), so
12289        // the borrowed-input `Cow<'static, str>` forward-projection
12290        // axis is a distinct trait-idiomatic surface that a
12291        // `let key: Cow<'static, str> = (&policy).into();`-shaped
12292        // call site or a
12293        // `RestartPolicy::ALL.iter().map(Cow::from)`-shaped pipe
12294        // reaches through this impl and no other — the paired owned-
12295        // input `From<RestartPolicy> for Cow<'static, str>` impl
12296        // (0612398) forces every borrowed-input call site through an
12297        // explicit `Copy` deref (`Cow::from(*policy)`) or a
12298        // `Cow::Borrowed(policy.as_str())` open-code whose type
12299        // bounds have no compile-time link back to the substrate
12300        // primitive.
12301        //
12302        // Also asserts the projection lands on the zero-alloc
12303        // [`std::borrow::Cow::Borrowed`] arm (not the
12304        // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
12305        // [`super::RestartPolicy::as_str`] accessor's `&'static str`
12306        // return lifetime by construction makes the borrowed arm the
12307        // type-correct projection with no runtime allocation on the
12308        // borrowed-input surface just as on the paired owned-input
12309        // surface.
12310        //
12311        // Closes the `{Self, &Self}` input-shape corner on the M2
12312        // OTP-shape per-child-restart [`Cow<'static, str>`] axis on
12313        // the second-of-two-in-M2 closed-set fieldless typed enum peer
12314        // on the caixa surface (`:supervisor :children :restart`),
12315        // exactly as d45c409 closed it on the top-level
12316        // [`super::CaixaKind`] one commit after the owning half
12317        // (99c1735) landed and as 9b3e4b3 closed it on the sibling
12318        // M2 OTP-shape [`super::RestartStrategy`] one commit after
12319        // (7dd28b3) landed. This lift closes the whole M2 OTP-shape
12320        // tier of the substrate-wide Cow<'static, str> forward-
12321        // projection campaign on both input-shape corners
12322        // ({Self, &Self}) of both M2 OTP-shape sibling peers.
12323        for &variant in RestartPolicy::ALL {
12324            let via_trait: std::borrow::Cow<'static, str> =
12325                <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&variant);
12326            let via_method: &'static str = variant.as_str();
12327            assert_eq!(
12328                via_trait.as_ref(),
12329                via_method,
12330                "From<&RestartPolicy> for Cow<'static, str> impl must \
12331                 round-trip &RestartPolicy::{variant:?} to the same \
12332                 lifted SUPERVISOR_CHILD_RESTART_* const \
12333                 RestartPolicy::as_str returns — divergence signals a \
12334                 silent detour off the substrate-primitive accessor"
12335            );
12336            assert!(
12337                matches!(via_trait, std::borrow::Cow::Borrowed(_)),
12338                "From<&RestartPolicy> for Cow<'static, str> impl must \
12339                 land on the zero-alloc Cow::Borrowed arm on \
12340                 &RestartPolicy::{variant:?} — a Cow::Owned outcome \
12341                 signals the projection has silently allocated where \
12342                 the substrate-primitive RestartPolicy::as_str \
12343                 `&'static str` return makes the borrowed arm the \
12344                 type-correct projection"
12345            );
12346            let via_into: std::borrow::Cow<'static, str> = (&variant).into();
12347            assert_eq!(
12348                via_into.as_ref(),
12349                via_method,
12350                "Into<Cow<'static, str>>::into on \
12351                 &RestartPolicy::{variant:?} must byte-equal \
12352                 RestartPolicy::as_str on the same input — the \
12353                 blanket-derived Into shape must resolve to the same \
12354                 as_str dispatch as the explicit From impl"
12355            );
12356            assert!(
12357                matches!(via_into, std::borrow::Cow::Borrowed(_)),
12358                "Into<Cow<'static, str>>::into on \
12359                 &RestartPolicy::{variant:?} must land on the \
12360                 zero-alloc Cow::Borrowed arm — the blanket-derived \
12361                 Into shape must resolve to the same Cow::Borrowed \
12362                 dispatch as the explicit From impl"
12363            );
12364        }
12365    }
12366
12367    #[test]
12368    fn restart_policy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
12369        // Cross-axis partition pin: the newly lifted trait-idiomatic
12370        // borrowed-input `From<&RestartPolicy> for
12371        // std::borrow::Cow<'static, str>` (this lift), the paired
12372        // owned-input `From<RestartPolicy> for
12373        // std::borrow::Cow<'static, str>` (0612398), the paired
12374        // borrowed-input owned-`&'static str` `From<&RestartPolicy>
12375        // for &'static str`, and the paired borrowed-input owned-
12376        // `String` `From<&RestartPolicy> for String` must resolve
12377        // identically on every arm, locking the four
12378        // return-shape × input-shape paths together by construction so
12379        // any future detour trips at caixa-core test time. Also byte-
12380        // parity witness against the sibling [`ToString::to_string`]
12381        // surface routed through [`std::fmt::Display`] — every owned-
12382        // heap-string path (this axis's `.into_owned()` promotion, the
12383        // paired [`From<&RestartPolicy> for String`], and
12384        // `.to_string()`) resolves to the same lifted
12385        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const per arm.
12386        //
12387        // Then a `.iter().map(std::borrow::Cow::from)` pipe witness
12388        // over [`super::RestartPolicy::ALL`] — whose iterator yields
12389        // `&RestartPolicy` by construction, so the borrowed-input
12390        // [`Cow<'static, str>`] axis is what routes the pipe through
12391        // the substrate-primitive [`super::RestartPolicy::as_str`]
12392        // accessor without a spurious [`Copy`] deref (which would only
12393        // be reachable through the owned-input
12394        // [`From<RestartPolicy> for Cow<'static, str>`] axis by first
12395        // calling `.copied()` on the iterator). The pipe witness also
12396        // pins the zero-alloc discipline: every element in the
12397        // collected vector satisfies the [`std::borrow::Cow::Borrowed`]
12398        // arm predicate, so a future accidental silent-allocation
12399        // regression on the pipe's iteration axis is a caixa-core-
12400        // test-time failure. Peer of the sibling
12401        // [`restart_strategy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
12402        // (9b3e4b3) on the M2 OTP-shape sibling-restart axis — closes
12403        // the whole borrowed-input `Cow<'static, str>` +
12404        // paired `{&'static str, String}` cross-axis-parity corner on
12405        // both M2 OTP-shape sibling peers.
12406        for &policy in RestartPolicy::ALL {
12407            let borrowed_cow: std::borrow::Cow<'static, str> =
12408                <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&policy);
12409            let owned_cow: std::borrow::Cow<'static, str> =
12410                <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(policy);
12411            let borrowed_static: &'static str =
12412                <&'static str as From<&RestartPolicy>>::from(&policy);
12413            let borrowed_string: String = <String as From<&RestartPolicy>>::from(&policy);
12414            assert_eq!(
12415                borrowed_cow, owned_cow,
12416                "From<&RestartPolicy> for Cow<'static, str> and \
12417                 From<RestartPolicy> for Cow<'static, str> must \
12418                 resolve identically on RestartPolicy::{policy:?} — \
12419                 divergence signals the borrowed-input and owned-input \
12420                 Cow<'static, str> forward-projection input-shape \
12421                 paths have drifted onto different emit-sets"
12422            );
12423            assert_eq!(
12424                borrowed_cow.as_ref(),
12425                borrowed_static,
12426                "From<&RestartPolicy> for Cow<'static, str> and \
12427                 From<&RestartPolicy> for &'static str must resolve \
12428                 identically on RestartPolicy::{policy:?} — \
12429                 divergence signals the borrowed-input Cow<'static, \
12430                 str> and &'static str return-shape paths have drifted \
12431                 onto different emit-sets"
12432            );
12433            assert_eq!(
12434                borrowed_cow.as_ref(),
12435                borrowed_string.as_str(),
12436                "From<&RestartPolicy> for Cow<'static, str> and \
12437                 From<&RestartPolicy> for String must resolve \
12438                 identically on RestartPolicy::{policy:?} — \
12439                 divergence signals the borrowed-input Cow<'static, \
12440                 str> and owned-`String` return-shape paths have \
12441                 drifted onto different emit-sets"
12442            );
12443            let via_to_string: String = policy.to_string();
12444            assert_eq!(
12445                borrowed_cow.as_ref(),
12446                via_to_string.as_str(),
12447                "From<&RestartPolicy> for Cow<'static, str> must \
12448                 byte-equal RestartPolicy::to_string on \
12449                 RestartPolicy::{policy:?} — divergence signals \
12450                 the trait-idiomatic borrowed-input Cow<'static, str> \
12451                 forward-projection axis and the ToString-through-\
12452                 Display axis have drifted onto different emit-sets"
12453            );
12454        }
12455        let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
12456            .iter()
12457            .map(std::borrow::Cow::from)
12458            .collect();
12459        let via_method: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
12460            .iter()
12461            .map(|p| std::borrow::Cow::Borrowed(p.as_str()))
12462            .collect();
12463        assert_eq!(
12464            via_iter, via_method,
12465            "`.iter().map(Cow::from)` over RestartPolicy::ALL — a \
12466             call site whose iteration axis holds `&RestartPolicy` \
12467             by construction — must byte-equal `.iter().map(|p| \
12468             Cow::Borrowed(p.as_str()))` on every arm — the borrowed-\
12469             input Cow<'static, str> `From<&RestartPolicy> for \
12470             Cow<'static, str>` axis is what makes the `Cow::from` \
12471             composition route through the substrate-primitive \
12472             `RestartPolicy::as_str` accessor with the zero-alloc \
12473             Cow::Borrowed arm by construction and without a spurious \
12474             `Copy` deref (which would only be reachable through the \
12475             owned-input `From<RestartPolicy> for Cow<'static, str>` \
12476             axis by first calling `.copied()` on the iterator)"
12477        );
12478        for cow in &via_iter {
12479            assert!(
12480                matches!(cow, std::borrow::Cow::Borrowed(_)),
12481                "every element of the .iter().map(Cow::from) pipe \
12482                 over RestartPolicy::ALL must land on the zero-\
12483                 alloc Cow::Borrowed arm — a Cow::Owned outcome on \
12484                 any arm signals the pipe's iteration axis has \
12485                 silently allocated where the substrate-primitive \
12486                 RestartPolicy::as_str `&'static str` return makes \
12487                 the borrowed arm the type-correct projection"
12488            );
12489        }
12490    }
12491
12492    #[test]
12493    fn restart_policy_from_into_box_str_routes_through_as_str_accessor() {
12494        // Fail-before-pass-after byte-parity pin on the newly lifted
12495        // `impl From<RestartPolicy> for Box<str>` — asserts the
12496        // owned-input standard-library trait impl and the
12497        // substrate-primitive [`super::RestartPolicy::as_str`]
12498        // `pub const fn` accessor resolve to the same three-arm emit-
12499        // set across every arm the exhaustive
12500        // [`super::RestartPolicy::ALL`] slice enumerates. Extends the
12501        // substrate-wide `Box<str>` forward-projection campaign tier
12502        // opened one commit prior (69ef45c) on the paired sibling-
12503        // restart [`RestartStrategy`] onto the second (and third-and-
12504        // final) M2 OTP-shape closed-set fieldless typed enum peer on
12505        // the caixa surface (`:children :restart`), immediately after
12506        // the paired `Cow<'static, str>` axis (0612398 / b4dc55c)
12507        // closed the
12508        // `{Self, &Self} × {&'static str, String, Cow<'static, str>}`
12509        // 2×3 corner on this enum. Rust's standard library carries
12510        // `impl From<&str> for Box<str>` and
12511        // `impl From<String> for Box<str>` but no blanket
12512        // `impl<T: AsRef<str>> From<T> for Box<str>`, so this axis is
12513        // a distinct trait-idiomatic surface that a
12514        // `let key: Box<str> = policy.into();`-shaped call site
12515        // reaches through this impl and no other — a paired
12516        // `Box::from(policy.as_str())` open-code has no compile-time
12517        // link back to the substrate primitive. Peer of the sibling
12518        // [`restart_strategy_from_into_box_str_routes_through_as_str_accessor`]
12519        // (69ef45c) — extends the trait-idiomatic owned-input
12520        // [`Box<str>`] forward-projection axis onto the third and
12521        // final M2-OTP-shape closed-set typed enum on the caixa
12522        // surface.
12523        for &variant in RestartPolicy::ALL {
12524            let via_trait: Box<str> = <Box<str> as From<RestartPolicy>>::from(variant);
12525            let via_method: &'static str = variant.as_str();
12526            assert_eq!(
12527                via_trait.as_ref(),
12528                via_method,
12529                "From<RestartPolicy> for Box<str> impl must round-\
12530                 trip RestartPolicy::{variant:?} to the same lifted \
12531                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
12532                 returns — divergence signals a silent detour off the \
12533                 substrate-primitive accessor"
12534            );
12535            let via_into: Box<str> = variant.into();
12536            assert_eq!(
12537                via_into.as_ref(),
12538                via_method,
12539                "Into<Box<str>>::into on RestartPolicy::{variant:?} \
12540                 must byte-equal RestartPolicy::as_str on the same \
12541                 input — the blanket-derived Into shape must resolve \
12542                 to the same as_str dispatch as the explicit From impl"
12543            );
12544        }
12545    }
12546
12547    #[test]
12548    fn restart_policy_from_borrowed_into_box_str_routes_through_as_str_accessor() {
12549        // Fail-before-pass-after byte-parity pin on the newly lifted
12550        // `impl From<&RestartPolicy> for Box<str>` — asserts the
12551        // borrowed-input standard-library trait impl and the
12552        // substrate-primitive [`super::RestartPolicy::as_str`]
12553        // `pub const fn` accessor resolve to the same three-arm emit-
12554        // set across every arm the exhaustive
12555        // [`super::RestartPolicy::ALL`] slice enumerates. Rust's
12556        // standard library does not carry a blanket
12557        // `impl<T: AsRef<str>> From<&T> for Box<str>` (nor a
12558        // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`),
12559        // so the borrowed-input `Box<str>` forward-projection axis
12560        // is a distinct trait-idiomatic surface that a
12561        // `let key: Box<str> = (&policy).into();`-shaped call site
12562        // or a `RestartPolicy::ALL.iter().map(Box::<str>::from)`-
12563        // shaped pipe reaches through this impl and no other — the
12564        // paired owned-input `From<RestartPolicy> for Box<str>`
12565        // impl (0a1b313) forces every borrowed-input call site
12566        // through an explicit `Copy` deref
12567        // (`Box::<str>::from((*policy).as_str())`) or a
12568        // `Box::<str>::from(policy.as_str())` open-code whose
12569        // type bounds have no compile-time link back to the
12570        // substrate primitive.
12571        //
12572        // Fourth (and closing) peer on the substrate-wide trait-
12573        // idiomatic [`Box<str>`] forward-projection family on the
12574        // M2 OTP-shape tier — closes the `{Self, &Self}` input-
12575        // shape corner of the [`Box<str>`] axis on the second (and
12576        // third-and-final) M2 OTP-shape closed-set fieldless typed
12577        // enum peer on the caixa surface (`:children :restart`),
12578        // exactly as b4dc55c closed the paired [`Cow<'static, str>`]
12579        // axis one commit after its owning half (0612398) landed
12580        // on this enum. Every remaining closed-set fieldless typed
12581        // enum peer on the M3 mesh-shape / outside-M3 caixa-core /
12582        // render-side / outside-caixa-core tiers is a future
12583        // target of the campaign.
12584        //
12585        // Also byte-parity witness against the paired owned-input
12586        // [`From<RestartPolicy> for Box<str>`] and the sibling
12587        // borrowed-input [`From<&RestartPolicy> for &'static str`],
12588        // [`From<&RestartPolicy> for String`], and
12589        // [`From<&RestartPolicy> for Cow<'static, str>`]
12590        // return-shape axes — locking the four
12591        // return-shape × input-shape paths together by construction
12592        // so any future detour trips at caixa-core test time. Then a
12593        // `.iter().map(Box::<str>::from)` pipe witness over
12594        // [`super::RestartPolicy::ALL`] — whose iterator yields
12595        // `&RestartPolicy` by construction, so the borrowed-input
12596        // [`Box<str>`] axis is what routes the pipe through the
12597        // substrate-primitive [`super::RestartPolicy::as_str`]
12598        // accessor without a spurious [`Copy`] deref (which would
12599        // only be reachable through the owned-input
12600        // [`From<RestartPolicy> for Box<str>`] axis by first
12601        // calling `.copied()` on the iterator).
12602        for &variant in RestartPolicy::ALL {
12603            let via_trait: Box<str> = <Box<str> as From<&RestartPolicy>>::from(&variant);
12604            let via_method: &'static str = variant.as_str();
12605            assert_eq!(
12606                via_trait.as_ref(),
12607                via_method,
12608                "From<&RestartPolicy> for Box<str> impl must round-\
12609                 trip &RestartPolicy::{variant:?} to the same lifted \
12610                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
12611                 returns — divergence signals a silent detour off the \
12612                 substrate-primitive accessor"
12613            );
12614            let via_into: Box<str> = (&variant).into();
12615            assert_eq!(
12616                via_into.as_ref(),
12617                via_method,
12618                "Into<Box<str>>::into on &RestartPolicy::{variant:?} \
12619                 must byte-equal RestartPolicy::as_str on the same \
12620                 input — the blanket-derived Into shape must resolve \
12621                 to the same as_str dispatch as the explicit From impl"
12622            );
12623            let owned_box: Box<str> = <Box<str> as From<RestartPolicy>>::from(variant);
12624            assert_eq!(
12625                via_trait, owned_box,
12626                "From<&RestartPolicy> for Box<str> and \
12627                 From<RestartPolicy> for Box<str> must resolve \
12628                 identically on RestartPolicy::{variant:?} — \
12629                 divergence signals the borrowed-input and owned-input \
12630                 Box<str> forward-projection input-shape paths have \
12631                 drifted onto different emit-sets"
12632            );
12633            let borrowed_static: &'static str =
12634                <&'static str as From<&RestartPolicy>>::from(&variant);
12635            assert_eq!(
12636                via_trait.as_ref(),
12637                borrowed_static,
12638                "From<&RestartPolicy> for Box<str> and \
12639                 From<&RestartPolicy> for &'static str must resolve \
12640                 identically on RestartPolicy::{variant:?} — \
12641                 divergence signals the borrowed-input Box<str> and \
12642                 &'static str return-shape paths have drifted onto \
12643                 different emit-sets"
12644            );
12645            let borrowed_string: String = <String as From<&RestartPolicy>>::from(&variant);
12646            assert_eq!(
12647                via_trait.as_ref(),
12648                borrowed_string.as_str(),
12649                "From<&RestartPolicy> for Box<str> and \
12650                 From<&RestartPolicy> for String must resolve \
12651                 identically on RestartPolicy::{variant:?} — \
12652                 divergence signals the borrowed-input Box<str> and \
12653                 owned-`String` return-shape paths have drifted onto \
12654                 different emit-sets"
12655            );
12656            let borrowed_cow: std::borrow::Cow<'static, str> =
12657                <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&variant);
12658            assert_eq!(
12659                via_trait.as_ref(),
12660                borrowed_cow.as_ref(),
12661                "From<&RestartPolicy> for Box<str> and \
12662                 From<&RestartPolicy> for Cow<'static, str> must \
12663                 resolve identically on RestartPolicy::{variant:?} — \
12664                 divergence signals the borrowed-input Box<str> and \
12665                 Cow<'static, str> return-shape paths have drifted \
12666                 onto different emit-sets"
12667            );
12668        }
12669        let via_iter: Vec<Box<str>> = RestartPolicy::ALL.iter().map(Box::<str>::from).collect();
12670        let via_method: Vec<Box<str>> = RestartPolicy::ALL
12671            .iter()
12672            .map(|p| Box::<str>::from(p.as_str()))
12673            .collect();
12674        assert_eq!(
12675            via_iter, via_method,
12676            "`.iter().map(Box::<str>::from)` over \
12677             RestartPolicy::ALL — a call site whose iteration axis \
12678             holds `&RestartPolicy` by construction — must byte-\
12679             equal `.iter().map(|p| Box::<str>::from(p.as_str()))` \
12680             on every arm — the borrowed-input Box<str> \
12681             `From<&RestartPolicy> for Box<str>` axis is what \
12682             makes the `Box::<str>::from` composition route through \
12683             the substrate-primitive `RestartPolicy::as_str` \
12684             accessor without a spurious `Copy` deref (which would \
12685             only be reachable through the owned-input \
12686             `From<RestartPolicy> for Box<str>` axis by first \
12687             calling `.copied()` on the iterator)"
12688        );
12689    }
12690
12691    #[test]
12692    fn restart_policy_from_into_arc_str_routes_through_as_str_accessor() {
12693        // Fail-before-pass-after byte-parity pin on the newly lifted
12694        // `impl From<RestartPolicy> for std::sync::Arc<str>` — asserts
12695        // the owned-input standard-library trait impl and the
12696        // substrate-primitive [`super::RestartPolicy::as_str`]
12697        // `pub const fn` accessor resolve to the same three-arm emit-
12698        // set across every arm the exhaustive
12699        // [`super::RestartPolicy::ALL`] slice enumerates. Extends the
12700        // substrate-wide [`std::sync::Arc<str>`] forward-projection
12701        // campaign tier opened one projection tier prior (bca2ec8) on
12702        // the paired sibling-restart [`RestartStrategy`] owned-input
12703        // first-mover onto the second (and third-and-final) M2 OTP-
12704        // shape closed-set fieldless typed enum peer on the caixa
12705        // surface (`:children :restart`), immediately after the paired
12706        // [`Box<str>`] axis (0a1b313 / cb1d068) closed the
12707        // `{Self, &Self} × {&'static str, String, Cow<'static, str>,
12708        // Box<str>}` 2×4 corner on this enum. Rust's standard library
12709        // carries `impl From<&str> for std::sync::Arc<str>` and
12710        // `impl From<String> for std::sync::Arc<str>` but no blanket
12711        // `impl<T: AsRef<str>> From<T> for std::sync::Arc<str>` (nor
12712        // an `impl<T: fmt::Display> From<T> for std::sync::Arc<str>`),
12713        // so this axis is a distinct trait-idiomatic surface that a
12714        // `let key: std::sync::Arc<str> = policy.into();`-shaped call
12715        // site reaches through this impl and no other — a paired
12716        // `std::sync::Arc::<str>::from(policy.as_str())` open-code
12717        // has no compile-time link back to the substrate primitive,
12718        // and a two-step `std::sync::Arc::<str>::from(String::from(
12719        // policy))` composition through the owned-`String` axis
12720        // allocates twice (once into the intermediate `String`, once
12721        // into the [`Arc<str>`] on the `From<String>` conversion)
12722        // where the single-step trait impl allocates once.
12723        //
12724        // Cross-axis byte-parity witness against the sibling owned-
12725        // input `{&'static str, String, Cow<'static, str>, Box<str>}`
12726        // return-shape axes — locking the five return-shape paths on
12727        // the owned-input surface together by construction so any
12728        // future detour off the substrate-primitive
12729        // [`super::RestartPolicy::as_str`] accessor trips at caixa-
12730        // core test time.
12731        for &variant in RestartPolicy::ALL {
12732            let via_trait: std::sync::Arc<str> =
12733                <std::sync::Arc<str> as From<RestartPolicy>>::from(variant);
12734            let via_method: &'static str = variant.as_str();
12735            assert_eq!(
12736                via_trait.as_ref(),
12737                via_method,
12738                "From<RestartPolicy> for std::sync::Arc<str> impl \
12739                 must round-trip RestartPolicy::{variant:?} to the \
12740                 same lifted SUPERVISOR_CHILD_RESTART_* const \
12741                 RestartPolicy::as_str returns — divergence signals \
12742                 a silent detour off the substrate-primitive accessor"
12743            );
12744            let via_into: std::sync::Arc<str> = variant.into();
12745            assert_eq!(
12746                via_into.as_ref(),
12747                via_method,
12748                "Into<std::sync::Arc<str>>::into on \
12749                 RestartPolicy::{variant:?} must byte-equal \
12750                 RestartPolicy::as_str on the same input — the \
12751                 blanket-derived Into shape must resolve to the same \
12752                 as_str dispatch as the explicit From impl"
12753            );
12754            let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
12755            assert_eq!(
12756                via_trait.as_ref(),
12757                owned_static,
12758                "From<RestartPolicy> for std::sync::Arc<str> and \
12759                 From<RestartPolicy> for &'static str must resolve \
12760                 identically on RestartPolicy::{variant:?} — \
12761                 divergence signals the owned-input std::sync::Arc<str> \
12762                 and &'static str return-shape paths have drifted onto \
12763                 different emit-sets"
12764            );
12765            let owned_string: String = <String as From<RestartPolicy>>::from(variant);
12766            assert_eq!(
12767                via_trait.as_ref(),
12768                owned_string.as_str(),
12769                "From<RestartPolicy> for std::sync::Arc<str> and \
12770                 From<RestartPolicy> for String must resolve \
12771                 identically on RestartPolicy::{variant:?} — \
12772                 divergence signals the owned-input std::sync::Arc<str> \
12773                 and owned-`String` return-shape paths have drifted \
12774                 onto different emit-sets"
12775            );
12776            let owned_cow: std::borrow::Cow<'static, str> =
12777                <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
12778            assert_eq!(
12779                via_trait.as_ref(),
12780                owned_cow.as_ref(),
12781                "From<RestartPolicy> for std::sync::Arc<str> and \
12782                 From<RestartPolicy> for Cow<'static, str> must \
12783                 resolve identically on RestartPolicy::{variant:?} — \
12784                 divergence signals the owned-input std::sync::Arc<str> \
12785                 and Cow<'static, str> return-shape paths have drifted \
12786                 onto different emit-sets"
12787            );
12788            let owned_box: Box<str> = <Box<str> as From<RestartPolicy>>::from(variant);
12789            assert_eq!(
12790                via_trait.as_ref(),
12791                owned_box.as_ref(),
12792                "From<RestartPolicy> for std::sync::Arc<str> and \
12793                 From<RestartPolicy> for Box<str> must resolve \
12794                 identically on RestartPolicy::{variant:?} — \
12795                 divergence signals the owned-input std::sync::Arc<str> \
12796                 and Box<str> return-shape paths have drifted onto \
12797                 different emit-sets"
12798            );
12799        }
12800    }
12801
12802    #[test]
12803    fn restart_policy_from_borrowed_into_arc_str_routes_through_as_str_accessor() {
12804        // Fail-before-pass-after byte-parity pin on the newly lifted
12805        // `impl From<&RestartPolicy> for std::sync::Arc<str>` —
12806        // asserts the borrowed-input standard-library trait impl and
12807        // the substrate-primitive [`super::RestartPolicy::as_str`]
12808        // `pub const fn` accessor resolve to the same three-arm
12809        // emit-set across every arm the exhaustive
12810        // [`super::RestartPolicy::ALL`] slice enumerates. Rust's
12811        // standard library carries `impl From<&str> for
12812        // std::sync::Arc<str>` and `impl From<String> for
12813        // std::sync::Arc<str>` but no blanket
12814        // `impl<T: AsRef<str>> From<&T> for std::sync::Arc<str>` (nor
12815        // a `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`),
12816        // so the borrowed-input [`std::sync::Arc<str>`] forward-
12817        // projection axis is a distinct trait-idiomatic surface that
12818        // a `let key: std::sync::Arc<str> = (&policy).into();`-shaped
12819        // call site or a
12820        // `RestartPolicy::ALL.iter().map(std::sync::Arc::<str>::from)`-
12821        // shaped pipe reaches through this impl and no other — the
12822        // paired owned-input [`From<RestartPolicy> for
12823        // std::sync::Arc<str>`] impl (b05724e) forces every borrowed-
12824        // input call site through an explicit [`Copy`] deref
12825        // (`std::sync::Arc::<str>::from((*policy).as_str())`) or a
12826        // `std::sync::Arc::<str>::from(policy.as_str())` open-code
12827        // whose type bounds have no compile-time link back to the
12828        // substrate primitive.
12829        //
12830        // Closes the `{Self, &Self}` input-shape corner of the
12831        // substrate-wide trait-idiomatic [`std::sync::Arc<str>`]
12832        // forward-projection family on the second (and third-and-
12833        // final) M2 OTP-shape closed-set fieldless typed enum peer
12834        // on the caixa surface (`:children :restart`), one commit
12835        // after b05724e opened the owned-input half — exactly as
12836        // b3e72d7 closed the paired [`std::sync::Arc<str>`] corner on
12837        // the sibling-restart [`RestartStrategy`] first-mover one
12838        // commit after its owning half (bca2ec8) landed, and as
12839        // cb1d068 closed the paired [`Box<str>`] corner on this
12840        // enum one commit after its owning half (0a1b313) landed.
12841        //
12842        // Also byte-parity witness against the paired owned-input
12843        // [`From<RestartPolicy> for std::sync::Arc<str>`] and the
12844        // sibling borrowed-input [`From<&RestartPolicy> for
12845        // &'static str`], [`From<&RestartPolicy> for String`],
12846        // [`From<&RestartPolicy> for Cow<'static, str>`], and
12847        // [`From<&RestartPolicy> for Box<str>`] return-shape axes —
12848        // locking the five return-shape × input-shape paths together
12849        // by construction so any future detour off the substrate-
12850        // primitive [`super::RestartPolicy::as_str`] accessor trips
12851        // at caixa-core test time. Then a
12852        // `.iter().map(std::sync::Arc::<str>::from)` pipe witness
12853        // over [`super::RestartPolicy::ALL`] — whose iterator yields
12854        // `&RestartPolicy` by construction, so the borrowed-input
12855        // [`std::sync::Arc<str>`] axis is what routes the pipe
12856        // through the substrate-primitive
12857        // [`super::RestartPolicy::as_str`] accessor without a
12858        // spurious [`Copy`] deref (which would only be reachable
12859        // through the owned-input
12860        // [`From<RestartPolicy> for std::sync::Arc<str>`] axis by
12861        // first calling `.copied()` on the iterator).
12862        for &variant in RestartPolicy::ALL {
12863            let via_trait: std::sync::Arc<str> =
12864                <std::sync::Arc<str> as From<&RestartPolicy>>::from(&variant);
12865            let via_method: &'static str = variant.as_str();
12866            assert_eq!(
12867                via_trait.as_ref(),
12868                via_method,
12869                "From<&RestartPolicy> for std::sync::Arc<str> impl \
12870                 must round-trip &RestartPolicy::{variant:?} to the \
12871                 same lifted SUPERVISOR_CHILD_RESTART_* const \
12872                 RestartPolicy::as_str returns — divergence signals \
12873                 a silent detour off the substrate-primitive accessor"
12874            );
12875            let via_into: std::sync::Arc<str> = (&variant).into();
12876            assert_eq!(
12877                via_into.as_ref(),
12878                via_method,
12879                "Into<std::sync::Arc<str>>::into on \
12880                 &RestartPolicy::{variant:?} must byte-equal \
12881                 RestartPolicy::as_str on the same input — the \
12882                 blanket-derived Into shape must resolve to the same \
12883                 as_str dispatch as the explicit From impl"
12884            );
12885            let owned_arc: std::sync::Arc<str> =
12886                <std::sync::Arc<str> as From<RestartPolicy>>::from(variant);
12887            assert_eq!(
12888                via_trait, owned_arc,
12889                "From<&RestartPolicy> for std::sync::Arc<str> and \
12890                 From<RestartPolicy> for std::sync::Arc<str> must \
12891                 resolve identically on RestartPolicy::{variant:?} — \
12892                 divergence signals the borrowed-input and owned-input \
12893                 std::sync::Arc<str> forward-projection input-shape \
12894                 paths have drifted onto different emit-sets"
12895            );
12896            let borrowed_static: &'static str =
12897                <&'static str as From<&RestartPolicy>>::from(&variant);
12898            assert_eq!(
12899                via_trait.as_ref(),
12900                borrowed_static,
12901                "From<&RestartPolicy> for std::sync::Arc<str> and \
12902                 From<&RestartPolicy> for &'static str must resolve \
12903                 identically on RestartPolicy::{variant:?} — \
12904                 divergence signals the borrowed-input std::sync::Arc<str> \
12905                 and &'static str return-shape paths have drifted onto \
12906                 different emit-sets"
12907            );
12908            let borrowed_string: String = <String as From<&RestartPolicy>>::from(&variant);
12909            assert_eq!(
12910                via_trait.as_ref(),
12911                borrowed_string.as_str(),
12912                "From<&RestartPolicy> for std::sync::Arc<str> and \
12913                 From<&RestartPolicy> for String must resolve \
12914                 identically on RestartPolicy::{variant:?} — \
12915                 divergence signals the borrowed-input std::sync::Arc<str> \
12916                 and owned-`String` return-shape paths have drifted \
12917                 onto different emit-sets"
12918            );
12919            let borrowed_cow: std::borrow::Cow<'static, str> =
12920                <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&variant);
12921            assert_eq!(
12922                via_trait.as_ref(),
12923                borrowed_cow.as_ref(),
12924                "From<&RestartPolicy> for std::sync::Arc<str> and \
12925                 From<&RestartPolicy> for Cow<'static, str> must \
12926                 resolve identically on RestartPolicy::{variant:?} — \
12927                 divergence signals the borrowed-input std::sync::Arc<str> \
12928                 and Cow<'static, str> return-shape paths have drifted \
12929                 onto different emit-sets"
12930            );
12931            let borrowed_box: Box<str> = <Box<str> as From<&RestartPolicy>>::from(&variant);
12932            assert_eq!(
12933                via_trait.as_ref(),
12934                borrowed_box.as_ref(),
12935                "From<&RestartPolicy> for std::sync::Arc<str> and \
12936                 From<&RestartPolicy> for Box<str> must resolve \
12937                 identically on RestartPolicy::{variant:?} — \
12938                 divergence signals the borrowed-input std::sync::Arc<str> \
12939                 and Box<str> return-shape paths have drifted onto \
12940                 different emit-sets"
12941            );
12942        }
12943        let via_iter: Vec<std::sync::Arc<str>> = RestartPolicy::ALL
12944            .iter()
12945            .map(std::sync::Arc::<str>::from)
12946            .collect();
12947        let via_method: Vec<std::sync::Arc<str>> = RestartPolicy::ALL
12948            .iter()
12949            .map(|p| std::sync::Arc::<str>::from(p.as_str()))
12950            .collect();
12951        assert_eq!(
12952            via_iter, via_method,
12953            "`.iter().map(std::sync::Arc::<str>::from)` over \
12954             RestartPolicy::ALL — a call site whose iteration axis \
12955             holds `&RestartPolicy` by construction — must byte-\
12956             equal `.iter().map(|p| std::sync::Arc::<str>::from(p.as_str()))` \
12957             on every arm — the borrowed-input std::sync::Arc<str> \
12958             `From<&RestartPolicy> for std::sync::Arc<str>` axis is \
12959             what makes the `std::sync::Arc::<str>::from` composition \
12960             route through the substrate-primitive \
12961             `RestartPolicy::as_str` accessor without a spurious \
12962             `Copy` deref (which would only be reachable through the \
12963             owned-input `From<RestartPolicy> for std::sync::Arc<str>` \
12964             axis by first calling `.copied()` on the iterator)"
12965        );
12966    }
12967
12968    // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_RESTART_* identity ─
12969
12970    #[test]
12971    fn restart_policy_variants_serialize_to_lifted_scalar_values() {
12972        // The fail-before-pass-after pin: pre-lift there was no
12973        // single-source binding between the [`RestartPolicy`] variant
12974        // name the un-`rename`d `Serialize` derive emits under
12975        // [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
12976        // byte-string every downstream cluster-side dispatcher (the
12977        // future wasm-operator's per-child post-exit restart-decision
12978        // branch, the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
12979        // materializer's admission-time enum-arm bind, the
12980        // `caixa-operator`'s hierarchical reconciliation scheduler's
12981        // per-child-policy fan-out) probes verbatim. A future
12982        // `#[serde(rename_all = "kebab-case")]` attribute on the enum —
12983        // or a per-variant `#[serde(rename = "…")]` override, or a
12984        // variant rename in the source — would silently rebrand the
12985        // emitted scalar under one spelling while every downstream
12986        // dispatcher still probed the other, with the failure surfacing
12987        // at the operator's reconcile posture (children coming up under
12988        // the `default()` `Permanent` arm rather than the typed slot's
12989        // declared policy — a `:temporary` `oneShot` child would be
12990        // restarted on clean exit, treating the successful-completion
12991        // signal as failure and re-running the completion-terminal
12992        // one-shot indefinitely; a `:transient` child that clean-exited
12993        // would be restarted, masking the clean-completion contract)
12994        // far from the source rebrand commit and with no field naming
12995        // the drift. Pinning the two paths (the `Serialize` derive's
12996        // serialized string AND the [`RestartPolicy::as_str`] helper)
12997        // to the same three lifted
12998        // [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
12999        // [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
13000        // [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
13001        // byte-strings makes any future drift on either endpoint fail
13002        // here at caixa-core build time. Peer of the sibling
13003        // [`restart_strategy_variants_serialize_to_lifted_scalar_values`]
13004        // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
13005        // and the M3
13006        // `placement_strategy_variants_serialize_to_lifted_scalar_values`
13007        // (3f0e21c) on the per-Aplicacao distribution-strategy axis —
13008        // same three-path-convergence discipline, extended to close the
13009        // third OTP-shaped closed-enum discriminator axis on the caixa
13010        // typed surface (per-child restart-decision policy).
13011        for (variant, expected) in [
13012            (
13013                RestartPolicy::Permanent,
13014                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
13015            ),
13016            (
13017                RestartPolicy::Temporary,
13018                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
13019            ),
13020            (
13021                RestartPolicy::Transient,
13022                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
13023            ),
13024        ] {
13025            let json = serde_json::to_string(&variant).unwrap();
13026            assert_eq!(
13027                json,
13028                format!("\"{expected}\""),
13029                "RestartPolicy::{variant:?} must serialize to {expected:?}"
13030            );
13031            assert_eq!(
13032                variant.as_str(),
13033                expected,
13034                "RestartPolicy::{variant:?}.as_str() must return the lifted \
13035                 SUPERVISOR_CHILD_RESTART_* constant"
13036            );
13037        }
13038    }
13039
13040    #[test]
13041    fn supervisor_child_restart_consts_are_pairwise_distinct() {
13042        // Cross-arm drift-detection pin: a future collapse of two
13043        // canonical variant byte-strings onto the same value (e.g. an
13044        // accidental copy-paste flip of `SUPERVISOR_CHILD_RESTART_TRANSIENT`
13045        // to also read `"Permanent"`) would silently reroute every
13046        // downstream operator's per-child-policy dispatch onto the
13047        // sibling arm's reconcile branch and pass every propagation-probe
13048        // test that expected only the stale arm's value — a `:transient`
13049        // child would come up under the `:permanent` restart-decision
13050        // posture on every subsequent clean exit, so a completion-terminal
13051        // child would be restarted indefinitely against its declared
13052        // policy. Peer of the sibling
13053        // [`supervisor_estrategia_consts_are_pairwise_distinct`]
13054        // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
13055        // and the four-way distinct pin
13056        // `supervisor_key_consts_are_pairwise_distinct` (40cc4e5) on the
13057        // top-level `SUPERVISOR_KEY_*` axis.
13058        let all = [
13059            crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
13060            crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
13061            crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
13062        ];
13063        for (i, a) in all.iter().enumerate() {
13064            for (j, b) in all.iter().enumerate() {
13065                if i != j {
13066                    assert_ne!(
13067                        a, b,
13068                        "SUPERVISOR_CHILD_RESTART_* consts must be pairwise distinct \
13069                         — got duplicate {a:?} at indices {i} and {j}",
13070                    );
13071                }
13072            }
13073        }
13074    }
13075
13076    #[test]
13077    fn restart_policy_display_routes_through_as_str_helper() {
13078        // The fail-before-pass-after pin on the first half of the
13079        // three-path convergence: pre-convergence [`RestartPolicy`]
13080        // carried a [`std::fmt::Display`] surface via its
13081        // `#[discriminant(also_display)]` gen-platform derive route,
13082        // which arrived kebab-case as `"permanent"` / `"temporary"`
13083        // / `"transient"` on this three-arm enum (whose variant
13084        // names each collapse to their own lowercase form under the
13085        // kebab-case transform) while the wire format ran as
13086        // PascalCase `"Permanent"` / `"Temporary"` / `"Transient"`
13087        // through the un-`rename`d serde derive. Every consumer
13088        // reaching for a policy byte-string past the wire format had
13089        // to pick between three paths ([`RestartPolicy::as_str`],
13090        // the `Serialize` derive's serialized string, or
13091        // `format!("{v}")` on the discriminant-Display route), any
13092        // two of which a future variant rename or
13093        // `#[serde(rename_all = "kebab-case")]` attribute would
13094        // silently desynchronize. Wiring [`std::fmt::Display`]
13095        // through [`RestartPolicy::as_str`] closes the third path:
13096        // every `format!("{v}")` call reaches the same lifted
13097        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the
13098        // wire format and the [`RestartPolicy::as_str`] helper
13099        // already route through, so a future variant rename lands at
13100        // exactly one place. Pin the routing here so a future
13101        // `impl std::fmt::Display for RestartPolicy`
13102        // reimplementation that hand-rolls the arms instead of
13103        // delegating to [`RestartPolicy::as_str`] fails at
13104        // caixa-core build time. Peer of the sibling
13105        // [`restart_strategy_display_routes_through_as_str_helper`]
13106        // on the per-supervisor sibling-restart-strategy axis and
13107        // the M3
13108        // `placement_strategy_display_routes_through_as_str_helper`
13109        // (cc8f749) — the third of three OTP-shape closed-enum
13110        // discriminator axes on the caixa typed surface now
13111        // converged onto the same three-path
13112        // (Display → as_str → lifted const) discipline.
13113        for variant in [
13114            RestartPolicy::Permanent,
13115            RestartPolicy::Temporary,
13116            RestartPolicy::Transient,
13117        ] {
13118            assert_eq!(
13119                variant.to_string(),
13120                variant.as_str(),
13121                "RestartPolicy::{variant:?} Display must route through \
13122                 RestartPolicy::as_str (single source of truth: the lifted \
13123                 SUPERVISOR_CHILD_RESTART_* const the wire format also emits)"
13124            );
13125        }
13126    }
13127
13128    #[test]
13129    fn restart_policy_display_matches_serialized_wire_byte_string() {
13130        // The fail-before-pass-after pin on the second half of the
13131        // three-path convergence: `Display` (user-facing text) agrees
13132        // byte-for-byte with the `Serialize` derive's wire format
13133        // (canonical camelCase-schema `SUPERVISOR_CHILD_KEY_RESTART`
13134        // scalar) on every variant. Pre-convergence the two paths
13135        // were structurally independent — a future
13136        // `#[serde(rename_all = "kebab-case")]` attribute on the
13137        // enum would silently rebrand the emitted wire scalar
13138        // (`permanent`, `temporary`, `transient`) while every
13139        // consumer that pretty-prints the policy (the future
13140        // wasm-operator's per-child post-exit restart-decision
13141        // diagnostic line, the future `feira app graph` per-child
13142        // restart column, the future M4
13143        // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
13144        // per-child admission-webhook rejection body) would still
13145        // emit the PascalCase form the `as_str` / `Display` route
13146        // returns, with the mismatch surfacing at consumer parse
13147        // time / operator dispatch time far from the source rebrand
13148        // commit. Pin the two paths byte-for-byte here so any future
13149        // serde-attribute or variant-rename drift is a
13150        // caixa-core-build-time test failure at this call, not a
13151        // silent per-consumer dispatch miss. Peer of the sibling
13152        // [`restart_strategy_display_matches_serialized_wire_byte_string`]
13153        // on the per-supervisor sibling-restart-strategy axis and
13154        // the M3
13155        // `placement_strategy_display_matches_serialized_wire_byte_string`
13156        // (cc8f749).
13157        for variant in [
13158            RestartPolicy::Permanent,
13159            RestartPolicy::Temporary,
13160            RestartPolicy::Transient,
13161        ] {
13162            let wire = serde_json::to_string(&variant).unwrap();
13163            let unquoted = wire
13164                .strip_prefix('"')
13165                .and_then(|s| s.strip_suffix('"'))
13166                .expect("serialized RestartPolicy is a JSON string");
13167            assert_eq!(
13168                variant.to_string(),
13169                unquoted,
13170                "RestartPolicy::{variant:?} Display byte-string must match the \
13171                 Serialize derive's wire byte-string (three-path convergence: \
13172                 Display + as_str + Serialize all resolve to the same \
13173                 SUPERVISOR_CHILD_RESTART_* const)"
13174            );
13175        }
13176    }
13177
13178    #[test]
13179    fn restart_policy_as_ref_str_routes_through_as_str_accessor() {
13180        // Fail-before-pass-after byte-parity pin on the lifted
13181        // `impl AsRef<str> for RestartPolicy` — asserts the
13182        // standard-library trait impl and the substrate-primitive
13183        // [`RestartPolicy::as_str`] `pub const fn` accessor resolve
13184        // to the same `&str` per instance across the three-arm
13185        // closed set, so any future silent detour that routes the
13186        // impl through a divergent projection (a per-arm inline
13187        // `match self { RestartPolicy::Permanent => "Permanent", … }`
13188        // re-inlining that opens a compile-time link to the un-lifted
13189        // arm-literal, a swap onto the kebab-case
13190        // [`gen_platform::Discriminant`] catalog identity that would
13191        // collide the wire axis with the dispatcher-catalog axis) trips
13192        // at caixa-core test time under `PartialEq` rather than at a
13193        // downstream `impl AsRef<str>`-bound consumer's silent split.
13194        // Sweeps every one of the three arms
13195        // [`RestartPolicy::ALL`] carries so no arm's projection is
13196        // covered only by the sibling wire-format `Serialize` derive
13197        // path. Peer of the sibling
13198        // [`restart_strategy_as_ref_str_routes_through_as_str_accessor`]
13199        // (63eb1a4) on the paired per-supervisor sibling-restart-
13200        // strategy axis and the [`crate::CaixaVersion`]
13201        // `AsRef<str>`-byte-parity pin (16d5c7e) on the paired
13202        // top-level `:versao` typed newtype — the three pins together
13203        // cover the substrate primitive's `AsRef<str>` projection axis
13204        // on the paired newtype + M2 closed-set-typed-enum surface.
13205        for &variant in RestartPolicy::ALL {
13206            assert_eq!(
13207                <RestartPolicy as AsRef<str>>::as_ref(&variant),
13208                variant.as_str(),
13209                "AsRef<str> impl on RestartPolicy::{variant:?} must \
13210                 byte-equal RestartPolicy::as_str on the same instance \
13211                 — divergence signals a silent detour off the substrate-\
13212                 primitive accessor"
13213            );
13214        }
13215    }
13216
13217    #[test]
13218    fn restart_policy_as_ref_str_routes_through_display_via_shared_accessor() {
13219        // Fail-before-pass-after byte-parity pin on the three-path
13220        // convergence discipline the M2 per-child-restart-policy
13221        // primitive now carries on the `&str`-projection axis:
13222        // `<RestartPolicy as AsRef<str>>::as_ref(&v)` (the newly
13223        // lifted impl), `format!("{v}")` (the pre-existing
13224        // [`fmt::Display`] impl), and `v.as_str()` (the substrate-
13225        // primitive `pub const fn` accessor both trait impls delegate
13226        // through) must resolve to the same byte-string on every
13227        // instance across the three-arm closed set. Refuses any future
13228        // divergence between the two trait impls (a stray
13229        // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
13230        // rather than delegating through the shared accessor; a
13231        // hypothetical `AsRef<str>` rewrite that inlines a per-arm
13232        // literal cascade) that would silently split the two
13233        // projection paths of the same closed-set typed enum. Mirrors
13234        // the sibling three-path-convergence discipline the peer
13235        // [`RestartStrategy`] typed enum carries on its
13236        // `AsRef<str>` / `Display` / `as_str` triple
13237        // (supervisor.rs pin
13238        // `restart_strategy_as_ref_str_routes_through_display_via_shared_accessor`,
13239        // 63eb1a4) and the [`crate::CaixaVersion`] typed newtype
13240        // carries on the same triple (version.rs pin
13241        // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
13242        // 16d5c7e).
13243        for &variant in RestartPolicy::ALL {
13244            let via_as_ref: &str = <RestartPolicy as AsRef<str>>::as_ref(&variant);
13245            let via_display: String = format!("{variant}");
13246            let via_accessor: &str = variant.as_str();
13247            assert_eq!(via_as_ref, via_accessor);
13248            assert_eq!(via_display, via_accessor);
13249            assert_eq!(via_as_ref, via_display.as_str());
13250        }
13251    }
13252
13253    // The `generic_bytes_sink(&variant)` and `borrowed_hasher.update(&variant)`
13254    // shapes below are the borrowed-input witness half of the by-value +
13255    // by-reference partition the paired witness pair carries: the pair proves
13256    // the trait bound accepts both owned (`variant`) and borrowed (`&variant`)
13257    // shapes through the same substrate-primitive `as_str` accessor, which is
13258    // the shape the caixa-lacre BLAKE3 content-address closure composes.
13259    // `clippy::needless_borrows_for_generic_args` would fold the borrowed half
13260    // into the owned half and collapse the by-value/by-reference partition
13261    // this test load-bears; the `#[allow]` documents that the partition is
13262    // deliberate, not an oversight.
13263    #[allow(clippy::needless_borrows_for_generic_args)]
13264    #[test]
13265    fn restart_policy_as_ref_bytes_routes_through_as_str_accessor() {
13266        // `<T: AsRef<[u8]>>`-bound generic-consumer witness: a byte-input
13267        // function that binds its argument through the standard-library
13268        // [`AsRef<[u8]>`] trait bound accepts a [`super::RestartPolicy`]
13269        // directly, without the caller open-coding the two-hop
13270        // `restart.as_str().as_bytes()` composition. Lifted to the top
13271        // of the function per `clippy::items_after_statements`.
13272        fn generic_bytes_sink<T: AsRef<[u8]>>(t: T) -> Vec<u8> {
13273            t.as_ref().to_vec()
13274        }
13275        // `blake3::Hasher::update`-shape byte-input surface mock: mirrors
13276        // `blake3::Hasher::update` / `ring::digest::Context::update` /
13277        // `sha2::Sha256::update`'s `impl AsRef<[u8]>`-bound `update`
13278        // signature so a per-child BLAKE3 content-address closure that
13279        // composes `hasher.update(restart)` on the [`crate::Lacre`]
13280        // closure builder reaches the substrate-primitive `as_str`
13281        // accessor through the [`super::RestartPolicy`] `AsRef<[u8]>`
13282        // axis and no other. Lifted to the top of the function per
13283        // `clippy::items_after_statements`.
13284        struct MockHasher(Vec<u8>);
13285        impl MockHasher {
13286            fn new() -> Self {
13287                Self(Vec::new())
13288            }
13289            fn update(&mut self, bytes: impl AsRef<[u8]>) -> &mut Self {
13290                self.0.extend_from_slice(bytes.as_ref());
13291                self
13292            }
13293            fn finalize(self) -> Vec<u8> {
13294                self.0
13295            }
13296        }
13297
13298        // Fail-before-pass-after byte-parity pin on the newly lifted
13299        // `impl AsRef<[u8]> for RestartPolicy` — asserts the trait-
13300        // idiomatic byte-view standard-library impl and the substrate-
13301        // primitive [`super::RestartPolicy::as_str`] `pub const fn`
13302        // accessor's `.as_bytes()` byte-tail resolve to the same three-
13303        // arm `PascalCase` wire byte-string emit-set across every arm
13304        // the exhaustive [`super::RestartPolicy::ALL`] slice enumerates.
13305        // Extends the trait-idiomatic byte-view axis onto the second
13306        // (and final) M2 OTP-shape closed-set fieldless typed enum peer
13307        // on the caixa surface (the paired per-child restart-decision
13308        // policy sibling on the same M2 `:supervisor` slot), closing
13309        // the byte-view axis across the `:supervisor :estrategia` +
13310        // `:children :restart` M2 slot pair the sibling
13311        // [`super::RestartStrategy`] first-mover (cd4c4e0) opened.
13312        //
13313        // Rust's standard library carries `impl AsRef<[u8]> for str` and
13314        // `impl AsRef<[u8]> for String`, so a two-hop composition
13315        // `restart.as_str().as_bytes()` (or the equally two-hop
13316        // `AsRef::<str>::as_ref(&restart).as_bytes()`) is reachable
13317        // through the pre-existing str-view axis alone. But that two-hop
13318        // shape has no compile-time link back to the byte-projection
13319        // axis, forces every downstream `<T: AsRef<[u8]>>`-bound
13320        // consumer to open-code the two-hop composition at every call
13321        // site, and admits a silent split whenever a future call site
13322        // takes a sibling reverse-projection axis whose `.as_bytes()`
13323        // byte-tail carries no compile-time byte-view surface. This
13324        // impl closes the byte-view axis at the substrate-primitive
13325        // [`super::RestartPolicy::as_str`] accessor so every future
13326        // `<T: AsRef<[u8]>>`-bound consumer reaches the same lifted
13327        // [`super::crate::render::SUPERVISOR_CHILD_RESTART_*`] const
13328        // roster the paired str-view axes already return through —
13329        // through one trait dispatch.
13330        for &variant in RestartPolicy::ALL {
13331            let via_trait: &[u8] = <RestartPolicy as AsRef<[u8]>>::as_ref(&variant);
13332            let via_method_bytes: &[u8] = variant.as_str().as_bytes();
13333            assert_eq!(
13334                via_trait, via_method_bytes,
13335                "AsRef<[u8]> for RestartPolicy impl must byte-equal \
13336                 RestartPolicy::as_str().as_bytes() on \
13337                 RestartPolicy::{variant:?} — divergence signals a \
13338                 silent detour off the substrate-primitive accessor"
13339            );
13340            // Cross-axis witness against the paired str-view axes'
13341            // `.as_bytes()` byte-tails: [`AsRef<str>`] /
13342            // [`std::fmt::Display`] / [`super::RestartPolicy::as_str`]
13343            // all resolve to the same lifted
13344            // [`super::crate::render::SUPERVISOR_CHILD_RESTART_*`] const
13345            // roster, and the byte-view axis must byte-equal each of
13346            // their `.as_bytes()` byte-tails by construction — locking
13347            // the str-view and byte-view axes together at the
13348            // substrate-primitive accessor.
13349            let str_view_ref: &str = <RestartPolicy as AsRef<str>>::as_ref(&variant);
13350            assert_eq!(
13351                via_trait,
13352                str_view_ref.as_bytes(),
13353                "AsRef<[u8]> for RestartPolicy and AsRef<str> for \
13354                 RestartPolicy must resolve to byte-equal byte-tails \
13355                 on RestartPolicy::{variant:?} — divergence signals \
13356                 the byte-view and str-view axes have drifted off the \
13357                 same substrate-primitive as_str accessor"
13358            );
13359            let display_bytes = variant.to_string();
13360            assert_eq!(
13361                via_trait,
13362                display_bytes.as_bytes(),
13363                "AsRef<[u8]> for RestartPolicy and \
13364                 <RestartPolicy as std::fmt::Display>::to_string must \
13365                 resolve to byte-equal byte-tails on \
13366                 RestartPolicy::{variant:?} — divergence signals the \
13367                 byte-view axis and the Display formatter axis have \
13368                 drifted off the same substrate-primitive as_str \
13369                 accessor"
13370            );
13371            // Cross-axis witness against the paired reverse-projection
13372            // axes' `.as_bytes()` byte-tails: every one of `{&'static
13373            // str, String, Cow<'static, str>, Box<str>,
13374            // std::sync::Arc<str>}` allocates (or borrows) the same
13375            // `PascalCase` wire byte-string the substrate-primitive
13376            // accessor emits, so the byte-view axis must byte-equal
13377            // each of their `.as_bytes()` byte-tails by construction.
13378            let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
13379            assert_eq!(
13380                via_trait,
13381                owned_static.as_bytes(),
13382                "AsRef<[u8]> for RestartPolicy and From<RestartPolicy> \
13383                 for &'static str must resolve to byte-equal byte-tails \
13384                 on RestartPolicy::{variant:?}"
13385            );
13386            let owned_string: String = <String as From<RestartPolicy>>::from(variant);
13387            assert_eq!(
13388                via_trait,
13389                owned_string.as_bytes(),
13390                "AsRef<[u8]> for RestartPolicy and From<RestartPolicy> \
13391                 for String must resolve to byte-equal byte-tails on \
13392                 RestartPolicy::{variant:?}"
13393            );
13394            let owned_cow: std::borrow::Cow<'static, str> =
13395                <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
13396            assert_eq!(
13397                via_trait,
13398                owned_cow.as_bytes(),
13399                "AsRef<[u8]> for RestartPolicy and From<RestartPolicy> \
13400                 for Cow<'static, str> must resolve to byte-equal byte-\
13401                 tails on RestartPolicy::{variant:?}"
13402            );
13403            let owned_box: Box<str> = <Box<str> as From<RestartPolicy>>::from(variant);
13404            assert_eq!(
13405                via_trait,
13406                owned_box.as_bytes(),
13407                "AsRef<[u8]> for RestartPolicy and From<RestartPolicy> \
13408                 for Box<str> must resolve to byte-equal byte-tails on \
13409                 RestartPolicy::{variant:?}"
13410            );
13411            let owned_arc: std::sync::Arc<str> =
13412                <std::sync::Arc<str> as From<RestartPolicy>>::from(variant);
13413            assert_eq!(
13414                via_trait,
13415                owned_arc.as_bytes(),
13416                "AsRef<[u8]> for RestartPolicy and From<RestartPolicy> \
13417                 for std::sync::Arc<str> must resolve to byte-equal \
13418                 byte-tails on RestartPolicy::{variant:?}"
13419            );
13420        }
13421        // `<T: AsRef<[u8]>>`-bound-consumer witness: the generic byte-
13422        // input function `generic_bytes_sink` (lifted above per
13423        // `clippy::items_after_statements`) accepts a
13424        // [`super::RestartPolicy`] directly through the trait bound,
13425        // without the caller open-coding the two-hop
13426        // `restart.as_str().as_bytes()` composition. This is the shape
13427        // that reaches the caixa-lacre BLAKE3 content-address closure's
13428        // `blake3::Hasher::update(impl AsRef<[u8]>)` byte-input surface
13429        // through this impl and no other.
13430        for &variant in RestartPolicy::ALL {
13431            let via_generic = generic_bytes_sink(variant);
13432            let via_borrowed_generic = generic_bytes_sink(&variant);
13433            let via_method_bytes = variant.as_str().as_bytes().to_vec();
13434            assert_eq!(
13435                via_generic, via_method_bytes,
13436                "generic `<T: AsRef<[u8]>>`-bound consumer on \
13437                 RestartPolicy::{variant:?} must yield the same byte-\
13438                 tail RestartPolicy::as_str().as_bytes() returns — \
13439                 divergence signals the byte-view axis fails to bridge \
13440                 a generic byte-input trait bound to the substrate-\
13441                 primitive accessor"
13442            );
13443            assert_eq!(
13444                via_borrowed_generic, via_method_bytes,
13445                "generic `<T: AsRef<[u8]>>`-bound consumer on \
13446                 &RestartPolicy::{variant:?} must yield the same byte-\
13447                 tail RestartPolicy::as_str().as_bytes() returns — the \
13448                 borrowed-input surface must resolve to the same as_str \
13449                 dispatch"
13450            );
13451        }
13452        // `blake3::Hasher::update`-shape byte-input surface witness on
13453        // the caixa-lacre compounding target: the `MockHasher` (lifted
13454        // above per `clippy::items_after_statements`) mirrors
13455        // `blake3::Hasher::update` / `ring::digest::Context::update` /
13456        // `sha2::Sha256::update`'s `impl AsRef<[u8]>`-bound update
13457        // signature and accepts a [`super::RestartPolicy`] directly,
13458        // routing its byte-tail through the substrate-primitive
13459        // `as_str` accessor — the shape a future per-child BLAKE3
13460        // content-address closure composes to fold a `:restart`
13461        // discriminator byte-tag into the [`crate::Lacre`] closure
13462        // body.
13463        for &variant in RestartPolicy::ALL {
13464            let mut owned_hasher = MockHasher::new();
13465            owned_hasher.update(variant);
13466            let owned_folded = owned_hasher.finalize();
13467            assert_eq!(
13468                owned_folded,
13469                variant.as_str().as_bytes(),
13470                "`hasher.update(restart)`-shape composition on \
13471                 RestartPolicy::{variant:?} must fold the same byte-\
13472                 tail RestartPolicy::as_str().as_bytes() returns — the \
13473                 shape a future per-child BLAKE3 content-address \
13474                 closure composes to fold a `:restart` discriminator \
13475                 byte-tag into the Lacre closure body"
13476            );
13477            let mut borrowed_hasher = MockHasher::new();
13478            borrowed_hasher.update(&variant);
13479            let borrowed_folded = borrowed_hasher.finalize();
13480            assert_eq!(
13481                borrowed_folded,
13482                variant.as_str().as_bytes(),
13483                "`hasher.update(&restart)`-shape composition on \
13484                 &RestartPolicy::{variant:?} must fold the same byte-\
13485                 tail RestartPolicy::as_str().as_bytes() returns — the \
13486                 borrowed-input surface must resolve to the same as_str \
13487                 dispatch"
13488            );
13489        }
13490    }
13491
13492    #[test]
13493    #[expect(
13494        clippy::too_many_lines,
13495        reason = "the byte-owned reverse-projection axis is closed \
13496                  here across the M2-OTP-shape :supervisor slot pair by \
13497                  extending onto the second and final M2-OTP-shape \
13498                  closed-set fieldless typed-enum peer, so the pin \
13499                  binds the new impl against every paired byte-view \
13500                  and str-owned axis on the same enum plus a generic \
13501                  <T: Into<Vec<u8>>>-bound consumer witness and a \
13502                  std::io::Write::write_all-shape owned-byte-sink \
13503                  surface witness on both owned and borrowed input \
13504                  shapes to lock the whole family against a future \
13505                  silent regression"
13506    )]
13507    fn restart_policy_from_into_owned_vec_bytes_routes_through_as_str_accessor() {
13508        // `<T: Into<Vec<u8>>>`-bound-consumer witness helper: a generic
13509        // owned-byte-input function accepts a [`super::RestartPolicy`]
13510        // directly through the trait bound, without the caller open-
13511        // coding the three-hop `restart.as_str().as_bytes().to_vec()`
13512        // composition. Lifted to the top of the function per
13513        // `clippy::items_after_statements`.
13514        fn generic_owned_bytes_sink<T: Into<Vec<u8>>>(t: T) -> Vec<u8> {
13515            t.into()
13516        }
13517        // `std::io::Write::write_all`-shape owned-byte-sink surface
13518        // mock: mirrors `std::io::Write::write_all` /
13519        // `bytes::BytesMut::extend_from_slice` / any per-arm audit-log
13520        // byte-sink that consumes a `Vec<u8>` payload via
13521        // `Into<Vec<u8>>`, so a future per-child per-`:restart` audit-
13522        // log emit reaches the substrate-primitive `as_str` accessor
13523        // through the byte-owned reverse-projection axis and no
13524        // other. Lifted to the top of the function per
13525        // `clippy::items_after_statements`.
13526        struct MockOwnedByteSink(Vec<u8>);
13527        impl MockOwnedByteSink {
13528            fn new() -> Self {
13529                Self(Vec::new())
13530            }
13531            fn write_all(&mut self, bytes: impl Into<Vec<u8>>) -> &mut Self {
13532                self.0.extend(bytes.into());
13533                self
13534            }
13535            fn finalize(self) -> Vec<u8> {
13536                self.0
13537            }
13538        }
13539
13540        // Fail-before-pass-after byte-parity pin on the newly lifted
13541        // `impl From<RestartPolicy> for Vec<u8>` and
13542        // `impl From<&RestartPolicy> for Vec<u8>` — asserts the trait-
13543        // idiomatic byte-owned reverse-projection standard-library
13544        // impls and the substrate-primitive
13545        // [`super::RestartPolicy::as_str`] `pub const fn` accessor's
13546        // `.as_bytes().to_vec()` byte-tail resolve to the same three-
13547        // arm PascalCase wire byte-string emit-set across every arm
13548        // the exhaustive [`super::RestartPolicy::ALL`] slice
13549        // enumerates. Closes the substrate-wide trait-idiomatic byte-
13550        // owned reverse-projection axis on the M2-OTP-shape closed-
13551        // set typed-enum pair the sibling first-mover
13552        // [`super::RestartStrategy`] `From<{Self, &Self}> for Vec<u8>`
13553        // lift (63e5dd0) opened one commit prior, matching the
13554        // trajectory the paired [`AsRef<[u8]>`] borrowed byte-view
13555        // axis campaign already tracked across the same slot pair
13556        // (cd4c4e0 → 98b08fa).
13557        for &variant in RestartPolicy::ALL {
13558            let via_owned_from: Vec<u8> = <Vec<u8> as From<RestartPolicy>>::from(variant);
13559            let via_borrowed_from: Vec<u8> = <Vec<u8> as From<&RestartPolicy>>::from(&variant);
13560            let via_method_bytes: Vec<u8> = variant.as_str().as_bytes().to_vec();
13561            assert_eq!(
13562                via_owned_from, via_method_bytes,
13563                "From<RestartPolicy> for Vec<u8> impl must byte-equal \
13564                 RestartPolicy::as_str().as_bytes().to_vec() on \
13565                 RestartPolicy::{variant:?} — divergence signals a \
13566                 silent detour off the substrate-primitive accessor"
13567            );
13568            assert_eq!(
13569                via_borrowed_from, via_method_bytes,
13570                "From<&RestartPolicy> for Vec<u8> impl must byte-\
13571                 equal RestartPolicy::as_str().as_bytes().to_vec() \
13572                 on RestartPolicy::{variant:?} — divergence signals \
13573                 a silent detour off the substrate-primitive accessor"
13574            );
13575            assert_eq!(
13576                via_owned_from, via_borrowed_from,
13577                "From<RestartPolicy> for Vec<u8> and \
13578                 From<&RestartPolicy> for Vec<u8> must byte-equal \
13579                 each other on RestartPolicy::{variant:?} — \
13580                 divergence signals the owned-input and borrowed-input \
13581                 paths have drifted off the same substrate-primitive \
13582                 as_str accessor"
13583            );
13584            // Cross-axis witness against the paired [`AsRef<[u8]>`]
13585            // borrowed byte-view axis (98b08fa): the byte-owned
13586            // reverse-projection axis must byte-equal the paired
13587            // borrowed byte-view axis by construction — locking the
13588            // byte-view and byte-owned axes together at the substrate-
13589            // primitive accessor.
13590            let borrowed_bytes: &[u8] = <RestartPolicy as AsRef<[u8]>>::as_ref(&variant);
13591            assert_eq!(
13592                via_owned_from,
13593                borrowed_bytes.to_vec(),
13594                "From<RestartPolicy> for Vec<u8> and AsRef<[u8]> for \
13595                 RestartPolicy must resolve to byte-equal byte-tails \
13596                 on RestartPolicy::{variant:?} — divergence signals \
13597                 the byte-owned and byte-view axes have drifted off \
13598                 the same substrate-primitive as_str accessor"
13599            );
13600            // Cross-axis witness against the str-owned reverse-
13601            // projection family's `.into_bytes()` / `.as_bytes().to_vec()`
13602            // byte-tails: every one of `{String, Cow<'static, str>,
13603            // Box<str>, std::sync::Arc<str>}` allocates (or borrows)
13604            // the same PascalCase wire byte-string the substrate-
13605            // primitive accessor emits, so the byte-owned axis must
13606            // byte-equal each of their owned byte-tails by
13607            // construction.
13608            let owned_string: String = <String as From<RestartPolicy>>::from(variant);
13609            assert_eq!(
13610                via_owned_from,
13611                owned_string.into_bytes(),
13612                "From<RestartPolicy> for Vec<u8> and \
13613                 String::from(policy).into_bytes() must resolve to \
13614                 byte-equal byte-tails on RestartPolicy::{variant:?}"
13615            );
13616            let owned_cow: std::borrow::Cow<'static, str> =
13617                <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
13618            assert_eq!(
13619                via_owned_from,
13620                owned_cow.as_bytes().to_vec(),
13621                "From<RestartPolicy> for Vec<u8> and \
13622                 From<RestartPolicy> for Cow<'static, str> must \
13623                 resolve to byte-equal byte-tails on \
13624                 RestartPolicy::{variant:?}"
13625            );
13626            let owned_box: Box<str> = <Box<str> as From<RestartPolicy>>::from(variant);
13627            assert_eq!(
13628                via_owned_from,
13629                owned_box.as_bytes().to_vec(),
13630                "From<RestartPolicy> for Vec<u8> and \
13631                 From<RestartPolicy> for Box<str> must resolve to \
13632                 byte-equal byte-tails on RestartPolicy::{variant:?}"
13633            );
13634            let owned_arc: std::sync::Arc<str> =
13635                <std::sync::Arc<str> as From<RestartPolicy>>::from(variant);
13636            assert_eq!(
13637                via_owned_from,
13638                owned_arc.as_bytes().to_vec(),
13639                "From<RestartPolicy> for Vec<u8> and \
13640                 From<RestartPolicy> for std::sync::Arc<str> must \
13641                 resolve to byte-equal byte-tails on \
13642                 RestartPolicy::{variant:?}"
13643            );
13644        }
13645        // `<T: Into<Vec<u8>>>`-bound-consumer witness on both owned
13646        // and borrowed input shapes: the generic owned-byte-input
13647        // function `generic_owned_bytes_sink` (lifted above per
13648        // `clippy::items_after_statements`) accepts a
13649        // [`super::RestartPolicy`] and a `&RestartPolicy` directly
13650        // through the trait bound, without the caller open-coding
13651        // the three-hop `restart.as_str().as_bytes().to_vec()`
13652        // composition.
13653        for &variant in RestartPolicy::ALL {
13654            let via_generic_owned = generic_owned_bytes_sink(variant);
13655            // Bind the borrowed-input path through an explicit
13656            // `&RestartPolicy` local so the generic-consumer witness
13657            // routes through `From<&RestartPolicy> for Vec<u8>` (T
13658            // binds to `&RestartPolicy`) rather than clippy-collapsing
13659            // the borrow onto the owned-input peer.
13660            let variant_ref: &RestartPolicy = &variant;
13661            let via_generic_borrowed = generic_owned_bytes_sink(variant_ref);
13662            let via_method_bytes = variant.as_str().as_bytes().to_vec();
13663            assert_eq!(
13664                via_generic_owned, via_method_bytes,
13665                "generic `<T: Into<Vec<u8>>>`-bound consumer on \
13666                 RestartPolicy::{variant:?} must yield the same byte-\
13667                 tail RestartPolicy::as_str().as_bytes() returns — \
13668                 divergence signals the byte-owned axis fails to bridge \
13669                 a generic owned-byte-input trait bound to the \
13670                 substrate-primitive accessor"
13671            );
13672            assert_eq!(
13673                via_generic_borrowed, via_method_bytes,
13674                "generic `<T: Into<Vec<u8>>>`-bound consumer on \
13675                 &RestartPolicy::{variant:?} must yield the same byte-\
13676                 tail RestartPolicy::as_str().as_bytes() returns — \
13677                 the borrowed-input surface must resolve to the same \
13678                 as_str dispatch"
13679            );
13680        }
13681        // `std::io::Write::write_all`-shape owned-byte-sink surface
13682        // witness: the `MockOwnedByteSink` (lifted above per
13683        // `clippy::items_after_statements`) mirrors
13684        // `std::io::Write::write_all` /
13685        // `bytes::BytesMut::extend_from_slice`'s `impl Into<Vec<u8>>`-
13686        // bound owned-byte input signature and accepts a
13687        // [`super::RestartPolicy`] directly on both owned and
13688        // borrowed input shapes, routing its byte-tail through the
13689        // substrate-primitive `as_str` accessor — the shape a future
13690        // per-child per-`:restart` audit-log emit composes to fold a
13691        // `:restart` discriminator byte-tag into a downstream owned-
13692        // byte-sink surface.
13693        for &variant in RestartPolicy::ALL {
13694            let mut owned_sink = MockOwnedByteSink::new();
13695            owned_sink.write_all(variant);
13696            let owned_folded = owned_sink.finalize();
13697            assert_eq!(
13698                owned_folded,
13699                variant.as_str().as_bytes(),
13700                "`sink.write_all(restart)`-shape composition on \
13701                 RestartPolicy::{variant:?} must fold the same byte-\
13702                 tail RestartPolicy::as_str().as_bytes() returns"
13703            );
13704            let mut borrowed_sink = MockOwnedByteSink::new();
13705            let variant_ref: &RestartPolicy = &variant;
13706            borrowed_sink.write_all(variant_ref);
13707            let borrowed_folded = borrowed_sink.finalize();
13708            assert_eq!(
13709                borrowed_folded,
13710                variant.as_str().as_bytes(),
13711                "`sink.write_all(&restart)`-shape composition on \
13712                 &RestartPolicy::{variant:?} must fold the same byte-\
13713                 tail RestartPolicy::as_str().as_bytes() returns — \
13714                 the borrowed-input surface must resolve to the same \
13715                 as_str dispatch"
13716            );
13717        }
13718    }
13719
13720    #[test]
13721    fn restart_policy_all_enumerates_every_variant_exactly_once() {
13722        // Fail-before-pass-after pin on the [`RestartPolicy::ALL`]
13723        // exhaustive-iteration surface: every variant appears exactly
13724        // once, and the slice length matches the arm count of the
13725        // closed set. Every consumer that walks the accepted-policy
13726        // set (a future `feira supervisor --restart …` CLI-side
13727        // arg-parse's "did you mean" hint, a future M4 admission-
13728        // webhook's per-child rejection body naming the accepted-
13729        // `:restart` list, the [`RestartPolicy::from_wire`] reverse-
13730        // projection consumers that iterate the accept-set for
13731        // diagnostic rendering) reads through this slice, so a future
13732        // arm addition that grows the enum but forgets to grow
13733        // [`Self::ALL`] silently truncates every downstream consumer's
13734        // accept-set at the same pre-addition boundary — this pin
13735        // fails at caixa-core build time on the pairwise-distinct +
13736        // arm-count invariants.
13737        //
13738        // Peer of the sibling [`RestartStrategy::ALL`] (4eec29c) /
13739        // [`crate::CaixaKind::ALL`] (6b1f4fb) /
13740        // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
13741        // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
13742        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
13743        // pins on the peer closed-set typed-enum axes.
13744        let all: &[RestartPolicy] = RestartPolicy::ALL;
13745        assert_eq!(
13746            all.len(),
13747            3,
13748            "RestartPolicy::ALL must enumerate every variant of the \
13749             three-arm closed set (Permanent, Temporary, Transient); \
13750             got {all:?}"
13751        );
13752        for (i, a) in all.iter().enumerate() {
13753            for (j, b) in all.iter().enumerate() {
13754                if i != j {
13755                    assert_ne!(
13756                        a, b,
13757                        "RestartPolicy::ALL must carry every variant exactly \
13758                         once — got duplicate {a:?} at indices {i} and {j}"
13759                    );
13760                }
13761            }
13762        }
13763        for variant in [
13764            RestartPolicy::Permanent,
13765            RestartPolicy::Temporary,
13766            RestartPolicy::Transient,
13767        ] {
13768            assert!(
13769                all.contains(&variant),
13770                "RestartPolicy::ALL must contain {variant:?} — a future arm \
13771                 addition that grows the enum but forgets to grow the ALL slice \
13772                 silently truncates every downstream consumer's accept-set at \
13773                 the pre-addition boundary"
13774            );
13775        }
13776    }
13777
13778    #[test]
13779    fn restart_policy_wire_names_covers_every_arm() {
13780        // Load-bearing pin on the substrate-canonical
13781        // [`RestartPolicy::WIRE_NAMES`] exhaustive accept-set roster on
13782        // the `PascalCase` wire byte-string axis: every variant of the
13783        // sibling [`RestartPolicy::ALL`] exhaustive-iteration surface
13784        // must project through [`RestartPolicy::as_str`] onto an entry
13785        // the [`RestartPolicy::WIRE_NAMES`] roster carries, and the
13786        // roster's length must byte-equal `RestartPolicy::ALL.len()` so
13787        // a silent skew between the [`RestartPolicy::as_str`] match's
13788        // arm-set and the roster's arm-set trips here at caixa-core
13789        // test time rather than at a downstream M4
13790        // `mesh.pleme.io/v1alpha1/Supervisor` CR admission-webhook
13791        // rejection body's wire-form `:restart` accepted-set
13792        // enumeration miss / a `feira supervisor --restart …` "did you
13793        // mean" hint drift / a future wasm-operator per-reconcile-step
13794        // diagnostic log line's accepted-wire-form enumeration miss.
13795        // A future arm addition (an OTP-`intrinsic` fourth arm the
13796        // theory
13797        // [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
13798        // might reach for once the three canonical OTP restart policies
13799        // stop covering the substrate's discovered load-shape) extends
13800        // [`RestartPolicy::ALL`] as a single edit and this pin sweeps
13801        // the new arm by iteration; the paired
13802        // [`RestartPolicy::WIRE_NAMES`] roster must grow in lockstep or
13803        // this assertion trips. Every entry is further pinned to open
13804        // with an ASCII uppercase byte so a silent collapse of the
13805        // wire-form axis with the peer kebab-case dispatcher-catalog
13806        // axis (an entry byte-identical to a sibling
13807        // [`RestartPolicy::discriminant`] kebab byte-string that would
13808        // let a wire-axis consumer accept the dispatcher-catalog
13809        // vocabulary) trips here rather than at a downstream K8s-CR
13810        // round-trip miss.
13811        //
13812        // Peer of the sibling
13813        // [`restart_strategy_wire_names_covers_every_arm`] (3033f45)
13814        // pin on the first M2 OTP-shape sibling-restart closed-set
13815        // typed enum, the sibling
13816        // [`crate::aplicacao::tests::placement_strategy_wire_names_covers_every_arm`]
13817        // (3e5b194) pin on the first M3 mesh-shape distribution-strategy
13818        // closed-set typed enum, the sibling
13819        // [`crate::kind::tests::caixa_kind_wire_names_covers_every_arm`]
13820        // (bd708bd) pin on the top-level typed-kind discriminator's
13821        // `PascalCase` wire byte-string axis, and the sibling
13822        // [`crate::upgrade::tests::upgrade_instruction_wire_forms_covers_every_arm`]
13823        // (cc42c0e) /
13824        // [`crate::upgrade::tests::upgrade_instruction_lisp_forms_covers_every_arm`]
13825        // (1898d77) pins on the OTP-appup discriminator's two-axis
13826        // roster split — the same closed-set exhaustive-roster coverage
13827        // discipline extended here onto the second and final M2
13828        // OTP-shape sibling-enum on the caixa surface, closing the
13829        // per-child restart-decision-policy axis paired with the peer
13830        // per-supervisor sibling-restart-strategy axis on the same M2
13831        // `:supervisor` slot.
13832        //
13833        // Fail-before-pass-after locally verified by mutating one arm
13834        // of the paired [`crate::render::SUPERVISOR_CHILD_RESTART_*`]
13835        // const family (e.g. dropping the trailing `t` from
13836        // `"Permanent"` → `"Permanen"`) — the length pin still passes
13837        // but the `contains` check fires on the mutated arm; and by
13838        // shortening the roster to two entries — the length pin fires
13839        // first.
13840        assert_eq!(
13841            RestartPolicy::WIRE_NAMES.len(),
13842            RestartPolicy::ALL.len(),
13843            "RestartPolicy::WIRE_NAMES.len() must byte-equal \
13844             RestartPolicy::ALL.len() — a mismatch means the roster \
13845             and the enum's arm-set have drifted; downstream consumers \
13846             that fan through both will silently disagree on the \
13847             accepted arm-set"
13848        );
13849        for &variant in RestartPolicy::ALL {
13850            let wire = variant.as_str();
13851            assert!(
13852                RestartPolicy::WIRE_NAMES.contains(&wire),
13853                "RestartPolicy::{variant:?}.as_str() = {wire:?} must \
13854                 be a member of RestartPolicy::WIRE_NAMES — the \
13855                 emitter and the roster have drifted out of lockstep"
13856            );
13857        }
13858        for tag in RestartPolicy::WIRE_NAMES {
13859            let first = tag.chars().next().unwrap_or_else(|| {
13860                panic!(
13861                    "RestartPolicy::WIRE_NAMES entry {tag:?} must be \
13862                     a non-empty PascalCase byte-string"
13863                )
13864            });
13865            assert!(
13866                first.is_ascii_uppercase(),
13867                "RestartPolicy::WIRE_NAMES entry {tag:?} must open \
13868                 with an ASCII uppercase byte (PascalCase wire form) — \
13869                 a lowercase entry would collide the wire-form axis \
13870                 with the peer kebab-case dispatcher-catalog axis \
13871                 [`RestartPolicy::discriminant`] serves"
13872            );
13873        }
13874    }
13875
13876    #[test]
13877    fn restart_policy_from_wire_accepts_every_lifted_constant() {
13878        // Fail-before-pass-after pin on the forward accept-set of the
13879        // [`RestartPolicy::from_wire`] reverse projection: every
13880        // canonical [`crate::render::SUPERVISOR_CHILD_RESTART_*`]
13881        // constant the [`RestartPolicy::as_str`] emitter walks parses
13882        // back to its paired variant. Any future arm addition that
13883        // grows the emitter's `as_str` match but forgets to grow the
13884        // parser's `from_wire` match silently splits the two halves of
13885        // the round-trip — the wire byte-string one non-serde consumer
13886        // parses from the one the emitter wrote — with the failure
13887        // surfacing at the operator's reconcile posture (a `:temporary`
13888        // `oneShot` child restarted on clean exit, a `:transient` child
13889        // restarted after clean completion) far from the rebrand
13890        // commit. Pinning the three-arm accept-set here catches the
13891        // drift at caixa-core build time.
13892        //
13893        // Peer of the sibling [`RestartStrategy::from_wire`] (4eec29c)
13894        // + [`crate::CaixaKind::from_wire`] (2aa6d23)
13895        // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
13896        // accept-set pins on the peer closed-set typed-enum `str → Self`
13897        // axes.
13898        for (wire, expected) in [
13899            (
13900                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
13901                RestartPolicy::Permanent,
13902            ),
13903            (
13904                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
13905                RestartPolicy::Temporary,
13906            ),
13907            (
13908                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
13909                RestartPolicy::Transient,
13910            ),
13911        ] {
13912            let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
13913                panic!(
13914                    "RestartPolicy::from_wire({wire:?}) must accept every \
13915                     SUPERVISOR_CHILD_RESTART_* constant — got None for the \
13916                     lifted canonical byte-string that RestartPolicy::{expected:?} \
13917                     serializes as under SUPERVISOR_CHILD_KEY_RESTART"
13918                )
13919            });
13920            assert_eq!(
13921                parsed, expected,
13922                "RestartPolicy::from_wire({wire:?}) must return \
13923                 RestartPolicy::{expected:?}; got RestartPolicy::{parsed:?}"
13924            );
13925        }
13926    }
13927
13928    #[test]
13929    fn restart_policy_from_wire_round_trips_through_as_str() {
13930        // Fail-before-pass-after pin on the closed round-trip between
13931        // the forward [`RestartPolicy::as_str`] emitter and the
13932        // reverse [`RestartPolicy::from_wire`] parser: for every
13933        // variant in [`RestartPolicy::ALL`], parsing the emitter's
13934        // output must return exactly the same variant. Any per-arm
13935        // divergence — a future arm added to `as_str` but not
13936        // `from_wire`, an accidental copy-paste flip in one but not
13937        // the other — silently splits the emit and parse halves and
13938        // the failure surfaces at consumer parse time far from the
13939        // drift site. The `ALL`-iterating shape means a future arm
13940        // addition picks up the coverage by construction.
13941        //
13942        // Peer of the sibling
13943        // [`restart_strategy_from_wire_round_trips_through_as_str`]
13944        // (4eec29c) round-trip pin on
13945        // [`RestartStrategy::from_wire`] and the M3
13946        // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
13947        // (18c7342) round-trip pin on
13948        // [`crate::aplicacao::PlacementStrategy::from_wire`].
13949        for &variant in RestartPolicy::ALL {
13950            let wire = variant.as_str();
13951            let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
13952                panic!(
13953                    "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
13954                     must be Some({variant:?}) — the two halves of the round-trip \
13955                     dispatch on the same lifted SUPERVISOR_CHILD_RESTART_* consts; \
13956                     got None on wire byte-string {wire:?}"
13957                )
13958            });
13959            assert_eq!(
13960                parsed, variant,
13961                "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
13962                 must round-trip to the same variant; got {parsed:?}"
13963            );
13964        }
13965    }
13966
13967    #[test]
13968    fn restart_policy_from_wire_rejects_unknown_byte_strings() {
13969        // Fail-before-pass-after pin on the closed-set refusal
13970        // discipline of [`RestartPolicy::from_wire`]: every
13971        // byte-string outside the three-arm accept-set returns `None`
13972        // rather than silently collapsing onto the [`Default`]
13973        // (`Permanent`) arm or an arbitrary neighbor. The refusal set
13974        // exercised here sweeps the load-bearing drift shapes: the
13975        // empty string (a stripped serde-attribute drift), all-
13976        // whitespace strings (the canonical text-editor accidental
13977        // padding shape), the kebab-case dispatcher-catalog identities
13978        // (`"permanent"` / `"temporary"` / `"transient"` — the
13979        // [`gen_platform::FromStrKind`]-derived [`std::str::FromStr`]
13980        // accept-set, which parses the *other* axis of this enum's
13981        // two-axis split and must not leak into the `from_wire`
13982        // PascalCase-wire accept-set — a lowercase leak here would
13983        // silently accept the operator's kebab-case
13984        // dispatcher-catalog probe under the wire-axis parser and mis-
13985        // route a `:permanent` intent), the padded canonical scalar
13986        // (`" Permanent "`), the trailing-newline shapes
13987        // (`"Permanent\n"`), the uppercase-single-word forms
13988        // (`"PERMANENT"`), and neighboring-but-unknown arms
13989        // (`"Restart"` — the canonical typo direction toward the
13990        // sibling [`RestartStrategy`] enum's own wire-arm namespace).
13991        //
13992        // Peer of the sibling
13993        // [`restart_strategy_from_wire_rejects_unknown_byte_strings`]
13994        // (4eec29c) +
13995        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
13996        // (2aa6d23) +
13997        // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
13998        // (18c7342) refusal pins on the peer closed-set typed-enum
13999        // axes.
14000        for bad in [
14001            "",
14002            " ",
14003            "\n",
14004            "\t",
14005            "permanent",
14006            "temporary",
14007            "transient",
14008            "PERMANENT",
14009            "TEMPORARY",
14010            "TRANSIENT",
14011            "Permanents",
14012            "Permanent ",
14013            " Permanent",
14014            " Transient ",
14015            "Permanent\n",
14016            "perma",
14017            "Trans",
14018            "OneForOne",
14019            "Restart",
14020            "?",
14021        ] {
14022            assert!(
14023                RestartPolicy::from_wire(bad).is_none(),
14024                "RestartPolicy::from_wire({bad:?}) must return None — the \
14025                 parser's accept-set is exactly the three RestartPolicy::as_str \
14026                 outputs (Permanent, Temporary, Transient), and this \
14027                 byte-string is outside that closed set"
14028            );
14029        }
14030    }
14031
14032    #[test]
14033    fn restart_policy_from_wire_matches_serialize_derive_wire_byte_string() {
14034        // Fail-before-pass-after pin on the fourth path of the four-path
14035        // convergence: `from_wire` (the reverse projection) inverts the
14036        // `Serialize` derive's wire byte-string on every variant.
14037        // Together with the pre-existing three-path convergence
14038        // (`Display` + `as_str` + `Serialize` all resolve to the same
14039        // lifted [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const,
14040        // pinned by
14041        // [`restart_policy_display_matches_serialized_wire_byte_string`])
14042        // this closes the round-trip: the wire byte-string the
14043        // `Serialize` derive emits parses back to the same variant
14044        // through `from_wire`, so any future serde-attribute or variant-
14045        // rename drift on the emit half now surfaces as a matched drift
14046        // on the parse half at caixa-core build time — the two halves
14047        // migrate as a unit through the lifted consts on any future
14048        // rename, and the round-trip cannot silently split.
14049        //
14050        // Peer of the sibling
14051        // [`restart_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
14052        // (4eec29c) wire-format pin on
14053        // [`RestartStrategy::from_wire`] and the M3
14054        // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
14055        // (18c7342) wire-format pin on
14056        // [`crate::aplicacao::PlacementStrategy::from_wire`].
14057        for &variant in RestartPolicy::ALL {
14058            let wire = serde_json::to_string(&variant).unwrap();
14059            let unquoted = wire
14060                .strip_prefix('"')
14061                .and_then(|s| s.strip_suffix('"'))
14062                .expect("serialized RestartPolicy is a JSON string");
14063            let parsed = RestartPolicy::from_wire(unquoted).unwrap_or_else(|| {
14064                panic!(
14065                    "RestartPolicy::from_wire({unquoted:?}) must accept the \
14066                     Serialize derive's wire byte-string for \
14067                     RestartPolicy::{variant:?} — the four-path convergence \
14068                     (Display + as_str + Serialize + from_wire) resolves through \
14069                     the same lifted SUPERVISOR_CHILD_RESTART_* const; got None"
14070                )
14071            });
14072            assert_eq!(
14073                parsed, variant,
14074                "RestartPolicy::from_wire of the Serialize derive's wire \
14075                 byte-string for RestartPolicy::{variant:?} must round-trip \
14076                 to the same variant; got {parsed:?}"
14077            );
14078        }
14079    }
14080
14081    // ── drift-detection: ChildSpec::nome accessor pins ────────────────────
14082    //
14083    // The M2 supervisor-tree sibling of the M3 `Membro::nome` (4a32abf) pin
14084    // pair (`membro_nome_returns_caixa_byte_equal_across_permutations` +
14085    // `membro_nome_borrows_from_caixa_storage`) — extended here to the M2
14086    // per-`:children` child-caixa `:nome` axis, sibling to the first M2
14087    // slot scalar accessor `UpgradeFromEntry::prior_versao` (75d27a8) on
14088    // the peer per-`:upgrade-from :from` axis. The three pins jointly
14089    // brace the accessor against every future silent detour that would
14090    // desynchronize it from the raw `.caixa` field access every consumer
14091    // previously open-coded.
14092
14093    #[test]
14094    fn child_spec_nome_returns_caixa_byte_equal_across_permutations() {
14095        // The canonical per-`:children` child-caixa `:nome`-scalar pin:
14096        // [`ChildSpec::nome`] must return the `:children :caixa` field
14097        // byte-for-byte across every DNS-1123-label value the upstream
14098        // [`crate::render::require_valid_dns_1123_label`] gate at
14099        // `SupervisorSpec::validate` admits. Peer of the sibling
14100        // `membro_nome_returns_caixa_byte_equal_across_permutations`
14101        // (4a32abf) pin on the M3 per-`:membros` axis — same "the
14102        // substrate-primitive accessor must byte-equal the raw field
14103        // access verbatim across every author-declared value" discipline
14104        // extended to the M2 supervisor-tree per-`:children` arm. Pins
14105        // against a future silent detour that re-normalized the child
14106        // identity (an accidental `.to_lowercase()` — every `:children
14107        // :caixa` is validated as a DNS-1123 label upstream, so any
14108        // re-normalization is redundant + a drift surface between the
14109        // validator and the accessor), a namespace-prefix rewrite (an
14110        // accidental `format!("{namespace}/{caixa}")` per-CR
14111        // fully-qualified rewrite that didn't land on the peer axes), or
14112        // a per-cluster alias stamp the future wasm-operator's
14113        // hierarchical reconciliation scheduler authors on one consumer
14114        // without the others. Five values sweep the accept-set the
14115        // DNS-1123 gate upstream admits (short single-word / dashed /
14116        // v-suffixed / mixed-digit child names).
14117        for name in [
14118            "worker",
14119            "cache-server",
14120            "scratch-job",
14121            "orders-v2",
14122            "session-8080",
14123        ] {
14124            let c = ChildSpec {
14125                caixa: name.into(),
14126                versao: "^0.1".into(),
14127                restart: RestartPolicy::Permanent,
14128            };
14129            assert_eq!(
14130                c.nome(),
14131                name,
14132                "ChildSpec::nome must return :children :caixa verbatim \
14133                 (got {:?}, expected {name:?})",
14134                c.nome(),
14135            );
14136            assert_eq!(
14137                c.nome(),
14138                c.caixa.as_str(),
14139                "ChildSpec::nome must byte-equal the .caixa field access",
14140            );
14141        }
14142    }
14143
14144    #[test]
14145    fn child_spec_nome_borrows_from_caixa_storage() {
14146        // The borrow-not-copy pin: [`ChildSpec::nome`] must return a
14147        // `&str` slice that borrows from the typed slot's own [`String`]
14148        // storage — same-address invariant with `c.caixa.as_str()`. Pins
14149        // against a future silent detour that allocated a fresh `String`
14150        // (`self.caixa.clone()` in the body would type-check but silently
14151        // drop the borrow, and every downstream consumer that assumed
14152        // the returned slice outlives `&self` would break on a stale-
14153        // reference use-after-free — the [`crate::render::insert_first_seen`]
14154        // dedup key at [`SupervisorSpec::validate`], the
14155        // [`validate_no_self_supervision`] equality check against the
14156        // parent's `:nome` string slice, the DNS-1123 gate's `&str`
14157        // borrow — each would silently misbehave if this accessor
14158        // produced a detached copy). Peer of the sibling
14159        // `membro_nome_borrows_from_caixa_storage` (4a32abf) pin on the
14160        // M3 per-`:membros` axis and the
14161        // `prior_versao_borrows_from_from_storage` (75d27a8) pin on the
14162        // first M2 slot scalar accessor.
14163        let c = ChildSpec {
14164            caixa: "worker".into(),
14165            versao: "^0.1".into(),
14166            restart: RestartPolicy::Permanent,
14167        };
14168        let name = c.nome();
14169        let caixa_slice = c.caixa.as_str();
14170        assert_eq!(
14171            name.as_ptr(),
14172            caixa_slice.as_ptr(),
14173            "ChildSpec::nome must borrow from the .caixa String's backing \
14174             storage — a fresh allocation here means the accessor no \
14175             longer names the substrate-primitive typed dispatch and \
14176             every downstream consumer would silently carry a detached \
14177             copy",
14178        );
14179        assert_eq!(
14180            name.len(),
14181            caixa_slice.len(),
14182            "ChildSpec::nome and .caixa.as_str() must byte-equal in length \
14183             as well as in address",
14184        );
14185    }
14186
14187    #[test]
14188    fn validate_gates_child_nome_through_lifted_accessor() {
14189        // Bilateral coherence pin: every `:children :caixa` that
14190        // [`SupervisorSpec::validate`] accepts is one
14191        // [`crate::render::require_valid_dns_1123_label`] accepts on the
14192        // accessor-projected value, and vice versa on the reject side.
14193        // This closes the "the validator reads through the accessor"
14194        // contract structurally — a future silent detour that made the
14195        // accessor return a different byte-string than the validator
14196        // gates against would surface here as a coverage mismatch, not
14197        // as an apply-time DNS-1123 rejection at
14198        // `metadata.name: Invalid value` far from the caixa.lisp source.
14199        // Peer of the M2 sibling
14200        // `validate_parses_prior_versao_through_lifted_accessor`
14201        // (75d27a8) on the per-`:upgrade-from :from` axis and the M3
14202        // `validate_membros` peer discipline.
14203        //
14204        // Accept-set sweep: five DNS-1123-label values the upstream gate
14205        // admits.
14206        for ok_name in ["a", "worker", "cache-server", "orders-v2", "svc-8080"] {
14207            let s = SupervisorSpec {
14208                children: vec![ChildSpec {
14209                    caixa: ok_name.into(),
14210                    versao: "^0.1".into(),
14211                    restart: RestartPolicy::Permanent,
14212                }],
14213                ..SupervisorSpec::default()
14214            };
14215            s.validate().unwrap_or_else(|e| {
14216                panic!(
14217                    "SupervisorSpec::validate must accept :children :caixa {ok_name:?} \
14218                     (upstream DNS-1123 gate accepts it): got {e:?}",
14219                );
14220            });
14221            let c = ChildSpec {
14222                caixa: ok_name.into(),
14223                versao: "^0.1".into(),
14224                restart: RestartPolicy::Permanent,
14225            };
14226            crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| ())
14227                .unwrap_or_else(|()| {
14228                    panic!(
14229                        "require_valid_dns_1123_label must accept the accessor-projected \
14230                     :children :caixa {ok_name:?}",
14231                    );
14232                });
14233        }
14234        // Reject-set sweep: five DNS-1123-label-violating shapes the
14235        // upstream gate refuses (empty / uppercase / underscore / dot /
14236        // leading-hyphen). Every rejection at the validator must
14237        // correspond to a rejection when the accessor's projected value
14238        // is fed back through the shared gate.
14239        for bad_name in ["", "Worker", "my_worker", "team.worker", "-worker"] {
14240            let s = SupervisorSpec {
14241                children: vec![ChildSpec {
14242                    caixa: bad_name.into(),
14243                    versao: "^0.1".into(),
14244                    restart: RestartPolicy::Permanent,
14245                }],
14246                ..SupervisorSpec::default()
14247            };
14248            let err = s.validate().unwrap_err();
14249            assert!(
14250                matches!(
14251                    err,
14252                    SupervisorError::EmptyChildName | SupervisorError::ChildCaixaInvalid { .. }
14253                ),
14254                "SupervisorSpec::validate must reject :children :caixa {bad_name:?} \
14255                 via the DNS-1123 gate: got {err:?}",
14256            );
14257            let c = ChildSpec {
14258                caixa: bad_name.into(),
14259                versao: "^0.1".into(),
14260                restart: RestartPolicy::Permanent,
14261            };
14262            assert!(
14263                crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| (),)
14264                    .is_err(),
14265                "require_valid_dns_1123_label must reject the accessor-projected \
14266                 :children :caixa {bad_name:?}",
14267            );
14268        }
14269    }
14270
14271    // ── drift-detection: ChildSpec::versao_requirement accessor pins ──────
14272    //
14273    // Sibling of the peer per-`:membros` `membro_versao_requirement_*`
14274    // (a40b0e3) pin pair on the M3 mesh-slot surface — extended here to the
14275    // M2 supervisor-tree per-`:children` child-`:versao` axis, sibling to
14276    // the just-landed [`ChildSpec::nome`] (57c61d0) child-`:nome` pin
14277    // trio on the peer per-`:children` `String`-carry axis. The three pins
14278    // jointly brace the accessor against every future silent detour that
14279    // would desynchronize it from the raw `.versao` field access the
14280    // requirement gate + error carrier previously open-coded.
14281    //
14282    // Closes the last unlifted per-`:children` `String`-carry axis: the
14283    // pair (`nome`, `versao_requirement`) now jointly projects the
14284    // (`.caixa`, `.versao`) field pair every OTP-shape supervisor-tree
14285    // consumer that fans on per-child identity + version pin reads,
14286    // matching the peer M3 (`Membro::nome`, `Membro::versao_requirement`)
14287    // pair discipline verbatim.
14288    #[test]
14289    fn child_spec_versao_requirement_returns_versao_byte_equal_across_permutations() {
14290        // The canonical per-`:children` child-`:versao`-scalar pin:
14291        // [`ChildSpec::versao_requirement`] must return the `:children
14292        // :versao` field byte-for-byte across every Cargo-shaped semver
14293        // requirement value the upstream
14294        // [`crate::render::require_valid_versao_requirement`] gate admits.
14295        // Peer of the sibling
14296        // `membro_versao_requirement_returns_versao_byte_equal_across_permutations`
14297        // (a40b0e3) pin on the M3 per-`:membros` axis — same "the
14298        // substrate-primitive accessor must byte-equal the raw field
14299        // access verbatim across every author-declared value" discipline
14300        // extended to the M2 supervisor-tree per-`:children` arm. Pins
14301        // against a future silent detour that re-canonicalized the
14302        // requirement (an accidental `.to_string()` via
14303        // [`crate::version::parse_requirement`] → [`std::fmt::Display`]
14304        // round-trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and
14305        // silently drifted the error carrier's quoted requirement away
14306        // from the source `caixa.lisp`, an accidental whitespace trim on
14307        // `"^ 0.1"` that no consumer ever produced from the field-access
14308        // side, an accidental per-cluster lacre-projected concrete-version
14309        // rewrite that didn't land on the peer requirement-gate call).
14310        // Five values sweep the accept-set the shared
14311        // [`crate::render::require_valid_versao_requirement`] gate admits
14312        // (caret / tilde / exact / wildcard / bare-major).
14313        for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
14314            let c = ChildSpec {
14315                caixa: "worker".into(),
14316                versao: req.into(),
14317                restart: RestartPolicy::Permanent,
14318            };
14319            assert_eq!(
14320                c.versao_requirement(),
14321                req,
14322                "ChildSpec::versao_requirement must return :children :versao \
14323                 verbatim (got {:?}, expected {req:?})",
14324                c.versao_requirement(),
14325            );
14326            assert_eq!(
14327                c.versao_requirement(),
14328                c.versao.as_str(),
14329                "ChildSpec::versao_requirement must byte-equal the .versao \
14330                 field access",
14331            );
14332        }
14333    }
14334
14335    #[test]
14336    fn child_spec_versao_requirement_borrows_from_versao_storage() {
14337        // The borrow-not-copy pin: [`ChildSpec::versao_requirement`] must
14338        // return a `&str` slice that borrows from the typed slot's own
14339        // [`String`] storage — same-address invariant with
14340        // `c.versao.as_str()`. Pins against a future silent detour that
14341        // allocated a fresh `String` (`self.versao.clone()` in the body
14342        // would type-check but silently drop the borrow, and every
14343        // downstream consumer that assumed the returned slice outlives
14344        // `&self` — the [`crate::render::require_valid_versao_requirement`]
14345        // gate's `&str` borrow, the [`SupervisorError::ChildVersaoInvalid`]
14346        // `.to_string()` carrier's byte-length assumption — would silently
14347        // misbehave if this accessor produced a detached copy). Peer of
14348        // the sibling `child_spec_nome_borrows_from_caixa_storage`
14349        // (57c61d0) pin on the per-`:children` `:nome` axis and the M3
14350        // `membro_versao_requirement_borrows_from_versao_storage` (a40b0e3)
14351        // pin on the peer per-`:membros` `:versao` axis.
14352        let c = ChildSpec {
14353            caixa: "worker".into(),
14354            versao: "^0.1".into(),
14355            restart: RestartPolicy::Permanent,
14356        };
14357        let req = c.versao_requirement();
14358        let versao_slice = c.versao.as_str();
14359        assert_eq!(
14360            req.as_ptr(),
14361            versao_slice.as_ptr(),
14362            "ChildSpec::versao_requirement must borrow from the .versao \
14363             String's backing storage — a fresh allocation here means the \
14364             accessor no longer names the substrate-primitive typed \
14365             dispatch and every downstream consumer would silently carry \
14366             a detached copy",
14367        );
14368        assert_eq!(
14369            req.len(),
14370            versao_slice.len(),
14371            "ChildSpec::versao_requirement and .versao.as_str() must \
14372             byte-equal in length as well as in address",
14373        );
14374    }
14375
14376    #[test]
14377    fn validate_gates_child_versao_through_lifted_accessor() {
14378        // Bilateral coherence pin: every `:children :versao` that
14379        // [`SupervisorSpec::validate`] accepts is one
14380        // [`crate::render::require_valid_versao_requirement`] accepts on
14381        // the accessor-projected value, and vice versa on the reject side.
14382        // This closes the "the validator reads through the accessor"
14383        // contract structurally — a future silent detour that made the
14384        // accessor return a different byte-string than the validator gates
14385        // against would surface here as a coverage mismatch, not as a
14386        // resolver-time semver-parse rejection at lacre-closure time far
14387        // from the caixa.lisp source. Peer of the sibling
14388        // `validate_gates_child_nome_through_lifted_accessor` (57c61d0) on
14389        // the per-`:children :caixa` axis and the M2
14390        // `validate_parses_prior_versao_through_lifted_accessor` (75d27a8)
14391        // on the peer per-`:upgrade-from :from` axis.
14392        //
14393        // Accept-set sweep: five Cargo-shaped semver requirement values
14394        // the upstream gate admits (caret / tilde / exact / wildcard /
14395        // bare-major).
14396        for ok_req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
14397            let s = SupervisorSpec {
14398                children: vec![ChildSpec {
14399                    caixa: "worker".into(),
14400                    versao: ok_req.into(),
14401                    restart: RestartPolicy::Permanent,
14402                }],
14403                ..SupervisorSpec::default()
14404            };
14405            s.validate().unwrap_or_else(|e| {
14406                panic!(
14407                    "SupervisorSpec::validate must accept :children :versao {ok_req:?} \
14408                     (upstream versao-requirement gate accepts it): got {e:?}",
14409                );
14410            });
14411            let c = ChildSpec {
14412                caixa: "worker".into(),
14413                versao: ok_req.into(),
14414                restart: RestartPolicy::Permanent,
14415            };
14416            crate::render::require_valid_versao_requirement(
14417                c.versao_requirement(),
14418                || (),
14419                |_reason| (),
14420            )
14421            .unwrap_or_else(|()| {
14422                panic!(
14423                    "require_valid_versao_requirement must accept the accessor-projected \
14424                     :children :versao {ok_req:?}",
14425                );
14426            });
14427        }
14428        // Reject-set sweep: five requirement-violating shapes the upstream
14429        // gate refuses. The empty string closes the empty-first arm of the
14430        // shared [`crate::render::require_valid_versao_requirement`]
14431        // cascade; the four non-empty arms exercise distinct semver-parse
14432        // failure modes the M3 peer per-`:membros` reject-set already pins
14433        // (`rejects_invalid_membro_versao_requirement` on `^bad-version`,
14434        // `rejects_membro_versao_with_double_caret_typo` on `^^0.1`,
14435        // `rejects_membro_versao_with_v_prefixed_tag` on `v0.1`) — the
14436        // shared parser routing means the same reject-set must fail
14437        // identically at the M2 supervisor-tree per-`:children` accessor
14438        // arm here. Every rejection at the validator must correspond to a
14439        // rejection when the accessor's projected value is fed back
14440        // through the shared gate.
14441        //
14442        // (Bare partial magnitudes like `"0.1"` and bare identifiers like
14443        // `"not-a-semver"` are intentionally *not* in the reject-set: the
14444        // semver crate accepts `"0.1"` as an implicit `^0.1` requirement,
14445        // and the identifier-tail arm's grammar admits some non-canonical
14446        // shapes — matching what the M3 peer test suite already documents
14447        // as the shared parser's accept-set edges.)
14448        for bad_req in ["", "v0.1.0", "^bad-version", "^^0.1", "v0.1"] {
14449            let s = SupervisorSpec {
14450                children: vec![ChildSpec {
14451                    caixa: "worker".into(),
14452                    versao: bad_req.into(),
14453                    restart: RestartPolicy::Permanent,
14454                }],
14455                ..SupervisorSpec::default()
14456            };
14457            let err = s.validate().unwrap_err();
14458            assert!(
14459                matches!(
14460                    err,
14461                    SupervisorError::EmptyChildVersion { .. }
14462                        | SupervisorError::ChildVersaoInvalid { .. }
14463                ),
14464                "SupervisorSpec::validate must reject :children :versao {bad_req:?} \
14465                 via the versao-requirement gate: got {err:?}",
14466            );
14467            let c = ChildSpec {
14468                caixa: "worker".into(),
14469                versao: bad_req.into(),
14470                restart: RestartPolicy::Permanent,
14471            };
14472            assert!(
14473                crate::render::require_valid_versao_requirement(
14474                    c.versao_requirement(),
14475                    || (),
14476                    |_reason| (),
14477                )
14478                .is_err(),
14479                "require_valid_versao_requirement must reject the accessor-projected \
14480                 :children :versao {bad_req:?}",
14481            );
14482        }
14483    }
14484
14485    // ── per-`:children` `:restart` typed-accessor coherence pins ──────────
14486    //
14487    // The [`ChildSpec::restart`] accessor lift closes the last unlifted
14488    // per-`:children` axis (the pair `nome()` + `versao_requirement()`
14489    // already project the `String`-carry `(caixa, versao)` fields; the
14490    // `Copy`-composite-enum `restart` field is the third and final axis).
14491    // Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
14492    // (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
14493    // scalar accessor and the M3 mesh-slot [`crate::Placement::estrategia`]
14494    // (921fe1b) `Copy`-return [`crate::PlacementStrategy`] distribution-
14495    // strategy scalar accessor — same "one typed dispatch on the substrate
14496    // primitive, `Copy`-projected closed-set enum-arm discriminator" shape
14497    // extended onto the M2 supervisor-slot per-`:children` restart-decision
14498    // axis. The pin below covers the accessor's byte-equal projection
14499    // against the raw field access across every variant in the closed
14500    // accept-set (`Permanent`, `Transient`, `Temporary`).
14501
14502    #[test]
14503    fn child_spec_restart_returns_restart_verbatim_across_permutations() {
14504        // The canonical per-`:children` restart-decision-policy-scalar
14505        // pin: [`ChildSpec::restart`] must return the `:children :restart`
14506        // field verbatim as a [`RestartPolicy`], `Copy`-projected from the
14507        // typed slot's own [`RestartPolicy`] storage across every variant
14508        // in the closed accept-set (`Permanent`, `Transient`, `Temporary`).
14509        // Pins against a future silent detour that re-derived the policy
14510        // from a peer axis (an accidental fallback to
14511        // `if is_supervisor_child { Permanent } else { Temporary }` that
14512        // collapsed the child's kind axis into the restart discriminator),
14513        // a variant remap the operator authors on one consumer without the
14514        // other, or a stale-derive detour that substituted
14515        // [`RestartPolicy::default`] when the field held any explicit
14516        // variant (which would silently collapse the distinction between
14517        // "author explicitly declared `:restart Permanent`" and "author
14518        // omitted the slot and inherited the default" the future
14519        // per-cluster restart-decision override slot depends on).
14520        //
14521        // Peer of the sibling per-`:supervisor`
14522        // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
14523        // (eafb619) pin on the M2 supervisor-slot sibling-restart-strategy
14524        // axis and the M3
14525        // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
14526        // (921fe1b) pin on the per-`:placement` distribution-strategy axis
14527        // — same "the substrate-primitive accessor must byte-equal the raw
14528        // field access verbatim across every author-declared value"
14529        // discipline extended onto the M2 supervisor-slot per-`:children`
14530        // restart-decision-policy axis, closing the last unlifted axis on
14531        // the per-`:children` [`ChildSpec`] type.
14532        for restart in [
14533            RestartPolicy::Permanent,
14534            RestartPolicy::Transient,
14535            RestartPolicy::Temporary,
14536        ] {
14537            let c = ChildSpec {
14538                caixa: "worker".into(),
14539                versao: "^0.1".into(),
14540                restart,
14541            };
14542            assert_eq!(
14543                c.restart(),
14544                restart,
14545                "ChildSpec::restart must return :children :restart \
14546                 verbatim (got {:?}, expected {restart:?})",
14547                c.restart(),
14548            );
14549            assert_eq!(
14550                c.restart(),
14551                c.restart,
14552                "ChildSpec::restart accessor and .restart field access \
14553                 must byte-equal — the accessor is the substrate-primitive \
14554                 typed dispatch every downstream per-child restart-\
14555                 decision consumer must route through",
14556            );
14557        }
14558    }
14559
14560    // ── per-`:supervisor` `:estrategia` typed-accessor coherence pins ─────
14561    //
14562    // The [`SupervisorSpec::estrategia`] accessor lift extends the peer M3
14563    // [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
14564    // distribution-strategy accessor discipline onto the M2 supervisor-slot
14565    // per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
14566    // scalar axis. The two pins below cover (1) the accessor's byte-equal
14567    // projection against the raw field access across every variant in the
14568    // closed accept-set, and (2) the two-consumer coherence between the
14569    // [`SupervisorSpec::validate`] partition-dispatch `match` arm and the
14570    // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
14571    // carrier's `estrategia:` field — peer of the sibling M3
14572    // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
14573    // / `validate_placement_reads_through_lifted_estrategia_accessor` pin
14574    // pair on the per-`:placement` distribution-strategy axis.
14575
14576    #[test]
14577    fn supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations() {
14578        // The canonical per-`:supervisor` sibling-restart-strategy-scalar
14579        // pin: [`SupervisorSpec::estrategia`] must return the
14580        // `:supervisor :estrategia` field verbatim as a
14581        // [`RestartStrategy`], `Copy`-projected from the typed slot's own
14582        // [`RestartStrategy`] storage across every variant in the closed
14583        // accept-set (`OneForOne`, `OneForAll`, `RestForOne`,
14584        // `SimpleOneForOne`). Pins against a future silent detour that
14585        // re-derived the strategy from a peer axis (an accidental
14586        // fallback to `if children.is_empty() { SimpleOneForOne } else {
14587        // OneForOne }` collapse that read the children-count axis into
14588        // the strategy discriminator), a variant remap the operator
14589        // authors on one consumer without the other, or a stale-derive
14590        // detour that substituted [`RestartStrategy::default`] when the
14591        // field held any explicit variant (which would silently collapse
14592        // the distinction between "author explicitly declared
14593        // `:estrategia OneForOne`" and "author omitted the slot and
14594        // inherited the default" the future per-cluster strategy override
14595        // slot depends on). Peer of the sibling M3
14596        // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
14597        // (921fe1b) pin on the M3 mesh-slot `Copy`-composite-enum scalar
14598        // axis — same "the substrate-primitive accessor must byte-equal
14599        // the raw field access verbatim across every author-declared
14600        // value" discipline extended onto the M2 supervisor-slot
14601        // per-`:supervisor` sibling-restart-strategy axis.
14602        for &estrategia in RestartStrategy::ALL {
14603            // `SimpleOneForOne` requires `children.is_empty()`; the peer
14604            // three strategies require a non-empty static children list.
14605            // Build each shape coherently so the pin's fixture would
14606            // itself pass [`SupervisorSpec::validate`] once fed through
14607            // the sibling coherence pin below — the byte-equal projection
14608            // asserted here is a strictly weaker property (a `Copy` field
14609            // read) that does not depend on `validate` running, but
14610            // keeping the fixture validate-clean means a future extension
14611            // of the pin to exercise `validate` end-to-end does not have
14612            // to re-author the children shape.
14613            //
14614            // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
14615            // shape partition through the [`gen_platform::IsVariant`]
14616            // derive-generated
14617            // [`RestartStrategy::is_simple_one_for_one`] predicate rather
14618            // than the raw `matches!(estrategia, RestartStrategy::
14619            // SimpleOneForOne)` open-coded pattern-match — same closed-
14620            // set-typed-enum arm-discriminator dispatch discipline the
14621            // sibling [`crate::upgrade::UpgradeInstruction::is_restart`]
14622            // convergence (915a934) extended onto its two paired positive
14623            // / negated `matches!` sites and the peer
14624            // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
14625            // predicate convergence (766ec63) extended onto the M3 mesh-
14626            // slot per-`:placement` distribution-strategy discriminator
14627            // axis. See the sibling `round_trip_all_strategies` and the
14628            // peer `manifest::tests::
14629            // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
14630            // fixture for the two peer sites the same lift closes on.
14631            let children = if estrategia.is_simple_one_for_one() {
14632                Vec::new()
14633            } else {
14634                vec![ChildSpec {
14635                    caixa: "worker".into(),
14636                    versao: "^0.1".into(),
14637                    restart: RestartPolicy::Permanent,
14638                }]
14639            };
14640            let s = SupervisorSpec {
14641                estrategia,
14642                children,
14643                ..SupervisorSpec::default()
14644            };
14645            assert_eq!(
14646                s.estrategia(),
14647                estrategia,
14648                "SupervisorSpec::estrategia must return :supervisor :estrategia \
14649                 verbatim (got {:?}, expected {estrategia:?})",
14650                s.estrategia(),
14651            );
14652            assert_eq!(
14653                s.estrategia(),
14654                s.estrategia,
14655                "SupervisorSpec::estrategia accessor and .estrategia field \
14656                 access must byte-equal — the accessor is the substrate-\
14657                 primitive typed dispatch every downstream sibling-restart-\
14658                 strategy consumer must route through",
14659            );
14660        }
14661    }
14662
14663    #[test]
14664    fn validate_reads_through_lifted_estrategia_accessor() {
14665        // Two-consumer coherence pin: the [`SupervisorSpec::validate`]
14666        // `SimpleOneForOne ↔ non-SimpleOneForOne` `match` partition
14667        // dispatch (which reads through [`SupervisorSpec::estrategia`]
14668        // to fan across the strategy-arm shape-gate cascades) and the
14669        // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
14670        // error carrier's `estrategia:` field (which reads through
14671        // [`SupervisorSpec::estrategia`] to name the strategy the empty
14672        // `:children` list was declared against) must both key off the
14673        // lifted accessor, so any future rebrand on the typed slot's
14674        // reader shape lands at exactly one place. Pins the two-site
14675        // coherence by exercising the `NoChildren` error surface end-to-
14676        // end across every non-`SimpleOneForOne` variant and asserting
14677        // the surfaced `estrategia:` field byte-equals the accessor's
14678        // return. Peer of the sibling M3
14679        // `validate_placement_reads_through_lifted_estrategia_accessor`
14680        // (921fe1b) three-consumer coherence pin on the per-`:placement`
14681        // distribution-strategy axis.
14682        for estrategia in [
14683            RestartStrategy::OneForOne,
14684            RestartStrategy::OneForAll,
14685            RestartStrategy::RestForOne,
14686        ] {
14687            let s = SupervisorSpec {
14688                estrategia,
14689                children: Vec::new(),
14690                ..SupervisorSpec::default()
14691            };
14692            let err = s.validate().unwrap_err();
14693            match err {
14694                SupervisorError::NoChildren { estrategia: e } => {
14695                    assert_eq!(
14696                        e,
14697                        s.estrategia(),
14698                        "NoChildren.estrategia must byte-equal \
14699                         SupervisorSpec::estrategia() — the empty-`:children` \
14700                         refusal reads through the lifted accessor",
14701                    );
14702                    assert_eq!(
14703                        e, estrategia,
14704                        "NoChildren.estrategia must carry the author-declared \
14705                         :supervisor :estrategia variant verbatim (got {e:?}, \
14706                         expected {estrategia:?})",
14707                    );
14708                }
14709                other => panic!("expected NoChildren, got {other:?} for estrategia={estrategia:?}"),
14710            }
14711        }
14712    }
14713
14714    // ── per-`:supervisor` `:max-restarts` typed-accessor coherence pins ────
14715    //
14716    // The [`SupervisorSpec::max_restarts`] accessor lift extends the peer M3
14717    // [`crate::CircuitBreaker::max_failures`] (3a74062) `Copy`-return
14718    // required-`u32` scalar accessor discipline onto the M2 supervisor-slot
14719    // per-`:supervisor` restart-budget-count `Copy`-`u32` scalar axis.
14720    // The two pins below cover (1) the accessor's byte-equal projection
14721    // against the raw field access across every representative value in
14722    // the `u32` accept-set (`1` lower boundary, `SUPERVISOR_MAX_RESTARTS_MAX`
14723    // upper boundary, `0` past-the-guard zero sentinel, `u32::MAX`
14724    // past-the-guard cap sentinel), and (2) the [`SupervisorSpec::validate`]
14725    // zero-floor / cap composition — the validate gate and the accessor
14726    // must route through the same substrate-primitive typed dispatch, so
14727    // any future silent detour that had the accessor perform a
14728    // bounds-collapsing clamp would fail here at caixa-core build time.
14729    // Peer of the sibling M3
14730    // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
14731    // (3a74062) pin on the per-`CircuitBreaker :max-failures` axis.
14732
14733    #[test]
14734    fn supervisor_spec_max_restarts_returns_max_restarts_u32_byte_equal_across_permutations() {
14735        // The canonical per-`:supervisor` restart-budget-count scalar pin:
14736        // [`SupervisorSpec::max_restarts`] must return the `:supervisor
14737        // :max-restarts` typed `u32` verbatim, `Copy`-projected from the
14738        // typed slot's own `u32` storage, byte-equal to the raw field
14739        // access across every representative value in the accept-set —
14740        // `1` (the lower boundary of the `1..=SUPERVISOR_MAX_RESTARTS_MAX`
14741        // accept-set the surrounding [`SupervisorSpec::validate`] gate
14742        // carves out on the sibling `ZeroMaxRestarts` refusal),
14743        // `SUPERVISOR_MAX_RESTARTS_MAX` (the upper boundary the same gate
14744        // carves out on the sibling `MaxRestartsExceedsCap` refusal), `0`
14745        // (a past-the-guard sentinel that pins the accessor doesn't
14746        // perform a silent bounds-collapse into `1` on the zero arm —
14747        // validate rejects zero but the accessor must ship the raw slot
14748        // verbatim so a validate-time gate regression surfaces at the
14749        // emit boundary rather than being silently absorbed), `u32::MAX`
14750        // (a past-the-guard sentinel that pins the accessor doesn't
14751        // perform a silent bounds-collapse through
14752        // `SUPERVISOR_MAX_RESTARTS_MAX` at the return path).
14753        //
14754        // Peer of the sibling M3
14755        // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
14756        // (3a74062) pin on the M3 mesh-slot `Copy`-`u32` sub-struct
14757        // required-scalar axis — same "the substrate-primitive accessor
14758        // must byte-equal the raw field access verbatim across every
14759        // value in the `u32` accept-set" discipline extended onto the M2
14760        // supervisor-slot per-`:supervisor` restart-budget-count axis.
14761        for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX, 0, u32::MAX] {
14762            let s = SupervisorSpec {
14763                max_restarts,
14764                ..SupervisorSpec::default()
14765            };
14766            assert_eq!(
14767                s.max_restarts(),
14768                max_restarts,
14769                "SupervisorSpec::max_restarts must return :supervisor \
14770                 :max-restarts verbatim (got {}, expected {max_restarts})",
14771                s.max_restarts(),
14772            );
14773            assert_eq!(
14774                s.max_restarts(),
14775                s.max_restarts,
14776                "SupervisorSpec::max_restarts accessor and .max_restarts \
14777                 field access must byte-equal — the accessor is the \
14778                 substrate-primitive typed dispatch every downstream \
14779                 restart-budget-count consumer must route through",
14780            );
14781        }
14782    }
14783
14784    #[test]
14785    fn validate_max_restarts_zero_floor_and_cap_arms_route_through_accessor() {
14786        // Composition pin: [`SupervisorSpec::validate`]'s `:max-restarts`
14787        // zero-floor + upper-cap bracket must key off
14788        // [`SupervisorSpec::max_restarts`], not the raw `.max_restarts`
14789        // field access. Structurally: a `SupervisorSpec { max_restarts:
14790        // 0, .. }` must surface the `ZeroMaxRestarts` refusal exactly, a
14791        // `SupervisorSpec { max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
14792        // .. }` must surface the `MaxRestartsExceedsCap` refusal exactly
14793        // (with the offending count carried verbatim from the accessor
14794        // return), and a `SupervisorSpec { max_restarts: 1, .. }` (the
14795        // lower boundary of the accept-set) plus a `SupervisorSpec {
14796        // max_restarts: SUPERVISOR_MAX_RESTARTS_MAX, .. }` (the upper
14797        // boundary) must pass validate. The four together jointly pin the
14798        // accessor + validate-gate composition: any future silent detour
14799        // that had the accessor return a fresh `1` on the zero arm (a
14800        // `.max_restarts().max(1)` collapse) would silently absorb the
14801        // `ZeroMaxRestarts` refusal at the accessor boundary and the
14802        // validate gate would accept a struct-literal `SupervisorSpec {
14803        // max_restarts: 0, .. }` — the composition pin catches that at
14804        // caixa-core build time.
14805        //
14806        // Peer of the sibling M3
14807        // `validate_politicas_max_failures_zero_floor_arm_routes_through_accessor`
14808        // (3a74062) pin on the sibling per-`CircuitBreaker :max-failures`
14809        // composition axis — same "the validate / shape-gate predicate
14810        // must route through the substrate-primitive typed dispatch"
14811        // discipline extended onto the peer M2 supervisor-slot
14812        // required-`u32` composition axis.
14813        let child = ChildSpec {
14814            caixa: "worker".into(),
14815            versao: "^0.1".into(),
14816            restart: RestartPolicy::Permanent,
14817        };
14818        // Zero-floor arm.
14819        let s = SupervisorSpec {
14820            max_restarts: 0,
14821            children: vec![child.clone()],
14822            ..SupervisorSpec::default()
14823        };
14824        assert_eq!(
14825            s.validate().unwrap_err(),
14826            SupervisorError::ZeroMaxRestarts,
14827            "validate must reject max_restarts == 0 with ZeroMaxRestarts \
14828             — the accessor and the validate gate must route through the \
14829             same substrate-primitive typed dispatch on the zero-floor arm",
14830        );
14831        // Cap arm — the surfaced `max_restarts:` field must byte-equal
14832        // the accessor's return so a future rebrand on the accessor
14833        // lands in the diagnostic without a coordinated rewrite.
14834        let over_cap = SUPERVISOR_MAX_RESTARTS_MAX + 1;
14835        let s = SupervisorSpec {
14836            max_restarts: over_cap,
14837            children: vec![child.clone()],
14838            ..SupervisorSpec::default()
14839        };
14840        match s.validate().unwrap_err() {
14841            SupervisorError::MaxRestartsExceedsCap { max_restarts } => {
14842                assert_eq!(
14843                    max_restarts,
14844                    s.max_restarts(),
14845                    "MaxRestartsExceedsCap.max_restarts must byte-equal \
14846                     SupervisorSpec::max_restarts() — the cap-arm refusal \
14847                     reads through the lifted accessor",
14848                );
14849                assert_eq!(
14850                    max_restarts, over_cap,
14851                    "MaxRestartsExceedsCap.max_restarts must carry the \
14852                     author-declared :supervisor :max-restarts value \
14853                     verbatim (got {max_restarts}, expected {over_cap})",
14854                );
14855            }
14856            other => panic!("expected MaxRestartsExceedsCap, got {other:?}"),
14857        }
14858        // Lower + upper accept-set boundaries.
14859        for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX] {
14860            let s = SupervisorSpec {
14861                max_restarts,
14862                children: vec![child.clone()],
14863                ..SupervisorSpec::default()
14864            };
14865            assert!(
14866                s.validate().is_ok(),
14867                "validate must accept max_restarts == {max_restarts} \
14868                 (an accept-set boundary of \
14869                 1..=SUPERVISOR_MAX_RESTARTS_MAX)",
14870            );
14871        }
14872    }
14873
14874    // ── per-`:supervisor` `:restart-window` typed-accessor coherence pins ─
14875    //
14876    // The [`SupervisorSpec::restart_window`] accessor lift extends the peer
14877    // M2 [`crate::LimitsSpec::wall_clock`] (8cb717b) `Option<Duration>`
14878    // accessor discipline and the peer M3 [`crate::MeshPolicy::timeout`]
14879    // (7073d0f) `Option<Duration>` accessor discipline onto the M2
14880    // supervisor-slot per-`:supervisor` restart-intensity-denominator
14881    // `Option<Duration>` scalar axis — third `Copy`-return accessor on the
14882    // M2 supervisor-slot `SupervisorSpec` type, closing the last unlifted
14883    // per-`:supervisor` scalar-value axis. The three pins below cover
14884    // (1) the accessor's byte-equal projection against the raw field
14885    // access across every representative value in the `Option<Duration>`
14886    // accept-set (`None` never-reset sentinel, `Some(Duration::from_millis(1))`
14887    // lower boundary, `Some(SUPERVISOR_RESTART_WINDOW_MAX)` upper boundary,
14888    // `Some(Duration::ZERO)` past-the-guard zero sentinel, `Some(Duration::MAX)`
14889    // past-the-guard above-cap sentinel), (2) the [`SupervisorSpec::validate`]
14890    // `if let Some(w) = self.restart_window() { … }` bracket-arm
14891    // composition — the validate gate and the accessor must route through
14892    // the same substrate-primitive typed dispatch, so any future silent
14893    // detour that had the accessor perform a bounds-collapsing clamp
14894    // would fail here at caixa-core build time, and (3) the accessor's
14895    // by-copy idempotence pin — the returned `Option<Duration>` must
14896    // outlive `&self` and two successive calls must return byte-equal
14897    // values. Peer of the sibling M2
14898    // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
14899    // (8cb717b) pin on the per-`:limits :wall-clock` axis and the sibling
14900    // M3 `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
14901    // (7073d0f) pin on the per-`:politicas :timeout` axis.
14902
14903    #[test]
14904    fn supervisor_spec_restart_window_returns_option_duration_byte_equal_across_permutations() {
14905        // The canonical per-`:supervisor` restart-intensity-denominator
14906        // scalar pin: [`SupervisorSpec::restart_window`] must return the
14907        // `:supervisor :restart-window` typed [`Duration`] verbatim as an
14908        // `Option<Duration>`, `Copy`-projected from the typed slot's own
14909        // `Option<Duration>` storage, byte-equal to the raw field access
14910        // across every representative value in the accept-set — `None`
14911        // (the "never reset — every restart across the supervisor's
14912        // lifetime counts against the sibling `:max-restarts` budget"
14913        // sentinel the field's own docstring names and the peer
14914        // `validate_accepts_none_restart_window` pin locks in on the
14915        // [`SupervisorSpec::validate`] entry-side),
14916        // `Some(Duration::from_millis(1))` (the structural minimum a
14917        // validated `:restart-window` may carry, the integer-millisecond
14918        // floor [`SupervisorError::RestartWindowNotCanonical`] rejects
14919        // everything sub-ms; `Duration::ZERO` is separately rejected by
14920        // [`SupervisorError::RestartWindowZero`]),
14921        // `Some(SUPERVISOR_RESTART_WINDOW_MAX)` (the upper boundary the
14922        // surrounding [`SupervisorSpec::validate`] gate carves out on the
14923        // sibling [`SupervisorError::RestartWindowExceedsCap`] refusal),
14924        // `Some(Duration::ZERO)` (a past-the-guard sentinel that pins the
14925        // accessor doesn't perform a silent bounds-collapse into `None` on
14926        // the zero-Duration arm — validate rejects zero but the accessor
14927        // must ship the raw slot verbatim so a validate-time gate
14928        // regression surfaces at the emit boundary rather than being
14929        // silently absorbed), and `Some(Duration::MAX)` (a past-the-guard
14930        // sentinel that pins the accessor doesn't perform a silent
14931        // bounds-collapse through [`SUPERVISOR_RESTART_WINDOW_MAX`] at the
14932        // return path).
14933        //
14934        // Peer of the sibling M2
14935        // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
14936        // (8cb717b) pin on the per-`:limits :wall-clock` axis and the
14937        // sibling M3
14938        // `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
14939        // (7073d0f) pin on the per-`:politicas :timeout` axis — same "the
14940        // substrate-primitive accessor must byte-equal the raw field
14941        // access verbatim across every value in the `Option<Duration>`
14942        // accept-set" discipline extended onto the M2 supervisor-slot
14943        // per-`:supervisor` `Option<Duration>` axis. Pins against a future
14944        // silent detour that re-derived the restart-window from a peer
14945        // axis (an accidental `.max_restarts.into()` collapse that read
14946        // the restart-budget-count as a duration — the two axes serve
14947        // different halves of the `MaxIntensity / Period` restart-
14948        // intensity ratio, and confusing them silently inverts the
14949        // ratio's numerator and denominator), a `None → Some(Duration::ZERO)`
14950        // "zero means never reset" collapse (the canonical
14951        // `Option<Duration>` → `Duration` collapse footgun the
14952        // [`SupervisorError::RestartWindowZero`] validate arm guards on
14953        // the peer zero-floor axis; a zero period either trips on the
14954        // first failure or never trips depending on operator
14955        // interpretation, neither of which is the author's "never reset"
14956        // intent that `None` expresses structurally), or a per-arm
14957        // variant swap that landed on one consumer without the other.
14958        for restart_window in [
14959            None,
14960            Some(Duration::from_millis(1)),
14961            Some(SUPERVISOR_RESTART_WINDOW_MAX),
14962            Some(Duration::ZERO),
14963            Some(Duration::MAX),
14964        ] {
14965            let s = SupervisorSpec {
14966                restart_window,
14967                ..SupervisorSpec::default()
14968            };
14969            assert_eq!(
14970                s.restart_window(),
14971                restart_window,
14972                "SupervisorSpec::restart_window must return :supervisor \
14973                 :restart-window verbatim (got {:?}, expected {restart_window:?})",
14974                s.restart_window(),
14975            );
14976            assert_eq!(
14977                s.restart_window(),
14978                s.restart_window,
14979                "SupervisorSpec::restart_window accessor and \
14980                 .restart_window field access must byte-equal — the \
14981                 accessor is the substrate-primitive typed dispatch every \
14982                 downstream restart-intensity-denominator consumer must \
14983                 route through",
14984            );
14985        }
14986    }
14987
14988    #[test]
14989    fn validate_restart_window_bracket_arm_routes_through_accessor() {
14990        // Composition pin: [`SupervisorSpec::validate`]'s
14991        // `:restart-window` `if let Some(w) = self.restart_window() { … }`
14992        // zero-floor + integer-millisecond canonical-form + upper-cap
14993        // bracket-arm must key off [`SupervisorSpec::restart_window`], not
14994        // the raw `.restart_window` field access. Structurally: a
14995        // `SupervisorSpec { restart_window: None, .. }` must pass the
14996        // arm gate structurally (the `if let Some(_)` shape returns
14997        // early on the `None` arm — the accessor and the validate gate
14998        // must agree on `None → skip the bracket cascade` so an authored
14999        // `:restart-window ()` structurally routes through the "never
15000        // reset" sentinel path), a `SupervisorSpec { restart_window:
15001        // Some(Duration::ZERO), .. }` must surface the `RestartWindowZero`
15002        // refusal exactly, a `SupervisorSpec { restart_window:
15003        // Some(Duration::from_micros(1500)), .. }` must surface the
15004        // `RestartWindowNotCanonical` refusal exactly (with the offending
15005        // duration carried verbatim from the accessor return), a
15006        // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX
15007        // + Duration::from_millis(1)), .. }` must surface the
15008        // `RestartWindowExceedsCap` refusal exactly (with the offending
15009        // duration carried verbatim from the accessor return), and a
15010        // `SupervisorSpec { restart_window: Some(Duration::from_millis(1)),
15011        // .. }` (the lower boundary of the accept-set) plus a
15012        // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
15013        // .. }` (the upper boundary) must pass validate. The six together
15014        // jointly pin the accessor + validate-gate composition: any future
15015        // silent detour that had the accessor return a fresh `None` on any
15016        // `Some` arm (a `.restart_window().filter(|w| !w.is_zero())`
15017        // collapse) would silently absorb the `RestartWindowZero` refusal
15018        // at the accessor boundary and the validate gate would accept a
15019        // struct-literal `SupervisorSpec { restart_window:
15020        // Some(Duration::ZERO), .. }` — the composition pin catches that
15021        // at caixa-core build time.
15022        //
15023        // Peer of the sibling M2 [`crate::LimitsSpec::wall_clock`]
15024        // (8cb717b) validate-arm-route pin on the per-`:limits :wall-clock`
15025        // axis and the peer M3 [`crate::MeshPolicy::timeout`] (7073d0f)
15026        // accessor-composition pin on the per-`:politicas :timeout` axis —
15027        // same "the validate / shape-gate predicate must route through
15028        // the substrate-primitive typed dispatch" discipline extended
15029        // onto the peer M2 supervisor-slot optional-`Duration` axis.
15030        let child = ChildSpec {
15031            caixa: "worker".into(),
15032            versao: "^0.1".into(),
15033            restart: RestartPolicy::Permanent,
15034        };
15035        // None arm — must not surface any :restart-window-shaped refusal;
15036        // the `if let Some(_)` bracket returns early on `None` structurally.
15037        let s = SupervisorSpec {
15038            restart_window: None,
15039            children: vec![child.clone()],
15040            ..SupervisorSpec::default()
15041        };
15042        assert!(
15043            s.validate().is_ok(),
15044            "validate must accept restart_window: None (the never-reset \
15045             sentinel) — the `if let Some(_)` bracket returns early on \
15046             the None arm and the accessor must agree",
15047        );
15048        // Zero-floor arm.
15049        let s = SupervisorSpec {
15050            restart_window: Some(Duration::ZERO),
15051            children: vec![child.clone()],
15052            ..SupervisorSpec::default()
15053        };
15054        assert_eq!(
15055            s.validate().unwrap_err(),
15056            SupervisorError::RestartWindowZero,
15057            "validate must reject restart_window == Some(Duration::ZERO) \
15058             with RestartWindowZero — the accessor and the validate gate \
15059             must route through the same substrate-primitive typed \
15060             dispatch on the zero-floor arm",
15061        );
15062        // Non-canonical (sub-ms) arm — the surfaced `window:` field must
15063        // byte-equal the accessor's return so a future rebrand on the
15064        // accessor lands in the diagnostic without a coordinated rewrite.
15065        let sub_ms = Duration::from_micros(1500);
15066        let s = SupervisorSpec {
15067            restart_window: Some(sub_ms),
15068            children: vec![child.clone()],
15069            ..SupervisorSpec::default()
15070        };
15071        match s.validate().unwrap_err() {
15072            SupervisorError::RestartWindowNotCanonical { window } => {
15073                assert_eq!(
15074                    Some(window),
15075                    s.restart_window(),
15076                    "RestartWindowNotCanonical.window must byte-equal \
15077                     SupervisorSpec::restart_window().unwrap() — the \
15078                     non-canonical-arm refusal reads through the lifted \
15079                     accessor",
15080                );
15081                assert_eq!(
15082                    window, sub_ms,
15083                    "RestartWindowNotCanonical.window must carry the \
15084                     author-declared :supervisor :restart-window value \
15085                     verbatim (got {window:?}, expected {sub_ms:?})",
15086                );
15087            }
15088            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
15089        }
15090        // Cap arm — the surfaced `window:` field must byte-equal the
15091        // accessor's return.
15092        let over_cap = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
15093        let s = SupervisorSpec {
15094            restart_window: Some(over_cap),
15095            children: vec![child.clone()],
15096            ..SupervisorSpec::default()
15097        };
15098        match s.validate().unwrap_err() {
15099            SupervisorError::RestartWindowExceedsCap { window } => {
15100                assert_eq!(
15101                    Some(window),
15102                    s.restart_window(),
15103                    "RestartWindowExceedsCap.window must byte-equal \
15104                     SupervisorSpec::restart_window().unwrap() — the \
15105                     cap-arm refusal reads through the lifted accessor",
15106                );
15107                assert_eq!(
15108                    window, over_cap,
15109                    "RestartWindowExceedsCap.window must carry the \
15110                     author-declared :supervisor :restart-window value \
15111                     verbatim (got {window:?}, expected {over_cap:?})",
15112                );
15113            }
15114            other => panic!("expected RestartWindowExceedsCap, got {other:?}"),
15115        }
15116        // Lower + upper accept-set boundaries.
15117        for restart_window in [Duration::from_millis(1), SUPERVISOR_RESTART_WINDOW_MAX] {
15118            let s = SupervisorSpec {
15119                restart_window: Some(restart_window),
15120                children: vec![child.clone()],
15121                ..SupervisorSpec::default()
15122            };
15123            assert!(
15124                s.validate().is_ok(),
15125                "validate must accept restart_window == Some({restart_window:?}) \
15126                 (an accept-set boundary of \
15127                 1ms..=SUPERVISOR_RESTART_WINDOW_MAX)",
15128            );
15129        }
15130    }
15131
15132    #[test]
15133    fn supervisor_spec_restart_window_projects_option_duration_by_copy() {
15134        // The by-copy pin: [`SupervisorSpec::restart_window`] returns
15135        // `Option<Duration>` by copy — `Duration` is `Copy` (so
15136        // `Option<Duration>` is `Copy`) and the accessor must return by
15137        // value, not by reference. Peer of the sibling M2
15138        // [`crate::LimitsSpec::wall_clock`] (8cb717b) by-copy pin on the
15139        // per-`:limits :wall-clock` axis and the sibling M3
15140        // [`crate::MeshPolicy::timeout`] (7073d0f) by-copy pin on the
15141        // per-`:politicas :timeout` axis, extended onto the peer M2
15142        // supervisor-slot `Option<Duration>` copy-invariant shape — the
15143        // accessor's returned `Option<Duration>` must outlive `&self`
15144        // (multiple calls must return equal values from a dropped-`&self`
15145        // copy, since the returned Option carries no borrow), and calling
15146        // the accessor twice on the same SupervisorSpec must yield the
15147        // same `Option<Duration>` verbatim (idempotent, no side effects
15148        // on `&self`).
15149        //
15150        // Pins against a future silent detour that returned
15151        // `Option<&Duration>` (which would type-check but silently break
15152        // every downstream caller — the future wasm-operator's
15153        // per-supervisor restart-intensity counter consumes `Duration` by
15154        // value and `&Duration` would fold to a detached copy at the call
15155        // site), an accidental `Option::as_ref()` projection
15156        // (`self.restart_window.as_ref()` would also type-check but
15157        // return `Option<&Duration>`), or a one-arm-only accessor that
15158        // reads `Some(*w)` in the Some arm but reads a fresh
15159        // `Default::default()` (which would collapse to `Duration::ZERO`,
15160        // not `None`) in the None arm — a footgun the
15161        // [`SupervisorError::RestartWindowZero`] validate arm explicitly
15162        // closes since Erlang/OTP's `MaxIntensity / Period` invariant
15163        // requires `Period > 0` and `None` structurally expresses "never
15164        // reset" instead.
15165        for restart_window in [
15166            None,
15167            Some(Duration::from_millis(1)),
15168            Some(Duration::from_secs(60)),
15169            Some(SUPERVISOR_RESTART_WINDOW_MAX),
15170        ] {
15171            let s = SupervisorSpec {
15172                restart_window,
15173                ..SupervisorSpec::default()
15174            };
15175            let first = s.restart_window();
15176            let second = s.restart_window();
15177            assert_eq!(
15178                first, second,
15179                "SupervisorSpec::restart_window must be idempotent — two \
15180                 successive calls on the same &self must return the \
15181                 same Option<Duration>",
15182            );
15183            assert_eq!(
15184                first, restart_window,
15185                "SupervisorSpec::restart_window must return :supervisor \
15186                 :restart-window verbatim by copy — got {first:?}, \
15187                 expected {restart_window:?}",
15188            );
15189        }
15190    }
15191
15192    // ── per-`:supervisor` `:children` typed-accessor coherence pins ─────────
15193    //
15194    // The [`SupervisorSpec::children`] accessor lift is the seed of the
15195    // slice-return (`&[T]`) accessor discipline on the substrate — the four
15196    // peer `Vec`-carry axes ([`crate::Placement::clusters`],
15197    // [`crate::AplicacaoSpec::membros`], [`crate::AplicacaoSpec::contratos`],
15198    // [`crate::UpgradeFromEntry::instructions`]) still key off the raw field
15199    // access at the time of this seed, and inherit this pin family's
15200    // discipline as future compounding runs migrate their consumers. The
15201    // three pins below cover (1) the accessor's byte-equal projection
15202    // against the raw field access across the empty / singleton / cohort
15203    // fixtures the [`SupervisorSpec::validate`] partition-dispatch fans
15204    // between, (2) the [`SupervisorSpec::validate`] `SimpleOneForOne ↔
15205    // non-SimpleOneForOne` partition dispatch's paired `.is_empty()`
15206    // consumer routing through the accessor on both arms, and (3) the
15207    // per-child validate loop's traversal reading the same slice-view the
15208    // accessor projects. Peer of the sibling M2
15209    // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
15210    // two-consumer coherence pin on the per-`:supervisor`
15211    // sibling-restart-strategy `Copy`-composite-enum scalar axis, extended
15212    // onto the per-`:supervisor` static-child-list `Vec`-carry axis.
15213
15214    #[test]
15215    fn supervisor_spec_children_returns_children_slice_byte_equal_across_permutations() {
15216        // The canonical per-`:supervisor` static-child-list scalar-shape
15217        // pin: [`SupervisorSpec::children`] must return the `:supervisor
15218        // :children` typed `Vec<ChildSpec>` verbatim as a `&[ChildSpec]`
15219        // slice-view over the same backing buffer the raw
15220        // `self.children.as_slice()` field access borrows from, byte-
15221        // equal across every representative fixture in the accept-set —
15222        // the empty slice (the `SimpleOneForOne`-arm sentinel),
15223        // the singleton slice (the minimal non-`SimpleOneForOne` shape),
15224        // and a two-child cohort (a peer non-`SimpleOneForOne` shape
15225        // with the peer three restart-policy variants in play).
15226        //
15227        // Pins against a future silent detour that returned
15228        // `&Vec<ChildSpec>` (which would type-check but leak the
15229        // storage-side `Vec`'s grow/push/reserve surface no consumer of
15230        // the typed view reaches for), a fresh-allocated
15231        // `Vec<ChildSpec>` copy (which would type-check via a coercion
15232        // but silently break every downstream caller that relied on the
15233        // slice sharing the backing buffer's identity), or an
15234        // out-of-order or length-drifted projection (which would silently
15235        // split the per-child validate loop's traversal input from the
15236        // paired partition-dispatch `.is_empty()` probe's input).
15237        //
15238        // Peer of the sibling
15239        // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
15240        // (eafb619) `Copy`-composite-enum byte-equal pin on the
15241        // per-`:supervisor` sibling-restart-strategy axis, extended onto
15242        // the per-`:supervisor` static-child-list `Vec`-carry axis.
15243        let fixtures: Vec<Vec<ChildSpec>> = vec![
15244            Vec::new(),
15245            vec![child("worker", "^0.1", RestartPolicy::Permanent)],
15246            vec![
15247                child("worker", "^0.1", RestartPolicy::Permanent),
15248                child("cache-server", "^0.1", RestartPolicy::Transient),
15249            ],
15250            vec![
15251                child("worker", "^0.1", RestartPolicy::Permanent),
15252                child("cache-server", "^0.1", RestartPolicy::Transient),
15253                child("scratch-job", "^0.1", RestartPolicy::Temporary),
15254            ],
15255        ];
15256        for children in fixtures {
15257            let s = SupervisorSpec {
15258                children: children.clone(),
15259                ..SupervisorSpec::default()
15260            };
15261            assert_eq!(
15262                s.children(),
15263                children.as_slice(),
15264                "SupervisorSpec::children must return :supervisor \
15265                 :children verbatim (got {:?}, expected {:?})",
15266                s.children(),
15267                children.as_slice(),
15268            );
15269            assert_eq!(
15270                s.children(),
15271                s.children.as_slice(),
15272                "SupervisorSpec::children accessor and \
15273                 .children.as_slice() field access must byte-equal — \
15274                 the accessor is the substrate-primitive typed \
15275                 dispatch every downstream static-child-list consumer \
15276                 must route through",
15277            );
15278            assert_eq!(
15279                s.children().len(),
15280                s.children.len(),
15281                "SupervisorSpec::children().len() must byte-equal \
15282                 self.children.len() — a length-drift would silently \
15283                 split the paired partition-dispatch `.is_empty()` \
15284                 probe input from the per-child validate loop's \
15285                 traversal input",
15286            );
15287        }
15288    }
15289
15290    #[test]
15291    fn validate_reads_through_lifted_children_accessor() {
15292        // Three-consumer coherence pin: the [`SupervisorSpec::validate`]
15293        // `SimpleOneForOne`-arm `!self.children().is_empty()` refusal
15294        // probe (which must trip [`SupervisorError::SimpleOneForOneWithStaticChildren`]
15295        // when the accessor projects a non-empty slice under a
15296        // `SimpleOneForOne` estrategia), the peer non-`SimpleOneForOne`-arm
15297        // `self.children().is_empty()` refusal probe (which must trip
15298        // [`SupervisorError::NoChildren`] when the accessor projects the
15299        // empty slice under any peer estrategia), and the per-child
15300        // validate loop's `for child in self.children()` traversal
15301        // (which must reach every entry in the same order the accessor
15302        // projects) must all key off the lifted accessor, so any future
15303        // rebrand on the typed slot's reader shape lands at exactly one
15304        // place. Pins the three-site coherence by exercising each
15305        // production consumer end-to-end: (1) the
15306        // `SimpleOneForOneWithStaticChildren` refusal under a non-empty
15307        // slice + `SimpleOneForOne` estrategia, (2) the `NoChildren`
15308        // refusal under the empty slice + non-`SimpleOneForOne`
15309        // estrategia across every peer variant, and (3) the per-child
15310        // duplicate-detection surface fires on the second entry of a
15311        // two-child cohort that shares a `:caixa` name (which requires
15312        // the loop to reach both entries — a first-entry-only projection
15313        // would silently pass since the dedup HashSet has room for the
15314        // first insert).
15315        //
15316        // Peer of the sibling M2
15317        // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
15318        // two-consumer coherence pin on the per-`:supervisor`
15319        // sibling-restart-strategy axis, extended onto the
15320        // per-`:supervisor` static-child-list `Vec`-carry axis.
15321
15322        // (1) `SimpleOneForOne`-arm probe: a non-empty slice under a
15323        // `SimpleOneForOne` estrategia must trip
15324        // `SimpleOneForOneWithStaticChildren`.
15325        let s = SupervisorSpec {
15326            estrategia: RestartStrategy::SimpleOneForOne,
15327            children: vec![child("worker", "^0.1", RestartPolicy::Permanent)],
15328            ..SupervisorSpec::default()
15329        };
15330        assert_eq!(
15331            s.validate().unwrap_err(),
15332            SupervisorError::SimpleOneForOneWithStaticChildren,
15333            "SimpleOneForOne + non-empty children must trip \
15334             SimpleOneForOneWithStaticChildren — the accessor projects \
15335             a non-empty slice, and the SimpleOneForOne-arm refusal \
15336             probe reads through the lifted accessor",
15337        );
15338        assert!(
15339            !s.children().is_empty(),
15340            "the SimpleOneForOne-arm refusal input must be a non-empty \
15341             slice per the accessor's projection",
15342        );
15343
15344        // (2) Peer non-`SimpleOneForOne`-arm probe: the empty slice
15345        // under any peer estrategia must trip `NoChildren`.
15346        for estrategia in [
15347            RestartStrategy::OneForOne,
15348            RestartStrategy::OneForAll,
15349            RestartStrategy::RestForOne,
15350        ] {
15351            let s = SupervisorSpec {
15352                estrategia,
15353                children: Vec::new(),
15354                ..SupervisorSpec::default()
15355            };
15356            match s.validate().unwrap_err() {
15357                SupervisorError::NoChildren { estrategia: e } => {
15358                    assert_eq!(
15359                        e, estrategia,
15360                        "NoChildren.estrategia must carry the author-\
15361                         declared :supervisor :estrategia variant \
15362                         verbatim (got {e:?}, expected {estrategia:?})",
15363                    );
15364                }
15365                other => panic!(
15366                    "expected NoChildren, got {other:?} for \
15367                     estrategia={estrategia:?}"
15368                ),
15369            }
15370            assert!(
15371                s.children().is_empty(),
15372                "the non-SimpleOneForOne-arm refusal input must be the \
15373                 empty slice per the accessor's projection",
15374            );
15375        }
15376
15377        // (3) Per-child validate loop: a two-child cohort that shares a
15378        // `:caixa` name must trip `DuplicateChildCaixa` — the loop must
15379        // reach both entries through the accessor.
15380        let s = SupervisorSpec {
15381            estrategia: RestartStrategy::OneForOne,
15382            children: vec![
15383                child("worker", "^0.1", RestartPolicy::Permanent),
15384                child("worker", "^0.2", RestartPolicy::Transient),
15385            ],
15386            ..SupervisorSpec::default()
15387        };
15388        match s.validate().unwrap_err() {
15389            SupervisorError::DuplicateChildCaixa { caixa } => {
15390                assert_eq!(
15391                    caixa, "worker",
15392                    "DuplicateChildCaixa.caixa must carry the shared \
15393                     child `:caixa` name verbatim",
15394                );
15395            }
15396            other => panic!("expected DuplicateChildCaixa, got {other:?}"),
15397        }
15398        assert_eq!(
15399            s.children().len(),
15400            2,
15401            "the per-child validate loop's traversal input must be a \
15402             two-element slice per the accessor's projection",
15403        );
15404    }
15405
15406    // Shared helper for the M2 per-`:children` per-slot-gate ≡
15407    // `validate` equivalence pins: builds an `OneForOne`-estrategia
15408    // one-cohort spec whose peer `:estrategia`↔`:children.is_empty()`
15409    // partition, `:max-restarts` zero-floor/cap, and `:restart-window`
15410    // bracket all pass cleanly so the sole failing surface is the
15411    // per-child cascade [`SupervisorSpec::validate_children`] owns, and
15412    // pins the two-altitude equivalence on the paired probe.
15413    fn assert_validate_children_matches_gate(children: Vec<ChildSpec>, expected: &SupervisorError) {
15414        let s = SupervisorSpec {
15415            estrategia: RestartStrategy::OneForOne,
15416            children,
15417            ..SupervisorSpec::default()
15418        };
15419        let via_gate = s.validate_children().unwrap_err();
15420        let via_validate = s.validate().unwrap_err();
15421        assert_eq!(&via_gate, expected, "validate_children direct dispatch",);
15422        assert_eq!(&via_validate, expected, "validate() end-to-end dispatch",);
15423        assert_eq!(
15424            via_gate, via_validate,
15425            "per-slot gate ≡ validate() must discriminate the same \
15426             refusal shape",
15427        );
15428    }
15429
15430    #[test]
15431    fn validate_children_matches_gate_on_per_axis_refusal_shapes() {
15432        // Fail-before-pass-after equivalence pin on the M2
15433        // per-`:children` per-slot gate ≡ [`SupervisorSpec::validate`]
15434        // convergence — sibling of the M3 mesh-slot
15435        // `validate_membros_*` / `validate_contratos_*` /
15436        // `validate_entrada_*` per-slot-gate ≡ `validate` pins on the
15437        // peer per-entry axes. Sweeps four of the five refusal shapes
15438        // the per-slot gate owns: (1) `EmptyChildName` on an empty-
15439        // `:caixa` child, (2) `ChildCaixaInvalid` on a structurally
15440        // invalid `:caixa` DNS-1123 label, (3) `EmptyChildVersion` on
15441        // an empty-`:versao` child, (4) `DuplicateChildCaixa` on a
15442        // duplicate-`:caixa` fan-out. Companion pin
15443        // `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
15444        // covers `ChildVersaoInvalid` (whose parser-owned reason string
15445        // needs pattern-matching, not equality) and the clean-pass
15446        // canonical fixture; together the two pins guarantee the
15447        // per-slot gate and `validate` discriminate the same set on
15448        // every per-child-covered input.
15449        assert_validate_children_matches_gate(
15450            vec![child("", "^0.1", RestartPolicy::Permanent)],
15451            &SupervisorError::EmptyChildName,
15452        );
15453        assert_validate_children_matches_gate(
15454            vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
15455            &SupervisorError::ChildCaixaInvalid {
15456                caixa: "Worker".into(),
15457                reason: "contains uppercase character 'W' (K8s DNS-1123 label names are lowercase-only; use \"worker\")".into(),
15458            },
15459        );
15460        assert_validate_children_matches_gate(
15461            vec![child("worker", "", RestartPolicy::Permanent)],
15462            &SupervisorError::EmptyChildVersion {
15463                caixa: "worker".into(),
15464            },
15465        );
15466        assert_validate_children_matches_gate(
15467            vec![
15468                child("worker", "^0.1", RestartPolicy::Permanent),
15469                child("worker", "^0.2", RestartPolicy::Transient),
15470            ],
15471            &SupervisorError::DuplicateChildCaixa {
15472                caixa: "worker".into(),
15473            },
15474        );
15475    }
15476
15477    #[test]
15478    fn validate_children_matches_gate_on_versao_invalid_and_clean_pass() {
15479        // Second half of the two-altitude equivalence pin — covers the
15480        // one refusal shape whose reason string is parser-owned
15481        // (`ChildVersaoInvalid`, whose reason comes from the shared
15482        // [`crate::version::parse_requirement`] impl and may drift) and
15483        // the clean-pass canonical fixture. Sibling pin
15484        // `validate_children_matches_gate_on_per_axis_refusal_shapes`
15485        // covers the four equality-comparable refusal shapes.
15486        let s_bad_versao = SupervisorSpec {
15487            estrategia: RestartStrategy::OneForOne,
15488            children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
15489            ..SupervisorSpec::default()
15490        };
15491        let via_gate = s_bad_versao.validate_children().unwrap_err();
15492        let via_validate = s_bad_versao.validate().unwrap_err();
15493        match (&via_gate, &via_validate) {
15494            (
15495                SupervisorError::ChildVersaoInvalid {
15496                    caixa: cg,
15497                    versao: vg,
15498                    ..
15499                },
15500                SupervisorError::ChildVersaoInvalid {
15501                    caixa: cv,
15502                    versao: vv,
15503                    ..
15504                },
15505            ) => {
15506                assert_eq!(cg, "worker", "per-slot gate :caixa carrier");
15507                assert_eq!(vg, "not-a-req", "per-slot gate :versao carrier");
15508                assert_eq!(cv, "worker", "validate() :caixa carrier");
15509                assert_eq!(vv, "not-a-req", "validate() :versao carrier");
15510            }
15511            other => panic!("expected ChildVersaoInvalid on both altitudes, got {other:?}"),
15512        }
15513        assert_eq!(
15514            via_gate, via_validate,
15515            "per-slot gate ≡ validate() on ChildVersaoInvalid full envelope",
15516        );
15517
15518        let s_ok = SupervisorSpec {
15519            estrategia: RestartStrategy::OneForOne,
15520            children: vec![
15521                child("worker-a", "^0.1", RestartPolicy::Permanent),
15522                child("worker-b", "~0.2.3", RestartPolicy::Transient),
15523                child("collector", "*", RestartPolicy::Temporary),
15524            ],
15525            ..SupervisorSpec::default()
15526        };
15527        s_ok.validate_children()
15528            .expect("per-slot gate must accept the clean-pass fixture");
15529        s_ok.validate()
15530            .expect("validate() must accept the clean-pass fixture");
15531    }
15532
15533    #[test]
15534    fn validate_children_is_self_contained_on_children_slot() {
15535        // Self-containment pin: [`SupervisorSpec::validate_children`]
15536        // resolves the per-child cascade against `&self` alone, without
15537        // depending on the peer `:estrategia`/`:max-restarts`/
15538        // `:restart-window` gates having run first — same posture the M3
15539        // peer per-slot gates carry (`validate_membros`,
15540        // `validate_contratos`, `validate_entrada`, `validate_placement`,
15541        // routing through their own oracles rather than borrowing state
15542        // threaded down from `validate`). A future consumer that reaches
15543        // the per-slot gate directly on a spec whose peer slots would
15544        // fail `validate` still surfaces the per-child refusal, not the
15545        // peer refusal.
15546        //
15547        // Construct a spec whose `:max-restarts` is `0` (which would
15548        // trip [`SupervisorError::ZeroMaxRestarts`] at `validate` after
15549        // the partition-dispatch) and whose `:children` carries a
15550        // `DuplicateChildCaixa` shape: the per-slot gate called directly
15551        // must surface `DuplicateChildCaixa`, proving it does not depend
15552        // on the peer `:max-restarts` gate running first.
15553        let s = SupervisorSpec {
15554            estrategia: RestartStrategy::OneForOne,
15555            max_restarts: 0,
15556            restart_window: Some(Duration::from_secs(60)),
15557            children: vec![
15558                child("worker", "^0.1", RestartPolicy::Permanent),
15559                child("worker", "^0.2", RestartPolicy::Transient),
15560            ],
15561        };
15562        assert_eq!(
15563            s.validate_children().unwrap_err(),
15564            SupervisorError::DuplicateChildCaixa {
15565                caixa: "worker".into(),
15566            },
15567            "per-slot gate must resolve per-child refusal directly against \
15568             `&self` — a dependency on the peer `:max-restarts` gate \
15569             running first would surface ZeroMaxRestarts here instead",
15570        );
15571        // The peer gate is still the surface `validate` reaches — pin
15572        // the ordering to establish that `validate_children` truly runs
15573        // last in `validate`'s dispatch, so a direct call bypasses the
15574        // peer gates on any spec whose per-child cascade would fail.
15575        assert_eq!(
15576            s.validate().unwrap_err(),
15577            SupervisorError::ZeroMaxRestarts,
15578            "validate() must surface the peer `:max-restarts` gate before \
15579             reaching the per-child cascade — this pins the dispatch \
15580             ordering the per-slot gate's self-containment complements",
15581        );
15582    }
15583
15584    #[test]
15585    fn child_spec_restart_accessor_is_const_fn() {
15586        // The [`ChildSpec::restart`] per-`:children` restart-decision-
15587        // policy `Copy`-return scalar accessor is declared
15588        // `#[must_use] pub const fn` — matching the sibling M2
15589        // per-`:supervisor` [`SupervisorSpec::estrategia`] (pinned by
15590        // [`supervisor_spec_estrategia_accessor_is_const_fn`] below,
15591        // both converted in this commit), the sibling M2
15592        // per-`:supervisor` [`SupervisorSpec::max_restarts`] (b698ec0)
15593        // `Copy`-`u32` accessor already `pub const fn`, and the peer M3
15594        // mesh-slot per-`:entrada` [`crate::Entrada::port`] (bafa004) /
15595        // per-`:placement` [`crate::Placement::estrategia`] (bafa004)
15596        // `Copy`-return `pub const fn` scalar accessors on the sibling
15597        // M3 surface. Pin the `const`-eval posture here so a future
15598        // accidental downgrade to non-`const` (an added runtime helper
15599        // reachable only from a non-`const` context, an
15600        // `Option<RestartPolicy>`-shape migration on the per-child
15601        // restart-decision axis once heterogeneous per-cluster
15602        // restart-policy overlays land that would silently drop the
15603        // `const` qualifier, a manual hand-rolled shadow) trips at
15604        // caixa-core build time rather than surfacing as a downstream
15605        // `const`-context regression far from the declaration.
15606        //
15607        // Same shape as the sibling M3
15608        // [`crate::aplicacao::tests::placement_estrategia_accessor_is_const_fn`]
15609        // and [`crate::aplicacao::tests::entrada_port_accessor_is_const_fn`]
15610        // (bafa004) pins on the peer M3 mesh-slot `Copy`-return scalar
15611        // accessor axis — the load-bearing witness lives in the
15612        // module-scope `const fn` wrapper `restart_via_const_fn` below:
15613        // a body that calls [`ChildSpec::restart`] under a `const fn`
15614        // signature is well-formed only when the callee is itself
15615        // `const fn`, so any future accidental downgrade of
15616        // [`ChildSpec::restart`] to non-`const` fails at caixa-core
15617        // build time (const-eval E0015 `cannot call non-const method`),
15618        // strictly stronger than a runtime `assert!(CONST)` and
15619        // side-stepping the destructor-in-const restriction that
15620        // blocks direct `const _: RestartPolicy = FIXTURE.restart()`
15621        // items on `ChildSpec`'s `String` carriers.
15622        //
15623        // The runtime body sweeps every closed-set [`RestartPolicy`]
15624        // arm and asserts the wrapped and direct dispatches agree.
15625        const fn restart_via_const_fn(c: &ChildSpec) -> RestartPolicy {
15626            c.restart()
15627        }
15628        for restart in [
15629            RestartPolicy::Permanent,
15630            RestartPolicy::Transient,
15631            RestartPolicy::Temporary,
15632        ] {
15633            let c = ChildSpec {
15634                caixa: "worker".into(),
15635                versao: "^0.1".into(),
15636                restart,
15637            };
15638            assert_eq!(
15639                restart_via_const_fn(&c),
15640                c.restart(),
15641                "const-fn-wrapped and direct dispatch on \
15642                 ChildSpec::restart must agree for {restart:?}",
15643            );
15644            assert_eq!(
15645                c.restart(),
15646                restart,
15647                "ChildSpec::restart must return the storage-side \
15648                 RestartPolicy verbatim for {restart:?} (a violation \
15649                 means the accessor stopped being a raw field-return \
15650                 copy)",
15651            );
15652        }
15653    }
15654
15655    #[test]
15656    fn supervisor_spec_estrategia_accessor_is_const_fn() {
15657        // The [`SupervisorSpec::estrategia`] per-`:supervisor`
15658        // sibling-restart-strategy `Copy`-return scalar accessor is
15659        // declared `#[must_use] pub const fn` — matching the sibling M2
15660        // per-`:children` [`ChildSpec::restart`] (pinned by
15661        // [`child_spec_restart_accessor_is_const_fn`] above, both
15662        // converted in this commit), the sibling M2 per-`:supervisor`
15663        // [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32`
15664        // accessor already `pub const fn`, and mirroring the peer M3
15665        // mesh-slot per-`:placement`
15666        // [`crate::Placement::estrategia`] (bafa004) `Copy`-return
15667        // `pub const fn` scalar accessor whose method-name discipline
15668        // the [`SupervisorSpec::estrategia`] method was authored to
15669        // match. Pin the `const`-eval posture here so a future
15670        // accidental downgrade to non-`const` (an added runtime helper
15671        // reachable only from a non-`const` context, an
15672        // `Option<RestartStrategy>`-shape migration once the substrate
15673        // grows per-cluster strategy overlays that would silently drop
15674        // the `const` qualifier, a manual hand-rolled shadow) trips at
15675        // caixa-core build time rather than surfacing as a downstream
15676        // `const`-context regression far from the declaration.
15677        //
15678        // Same shape as the sibling
15679        // [`child_spec_restart_accessor_is_const_fn`] pin above — the
15680        // load-bearing witness lives in the module-scope `const fn`
15681        // wrapper `estrategia_via_const_fn` below: a body that calls
15682        // [`SupervisorSpec::estrategia`] under a `const fn` signature
15683        // is well-formed only when the callee is itself `const fn`,
15684        // side-stepping the destructor-in-const restriction that would
15685        // otherwise block a direct
15686        // `const _: RestartStrategy = FIXTURE.estrategia()` item on
15687        // `SupervisorSpec`'s `Vec<ChildSpec>` / `Option<Duration>`
15688        // carriers.
15689        //
15690        // The runtime body sweeps every closed-set [`RestartStrategy`]
15691        // arm via [`RestartStrategy::ALL`] and asserts the wrapped and
15692        // direct dispatches agree.
15693        const fn estrategia_via_const_fn(s: &SupervisorSpec) -> RestartStrategy {
15694            s.estrategia()
15695        }
15696        for &estrategia in RestartStrategy::ALL {
15697            let s = SupervisorSpec {
15698                estrategia,
15699                max_restarts: 5,
15700                restart_window: Some(Duration::from_secs(60)),
15701                children: Vec::new(),
15702            };
15703            assert_eq!(
15704                estrategia_via_const_fn(&s),
15705                s.estrategia(),
15706                "const-fn-wrapped and direct dispatch on \
15707                 SupervisorSpec::estrategia must agree for {estrategia:?}",
15708            );
15709            assert_eq!(
15710                s.estrategia(),
15711                estrategia,
15712                "SupervisorSpec::estrategia must return the storage-side \
15713                 RestartStrategy verbatim for {estrategia:?} (a violation \
15714                 means the accessor stopped being a raw field-return \
15715                 copy)",
15716            );
15717        }
15718    }
15719
15720    // Per-variant equivalence pins for the [`supervisor_caixa_only_ctors!`]
15721    // macro definition (see the paired doc-block above the macro
15722    // definition) — every generated `<ctor>(caixa: &str) -> Self`
15723    // constructor folds the uniform `Self::<Variant> { caixa:
15724    // caixa.to_string() }` one-field struct-literal onto one substrate
15725    // primitive. The three per-variant equivalence pins below
15726    // (fail-before-pass-after by construction — a byte-mismatched macro
15727    // arm would trip its equivalence pin first) lock each generated
15728    // constructor to its struct-literal peer under `PartialEq`, so
15729    // every wire-up in [`SupervisorSpec::validate_children`] and
15730    // [`validate_no_self_supervision`] on that variant produces a
15731    // byte-equal `SupervisorError` to the pre-lift open-coded
15732    // struct-literal. The cross-axis pin that follows (non-default
15733    // caixa name) routes the sole constructor input axis through
15734    // `.to_string()`, so the fold does not silently collapse onto a
15735    // fixed name.
15736    //
15737    // Peer of the sibling `<slot>_ctor_matches_tuple_literal_wrap` /
15738    // `<slot>_violation_ctor_matches_struct_literal_wrap` /
15739    // `<slot>_slots_on_non_<owner>_ctor_matches_struct_literal_wrap` /
15740    // `missing_entry_ctor_matches_struct_literal_wrap` /
15741    // `entrada_host_invalid_ctor_matches_struct_literal_wrap` /
15742    // `contrato_wrong_target_ctor_matches_struct_literal_wrap` /
15743    // `contrato_missing_target_ctor_matches_struct_literal_wrap` /
15744    // `<variant>_ctor_matches_struct_literal_wrap` equivalence pins
15745    // on the six sibling ctor families the recent trajectory closed
15746    // on the peer `LayoutError` / `AplicacaoError` envelopes.
15747
15748    #[test]
15749    fn empty_child_version_ctor_matches_struct_literal_wrap() {
15750        assert_eq!(
15751            SupervisorError::empty_child_version("worker"),
15752            SupervisorError::EmptyChildVersion {
15753                caixa: "worker".to_string(),
15754            },
15755            "generated empty_child_version ctor must produce byte-equal \
15756             SupervisorError to the open-coded struct-literal wrap on the \
15757             same &str fixture",
15758        );
15759    }
15760
15761    #[test]
15762    fn duplicate_child_caixa_ctor_matches_struct_literal_wrap() {
15763        assert_eq!(
15764            SupervisorError::duplicate_child_caixa("worker"),
15765            SupervisorError::DuplicateChildCaixa {
15766                caixa: "worker".to_string(),
15767            },
15768            "generated duplicate_child_caixa ctor must produce byte-equal \
15769             SupervisorError to the open-coded struct-literal wrap on the \
15770             same &str fixture",
15771        );
15772    }
15773
15774    #[test]
15775    fn child_supervises_self_ctor_matches_struct_literal_wrap() {
15776        assert_eq!(
15777            SupervisorError::child_supervises_self("orquestra"),
15778            SupervisorError::ChildSupervisesSelf {
15779                caixa: "orquestra".to_string(),
15780            },
15781            "generated child_supervises_self ctor must produce byte-equal \
15782             SupervisorError to the open-coded struct-literal wrap on the \
15783             same &str fixture",
15784        );
15785    }
15786
15787    // Per-variant equivalence pins for the two lifted
15788    // [`SupervisorError::child_caixa_invalid`] /
15789    // [`SupervisorError::child_versao_invalid`] inherent constructors
15790    // (fail-before-pass-after by construction — a byte-mismatched ctor body
15791    // would trip its equivalence pin first). Each pins the ctor output to
15792    // its pre-lift struct-literal peer under `PartialEq`, so every wire-up
15793    // in [`SupervisorSpec::validate_children`] on the two variants
15794    // produces a byte-equal `SupervisorError` to the pre-lift open-coded
15795    // struct-literal on the same scalar fixtures. Peers of the sibling
15796    // `membro_caixa_invalid_ctor_matches_struct_literal_wrap` /
15797    // `entrada_para_invalid_ctor_matches_struct_literal_wrap` / … pins on
15798    // the peer `AplicacaoError` envelope's
15799    // [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold.
15800
15801    #[test]
15802    fn child_caixa_invalid_ctor_matches_struct_literal_wrap() {
15803        let caixa = "Worker";
15804        let reason = "sample reason text";
15805        assert_eq!(
15806            SupervisorError::child_caixa_invalid(caixa, reason),
15807            SupervisorError::ChildCaixaInvalid {
15808                caixa: caixa.to_string(),
15809                reason: reason.to_string(),
15810            },
15811            "lifted child_caixa_invalid ctor must produce byte-equal \
15812             SupervisorError to the open-coded struct-literal wrap on the \
15813             same (&str, reason) fixture",
15814        );
15815    }
15816
15817    #[test]
15818    fn child_versao_invalid_ctor_matches_struct_literal_wrap() {
15819        let caixa = "worker";
15820        let versao = "not-a-req";
15821        let reason = "sample reason text";
15822        assert_eq!(
15823            SupervisorError::child_versao_invalid(caixa, versao, reason),
15824            SupervisorError::ChildVersaoInvalid {
15825                caixa: caixa.to_string(),
15826                versao: versao.to_string(),
15827                reason: reason.to_string(),
15828            },
15829            "lifted child_versao_invalid ctor must produce byte-equal \
15830             SupervisorError to the open-coded struct-literal wrap on the \
15831             same (&str, &str, reason) fixture",
15832        );
15833    }
15834
15835    #[test]
15836    fn supervisor_child_reason_ctors_route_reason_through_into_uniformly() {
15837        // Cross-axis pin: sweep the two lifted `{ …, reason }` ctors
15838        // against a `&str`-literal vs. `format!(…)` reason input to pin
15839        // both constructors accept the `impl Into<String>` bound
15840        // uniformly, so neither wire-up site drifts under a per-arm
15841        // wrapper transformation on the caller-side `reason` axis. Peer
15842        // of the sibling
15843        // `aplicacao_field_reason_ctors_route_reason_through_into_uniformly`
15844        // sweep on the peer `AplicacaoError` envelope.
15845        let via_literal = "literal reason text";
15846        let via_format = format!("{} reason text", "literal");
15847        assert_eq!(
15848            SupervisorError::child_caixa_invalid("Worker", via_literal),
15849            SupervisorError::child_caixa_invalid("Worker", via_format.clone()),
15850        );
15851        assert_eq!(
15852            SupervisorError::child_versao_invalid("worker", "not-a-req", via_literal),
15853            SupervisorError::child_versao_invalid("worker", "not-a-req", via_format),
15854        );
15855    }
15856
15857    #[test]
15858    fn supervisor_caixa_only_ctors_route_caixa_through_to_string() {
15859        // Cross-axis pin: sweep the sole constructor input axis (`caixa:
15860        // &str`) through a non-default fixture name against every
15861        // generated arm in the [`supervisor_caixa_only_ctors!`] macro,
15862        // so any wrapper-side lowercase / trim / truncate / re-order on
15863        // the `caixa.to_string()` sole-field construction surfaces
15864        // here rather than at a downstream diagnostic-shape mismatch.
15865        // Peer of the sibling `nome_only_ctor_routes_caixa_through_
15866        // nome_accessor` / `entrada_host_invalid_ctor_routes_host_
15867        // through_to_string` / `contrato_target_ctors_route_edge_
15868        // triple_through_verbatim` / `contrato_empty_pair_ctors_
15869        // route_edge_pair_through_verbatim` cross-axis routing pins on
15870        // the peer `LayoutError` / `AplicacaoError` envelopes; extended
15871        // here onto the `SupervisorError` `{ caixa: String }` envelope
15872        // so every substrate-primitive ctor family in caixa-core
15873        // guarantees the sole-field construction routes the caller's
15874        // `&str` through `.to_string()` verbatim.
15875        let name = "cache-v2";
15876        assert_eq!(
15877            SupervisorError::empty_child_version(name),
15878            SupervisorError::EmptyChildVersion {
15879                caixa: name.to_string(),
15880            },
15881        );
15882        assert_eq!(
15883            SupervisorError::duplicate_child_caixa(name),
15884            SupervisorError::DuplicateChildCaixa {
15885                caixa: name.to_string(),
15886            },
15887        );
15888        assert_eq!(
15889            SupervisorError::child_supervises_self(name),
15890            SupervisorError::ChildSupervisesSelf {
15891                caixa: name.to_string(),
15892            },
15893        );
15894    }
15895
15896    // ── supervisor_scalar_ctors! per-variant + cross-axis pins ──────────────
15897    //
15898    // Per-variant byte-equality pins guaranteeing every generated ctor arm in
15899    // the [`supervisor_scalar_ctors!`] macro produces a `SupervisorError`
15900    // structurally identical to the pre-lift `Self::<variant> { <field>: <val> }`
15901    // one-line struct-literal on the same `Copy`-`RestartStrategy | u32 |
15902    // Duration` fixture, plus one cross-axis sweep that routes each per-variant
15903    // `<field>: <ty>` scalar through the sole `$field:ident: $ty:ty` axis the
15904    // macro exposes so any wrapper-side truncation / re-order / silent `.into()`
15905    // / silent constant-substitution on any one variant surfaces here rather
15906    // than at a downstream per-`:supervisor` diagnostic-shape drift. Peer of the
15907    // sibling per-variant pins on `aplicacao_policy_scalar_ctors!` (7ef425e,
15908    // the 8-variant `AplicacaoError` `{ <field>: Duration | u32 }` fold on the
15909    // per-`:politicas` per-axis cap / canonical-form arms), plus the sibling
15910    // `supervisor_caixa_only_ctors!` (db09650), `SupervisorError::
15911    // {child_caixa_invalid,child_versao_invalid}` (d2ef2ec), and the peer
15912    // `DepError` / `AplicacaoError` / `LayoutError` / `LimitsError` /
15913    // `BehaviorError` / `UpgradeError` per-envelope ctor-macro pins.
15914    #[test]
15915    fn no_children_ctor_matches_struct_literal_wrap() {
15916        let estrategia = RestartStrategy::OneForAll;
15917        assert_eq!(
15918            SupervisorError::no_children(estrategia),
15919            SupervisorError::NoChildren { estrategia },
15920            "generated no_children ctor must produce byte-equal \
15921             `SupervisorError::NoChildren` to the pre-lift struct-literal wrap \
15922             on the same `Copy`-`RestartStrategy` fixture",
15923        );
15924    }
15925
15926    #[test]
15927    fn max_restarts_exceeds_cap_ctor_matches_struct_literal_wrap() {
15928        let max_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 1;
15929        assert_eq!(
15930            SupervisorError::max_restarts_exceeds_cap(max_restarts),
15931            SupervisorError::MaxRestartsExceedsCap { max_restarts },
15932            "generated max_restarts_exceeds_cap ctor must produce byte-equal \
15933             `SupervisorError::MaxRestartsExceedsCap` to the pre-lift \
15934             struct-literal wrap on the same `Copy`-`u32` fixture",
15935        );
15936    }
15937
15938    #[test]
15939    fn restart_window_not_canonical_ctor_matches_struct_literal_wrap() {
15940        let window = Duration::from_micros(1_500);
15941        assert_eq!(
15942            SupervisorError::restart_window_not_canonical(window),
15943            SupervisorError::RestartWindowNotCanonical { window },
15944            "generated restart_window_not_canonical ctor must produce \
15945             byte-equal `SupervisorError::RestartWindowNotCanonical` to the \
15946             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
15947        );
15948    }
15949
15950    #[test]
15951    fn restart_window_exceeds_cap_ctor_matches_struct_literal_wrap() {
15952        let window = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
15953        assert_eq!(
15954            SupervisorError::restart_window_exceeds_cap(window),
15955            SupervisorError::RestartWindowExceedsCap { window },
15956            "generated restart_window_exceeds_cap ctor must produce \
15957             byte-equal `SupervisorError::RestartWindowExceedsCap` to the \
15958             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
15959        );
15960    }
15961
15962    #[test]
15963    fn supervisor_scalar_ctors_route_field_through_copy_uniformly() {
15964        // Cross-axis routing pin: sweep each generated `<field>: <ty>`
15965        // constructor input axis through a non-default `Copy` fixture against
15966        // every arm in the [`supervisor_scalar_ctors!`] macro, so any wrapper-
15967        // side silent `.into()` / silent constant-substitution / silent field
15968        // re-name away from the canonical `estrategia | max_restarts | window`
15969        // axes on any one variant, or a `RestartStrategy | u32 | Duration`
15970        // axis silently rerouted through some other `Copy` coercion, surfaces
15971        // here rather than at a downstream per-`:supervisor` diagnostic-shape
15972        // drift. Peer of the sibling
15973        // `aplicacao_policy_scalar_ctors_route_field_through_copy_uniformly`
15974        // (7ef425e) cross-axis routing pin on the peer `AplicacaoError`
15975        // envelope's per-`:politicas` per-axis ctor family, extended here onto
15976        // the last M2 per-`:supervisor` `Copy`-scalar `SupervisorError`
15977        // variant family folded onto a substrate primitive.
15978        //
15979        // Fixtures picked out of each variant's accept-set boundary rather
15980        // than the default value so a silent constant-substitution to a per-
15981        // variant sentinel surfaces here on the structural-equality assertion.
15982        // The `RestartStrategy` fixture picks `RestForOne` (a non-default arm
15983        // that isn't the `OneForOne` [`SUPERVISOR_ESTRATEGIA_DEFAULT`] and
15984        // isn't the `SimpleOneForOne` arm the sibling
15985        // `SimpleOneForOneWithStaticChildren` unit variant intercepts). The
15986        // `max_restarts` fixture picks an above-cap magnitude the cap arm
15987        // rejects; the two `Duration` fixtures pick the sub-millisecond and
15988        // above-cap ends of the `:restart-window` canonical-form + cap
15989        // bracket respectively.
15990        let estrategia = RestartStrategy::RestForOne;
15991        let above_cap_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 137;
15992        let sub_ms = Duration::from_micros(1_500);
15993        let above_hour = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
15994        assert_eq!(
15995            SupervisorError::no_children(estrategia),
15996            SupervisorError::NoChildren { estrategia },
15997        );
15998        assert_eq!(
15999            SupervisorError::max_restarts_exceeds_cap(above_cap_restarts),
16000            SupervisorError::MaxRestartsExceedsCap {
16001                max_restarts: above_cap_restarts,
16002            },
16003        );
16004        assert_eq!(
16005            SupervisorError::restart_window_not_canonical(sub_ms),
16006            SupervisorError::RestartWindowNotCanonical { window: sub_ms },
16007        );
16008        assert_eq!(
16009            SupervisorError::restart_window_exceeds_cap(above_hour),
16010            SupervisorError::RestartWindowExceedsCap { window: above_hour },
16011        );
16012    }
16013
16014    #[test]
16015    fn restart_strategy_try_from_bytes_routes_through_from_wire_accessor() {
16016        // Fail-before-pass-after byte-parity pin on the newly lifted
16017        // `impl TryFrom<&[u8]> for RestartStrategy` — asserts the trait-
16018        // idiomatic byte-view reverse-projection standard-library impl
16019        // and the substrate-primitive [`RestartStrategy::from_wire`]
16020        // `Option<Self>` accessor resolve to the same four-arm
16021        // `PascalCase` wire accept-set across every arm the exhaustive
16022        // [`RestartStrategy::ALL`] slice enumerates. Extends the
16023        // substrate-wide trait-idiomatic byte-view reverse-projection
16024        // axis onto the first M2-OTP-shape supervisor-slot closed-set
16025        // fieldless typed enum peer — mirror of the paired
16026        // [`TryFrom<&str> for RestartStrategy`] str-view reverse-
16027        // projection axis on the same enum, and the byte-view companion
16028        // of the pre-existing byte-owned reverse-projection family
16029        // ([`AsRef<[u8]>`], [`From<RestartStrategy> for Vec<u8>`],
16030        // [`From<&RestartStrategy> for Vec<u8>`]) on this same enum.
16031        // Peer of the sibling
16032        // [`crate::kind::tests::caixa_kind_try_from_bytes_routes_through_from_wire_accessor`]
16033        // (18d1940),
16034        // [`crate::dialeto::tests::caixa_dialeto_try_from_bytes_routes_through_from_wire_accessor`]
16035        // (d102cb8), and
16036        // [`crate::dep::tests::dep_list_try_from_bytes_routes_through_from_wire_accessor`]
16037        // (b8f25d5) — tracks the "route through `from_wire` via
16038        // `std::str::from_utf8`" discipline the first-mover established.
16039        //
16040        // Rust's standard library carries no blanket
16041        // `impl<T: for<'a> TryFrom<&'a str>> TryFrom<&[u8]> for T`, so
16042        // a two-hop composition through [`std::str::from_utf8`] + the
16043        // paired [`TryFrom<&str>`] axis is reachable through the pre-
16044        // existing str-view reverse-projection axis alone. But that
16045        // two-hop shape has no compile-time link back to the byte-view
16046        // reverse-projection axis, forces every downstream
16047        // `<T: for<'a> TryFrom<&'a [u8]>>`-bound consumer to open-code
16048        // the composition at every call site, and admits a silent split
16049        // whenever a future call site takes a sibling byte-projection
16050        // axis whose parse arm-set carries no compile-time byte-view
16051        // surface. This impl closes the byte-view reverse-projection
16052        // axis at the substrate-primitive [`RestartStrategy::from_wire`]
16053        // accessor so every future `<T: for<'a> TryFrom<&'a [u8]>>`-
16054        // bound consumer reaches the same four-arm `PascalCase` wire
16055        // accept-set through one trait dispatch.
16056        for &variant in RestartStrategy::ALL {
16057            let wire_bytes: &[u8] = variant.as_str().as_bytes();
16058            assert_eq!(
16059                <RestartStrategy as TryFrom<&[u8]>>::try_from(wire_bytes),
16060                Ok(variant),
16061                "TryFrom<&[u8]> impl on RestartStrategy must round-trip \
16062                 RestartStrategy::{variant:?}.as_str().as_bytes() back to \
16063                 Ok(RestartStrategy::{variant:?}) — divergence from \
16064                 RestartStrategy::from_wire signals a silent detour off \
16065                 the substrate-primitive accessor"
16066            );
16067            assert_eq!(
16068                <RestartStrategy as TryFrom<&[u8]>>::try_from(wire_bytes).ok(),
16069                RestartStrategy::from_wire(variant.as_str()),
16070                "TryFrom<&[u8]> ok()-projection on \
16071                 RestartStrategy::{variant:?}.as_str().as_bytes() must \
16072                 byte-equal RestartStrategy::from_wire on the paired \
16073                 &str input"
16074            );
16075            // Cross-axis witness: the byte-view reverse-projection axis
16076            // must agree with the paired str-view reverse-projection
16077            // axis ([`TryFrom<&str>`]) on every accepted arm — the two
16078            // reverse paths share one `PascalCase` accept-set through
16079            // the substrate-primitive `from_wire` accessor.
16080            let via_str: Result<RestartStrategy, ()> =
16081                <RestartStrategy as TryFrom<&str>>::try_from(variant.as_str());
16082            let via_bytes: Result<RestartStrategy, ()> =
16083                <RestartStrategy as TryFrom<&[u8]>>::try_from(wire_bytes);
16084            assert_eq!(
16085                via_bytes, via_str,
16086                "TryFrom<&[u8]> and TryFrom<&str> reverse-projection \
16087                 axes on RestartStrategy must agree on \
16088                 RestartStrategy::{variant:?} — divergence signals the \
16089                 byte-view and str-view reverse paths have drifted off \
16090                 the same substrate-primitive from_wire accessor"
16091            );
16092            // Forward/reverse byte-view cross-axis witness: feed the
16093            // paired [`AsRef<[u8]>`] byte-tail back through the new
16094            // impl and assert it round-trips to the originating arm.
16095            let via_asref: &[u8] = <RestartStrategy as AsRef<[u8]>>::as_ref(&variant);
16096            assert_eq!(
16097                <RestartStrategy as TryFrom<&[u8]>>::try_from(via_asref),
16098                Ok(variant),
16099                "TryFrom<&[u8]> ∘ AsRef<[u8]> must round-trip \
16100                 RestartStrategy::{variant:?} — divergence signals the \
16101                 forward and reverse byte-view axes have drifted off \
16102                 the same substrate-primitive as_str/from_wire pair"
16103            );
16104        }
16105    }
16106
16107    #[test]
16108    fn restart_strategy_try_from_bytes_rejects_unknown_and_non_utf8_bytes() {
16109        // Rejection witness on the `impl TryFrom<&[u8]> for
16110        // RestartStrategy` — sweeps two rejection paths the byte-view
16111        // reverse-projection axis collapses onto the single unit-error
16112        // `Err(())` return: the invalid-UTF-8 rejection path
16113        // ([`std::str::from_utf8`] returns `Err` before
16114        // [`RestartStrategy::from_wire`] runs) and the valid-UTF-8-but-
16115        // unknown-wire rejection path ([`RestartStrategy::from_wire`]
16116        // returns `None` on a byte-string outside the four-arm
16117        // `PascalCase` accept-set). Both must reject, so a future
16118        // accidental widening of the trait impl's accept-set (a case-
16119        // fold path, a silent acceptance of the kebab-case dispatcher-
16120        // catalog byte-strings on this axis — which would collide the
16121        // two-axis wire/catalog split the sibling
16122        // [`RestartStrategy::from_wire`] doc block makes load-bearing —
16123        // a `#[serde(rename_all = "…")]` attribute drift that widens
16124        // the parse arm-set silently, a stray fallback that maps
16125        // invalid UTF-8 onto a default arm rather than the trait-
16126        // idiomatic `Err(())`) trips at caixa-core test time. Peer of
16127        // the sibling
16128        // [`crate::kind::tests::caixa_kind_try_from_bytes_rejects_unknown_and_non_utf8_bytes`]
16129        // (18d1940),
16130        // [`crate::dialeto::tests::caixa_dialeto_try_from_bytes_rejects_unknown_and_non_utf8_bytes`]
16131        // (d102cb8), and
16132        // [`crate::dep::tests::dep_list_try_from_bytes_rejects_unknown_and_non_utf8_bytes`]
16133        // (b8f25d5) rejection witnesses.
16134        //
16135        // Non-UTF-8 candidates:
16136        //   - a lone 0xFF byte (never valid as a UTF-8 leading byte)
16137        //   - a lone 0x80 continuation byte with no leading byte
16138        //   - a truncated multi-byte sequence (0xC3 without its continuation)
16139        //   - a UTF-16 BOM-style byte pair the UTF-8 validator rejects
16140        //   - a UTF-16 surrogate half rejected by UTF-8
16141        let non_utf8_rejected: &[&[u8]] = &[
16142            &[0xFF],
16143            &[0x80],
16144            &[0xC3],
16145            &[0xFF, 0xFE],
16146            &[0xED, 0xA0, 0x80],
16147        ];
16148        for &input in non_utf8_rejected {
16149            assert_eq!(
16150                <RestartStrategy as TryFrom<&[u8]>>::try_from(input),
16151                Err(()),
16152                "TryFrom<&[u8]> impl on RestartStrategy must reject the \
16153                 non-UTF-8 byte-sequence {input:?} with Err(()) — \
16154                 silent acceptance signals the UTF-8 validation path \
16155                 collapsed onto a default arm rather than the trait-\
16156                 idiomatic unit-error"
16157            );
16158        }
16159        // Valid-UTF-8-but-unknown-wire candidates mirror the corpus
16160        // the sibling `restart_strategy_try_from_str_rejects_unknown_byte_strings`
16161        // (5b828ed) str-view rejection witness already pins on the
16162        // paired [`TryFrom<&str>`] axis: the empty byte-string,
16163        // whitespace-only padding, the kebab-case dispatcher-catalog
16164        // byte-strings on the sibling axis the pre-existing
16165        // [`std::str::FromStr`] impl the [`gen_platform::FromStrKind`]
16166        // derive installs parses onto (a caller who confuses the two
16167        // axes trips here rather than at a downstream K8s-CR round-
16168        // trip miss), lowercase / uppercase / mixed-case folds of each
16169        // `PascalCase` arm, whitespace-padded / trailing-newline /
16170        // quote-wrapped forms, and plausible-but-wrong English rebrand
16171        // candidates.
16172        let unknown_wire_rejected: &[&[u8]] = &[
16173            b"",
16174            b" ",
16175            b"\n",
16176            b"\t",
16177            b"one-for-one",
16178            b"one-for-all",
16179            b"rest-for-one",
16180            b"simple-one-for-one",
16181            b"oneforone",
16182            b"one_for_one",
16183            b"OneForOnes",
16184            b"ONEFORONE",
16185            b"oneforall",
16186            b"restforone",
16187            b"simpleoneforone",
16188            b"OneForOne ",
16189            b" OneForOne",
16190            b" OneForAll ",
16191            b"OneForOne\n",
16192            b"RestForOne\t",
16193            b"OneForEach",
16194            b"AllForOne",
16195            b"one for one",
16196            b"\"OneForOne\"",
16197            b"?",
16198        ];
16199        for &input in unknown_wire_rejected {
16200            assert_eq!(
16201                <RestartStrategy as TryFrom<&[u8]>>::try_from(input),
16202                Err(()),
16203                "TryFrom<&[u8]> impl on RestartStrategy must reject the \
16204                 valid-UTF-8-but-unknown-wire byte-string {input:?} \
16205                 with Err(()) — silent acceptance signals an accept-\
16206                 set widening off the paired RestartStrategy::from_wire \
16207                 resolver"
16208            );
16209            // Cross-axis witness: on a byte-string that is valid UTF-8,
16210            // the byte-view reverse-projection axis must agree with the
16211            // paired str-view reverse-projection axis
16212            // ([`TryFrom<&str>`]) — both route through the same
16213            // [`RestartStrategy::from_wire`] resolver, so the two
16214            // rejection paths align by construction.
16215            if let Ok(s) = std::str::from_utf8(input) {
16216                assert_eq!(
16217                    <RestartStrategy as TryFrom<&[u8]>>::try_from(input),
16218                    <RestartStrategy as TryFrom<&str>>::try_from(s),
16219                    "TryFrom<&[u8]> and TryFrom<&str> reverse-\
16220                     projection axes on RestartStrategy must agree on \
16221                     the valid-UTF-8 input {input:?} — divergence \
16222                     signals the two reverse paths have drifted off \
16223                     the same substrate-primitive from_wire accessor"
16224                );
16225            }
16226        }
16227    }
16228
16229    #[test]
16230    fn restart_strategy_try_from_vec_bytes_routes_through_borrowed_byte_view_axis() {
16231        // Fail-before-pass-after byte-parity pin on the newly lifted
16232        // `impl TryFrom<Vec<u8>> for RestartStrategy` — asserts the trait-
16233        // idiomatic owned-byte-vec reverse-projection standard-library
16234        // impl and the sibling borrowed-input [`TryFrom<&[u8]>`] axis
16235        // resolve to the same four-arm `PascalCase` wire accept-set
16236        // across every arm the exhaustive [`RestartStrategy::ALL`] slice
16237        // enumerates. Extends the substrate-wide trait-idiomatic byte-
16238        // owned reverse-projection axis onto the first M2-OTP-shape
16239        // supervisor-slot closed-set fieldless typed enum peer — owned-
16240        // input mirror of the paired [`TryFrom<&[u8]>`] byte-view
16241        // reverse-projection axis (c699a83), and byte-owned reverse
16242        // companion of the pre-existing byte-owned *forward*-projection
16243        // pair ([`From<RestartStrategy> for Vec<u8>`],
16244        // [`From<&RestartStrategy> for Vec<u8>`]) on this same enum.
16245        // Peer of the sibling first-mover
16246        // [`crate::kind::tests::caixa_kind_try_from_vec_bytes_routes_through_borrowed_byte_view_axis`]
16247        // (99c2849) on the [`crate::CaixaKind`] closed-set typed-enum
16248        // peer, the sibling second-mover
16249        // [`crate::dialeto::tests::caixa_dialeto_try_from_vec_bytes_routes_through_borrowed_byte_view_axis`]
16250        // (83a1526) on the [`crate::CaixaDialeto`] peer, and the sibling
16251        // third-mover
16252        // [`crate::dep::tests::dep_list_try_from_vec_bytes_routes_through_borrowed_byte_view_axis`]
16253        // (42091cb) on the [`crate::dep::DepList`] peer — tracks the
16254        // "delegate through `TryFrom<&[u8]>` on the `Vec<u8>::as_slice`
16255        // borrow" discipline the first-mover established.
16256        //
16257        // Rust's standard library carries no blanket
16258        // `impl<T: for<'a> TryFrom<&'a [u8]>> TryFrom<Vec<u8>> for T`,
16259        // so an owned-byte-vec caller otherwise picks between an open-
16260        // coded `<T as TryFrom<&[u8]>>::try_from(bytes.as_slice())` at
16261        // every call site whose type bounds have no compile-time link
16262        // back to the byte-owned reverse-projection axis, or a
16263        // `String::from_utf8(bytes)` two-hop shape whose error surface
16264        // leaks the standard-library `FromUtf8Error` type. This impl
16265        // closes the byte-owned reverse-projection axis at the
16266        // substrate-primitive [`RestartStrategy::from_wire`] accessor so
16267        // every future `<T: TryFrom<Vec<u8>>>`-bound owned-byte-vec
16268        // consumer reaches the same four-arm `PascalCase` wire accept-
16269        // set through one trait dispatch.
16270        for &variant in RestartStrategy::ALL {
16271            let wire_bytes: Vec<u8> = variant.as_str().as_bytes().to_vec();
16272            assert_eq!(
16273                <RestartStrategy as TryFrom<Vec<u8>>>::try_from(wire_bytes.clone()),
16274                Ok(variant),
16275                "TryFrom<Vec<u8>> impl on RestartStrategy must round-trip \
16276                 RestartStrategy::{variant:?}.as_str().as_bytes().to_vec() \
16277                 back to Ok(RestartStrategy::{variant:?}) — divergence \
16278                 from the sibling TryFrom<&[u8]> axis signals a silent \
16279                 detour off the substrate-primitive from_wire accessor"
16280            );
16281            // Cross-axis witness: the owned-byte-vec reverse-projection
16282            // axis must agree with the borrowed byte-slice reverse-
16283            // projection axis on every accepted arm — the two axes share
16284            // one `PascalCase` wire vocabulary through the substrate-
16285            // primitive `from_wire` accessor, and the owned-input axis
16286            // delegates to the borrowed peer by design.
16287            let via_owned: Result<RestartStrategy, ()> =
16288                <RestartStrategy as TryFrom<Vec<u8>>>::try_from(wire_bytes.clone());
16289            let via_borrowed: Result<RestartStrategy, ()> =
16290                <RestartStrategy as TryFrom<&[u8]>>::try_from(wire_bytes.as_slice());
16291            assert_eq!(
16292                via_owned, via_borrowed,
16293                "TryFrom<Vec<u8>> and TryFrom<&[u8]> reverse-projection \
16294                 axes on RestartStrategy must agree on \
16295                 RestartStrategy::{variant:?} — divergence signals the \
16296                 owned-input and borrowed-input byte-view reverse paths \
16297                 have drifted off the same substrate-primitive \
16298                 from_wire accessor"
16299            );
16300            // Cross-axis witness against the paired str-view reverse
16301            // axis ([`TryFrom<&str>`]) — the three reverse paths (str-
16302            // view, byte-view borrowed, byte-view owned) share one
16303            // substrate primitive.
16304            let via_str: Result<RestartStrategy, ()> =
16305                <RestartStrategy as TryFrom<&str>>::try_from(variant.as_str());
16306            assert_eq!(
16307                via_owned, via_str,
16308                "TryFrom<Vec<u8>> and TryFrom<&str> reverse-projection \
16309                 axes on RestartStrategy must agree on \
16310                 RestartStrategy::{variant:?} — divergence signals the \
16311                 byte-owned and str-view reverse paths have drifted off \
16312                 the same substrate-primitive from_wire accessor"
16313            );
16314            // Four-corner witness: because [`RestartStrategy`] carries
16315            // no wire-vs-diagnostic split (as_str and from_wire share
16316            // one `PascalCase` byte-vocabulary — unlike the sibling
16317            // [`crate::CaixaKind`] whose peer test deliberately declines
16318            // this witness), the byte-owned reverse-projection axis on
16319            // this enum *does* round-trip against the paired byte-owned
16320            // forward-projection pair. Pin every corner of the {owned-
16321            // input, borrowed-input} × {From<Self> → Vec<u8>,
16322            // From<&Self> → Vec<u8>} square onto the same Ok(variant)
16323            // return so a future accident that drops one corner off the
16324            // substrate-primitive accessor trips here.
16325            let owned_forward: Vec<u8> = <Vec<u8> as From<RestartStrategy>>::from(variant);
16326            let borrowed_forward: Vec<u8> = <Vec<u8> as From<&RestartStrategy>>::from(&variant);
16327            assert_eq!(
16328                owned_forward, wire_bytes,
16329                "From<RestartStrategy> for Vec<u8> forward projection on \
16330                 RestartStrategy::{variant:?} must byte-equal \
16331                 variant.as_str().as_bytes().to_vec() — divergence \
16332                 signals the paired forward pair drifted off the \
16333                 substrate-primitive as_str accessor"
16334            );
16335            assert_eq!(
16336                borrowed_forward, wire_bytes,
16337                "From<&RestartStrategy> for Vec<u8> forward projection \
16338                 on &RestartStrategy::{variant:?} must byte-equal \
16339                 variant.as_str().as_bytes().to_vec() — divergence \
16340                 signals the paired forward pair drifted off the \
16341                 substrate-primitive as_str accessor"
16342            );
16343            assert_eq!(
16344                <RestartStrategy as TryFrom<Vec<u8>>>::try_from(owned_forward.clone()),
16345                Ok(variant),
16346                "Four-corner round-trip on RestartStrategy::{variant:?} \
16347                 through From<RestartStrategy> for Vec<u8> then \
16348                 TryFrom<Vec<u8>> for RestartStrategy must return \
16349                 Ok(variant) — divergence signals the byte-owned \
16350                 forward pair and the byte-owned reverse axis have \
16351                 drifted apart"
16352            );
16353            assert_eq!(
16354                <RestartStrategy as TryFrom<Vec<u8>>>::try_from(borrowed_forward),
16355                Ok(variant),
16356                "Four-corner round-trip on RestartStrategy::{variant:?} \
16357                 through From<&RestartStrategy> for Vec<u8> then \
16358                 TryFrom<Vec<u8>> for RestartStrategy must return \
16359                 Ok(variant) — divergence signals the borrowed-input \
16360                 forward corner and the owned-input reverse corner have \
16361                 drifted apart"
16362            );
16363        }
16364    }
16365
16366    #[test]
16367    fn restart_strategy_try_from_vec_bytes_rejects_unknown_and_non_utf8_bytes() {
16368        // Rejection witness on the `impl TryFrom<Vec<u8>> for
16369        // RestartStrategy` — sweeps the same two rejection paths the
16370        // sibling borrowed `TryFrom<&[u8]>` axis collapses onto the
16371        // single unit-error return: the invalid-UTF-8 rejection path
16372        // (`std::str::from_utf8` on the underlying byte-slice returns
16373        // `Err` before [`RestartStrategy::from_wire`] runs) and the
16374        // valid-UTF-8-but-unknown-wire rejection path
16375        // ([`RestartStrategy::from_wire`] returns `None` on a byte-
16376        // string outside the four-arm `PascalCase` accept-set). Both
16377        // must reject so a future accidental widening of the trait
16378        // impl's accept-set (a case-fold path, a silent acceptance of
16379        // the kebab-case dispatcher-catalog byte-strings on this axis —
16380        // which would collide the two-axis wire/catalog split the
16381        // sibling [`RestartStrategy::from_wire`] doc block makes load-
16382        // bearing — a `#[serde(rename_all = "…")]` attribute drift that
16383        // widens the parse arm-set silently, a stray
16384        // `String::from_utf8_lossy` detour that widens the input
16385        // surface with the U+FFFD replacement character, an
16386        // `Option::unwrap_or_default`-shape fallback that maps invalid
16387        // UTF-8 onto a default arm rather than the trait-idiomatic
16388        // `Err(())`) trips at caixa-core test time. Peer of the sibling
16389        // first-mover
16390        // [`crate::kind::tests::caixa_kind_try_from_vec_bytes_rejects_unknown_and_non_utf8_bytes`]
16391        // (99c2849) on the [`crate::CaixaKind`] peer, the sibling
16392        // second-mover
16393        // [`crate::dialeto::tests::caixa_dialeto_try_from_vec_bytes_rejects_unknown_and_non_utf8_bytes`]
16394        // (83a1526) on the [`crate::CaixaDialeto`] peer, and the
16395        // sibling third-mover
16396        // [`crate::dep::tests::dep_list_try_from_vec_bytes_rejects_unknown_and_non_utf8_bytes`]
16397        // (42091cb) on the [`crate::dep::DepList`] peer rejection
16398        // witnesses.
16399        let non_utf8_rejected: &[&[u8]] = &[
16400            &[0xFF],
16401            &[0x80],
16402            &[0xC3],
16403            &[0xFF, 0xFE],
16404            &[0xED, 0xA0, 0x80], // UTF-16 surrogate half — rejected by UTF-8
16405        ];
16406        for &input in non_utf8_rejected {
16407            let owned: Vec<u8> = input.to_vec();
16408            assert_eq!(
16409                <RestartStrategy as TryFrom<Vec<u8>>>::try_from(owned),
16410                Err(()),
16411                "TryFrom<Vec<u8>> impl on RestartStrategy must reject \
16412                 the non-UTF-8 byte-sequence {input:?} with Err(()) — \
16413                 silent acceptance signals the UTF-8 validation path \
16414                 collapsed onto a default arm rather than the trait-\
16415                 idiomatic unit-error"
16416            );
16417            // Cross-axis witness: the owned-input axis must agree with
16418            // the borrowed-input axis on every rejected input.
16419            assert_eq!(
16420                <RestartStrategy as TryFrom<Vec<u8>>>::try_from(input.to_vec()),
16421                <RestartStrategy as TryFrom<&[u8]>>::try_from(input),
16422                "TryFrom<Vec<u8>> and TryFrom<&[u8]> reverse-projection \
16423                 axes on RestartStrategy must agree on the non-UTF-8 \
16424                 input {input:?} — divergence signals the owned-input \
16425                 and borrowed-input byte-view reverse paths have drifted \
16426                 off the same substrate-primitive from_wire accessor"
16427            );
16428        }
16429        // Valid-UTF-8-but-unknown-wire candidates mirror the corpus the
16430        // sibling borrowed-input rejection witness
16431        // [`restart_strategy_try_from_bytes_rejects_unknown_and_non_utf8_bytes`]
16432        // (c699a83) already pins on the paired byte-view axis: the
16433        // empty byte-string, whitespace-only padding, the kebab-case
16434        // dispatcher-catalog byte-strings on the sibling axis the pre-
16435        // existing [`std::str::FromStr`] impl the
16436        // [`gen_platform::FromStrKind`] derive installs parses onto (a
16437        // caller who confuses the two axes trips here rather than at a
16438        // downstream K8s-CR round-trip miss), lowercase / uppercase /
16439        // mixed-case folds of each `PascalCase` arm, whitespace-padded
16440        // / trailing-newline / quote-wrapped forms, and plausible-but-
16441        // wrong English rebrand candidates.
16442        let unknown_wire_rejected: &[&[u8]] = &[
16443            b"",
16444            b" ",
16445            b"\n",
16446            b"\t",
16447            b"one-for-one",
16448            b"one-for-all",
16449            b"rest-for-one",
16450            b"simple-one-for-one",
16451            b"oneforone",
16452            b"one_for_one",
16453            b"OneForOnes",
16454            b"ONEFORONE",
16455            b"oneforall",
16456            b"restforone",
16457            b"simpleoneforone",
16458            b"OneForOne ",
16459            b" OneForOne",
16460            b" OneForAll ",
16461            b"OneForOne\n",
16462            b"RestForOne\t",
16463            b"OneForEach",
16464            b"AllForOne",
16465            b"one for one",
16466            b"\"OneForOne\"",
16467            b"?",
16468        ];
16469        for &input in unknown_wire_rejected {
16470            let owned: Vec<u8> = input.to_vec();
16471            assert_eq!(
16472                <RestartStrategy as TryFrom<Vec<u8>>>::try_from(owned),
16473                Err(()),
16474                "TryFrom<Vec<u8>> impl on RestartStrategy must reject \
16475                 the valid-UTF-8-but-unknown-wire byte-string {input:?} \
16476                 with Err(()) — silent acceptance signals an accept-\
16477                 set widening off the paired RestartStrategy::from_wire \
16478                 resolver"
16479            );
16480            // Cross-axis witness against the borrowed byte-view axis:
16481            // the two paths must agree by construction, since the owned
16482            // axis delegates to the borrowed peer.
16483            assert_eq!(
16484                <RestartStrategy as TryFrom<Vec<u8>>>::try_from(input.to_vec()),
16485                <RestartStrategy as TryFrom<&[u8]>>::try_from(input),
16486                "TryFrom<Vec<u8>> and TryFrom<&[u8]> reverse-projection \
16487                 axes on RestartStrategy must agree on the valid-UTF-8-\
16488                 but-unknown-wire input {input:?} — divergence signals \
16489                 the owned-input and borrowed-input byte-view reverse \
16490                 paths have drifted off the same substrate-primitive \
16491                 from_wire accessor"
16492            );
16493        }
16494    }
16495
16496    #[test]
16497    fn restart_policy_try_from_bytes_routes_through_from_wire_accessor() {
16498        // Fail-before-pass-after byte-parity pin on the newly lifted
16499        // `impl TryFrom<&[u8]> for RestartPolicy` — asserts the trait-
16500        // idiomatic byte-view reverse-projection standard-library impl
16501        // and the substrate-primitive [`RestartPolicy::from_wire`]
16502        // `Option<Self>` accessor resolve to the same three-arm
16503        // `PascalCase` wire accept-set across every arm the exhaustive
16504        // [`RestartPolicy::ALL`] slice enumerates. Closes the substrate-
16505        // wide trait-idiomatic byte-view reverse-projection axis on the
16506        // M2-OTP-shape `:supervisor :estrategia` + `:children :restart`
16507        // slot pair the sibling [`RestartStrategy`] first-mover
16508        // (c699a83) opened one commit prior — mirror of the paired
16509        // [`TryFrom<&str> for RestartPolicy`] str-view reverse-
16510        // projection axis on the same enum, and the byte-view companion
16511        // of the pre-existing byte-owned reverse-projection family
16512        // ([`AsRef<[u8]>`], [`From<RestartPolicy> for Vec<u8>`],
16513        // [`From<&RestartPolicy> for Vec<u8>`]) on this same enum. Peer
16514        // of the sibling
16515        // [`restart_strategy_try_from_bytes_routes_through_from_wire_accessor`]
16516        // (c699a83),
16517        // [`crate::kind::tests::caixa_kind_try_from_bytes_routes_through_from_wire_accessor`]
16518        // (18d1940),
16519        // [`crate::dialeto::tests::caixa_dialeto_try_from_bytes_routes_through_from_wire_accessor`]
16520        // (d102cb8), and
16521        // [`crate::dep::tests::dep_list_try_from_bytes_routes_through_from_wire_accessor`]
16522        // (b8f25d5) — tracks the "route through `from_wire` via
16523        // `std::str::from_utf8`" discipline the first-mover established.
16524        //
16525        // Rust's standard library carries no blanket
16526        // `impl<T: for<'a> TryFrom<&'a str>> TryFrom<&[u8]> for T`, so a
16527        // two-hop composition through [`std::str::from_utf8`] + the
16528        // paired [`TryFrom<&str>`] axis is reachable through the pre-
16529        // existing str-view reverse-projection axis alone. But that
16530        // two-hop shape has no compile-time link back to the byte-view
16531        // reverse-projection axis, forces every downstream
16532        // `<T: for<'a> TryFrom<&'a [u8]>>`-bound consumer to open-code
16533        // the composition at every call site, and admits a silent split
16534        // whenever a future call site takes a sibling byte-projection
16535        // axis whose parse arm-set carries no compile-time byte-view
16536        // surface. This impl closes the byte-view reverse-projection
16537        // axis at the substrate-primitive [`RestartPolicy::from_wire`]
16538        // accessor so every future `<T: for<'a> TryFrom<&'a [u8]>>`-
16539        // bound consumer reaches the same three-arm `PascalCase` wire
16540        // accept-set through one trait dispatch.
16541        for &variant in RestartPolicy::ALL {
16542            let wire_bytes: &[u8] = variant.as_str().as_bytes();
16543            assert_eq!(
16544                <RestartPolicy as TryFrom<&[u8]>>::try_from(wire_bytes),
16545                Ok(variant),
16546                "TryFrom<&[u8]> impl on RestartPolicy must round-trip \
16547                 RestartPolicy::{variant:?}.as_str().as_bytes() back to \
16548                 Ok(RestartPolicy::{variant:?}) — divergence from \
16549                 RestartPolicy::from_wire signals a silent detour off \
16550                 the substrate-primitive accessor"
16551            );
16552            assert_eq!(
16553                <RestartPolicy as TryFrom<&[u8]>>::try_from(wire_bytes).ok(),
16554                RestartPolicy::from_wire(variant.as_str()),
16555                "TryFrom<&[u8]> ok()-projection on \
16556                 RestartPolicy::{variant:?}.as_str().as_bytes() must \
16557                 byte-equal RestartPolicy::from_wire on the paired \
16558                 &str input"
16559            );
16560            // Cross-axis witness: the byte-view reverse-projection axis
16561            // must agree with the paired str-view reverse-projection
16562            // axis ([`TryFrom<&str>`]) on every accepted arm — the two
16563            // reverse paths share one `PascalCase` accept-set through
16564            // the substrate-primitive `from_wire` accessor.
16565            let via_str: Result<RestartPolicy, ()> =
16566                <RestartPolicy as TryFrom<&str>>::try_from(variant.as_str());
16567            let via_bytes: Result<RestartPolicy, ()> =
16568                <RestartPolicy as TryFrom<&[u8]>>::try_from(wire_bytes);
16569            assert_eq!(
16570                via_bytes, via_str,
16571                "TryFrom<&[u8]> and TryFrom<&str> reverse-projection \
16572                 axes on RestartPolicy must agree on \
16573                 RestartPolicy::{variant:?} — divergence signals the \
16574                 byte-view and str-view reverse paths have drifted off \
16575                 the same substrate-primitive from_wire accessor"
16576            );
16577            // Forward/reverse byte-view cross-axis witness: feed the
16578            // paired [`AsRef<[u8]>`] byte-tail back through the new
16579            // impl and assert it round-trips to the originating arm.
16580            let via_asref: &[u8] = <RestartPolicy as AsRef<[u8]>>::as_ref(&variant);
16581            assert_eq!(
16582                <RestartPolicy as TryFrom<&[u8]>>::try_from(via_asref),
16583                Ok(variant),
16584                "TryFrom<&[u8]> ∘ AsRef<[u8]> must round-trip \
16585                 RestartPolicy::{variant:?} — divergence signals the \
16586                 forward and reverse byte-view axes have drifted off \
16587                 the same substrate-primitive as_str/from_wire pair"
16588            );
16589        }
16590    }
16591
16592    #[test]
16593    fn restart_policy_try_from_bytes_rejects_unknown_and_non_utf8_bytes() {
16594        // Rejection witness on the `impl TryFrom<&[u8]> for RestartPolicy`
16595        // — sweeps two rejection paths the byte-view reverse-projection
16596        // axis collapses onto the single unit-error `Err(())` return: the
16597        // invalid-UTF-8 rejection path ([`std::str::from_utf8`] returns
16598        // `Err` before [`RestartPolicy::from_wire`] runs) and the
16599        // valid-UTF-8-but-unknown-wire rejection path
16600        // ([`RestartPolicy::from_wire`] returns `None` on a byte-string
16601        // outside the three-arm `PascalCase` accept-set). Both must
16602        // reject, so a future accidental widening of the trait impl's
16603        // accept-set (a case-fold path, a silent acceptance of the
16604        // kebab-case dispatcher-catalog byte-strings on this axis — which
16605        // would collide the two-axis wire/catalog split the sibling
16606        // [`RestartPolicy::from_wire`] doc block makes load-bearing — a
16607        // `#[serde(rename_all = "…")]` attribute drift that widens the
16608        // parse arm-set silently, a stray fallback that maps invalid
16609        // UTF-8 onto a default arm rather than the trait-idiomatic
16610        // `Err(())`) trips at caixa-core test time. Peer of the sibling
16611        // [`restart_strategy_try_from_bytes_rejects_unknown_and_non_utf8_bytes`]
16612        // (c699a83),
16613        // [`crate::kind::tests::caixa_kind_try_from_bytes_rejects_unknown_and_non_utf8_bytes`]
16614        // (18d1940),
16615        // [`crate::dialeto::tests::caixa_dialeto_try_from_bytes_rejects_unknown_and_non_utf8_bytes`]
16616        // (d102cb8), and
16617        // [`crate::dep::tests::dep_list_try_from_bytes_rejects_unknown_and_non_utf8_bytes`]
16618        // (b8f25d5) rejection witnesses.
16619        //
16620        // Non-UTF-8 candidates:
16621        //   - a lone 0xFF byte (never valid as a UTF-8 leading byte)
16622        //   - a lone 0x80 continuation byte with no leading byte
16623        //   - a truncated multi-byte sequence (0xC3 without its continuation)
16624        //   - a UTF-16 BOM-style byte pair the UTF-8 validator rejects
16625        //   - a UTF-16 surrogate half rejected by UTF-8
16626        let non_utf8_rejected: &[&[u8]] = &[
16627            &[0xFF],
16628            &[0x80],
16629            &[0xC3],
16630            &[0xFF, 0xFE],
16631            &[0xED, 0xA0, 0x80],
16632        ];
16633        for &input in non_utf8_rejected {
16634            assert_eq!(
16635                <RestartPolicy as TryFrom<&[u8]>>::try_from(input),
16636                Err(()),
16637                "TryFrom<&[u8]> impl on RestartPolicy must reject the \
16638                 non-UTF-8 byte-sequence {input:?} with Err(()) — \
16639                 silent acceptance signals the UTF-8 validation path \
16640                 collapsed onto a default arm rather than the trait-\
16641                 idiomatic unit-error"
16642            );
16643        }
16644        // Valid-UTF-8-but-unknown-wire candidates mirror the corpus the
16645        // sibling `restart_policy_try_from_str_rejects_unknown_byte_strings`
16646        // str-view rejection witness already pins on the paired
16647        // [`TryFrom<&str>`] axis: the empty byte-string, whitespace-only
16648        // padding, the kebab-case dispatcher-catalog byte-strings on the
16649        // sibling axis the pre-existing [`std::str::FromStr`] impl the
16650        // [`gen_platform::FromStrKind`] derive installs parses onto (a
16651        // caller who confuses the two axes trips here rather than at a
16652        // downstream K8s-CR round-trip miss), lowercase / uppercase /
16653        // mixed-case folds of each `PascalCase` arm, whitespace-padded /
16654        // trailing-newline / quote-wrapped forms, and plausible-but-wrong
16655        // English rebrand candidates (`Ephemeral`, `Always`, `Never`,
16656        // `OnAbnormalExit`, `intrinsic`).
16657        let unknown_wire_rejected: &[&[u8]] = &[
16658            b"",
16659            b" ",
16660            b"\n",
16661            b"\t",
16662            b"permanent",
16663            b"temporary",
16664            b"transient",
16665            b"PERMANENT",
16666            b"TEMPORARY",
16667            b"TRANSIENT",
16668            b"Permanents",
16669            b"Permanent ",
16670            b" Permanent",
16671            b" Temporary ",
16672            b"Permanent\n",
16673            b"Transient\t",
16674            b"\"Permanent\"",
16675            b"Ephemeral",
16676            b"Always",
16677            b"Never",
16678            b"OnAbnormalExit",
16679            b"intrinsic",
16680            b"?",
16681        ];
16682        for &input in unknown_wire_rejected {
16683            assert_eq!(
16684                <RestartPolicy as TryFrom<&[u8]>>::try_from(input),
16685                Err(()),
16686                "TryFrom<&[u8]> impl on RestartPolicy must reject the \
16687                 valid-UTF-8-but-unknown-wire byte-string {input:?} \
16688                 with Err(()) — silent acceptance signals an accept-\
16689                 set widening off the paired RestartPolicy::from_wire \
16690                 resolver"
16691            );
16692            // Cross-axis witness: on a byte-string that is valid UTF-8,
16693            // the byte-view reverse-projection axis must agree with the
16694            // paired str-view reverse-projection axis
16695            // ([`TryFrom<&str>`]) — both route through the same
16696            // [`RestartPolicy::from_wire`] resolver, so the two
16697            // rejection paths align by construction.
16698            if let Ok(s) = std::str::from_utf8(input) {
16699                assert_eq!(
16700                    <RestartPolicy as TryFrom<&[u8]>>::try_from(input),
16701                    <RestartPolicy as TryFrom<&str>>::try_from(s),
16702                    "TryFrom<&[u8]> and TryFrom<&str> reverse-\
16703                     projection axes on RestartPolicy must agree on \
16704                     the valid-UTF-8 input {input:?} — divergence \
16705                     signals the two reverse paths have drifted off \
16706                     the same substrate-primitive from_wire accessor"
16707                );
16708            }
16709        }
16710    }
16711
16712    #[test]
16713    fn supervisor_scalar_ctors_are_const_zero_runtime_work() {
16714        // Const-eval pin: the [`supervisor_scalar_ctors!`] macro spells every
16715        // generated ctor `const fn` so a caller can pin a `SupervisorError`
16716        // at compile time — the same zero-runtime-work property the pre-lift
16717        // `|<slot>| SupervisorError::<Variant> { <slot> }` closure carried on
16718        // its `Copy`-pass-through construction path (no `.to_string()` /
16719        // `.into()` allocation, no branching). If any future edit silently
16720        // drops the `const` qualifier from the macro body the per-arm `const`
16721        // bindings below fail to compile, which surfaces the regression at
16722        // the substrate-primitive definition rather than at some downstream
16723        // consumer that had come to rely on the `const`-constructibility.
16724        // Peer of the sibling
16725        // `aplicacao_policy_scalar_ctors_are_const_zero_runtime_work`
16726        // (7ef425e) const-eval pin on the peer `AplicacaoError` envelope's
16727        // per-`:politicas` per-axis ctor family.
16728        const NO_CHILDREN: SupervisorError =
16729            SupervisorError::no_children(RestartStrategy::OneForAll);
16730        const MAX_RESTARTS_CAP: SupervisorError = SupervisorError::max_restarts_exceeds_cap(1_337);
16731        const WINDOW_NC: SupervisorError =
16732            SupervisorError::restart_window_not_canonical(Duration::from_micros(1));
16733        const WINDOW_CAP: SupervisorError =
16734            SupervisorError::restart_window_exceeds_cap(Duration::from_secs(3_601));
16735        assert!(matches!(NO_CHILDREN, SupervisorError::NoChildren { .. }));
16736        assert!(matches!(
16737            MAX_RESTARTS_CAP,
16738            SupervisorError::MaxRestartsExceedsCap { .. }
16739        ));
16740        assert!(matches!(
16741            WINDOW_NC,
16742            SupervisorError::RestartWindowNotCanonical { .. }
16743        ));
16744        assert!(matches!(
16745            WINDOW_CAP,
16746            SupervisorError::RestartWindowExceedsCap { .. }
16747        ));
16748    }
16749
16750    #[test]
16751    fn restart_policy_try_from_vec_bytes_routes_through_borrowed_byte_view_axis() {
16752        // Fail-before-pass-after byte-parity pin on the newly lifted
16753        // `impl TryFrom<Vec<u8>> for RestartPolicy` — asserts the trait-
16754        // idiomatic owned-byte-vec reverse-projection standard-library
16755        // impl and the sibling borrowed-input [`TryFrom<&[u8]>`] axis
16756        // resolve to the same three-arm `PascalCase` wire accept-set
16757        // across every arm the exhaustive [`RestartPolicy::ALL`] slice
16758        // enumerates. Closes the substrate-wide trait-idiomatic byte-
16759        // owned reverse-projection axis on the M2-OTP-shape
16760        // `:supervisor :estrategia` + `:children :restart` slot pair the
16761        // sibling [`RestartStrategy`] first-mover
16762        // [`restart_strategy_try_from_vec_bytes_routes_through_borrowed_byte_view_axis`]
16763        // (34951fe) opened one commit-window prior — owned-input mirror
16764        // of the paired [`TryFrom<&[u8]>`] byte-view reverse-projection
16765        // axis on this same enum (d9ef5f0), and byte-owned reverse
16766        // companion of the pre-existing byte-owned *forward*-projection
16767        // pair ([`From<RestartPolicy> for Vec<u8>`],
16768        // [`From<&RestartPolicy> for Vec<u8>`]) on this same enum. Peer
16769        // of the sibling first-mover
16770        // [`crate::kind::tests::caixa_kind_try_from_vec_bytes_routes_through_borrowed_byte_view_axis`]
16771        // (99c2849) on the [`crate::CaixaKind`] closed-set typed-enum
16772        // peer, the sibling second-mover
16773        // [`crate::dialeto::tests::caixa_dialeto_try_from_vec_bytes_routes_through_borrowed_byte_view_axis`]
16774        // (83a1526) on the [`crate::CaixaDialeto`] peer, the sibling
16775        // third-mover
16776        // [`crate::dep::tests::dep_list_try_from_vec_bytes_routes_through_borrowed_byte_view_axis`]
16777        // (42091cb) on the [`crate::dep::DepList`] peer, and the sibling
16778        // fourth-mover
16779        // [`restart_strategy_try_from_vec_bytes_routes_through_borrowed_byte_view_axis`]
16780        // (34951fe) on the [`RestartStrategy`] peer — tracks the
16781        // "delegate through `TryFrom<&[u8]>` on the `Vec<u8>::as_slice`
16782        // borrow" discipline the first-mover established.
16783        //
16784        // Rust's standard library carries no blanket
16785        // `impl<T: for<'a> TryFrom<&'a [u8]>> TryFrom<Vec<u8>> for T`,
16786        // so an owned-byte-vec caller otherwise picks between an open-
16787        // coded `<T as TryFrom<&[u8]>>::try_from(bytes.as_slice())` at
16788        // every call site whose type bounds have no compile-time link
16789        // back to the byte-owned reverse-projection axis, or a
16790        // `String::from_utf8(bytes)` two-hop shape whose error surface
16791        // leaks the standard-library `FromUtf8Error` type. This impl
16792        // closes the byte-owned reverse-projection axis at the
16793        // substrate-primitive [`RestartPolicy::from_wire`] accessor so
16794        // every future `<T: TryFrom<Vec<u8>>>`-bound owned-byte-vec
16795        // consumer reaches the same three-arm `PascalCase` wire accept-
16796        // set through one trait dispatch.
16797        for &variant in RestartPolicy::ALL {
16798            let wire_bytes: Vec<u8> = variant.as_str().as_bytes().to_vec();
16799            assert_eq!(
16800                <RestartPolicy as TryFrom<Vec<u8>>>::try_from(wire_bytes.clone()),
16801                Ok(variant),
16802                "TryFrom<Vec<u8>> impl on RestartPolicy must round-trip \
16803                 RestartPolicy::{variant:?}.as_str().as_bytes().to_vec() \
16804                 back to Ok(RestartPolicy::{variant:?}) — divergence \
16805                 from the sibling TryFrom<&[u8]> axis signals a silent \
16806                 detour off the substrate-primitive from_wire accessor"
16807            );
16808            // Cross-axis witness: the owned-byte-vec reverse-projection
16809            // axis must agree with the borrowed byte-slice reverse-
16810            // projection axis on every accepted arm — the two axes share
16811            // one `PascalCase` wire vocabulary through the substrate-
16812            // primitive `from_wire` accessor, and the owned-input axis
16813            // delegates to the borrowed peer by design.
16814            let via_owned: Result<RestartPolicy, ()> =
16815                <RestartPolicy as TryFrom<Vec<u8>>>::try_from(wire_bytes.clone());
16816            let via_borrowed: Result<RestartPolicy, ()> =
16817                <RestartPolicy as TryFrom<&[u8]>>::try_from(wire_bytes.as_slice());
16818            assert_eq!(
16819                via_owned, via_borrowed,
16820                "TryFrom<Vec<u8>> and TryFrom<&[u8]> reverse-projection \
16821                 axes on RestartPolicy must agree on \
16822                 RestartPolicy::{variant:?} — divergence signals the \
16823                 owned-input and borrowed-input byte-view reverse paths \
16824                 have drifted off the same substrate-primitive \
16825                 from_wire accessor"
16826            );
16827            // Cross-axis witness against the paired str-view reverse
16828            // axis ([`TryFrom<&str>`]) — the three reverse paths (str-
16829            // view, byte-view borrowed, byte-view owned) share one
16830            // substrate primitive.
16831            let via_str: Result<RestartPolicy, ()> =
16832                <RestartPolicy as TryFrom<&str>>::try_from(variant.as_str());
16833            assert_eq!(
16834                via_owned, via_str,
16835                "TryFrom<Vec<u8>> and TryFrom<&str> reverse-projection \
16836                 axes on RestartPolicy must agree on \
16837                 RestartPolicy::{variant:?} — divergence signals the \
16838                 byte-owned and str-view reverse paths have drifted off \
16839                 the same substrate-primitive from_wire accessor"
16840            );
16841            // Four-corner witness: because [`RestartPolicy`] carries
16842            // no wire-vs-diagnostic split (as_str and from_wire share
16843            // one `PascalCase` byte-vocabulary — like the sibling
16844            // [`RestartStrategy`] and unlike the sibling
16845            // [`crate::CaixaKind`] whose peer test deliberately declines
16846            // this witness), the byte-owned reverse-projection axis on
16847            // this enum *does* round-trip against the paired byte-owned
16848            // forward-projection pair. Pin every corner of the {owned-
16849            // input, borrowed-input} × {From<Self> → Vec<u8>,
16850            // From<&Self> → Vec<u8>} square onto the same Ok(variant)
16851            // return so a future accident that drops one corner off the
16852            // substrate-primitive accessor trips here.
16853            let owned_forward: Vec<u8> = <Vec<u8> as From<RestartPolicy>>::from(variant);
16854            let borrowed_forward: Vec<u8> = <Vec<u8> as From<&RestartPolicy>>::from(&variant);
16855            assert_eq!(
16856                owned_forward, wire_bytes,
16857                "From<RestartPolicy> for Vec<u8> forward projection on \
16858                 RestartPolicy::{variant:?} must byte-equal \
16859                 variant.as_str().as_bytes().to_vec() — divergence \
16860                 signals the paired forward pair drifted off the \
16861                 substrate-primitive as_str accessor"
16862            );
16863            assert_eq!(
16864                borrowed_forward, wire_bytes,
16865                "From<&RestartPolicy> for Vec<u8> forward projection \
16866                 on &RestartPolicy::{variant:?} must byte-equal \
16867                 variant.as_str().as_bytes().to_vec() — divergence \
16868                 signals the paired forward pair drifted off the \
16869                 substrate-primitive as_str accessor"
16870            );
16871            assert_eq!(
16872                <RestartPolicy as TryFrom<Vec<u8>>>::try_from(owned_forward.clone()),
16873                Ok(variant),
16874                "Four-corner round-trip on RestartPolicy::{variant:?} \
16875                 through From<RestartPolicy> for Vec<u8> then \
16876                 TryFrom<Vec<u8>> for RestartPolicy must return \
16877                 Ok(variant) — divergence signals the byte-owned \
16878                 forward pair and the byte-owned reverse axis have \
16879                 drifted apart"
16880            );
16881            assert_eq!(
16882                <RestartPolicy as TryFrom<Vec<u8>>>::try_from(borrowed_forward),
16883                Ok(variant),
16884                "Four-corner round-trip on RestartPolicy::{variant:?} \
16885                 through From<&RestartPolicy> for Vec<u8> then \
16886                 TryFrom<Vec<u8>> for RestartPolicy must return \
16887                 Ok(variant) — divergence signals the borrowed-input \
16888                 forward corner and the owned-input reverse corner have \
16889                 drifted apart"
16890            );
16891        }
16892    }
16893
16894    #[test]
16895    fn restart_policy_try_from_vec_bytes_rejects_unknown_and_non_utf8_bytes() {
16896        // Rejection witness on the `impl TryFrom<Vec<u8>> for
16897        // RestartPolicy` — sweeps the same two rejection paths the
16898        // sibling borrowed `TryFrom<&[u8]>` axis collapses onto the
16899        // single unit-error return: the invalid-UTF-8 rejection path
16900        // (`std::str::from_utf8` on the underlying byte-slice returns
16901        // `Err` before [`RestartPolicy::from_wire`] runs) and the
16902        // valid-UTF-8-but-unknown-wire rejection path
16903        // ([`RestartPolicy::from_wire`] returns `None` on a byte-
16904        // string outside the three-arm `PascalCase` accept-set). Both
16905        // must reject so a future accidental widening of the trait
16906        // impl's accept-set (a case-fold path, a silent acceptance of
16907        // the kebab-case dispatcher-catalog byte-strings on this axis —
16908        // which would collide the two-axis wire/catalog split the
16909        // sibling [`RestartPolicy::from_wire`] doc block makes load-
16910        // bearing — a `#[serde(rename_all = "…")]` attribute drift that
16911        // widens the parse arm-set silently, a stray
16912        // `String::from_utf8_lossy` detour that widens the input
16913        // surface with the U+FFFD replacement character, an
16914        // `Option::unwrap_or_default`-shape fallback that maps invalid
16915        // UTF-8 onto a default arm rather than the trait-idiomatic
16916        // `Err(())`) trips at caixa-core test time. Peer of the sibling
16917        // first-mover
16918        // [`crate::kind::tests::caixa_kind_try_from_vec_bytes_rejects_unknown_and_non_utf8_bytes`]
16919        // (99c2849) on the [`crate::CaixaKind`] peer, the sibling
16920        // second-mover
16921        // [`crate::dialeto::tests::caixa_dialeto_try_from_vec_bytes_rejects_unknown_and_non_utf8_bytes`]
16922        // (83a1526) on the [`crate::CaixaDialeto`] peer, the sibling
16923        // third-mover
16924        // [`crate::dep::tests::dep_list_try_from_vec_bytes_rejects_unknown_and_non_utf8_bytes`]
16925        // (42091cb) on the [`crate::dep::DepList`] peer, and the
16926        // sibling fourth-mover
16927        // [`restart_strategy_try_from_vec_bytes_rejects_unknown_and_non_utf8_bytes`]
16928        // (34951fe) on the [`RestartStrategy`] peer rejection
16929        // witnesses.
16930        let non_utf8_rejected: &[&[u8]] = &[
16931            &[0xFF],
16932            &[0x80],
16933            &[0xC3],
16934            &[0xFF, 0xFE],
16935            &[0xED, 0xA0, 0x80], // UTF-16 surrogate half — rejected by UTF-8
16936        ];
16937        for &input in non_utf8_rejected {
16938            let owned: Vec<u8> = input.to_vec();
16939            assert_eq!(
16940                <RestartPolicy as TryFrom<Vec<u8>>>::try_from(owned),
16941                Err(()),
16942                "TryFrom<Vec<u8>> impl on RestartPolicy must reject \
16943                 the non-UTF-8 byte-sequence {input:?} with Err(()) — \
16944                 silent acceptance signals the UTF-8 validation path \
16945                 collapsed onto a default arm rather than the trait-\
16946                 idiomatic unit-error"
16947            );
16948            // Cross-axis witness: the owned-input axis must agree with
16949            // the borrowed-input axis on every rejected input.
16950            assert_eq!(
16951                <RestartPolicy as TryFrom<Vec<u8>>>::try_from(input.to_vec()),
16952                <RestartPolicy as TryFrom<&[u8]>>::try_from(input),
16953                "TryFrom<Vec<u8>> and TryFrom<&[u8]> reverse-projection \
16954                 axes on RestartPolicy must agree on the non-UTF-8 \
16955                 input {input:?} — divergence signals the owned-input \
16956                 and borrowed-input byte-view reverse paths have drifted \
16957                 off the same substrate-primitive from_wire accessor"
16958            );
16959        }
16960        // Valid-UTF-8-but-unknown-wire candidates mirror the corpus the
16961        // sibling borrowed-input rejection witness
16962        // [`restart_policy_try_from_bytes_rejects_unknown_and_non_utf8_bytes`]
16963        // (d9ef5f0) already pins on the paired byte-view axis: the
16964        // empty byte-string, whitespace-only padding, the kebab-case
16965        // dispatcher-catalog byte-strings on the sibling axis the pre-
16966        // existing [`std::str::FromStr`] impl the
16967        // [`gen_platform::FromStrKind`] derive installs parses onto (a
16968        // caller who confuses the two axes trips here rather than at a
16969        // downstream K8s-CR round-trip miss), lowercase / uppercase /
16970        // mixed-case folds of each `PascalCase` arm, whitespace-padded /
16971        // trailing-newline / quote-wrapped forms, and plausible-but-
16972        // wrong English rebrand candidates (`Ephemeral`, `Always`,
16973        // `Never`, `OnAbnormalExit`, `intrinsic`).
16974        let unknown_wire_rejected: &[&[u8]] = &[
16975            b"",
16976            b" ",
16977            b"\n",
16978            b"\t",
16979            b"permanent",
16980            b"temporary",
16981            b"transient",
16982            b"PERMANENT",
16983            b"TEMPORARY",
16984            b"TRANSIENT",
16985            b"Permanents",
16986            b"Permanent ",
16987            b" Permanent",
16988            b" Temporary ",
16989            b"Permanent\n",
16990            b"Transient\t",
16991            b"\"Permanent\"",
16992            b"Ephemeral",
16993            b"Always",
16994            b"Never",
16995            b"OnAbnormalExit",
16996            b"intrinsic",
16997            b"?",
16998        ];
16999        for &input in unknown_wire_rejected {
17000            let owned: Vec<u8> = input.to_vec();
17001            assert_eq!(
17002                <RestartPolicy as TryFrom<Vec<u8>>>::try_from(owned),
17003                Err(()),
17004                "TryFrom<Vec<u8>> impl on RestartPolicy must reject \
17005                 the valid-UTF-8-but-unknown-wire byte-string {input:?} \
17006                 with Err(()) — silent acceptance signals an accept-\
17007                 set widening off the paired RestartPolicy::from_wire \
17008                 resolver"
17009            );
17010            // Cross-axis witness against the borrowed byte-view axis:
17011            // the two paths must agree by construction, since the owned
17012            // axis delegates to the borrowed peer.
17013            assert_eq!(
17014                <RestartPolicy as TryFrom<Vec<u8>>>::try_from(input.to_vec()),
17015                <RestartPolicy as TryFrom<&[u8]>>::try_from(input),
17016                "TryFrom<Vec<u8>> and TryFrom<&[u8]> reverse-projection \
17017                 axes on RestartPolicy must agree on the valid-UTF-8-\
17018                 but-unknown-wire input {input:?} — divergence signals \
17019                 the owned-input and borrowed-input byte-view reverse \
17020                 paths have drifted off the same substrate-primitive \
17021                 from_wire accessor"
17022            );
17023        }
17024    }
17025}