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/// Per-child restart policy.
1617///
1618/// Permanent / Temporary / Transient match Erlang/OTP semantics 1:1.
1619#[derive(
1620    Serialize,
1621    Deserialize,
1622    Debug,
1623    Clone,
1624    Copy,
1625    PartialEq,
1626    Eq,
1627    Hash,
1628    gen_platform::TypedDispatcher,
1629    gen_platform::Discriminant,
1630    gen_platform::IsVariant,
1631    gen_platform::FromStrKind,
1632)]
1633pub enum RestartPolicy {
1634    /// Always restart the child, regardless of how it died. Used for
1635    /// long-running services that must always be up.
1636    Permanent,
1637    /// Never restart. Used for one-shot work whose completion is
1638    /// itself the success signal (`oneShot` triggers map here).
1639    Temporary,
1640    /// Restart only when the child died *abnormally* (non-zero exit
1641    /// or unhandled exception). A clean exit completes the child.
1642    Transient,
1643}
1644
1645impl Default for RestartPolicy {
1646    fn default() -> Self {
1647        // Route the [`Default for RestartPolicy`] impl's return arm through
1648        // the substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed
1649        // `pub const` rather than a raw `Self::Permanent` arm — one source
1650        // of truth for the Erlang/OTP-canonical `permanent` worker-child
1651        // default across the two production consumers that currently
1652        // dispatch on it (this impl at the [`RestartPolicy::default`] call
1653        // and the serde-side `#[serde(default)]` on
1654        // [`ChildSpec::restart`] that resolves an author-omitted
1655        // `:children :restart` slot through `RestartPolicy::default()`).
1656        // Peer of the sibling per-`:supervisor` axis
1657        // [`Default for RestartStrategy`] → [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
1658        // route (95ffacc) — the two impls now share one substrate-primitive
1659        // lift discipline, so any future coherent rebrand of the OTP-shape
1660        // supervisor+child default set migrates through typed constants in
1661        // lockstep instead of splitting a lifted supervisor half against
1662        // an open-coded child half. Pinned by
1663        // `restart_policy_default_routes_through_lifted_default` +
1664        // `child_spec_serde_default_restart_routes_through_lifted_default`
1665        // in the tests module.
1666        SUPERVISOR_CHILD_RESTART_DEFAULT
1667    }
1668}
1669
1670impl RestartPolicy {
1671    /// Exhaustive iteration surface for every consumer that walks the
1672    /// closed three-arm [`RestartPolicy`] discriminator set (the future
1673    /// M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
1674    /// per-child admission-webhook rejection body naming the accepted-
1675    /// `:restart` list, a future `feira supervisor --restart …` CLI
1676    /// arg-parse's "did you mean" hint via a [`Self::from_wire`]-scan
1677    /// over the slice, the future `feira app graph` per-child restart
1678    /// column, any future round-trip fuzz harness that sweeps every
1679    /// arm). A future arm addition (an OTP-`intrinsic` fourth arm the
1680    /// theory
1681    /// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1682    /// might reach for once the three canonical OTP restart policies
1683    /// stop covering the substrate's discovered load-shape) extends
1684    /// this slice as one edit and every consumer picks up the new entry
1685    /// by construction; the compiler-checked exhaustiveness on the
1686    /// sibling method `match` arms ([`Self::as_str`] / [`Self::from_wire`])
1687    /// is the build-time guarantee that no arm forgets to grow.
1688    ///
1689    /// Peer of the sibling closed-set typed enums'
1690    /// [`RestartStrategy::ALL`] (4eec29c) /
1691    /// [`crate::CaixaKind::ALL`] (6b1f4fb) /
1692    /// [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
1693    /// [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
1694    /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
1695    /// surfaces — the sixth (and the third and final M2 OTP-shape)
1696    /// closed-set typed enum on the caixa surface to converge onto the
1697    /// same one-canonical-arm-list-per-enum discipline. Sibling axis to
1698    /// the peer [`RestartStrategy::ALL`] on the per-supervisor
1699    /// sibling-restart-strategy axis; this closes the per-child
1700    /// restart-decision-policy axis on the same M2 `:supervisor` slot.
1701    pub const ALL: &'static [Self] = &[Self::Permanent, Self::Temporary, Self::Transient];
1702
1703    /// Substrate-canonical exhaustive accept-set on the [`RestartPolicy`]
1704    /// `PascalCase` wire byte-string axis — the closed three-arm roster
1705    /// of every byte-string [`Self::as_str`] returns, routed byte-for-byte
1706    /// through the paired
1707    /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1708    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1709    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] lifted
1710    /// `pub const` roster the [`Self::as_str`] emitter (and the
1711    /// [`std::fmt::Display`] impl / `Serialize` derive routed through it)
1712    /// walks — and byte-for-byte the same three strings the un-`rename`d
1713    /// `Serialize` derive emits under the paired
1714    /// [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] tag key on every
1715    /// JSON / YAML CR round-trip.
1716    ///
1717    /// Peer of the sibling [`crate::CaixaKind::WIRE_NAMES`] (bd708bd)
1718    /// roster on the top-level typed-kind discriminator's `PascalCase`
1719    /// wire byte-string axis, the sibling
1720    /// [`RestartStrategy::WIRE_NAMES`] (3033f45) roster on the per-
1721    /// supervisor sibling-restart-strategy axis (the first M2 OTP-shape
1722    /// closed-set typed enum to converge onto the paired-roster
1723    /// discipline), the sibling
1724    /// [`crate::aplicacao::PlacementStrategy::WIRE_NAMES`] (3e5b194)
1725    /// roster on the first M3 mesh-shape distribution-strategy closed-
1726    /// set typed enum, and the sibling
1727    /// [`crate::upgrade::UpgradeInstruction::WIRE_FORMS`] (cc42c0e) /
1728    /// [`crate::upgrade::UpgradeInstruction::LISP_FORMS`] (1898d77)
1729    /// rosters on the OTP-appup discriminator's two-axis roster split —
1730    /// the same closed-set exhaustive-accept-set roster discipline
1731    /// extended here onto the second and final M2 OTP-shape sibling-
1732    /// enum on the caixa surface, closing the per-child restart-decision-
1733    /// policy axis paired with the peer [`RestartStrategy::WIRE_NAMES`]
1734    /// per-supervisor sibling-restart-strategy axis on the same M2
1735    /// `:supervisor` slot.
1736    ///
1737    /// Downstream consumers of the closed accepted-wire-form set — a
1738    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR admission-
1739    /// webhook rejection body enumerating the accepted JSON `:restart`
1740    /// values verbatim (as distinct from the kebab-case dispatcher-
1741    /// catalog enumeration [`Self::discriminant`] serves, whose per-arm
1742    /// form `"permanent"` / `"temporary"` / `"transient"` structurally
1743    /// disagrees with the wire byte-string these `PascalCase` entries
1744    /// carry — the split the sibling
1745    /// [`tests::restart_policy_display_matches_serialized_wire_byte_string`]
1746    /// pin already makes load-bearing), a future `feira supervisor
1747    /// --restart …` CLI-side "did you mean" hint whose candidate-list
1748    /// must byte-match the wire form the operator's per-child dispatch
1749    /// keys off, a future `feira app graph` per-child `:restart`-
1750    /// histogram column that renders zero-count arms, a future
1751    /// `caixa-operator` per-reconcile-step diagnostic log line
1752    /// enumerating accepted wire forms on an unknown-policy rejection,
1753    /// a future
1754    /// `tracing::field::valuable::Value::List` structured-log accepted-
1755    /// wire-form emit — now reach for one lifted substrate-primitive
1756    /// roster rather than open-coding a three-string array-literal
1757    /// (`["Permanent", "Temporary", "Transient"]`) whose arm-set has no
1758    /// compile-time link back to the typed [`RestartPolicy`] enum. A
1759    /// future arm addition (an OTP-`intrinsic` fourth arm the theory
1760    /// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1761    /// might reach for once the three canonical OTP restart policies
1762    /// stop covering the substrate's discovered load-shape) extends
1763    /// this roster as a single edit — paired with the [`Self::as_str`]
1764    /// match's compiler-checked exhaustiveness on the new arm — and
1765    /// every consumer picks up the new wire form by construction rather
1766    /// than a coordinated array-literal rewrite across every downstream
1767    /// site.
1768    ///
1769    /// Length is pinned load-bearing at `RestartPolicy::ALL.len()`
1770    /// (three) by
1771    /// [`tests::restart_policy_wire_names_covers_every_arm`], every
1772    /// variant's [`Self::as_str`] projection is pinned to a member of
1773    /// the roster so a silent skew between the emitter's arm-set and
1774    /// this const's arm-set trips at caixa-core test time rather than at
1775    /// a downstream consumer's accepted-set enumeration miss, and every
1776    /// entry is further pinned to open with an ASCII uppercase byte so
1777    /// a silent collapse of the `PascalCase` wire-form axis with the
1778    /// peer kebab-case dispatcher-catalog axis (an entry byte-identical
1779    /// to a sibling [`Self::discriminant`] kebab byte-string that would
1780    /// let a wire-axis consumer accept the dispatcher-catalog
1781    /// vocabulary) trips here rather than at a downstream K8s-CR round-
1782    /// trip miss.
1783    pub const WIRE_NAMES: &'static [&'static str] = &[
1784        crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
1785        crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
1786        crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
1787    ];
1788
1789    /// Canonical PascalCase discriminator scalar this variant serializes
1790    /// as under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`]. The three
1791    /// arms return the paired
1792    /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1793    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1794    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] lifted
1795    /// constants so every substrate consumer that dispatches on the
1796    /// per-child restart-decision policy (the future wasm-operator's
1797    /// per-child post-exit restart-decision branch, the future M4
1798    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
1799    /// admission-time enum-arm bind, the `caixa-operator`'s hierarchical
1800    /// reconciliation scheduler's per-child-policy fan-out) reads the
1801    /// same byte-string the `Serialize` derive emits — the pin test in
1802    /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
1803    /// asserts the two paths agree, peer of the M2
1804    /// [`RestartStrategy::as_str`] (09ffb2d) on the sibling per-supervisor
1805    /// sibling-restart-strategy axis and the M3
1806    /// [`crate::aplicacao::PlacementStrategy::as_str`] (cc8f749) on the
1807    /// per-Aplicacao distribution-strategy axis — the third of three
1808    /// OTP-shaped closed-enum discriminator axes on the caixa typed
1809    /// surface to converge onto the same three-path-convergence
1810    /// (`Serialize` derive → `as_str` helper → lifted constant)
1811    /// drift-detection posture.
1812    #[must_use]
1813    pub const fn as_str(self) -> &'static str {
1814        match self {
1815            Self::Permanent => crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
1816            Self::Temporary => crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
1817            Self::Transient => crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
1818        }
1819    }
1820
1821    /// Substrate-canonical reverse projection on the `:children :restart`
1822    /// closed-set axis — parses the `PascalCase` discriminator scalar
1823    /// back to the typed variant, or `None` when `s` is outside the
1824    /// closed-set arm-string set [`Self::as_str`] emits. Dispatches on
1825    /// the same lifted
1826    /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1827    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1828    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] constants
1829    /// the [`Self::as_str`] emitter walks, so the parse and emit halves
1830    /// of the round-trip migrate through one caixa-core edit on any
1831    /// future arm addition.
1832    ///
1833    /// Prior to this lift the substrate carried only the forward
1834    /// `Self → &str` projection on the OTP per-child restart-policy
1835    /// axis (the [`Self::as_str`] emitter, the [`std::fmt::Display`]
1836    /// impl routed through it, the `Serialize` derive that emits the
1837    /// same byte-string under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`])
1838    /// plus the kebab-case dispatcher-catalog identity via
1839    /// [`Self::discriminant`] — every non-serde consumer that wanted to
1840    /// parse a wire-form `PascalCase` policy scalar had to re-inline a
1841    /// three-arm `match s { "Permanent" => …, "Temporary" => …,
1842    /// "Transient" => …, _ => … }` cascade that expressed no
1843    /// compile-time link back to the typed variant's canonical lifted
1844    /// constant. A future variant rename or per-arm serde-attribute
1845    /// drift would silently split the wire byte-string one non-serde
1846    /// consumer parsed from the one the emitter wrote, with the failure
1847    /// surfacing at the operator's reconcile posture (a `:temporary`
1848    /// `oneShot` child being restarted on clean exit, treating the
1849    /// successful-completion signal as failure and re-running the
1850    /// completion-terminal one-shot indefinitely; a `:transient` child
1851    /// that clean-exited being restarted, masking the clean-completion
1852    /// contract) far from the rebrand commit and with no field naming
1853    /// the drift.
1854    ///
1855    /// Distinct axis from the [`std::str::FromStr`] impl the
1856    /// [`gen_platform::FromStrKind`] derive already installs on this
1857    /// enum by design, not by drift: `FromStr` parses the *kebab-case*
1858    /// dispatcher-catalog identity (`"permanent"` / `"temporary"` /
1859    /// `"transient"` — the inverse of [`Self::discriminant`]), while
1860    /// this method inverts the `PascalCase` wire byte-string
1861    /// [`Self::as_str`] emits. The two-axis split lets the dispatcher-
1862    /// catalog identity live in kebab-case (where every peer catalog
1863    /// identifier already lives) without forcing a wire-format rename
1864    /// on the tatara-lisp author surface (`:restart Permanent`,
1865    /// `PascalCase`) — the same two-axis distinction the sibling
1866    /// [`RestartStrategy::from_wire`] (4eec29c) /
1867    /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
1868    /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
1869    /// carry on their peer closed-set typed-enum wire round-trips.
1870    ///
1871    /// Same closed-set-reverse-projection discipline the sibling
1872    /// [`RestartStrategy::from_wire`] (4eec29c) /
1873    /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
1874    /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342) /
1875    /// [`crate::aplicacao::RateLimitUnit::from_suffix`] typed enums
1876    /// carry on the peer wire-side `str → Self` axes — extended onto
1877    /// the M2 OTP-shape per-child restart-policy closed-set axis, the
1878    /// sixth substrate-side closed-set typed enum (and the third and
1879    /// final OTP-shape closed-enum discriminator axis) to converge on
1880    /// the two-way `str ↔ Self` round-trip. Method-named `from_wire`
1881    /// (not `from_str`) to match the peer [`RestartStrategy::from_wire`]
1882    /// shape verbatim and side-step the [`std::str::FromStr`] impl the
1883    /// derive already installs on the sibling kebab-case axis. Returns
1884    /// `Option<Self>` (rather than `Result<Self, _>`) to match the peer
1885    /// shapes: the caller picks the diagnostic form appropriate for
1886    /// its use site.
1887    #[must_use]
1888    pub fn from_wire(s: &str) -> Option<Self> {
1889        match s {
1890            crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT => Some(Self::Permanent),
1891            crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY => Some(Self::Temporary),
1892            crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT => Some(Self::Transient),
1893            _ => None,
1894        }
1895    }
1896}
1897
1898/// [`std::fmt::Display`] routed through [`RestartPolicy::as_str`], so the
1899/// pretty-printed byte-string every consumer that formats the policy as
1900/// user-facing text lands on (the future wasm-operator's per-child
1901/// post-exit restart-decision diagnostic line, the future `feira app
1902/// graph` per-child restart column, the future M4
1903/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
1904/// admission-webhook rejection body) reaches for the same lifted
1905/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1906/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1907/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1908/// wire-format `Serialize` derive already emits under
1909/// [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
1910/// [`RestartPolicy::as_str`] helper already returns.
1911///
1912/// Pre-convergence the two paths structurally disagreed — the
1913/// `#[derive(gen_platform::Discriminant)]` + `#[discriminant(also_display)]`
1914/// route (now retired here) sent [`std::fmt::Display`] through the
1915/// gen-platform discriminant catalog string, which arrives kebab-case as
1916/// `"permanent"` / `"temporary"` / `"transient"` on this three-arm enum
1917/// (whose variant names each collapse to their own lowercase form under
1918/// the kebab-case transform), while the wire format ran as `PascalCase`
1919/// `"Permanent"` / `"Temporary"` / `"Transient"` through the un-`rename`d
1920/// serde derive. Every consumer that formatted the policy for a
1921/// diagnostic line, a graph column, or a rejection body under
1922/// `format!("{v}")` therefore landed under a different byte-string than
1923/// the wire format the operator's per-child-policy dispatch keyed off —
1924/// a silent split whose apply-time symptom (a `format!("{v}")`-carrying
1925/// diagnostic quoting `"permanent"` while the wire scalar the operator
1926/// probed was `"Permanent"`) surfaced as a confused correlate at
1927/// operator-log time far from the two-declaration site.
1928///
1929/// Routing `Display` through [`RestartPolicy::as_str`] closes the third
1930/// path: every `format!("{v}")` call reaches the same lifted
1931/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the wire format
1932/// and the [`RestartPolicy::as_str`] helper route through — `Debug` (the
1933/// compiler-derived variant name), `Display` (via `as_str`), and `Serialize`
1934/// (via the un-`rename`d derive) all resolve to the same `PascalCase`
1935/// byte-string per variant. A future variant rename or
1936/// `#[serde(rename_all = "kebab-case")]` attribute reaches every path at
1937/// exactly one place, structurally.
1938///
1939/// The dispatcher-catalog identity remains kebab-case — [`Self::discriminant`]
1940/// (from `#[derive(gen_platform::Discriminant)]`) still returns
1941/// `"permanent"` / `"temporary"` / `"transient"`, and the fleet-wide
1942/// [`gen_platform::register_dispatcher!("caixa.restart-policy", …)`]
1943/// registration keys the catalog off the same kebab identity. The two
1944/// naming worlds now live on separate typed methods (`Display` /
1945/// `as_str` for the wire byte-string, `discriminant` for the catalog
1946/// identity) rather than sharing one `Display` route that structurally
1947/// disagrees with the wire format.
1948///
1949/// Pin tests
1950/// [`tests::restart_policy_display_routes_through_as_str_helper`]
1951/// and
1952/// [`tests::restart_policy_display_matches_serialized_wire_byte_string`]
1953/// assert the three paths agree byte-for-byte on every variant, so a
1954/// future variant rename or per-arm serde attribute drift is a build
1955/// error visible at caixa-core test time, not a silent per-consumer
1956/// dispatch miss at apply / reconcile time.
1957///
1958/// Mirrors the M3 [`crate::aplicacao::PlacementStrategy`] `Display` impl
1959/// (aplicacao.rs:2306) on the per-Aplicacao distribution-strategy axis
1960/// and the sibling [`RestartStrategy`] `Display` impl on the
1961/// per-supervisor sibling-restart-strategy axis — same three-path-
1962/// convergence discipline, extended to close the third and final of
1963/// three OTP-shaped closed-enum discriminator axes on the caixa typed
1964/// surface.
1965impl std::fmt::Display for RestartPolicy {
1966    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1967        f.write_str(self.as_str())
1968    }
1969}
1970
1971/// Substrate-canonical [`AsRef<str>`] projection on the M2
1972/// per-child-restart-policy [`RestartPolicy`] closed-set typed enum —
1973/// routes through the same [`RestartPolicy::as_str`] `pub const fn`
1974/// scalar accessor the paired [`std::fmt::Display`] impl and the
1975/// un-`rename`d [`serde::Serialize`] derive already key off, so any
1976/// future consumer that binds a [`RestartPolicy`] through the
1977/// standard-library `impl AsRef<str>` bound (a future
1978/// [`caixa-feira`] `feira supervisor --restart <arm>` verb that
1979/// composes the emitted `PascalCase` wire scalar into a
1980/// [`std::process::Command::arg`] shell-out of the future
1981/// wasm-operator's per-child admission gate, a per-child structured-
1982/// log recorder on the future `caixa-operator`'s hierarchical
1983/// reconciliation surface that accepts `impl AsRef<str>` at the
1984/// `tracing::field::Value` `Str`-arm, a [`std::collections::HashMap`]
1985/// lookup keyed on the restart-policy wire byte through
1986/// `map.get::<str>(policy.as_ref())` on a future per-policy
1987/// dispatch table) reaches the paired
1988/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1989/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1990/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
1991/// lifted-const through one substrate-primitive dispatch rather
1992/// than an open-coded `.as_str()` projection at every wire-up.
1993///
1994/// Peer of the sibling [`std::fmt::Display`] impl on the same
1995/// primitive — both delegate to the shared [`RestartPolicy::as_str`]
1996/// `pub const fn` accessor, so [`format!("{v}")`], `v.as_str()`, and
1997/// `<RestartPolicy as AsRef<str>>::as_ref(&v)` resolve to the same
1998/// byte-string per instance by construction. A future variant rename
1999/// or `#[serde(rename_all = "kebab-case")]` attribute-drift on the
2000/// enum reaches every one of the three paths (plus the wire-format
2001/// `Serialize` derive that already routes through the same lifted
2002/// const) through exactly one caixa-core edit.
2003///
2004/// Same "route the trait impl through the substrate-primitive
2005/// accessor" discipline the sibling [`crate::CaixaVersion`]
2006/// [`AsRef<str>`] impl (16d5c7e) and the paired M2
2007/// [`RestartStrategy`] [`AsRef<str>`] impl (63eb1a4) carry — extends
2008/// the axis onto the paired per-child-restart-decision-policy
2009/// sibling on the same M2 `:supervisor` slot (the second M2
2010/// OTP-shape closed-set typed enum to converge onto the standard-
2011/// library [`AsRef<str>`] projection). Rust-side newtype/typed-enum
2012/// convention pairs [`AsRef<str>`] and [`fmt::Display`] on the same
2013/// primitive so a caller who has one has both; before this lift,
2014/// [`RestartPolicy`] carried [`fmt::Display`] but not the paired
2015/// [`AsRef<str>`] impl the convention names.
2016///
2017/// Pinned load-bearing by
2018/// [`tests::restart_policy_as_ref_str_routes_through_as_str_accessor`]
2019/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2020/// three-arm closed set) and
2021/// [`tests::restart_policy_as_ref_str_routes_through_display_via_shared_accessor`]
2022/// (three-path convergence: `AsRef<str>` + `Display` + `as_str` all
2023/// resolve to the same lifted `SUPERVISOR_CHILD_RESTART_*` const per
2024/// arm) — any future silent detour that routes the impl through a
2025/// divergent projection (a per-arm inline `match self { … }`
2026/// re-inlining that opens a compile-time link to the un-lifted
2027/// arm-literal, a swap onto the kebab-case
2028/// [`gen_platform::Discriminant`] catalog identity that would
2029/// collide the wire axis with the dispatcher-catalog axis) trips at
2030/// caixa-core test time under `assert_eq!` rather than at a
2031/// downstream `impl AsRef<str>`-bound consumer's silent split.
2032impl AsRef<str> for RestartPolicy {
2033    fn as_ref(&self) -> &str {
2034        self.as_str()
2035    }
2036}
2037
2038/// Trait-idiomatic reverse projection on the M2-OTP-shape per-child
2039/// restart-policy [`RestartPolicy`] closed-set typed enum — routes
2040/// byte-for-byte through the paired substrate-primitive
2041/// [`RestartPolicy::from_wire`] `Option<Self>` accessor so every future
2042/// consumer that binds a `PascalCase` `:children :restart` wire
2043/// byte-string through the standard-library `.try_into()` / [`TryFrom`]
2044/// axis (a future [`caixa-feira`] `feira supervisor --restart
2045/// <Permanent|Temporary|Transient>` CLI arg-parse that composes into
2046/// `let restart: RestartPolicy = s.try_into()?`, a future
2047/// `mesh.pleme.io/v1alpha1/Supervisor` CR admission-webhook that folds a
2048/// `spec.children[*].restart: String` field through
2049/// `RestartPolicy::try_from(&s)?`, a generic
2050/// `<T: TryFrom<&str>>`-bound loader over any of the substrate's closed-
2051/// set typed enums) reaches the same three-arm accept-set the sibling
2052/// [`RestartPolicy::from_wire`] resolver parses through and the sibling
2053/// [`RestartPolicy::as_str`] emits, rather than an open-coded per-arm
2054/// `match s { "Permanent" => …, "Temporary" => …, "Transient" => …, _ =>
2055/// … }` cascade whose arm-set has no compile-time link back to the
2056/// substrate primitive.
2057///
2058/// Complements the pre-existing forward-projection triple
2059/// ([`std::fmt::Display`], [`AsRef<str>`], [`RestartPolicy::as_str`])
2060/// with the paired trait-idiomatic reverse-projection axis: Rust-side
2061/// newtype/typed-enum convention pairs [`AsRef<str>`] with either
2062/// [`std::str::FromStr`] or [`TryFrom<&str>`] on the same primitive so a
2063/// caller who can project *out to* a `&str` can also project *in from*
2064/// one. The [`TryFrom<&str>`] axis is deliberately chosen over
2065/// [`std::str::FromStr`] to sidestep the `clippy::should_implement_trait`
2066/// lint the sibling method-named [`RestartPolicy::from_wire`] would
2067/// trigger under a `FromStr` impl and to avoid colliding with the
2068/// [`std::str::FromStr`] impl the [`gen_platform::FromStrKind`] derive
2069/// already installs on the paired *kebab-case dispatcher-catalog* axis
2070/// (which parses `"permanent"` / `"temporary"` / `"transient"`, the
2071/// inverse of [`Self::discriminant`]) — this impl closes the trait-
2072/// idiomatic reverse axis on the *`PascalCase` wire* half without
2073/// disturbing either the method-named `from_wire` shape every sibling
2074/// closed-set typed enum on the substrate already carries or the
2075/// pre-existing `FromStr` on the dispatcher-catalog half, keeping the
2076/// two-axis split the sibling [`Self::from_wire`] doc block motivates.
2077///
2078/// `type Error = ()` matches the sibling [`RestartPolicy::from_wire`]'s
2079/// `Option<Self>` return-shape's deliberate deferral of error typing: the
2080/// caller picks the diagnostic form appropriate for its use site (a
2081/// future `feira supervisor --restart` arg-parse composes its own
2082/// per-verb "unknown restart: <arg> — accepted: {…}" message enumerating
2083/// [`RestartPolicy::ALL`], a future M4 admission-webhook rejection body
2084/// wraps the `Err(())` outcome with the accepted-set enumeration for
2085/// operator diagnostics, a `Result::map_err` at the call site lifts the
2086/// unit-error to a per-verb error type). Same shape the peer
2087/// [`RestartStrategy`] (5b828ed) on the sibling per-supervisor axis,
2088/// [`crate::CaixaKind`] (3c83606), [`crate::CaixaDialeto`] (bf33136), and
2089/// [`crate::aplicacao::PlacementStrategy`] (6fd00cd) blocks motivate on
2090/// their peer closed-set typed enums' reverse projections.
2091///
2092/// The paired [`TryFrom<&str>`] impl reaches the same three-arm accept-
2093/// set the [`RestartPolicy::from_wire`] resolver dispatches through, so
2094/// any future arm addition (an OTP-`intrinsic` fourth arm the theory
2095/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
2096/// might reach for once the three canonical OTP restart policies stop
2097/// covering the substrate's discovered load-shape) grows the trait-
2098/// idiomatic axis by construction — one caixa-core edit on
2099/// [`RestartPolicy::from_wire`] extends both the method-named reverse
2100/// projection every existing consumer keys off and the trait-idiomatic
2101/// reverse projection this impl exposes, without a coordinated rewrite
2102/// across every future `TryFrom<&str>`-bound consumer's arm-set.
2103///
2104/// Extends the substrate-wide closed-set-enum reverse-projection family
2105/// ([`crate::CaixaKind`] via 3c83606, [`crate::CaixaDialeto`] via
2106/// bf33136, [`crate::aplicacao::PlacementStrategy`] via 6fd00cd, and
2107/// [`RestartStrategy`] via 5b828ed) onto the third and final OTP-shape
2108/// closed-enum discriminator axis on the caixa surface — the paired
2109/// per-child `:children :restart` closed set the future wasm-operator's
2110/// hierarchical reconciliation scheduler's per-child post-exit
2111/// restart-decision branch keys off end-to-end.
2112///
2113/// Pinned load-bearing by
2114/// [`tests::restart_policy_try_from_str_routes_through_from_wire_accessor`]
2115/// (byte-parity pin against [`RestartPolicy::from_wire`] across the
2116/// three-arm accept-set),
2117/// [`tests::restart_policy_try_from_str_rejects_unknown_byte_strings`]
2118/// (rejection witness against silent accept-set widening), and
2119/// [`tests::restart_policy_try_from_str_and_from_wire_partition_the_accept_set`]
2120/// (cross-axis partition pin locking the trait and method-named
2121/// projections onto one accept-set).
2122impl TryFrom<&str> for RestartPolicy {
2123    type Error = ();
2124
2125    fn try_from(s: &str) -> Result<Self, Self::Error> {
2126        Self::from_wire(s).ok_or(())
2127    }
2128}
2129
2130/// Trait-idiomatic forward projection on the M2-OTP-shape per-child
2131/// restart-policy [`RestartPolicy`] closed-set typed enum — routes
2132/// byte-for-byte through the paired substrate-primitive
2133/// [`RestartPolicy::as_str`] `pub const fn` accessor. Return type is
2134/// `&'static str` by construction — every [`RestartPolicy::as_str`] arm
2135/// resolves to a [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const
2136/// &str` with `'static` lifetime, so the trait's return-type promise is
2137/// upheld structurally without a [`String::leak`] cast or a per-arm inline
2138/// literal.
2139///
2140/// Every future consumer that specifically needs `&'static str` lifetime
2141/// bytes on the per-child restart-decision axis (a
2142/// [`tracing::field::valuable::Value::Str`] recording where the `Str`
2143/// arm's typing demands `&'static str`, a
2144/// [`std::borrow::Cow::Borrowed`]`::<'static, str>(policy.into())` composer
2145/// on the future M4 admission-webhook rejection body where the
2146/// `Cow<'static, str>` typing rules out the sibling [`AsRef<str>`]
2147/// borrowed return, a generic `<T: Into<&'static str>>`-bound serializer
2148/// or error formatter that requires the `'static` bound) reaches the same
2149/// lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2150/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2151/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] substrate-
2152/// primitive dispatch rather than an open-coded per-arm literal cascade
2153/// whose arm-set has no compile-time link back to the substrate primitive.
2154///
2155/// Peer of the sibling M2-OTP-shape [`RestartStrategy`] forward-projection
2156/// impl (523157d) on the per-supervisor sibling-restart-strategy axis —
2157/// the second (and second-of-two-in-M2) closed-set typed enum on the
2158/// caixa surface to converge onto the paired trait-idiomatic forward-
2159/// projection axis. With this lift the paired per-child
2160/// `:children :restart` closed-set typed enum carries the full sibling
2161/// quintet ([`std::fmt::Display`], [`AsRef<str>`], [`Self::as_str`],
2162/// [`TryFrom<&str>`] via 6fdd0d9, `From<Self> for &'static str` via this
2163/// lift) plus the round-trip witness through both the trait-idiomatic
2164/// (`From<Self> for &'static str` + `TryFrom<&str>`) and the method-named
2165/// (`as_str` + `from_wire`) axis pairs — mirrors the sibling
2166/// [`RestartStrategy`] surface arm-for-arm, so every future arm addition
2167/// (an OTP-`intrinsic` fourth arm the theory
2168/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
2169/// might reach for once the three canonical OTP restart policies stop
2170/// covering the substrate's discovered load-shape) grows the trait-
2171/// idiomatic forward axis by construction: one caixa-core edit on
2172/// [`RestartPolicy::as_str`] extends every one of the five sibling
2173/// forward-projection paths ([`std::fmt::Display`], [`AsRef<str>`],
2174/// [`Self::as_str`] itself, this `From<Self> for &'static str`, and the
2175/// un-`rename`d [`serde::Serialize`] derive that also emits `as_str`'s
2176/// bytes) without a coordinated rewrite across every future
2177/// `Into<&'static str>`-bound consumer's arm-set.
2178///
2179/// Pinned load-bearing by
2180/// [`tests::restart_policy_from_into_static_str_routes_through_as_str_accessor`]
2181/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2182/// three-arm emit-set, plus a `const`-context materialization witness for
2183/// the `&'static str` lifetime promise) and
2184/// [`tests::restart_policy_from_into_static_str_and_as_str_partition_the_emit_set`]
2185/// (partition pin asserting `<&'static str as From<RestartPolicy>>::from`
2186/// and [`RestartPolicy::as_str`] agree on every arm, plus a two-way
2187/// round-trip witness through the paired trait-idiomatic reverse-
2188/// projection axis [`TryFrom<&str>`] (6fdd0d9): every
2189/// `policy.into::<&'static str>()` output re-parses back through
2190/// [`RestartPolicy::try_from`] to the original variant, closing the two-
2191/// way `Self ↔ &'static str` round-trip on the trait-idiomatic axis pair).
2192impl From<RestartPolicy> for &'static str {
2193    fn from(policy: RestartPolicy) -> &'static str {
2194        policy.as_str()
2195    }
2196}
2197
2198/// Trait-idiomatic *forward* projection on [`RestartPolicy`] from a
2199/// *borrowed* input onto the `&'static str` axis — the borrowed-input
2200/// companion to the paired owned-input [`From<RestartPolicy> for
2201/// &'static str`] impl immediately above. Routes byte-for-byte through
2202/// the same substrate-primitive [`RestartPolicy::as_str`] `pub const
2203/// fn` accessor so every consumer that binds a `&RestartPolicy`
2204/// through the standard-library `.into()` / [`From<&Self> for &'static
2205/// str`] axis (a `RestartPolicy::ALL.iter().map(<&'static
2206/// str>::from).collect::<Vec<_>>()` per-arm accept-set materializer —
2207/// whose iterator over `&'static [RestartPolicy]` yields
2208/// `&RestartPolicy`, not `RestartPolicy`, so the owned-input
2209/// [`From<RestartPolicy>`] axis alone forces every call site through
2210/// an explicit `.copied()` / dereference / [`Copy`]-bound restatement
2211/// rather than the direct trait-idiomatic projection; a future generic
2212/// `<T: Copy + for<'a> Into<&'static str>>`-bound diagnostic column
2213/// that walks the `iter().map(Into::into)` shape verbatim across every
2214/// substrate-wide closed-set typed enum; the future wasm-operator's
2215/// per-child post-exit restart-decision diagnostic line that composes
2216/// the accepted-set enumeration from an iterated
2217/// `RestartPolicy::ALL.iter().map(|p| p.into())` pipe rather than a
2218/// per-arm `match p { … }` cascade; a future
2219/// `HashMap::<&'static str, RestartPolicy>::from_iter(
2220///     RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))`-style
2221/// per-policy reverse-lookup table the sibling [`TryFrom<&str>`] impl
2222/// cannot compose without this borrowed-input axis in place) reaches
2223/// the same three-arm lifted
2224/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2225/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2226/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2227/// paired owned-input [`From<RestartPolicy> for &'static str`], the
2228/// sibling [`std::fmt::Display`], [`AsRef<str>`], and
2229/// [`RestartPolicy::as_str`] surfaces already return.
2230///
2231/// Fifth peer on the substrate-wide trait-idiomatic *borrowed-input*
2232/// forward-projection family opened on [`crate::dep::DepList`]
2233/// (64aa742) and extended onto [`crate::CaixaKind`] (5ab993a),
2234/// [`crate::CaixaDialeto`] (807b0b5), and the paired
2235/// per-supervisor sibling-restart-strategy [`RestartStrategy`]
2236/// (e941836). Rust's `From` trait does not auto-derive the
2237/// `From<&Self>` sibling from a `From<Self>` impl (the blanket
2238/// `impl<T, U> From<&T> for U where T: Copy, U: From<T>` does not
2239/// exist in `core`), so every closed-set typed enum that carries the
2240/// owned-input axis but not the borrowed-input axis forces every
2241/// borrowed-input call site through a `.copied()` /
2242/// `<&'static str>::from(*policy)` / `policy.as_str()` detour whose
2243/// type bounds have no compile-time link to the substrate primitive.
2244/// [`RestartPolicy`] is the second (and second-of-two-in-M2)
2245/// OTP-shape peer to converge onto this campaign — sibling of the
2246/// paired per-supervisor [`RestartStrategy`] borrowed-input axis, so
2247/// with this lift both closed-set typed enums on the M2 `:supervisor`
2248/// slot now carry the full sibling quintet ([`std::fmt::Display`],
2249/// [`AsRef<str>`], [`Self::as_str`], `From<Self> for &'static str`,
2250/// `From<&Self> for &'static str`) plus the paired trait-idiomatic
2251/// reverse projection [`TryFrom<&str>`], closing the borrowed-input
2252/// forward-projection axis on the M2 OTP-shape slot as a unit.
2253///
2254/// Same three-path convergence discipline as the paired owned-input
2255/// impl (this borrowed-input axis, the paired owned-input
2256/// [`From<RestartPolicy> for &'static str`], and
2257/// [`RestartPolicy::as_str`] all route through the same lifted
2258/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const), so a future
2259/// variant rename or per-arm serde-attribute drift reaches every one
2260/// of the six sibling forward-projection paths
2261/// ([`std::fmt::Display`], [`AsRef<str>`], [`Self::as_str`],
2262/// [`From<Self> for &'static str`], this [`From<&Self> for &'static
2263/// str`], and the un-`rename`d [`serde::Serialize`] derive that also
2264/// emits [`Self::as_str`]'s bytes) through exactly one caixa-core
2265/// edit.
2266///
2267/// The [`RestartPolicy::as_str`] emit and [`RestartPolicy::from_wire`]
2268/// parse share the same `PascalCase` vocabulary by construction, so
2269/// the borrowed-input forward axis and the reverse axis compose
2270/// directly — the round-trip witness pin below locks this direct
2271/// composition without the intermediate wire-vocab hop the peer
2272/// [`crate::CaixaKind`] axis pair requires.
2273///
2274/// Pinned load-bearing by
2275/// [`tests::restart_policy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
2276/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2277/// three-arm emit-set via a borrowed input, plus a `const`-context
2278/// materialization witness for the `&'static str` lifetime promise,
2279/// plus a blanket `.into()` shape) and
2280/// [`tests::restart_policy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
2281/// (cross-axis partition pin against the paired owned-input
2282/// [`From<RestartPolicy> for &'static str`] impl, plus a
2283/// `.iter().map(Into::into)` pipe witness over
2284/// [`RestartPolicy::ALL`], plus a direct round-trip witness through
2285/// [`TryFrom<&str>`] that closes the two-way `&Self → &'static str →
2286/// Self` round-trip without the wire-vocab intermediate the peer
2287/// [`crate::CaixaKind`] axis pair requires).
2288impl From<&RestartPolicy> for &'static str {
2289    fn from(policy: &RestartPolicy) -> &'static str {
2290        policy.as_str()
2291    }
2292}
2293
2294/// Trait-idiomatic *owned-`String`* forward projection on the second
2295/// M2 OTP-shape closed-set typed enum ([`RestartPolicy`]) — the
2296/// owned-heap-string companion to the paired `&'static str`-returning
2297/// [`From<RestartPolicy> for &'static str`] / [`From<&RestartPolicy>
2298/// for &'static str`] impls immediately above. Routes byte-for-byte
2299/// through the substrate-primitive [`RestartPolicy::as_str`] `pub
2300/// const fn` accessor (via [`str::to_owned`]) so every consumer that
2301/// binds a [`RestartPolicy`] through the standard-library `.into()` /
2302/// [`From<Self> for String`] (equivalently [`Into<String>`]) axis — a
2303/// future `serde_json::Value::String(policy.into())` structured-payload
2304/// composer where the `Value::String` arm typing demands an owned
2305/// [`String`] and the sibling [`&'static str`]-returning axis forces
2306/// an explicit `.to_owned()` / `String::from` restatement at every
2307/// call site, a future `HashMap::<String, RestartPolicy>::from_iter(
2308/// RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))` per-policy
2309/// lookup where the map's key type is owned [`String`] rather than
2310/// [`&'static str`], a future `Cow::<'static, str>::Owned(policy.into())`
2311/// composer on the future M4 admission-webhook rejection body's
2312/// owned-arm, the future wasm-operator's per-child post-exit
2313/// diagnostic emit `serde_json::json!({ "restart": policy })` where the
2314/// JSON serializer's `Serialize` impl on [`String`] owns the emit-path
2315/// — reaches the same three-arm lifted
2316/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2317/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2318/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2319/// paired [`std::fmt::Display`], [`AsRef<str>`],
2320/// [`RestartPolicy::as_str`], and the two `&'static str`-returning
2321/// forward-projection impls already return.
2322///
2323/// Extends the trait-idiomatic *owned-`String`* forward-projection
2324/// axis onto the second-of-two M2 OTP-shape closed-set typed enums on
2325/// the caixa surface — mirror of the first-mover
2326/// [`From<RestartStrategy> for String`] (7baa18a) that opened this
2327/// axis on the sibling supervisor-level strategy enum. Rust's standard
2328/// library does not carry a blanket `impl<T: AsRef<str>> From<T> for
2329/// String` (nor an `impl<T: fmt::Display> From<T> for String`), so
2330/// every closed-set typed enum that carries the paired `AsRef<str>` /
2331/// `Display` / `From<Self> for &'static str` triple but not the
2332/// owned-[`String`] axis forces every owned-string call site through a
2333/// `.to_string()` / `.as_str().to_owned()` / `String::from(policy.as_str())`
2334/// detour whose type bounds have no compile-time link to the
2335/// substrate primitive.
2336///
2337/// Deliberately routes through the human-readable
2338/// [`RestartPolicy::as_str`] axis — for this enum the wire format
2339/// (`PascalCase`, tatara-lisp author surface `:restart Permanent`) and
2340/// the diagnostic byte-string share the same vocabulary by
2341/// construction (unlike the sibling [`crate::CaixaKind`] enum whose
2342/// two axes diverge), so the owned-[`String`] projection lands
2343/// byte-identically on both the wire vocabulary the paired
2344/// [`serde::Serialize`] derive emits and the diagnostic vocabulary the
2345/// [`RestartPolicy::as_str`] helper returns, and — because the paired
2346/// [`TryFrom<&str>`] / [`RestartPolicy::from_wire`] reverse-projection
2347/// axis parses the same `PascalCase` vocabulary — the direct two-way
2348/// `Self → String → Self` round-trip composes without the wire-vocab
2349/// intermediate hop the peer [`crate::CaixaKind`] owned-[`String`]
2350/// axis pair requires.
2351///
2352/// Pinned load-bearing by
2353/// [`tests::restart_policy_from_into_owned_string_routes_through_as_str_accessor`]
2354/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2355/// three-arm emit-set, plus a blanket `.into::<String>()` shape
2356/// witness) and
2357/// [`tests::restart_policy_from_into_owned_string_and_static_str_agree_on_every_arm`]
2358/// (cross-axis partition pin against the paired owned-input
2359/// [`From<RestartPolicy> for &'static str`] impl and the sibling
2360/// [`ToString::to_string`] surface routed through [`std::fmt::Display`],
2361/// plus a `.iter().copied().map(String::from)` pipe witness over
2362/// [`RestartPolicy::ALL`], plus a direct round-trip witness through
2363/// [`TryFrom<&str>`] on the owned-[`String`]'s [`String::as_str`]
2364/// borrow that closes the two-way `Self → String → Self` round-trip
2365/// on the trait-idiomatic owned-[`String`] forward + reverse axis
2366/// pair).
2367impl From<RestartPolicy> for String {
2368    fn from(policy: RestartPolicy) -> String {
2369        policy.as_str().to_owned()
2370    }
2371}
2372
2373/// Trait-idiomatic *borrowed-input, owned-`String` output* forward
2374/// projection on the second-of-two M2 OTP-shape closed-set typed enum
2375/// ([`RestartPolicy`]) — the fourth (and closing) corner of the
2376/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
2377/// projection family on this enum, mirror of the first-mover
2378/// [`From<&RestartStrategy> for String`] (579385f) that opened the
2379/// 2×2-completion corner on the sibling supervisor-level strategy
2380/// enum. Routes byte-for-byte through the substrate-primitive
2381/// [`RestartPolicy::as_str`] `pub const fn` accessor (via
2382/// [`str::to_owned`]) so every consumer that holds a borrowed
2383/// [`&RestartPolicy`] and needs an owned [`String`] — a future
2384/// `serde_json::Value::String(String::from(&policy))` structured-payload
2385/// composer over a borrowed field, a future `Iterator::map` over
2386/// `&[RestartPolicy]` that projects to owned keys through
2387/// `.iter().map(String::from)`, a future `HashMap::<String,
2388/// RestartPolicy>::from_iter` that keys off a borrowed-iteration axis
2389/// where dereferencing the policy would force an unnecessary `Copy` at
2390/// every step, the future wasm-operator's per-supervisor
2391/// `child_policies.iter().map(String::from).collect()` per-child post-
2392/// exit restart-decision diagnostic emit whose iteration axis is
2393/// borrowed by construction — reaches the same three-arm lifted
2394/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2395/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2396/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2397/// paired [`std::fmt::Display`], [`AsRef<str>`],
2398/// [`RestartPolicy::as_str`], and the three other trait-idiomatic
2399/// forward-projection impls
2400/// ([`From<RestartPolicy> for &'static str`],
2401/// [`From<&RestartPolicy> for &'static str`],
2402/// [`From<RestartPolicy> for String`]) already return.
2403///
2404/// Second peer on the substrate-wide trait-idiomatic *borrowed-input,
2405/// owned-`String` output* forward-projection family opened on
2406/// [`crate::supervisor::RestartStrategy`] (579385f) — closes the
2407/// `{Self, &Self} × {&'static str, String}` 2×2 projection corner on
2408/// both M2 OTP-shape sibling peers (the paired supervisor-level
2409/// sibling-restart-strategy axis and the per-child restart-decision-
2410/// policy axis), so the whole M2 OTP-shape axis pair now carries the
2411/// full four-corner family by construction. Rust's standard library
2412/// does not carry a blanket `impl<T: AsRef<str>> From<&T> for String`
2413/// (nor an `impl<T: fmt::Display> From<&T> for String`), so every
2414/// closed-set typed enum that carries the paired `AsRef<str>` /
2415/// `Display` / `From<Self> for &'static str` / `From<&Self> for
2416/// &'static str` / `From<Self> for String` quintuple but not the
2417/// borrowed-input owned-[`String`] axis forces every borrowed-input
2418/// owned-string call site through a `policy.as_str().to_owned()` /
2419/// `String::from(*policy)` (with a spurious `Copy`) /
2420/// `policy.to_string()` (through `Display`) detour whose type bounds
2421/// have no compile-time link to the substrate primitive.
2422///
2423/// Deliberately routes through the human-readable
2424/// [`RestartPolicy::as_str`] axis — for this enum the wire format
2425/// (`PascalCase`, tatara-lisp author surface `:restart Permanent`) and
2426/// the diagnostic byte-string share the same vocabulary by
2427/// construction (unlike the sibling [`crate::CaixaKind`] enum whose
2428/// two axes diverge), so the borrowed-input owned-[`String`]
2429/// projection lands byte-identically on both the wire vocabulary the
2430/// paired [`serde::Serialize`] derive emits and the diagnostic
2431/// vocabulary the [`RestartPolicy::as_str`] helper returns, and —
2432/// because the paired [`TryFrom<&str>`] / [`RestartPolicy::from_wire`]
2433/// reverse-projection axis parses the same `PascalCase` vocabulary —
2434/// the direct two-way `&Self → String → Self` round-trip composes
2435/// without the wire-vocab intermediate hop the peer
2436/// [`crate::CaixaKind`] axis pair requires.
2437///
2438/// The remaining thirteen closed-set typed enums on the caixa
2439/// substrate surface (`CaixaKind`, `CaixaDialeto`, `DepList`,
2440/// `PlacementStrategy`, `WitShape`, `RateLimitUnit`,
2441/// `PathShapeViolation`, `InvariantKind`, `ArchVerdict`, `Severity`,
2442/// `FixSafety`, `Semantic`, `FerriteRuntime`) are the future targets
2443/// of this 2×2-completion campaign — each carries the same paired
2444/// quintuple that this borrowed-input owned-[`String`] axis extends
2445/// onto.
2446///
2447/// Pinned load-bearing by
2448/// [`tests::restart_policy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
2449/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2450/// three-arm emit-set through the borrowed-input surface) and
2451/// [`tests::restart_policy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
2452/// (cross-axis partition pin against the paired owned-input owned-
2453/// [`String`] [`From<RestartPolicy> for String`] impl, the paired
2454/// borrowed-input owned-[`&'static str`] [`From<&RestartPolicy> for
2455/// &'static str`] impl, and the sibling [`ToString::to_string`]
2456/// surface routed through [`std::fmt::Display`], plus a direct round-
2457/// trip witness through [`TryFrom<&str>`] on the owned-[`String`]'s
2458/// [`String::as_str`] borrow that closes the two-way
2459/// `&Self → String → Self` round-trip on the trait-idiomatic
2460/// borrowed-input owned-[`String`] forward + reverse axis pair).
2461impl From<&RestartPolicy> for String {
2462    fn from(policy: &RestartPolicy) -> String {
2463        policy.as_str().to_owned()
2464    }
2465}
2466
2467/// Trait-idiomatic *owned-input, [`std::borrow::Cow<'static, str>`]
2468/// output* forward projection on the M2 OTP-shape per-child-restart
2469/// [`RestartPolicy`] closed-set typed enum — extends the substrate-
2470/// wide [`std::borrow::Cow<'static, str>`] forward-projection family
2471/// opened on [`crate::CaixaKind`] (99c1735 owned-input, d45c409
2472/// borrowed-input) and first extended off it onto the sibling M2
2473/// OTP-shape sibling-restart [`RestartStrategy`] (7dd28b3 owned-input,
2474/// 9b3e4b3 borrowed-input) onto the second (and second-of-two-in-M2)
2475/// M2 OTP-shape closed-set fieldless typed enum peer on the caixa
2476/// surface (`:children :restart`). Routes byte-for-byte through the
2477/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
2478/// accessor (via [`std::borrow::Cow::Borrowed`]) so every consumer
2479/// that binds a [`RestartPolicy`] through the trait-idiomatic
2480/// [`std::borrow::Cow<'static, str>`] axis — a future
2481/// `axum::response::IntoResponse` composer whose per-policy
2482/// diagnostic-body typing rules out the sibling [`AsRef<str>`]
2483/// borrowed return, a future M4 admission-webhook rejection body
2484/// that composes the accepted-policy enumeration through the same
2485/// `RestartPolicy::ALL.iter().map(Cow::from)` shape [`crate::CaixaKind`]
2486/// and [`RestartStrategy`] already route through, a generic `<T: for<'a>
2487/// Into<std::borrow::Cow<'static, str>>>`-bound structured-log
2488/// emitter on a per-child-policy diagnostic column — reaches the same
2489/// three-arm lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`]
2490/// / [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2491/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2492/// paired [`std::fmt::Display`], [`AsRef<str>`],
2493/// [`RestartPolicy::as_str`], and the four
2494/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
2495/// forward-projection corners already return.
2496///
2497/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
2498/// [`std::borrow::Cow::Owned`] — the substrate-primitive
2499/// [`RestartPolicy::as_str`] accessor's return carries the `&'static
2500/// str` lifetime by construction (each `match` arm resolves to a
2501/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const &str`
2502/// with static lifetime), so the zero-alloc borrowed arm is the
2503/// type-correct projection with no runtime allocation.
2504///
2505/// Rust's standard library carries no blanket `impl<T: AsRef<str>>
2506/// From<T> for Cow<'static, str>` (nor an `impl<T: fmt::Display>
2507/// From<T> for Cow<'static, str>`), so the paired sibling
2508/// [`From<RestartPolicy> for &'static str`] (9fb37d0),
2509/// [`From<RestartPolicy> for String`] (7851725), [`AsRef<str>`], and
2510/// [`std::fmt::Display`] surfaces do not implicitly extend to a
2511/// [`Cow<'static, str>`]-bound call site — every such site is forced
2512/// through a `Cow::Borrowed(policy.as_str())` /
2513/// `Cow::Owned(policy.to_string())` open-code whose type bounds have
2514/// no compile-time link back to the substrate primitive until this
2515/// lift.
2516///
2517/// Second peer to extend the substrate-wide trait-idiomatic
2518/// [`std::borrow::Cow<'static, str>`] forward-projection axis off the
2519/// top-level [`crate::CaixaKind`] enum (99c1735 owned-input, d45c409
2520/// borrowed-input) onto the wider substrate — closes the M2 OTP-shape
2521/// tier of the campaign (both sibling peers, `RestartStrategy` and
2522/// `RestartPolicy`, now carry the owned-input Cow<'static, str>
2523/// forward projection) so the remaining eleven peers
2524/// (`PlacementStrategy`, `RateLimitUnit`, `DepList`, `CaixaDialeto`,
2525/// and the outside-`caixa-core` peers `WitShape`, `PathShapeViolation`,
2526/// `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`,
2527/// `FerriteRuntime`) are the future targets. Every future arm addition
2528/// (an OTP-`intrinsic` fourth restart policy the ABSORPTION-ROADMAP
2529/// might reach for once the three canonical OTP restart policies stop
2530/// covering the substrate's discovered load-shape) grows the
2531/// Cow<'static, str> axis by construction through one caixa-core edit
2532/// on [`RestartPolicy::as_str`] — rather than a coordinated rewrite
2533/// across every future Cow<'static, str>-bound consumer site.
2534///
2535/// Pinned load-bearing by
2536/// [`tests::restart_policy_from_into_static_cow_str_routes_through_as_str_accessor`]
2537/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
2538/// against [`RestartPolicy::as_str`] across the three-arm
2539/// [`RestartPolicy::ALL`]) and
2540/// [`tests::restart_policy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
2541/// (cross-axis partition pin against the paired [`From<RestartPolicy>
2542/// for &'static str`], [`From<RestartPolicy> for String`], and
2543/// [`ToString`]-through-[`std::fmt::Display`] axes, plus a
2544/// `.iter().copied().map(Cow::from)` pipe witness over
2545/// [`RestartPolicy::ALL`] that materializes the three-arm accept-set
2546/// through the [`Cow<'static, str>`] axis alone and pins the
2547/// zero-alloc discipline on every element).
2548impl From<RestartPolicy> for std::borrow::Cow<'static, str> {
2549    fn from(policy: RestartPolicy) -> std::borrow::Cow<'static, str> {
2550        std::borrow::Cow::Borrowed(policy.as_str())
2551    }
2552}
2553
2554/// Trait-idiomatic *borrowed-input, [`std::borrow::Cow<'static, str>`]
2555/// output* forward projection on the M2 OTP-shape per-child-restart
2556/// [`RestartPolicy`] closed-set typed enum — the borrowed-input
2557/// companion to the paired owned-input
2558/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] impl
2559/// immediately above (0612398). Routes byte-for-byte through the same
2560/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
2561/// accessor (via [`std::borrow::Cow::Borrowed`]) so every consumer
2562/// that holds a `&RestartPolicy` and needs a
2563/// [`std::borrow::Cow<'static, str>`] — a
2564/// `RestartPolicy::ALL.iter().map(std::borrow::Cow::from).collect::<Vec<_>>()`
2565/// per-arm accept-set materializer (whose iterator over
2566/// `&'static [RestartPolicy]` yields `&RestartPolicy`, not
2567/// `RestartPolicy`, so the paired owned-input
2568/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] axis
2569/// alone forces every call site through an explicit `.copied()` /
2570/// dereference / [`Copy`]-bound restatement rather than the direct
2571/// trait-idiomatic projection), a future generic
2572/// `<T: for<'a> Into<std::borrow::Cow<'static, str>>>`-bound emitter
2573/// on a per-child-policy diagnostic column that walks the
2574/// `iter().map(Into::into)` shape verbatim, the future M4 admission-
2575/// webhook rejection body that composes the accepted-policy
2576/// enumeration from an iterated
2577/// `RestartPolicy::ALL.iter().map(|p| p.into())` pipe rather than a
2578/// per-arm `match p { … }` cascade — reaches the same three-arm
2579/// lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2580/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2581/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2582/// paired [`std::fmt::Display`], [`AsRef<str>`],
2583/// [`RestartPolicy::as_str`], the four
2584/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
2585/// forward-projection corners, and the paired owned-input
2586/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] impl
2587/// already return.
2588///
2589/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
2590/// [`std::borrow::Cow::Owned`] — the substrate-primitive
2591/// [`RestartPolicy::as_str`] accessor's return carries the
2592/// `&'static str` lifetime by construction (each `match` arm resolves
2593/// to a [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const &str`
2594/// with static lifetime), so the zero-alloc borrowed arm is the
2595/// type-correct projection with no runtime allocation.
2596///
2597/// Closes the `{Self, &Self}` input-shape corner on the M2 OTP-shape
2598/// per-child-restart [`std::borrow::Cow<'static, str>`] axis opened
2599/// one commit prior (0612398) on the paired owned-input
2600/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] impl —
2601/// second-of-two-in-M2 closed-set fieldless typed enum peer on the
2602/// caixa surface (paired with the sibling-restart [`RestartStrategy`]
2603/// which carries both {Self, &Self} × Cow<'static, str> corners since
2604/// 7dd28b3 owned-input, 9b3e4b3 borrowed-input), exactly as d45c409
2605/// closed it on the top-level [`crate::CaixaKind`] one commit after
2606/// the owning half (99c1735) landed. This lift closes the whole M2
2607/// OTP-shape tier of the substrate-wide [`Cow<'static, str>`]
2608/// forward-projection campaign on both input-shape corners
2609/// ({Self, &Self}) of both M2 OTP-shape sibling peers
2610/// ([`RestartStrategy`] and [`RestartPolicy`]), so the remaining
2611/// eleven substrate-wide peers (`PlacementStrategy`, `RateLimitUnit`,
2612/// `DepList`, `CaixaDialeto`, `WitShape`, `PathShapeViolation`,
2613/// `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`,
2614/// `FerriteRuntime`) become the future targets of the campaign. Rust's
2615/// standard library does not carry a blanket
2616/// `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor an
2617/// `impl<T: fmt::Display> From<&T> for Cow<'static, str>`), so every
2618/// closed-set fieldless typed enum peer on the substrate that carries
2619/// the paired owned-input [`Cow<'static, str>`] axis but not the
2620/// borrowed-input axis forces every borrowed-input
2621/// [`Cow<'static, str>`]-parameterized call site through a spurious
2622/// [`Copy`] deref (`std::borrow::Cow::from(*policy)`) or a
2623/// `std::borrow::Cow::Borrowed(policy.as_str())` open-code whose type
2624/// bounds have no compile-time link to the substrate primitive.
2625///
2626/// Pinned load-bearing by
2627/// [`tests::restart_policy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor`]
2628/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
2629/// against [`RestartPolicy::as_str`] across the three-arm
2630/// [`RestartPolicy::ALL`] through the borrowed-input surface) and
2631/// [`tests::restart_policy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
2632/// (cross-axis partition pin against the paired owned-input
2633/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`], the
2634/// paired borrowed-input owned-`&'static str`
2635/// [`From<&RestartPolicy> for &'static str`], and the paired
2636/// borrowed-input owned-`String` [`From<&RestartPolicy> for String`]
2637/// impls, plus a `.iter().map(std::borrow::Cow::from)` pipe witness
2638/// over [`RestartPolicy::ALL`] — whose iterator yields
2639/// `&RestartPolicy` by construction, so the borrowed-input
2640/// [`Cow<'static, str>`] axis is what routes the pipe through the
2641/// substrate-primitive [`RestartPolicy::as_str`] accessor with the
2642/// zero-alloc [`Cow::Borrowed`] arm by construction and without a
2643/// spurious [`Copy`] deref).
2644impl From<&RestartPolicy> for std::borrow::Cow<'static, str> {
2645    fn from(policy: &RestartPolicy) -> std::borrow::Cow<'static, str> {
2646        std::borrow::Cow::Borrowed(policy.as_str())
2647    }
2648}
2649
2650/// Trait-idiomatic *owned-input, [`Box<str>`] output* forward
2651/// projection on the M2 OTP-shape per-child-restart [`RestartPolicy`]
2652/// closed-set fieldless typed enum — extends the substrate-wide
2653/// `Box<str>` forward-projection campaign tier opened one commit prior
2654/// (69ef45c) on the paired sibling-restart [`RestartStrategy`] onto
2655/// the second (and third-and-final) M2 OTP-shape closed-set fieldless
2656/// typed enum peer on the caixa surface (`:children :restart`),
2657/// immediately after the paired `Cow<'static, str>` axis (0612398 /
2658/// b4dc55c) closed the
2659/// `{Self, &Self} × {&'static str, String, Cow<'static, str>}` 2×3
2660/// corner on this enum. Routes byte-for-byte through the
2661/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
2662/// accessor via [`Box::<str>::from`] on the returned `&'static str`,
2663/// so every consumer that binds a
2664/// `let key: Box<str> = policy.into();`-shaped call site — a
2665/// per-child metric-key materializer that stashes the policy
2666/// discriminator in a `Box<str>`-typed heap-owned scalar for cheap
2667/// clone (a shared-nothing per-policy accept-set the `caixa-operator`
2668/// hierarchical reconciliation scheduler's per-child restart-decision
2669/// fan-out carries), a future admission-webhook rejection body whose
2670/// per-arm `Box<str>` field composes from an owned `RestartPolicy`
2671/// handle — reaches the same three-arm lifted
2672/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2673/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2674/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2675/// sibling
2676/// `{Self, &Self} × {&'static str, String, Cow<'static, str>}`
2677/// forward-projection corner already returns. Rust's standard library
2678/// carries `impl From<&str> for Box<str>` and
2679/// `impl From<String> for Box<str>` but no blanket
2680/// `impl<T: AsRef<str>> From<T> for Box<str>` (nor any
2681/// `impl<T: Copy, U: From<T>> From<T> for U` route from the enum), so
2682/// this axis is a distinct trait-idiomatic surface that a downstream
2683/// `RestartPolicy → Box<str>` `.into()` reaches through this impl and
2684/// no other — without a `Box::from(policy.as_str())` open-code whose
2685/// type bounds have no compile-time link back to the substrate
2686/// primitive.
2687///
2688/// Second peer on the substrate-wide trait-idiomatic [`Box<str>`]
2689/// forward-projection family opened on the sibling-restart
2690/// [`RestartStrategy`] (69ef45c / 59ae5dc) — closes the whole M2
2691/// OTP-shape tier of the substrate-wide [`Box<str>`] forward-
2692/// projection campaign's owned-input corner on both M2 OTP-shape
2693/// sibling peers ([`RestartStrategy`] and [`RestartPolicy`]), the
2694/// paired borrowed-input `From<&RestartPolicy> for Box<str>` closer
2695/// and the remaining fieldless-enum peers on the M3 mesh-shape /
2696/// outside-M3 caixa-core / render-side / outside-caixa-core tiers
2697/// are the future targets of the campaign.
2698///
2699/// Pinned load-bearing by
2700/// [`tests::restart_policy_from_into_box_str_routes_through_as_str_accessor`]
2701/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2702/// three-arm [`RestartPolicy::ALL`] emit-set on the owned-input
2703/// surface, plus a blanket-derived [`Into`] shape witness).
2704impl From<RestartPolicy> for Box<str> {
2705    fn from(policy: RestartPolicy) -> Box<str> {
2706        Box::<str>::from(policy.as_str())
2707    }
2708}
2709
2710/// Trait-idiomatic *borrowed-input, [`Box<str>`] output* forward
2711/// projection on the M2 OTP-shape per-child-restart [`RestartPolicy`]
2712/// closed-set fieldless typed enum — the borrowed-input companion to
2713/// the paired owned-input [`From<RestartPolicy> for Box<str>`] impl
2714/// (0a1b313, one commit prior) that closes the `{Self, &Self}`
2715/// input-shape corner of the substrate-wide [`Box<str>`] forward-
2716/// projection axis on the second (and third-and-final) M2 OTP-shape
2717/// closed-set fieldless typed enum peer on the caixa surface
2718/// (`:children :restart`), routing byte-for-byte through the
2719/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
2720/// accessor via [`Box::<str>::from`] on the returned `&'static str`.
2721/// Every consumer that holds a `&RestartPolicy` and needs a
2722/// [`Box<str>`] — a
2723/// `RestartPolicy::ALL.iter().map(Box::<str>::from).collect::<Vec<_>>()`
2724/// per-arm accept-set materializer (whose iterator over
2725/// `&'static [RestartPolicy]` yields `&RestartPolicy`, not
2726/// `RestartPolicy`, so the paired owned-input
2727/// [`From<RestartPolicy> for Box<str>`] axis alone forces every
2728/// call site through an explicit [`Copy`] deref or a
2729/// `.copied()` restatement rather than the direct trait-idiomatic
2730/// projection), a per-child metric-key materializer holding
2731/// `&RestartPolicy` through a `caixa-operator` hierarchical
2732/// reconciliation scheduler's borrow lifetime, a future admission-
2733/// webhook rejection body whose per-arm `Box<str>` field composes
2734/// from a borrowed `&RestartPolicy` handle — reaches the
2735/// substrate-primitive [`RestartPolicy::as_str`] accessor through
2736/// this impl and no other, without a
2737/// `Box::<str>::from(policy.as_str())` open-code whose type bounds
2738/// have no compile-time link back to the substrate primitive.
2739///
2740/// Rust's standard library carries `impl From<&str> for Box<str>`
2741/// and `impl From<String> for Box<str>` but no blanket
2742/// `impl<T: AsRef<str>> From<&T> for Box<str>` (nor a
2743/// `Copy`-based `impl<T: Copy, U: From<&T> for U`), so every closed-
2744/// set fieldless typed enum peer on the substrate that carries the
2745/// paired owned-input `Box<str>` axis but not the borrowed-input
2746/// axis forces every borrowed-input `Box<str>`-parameterized call
2747/// site through a spurious [`Copy`] deref
2748/// (`Box::<str>::from((*policy).as_str())`) or a
2749/// `Box::<str>::from(policy.as_str())` open-code whose type bounds
2750/// have no compile-time link back to the substrate primitive.
2751///
2752/// Fourth (and closing) peer on the substrate-wide trait-idiomatic
2753/// [`Box<str>`] forward-projection family on the M2 OTP-shape tier
2754/// — closes the whole `{Self, &Self}` input-shape corner of the
2755/// [`Box<str>`] axis on both M2 OTP-shape sibling peers
2756/// ([`RestartStrategy`] and [`RestartPolicy`]), exactly as b4dc55c
2757/// closed the paired [`Cow<'static, str>`] axis one commit after
2758/// its owning half (0612398) landed on this enum. The remaining
2759/// fieldless-enum peers on the M3 mesh-shape / outside-M3 caixa-
2760/// core / render-side / outside-caixa-core tiers are the future
2761/// targets of the [`Box<str>`] campaign.
2762///
2763/// Pinned load-bearing by
2764/// [`tests::restart_policy_from_borrowed_into_box_str_routes_through_as_str_accessor`]
2765/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2766/// three-arm [`RestartPolicy::ALL`] emit-set on the borrowed-input
2767/// surface, plus a blanket-derived [`Into`] shape witness, a
2768/// cross-axis partition pin against the paired owned-input
2769/// [`From<RestartPolicy> for Box<str>`] and the sibling borrowed-
2770/// input `{&'static str, String, Cow<'static, str>}` return-shape
2771/// axes, and a `.iter().map(Box::<str>::from)` pipe witness over
2772/// [`RestartPolicy::ALL`] — whose iterator yields `&RestartPolicy`
2773/// by construction, so the borrowed-input [`Box<str>`] axis is
2774/// what routes the pipe through the substrate-primitive
2775/// [`RestartPolicy::as_str`] accessor without a spurious [`Copy`]
2776/// deref).
2777impl From<&RestartPolicy> for Box<str> {
2778    fn from(policy: &RestartPolicy) -> Box<str> {
2779        Box::<str>::from(policy.as_str())
2780    }
2781}
2782
2783/// Trait-idiomatic *owned-input, [`std::sync::Arc<str>`] output*
2784/// forward projection on the M2 OTP-shape per-child-restart
2785/// [`RestartPolicy`] closed-set fieldless typed enum — routes byte-
2786/// for-byte through the substrate-primitive [`RestartPolicy::as_str`]
2787/// `pub const fn` accessor via [`std::sync::Arc::<str>::from`] on the
2788/// returned `&'static str`, so every consumer that binds a
2789/// [`RestartPolicy`] through the standard-library `.into()` /
2790/// [`From<Self> for std::sync::Arc<str>`] (equivalently
2791/// [`Into<std::sync::Arc<str>>`]) axis — a future admission-webhook's
2792/// per-request `Sync` + `Send`-safe structured-log field composed
2793/// across an `.await` boundary through a
2794/// `<T: Into<std::sync::Arc<str>>>`-bound diagnostic-column dispatch,
2795/// a future wasm-operator's per-child post-exit restart-decision
2796/// pipeline holding a shared-ownership per-arm cache key, a
2797/// `<T: Into<std::sync::Arc<str>>>`-bound `tracing`-span attributes
2798/// collector recording a per-child-policy field onto the parent
2799/// span's shared-ownership context — reaches the same three-arm
2800/// lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2801/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2802/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2803/// sibling
2804/// `{Self, &Self} × {&'static str, String, Cow<'static, str>, Box<str>}`
2805/// forward-projection corner already returns.
2806///
2807/// Second peer on the substrate-wide trait-idiomatic
2808/// [`std::sync::Arc<str>`] forward-projection family opened one
2809/// projection tier prior (bca2ec8) on the paired sibling-restart
2810/// [`RestartStrategy`] owned-input first-mover — extends the tier
2811/// onto the second (and third-and-final) M2 OTP-shape closed-set
2812/// fieldless typed enum peer on the caixa surface
2813/// (`:children :restart`), immediately after the paired [`Box<str>`]
2814/// axis (0a1b313 / cb1d068) closed the whole
2815/// `{Self, &Self} × {&'static str, String, Cow<'static, str>, Box<str>}`
2816/// 2×4 corner on this enum. Rust's standard library carries
2817/// `impl From<&str> for std::sync::Arc<str>` and
2818/// `impl From<String> for std::sync::Arc<str>` but no blanket
2819/// `impl<T: AsRef<str>> From<T> for std::sync::Arc<str>` (nor an
2820/// `impl<T: fmt::Display> From<T> for std::sync::Arc<str>`), so this
2821/// axis is a distinct trait-idiomatic surface that a
2822/// `let key: std::sync::Arc<str> = policy.into();`-shaped call site
2823/// reaches through this impl and no other — a paired
2824/// `std::sync::Arc::<str>::from(policy.as_str())` open-code has no
2825/// compile-time link back to the substrate primitive, and a two-step
2826/// `std::sync::Arc::<str>::from(String::from(policy))` composition
2827/// through the owned-`String` axis allocates twice (once into the
2828/// intermediate `String`, once into the [`Arc<str>`] on the
2829/// `From<String>` conversion) where the single-step trait impl
2830/// allocates once.
2831///
2832/// Peer of the sibling [`Box<str>`] second-tier extender (0a1b313) —
2833/// same "extends the substrate-wide projection tier onto the next
2834/// M2 OTP-shape peer" discipline, extended onto the
2835/// [`std::sync::Arc<str>`] axis whose shared-ownership + [`Sync`] +
2836/// [`Send`] contract is the distinct value the [`Box<str>`] axis's
2837/// owned-move return-shape cannot provide.
2838///
2839/// Pinned load-bearing by
2840/// [`tests::restart_policy_from_into_arc_str_routes_through_as_str_accessor`]
2841/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2842/// three-arm [`RestartPolicy::ALL`] emit-set on the owned-input
2843/// surface, plus a blanket-derived [`Into`] shape witness and cross-
2844/// axis byte-parity pins against the sibling owned-input
2845/// `{&'static str, String, Cow<'static, str>, Box<str>}` return-shape
2846/// axes).
2847impl From<RestartPolicy> for std::sync::Arc<str> {
2848    fn from(policy: RestartPolicy) -> std::sync::Arc<str> {
2849        std::sync::Arc::<str>::from(policy.as_str())
2850    }
2851}
2852
2853/// Trait-idiomatic *borrowed-input, [`std::sync::Arc<str>`] output*
2854/// forward projection on the M2 OTP-shape per-child-restart
2855/// [`RestartPolicy`] closed-set fieldless typed enum — closes the
2856/// `{Self, &Self}` input-shape corner of the [`std::sync::Arc<str>`]
2857/// forward-projection axis on the second (and third-and-final) M2
2858/// OTP-shape closed-set fieldless typed enum peer on the caixa
2859/// surface (`:children :restart`), companion to the paired
2860/// owned-input [`From<RestartPolicy> for std::sync::Arc<str>`] impl
2861/// one commit prior (b05724e). Routes byte-for-byte through the
2862/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
2863/// accessor (via [`std::sync::Arc::<str>::from`] on the returned
2864/// `&'static str`), so every consumer that binds a
2865/// [`&RestartPolicy`] through the standard-library `.into()` /
2866/// [`From<&Self> for std::sync::Arc<str>`] (equivalently
2867/// [`Into<std::sync::Arc<str>>`]) axis — a future admission-webhook's
2868/// per-request borrowed-`&RestartPolicy` handle rendering a per-arm
2869/// `Sync` + `Send`-safe structured-log field across an `.await`
2870/// boundary through a `<T: Into<std::sync::Arc<str>>>`-bound
2871/// diagnostic-column dispatch, a future wasm-operator's per-child
2872/// post-exit restart-decision pipeline whose
2873/// `.iter().map(std::sync::Arc::<str>::from)` collector reaches
2874/// into the shared-ownership per-arm key without a spurious [`Copy`]
2875/// deref (which would only be reachable through the owned-input
2876/// [`From<RestartPolicy> for std::sync::Arc<str>`] axis by first
2877/// calling `.copied()` on the iterator), a future
2878/// `<T: Into<std::sync::Arc<str>>>`-bound `tracing`-span attributes
2879/// collector recording a borrowed-`&RestartPolicy` per-arm field
2880/// onto the parent span's shared-ownership context — reaches the
2881/// same three-arm lifted
2882/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2883/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2884/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2885/// paired owned-input [`From<RestartPolicy> for std::sync::Arc<str>`]
2886/// impl and the sibling `{&'static str, String, Cow<'static, str>,
2887/// Box<str>}` forward-projection corner already return.
2888///
2889/// Closes the substrate-wide trait-idiomatic
2890/// [`std::sync::Arc<str>`] forward-projection family opened one
2891/// commit prior (b05724e) on the paired owned-input
2892/// [`From<RestartPolicy> for std::sync::Arc<str>`] impl — closes
2893/// the `{Self, &Self}` input-shape corner of the
2894/// [`std::sync::Arc<str>`] axis on the second (and third-and-final)
2895/// M2 OTP-shape closed-set fieldless typed enum peer on the caixa
2896/// surface, exactly as b3e72d7 closed the paired
2897/// [`std::sync::Arc<str>`] corner on the sibling-restart
2898/// [`RestartStrategy`] first-mover one commit after its owning half
2899/// (bca2ec8) landed, and as cb1d068 closed the paired [`Box<str>`]
2900/// corner on this enum one commit after its owning half (0a1b313)
2901/// landed. Rust's standard library carries `impl From<&str> for
2902/// std::sync::Arc<str>` and `impl From<String> for
2903/// std::sync::Arc<str>` but no blanket `impl<T: AsRef<str>> From<&T>
2904/// for std::sync::Arc<str>` (nor a `Copy`-based `impl<T: Copy,
2905/// U: From<T>> From<&T> for U`), so every closed-set fieldless typed
2906/// enum peer on the substrate that carries the paired owned-input
2907/// [`std::sync::Arc<str>`] axis but not the borrowed-input axis
2908/// forces every borrowed-input [`std::sync::Arc<str>`]-parameterized
2909/// call site through a spurious [`Copy`] deref
2910/// (`std::sync::Arc::<str>::from((*policy).as_str())`) or a
2911/// `std::sync::Arc::<str>::from(policy.as_str())` open-code whose
2912/// type bounds have no compile-time link back to the substrate
2913/// primitive.
2914///
2915/// Pinned load-bearing by
2916/// [`tests::restart_policy_from_borrowed_into_arc_str_routes_through_as_str_accessor`]
2917/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2918/// three-arm [`RestartPolicy::ALL`] emit-set on the borrowed-input
2919/// surface, plus a blanket-derived [`Into`] shape witness, a
2920/// cross-axis pin against the paired owned-input
2921/// [`From<RestartPolicy> for std::sync::Arc<str>`] and the sibling
2922/// borrowed-input `{&'static str, String, Cow<'static, str>,
2923/// Box<str>}` return-shape axes, and a
2924/// `.iter().map(std::sync::Arc::<str>::from)` pipe witness over
2925/// [`RestartPolicy::ALL`]).
2926impl From<&RestartPolicy> for std::sync::Arc<str> {
2927    fn from(policy: &RestartPolicy) -> std::sync::Arc<str> {
2928        std::sync::Arc::<str>::from(policy.as_str())
2929    }
2930}
2931
2932/// Trait-idiomatic byte-view surface on the per-child restart-decision
2933/// policy typed enum.
2934///
2935/// Every consumer that binds its input through the standard-library
2936/// [`AsRef<[u8]>`] trait bound — a byte-keyed
2937/// `HashMap<K: AsRef<[u8]>, V>` per-policy reconciliation-decision
2938/// table lookup on the future wasm-operator supervisor scheduler; a
2939/// `blake3::Hasher::update` / `ring::digest::Context::update` /
2940/// `sha2::Sha256::update` byte-input surface on any future per-child
2941/// content-address digest folded into the [`crate::Lacre`] closure so
2942/// downstream cache-keys partition on the three OTP restart policies
2943/// (`Permanent`, `Temporary`, `Transient`) at content-address time; an
2944/// `std::io::Write::write_all`-bound structured-log per-arm byte-sink —
2945/// reaches the substrate primitive through one trait dispatch rather
2946/// than open-coding the two-hop `restart.as_str().as_bytes()`
2947/// composition at every call site. Routed byte-for-byte through the
2948/// [`RestartPolicy::as_str`] `pub const fn` accessor the paired
2949/// str-view ([`AsRef<str>`], [`std::fmt::Display`],
2950/// [`RestartPolicy::as_str`]) and the five reverse-projection
2951/// (`&'static str`, `String`, `Cow<'static, str>`, `Box<str>`,
2952/// `std::sync::Arc<str>`) return-shape axes already resolve through,
2953/// so any future divergence between the byte-view and str-view axes
2954/// trips at caixa-core test time rather than at a downstream byte-
2955/// consumer's silent split.
2956///
2957/// Peer of the sibling per-supervisor-restart-strategy axis
2958/// [`AsRef<[u8]> for RestartStrategy`] (cd4c4e0, the first M2-OTP-
2959/// shape supervisor slot enum to open this axis) — the sixth
2960/// closed-set fieldless typed enum on the caixa surface to converge
2961/// onto the trait-idiomatic byte-view discipline, and the second (and
2962/// final) M2-OTP-shape sibling to pick it up, closing the byte-view
2963/// axis across the paired `:supervisor :estrategia` +
2964/// `:children :restart` M2 slot pair. Pin load-bearing by the paired
2965/// [`tests::restart_policy_as_ref_bytes_routes_through_as_str_accessor`]
2966/// (fail-before-pass-after byte-parity pin against
2967/// [`RestartPolicy::as_str`] `.as_bytes()` across the three-arm
2968/// [`RestartPolicy::ALL`] emit-set, cross-axis witness against the
2969/// paired str-view [`AsRef<str>`] / [`std::fmt::Display`] /
2970/// [`RestartPolicy::as_str`] axes' `.as_bytes()` byte-tails,
2971/// cross-axis witness against the paired reverse-projection
2972/// `{&'static str, String, Cow<'static, str>, Box<str>,
2973/// std::sync::Arc<str>}` return-shape axes' `.as_bytes()` byte-tails,
2974/// a `<T: AsRef<[u8]>>`-bound-consumer witness that a generic
2975/// byte-input function accepts a [`RestartPolicy`] directly through
2976/// the trait bound, and a `blake3::Hasher::update`-shape byte-input
2977/// surface witness routed through the `<T: AsRef<[u8]>>`-bound
2978/// consumer axis to reach the caixa-lacre compounding target). Any
2979/// future silent detour that routes the byte-view impl off the
2980/// substrate-primitive [`RestartPolicy::as_str`] accessor (a per-arm
2981/// inline `b"Permanent".as_slice()`-shaped re-inlining that opens a
2982/// compile-time link to the un-lifted arm-literal, a swap onto the
2983/// kebab-case [`gen_platform::Discriminant`] catalog identity that
2984/// would collide the wire axis with the dispatcher-catalog axis) trips
2985/// at caixa-core test time rather than at a downstream byte-consumer's
2986/// silent split.
2987impl AsRef<[u8]> for RestartPolicy {
2988    fn as_ref(&self) -> &[u8] {
2989        self.as_str().as_bytes()
2990    }
2991}
2992
2993/// Trait-idiomatic *owned-input, owned-`Vec<u8>` output* byte-owned
2994/// reverse projection on the second (and final) M2 OTP-shape closed-set
2995/// fieldless typed enum peer on the caixa surface ([`RestartPolicy`]) —
2996/// the byte-mirror of the [`From<RestartPolicy> for String`] str-owned
2997/// reverse-projection axis and the owned-`Vec<u8>` reverse-projection
2998/// sibling of the paired [`AsRef<[u8]>`] borrowed byte-view axis
2999/// (98b08fa) lifted on this same enum. Routes byte-for-byte through
3000/// the substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
3001/// accessor via [`str::as_bytes`] + [`slice::to_vec`] so every
3002/// consumer that binds a [`RestartPolicy`] through the standard-
3003/// library `impl From<RestartPolicy> for Vec<u8>` axis
3004/// (equivalently `<T: Into<Vec<u8>>>`) — a future
3005/// [`std::io::Write::write_all`]-shape per-child audit-log byte-sink
3006/// whose input parameter is an owned [`Vec<u8>`] payload, a future
3007/// `bytes::Bytes::from(Vec::<u8>::from(restart))` composer folding
3008/// the per-arm restart-decision-policy byte-tag into the
3009/// [`bytes::Bytes`] framing surface, a future
3010/// `hasher.update(&Vec::<u8>::from(restart))`-shape BLAKE3 content-
3011/// address closure that needs the owned byte-tail buffered before
3012/// folding into the [`crate::Lacre`] closure body, a future per-child
3013/// protobuf/CBOR/msgpack payload composer whose framer takes an owned
3014/// [`Vec<u8>`] rather than a borrowed byte-slice — reaches the
3015/// substrate primitive through one trait dispatch rather than an
3016/// open-coded per-call-site `restart.as_str().as_bytes().to_vec()`
3017/// composition whose type bounds have no compile-time link back to
3018/// the substrate primitive.
3019///
3020/// Closes the substrate-wide trait-idiomatic byte-owned reverse-
3021/// projection axis on the M2-OTP-shape `:supervisor :estrategia` +
3022/// `:children :restart` slot pair the sibling
3023/// [`RestartStrategy`] first-mover (63e5dd0) opened one commit prior,
3024/// matching the discipline the paired [`AsRef<[u8]>`] borrowed byte-
3025/// view axis campaign already carried across the same slot pair
3026/// (cd4c4e0 → 98b08fa). Every future arm addition (an OTP-
3027/// `intrinsic` fourth arm the theory
3028/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
3029/// might reach for once the three canonical OTP restart policies
3030/// stop covering the substrate's discovered load-shape) grows the
3031/// byte-owned axis through one edit on the substrate-primitive
3032/// [`RestartPolicy::as_str`] accessor.
3033///
3034/// Pinned load-bearing by
3035/// [`tests::restart_policy_from_into_owned_vec_bytes_routes_through_as_str_accessor`]
3036/// (byte-parity pin against [`RestartPolicy::as_str`] across the
3037/// three-arm [`RestartPolicy::ALL`] emit-set binding the byte-owned
3038/// reverse-projection axis against the paired [`AsRef<[u8]>`]
3039/// borrowed byte-view axis and the str-owned reverse-projection
3040/// family (`String`, `Cow<'static, str>`, `Box<str>`,
3041/// `std::sync::Arc<str>`) `.into_bytes()` / `.as_bytes().to_vec()`
3042/// byte-tails, a `<T: Into<Vec<u8>>>`-bound generic-consumer witness,
3043/// and a `std::io::Write::write_all`-shape owned-byte-sink surface
3044/// witness on both owned and borrowed input shapes).
3045impl From<RestartPolicy> for Vec<u8> {
3046    fn from(policy: RestartPolicy) -> Vec<u8> {
3047        policy.as_str().as_bytes().to_vec()
3048    }
3049}
3050
3051/// Trait-idiomatic *borrowed-input, owned-`Vec<u8>` output* byte-
3052/// owned reverse projection on the second (and final) M2 OTP-shape
3053/// closed-set fieldless typed enum peer on the caixa surface
3054/// ([`RestartPolicy`]) — the borrowed-input peer of
3055/// [`From<RestartPolicy> for Vec<u8>`], closing the
3056/// `{Self, &Self} → Vec<u8>` pair on the byte-owned reverse-projection
3057/// axis in one lift. Routes byte-for-byte through the substrate-
3058/// primitive [`RestartPolicy::as_str`] `pub const fn` accessor so
3059/// every consumer that holds a borrowed [`&RestartPolicy`] and needs
3060/// an owned [`Vec<u8>`] — a future
3061/// `.iter().map(Vec::<u8>::from).collect()` pipe over
3062/// `&[RestartPolicy]` (whose iterator yields `&RestartPolicy`,
3063/// not `RestartPolicy`, so the owned-input axis alone forces every
3064/// call site through an explicit `.copied()` / spurious [`Copy`]
3065/// deref restatement rather than the direct trait-idiomatic
3066/// projection), a future admission-webhook rejection body composer
3067/// that walks [`RestartPolicy::ALL`] through an `Into<Vec<u8>>`-
3068/// bound per-arm byte-writer to surface the accepted `:children
3069/// :restart` set — reaches the substrate primitive through one
3070/// trait dispatch rather than a `Vec::<u8>::from(*policy)` spurious-
3071/// [`Copy`]-deref restatement.
3072impl From<&RestartPolicy> for Vec<u8> {
3073    fn from(policy: &RestartPolicy) -> Vec<u8> {
3074        policy.as_str().as_bytes().to_vec()
3075    }
3076}
3077
3078// Fleet-wide dispatcher-catalog registrations for caixa's OTP
3079// supervisor surface — two more typed shadows over Erlang/OTP
3080// primitives the substrate now mechanically tracks (see
3081// theory/UNIFIED-COMPUTING-MODEL.md §VI for the roadmap +
3082// theory/TYPED-ABSORPTION.md for the absorption arc).
3083gen_platform::register_dispatcher!("caixa.restart-strategy", RestartStrategy);
3084gen_platform::register_dispatcher!("caixa.restart-policy", RestartPolicy);
3085
3086/// One child entry in the supervisor's `:children` list.
3087///
3088/// Every child references another caixa by `:caixa <nome>` + version
3089/// constraint. The supervisor materializes one ComputeUnit per entry.
3090#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
3091#[serde(rename_all = "camelCase")]
3092pub struct ChildSpec {
3093    /// The child caixa's `:nome`. Must resolve via the same dependency
3094    /// resolution path as `:deps` (caixa-resolver).
3095    pub caixa: String,
3096
3097    /// Semver constraint (`"^0.1"`, `"~0.1.2"`, etc.) — same shape as
3098    /// [`crate::dep::Dep::versao`].
3099    pub versao: String,
3100
3101    /// Restart policy — an author-omitted slot degrades onto the
3102    /// substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`]
3103    /// (`permanent`, the Erlang/OTP worker-child default) through the
3104    /// [`Default for RestartPolicy`] impl this `#[serde(default)]` routes
3105    /// to.
3106    #[serde(default)]
3107    pub restart: RestartPolicy,
3108}
3109
3110impl ChildSpec {
3111    /// Substrate-canonical per-`:children` child-caixa `:nome` scalar
3112    /// accessor every consumer that reads the OTP-shape supervised
3113    /// child's identity keys off — returns the author-declared
3114    /// `:children :caixa` byte-string verbatim as a `&str`, borrowed
3115    /// from the typed slot's own [`String`] storage.
3116    ///
3117    /// The `:children :caixa` slot carries the DNS-1123 label — the
3118    /// child caixa's `:nome` — that every emitted cluster artifact
3119    /// derives its `metadata.name` from verbatim: the rendered
3120    /// `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name` per child, the
3121    /// [`crate::LABEL_PROGRAM`] label value on every child's pod
3122    /// identity, and the per-child K8s Service `metadata.name` the
3123    /// future wasm-operator (M3) provisions for inter-child supervision-
3124    /// tree wiring. Every downstream consumer that fans on the child's
3125    /// caixa-name keys off this scalar (the [`SupervisorSpec::validate`]
3126    /// per-child DNS-1123 gate at
3127    /// `require_valid_dns_1123_label(child.nome(), …)`, the per-child
3128    /// duplicate-detection [`crate::render::insert_first_seen`] key, the
3129    /// [`validate_no_self_supervision`] cross-slot equality check
3130    /// against the parent's `:nome`, every `SupervisorError` variant
3131    /// carrying the offending child caixa verbatim for `feira lint`
3132    /// rendering, the future wasm-operator's hierarchical reconciliation
3133    /// scheduler's per-child ComputeUnit-name projection, the future M4
3134    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
3135    /// admission webhook).
3136    ///
3137    /// Prior to this lift the `.caixa` byte-string was accessed inline
3138    /// at seven sites in `supervisor.rs` — the DNS-1123 gate's
3139    /// `&child.caixa`, the four `SupervisorError::{ChildCaixaInvalid,
3140    /// EmptyChildVersion, ChildVersaoInvalid, DuplicateChildCaixa}`
3141    /// carriers' `child.caixa.clone()`, the dedup key's
3142    /// `child.caixa.as_str()`, and the [`validate_no_self_supervision`]
3143    /// `child.caixa == parent_nome` cross-slot check — seven open-coded
3144    /// field-accesses that expressed no compile-time link back to the
3145    /// typed slot. A future extension of the `:children :caixa` axis to
3146    /// a richer author surface (a per-cluster alias table the operator
3147    /// pins through a future `:placement`-scoped slot on the supervisor
3148    /// tree, a namespace-qualified rewrite the M4 CR materializer
3149    /// applies per-CR, a per-child overlay from the future `:children
3150    /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
3151    /// acknowledges) would have had to be threaded through every
3152    /// open-coded copy in lockstep or one consumer would silently
3153    /// disagree with the peers on which caixa a given child resolves to
3154    /// — a child-set lookup that treated the name as `"cart-worker"`
3155    /// while the peer duplicate-detector treated it as
3156    /// `"tenant-a/cart-worker"` would silently split the
3157    /// `DuplicateChildCaixa` membership-lookup diagnostic from the
3158    /// self-supervision detector's parent-equality check, a two-consumer
3159    /// split at the validator far from the source `caixa.lisp` with no
3160    /// field naming the identity-drift root cause. Lifting the resolution
3161    /// rule to a typed method on the substrate primitive means every
3162    /// downstream consumer of the Supervisor's per-`:children` identity
3163    /// surface reaches for exactly one typed dispatch — the resolver's
3164    /// accept-set migrates as a unit on any future axis addition.
3165    ///
3166    /// Sibling of the peer per-`:membros` [`crate::Membro::nome`]
3167    /// (4a32abf) member-caixa `:nome` scalar accessor on the M3
3168    /// mesh-slot surface — same "one typed dispatch on the substrate
3169    /// primitive, thin projections at each consumer" discipline extended
3170    /// onto the M2 supervisor-tree per-`:children` child-identity axis.
3171    /// The two typed axes (`Membro::nome` on the M3 Aplicacao side,
3172    /// `ChildSpec::nome` on the M2 Supervisor side) now share one
3173    /// accessor discipline for the shared substrate concept "another
3174    /// caixa referenced by `:nome`". Peer of the second M2 slot scalar
3175    /// accessor [`crate::UpgradeFromEntry::prior_versao`] (75d27a8) on
3176    /// the sibling per-`:upgrade-from :from` OTP-appup axis — the M2
3177    /// slot family's typed-accessor discipline now spans both the
3178    /// upgrade axis (`:upgrade-from`) and the supervision axis
3179    /// (`:children`), matching the closed M3 mesh-slot accessor family's
3180    /// shape. Named `nome()` to match the tatara-lisp author-surface
3181    /// term the field's docstring already reaches for ("The child
3182    /// caixa's `:nome`") and the peer [`crate::Membro::nome`] /
3183    /// [`crate::Caixa::nome`] / [`crate::dep::Dep::nome`] field-name
3184    /// discipline the substrate already carries — the accessor's name
3185    /// maps directly onto the canonical caixa-identity vocabulary rather
3186    /// than shadowing the field's storage-side `caixa` label.
3187    #[must_use]
3188    pub const fn nome(&self) -> &str {
3189        self.caixa.as_str()
3190    }
3191
3192    /// Substrate-canonical per-`:children` child-caixa `:versao` semver-
3193    /// requirement scalar accessor every consumer that reads the OTP-shape
3194    /// supervised child's version pin keys off — returns the author-declared
3195    /// `:children :versao` byte-string verbatim as a `&str`, borrowed from
3196    /// the typed slot's own [`String`] storage.
3197    ///
3198    /// The `:children :versao` slot carries the Cargo-shaped semver
3199    /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that pins
3200    /// which release of the supervised child caixa the OTP-shape supervisor
3201    /// tree materializes against — the same requirement grammar the peer
3202    /// `:deps :versao` / `:membros :versao` axes carry, resolved through the
3203    /// shared [`crate::render::require_valid_versao_requirement`] cascade
3204    /// and the shared [`crate::version::parse_requirement`] parser. Every
3205    /// downstream consumer that fans on the child's version pin keys off
3206    /// this scalar (the [`SupervisorSpec::validate`] per-child requirement
3207    /// gate at `require_valid_versao_requirement(child.versao_requirement(),
3208    /// …)`, the [`SupervisorError::ChildVersaoInvalid`] variant's carrier
3209    /// for `feira lint` rendering, every future per-cluster version-lock
3210    /// overlay the caixa-operator's hierarchical reconciliation scheduler
3211    /// pins through a future `:placement`-scoped supervisor-tree slot, the
3212    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
3213    /// per-child version resolver, the future wasm-operator's per-child
3214    /// lacre BLAKE3-closure lookup at `ComputeUnit` materialization time).
3215    ///
3216    /// Prior to this lift the `.versao` byte-string was accessed inline at
3217    /// two `&str`-shaped sites in `caixa-core/src/supervisor.rs` — the
3218    /// [`SupervisorSpec::validate`] requirement-gate call
3219    /// `require_valid_versao_requirement(&child.versao, …)` and the
3220    /// [`SupervisorError::ChildVersaoInvalid`] carrier at
3221    /// `versao: child.versao.clone()` — two open-coded field-accesses that
3222    /// expressed no compile-time link back to the typed slot. A future
3223    /// extension of the `:children :versao` axis to a richer author surface
3224    /// (a per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
3225    /// flow, a lacre-projected concrete-version rewrite the operator
3226    /// materializes at CR-admission time, a future `:children :versao-lock`
3227    /// per-cluster override slot the wasm-operator's hierarchical
3228    /// reconciliation scheduler authors per-CR) would have had to be
3229    /// threaded through both open-coded copies in lockstep or one consumer
3230    /// would silently disagree with the peer on which release constraint a
3231    /// given child resolves to — the requirement-gate call reading
3232    /// `"^0.1"` while the error-body carrier read `"tenant-a-pin/^0.1"`
3233    /// would silently split the `ChildVersaoInvalid` diagnostic quote from
3234    /// the actual gate rejection input, a two-consumer split at the
3235    /// validator far from the source `caixa.lisp` with no field naming the
3236    /// version-pin drift root cause. Lifting the resolution rule to a typed
3237    /// method on the substrate primitive means every downstream
3238    /// requirement-facing consumer of the Supervisor's per-`:children`
3239    /// version-pin surface reaches for exactly one typed dispatch — the
3240    /// resolver's accept-set migrates as a unit on any future axis addition.
3241    ///
3242    /// Sibling of the peer per-`:membros` [`crate::Membro::versao_requirement`]
3243    /// (a40b0e3) member-caixa `:versao` scalar accessor on the M3 mesh-slot
3244    /// surface — same "one typed dispatch on the substrate primitive, thin
3245    /// projections at each consumer" discipline extended onto the M2
3246    /// supervisor-tree per-`:children` child-version-pin axis. The two typed
3247    /// axes (`Membro::versao_requirement` on the M3 Aplicacao side,
3248    /// `ChildSpec::versao_requirement` on the M2 Supervisor side) now share
3249    /// one accessor discipline for the shared substrate concept "another
3250    /// caixa referenced by a Cargo-shaped semver requirement". Peer of the
3251    /// sibling per-`:children` [`ChildSpec::nome`] (57c61d0) child-caixa
3252    /// `:nome` scalar accessor — the pair
3253    /// `(nome(), versao_requirement())` jointly projects the
3254    /// `(caixa, versao)` field pair every OTP-shape supervisor-tree consumer
3255    /// that fans on per-child identity + version pin keys off, closing the
3256    /// last unlifted per-`:children` `String`-carry axis so every downstream
3257    /// per-`:children` reader now routes through a typed dispatch on the
3258    /// substrate primitive. Named `versao_requirement()` rather than
3259    /// `versao()` because the field's storage-side `.versao` label is
3260    /// already the author-surface term (`:versao`); the accessor's name
3261    /// carries the semantic role — the semver *requirement* string the
3262    /// shared [`crate::version::parse_requirement`] entry-point consumes —
3263    /// so a raw field access and a typed dispatch read differently at every
3264    /// consumer site. Matches the peer [`crate::Membro::versao_requirement`]
3265    /// naming discipline verbatim.
3266    #[must_use]
3267    pub const fn versao_requirement(&self) -> &str {
3268        self.versao.as_str()
3269    }
3270
3271    /// Substrate-canonical per-`:children` `:restart` OTP-shaped
3272    /// per-child post-exit restart-decision policy scalar accessor every
3273    /// consumer that dispatches on the supervised child's post-exit
3274    /// reconcile posture keys off — returns the author-declared
3275    /// `:children :restart` variant verbatim as a [`RestartPolicy`],
3276    /// `Copy`-projected from the typed slot's own [`RestartPolicy`]
3277    /// storage.
3278    ///
3279    /// The `:children :restart` slot carries the closed-set OTP-shaped
3280    /// per-child restart-decision policy discriminator
3281    /// ([`RestartPolicy::Permanent`] — always restart, the OTP `permanent`
3282    /// worker-child default; [`RestartPolicy::Transient`] — restart only
3283    /// on abnormal exit, the OTP `transient` clean-completion-aware
3284    /// default; [`RestartPolicy::Temporary`] — never restart, the OTP
3285    /// `temporary` one-shot default) that every downstream consumer of
3286    /// the Supervisor's per-child post-exit reconcile branch keys off.
3287    /// Every future downstream consumer that fans on the per-child
3288    /// restart-decision keys off this scalar (the future `feira app
3289    /// graph` per-child restart column, the future wasm-operator's
3290    /// per-child post-exit restart-decision branch, the future M4
3291    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
3292    /// admission webhook, the `caixa-operator`'s hierarchical
3293    /// reconciliation scheduler's per-child post-exit reconcile branch,
3294    /// the [`RestartPolicy::as_str`] `Serialize`-derive-pinning path the
3295    /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
3296    /// pin threads through).
3297    ///
3298    /// Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
3299    /// (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
3300    /// scalar accessor and the M3 mesh-slot
3301    /// [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
3302    /// [`crate::PlacementStrategy`] distribution-strategy scalar accessor
3303    /// — same "one typed dispatch on the substrate primitive,
3304    /// `Copy`-projected closed-set enum-arm discriminator that partitions
3305    /// the downstream renderer's per-arm fan-out" discipline extended
3306    /// onto the M2 supervisor-slot per-`:children` restart-decision-policy
3307    /// `Copy`-composite-enum scalar axis. Third axis on the per-`:children`
3308    /// [`ChildSpec`] type — companion to the sibling per-`:children`
3309    /// [`ChildSpec::nome`] (57c61d0) child-caixa `:nome` scalar accessor
3310    /// and the per-`:children` [`ChildSpec::versao_requirement`]
3311    /// (2c053c8) child-caixa `:versao` semver-requirement scalar accessor
3312    /// on the sibling `String`-carry axes. The triple
3313    /// `(nome(), versao_requirement(), restart())` jointly projects the
3314    /// `(caixa, versao, restart)` field trio every OTP-shape supervisor-
3315    /// tree consumer that fans on per-child identity + version pin +
3316    /// restart-decision keys off, closing the last unlifted per-`:children`
3317    /// axis so every downstream per-`:children` reader now routes through
3318    /// a typed dispatch on the substrate primitive. Named `restart()` to
3319    /// match the storage field's name and the author-surface
3320    /// `:children :restart` slot term verbatim; the accessor's identity
3321    /// name maps onto the canonical OTP-shape per-child restart-decision-
3322    /// policy vocabulary the [`RestartPolicy`] enum's docstring already
3323    /// carries.
3324    ///
3325    /// Declared `pub const fn` to close the last non-`const`
3326    /// `Copy`-return raw-field-getter posture on the M2
3327    /// per-`:children` [`ChildSpec`] substrate-primitive surface — peer
3328    /// of the sibling M2 per-`:supervisor`
3329    /// [`SupervisorSpec::estrategia`] (converted in this commit)
3330    /// `Copy`-composite-enum accessor, the sibling M2 per-`:supervisor`
3331    /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
3332    /// already lifted, and the peer M3 mesh-slot per-`:entrada`
3333    /// [`crate::Entrada::port`] (bafa004) / per-`:placement`
3334    /// [`crate::Placement::estrategia`] (bafa004) `Copy`-return
3335    /// `pub const fn` scalar accessors on the sibling M3 surface. Every
3336    /// downstream substrate-side `const`-context consumer of the
3337    /// per-`:children` restart-decision-policy scalar (a future
3338    /// module-scope `const _:() = assert!(matches!(child.restart(),
3339    /// RestartPolicy::Permanent))` invariant pin on a typed fixture, a
3340    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
3341    /// admission-webhook `const fn` per-child restart-decision floor
3342    /// over a typed [`ChildSpec`], any future `const fn` supervisor-tree
3343    /// composer over the substrate primitive that fans on the per-child
3344    /// restart-decision policy at compile time) now reaches through the
3345    /// same typed dispatch on the substrate primitive at const-eval
3346    /// time as at runtime. A future non-`Copy`-return promotion of the
3347    /// scalar (an `Option<RestartPolicy>`-shape migration on the
3348    /// per-child restart-decision axis once heterogeneous per-cluster
3349    /// restart-policy overlays land, a per-tenant restart-policy-alias
3350    /// table the M4 CR materializer resolves per-CR) that would drop
3351    /// the `const` qualifier fails the fail-before-pass-after pin
3352    /// [`tests::child_spec_restart_accessor_is_const_fn`] at caixa-core
3353    /// build time rather than surfacing as a downstream consumer
3354    /// regression.
3355    #[must_use]
3356    pub const fn restart(&self) -> RestartPolicy {
3357        self.restart
3358    }
3359}
3360
3361/// Supervisor-typed slots that live alongside the standard Caixa
3362/// fields when `:kind Supervisor`. Held flat in [`crate::Caixa`] so
3363/// the manifest stays a single typed form; this struct exists for
3364/// validation + conversion.
3365#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
3366#[serde(rename_all = "camelCase")]
3367pub struct SupervisorSpec {
3368    /// Restart strategy. Defaults to [`RestartStrategy::OneForOne`].
3369    #[serde(default)]
3370    pub estrategia: RestartStrategy,
3371
3372    /// Max restarts within [`Self::restart_window`] before the
3373    /// supervisor itself terminates (and its parent supervisor decides
3374    /// what to do). Default 5.
3375    #[serde(default = "default_max_restarts")]
3376    pub max_restarts: u32,
3377
3378    /// Sliding window for `max_restarts`. Authored as a duration
3379    /// string (`"60s"`, `"5m"`); absent = "never reset". A `Some(0s)`
3380    /// is rejected by [`Self::validate`] — Erlang/OTP's
3381    /// `MaxIntensity / Period` invariant requires a positive window
3382    /// (a zero-period supervisor either trips on the first failure or
3383    /// never trips, depending on operator interpretation, neither of
3384    /// which is the author's intent). Omit the slot to express "no
3385    /// reset"; carry a positive duration to express the sliding window.
3386    #[serde(
3387        default,
3388        skip_serializing_if = "Option::is_none",
3389        with = "duration_codec"
3390    )]
3391    pub restart_window: Option<Duration>,
3392
3393    /// Static children. Empty for `SimpleOneForOne` (children added
3394    /// dynamically); required for the other three strategies.
3395    #[serde(default)]
3396    pub children: Vec<ChildSpec>,
3397}
3398
3399const fn default_max_restarts() -> u32 {
3400    // Route the private serde-`#[serde(default = "…")]` helper through
3401    // the substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] typed
3402    // `pub const` rather than the raw `5` literal — one source of truth
3403    // for the Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
3404    // default across the two production consumers that currently
3405    // dispatch on it (this helper via `#[serde(default = "…")]` on
3406    // `SupervisorSpec::max_restarts` and the [`Default for SupervisorSpec`]
3407    // impl at line 962). Pinned by
3408    // `default_max_restarts_helper_routes_through_lifted_default` +
3409    // `supervisor_spec_default_max_restarts_routes_through_lifted_default`
3410    // in the tests module; peer of the sibling caixa-core
3411    // [`crate::manifest::Caixa::supervisor_view`] `unwrap_or(…)` fold
3412    // that now routes its author-omitted `:max-restarts` arm through
3413    // the same lifted constant.
3414    SUPERVISOR_MAX_RESTARTS_DEFAULT
3415}
3416
3417/// Substrate-canonical Erlang/OTP-shaped `MaxIntensity` restart-budget-
3418/// count default for the `:supervisor :max-restarts` axis — the
3419/// canonical `{intensity, 5, 60}` `MaxIntensity` half of Learn You Some
3420/// Erlang's worker-supervisor default, extracted as a typed `pub const`
3421/// so every substrate-side consumer that resolves "what
3422/// [`SupervisorSpec::max_restarts`] value does an author-omitted
3423/// `:max-restarts` slot degrade onto?" reaches for exactly one
3424/// substrate-primitive `u32`.
3425///
3426/// The `:max-restarts` default axis has two production consumers on the
3427/// substrate side today (both prior to this lift folded onto raw `5`
3428/// literals with no compile-time link back to a shared truth): the
3429/// serde-`#[serde(default = "default_max_restarts")]` helper on
3430/// [`SupervisorSpec::max_restarts`] that every author-omitted
3431/// `:supervisor :max-restarts` slot lands in past the derive-macro's
3432/// wire-format compose, and the [`crate::manifest::Caixa::supervisor_view`]
3433/// `.max_restarts().unwrap_or(5)` fold that every downstream consumer of
3434/// the composed [`SupervisorSpec`] altitude reaches through
3435/// (`feira app graph`, the future wasm-operator's per-supervisor
3436/// restart-intensity counter, the future M4
3437/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
3438/// webhook, the caixa-operator's hierarchical reconciliation scheduler).
3439/// A pair of open-coded `5`s across two files that expressed no
3440/// compile-time link back to the shared OTP-canonical default — a
3441/// future rebrand of the default (a tightening to Elixir's
3442/// `Supervisor.max_restarts: 3`, a widening to a per-cluster overlay
3443/// the operator pins through a future
3444/// `:supervisor :max-restarts-overrides` slot the MESH-COMPOSITION
3445/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
3446/// plain `u32` count to a richer `{MaxR, MaxT}` per-child-cohort
3447/// restart-budget-partition once the INSPIRATIONS §II.2 Erlang/OTP
3448/// per-child-cohort roadmap lands) would have had to be threaded
3449/// through both open-coded copies in lockstep or the wire-format
3450/// author-omitted arm and the view-construction author-omitted arm
3451/// would silently disagree on which restart-budget an omitted
3452/// `:max-restarts` resolves to (an author writing `:supervisor
3453/// (:max-restarts ())` would round-trip through serde with the new
3454/// default while `supervisor_view` silently continued to compose the
3455/// stale `5`, or vice versa), a two-consumer split at the composition
3456/// boundary far from the source `caixa.lisp` with no field naming the
3457/// default-drift root cause. Lifting the resolution rule to a typed
3458/// `pub const` on the substrate primitive means every downstream
3459/// consumer of the per-Supervisor default-restart-budget-count surface
3460/// reaches for exactly one substrate-primitive `u32` — the resolver's
3461/// accepted value migrates as a unit on any future axis change.
3462///
3463/// The `5` value pins Learn You Some Erlang's `{intensity, 5, 60}`
3464/// worker-supervisor default (the closest canonical OTP-shape
3465/// production reference the substrate carries, matching the sibling
3466/// `60s` `Period` default the [`Default for SupervisorSpec`] impl pairs
3467/// this constant with on the paired sliding-window axis). Two orders of
3468/// magnitude below the [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` ceiling
3469/// (the upper bracket on the same axis, sibling of this lower default;
3470/// both are typed `u32` const bounds on the `:supervisor :max-restarts`
3471/// axis and now share one accessor discipline on the substrate) and
3472/// above the OTP-`supervisor` callback-module `MaxR = 1` minimum-
3473/// restart floor — the "one restart, then escalate" default is
3474/// deliberately loose enough to absorb a short burst of transient
3475/// child failures without escalating past the supervisor's parent
3476/// while remaining tight enough to trip the `MaxIntensity / Period`
3477/// ratio's escalation on a genuinely-stuck child within the sibling
3478/// `60s` sliding window.
3479///
3480/// Lifted as a typed `pub const` so the bound has exactly one source
3481/// of truth — the serde-side wire-format author-omitted arm at
3482/// [`default_max_restarts`], the [`Default for SupervisorSpec`] impl's
3483/// struct-literal default field, and the caixa-core
3484/// [`crate::manifest::Caixa::supervisor_view`] fold's author-omitted
3485/// arm all read from one place. Same shape every other typed default
3486/// in this crate carries (the sibling
3487/// [`SUPERVISOR_MAX_RESTARTS_MAX`] upper cap on the same axis, the
3488/// paired [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the
3489/// sibling `:restart-window` axis, and the peer
3490/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
3491/// per-renderer defaults on the caixa-flux / caixa-helm rendering
3492/// axes).
3493pub const SUPERVISOR_MAX_RESTARTS_DEFAULT: u32 = 5;
3494
3495/// Upper-bound ceiling on the `:supervisor :max-restarts` axis — every
3496/// validated [`SupervisorSpec::max_restarts`] past
3497/// [`SupervisorSpec::validate`] lies in `1..=SUPERVISOR_MAX_RESTARTS_MAX`.
3498///
3499/// The typed field is `u32` (the zero-floor arm
3500/// [`SupervisorError::ZeroMaxRestarts`] already brackets the bottom edge),
3501/// so a programmatic struct literal
3502/// (`SupervisorSpec { max_restarts: u32::MAX, .. }`) and the equivalent
3503/// author-surface form (`:max-restarts 4294967295` or any
3504/// `:max-restarts 100000`-shape typo landing in the slot) both round-trip
3505/// cleanly through serde — a structurally unbounded `u32` ceiling. The
3506/// runtime substrate consuming the value (Erlang/OTP's
3507/// `MaxIntensity / Period` ratio, the future wasm-operator's
3508/// per-supervisor restart-intensity counter, the M4
3509/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook)
3510/// then turned a typed `:max-restarts` policy into a no-op supervisor: the
3511/// escalation threshold is structurally so high that no realistic
3512/// restarts-per-`:restart-window` traffic shape can reach it, the
3513/// supervisor never escalates to its parent, and a bad child can loop
3514/// inside the window indefinitely with the parent supervisor structurally
3515/// never receiving the "this subtree has exceeded its restart budget"
3516/// signal the typed slot is meant to express — the canonical
3517/// "supervisor intensity declared, no escalation" footgun, exactly the
3518/// peer of the [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap
3519/// on the `:politicas :circuit-breaker :max-failures` axis (both are
3520/// "trip the next-higher protection layer after N events in a rolling
3521/// window" counters with identical degenerate-at-the-high-end shape).
3522///
3523/// The `1000` ceiling matches the sibling
3524/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] (the closest
3525/// peer — same "events-per-window trip threshold" semantics, same `u32`
3526/// type, same no-op-at-the-high-end failure mode) so the M4
3527/// `mesh.pleme.io/v1alpha1/Supervisor` / `.../Aplicacao` CR materializers
3528/// and the future wasm-operator's per-supervisor restart-intensity
3529/// counter reach for either field knowing the value is in `1..=1000`
3530/// without re-validating at the reconciler layer. The cap sits two
3531/// orders of magnitude above every documented Erlang/OTP production
3532/// playbook recommendation (Learn You Some Erlang's
3533/// `{intensity, 5, 60}` worker-supervisor default, Elixir's `Supervisor`
3534/// `max_restarts: 3` default, OTP's `supervisor` callback module
3535/// `MaxR = 1` / `MaxT = 5` "minimal-restart" default, Riak Core's
3536/// typical `MaxR ∈ 5..=100`, RabbitMQ's broker-supervisor `MaxR = 5`
3537/// default) and below the clearly-pathological "effectively no
3538/// escalation" floor (`10_000`, `100_000`, `u32::MAX`): a value the
3539/// author can plausibly want at hyperscale (a long-running supervisor
3540/// over a very-flaky pool tolerating thousands of transient restarts
3541/// before escalating), but a hard wall above which the typed policy is
3542/// structurally a no-op carried verbatim on every emitted child-restart
3543/// reconciliation contract.
3544///
3545/// Lifted as a typed `pub const` so the bound has exactly one source of
3546/// truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
3547/// materializer's admission webhook and the wasm-operator-side
3548/// per-supervisor restart-intensity reconciler read from one place. Same
3549/// shape every other typed upper bound in this crate carries
3550/// ([`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
3551/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
3552/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
3553/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3554/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3555/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3556pub const SUPERVISOR_MAX_RESTARTS_MAX: u32 = 1000;
3557
3558/// Upper-bound ceiling on the `:supervisor :restart-window` axis —
3559/// every validated `Some(`[`SupervisorSpec::restart_window`]`)` past
3560/// [`SupervisorSpec::validate`] lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
3561/// (inclusive on both ends, integer-millisecond magnitudes by the
3562/// canonical-form gate immediately preceding).
3563///
3564/// The typed field is `Option<Duration>` (the zero-floor arm
3565/// [`SupervisorError::RestartWindowZero`] already rejects
3566/// `Some(Duration::ZERO)`, and the canonical-form arm
3567/// [`SupervisorError::RestartWindowNotCanonical`] already rejects
3568/// sub-millisecond residue), so a programmatic struct literal
3569/// (`SupervisorSpec { restart_window: Some(Duration::from_secs(86_400)),
3570/// .. }` — 24h) and the equivalent author-surface form
3571/// (`(:supervisor (:restart-window "24h"))` — the shared duration codec
3572/// emits `"<n>h"` for any integer-hour magnitude) both round-trip
3573/// cleanly through serde — a structurally unbounded `Duration` ceiling.
3574/// A `:restart-window` value far above the documented Erlang/OTP
3575/// `MaxIntensity / Period` production-playbook band (Learn You Some
3576/// Erlang's `{intensity, 5, 60}` worker-supervisor `Period = 60s`
3577/// default, Elixir's `Supervisor` `max_seconds: 5` default, OTP's
3578/// `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's
3579/// `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default)
3580/// degenerates the supervisor's restart-intensity counter into a
3581/// lifetime counter: the rolling failure-counting window is structurally
3582/// so long that transient restarts are never forgotten, so the
3583/// `MaxIntensity / Period` ratio degenerates from "trip the parent
3584/// supervisor when the child has exceeded its restart budget *within
3585/// the recent window*" to "trip the parent when the child has exceeded
3586/// its restart budget *over its lifetime*" — every transient restart
3587/// counts against the budget forever, the supervisor's reset semantic
3588/// never reaches the child, and the typed `:restart-window` slot
3589/// becomes a no-op rolling window carried on every emitted hierarchical
3590/// reconciliation contract. The canonical
3591/// rolling-window-degenerates-to-lifetime-counter footgun the sibling
3592/// [`crate::POLICY_BREAKER_WINDOW_MAX`] cap closes on the peer
3593/// `:politicas :circuit-breaker :window` axis with identical shape (both
3594/// are "rolling failure-counting window with a per-`Period` reset" Duration
3595/// axes whose lifetime-counter degenerate at the high end is the same
3596/// "the reset semantic never fires" CSE invariant violation).
3597///
3598/// The `1h` (3600s = `3_600_000` ms) ceiling matches the largest unit
3599/// the shared duration codec emits (`"<n>h"` for any integer-hour
3600/// magnitude) — every value in the canonical authoring form's
3601/// `<integer><unit>` grammar at or below this cap renders to a clean
3602/// canonical string — and matches the three sibling typed-`Duration`
3603/// caps already lifted to this surface
3604/// ([`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
3605/// [`crate::POLICY_BREAKER_WINDOW_MAX`]). All four typed-`Duration`
3606/// axes — per-process `:limits :wall-clock`, per-edge `:politicas
3607/// :timeout`, per-breaker `:politicas :circuit-breaker :window`, and
3608/// per-supervisor `:supervisor :restart-window` — now share a single
3609/// uniform top edge at the codec's largest emitted unit so the next
3610/// typed-slot wiring (the future wasm-operator's per-supervisor
3611/// `MaxIntensity / Period` reconciler, the M4
3612/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
3613/// webhook, the `caixa-operator`'s hierarchical reconciliation
3614/// scheduler) reaches for any of the four knowing the value is in
3615/// `1ms..=1h` without re-validating at the renderer layer. The cap sits
3616/// two orders of magnitude above every documented Erlang/OTP / Elixir /
3617/// Riak Core / RabbitMQ production-playbook recommendation band
3618/// (`5s..=300s`) and below the clearly-pathological "rolling window
3619/// degenerates to lifetime counter" floor (`24h`, `7d`, `Duration::MAX`):
3620/// a value the author can plausibly want for a very-low-traffic
3621/// long-tail failure-restart window over a hyperscale-flaky child pool,
3622/// but a hard wall above which the rolling-window contract is
3623/// structurally a lifetime-counter contract.
3624///
3625/// Lifted as a typed `pub const` so the bound has exactly one source
3626/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
3627/// materializer's admission webhook, the wasm-operator-side
3628/// per-supervisor `MaxIntensity / Period` reconciler, and the
3629/// `caixa-operator`'s hierarchical reconciliation scheduler all read
3630/// from one place. Same shape every other typed upper bound in this
3631/// crate carries ([`SUPERVISOR_MAX_RESTARTS_MAX`],
3632/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
3633/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
3634/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
3635/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3636/// [`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
3637/// [`crate::POLICY_BREAKER_WINDOW_MAX`],
3638/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3639/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3640pub const SUPERVISOR_RESTART_WINDOW_MAX: Duration = Duration::from_secs(3600);
3641
3642/// Substrate-canonical Erlang/OTP-shaped `Period` sliding-window-duration
3643/// default for the `:supervisor :restart-window` axis — the canonical
3644/// `{intensity, 5, 60}` `Period` half of Learn You Some Erlang's
3645/// worker-supervisor default, extracted as a typed `pub const` so every
3646/// substrate-side consumer that resolves "what
3647/// [`SupervisorSpec::restart_window`] value does an author-omitted
3648/// `:restart-window` slot degrade onto?" reaches for exactly one
3649/// substrate-primitive [`Duration`].
3650///
3651/// The `:restart-window` default axis has one production consumer on the
3652/// substrate side today: the [`Default for SupervisorSpec`] impl's
3653/// struct-literal `restart_window` field, which prior to this lift folded
3654/// onto a raw `Duration::from_secs(60)` literal with no compile-time link
3655/// back to the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity`
3656/// half of the same `{intensity, 5, 60}` OTP-canonical default. The
3657/// [`crate::manifest::Caixa::supervisor_view`] fold deliberately does
3658/// *not* fall back to this default on the sibling `:restart-window` axis
3659/// — an author-omitted `:supervisor :restart-window` composes to
3660/// `restart_window: None` (the shared codec's soft-swallow shape),
3661/// keeping author-declared intent ("no reset — never escalate on rolling
3662/// window") distinct from the [`Default for SupervisorSpec`] "canonical
3663/// 60s Period" arm every programmatic `SupervisorSpec::default()` caller
3664/// resolves to. Prior to this lift the paired `{intensity, 5, 60}` OTP
3665/// default was split across two files with no compile-time link between
3666/// the halves: [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] pinned the
3667/// `MaxIntensity` half at the substrate primitive while the `Period`
3668/// half rode as an open-coded literal at the composition site, so a
3669/// future coherent rebrand of the paired canonical (a tightening to
3670/// Elixir's `{max_restarts: 3, max_seconds: 5}`, a widening to a
3671/// per-cluster overlay the operator pins through a future
3672/// `:supervisor :restart-window-overrides` slot the MESH-COMPOSITION
3673/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
3674/// paired constants to a per-child-cohort `{MaxR, MaxT}` restart-budget-
3675/// partition once the INSPIRATIONS §II.2 Erlang/OTP per-child-cohort
3676/// roadmap lands) would have had to migrate the `MaxIntensity` half
3677/// through the lifted constant and the `Period` half through a raw
3678/// literal in lockstep or the two halves of the same OTP-canonical
3679/// default would silently drift out of pairing. Lifting the resolution
3680/// rule to a typed `pub const` on the substrate primitive means the
3681/// paired OTP-canonical default migrates as one unit on any future
3682/// axis change.
3683///
3684/// The `60s` value pins Learn You Some Erlang's `{intensity, 5, 60}`
3685/// worker-supervisor default (the closest canonical OTP-shape
3686/// production reference the substrate carries, matching the paired
3687/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5` `MaxIntensity` half this
3688/// constant is the `Period` denominator of on the same
3689/// `MaxIntensity / Period` restart-intensity ratio). Two orders of
3690/// magnitude below the [`SUPERVISOR_RESTART_WINDOW_MAX`] `3600s`
3691/// (`1h`) ceiling (the upper bracket on the same axis, sibling of
3692/// this lower default; both are typed [`Duration`] const bounds on the
3693/// `:supervisor :restart-window` axis and now share one accessor
3694/// discipline on the substrate) and above the OTP-`supervisor`
3695/// callback-module `MaxT = 5` seconds "minimal-window" floor — the "60s
3696/// rolling window" default is deliberately loose enough to absorb a
3697/// short burst of transient child failures without escalating past the
3698/// supervisor's parent while remaining tight enough for the paired
3699/// `MaxIntensity / Period` ratio's escalation to trip on a genuinely-
3700/// stuck child within a human-scale observation window.
3701///
3702/// Lifted as a typed `pub const` so the paired OTP-canonical default has
3703/// exactly one source of truth on each half — the sibling
3704/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half and this
3705/// `Period` `60s` half now share the same substrate-primitive lift
3706/// discipline. Same shape every other typed default in this crate
3707/// carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] paired
3708/// `MaxIntensity` half on the same OTP-canonical `{intensity, 5, 60}`,
3709/// the sibling [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the same
3710/// axis, and the peer [`crate::render::DEFAULT_NAMESPACE`] /
3711/// [`crate::render::DEFAULT_LIBRARY_NAME`] per-renderer defaults on the
3712/// caixa-flux / caixa-helm rendering axes).
3713pub const SUPERVISOR_RESTART_WINDOW_DEFAULT: Duration = Duration::from_secs(60);
3714
3715/// Substrate-canonical Erlang/OTP-shaped sibling-restart-strategy default
3716/// for the `:supervisor :estrategia` axis — the canonical `one_for_one`
3717/// half of Learn You Some Erlang's `{one_for_one, intensity, 5, 60}`
3718/// worker-supervisor default, extracted as a typed `pub const` so every
3719/// substrate-side consumer that resolves "what
3720/// [`SupervisorSpec::estrategia`] variant does an author-omitted
3721/// `:estrategia` slot degrade onto?" reaches for exactly one substrate-
3722/// primitive [`RestartStrategy`].
3723///
3724/// The `:estrategia` default axis has three production consumers on the
3725/// substrate side today: the [`Default for RestartStrategy`] impl's
3726/// return arm, the [`Default for SupervisorSpec`] impl's struct-literal
3727/// `estrategia` field, and the
3728/// [`crate::manifest::Caixa::supervisor_view`] fold's
3729/// `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)` `Option<RestartStrategy>`
3730/// collapse arm — three entry points onto the same OTP-canonical
3731/// `one_for_one` value that prior to this lift folded onto a raw
3732/// `Self::OneForOne` arm at the [`Default for RestartStrategy`] impl and
3733/// implicit `RestartStrategy::default()` routes at the sibling consumers,
3734/// with no compile-time link back to the paired
3735/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` half + the paired
3736/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` half of the same
3737/// `{one_for_one, intensity, 5, 60}` OTP-canonical default. The paired
3738/// triple was split across three altitudes with no compile-time link
3739/// between the halves: the `MaxIntensity` half rode through the lifted
3740/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant (b698ec0) and the `Period`
3741/// half rode through the lifted [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
3742/// constant (f7dcd0e) while the `one_for_one` half rode as an open-coded
3743/// discriminator at the [`Default for RestartStrategy`] impl, so a future
3744/// coherent rebrand of the triple (Elixir's `{:one_for_one,
3745/// max_restarts: 3, max_seconds: 5}` — same strategy, different
3746/// intensity/period; an OTP `rest_for_one` widening once the substrate
3747/// discovers startup-order-coupled child cohorts as the more common
3748/// worker-supervisor default; a per-cluster overlay the operator pins
3749/// through a future `:estrategia-overrides` slot the MESH-COMPOSITION
3750/// §III.2 supervision-canary roadmap acknowledges) would have had to
3751/// migrate the `MaxIntensity` + `Period` halves through the lifted
3752/// constants and the `one_for_one` half through an open-coded arm in
3753/// lockstep or the three halves of the same OTP-canonical default would
3754/// silently drift out of pairing. Lifting the resolution rule to a typed
3755/// `pub const` on the substrate primitive means the paired OTP-canonical
3756/// worker-supervisor default migrates as one unit on any future axis
3757/// change.
3758///
3759/// The [`RestartStrategy::OneForOne`] value pins Learn You Some Erlang's
3760/// `{one_for_one, intensity, 5, 60}` worker-supervisor default (the
3761/// closest canonical OTP-shape production reference the substrate
3762/// carries, matching the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5`
3763/// `MaxIntensity` half and the paired [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
3764/// `60s` `Period` half). The `one_for_one` strategy — restart only the
3765/// failed child, leaving siblings untouched — is the default for tree-of-
3766/// independent-workers use cases the substrate's [`RestartStrategy`]
3767/// discriminator's own docstring already carries as the default arm; it
3768/// composes with the `{5, 60}` restart-intensity ratio to name the same
3769/// substrate-canonical "canonical worker-supervisor" shape the paired
3770/// halves close on their respective axes.
3771///
3772/// Lifted as a typed `pub const` so the paired OTP-canonical default has
3773/// exactly one source of truth on each of its three halves — the sibling
3774/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half, the
3775/// sibling [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` `60s` half, and
3776/// this `one_for_one` strategy half now share the same substrate-
3777/// primitive lift discipline. Same shape every other typed default in
3778/// this crate carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] +
3779/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] paired halves on the same OTP-
3780/// canonical `{one_for_one, intensity, 5, 60}`, the sibling
3781/// [`SUPERVISOR_MAX_RESTARTS_MAX`] + [`SUPERVISOR_RESTART_WINDOW_MAX`]
3782/// upper caps on the paired sibling axes, and the peer
3783/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
3784/// per-renderer defaults on the caixa-flux / caixa-helm rendering axes).
3785pub const SUPERVISOR_ESTRATEGIA_DEFAULT: RestartStrategy = RestartStrategy::OneForOne;
3786
3787/// Substrate-canonical Erlang/OTP-shaped per-child restart-decision-policy
3788/// default for the `:children :restart` axis — the OTP `permanent`
3789/// worker-child default (`{ChildId, StartFunc, permanent, …}` in a
3790/// `supervisor`'s `init/1` child-spec tuple), extracted as a typed
3791/// `pub const` so every substrate-side consumer that resolves "what
3792/// [`ChildSpec::restart`] variant does an author-omitted `:children
3793/// :restart` slot degrade onto?" reaches for exactly one substrate-
3794/// primitive [`RestartPolicy`].
3795///
3796/// Completes the OTP-shape supervisor-tree default set at the substrate
3797/// primitive. The per-`:supervisor` axis already carries all three of its
3798/// halves as lifted typed constants — [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
3799/// (`one_for_one`, 95ffacc), [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
3800/// (`MaxIntensity` `5`, b698ec0), [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
3801/// (`Period` `60s`, f7dcd0e) — while the per-`:children` axis's own
3802/// OTP-canonical default rode as an open-coded `Self::Permanent` arm in
3803/// the [`Default for RestartPolicy`] impl, the last un-lifted default on
3804/// the M2 `:supervisor` slot family. The split mattered because the two
3805/// axes resolve *together* on every author-omitted supervisor: a
3806/// `(defcaixa :kind Supervisor :children ((:caixa "worker" :versao
3807/// "^0.1")))` with no `:estrategia` and no per-child `:restart` degrades
3808/// onto `{one_for_one, 5, 60}` through three lifted constants and onto
3809/// `permanent` through an open-coded enum arm, so a future coherent
3810/// rebrand of the OTP-shape default set (an Elixir-shaped
3811/// `{:one_for_one, max_restarts: 3, max_seconds: 5}` tightening, a
3812/// per-cluster overlay the operator pins through the MESH-COMPOSITION
3813/// §III.2 supervision-canary roadmap slots, an OTP-`transient` widening
3814/// once the substrate discovers clean-completion-aware children as the
3815/// more common child shape) would have had to migrate three halves
3816/// through typed constants and the fourth through a raw enum arm in
3817/// lockstep or the supervisor-level and child-level defaults would
3818/// silently drift apart.
3819///
3820/// The `:children :restart` default axis has two production consumers on
3821/// the substrate side today: the [`Default for RestartPolicy`] impl's
3822/// return arm, and the serde-side `#[serde(default)]` on
3823/// [`ChildSpec::restart`] that resolves an author-omitted `:children
3824/// :restart` slot through that same impl. Both now key off this one
3825/// substrate primitive, so the future wasm-operator's per-child post-exit
3826/// restart-decision branch, the future M4
3827/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
3828/// admission webhook, and the `caixa-operator`'s hierarchical
3829/// reconciliation scheduler's per-child fan-out all reach for one typed
3830/// identifier when they resolve an omitted per-child restart posture.
3831///
3832/// The [`RestartPolicy::Permanent`] value pins Erlang/OTP's `permanent`
3833/// worker-child restart type — always restart the child regardless of how
3834/// it died, the canonical posture for long-running services that must
3835/// always be up, matching the sibling [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
3836/// `one_for_one` tree-of-independent-workers strategy this constant pairs
3837/// with under the same `{one_for_one, intensity, 5, 60}` worker-supervisor
3838/// shape. The two alternatives the closed [`RestartPolicy::ALL`] accept-set
3839/// carries ([`RestartPolicy::Transient`] — restart only on abnormal exit;
3840/// [`RestartPolicy::Temporary`] — never restart) express deliberate
3841/// one-shot / clean-completion-aware postures an author declares
3842/// explicitly, never a posture an omitted slot should silently assume.
3843pub const SUPERVISOR_CHILD_RESTART_DEFAULT: RestartPolicy = RestartPolicy::Permanent;
3844
3845/// Route the manually-authored [`Default`] impl on [`SupervisorSpec`]
3846/// through the substrate-canonical [`SupervisorSpec::otp_canonical`]
3847/// `pub const fn` constructor rather than a struct-literal cascade over
3848/// the paired [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
3849/// [`default_max_restarts`] / [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
3850/// lifted consts — one source of truth for the Erlang/OTP-canonical
3851/// `{one_for_one, 5, 60}` worker-supervisor baseline across the two
3852/// paths every downstream consumer already reaches through (the
3853/// hand-authored-until-now [`Default::default`] the
3854/// `..SupervisorSpec::default()` struct-update-syntax on every
3855/// one-axis-under-test fixture in this crate's test module rests on,
3856/// and the `pub const fn` [`SupervisorSpec::otp_canonical`] constructor
3857/// every `const`-context consumer reaches through).
3858///
3859/// Extends the [`Default`]-through-const-ctor fold discipline the
3860/// [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
3861/// (abd52c2), [`crate::aplicacao::MeshPolicy`]
3862/// [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`] (91641a4),
3863/// and [`crate::BehaviorSpec`]
3864/// [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c) folds
3865/// closed on the M2 / M3 `Option`-only "canonical unset baseline"
3866/// typed-slot spec family — extended here onto the M2 supervisor-slot
3867/// [`SupervisorSpec`] whose canonical baseline is not "everything
3868/// `None`" but the OTP-canonical `{one_for_one, 5, 60}` worker-
3869/// supervisor triple. The `empty()` peer's naming did not fit
3870/// (`SupervisorSpec` carries a discriminator-shaped `estrategia` field
3871/// and a non-zero `max_restarts`/`restart_window` pair whose canonical
3872/// shape is Erlang/OTP-descended, not the "no axis declared" bottom
3873/// the sibling `Option`-only slots fold to), so this peer is named
3874/// [`SupervisorSpec::otp_canonical`] instead — the same phrasing the
3875/// existing per-arm pin tests
3876/// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`] /
3877/// [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`] /
3878/// [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
3879/// already reach for. Pinned load-bearing by
3880/// [`tests::supervisor_spec_default_routes_through_otp_canonical_ctor`]
3881/// (byte-parity pin against [`SupervisorSpec::otp_canonical`] under
3882/// [`PartialEq`], sharpening the sibling
3883/// `supervisor_spec_default_*_routes_through_lifted_default` per-arm
3884/// pins from a per-field lift into a whole-struct one-source-of-truth
3885/// pin — the derived-until-now [`Default::default`] and the
3886/// [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
3887/// construction, not by coincidence).
3888impl Default for SupervisorSpec {
3889    #[inline]
3890    fn default() -> Self {
3891        Self::otp_canonical()
3892    }
3893}
3894
3895impl SupervisorSpec {
3896    /// `const`-context peer of the [`Default for SupervisorSpec`]
3897    /// impl (which routes through this constructor) — returns the
3898    /// Erlang/OTP-canonical `{one_for_one, 5, 60}` worker-supervisor
3899    /// baseline this crate reaches for in every fixture-builder
3900    /// `..SupervisorSpec::default()` struct-update expression and
3901    /// every downstream `SupervisorSpec::default()` seed.
3902    ///
3903    /// Each field routes through the same substrate-canonical
3904    /// [`SUPERVISOR_ESTRATEGIA_DEFAULT`] / [`default_max_restarts`] /
3905    /// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] lifted consts the
3906    /// per-arm pin tests
3907    /// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`]
3908    /// / [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`]
3909    /// / [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
3910    /// already assert, so a future coherent rebrand of the OTP-canonical
3911    /// triple (Elixir's `{max_restarts: 3, max_seconds: 5}`, a per-
3912    /// cluster overlay via a future `:restart-window-overrides` slot, a
3913    /// per-child-cohort promotion the INSPIRATIONS.md §II.2 Erlang/OTP
3914    /// absorption roadmap acknowledges) migrates through three typed
3915    /// constants in lockstep, and the paired [`Default`] impl inherits
3916    /// every future extension by construction.
3917    ///
3918    /// `pub const fn` rather than the derived-style `Default::default`
3919    /// or a `pub const SUPERVISOR_SPEC_DEFAULT: SupervisorSpec` item —
3920    /// [`Default::default`] is not `const` on stable Rust, and
3921    /// `SupervisorSpec` is non-`Copy` so a `pub const` item would force
3922    /// every consumer through a [`Clone::clone`]. The `pub const fn`
3923    /// discipline lets `const`-context callers construct the OTP-
3924    /// canonical baseline at compile time without runtime dispatch on
3925    /// the derived [`Default::default`], the same posture the sibling
3926    /// [`crate::LimitsSpec::empty`] (9739971) /
3927    /// [`crate::aplicacao::MeshPolicy::empty`] (6df969b) /
3928    /// [`crate::BehaviorSpec::empty`] (f9b18e3) `Option`-only typed-slot
3929    /// spec `pub const fn` constructors carry on the sibling
3930    /// "everything `None`" baseline axis.
3931    ///
3932    /// Fourth peer on the M2 / M3 typed-slot-spec "const-context peer
3933    /// of the derived-style [`Default`]" family — sibling of the
3934    /// [`crate::LimitsSpec::empty`] / [`crate::aplicacao::MeshPolicy::empty`]
3935    /// / [`crate::BehaviorSpec::empty`] `Option`-only "canonical unset
3936    /// baseline" trio, extended here onto the M2 supervisor-slot
3937    /// [`SupervisorSpec`] whose canonical baseline is not "everything
3938    /// `None`" but the Erlang/OTP-canonical `{one_for_one, 5, 60}`
3939    /// worker-supervisor triple. Named [`Self::otp_canonical`] rather
3940    /// than `empty()` to name the actual invariant the return value
3941    /// pins — the same phrasing already used in the per-arm pin tests
3942    /// on this file. Pinned load-bearing by
3943    /// [`tests::supervisor_spec_otp_canonical_byte_equals_default`] and
3944    /// [`tests::supervisor_spec_otp_canonical_is_usable_in_const_context`].
3945    #[must_use]
3946    pub const fn otp_canonical() -> Self {
3947        Self {
3948            estrategia: SUPERVISOR_ESTRATEGIA_DEFAULT,
3949            max_restarts: default_max_restarts(),
3950            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
3951            children: Vec::new(),
3952        }
3953    }
3954
3955    /// Substrate-canonical per-`:supervisor` `:estrategia` OTP-shaped
3956    /// sibling-restart-strategy scalar accessor every consumer that
3957    /// dispatches on the supervisor's per-sibling restart-decision shape
3958    /// keys off — returns the author-declared `:supervisor :estrategia`
3959    /// variant verbatim as a [`RestartStrategy`], `Copy`-projected from
3960    /// the typed slot's own [`RestartStrategy`] storage.
3961    ///
3962    /// The `:supervisor :estrategia` slot carries the closed-set
3963    /// OTP-shaped sibling-restart-strategy discriminator ([`RestartStrategy::OneForOne`]
3964    /// — restart only the failed child, the Erlang/OTP `one_for_one` default;
3965    /// [`RestartStrategy::OneForAll`] — restart every child on any child
3966    /// failure, the Erlang/OTP `one_for_all` shared-state cohort default;
3967    /// [`RestartStrategy::RestForOne`] — restart the failed child and
3968    /// every child started after it, the Erlang/OTP `rest_for_one`
3969    /// startup-order default; [`RestartStrategy::SimpleOneForOne`] —
3970    /// dynamic children of the same shape, the Erlang/OTP
3971    /// `simple_one_for_one` per-session default) that every downstream
3972    /// consumer of the Supervisor's per-sibling restart-decision fan-out
3973    /// shape keys off. Validated by [`SupervisorSpec::validate`] to be
3974    /// paired coherently with the sibling `:children` axis
3975    /// (`SimpleOneForOne ↔ children.is_empty()` — the cross-slot
3976    /// partition the strategy-arm's [`SupervisorError::SimpleOneForOneWithStaticChildren`]
3977    /// / [`SupervisorError::NoChildren`] refusal cascade pins), and every
3978    /// downstream consumer that reads the strategy keys off this scalar
3979    /// (the [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
3980    /// partition-dispatch `match` arm, the non-`SimpleOneForOne`-arm
3981    /// declared-but-empty [`SupervisorError::NoChildren`] error carrier's
3982    /// `estrategia:` field, the future `feira app graph` per-Supervisor
3983    /// strategy print line, the future wasm-operator's per-supervisor
3984    /// sibling-restart-strategy branch, the future M4
3985    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-strategy
3986    /// admission-webhook resolver, the `caixa-operator`'s hierarchical
3987    /// reconciliation scheduler's per-strategy fan-out).
3988    ///
3989    /// Prior to this lift the `.estrategia` field was accessed inline at
3990    /// two production sites in `caixa-core/src/supervisor.rs` — the
3991    /// [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
3992    /// `match self.estrategia { … }` partition dispatch, and the
3993    /// non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
3994    /// carrier at `estrategia: self.estrategia` — two open-coded
3995    /// field-accesses that expressed no compile-time link back to the
3996    /// typed slot. A future extension of the `:supervisor :estrategia`
3997    /// axis to a richer author surface (a per-cluster strategy override
3998    /// the operator pins through a future `:supervisor :estrategia-overrides`
3999    /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
4000    /// acknowledges, a per-tenant strategy-alias table the M4 CR
4001    /// materializer resolves per-CR, a per-Supervisor dynamic strategy
4002    /// derivation the future adaptive-supervision engine computes from
4003    /// child-failure-history topology, a per-child-cohort strategy split
4004    /// the future `RestForCohort` extension acknowledged by the
4005    /// INSPIRATIONS.md §II.2 Erlang/OTP absorption roadmap acknowledges)
4006    /// would have had to be threaded through every open-coded copy in
4007    /// lockstep — one consumer reading the raw variant while a peer read
4008    /// the operator-resolved variant would silently split the
4009    /// [`SupervisorError::NoChildren`] diagnostic's quoted strategy from
4010    /// the actual partition-dispatch input the empty-children refusal
4011    /// arm reached under, a two-consumer split at the validator far from
4012    /// the source `caixa.lisp` with no field naming the strategy-drift
4013    /// root cause. Lifting the resolution rule to a typed method on the
4014    /// substrate primitive means every downstream consumer of the
4015    /// Supervisor's per-`:supervisor` sibling-restart-strategy surface
4016    /// reaches for exactly one typed dispatch — the resolver's accept-set
4017    /// migrates as a unit on any future axis addition.
4018    ///
4019    /// Peer of the sibling M3 mesh-slot [`crate::Placement::estrategia`]
4020    /// (921fe1b) `Copy`-return `PlacementStrategy` scalar accessor on the
4021    /// per-`:placement` distribution-strategy axis — same "one typed
4022    /// dispatch on the substrate primitive, thin projections at each
4023    /// consumer" discipline extended onto the M2 supervisor-slot
4024    /// per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
4025    /// scalar axis. The two typed axes (`Placement::estrategia` on the
4026    /// M3 Aplicacao side, `SupervisorSpec::estrategia` on the M2
4027    /// Supervisor side) now share one accessor discipline for the shared
4028    /// substrate concept "a `Copy`-projected closed-set enum-arm
4029    /// discriminator that partitions the downstream renderer's per-arm
4030    /// fan-out". First `Copy`-return accessor on the M2 supervisor-slot
4031    /// `SupervisorSpec` type — companion to the sibling per-`:children`
4032    /// [`crate::ChildSpec::nome`] (57c61d0) /
4033    /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
4034    /// scalar accessors on the sibling per-`:children` `String`-carry
4035    /// axes. Named `estrategia()` to match the storage field's name and
4036    /// the peer [`crate::Placement::estrategia`] method-name discipline
4037    /// verbatim; the accessor's identity name maps onto the canonical
4038    /// OTP-shape supervision vocabulary the [`RestartStrategy`] enum's
4039    /// docstring already carries.
4040    ///
4041    /// Declared `pub const fn` to close the M2 supervisor-slot
4042    /// `Copy`-return raw-field-getter `const`-eval-surface pass —
4043    /// sibling of the peer M2 per-`:children` [`ChildSpec::restart`]
4044    /// (converted in this commit) `Copy`-composite-enum accessor, peer
4045    /// of the sibling M2 per-`:supervisor`
4046    /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
4047    /// already lifted, and mirror of the peer M3 mesh-slot
4048    /// per-`:placement` [`crate::Placement::estrategia`] (bafa004)
4049    /// `Copy`-return `pub const fn` scalar accessor whose method-name
4050    /// discipline this accessor was authored to match. Every downstream
4051    /// substrate-side `const`-context consumer of the per-`:supervisor`
4052    /// sibling-restart-strategy scalar (a future module-scope `const
4053    /// _:() = assert!(matches!(sup.estrategia(),
4054    /// RestartStrategy::OneForOne))` invariant pin on a typed fixture,
4055    /// a future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
4056    /// admission-webhook `const fn` per-supervisor strategy-arm floor
4057    /// over a typed [`SupervisorSpec`], any future `const fn`
4058    /// supervisor-tree composer over the substrate primitive that fans
4059    /// on the sibling-restart-strategy at compile time) now reaches
4060    /// through the same typed dispatch on the substrate primitive at
4061    /// const-eval time as at runtime. A future non-`Copy`-return
4062    /// promotion of the scalar (an `Option<RestartStrategy>`-shape
4063    /// migration once the substrate grows per-cluster strategy overlays
4064    /// the [`SupervisorSpec`] docstring already anticipates, a
4065    /// per-tenant strategy-alias table the M4 CR materializer resolves
4066    /// per-CR) that would drop the `const` qualifier fails the
4067    /// fail-before-pass-after pin
4068    /// [`tests::supervisor_spec_estrategia_accessor_is_const_fn`] at
4069    /// caixa-core build time rather than surfacing as a downstream
4070    /// consumer regression.
4071    #[must_use]
4072    pub const fn estrategia(&self) -> RestartStrategy {
4073        self.estrategia
4074    }
4075
4076    /// Substrate-canonical per-`:supervisor` `:max-restarts` OTP-shaped
4077    /// `MaxIntensity` restart-budget scalar accessor every consumer that
4078    /// reads the supervisor's per-`:restart-window` restart-budget count
4079    /// keys off — returns the author-declared `:supervisor :max-restarts`
4080    /// typed `u32` verbatim, `Copy`-projected from the typed slot's own
4081    /// `u32` storage (`u32` is `Copy`, so the accessor returns by value; no
4082    /// borrow of `&self` past the call). Non-optional (the `u32` field
4083    /// carries the restart-budget count as a required axis with a
4084    /// [`default_max_restarts`]-supplied default; the zero-floor arm
4085    /// [`SupervisorError::ZeroMaxRestarts`] and the cap arm
4086    /// [`SupervisorError::MaxRestartsExceedsCap`] jointly bracket the
4087    /// accept-set to `1..=SUPERVISOR_MAX_RESTARTS_MAX`).
4088    ///
4089    /// The `:supervisor :max-restarts` slot carries the Erlang/OTP
4090    /// `MaxIntensity` restart-budget count that pairs with the sibling
4091    /// `:restart-window` `Period` to form the `MaxIntensity / Period`
4092    /// restart-intensity ratio the supervisor trips its own escalation on
4093    /// (`theory/RUNTIME-PATTERNS.md` §II.2, Learn You Some Erlang's
4094    /// `{intensity, 5, 60}` worker-supervisor default). Every downstream
4095    /// consumer of the Supervisor's per-`:supervisor` restart-budget count
4096    /// keys off this scalar (the [`SupervisorSpec::validate`] zero-floor +
4097    /// upper-cap bracket at
4098    /// `require_positive_bounded_u32(self.max_restarts(), …)`, the future
4099    /// wasm-operator's per-supervisor restart-intensity counter's
4100    /// budget-vs-count comparator, the future M4
4101    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
4102    /// webhook, the `caixa-operator`'s hierarchical reconciliation
4103    /// scheduler's per-supervisor escalation-decision branch, every
4104    /// `SupervisorError::MaxRestartsExceedsCap` variant carrying the
4105    /// offending count verbatim for `feira lint` rendering).
4106    ///
4107    /// Prior to this lift the `.max_restarts` field was accessed inline at
4108    /// one production site in `caixa-core/src/supervisor.rs` — the
4109    /// [`SupervisorSpec::validate`] `require_positive_bounded_u32(self
4110    /// .max_restarts, …)` bracket-gate call — one open-coded field-access
4111    /// that expressed no compile-time link back to the typed slot. A
4112    /// future extension of the `:max-restarts` axis to a richer author
4113    /// surface (a per-cluster restart-budget override the operator pins
4114    /// through a future `:supervisor :max-restarts-overrides` slot the
4115    /// MESH-COMPOSITION §III.2 supervision-canary roadmap acknowledges,
4116    /// a per-tenant restart-budget-alias table the M4 CR materializer
4117    /// resolves per-CR, a per-supervisor dynamic restart-budget derivation
4118    /// the future adaptive-supervision engine computes from child-failure-
4119    /// history topology, a promotion of the plain `u32` count to a richer
4120    /// `{MaxR, MaxT}` tuple once Erlang/OTP's per-child-cohort restart-
4121    /// budget-partition slot comes into scope) would have had to be
4122    /// threaded through every open-coded copy in lockstep or the validate
4123    /// gate and the future M4 emit path would silently disagree on which
4124    /// restart-budget count a given supervisor resolves to — an author's
4125    /// `:max-restarts 5` would satisfy validate while the emit path
4126    /// silently read a drifted other value (a `:max-restarts 10000`
4127    /// no-op supervisor at the emit boundary would carry the author's
4128    /// declared `5` verbatim in `feira lint` output while the future
4129    /// wasm-operator's restart-intensity counter operated under the
4130    /// drifted count), a two-consumer split at the validator far from the
4131    /// source `caixa.lisp` with no field naming the restart-budget-drift
4132    /// root cause. Lifting the resolution rule to a typed method on the
4133    /// substrate primitive means every downstream consumer of the
4134    /// Supervisor's per-`:supervisor` restart-budget-count surface reaches
4135    /// for exactly one typed dispatch — the resolver's accept-set migrates
4136    /// as a unit on any future axis addition.
4137    ///
4138    /// Peer of the sibling M3 mesh-slot [`crate::CircuitBreaker::max_failures`]
4139    /// (3a74062) `Copy`-return `u32` sub-struct required-scalar accessor
4140    /// on the per-`:politicas :circuit-breaker :max-failures` Envoy-
4141    /// outlier-detection trip-threshold axis — same "one typed dispatch on
4142    /// the substrate primitive, thin projections at each consumer"
4143    /// discipline extended onto the M2 supervisor-slot per-`:supervisor`
4144    /// restart-budget-count `Copy`-`u32` scalar axis. The two typed axes
4145    /// (`CircuitBreaker::max_failures` on the M3 Aplicacao side,
4146    /// `SupervisorSpec::max_restarts` on the M2 Supervisor side) now share
4147    /// one accessor discipline for the shared substrate concept "a
4148    /// `Copy`-projected required `u32` count that trips the next-higher
4149    /// protection layer after N events in a rolling window" — both are
4150    /// counters with identical degenerate-at-the-high-end shape and share
4151    /// the paired [`crate::POLICY_BREAKER_MAX_FAILURES_MAX`] /
4152    /// [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` cap. Second `Copy`-return
4153    /// accessor on the M2 supervisor-slot `SupervisorSpec` type, sibling
4154    /// to the [`SupervisorSpec::estrategia`] (eafb619) `Copy`-composite-
4155    /// enum `RestartStrategy` accessor. Named `max_restarts()` to match
4156    /// the storage field's name verbatim and the peer
4157    /// [`crate::CircuitBreaker::max_failures`] method-name discipline; the
4158    /// accessor's identity maps onto the canonical OTP-shape supervision
4159    /// vocabulary the [`SupervisorSpec::max_restarts`] field's docstring
4160    /// already carries.
4161    #[must_use]
4162    pub const fn max_restarts(&self) -> u32 {
4163        self.max_restarts
4164    }
4165
4166    /// Substrate-canonical per-`:supervisor` `:restart-window` OTP-shaped
4167    /// `Period` sliding-window scalar accessor every consumer of the
4168    /// supervisor's `MaxIntensity / Period` restart-intensity denominator
4169    /// keys off — returns the author-declared `:supervisor :restart-window`
4170    /// typed [`Duration`] verbatim as an `Option<Duration>`, copied out of
4171    /// the typed slot's own `Option<Duration>` storage (`Duration` is
4172    /// `Copy`, so `Option<Duration>` is `Copy` and the accessor returns by
4173    /// value; no borrow of `&self` past the call). `None` when the slot is
4174    /// absent (the canonical "never reset — every restart across the
4175    /// supervisor's lifetime counts against the sibling `:max-restarts`
4176    /// budget" sentinel the field's own docstring names and the peer
4177    /// `validate_accepts_none_restart_window` pin locks in on the
4178    /// [`SupervisorSpec::validate`] entry-side).
4179    ///
4180    /// The `:supervisor :restart-window` slot carries the Erlang/OTP
4181    /// `Period` sliding-observation-interval that pairs with the sibling
4182    /// `:max-restarts` `MaxIntensity` restart-budget count to form the
4183    /// `MaxIntensity / Period` restart-intensity ratio the supervisor
4184    /// trips its own escalation on (`theory/RUNTIME-PATTERNS.md` §II.2,
4185    /// Learn You Some Erlang's `{intensity, 5, 60}` worker-supervisor
4186    /// default). The typed slot's `Option<Duration>` accept-set —
4187    /// zero-floor rejected through [`SupervisorError::RestartWindowZero`]
4188    /// (Erlang/OTP's `MaxIntensity / Period` invariant requires
4189    /// `Period > 0`; a zero period either trips on the first failure or
4190    /// never trips depending on operator interpretation, neither of which
4191    /// is the author's intent — omit the slot to express "no reset";
4192    /// carry a positive duration to express the sliding window),
4193    /// integer-millisecond canonical form enforced through
4194    /// [`SupervisorError::RestartWindowNotCanonical`] (the duration
4195    /// codec's canonical form emits `"1500ms"` not `"1.5s"` and the
4196    /// future wasm-operator's per-supervisor restart-intensity counter
4197    /// quantizes at milliseconds), upper-bounded by
4198    /// [`SUPERVISOR_RESTART_WINDOW_MAX`] (1h — the coarsest per-
4199    /// supervisor rolling window any operationally-reachable supervisor
4200    /// can honor without spanning multiple scheduler epochs the
4201    /// hierarchical-reconciliation scheduler treats as independent) —
4202    /// maps onto the future wasm-operator (M3) per-supervisor
4203    /// restart-intensity counter's rolling-observation-interval, the
4204    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
4205    /// per-`spec.restartWindow` admission webhook, and the sibling
4206    /// `duration_codec`-serialized wire scalar every downstream consumer
4207    /// of the supervisor's per-`:supervisor` restart-intensity denominator
4208    /// keys off.
4209    ///
4210    /// Prior to this lift the `.restart_window` field was accessed inline
4211    /// at one production site in `caixa-core/src/supervisor.rs` — the
4212    /// [`SupervisorSpec::validate`] `if let Some(w) = self.restart_window {
4213    /// … }` zero-floor + canonical-form + upper-cap bracket arm — one
4214    /// open-coded field-access that expressed no compile-time link back to
4215    /// the typed slot. A future extension of the `:restart-window` axis to
4216    /// a richer author surface (a per-cluster restart-window override the
4217    /// operator pins through a future `:supervisor :restart-window-overrides`
4218    /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
4219    /// acknowledges, a per-tenant restart-window-alias table the M4 CR
4220    /// materializer resolves per-CR, a per-supervisor dynamic
4221    /// restart-window derivation the future adaptive-supervision engine
4222    /// computes from child-failure-history topology, a promotion of the
4223    /// plain `Option<Duration>` window to a richer `{observation, cooldown}`
4224    /// pair once Erlang/OTP's per-child-cohort observation-interval-
4225    /// partition slot comes into scope) would have had to be threaded
4226    /// through every open-coded copy in lockstep or the validate gate and
4227    /// the future M4 emit path would silently disagree on which
4228    /// restart-window a given supervisor resolves to — an author's
4229    /// `:restart-window "60s"` would satisfy validate while the emit path
4230    /// silently read a drifted other value (a `Some(Duration::from_secs(60))`
4231    /// authored slot at the emit boundary would carry the author's
4232    /// declared window verbatim in `feira lint` output while the future
4233    /// wasm-operator's restart-intensity counter operated under a
4234    /// drifted window, or vice versa: an author's `:restart-window ()`
4235    /// would carry the "never reset" sentinel through validate while the
4236    /// emit path silently substituted a default sliding window), a
4237    /// two-consumer split at the validator far from the source
4238    /// `caixa.lisp` with no field naming the restart-window-drift root
4239    /// cause. Lifting the resolution rule to a typed method on the
4240    /// substrate primitive means every downstream consumer of the
4241    /// Supervisor's per-`:supervisor` restart-intensity-denominator
4242    /// surface reaches for exactly one typed dispatch — the resolver's
4243    /// accept-set migrates as a unit on any future axis addition.
4244    ///
4245    /// Third `Copy`-return accessor on the M2 supervisor-slot
4246    /// `SupervisorSpec` type, closing the last unlifted per-`:supervisor`
4247    /// scalar-value axis (`children: Vec<ChildSpec>` carries a `Vec`
4248    /// payload rather than a `Copy`-scalar, and the per-`:children`
4249    /// [`crate::ChildSpec::nome`] (57c61d0) /
4250    /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
4251    /// scalar accessors already close the per-element `String`-carry
4252    /// axes). Sibling to the peer M2 [`crate::LimitsSpec::wall_clock`]
4253    /// (8cb717b) `Option<Duration>` accessor on the `:limits` slot's
4254    /// per-outermost-call wall-clock-deadline axis and the peer M3
4255    /// [`crate::MeshPolicy::timeout`] (7073d0f) `Option<Duration>`
4256    /// accessor on the `:politicas` slot's per-call-deadline axis — all
4257    /// three share the shared substrate concept "a `Copy`-projected
4258    /// optional `Duration` that carries a positive integer-millisecond
4259    /// canonical value with a `1ms..=<axis-specific>_MAX` accept-set and
4260    /// the paired zero-floor / non-canonical / above-cap refusal cascade"
4261    /// through the same [`crate::render::require_positive_canonical_bounded_duration`]
4262    /// bracket-helper the three axes each route through. Named
4263    /// `restart_window()` to match the storage field's name verbatim and
4264    /// the peer [`crate::LimitsSpec::wall_clock`] /
4265    /// [`crate::MeshPolicy::timeout`] method-name discipline; the
4266    /// accessor's identity maps onto the canonical OTP-shape supervision
4267    /// vocabulary the [`SupervisorSpec::restart_window`] field's docstring
4268    /// already carries.
4269    #[must_use]
4270    pub const fn restart_window(&self) -> Option<Duration> {
4271        self.restart_window
4272    }
4273
4274    /// Substrate-canonical per-`:supervisor` `:children` OTP-shaped
4275    /// static-child-list slice accessor every consumer that walks the
4276    /// supervisor's declared child set keys off — returns the author-
4277    /// declared `:supervisor :children` `Vec<ChildSpec>` verbatim as a
4278    /// `&[ChildSpec]` slice-view, borrowed from the typed slot's own
4279    /// `Vec<ChildSpec>` storage (a zero-copy slice-view over the same
4280    /// backing buffer the `Serialize`/`Deserialize` derives round-trip
4281    /// through). Non-optional: an empty slice is the load-bearing
4282    /// "author declared `:children ()`" sentinel every consumer of the
4283    /// cross-slot `SimpleOneForOne ↔ children.is_empty()` partition
4284    /// keys off (`SimpleOneForOne` requires the empty slice; the peer
4285    /// three strategies require a non-empty slice — the paired
4286    /// [`SupervisorError::SimpleOneForOneWithStaticChildren`] /
4287    /// [`SupervisorError::NoChildren`] refusal cascade pins the
4288    /// partition on both arms).
4289    ///
4290    /// The `:supervisor :children` slot carries the OTP-shaped static
4291    /// child list the supervisor materializes one ComputeUnit per
4292    /// entry from — the Erlang/OTP `supervisor:init/1`'s
4293    /// `{ok, {SupFlags, ChildSpecs}}` `ChildSpecs` list, projected
4294    /// through the tatara-lisp `:children` author surface onto a typed
4295    /// `Vec<ChildSpec>` whose per-element `(nome(),
4296    /// versao_requirement(), restart)` triple the per-child
4297    /// [`SupervisorSpec::validate`] loop already gates through the
4298    /// lifted [`ChildSpec::nome`] (57c61d0) /
4299    /// [`ChildSpec::versao_requirement`] (2c053c8) scalar accessors.
4300    /// Every downstream consumer that fans on the static child list
4301    /// keys off this slice (the [`SupervisorSpec::validate`]
4302    /// `SimpleOneForOne ↔ non-SimpleOneForOne` partition dispatch's
4303    /// `.is_empty()` probe on both arms, the [`SupervisorSpec::validate`]
4304    /// per-child DNS-1123 / semver-requirement / duplicate-detection
4305    /// fan-out loop, every future wasm-operator (M3) per-supervisor
4306    /// hierarchical-reconciliation scheduler's per-child ComputeUnit
4307    /// materialization loop, the future M4
4308    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
4309    /// admission-webhook fan-out, the future `feira app graph`
4310    /// per-supervisor tree-print traversal).
4311    ///
4312    /// Prior to this lift the `.children` `Vec<ChildSpec>` was accessed
4313    /// inline at three production sites in `caixa-core/src/supervisor.rs`
4314    /// — the [`SupervisorSpec::validate`] `SimpleOneForOne`-arm
4315    /// `!self.children.is_empty()` cross-slot refusal probe, the peer
4316    /// non-`SimpleOneForOne`-arm `self.children.is_empty()`
4317    /// [`SupervisorError::NoChildren`] refusal probe, and the per-child
4318    /// validate loop's `for child in &self.children` traversal head —
4319    /// three open-coded field-accesses that expressed no compile-time
4320    /// link back to the typed slot. A future extension of the
4321    /// `:supervisor :children` axis to a richer author surface (a
4322    /// per-cluster child-set overlay the operator pins through a future
4323    /// `:supervisor :children-overrides` slot the MESH-COMPOSITION §III.2
4324    /// supervision-canary roadmap acknowledges, a per-tenant
4325    /// child-set-alias table the M4 CR materializer resolves per-CR,
4326    /// a per-supervisor dynamic-child derivation the future adaptive-
4327    /// supervision engine computes from child-failure-history topology,
4328    /// a promotion of the plain `Vec<ChildSpec>` to a richer
4329    /// `{static, dynamic}` partition once Erlang/OTP's
4330    /// `simple_one_for_one` dynamic-child slot comes into typed scope)
4331    /// would have had to be threaded through all three open-coded copies
4332    /// in lockstep or one consumer would silently disagree with the
4333    /// peers on which child-set a given supervisor resolves to — the
4334    /// `SimpleOneForOne`-arm probe reading the raw slot while the peer
4335    /// non-`SimpleOneForOne`-arm probe read an operator-resolved slot
4336    /// would silently split the partition-dispatch's two-arm coherence
4337    /// (a supervisor that satisfies neither arm's precondition, or that
4338    /// satisfies both, at the cost of the paired
4339    /// `SimpleOneForOneWithStaticChildren`/`NoChildren` refusal cascade
4340    /// silently drifting from the per-child validate loop's actual
4341    /// traversal input), a three-consumer split at the validator far
4342    /// from the source `caixa.lisp` with no field naming the
4343    /// child-set-drift root cause. Lifting the resolution rule to a
4344    /// typed method on the substrate primitive means every downstream
4345    /// consumer of the Supervisor's per-`:supervisor` static-child-list
4346    /// surface reaches for exactly one typed dispatch — the resolver's
4347    /// accept-set migrates as a unit on any future axis addition.
4348    ///
4349    /// First slice-return (`&[T]`) accessor on any M2 or M3 typed slot
4350    /// — the seed for the same "one typed dispatch on the substrate
4351    /// primitive, thin projections at each consumer" discipline the
4352    /// closed [`crate::LimitsSpec`] / [`BehaviorSpec`] /
4353    /// [`crate::UpgradeFromEntry`] scalar-accessor families each carry
4354    /// on their `Copy` / `Option<Copy>` / `Option<&str>` axes, extended
4355    /// onto the first `Vec`-carry axis on the substrate. The four peer
4356    /// `Vec`-carry axes still unlifted at the time of this seed —
4357    /// [`crate::Placement::clusters`] (`Vec<String>` per-cluster
4358    /// distribution-target list), [`crate::AplicacaoSpec::membros`]
4359    /// (`Vec<Membro>` per-Aplicacao member list),
4360    /// [`crate::AplicacaoSpec::contratos`] (`Vec<WitContract>`
4361    /// per-Aplicacao WIT-typed edge list),
4362    /// [`crate::UpgradeFromEntry::instructions`]
4363    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
4364    /// — inherit this accessor's discipline as future compounding runs
4365    /// migrate their consumers onto the shared slice-return shape.
4366    /// Fourth (and final) accessor on the M2 supervisor-slot
4367    /// `SupervisorSpec` type, sibling to the three `Copy`-return
4368    /// [`SupervisorSpec::estrategia`] (eafb619) /
4369    /// [`SupervisorSpec::max_restarts`] (7844f4e) /
4370    /// [`SupervisorSpec::restart_window`] (7e7b32f) accessors — closes
4371    /// the last unlifted per-`:supervisor` field axis (the
4372    /// `Vec<ChildSpec>` static-child-list carrier) so every downstream
4373    /// per-`:supervisor` reader now routes through a typed dispatch on
4374    /// the substrate primitive. Named `children()` to match the storage
4375    /// field's name verbatim and the tatara-lisp author-surface term
4376    /// (`:children`) the field's own docstring already carries; the
4377    /// accessor's identity maps onto the canonical OTP-shape
4378    /// supervision vocabulary the [`SupervisorSpec::children`] field's
4379    /// docstring already reaches for ("Static children ..."). Returns
4380    /// `&[ChildSpec]` (not `&Vec<ChildSpec>`) because every downstream
4381    /// consumer of the child list treats it as a read-only sequence —
4382    /// the slice-view is the narrowest borrow that supports every
4383    /// present + roadmapped consumer (`.is_empty()`, `.iter()`,
4384    /// index, `.len()`) without leaking the backing `Vec`'s
4385    /// grow/push/reserve surface that no consumer of the typed view
4386    /// reaches for (the storage-side `Vec` remains reachable through
4387    /// the `pub children` field for the mutation-carrying
4388    /// `Caixa::supervisor_view` fold-in path in
4389    /// `manifest.rs:supervisor_view`).
4390    #[must_use]
4391    pub const fn children(&self) -> &[ChildSpec] {
4392        self.children.as_slice()
4393    }
4394
4395    /// Validate the supervisor's typed shape — strategy ↔ children
4396    /// invariants, max_restarts > 0, restart_window > 0 when set,
4397    /// per-child non-empty + duplicate-free names.
4398    ///
4399    /// Mirrors the value-shape discipline applied to every other
4400    /// typed slot:
4401    ///
4402    ///   - `Some(Duration::ZERO)` on a Duration-bearing axis is the
4403    ///     same "0 means the opposite of what you think" footgun
4404    ///     closed for `:politicas :timeout` (Envoy interprets a zero
4405    ///     timeout as `infinite`), `:politicas :circuit-breaker
4406    ///     :window`, and `:limits :wall-clock`. The
4407    ///     `MaxIntensity / Period` ratio in Erlang/OTP's
4408    ///     `supervisor` requires `Period > 0`; a zero period either
4409    ///     trips on the first failure or never trips depending on
4410    ///     operator interpretation, neither of which is the
4411    ///     author's intent. Omit `:restart-window` to express "no
4412    ///     reset"; carry a positive duration to express the window.
4413    ///   - duplicate `:children` `:caixa` names are the same
4414    ///     graph-node-set / multiset distinction closed for
4415    ///     `:membros` (4bb3f3d), `:placement :clusters` (c7c7799),
4416    ///     and `:entrada :paths` (eb3456d). Two children with the
4417    ///     same `:caixa` materialize as two ComputeUnits with the
4418    ///     same name in the cluster's HelmRelease values, one
4419    ///     silently overwriting the other. Erlang/OTP's
4420    ///     `child_spec.id` is required-unique per supervisor;
4421    ///     pleme-io enforces the same set-not-multiset shape on
4422    ///     `:caixa` (the load-bearing identity in our renderer).
4423    pub fn validate(&self) -> Result<(), SupervisorError> {
4424        // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition
4425        // dispatch and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
4426        // error carrier's `estrategia:` field through the lifted
4427        // [`SupervisorSpec::estrategia`] accessor rather than the raw
4428        // `self.estrategia` field access — the two production consumers
4429        // of the per-`:supervisor` sibling-restart-strategy scalar now
4430        // key off exactly one typed dispatch on the substrate primitive,
4431        // so any future rebrand on the axis (a per-cluster strategy
4432        // override the operator pins through a future `:supervisor
4433        // :estrategia-overrides` slot, a per-tenant strategy-alias table
4434        // the M4 CR materializer resolves per-CR) migrates as a single
4435        // caixa-core edit rather than a coordinated rewrite of the two
4436        // call sites — sibling of the peer M3 [`crate::Placement::estrategia`]
4437        // (921fe1b) four-consumer migration on the per-`:placement`
4438        // distribution-strategy axis.
4439        // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition-
4440        // dispatch's paired `.is_empty()` cross-slot refusal probes
4441        // (the `SimpleOneForOne`-arm
4442        // [`SupervisorError::SimpleOneForOneWithStaticChildren`] refusal
4443        // and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
4444        // refusal) through the lifted [`SupervisorSpec::children`]
4445        // slice-return accessor rather than the raw `self.children`
4446        // field access — the two paired production consumers of the
4447        // per-`:supervisor` static-child-list scalar-shape now key off
4448        // exactly one typed dispatch on the substrate primitive, so any
4449        // future rebrand on the axis (a per-cluster child-set overlay
4450        // the operator pins through a future `:supervisor
4451        // :children-overrides` slot, a per-tenant child-set-alias table
4452        // the M4 CR materializer resolves per-CR) migrates as a single
4453        // caixa-core edit rather than a coordinated rewrite of the
4454        // paired arms — first slice-return migration on any typed slot,
4455        // seed for the peer per-`:placement :clusters`,
4456        // per-`:membros`, per-`:contratos`, and per-`:upgrade-from
4457        // :instructions` `Vec`-carry axes.
4458        match self.estrategia() {
4459            RestartStrategy::SimpleOneForOne => {
4460                // SimpleOneForOne: children added at runtime. Static
4461                // list must be empty (one shape declared elsewhere).
4462                if !self.children().is_empty() {
4463                    return Err(SupervisorError::SimpleOneForOneWithStaticChildren);
4464                }
4465            }
4466            _ => {
4467                if self.children().is_empty() {
4468                    return Err(SupervisorError::no_children(self.estrategia()));
4469                }
4470            }
4471        }
4472        // Zero-floor + upper-cap bracket on the typed `:max-restarts`
4473        // axis. See [`crate::render::require_positive_bounded_u32`] for
4474        // the ordering discipline (zero-floor arm strictly precedes cap
4475        // arm so `0` surfaces the self-locating `ZeroMaxRestarts`
4476        // diagnostic with its counter-axis remediation directly named,
4477        // not the misleading `0 > SUPERVISOR_MAX_RESTARTS_MAX == false`
4478        // cap-arm miss). Until this bracket landed the top edge ran all
4479        // the way to `u32::MAX` and a struct-literal
4480        // `SupervisorSpec { max_restarts: 100_000, .. }` (or the
4481        // equivalent author-surface `:max-restarts 100000` /
4482        // `:max-restarts 4294967295` typo landing in the slot) silently
4483        // passed validate. The runtime substrate consuming the value
4484        // (Erlang/OTP's `MaxIntensity / Period` ratio, the future
4485        // wasm-operator's per-supervisor restart-intensity counter, the
4486        // M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
4487        // admission webhook) then turned a typed `:max-restarts`
4488        // policy into a no-op supervisor: the escalation threshold is
4489        // structurally so high that no realistic
4490        // restarts-per-`:restart-window` traffic shape can reach it,
4491        // the supervisor never escalates to its parent, and a bad
4492        // child can loop inside the window indefinitely with the
4493        // parent supervisor structurally never receiving the "this
4494        // subtree has exceeded its restart budget" signal the typed
4495        // slot is meant to express. The bracket set is
4496        // `1..=SUPERVISOR_MAX_RESTARTS_MAX`, peer with the
4497        // [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap on
4498        // the sibling `:politicas :circuit-breaker :max-failures` axis:
4499        // both are "trip the next-higher protection layer after N
4500        // events in a rolling window" counters with identical
4501        // degenerate-at-the-high-end shape and now share one canonical
4502        // bracket helper. The bracket precedes the sibling
4503        // `:restart-window` zero-floor / canonical-millisecond arms so
4504        // an over-cap `max_restarts` paired with a structurally invalid
4505        // window surfaces the bracket diagnostic first, mirroring the
4506        // `PolicyBreakerMaxFailuresExceedsCap` / window-axis cross-arm
4507        // ordering on the peer `:politicas :circuit-breaker` slot.
4508        // Route the [`SupervisorSpec::validate`] `:max-restarts` zero-floor +
4509        // upper-cap bracket-gate through the lifted [`SupervisorSpec::max_restarts`]
4510        // accessor rather than the raw `self.max_restarts` field access —
4511        // the one production consumer of the per-`:supervisor`
4512        // restart-budget-count scalar now keys off exactly one typed
4513        // dispatch on the substrate primitive, so any future rebrand on
4514        // the axis (a per-cluster restart-budget override the operator
4515        // pins through a future `:supervisor :max-restarts-overrides`
4516        // slot, a per-tenant restart-budget-alias table the M4 CR
4517        // materializer resolves per-CR) migrates as a single caixa-core
4518        // edit rather than a coordinated rewrite — sibling of the peer M3
4519        // [`crate::CircuitBreaker::max_failures`] (3a74062) migration on
4520        // the per-`:politicas :circuit-breaker :max-failures` axis.
4521        crate::render::require_positive_bounded_u32(
4522            self.max_restarts(),
4523            SUPERVISOR_MAX_RESTARTS_MAX,
4524            || SupervisorError::ZeroMaxRestarts,
4525            SupervisorError::max_restarts_exceeds_cap,
4526        )?;
4527        // Route the [`SupervisorSpec::validate`] `:restart-window`
4528        // zero-floor + integer-millisecond canonical-form + upper-cap
4529        // bracket-gate through the lifted [`SupervisorSpec::restart_window`]
4530        // accessor rather than the raw `self.restart_window` field access —
4531        // the one production consumer of the per-`:supervisor`
4532        // restart-intensity-denominator scalar now keys off exactly one
4533        // typed dispatch on the substrate primitive, so any future rebrand
4534        // on the axis (a per-cluster restart-window override the operator
4535        // pins through a future `:supervisor :restart-window-overrides`
4536        // slot, a per-tenant restart-window-alias table the M4 CR
4537        // materializer resolves per-CR) migrates as a single caixa-core
4538        // edit rather than a coordinated rewrite — sibling of the peer M2
4539        // [`crate::LimitsSpec::wall_clock`] (8cb717b) validate-arm-route
4540        // on the per-`:limits :wall-clock` axis and the peer M3
4541        // [`crate::MeshPolicy::timeout`] (7073d0f) accessor-route on the
4542        // per-`:politicas :timeout` axis.
4543        if let Some(w) = self.restart_window() {
4544            // Zero-floor + integer-millisecond canonical-form +
4545            // upper-cap bracket on the typed `:restart-window` axis.
4546            // See
4547            // [`crate::render::require_positive_canonical_bounded_duration`]
4548            // for the full three-arm ordering discipline (zero-floor
4549            // strictly precedes canonical-form so `Duration::ZERO`
4550            // surfaces the self-locating `RestartWindowZero`
4551            // diagnostic; canonical-form strictly precedes the cap arm
4552            // so a sub-millisecond above-cap value surfaces the more
4553            // fundamental round-trip-shape diagnostic first) and the
4554            // three peer typed-`Duration` sites that share this
4555            // canonical bracket ([`crate::MeshPolicy::timeout`],
4556            // [`crate::CircuitBreaker::window`],
4557            // [`crate::LimitsSpec::wall_clock`]). Every validated
4558            // value lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
4559            // (1ms..=1h), integer-millisecond granularity.
4560            crate::render::require_positive_canonical_bounded_duration(
4561                w,
4562                SUPERVISOR_RESTART_WINDOW_MAX,
4563                || SupervisorError::RestartWindowZero,
4564                SupervisorError::restart_window_not_canonical,
4565                SupervisorError::restart_window_exceeds_cap,
4566            )?;
4567        }
4568        // Route the per-child DNS-1123 / semver-requirement / duplicate-
4569        // detection fan-out loop through the lifted named per-slot gate
4570        // [`SupervisorSpec::validate_children`] rather than an inline
4571        // three-per-child cascade — every future consumer that wants to
4572        // re-check only the `:children` slot's per-entry axes (the M4
4573        // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
4574        // admission webhook re-validating one added/renamed child, the
4575        // future wasm-operator's per-child dynamic-add re-validator on
4576        // the `SimpleOneForOne` runtime-add path once dynamic-children
4577        // graduate to a typed slot, a future partial re-validator on a
4578        // per-`:children`-entry patch) reaches every per-entry axis
4579        // through one dispatch rather than re-inlining the three-arm
4580        // cascade in lockstep with `validate` or paying the peer
4581        // `:estrategia`/`:max-restarts`/`:restart-window` gates to
4582        // reach one entry check. Sibling of the peer M3 mesh-slot
4583        // per-slot gate family (`validate_membros` — the exact peer on
4584        // the M3 side, [`crate::AplicacaoSpec::validate_membros`];
4585        // `validate_contratos` — 906a5c6; `validate_entrada` — 20cd523;
4586        // `validate_placement`; `validate_politicas` routing through
4587        // `MeshPolicy::validate` — f03a154) — the M2 supervisor-slot
4588        // per-slot gate discipline now spans both the M3 mesh-slot
4589        // family and the M2 `:children` per-child-cascade axis on one
4590        // shape: one named per-slot gate per typed per-entry loop.
4591        self.validate_children()?;
4592        Ok(())
4593    }
4594
4595    /// Named per-slot gate on the M2 `:supervisor :children` per-entry
4596    /// axis — folds the per-child DNS-1123 name gate, semver-requirement
4597    /// gate, and duplicate-`:caixa` dedup arm into one call every
4598    /// consumer that wants to re-validate one `:children` entry (or the
4599    /// whole list) against the same accept-set [`SupervisorSpec::validate`]
4600    /// admits reaches through.
4601    ///
4602    /// Peer of the M3 mesh-slot [`crate::AplicacaoSpec::validate_membros`]
4603    /// per-slot gate on the analogous per-entry axis (`:membros`) — same
4604    /// three-per-entry shape (DNS-1123 name + semver-requirement +
4605    /// duplicate-`:caixa` dedup), lifted to one named substrate
4606    /// primitive per slot. The M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
4607    /// materializer's admission webhook re-checking one added or renamed
4608    /// child, the future wasm-operator's per-child dynamic-add
4609    /// re-validator on the `SimpleOneForOne` runtime-add path once
4610    /// dynamic-children graduate to a typed slot, a future partial
4611    /// re-validator on a per-`:children`-entry patch — each reaches the
4612    /// three per-entry axes through this one dispatch rather than
4613    /// re-inlining the three-arm cascade in lockstep with `validate`
4614    /// (the duplication the PRIME DIRECTIVE names as a bug) or paying
4615    /// the peer `:estrategia`/`:max-restarts`/`:restart-window` gates to
4616    /// reach one entry check.
4617    ///
4618    /// Self-contained on `&self` — resolves its own dedup `HashSet`
4619    /// through [`SupervisorSpec::children`] rather than borrowing one
4620    /// threaded down from `validate`, the same posture the peer M3
4621    /// mesh-slot per-slot gates ([`crate::AplicacaoSpec::validate_membros`],
4622    /// [`crate::AplicacaoSpec::validate_contratos`],
4623    /// [`crate::AplicacaoSpec::validate_entrada`],
4624    /// [`crate::AplicacaoSpec::validate_placement`]) each carry, so a
4625    /// consumer that reaches this gate directly (without first calling
4626    /// `validate`) still runs the full per-child cascade — pinned by
4627    /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
4628    /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
4629    /// + `validate_children_is_self_contained_on_children_slot`.
4630    ///
4631    /// The three per-entry arms run in the same canonical order the
4632    /// pre-lift inline cascade encoded (DNS-1123 → semver → dedup), so
4633    /// the diagnostic every author-declared per-`:children` entry surfaces
4634    /// through `validate` is byte-equal to the diagnostic this gate
4635    /// surfaces when called directly — the equivalence-pin pair
4636    /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
4637    /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
4638    /// asserts the two altitudes discriminate the same set on every
4639    /// per-entry-covered input.
4640    pub fn validate_children(&self) -> Result<(), SupervisorError> {
4641        let mut seen = std::collections::HashSet::new();
4642        for child in self.children() {
4643            // Every emitted cluster artifact's `metadata.name` for a
4644            // supervised child derives from this `:children :caixa` value
4645            // verbatim — the rendered `wasm.pleme.io/v1alpha1/ComputeUnit
4646            // .metadata.name` per child, the [`crate::LABEL_PROGRAM`]
4647            // label value on every child's pod identity, and the per-
4648            // child K8s [`Service`][svc] `metadata.name` the future
4649            // wasm-operator (M3) provisions for inter-child supervision
4650            // tree wiring. Each apiserver-side schema on each landing
4651            // site enforces the DNS-1123 label rule on admission; a
4652            // structurally invalid child name (`"Worker"`, `"my_worker"`,
4653            // `"team.worker"`, `"-worker"`, `"worker-"`, the >63-byte
4654            // UUID-shaped mistaken-identity slug) silently passes the
4655            // prior empty-/duplicate-only gate and the failure surfaces
4656            // at `kubectl apply` time as a `metadata.name: Invalid value`
4657            // rejection, far from the source caixa.lisp, with no field
4658            // naming the offending `:children` entry. Lifting the gate
4659            // to caixa-build time mirrors the `:membros :caixa` value-
4660            // shape trajectory (3f9d7a0) and the `:placement :clusters`
4661            // trajectory (6cbb900) onto the third DNS-1123-label-shaped
4662            // identifier axis — the supervisor tree's child names —
4663            // through the lifted
4664            // [`crate::render::require_valid_dns_1123_label`] gate the
4665            // seven peer name axes (`:membros :caixa`, `:placement
4666            // :clusters`, `:placement :affinity`, `:contratos :de`/`:para`,
4667            // `:entrada :para`, `:nome`, `:upgrade-from :module`) each
4668            // route through, so drift between the eight axes' accepted
4669            // DNS-1123-label sets is structurally impossible.
4670            //
4671            // [svc]: https://kubernetes.io/docs/concepts/services-networking/service/
4672            crate::render::require_valid_dns_1123_label(
4673                child.nome(),
4674                || SupervisorError::EmptyChildName,
4675                |reason| SupervisorError::child_caixa_invalid(child.nome(), reason),
4676            )?;
4677            // The author surface for `:children :versao` is the same
4678            // Cargo-shaped semver requirement string `:deps :versao` and
4679            // `:membros :versao` carry — and the lacre pipeline resolves
4680            // all three axes through the same
4681            // [`crate::version::parse_requirement`] entry-point. The
4682            // shared [`crate::render::require_valid_versao_requirement`]
4683            // helper brackets the empty-first + parse cascade both peer
4684            // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
4685            // [`crate::AplicacaoSpec::validate_membros`] on `:membros
4686            // :versao`) route through, so drift between the three axes'
4687            // accepted requirement sets is structurally impossible and
4688            // the parse-side no-op the empty-first arm closes (semver's
4689            // empty parse yields an implicit `*`) lives in exactly one
4690            // predicate. Every `ChildSpec::versao` past validate is
4691            // round-trippable through [`crate::parse_requirement`]
4692            // without re-checking at the resolver layer, and the three
4693            // `:versao` typed surfaces (`:deps`, `:membros`, `:children`)
4694            // are now structurally equivalent by construction.
4695            crate::render::require_valid_versao_requirement(
4696                child.versao_requirement(),
4697                || SupervisorError::empty_child_version(child.nome()),
4698                |reason| {
4699                    SupervisorError::child_versao_invalid(
4700                        child.nome(),
4701                        child.versao_requirement(),
4702                        reason,
4703                    )
4704                },
4705            )?;
4706            crate::render::insert_first_seen(&mut seen, child.nome(), || {
4707                SupervisorError::duplicate_child_caixa(child.nome())
4708            })?;
4709        }
4710        Ok(())
4711    }
4712}
4713
4714/// Cross-slot coherence gate on the supervision tree: no
4715/// `:children :caixa` entry may name the supervisor's own `:nome`.
4716///
4717/// A supervisor that lists itself as a child is a degenerate self-parent
4718/// — the supervision tree is a DAG rooted at the supervisor (OTP child
4719/// specs reference *distinct* child processes; a supervisor is never its
4720/// own child), and the wasm-operator's hierarchical reconciliation would
4721/// otherwise be handed a node that is its own parent: a one-node cycle it
4722/// either rejects far from the source `caixa.lisp` or recurses on. Because
4723/// every `:nome` is a globally-unique substrate identity (DNS-1123 label +
4724/// lacre closure root), a child whose `:caixa` equals the supervisor's
4725/// `:nome` *is* the supervisor itself, not a coincidentally-named peer.
4726///
4727/// Lives outside [`SupervisorSpec::validate`] because the typed view
4728/// carries the children but not the parent `:nome`; mirrors the
4729/// cross-slot precedence gate `validate_upgrade_from_against_versao`
4730/// (which likewise reads one slot against another at the
4731/// [`crate::layout`] wire-up site) and the mesh self-edge gate
4732/// `AplicacaoSpec`'s `ContratoSelfLoop` — the same "an edge from a graph
4733/// node to itself is structurally not a tree/mesh edge" discipline, here
4734/// on the supervision-tree axis.
4735pub fn validate_no_self_supervision(
4736    children: &[ChildSpec],
4737    parent_nome: &str,
4738) -> Result<(), SupervisorError> {
4739    for child in children {
4740        if child.nome() == parent_nome {
4741            return Err(SupervisorError::child_supervises_self(parent_nome));
4742        }
4743    }
4744    Ok(())
4745}
4746
4747#[derive(Debug, Error, PartialEq, Eq)]
4748pub enum SupervisorError {
4749    #[error("supervisor :estrategia {estrategia:?} requires at least one :children entry")]
4750    NoChildren { estrategia: RestartStrategy },
4751    #[error(
4752        "SimpleOneForOne supervisors must declare zero static children (children spawn dynamically)"
4753    )]
4754    SimpleOneForOneWithStaticChildren,
4755    #[error(":max-restarts must be > 0")]
4756    ZeroMaxRestarts,
4757    #[error(
4758        ":supervisor :max-restarts ({max_restarts}) exceeds the supervisor-policy ceiling \
4759         (SUPERVISOR_MAX_RESTARTS_MAX = 1000) — a value above this cap turns the typed \
4760         restart-intensity policy into a no-op supervisor: the escalation threshold is \
4761         structurally so high that no realistic restarts-per-:restart-window traffic shape \
4762         can reach it, so the supervisor never escalates to its parent and a bad child can \
4763         loop inside the window indefinitely. Every typed-slot consumer (Erlang/OTP's \
4764         MaxIntensity/Period ratio, the future wasm-operator's per-supervisor \
4765         restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
4766         materializer's admission webhook) emits a `:max-restarts` declaration that is \
4767         structurally never reached. Pin a value in 1..=1000 (Erlang/OTP / Elixir / Riak \
4768         Core / RabbitMQ production playbooks recommend 3..=100; the OTP `supervisor` \
4769         callback module's `MaxR = 1` minimal-restart default sits at the bottom of the \
4770         band) or restructure the supervision tree (split the flaky child into its own \
4771         sub-supervisor with a tighter budget) if you need a higher restart tolerance."
4772    )]
4773    MaxRestartsExceedsCap { max_restarts: u32 },
4774    #[error(
4775        ":restart-window must be > 0 when set — Erlang/OTP's MaxIntensity/Period \
4776         requires Period > 0; a zero window either trips on the first failure or \
4777         never trips depending on operator interpretation. Omit :restart-window to \
4778         express `never reset`; carry a positive duration to express the window."
4779    )]
4780    RestartWindowZero,
4781    #[error(
4782        ":supervisor :restart-window ({window:?}) carries a sub-millisecond residue the shared `duration_codec` cannot round-trip — \
4783         the codec truncates to `as_millis()` before picking the canonical unit, so a value with `subsec_nanos() % 1_000_000 != 0` either \
4784         truncates on first serialize (e.g. `Duration::from_micros(1500)` → \"1ms\" → `Duration::from_millis(1)` ≠ original) or renders \
4785         as \"0s\" the `RestartWindowZero` arm then rejects on re-validate. Pin an integer-millisecond magnitude in the canonical authoring form \
4786         (`<integer><unit>` for unit ∈ {{ms, s, m, h}}, e.g. `\"500ms\"`, `\"30s\"`, `\"2m\"`, `\"1h\"`) or omit the field for `never reset`"
4787    )]
4788    RestartWindowNotCanonical { window: Duration },
4789    #[error(
4790        ":supervisor :restart-window ({window:?}) exceeds the supervisor-policy ceiling \
4791         (SUPERVISOR_RESTART_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
4792         per-supervisor rolling-window restart-intensity counter into a lifetime counter: the \
4793         failure-counting window is structurally so long that transient restarts are never \
4794         forgotten, the MaxIntensity/Period ratio degenerates from `trip the parent supervisor \
4795         when the child has exceeded its restart budget within the recent window` to `trip the \
4796         parent when the child has exceeded its restart budget over its lifetime`, and the \
4797         supervisor's reset semantic never reaches the child — every typed-slot consumer \
4798         (Erlang/OTP's MaxIntensity/Period reconciler, the future wasm-operator's \
4799         per-supervisor restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
4800         materializer's admission webhook, the caixa-operator's hierarchical reconciliation \
4801         scheduler) emits a `:restart-window` declaration that is structurally a no-op rolling \
4802         window. Pin a value in 1ms..=1h (Learn You Some Erlang's `{{intensity, 5, 60}}` \
4803         worker-supervisor `Period = 60s` default, Elixir's `Supervisor` `max_seconds: 5` \
4804         default, OTP's `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's \
4805         `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default — every Erlang/OTP \
4806         / Elixir production playbook sits in the 5s..=300s band; the longest documented \
4807         per-supervisor restart-window any pleme-io substrate playbook recommends maxes at \
4808         ~30m) or omit :restart-window to express `never reset` (the supervisor's restart \
4809         budget then becomes a strict lifetime counter by design, not a degenerate one — the \
4810         author surfaces the lifetime-counter semantic explicitly at the slot, rather than \
4811         hiding it behind a rolling-window declaration the cap arm rejects)"
4812    )]
4813    RestartWindowExceedsCap { window: Duration },
4814    #[error("child entry has empty :caixa name")]
4815    EmptyChildName,
4816    #[error(
4817        "child :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
4818         (the K8s apiserver enforces this rule on every `metadata.name` / Service \
4819         name / label value the child name lands in — the per-child \
4820         `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name`, the `LABEL_PROGRAM` \
4821         label value, and the future wasm-operator per-child Service `metadata.name` \
4822         — each apiserver-side schema rejects names that don't match; use a \
4823         lowercase alphanumeric + hyphen identifier like `\"worker\"` or `\"cache-v2\"`)"
4824    )]
4825    ChildCaixaInvalid { caixa: String, reason: String },
4826    #[error("child {caixa:?} has empty :versao constraint")]
4827    EmptyChildVersion { caixa: String },
4828    #[error(
4829        "child {caixa:?} :versao {versao:?} is not a valid semver requirement: \
4830         {reason} (use Cargo-shaped forms like `\"^0.1\"`, `\"~0.1.2\"`, \
4831         `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` and \
4832         `:membros :versao` carry; the lacre pipeline resolves all three \
4833         through the same parser)"
4834    )]
4835    ChildVersaoInvalid {
4836        caixa: String,
4837        versao: String,
4838        reason: String,
4839    },
4840    #[error(
4841        "child {caixa:?} appears more than once (Erlang/OTP requires unique \
4842         child_spec.id per supervisor; duplicate children materialize as duplicate \
4843         ComputeUnits in the rendered chart, one silently overwriting the other)"
4844    )]
4845    DuplicateChildCaixa { caixa: String },
4846    #[error(
4847        "supervisor {caixa:?} lists itself as a :children entry — a supervisor is \
4848         never its own child (the supervision tree is a DAG rooted at the supervisor; \
4849         OTP child specs reference distinct child processes). Since every :nome is a \
4850         globally-unique substrate identity, a child naming the supervisor's own :nome \
4851         is a one-node reconciliation cycle, not a coincidentally-named peer; drop the \
4852         self-referential :children entry or rename it to the actual child caixa."
4853    )]
4854    ChildSupervisesSelf { caixa: String },
4855}
4856
4857// Fold the three `SupervisorError::<Variant> { caixa: <&str>.to_string() }`
4858// caixa-only struct-variant wire-up sites at [`SupervisorSpec::validate_children`]
4859// and [`validate_no_self_supervision`] onto one substrate primitive per
4860// typed variant — the sibling on `SupervisorError` of the four uniform-shape
4861// `LayoutError`-envelope constructor families the peer
4862// [`crate::layout::layout_violation_ctors!`] macro closed (131ca0d, 16
4863// variants on `{ caixa, issue }`), the [`crate::layout::layout_slot_kind_ctors!`]
4864// macro closed (0419438, 4 variants on `{ caixa, kind, slots }`), the
4865// [`crate::LayoutError::missing_entry`] one-variant ctor closed (1b09f9d,
4866// on `{ kind, path }`), and the [`crate::layout::layout_nome_only_ctors!`]
4867// macro closed (3fe3dd7, 6 variants on `<Variant>(String)`), plus the
4868// [`crate::AplicacaoError::entrada_host_invalid`] one-variant ctor
4869// (17dd504, `{ host, reason }`), the [`crate::aplicacao::contrato_target_ctors!`]
4870// macro (14b81d5, 2 variants on `{ de, para, wit, expected }`), and the
4871// [`crate::aplicacao::contrato_empty_pair_ctors!`] macro (8580068, 4
4872// variants on `{ de, para }`) already at that discipline on the peer
4873// `AplicacaoError` envelopes.
4874//
4875// Each of the three wire-up sites on this shape (`EmptyChildVersion` at
4876// the per-`:children` semver-requirement empty-first arm, `DuplicateChildCaixa`
4877// at the per-`:children` dedup arm, `ChildSupervisesSelf` at the cross-slot
4878// self-supervision arm) opened the identical
4879// `SupervisorError::<Variant> { caixa: <&str>.to_string() }` struct-literal —
4880// the exact "same block re-inlined at every consumer" shape the PRIME
4881// DIRECTIVE names as a bug, on the same altitude the peer `LayoutError` /
4882// `AplicacaoError` families each closed on their sibling envelopes. The
4883// three variants share one `{ caixa: String }` shape, so the fold routes
4884// each wire-up site through one dispatch per typed variant.
4885//
4886// The macro below generates one static constructor per variant of shape
4887// `fn <slot>(caixa: &str) -> SupervisorError`, so every wire-up site
4888// collapses onto one dispatch:
4889// `SupervisorError::<slot>(<&str>)`, byte-equal to the pre-lift
4890// struct-literal on the same `&str` fixture. The uniform one-field
4891// construction (`caixa: caixa.to_string()`) is spelled once — inside the
4892// macro — rather than at every wire-up site. Every constructor is
4893// `#[must_use]` so a caller who mistakenly discards the constructed error
4894// trips a compile warning at the wire-up site.
4895//
4896// Every future consumer that wants to construct one of these three
4897// variants outside `SupervisorSpec::validate_children` /
4898// `validate_no_self_supervision` — a deferred
4899// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
4900// webhook re-checking one added/renamed child, a future
4901// `feira validate --supervisor` per-caixa admission verb, a per-child
4902// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path
4903// once dynamic-children graduate to a typed slot, a per-Supervisor
4904// overlay resolver rejecting a duplicate/self-supervising child against
4905// a cluster-local snapshot — now reaches each variant through one call
4906// rather than re-inlining the three-line struct-literal in lockstep
4907// with the three in-crate wire-up sites.
4908macro_rules! supervisor_caixa_only_ctors {
4909    ($($ctor:ident => $variant:ident),* $(,)?) => {
4910        impl SupervisorError {
4911            $(
4912                #[doc = concat!(
4913                    "Construct a [`SupervisorError::",
4914                    stringify!($variant),
4915                    "`] naming the offending `:children :caixa` (or ",
4916                    "supervisor `:nome`, on the self-supervision arm). ",
4917                    "Folds the uniform `Self::",
4918                    stringify!($variant),
4919                    " { caixa: caixa.to_string() }` one-field ",
4920                    "struct-literal onto one substrate primitive so ",
4921                    "every [`SupervisorSpec::validate_children`] / ",
4922                    "[`validate_no_self_supervision`] wire-up on this ",
4923                    "variant reads through one dispatch rather than the ",
4924                    "pre-lift open-coded struct-literal block."
4925                )]
4926                #[must_use]
4927                pub fn $ctor(caixa: &str) -> Self {
4928                    Self::$variant { caixa: caixa.to_string() }
4929                }
4930            )*
4931        }
4932    };
4933}
4934
4935supervisor_caixa_only_ctors! {
4936    empty_child_version => EmptyChildVersion,
4937    duplicate_child_caixa => DuplicateChildCaixa,
4938    child_supervises_self => ChildSupervisesSelf,
4939}
4940
4941// Fold the two `SupervisorError::{ChildCaixaInvalid, ChildVersaoInvalid}`
4942// struct-variant wire-up sites at [`SupervisorSpec::validate_children`] onto
4943// one substrate primitive per typed variant — the M2 supervisor-side siblings
4944// of the peer [`crate::AplicacaoError::membro_caixa_invalid`] two-slot ctor
4945// already lifted through the sibling
4946// [`crate::aplicacao::aplicacao_field_reason_ctors!`] macro (981060b) on the
4947// peer `AplicacaoError { caixa: String, reason: String }` envelope. The
4948// `ChildCaixaInvalid` variant carries the same `{ <name>: String, reason:
4949// String }` two-slot shape the peer seven-variant
4950// [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold closed on the
4951// `AplicacaoError` envelope (`MembroCaixaInvalid`, `EntradaParaInvalid`,
4952// `EntradaHostInvalid`, `EntradaPathInvalid`, `PlacementClusterInvalid`,
4953// `PlacementAffinityInvalid`, `ShardKeyInvalid`); the `ChildVersaoInvalid`
4954// variant carries the `{ caixa: String, versao: String, reason: String }`
4955// three-slot shape the sibling `AplicacaoError::MembroVersaoInvalid` axis
4956// carries on the same `:versao` value-shape.
4957//
4958// Each of the two wire-up sites opened the same closure-shaped
4959// `|reason| SupervisorError::<Variant> { caixa: child.nome().to_string(),
4960// [versao: child.versao_requirement().to_string(),] reason }` block inside
4961// the paired [`crate::render::require_valid_dns_1123_label`] and
4962// [`crate::render::require_valid_versao_requirement`] callbacks — the exact
4963// "same block re-inlined at every consumer" shape the PRIME DIRECTIVE names
4964// as a bug, on the same altitude the peer `AplicacaoError` /
4965// `SupervisorError` / `LayoutError` / `DepError` / `LimitsError` ctor
4966// families already closed on their sibling envelopes.
4967//
4968// The two `#[must_use]` inherent constructors below fold each wire-up onto
4969// one dispatch: `SupervisorError::child_caixa_invalid(<name>, <reason>)`
4970// and `SupervisorError::child_versao_invalid(<name>, <versao>, <reason>)`,
4971// byte-equal to the pre-lift struct-literal on the same scalar fixtures.
4972// The uniform per-field `.to_string()` / `.into()` construction is spelled
4973// once — inside each ctor body — rather than at every wire-up site. The
4974// `reason: impl Into<String>` bound accepts both `&str` literals and
4975// `format!(…)` outputs verbatim so no wire-up site changes its per-arm
4976// diagnostic shape at the lift, matching the peer
4977// [`aplicacao_field_reason_ctors!`] and
4978// [`crate::aplicacao::contrato_pair_value_reason_ctors!`] bounds on the
4979// sibling envelopes.
4980//
4981// Every future consumer that wants to construct one of these two variants
4982// outside `SupervisorSpec::validate_children` — a deferred
4983// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook
4984// re-checking one added/renamed child's `:caixa` or `:versao`, a future
4985// `feira validate --supervisor` per-caixa admission verb, a per-child
4986// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path once
4987// dynamic-children graduate to a typed slot, a per-Supervisor overlay
4988// resolver rejecting a shape-invalid child `:caixa`/`:versao` against a
4989// cluster-local snapshot — now reaches each variant through one call rather
4990// than re-inlining the per-shape struct-literal block in lockstep with the
4991// two in-crate wire-up sites.
4992impl SupervisorError {
4993    /// Construct a [`SupervisorError::ChildCaixaInvalid`] naming the
4994    /// offending `:children :caixa` value under the given `reason`. Folds
4995    /// the uniform `Self::ChildCaixaInvalid { caixa: caixa.to_string(),
4996    /// reason: reason.into() }` two-slot struct-literal onto one substrate
4997    /// primitive so every wire-up on this variant reads through one
4998    /// dispatch, matching the peer
4999    /// [`crate::AplicacaoError::membro_caixa_invalid`] ctor's shape on the
5000    /// sibling `AplicacaoError { caixa: String, reason: String }`
5001    /// envelope. `reason` accepts both `&str` literals and `format!(…)`
5002    /// outputs through the `impl Into<String>` bound.
5003    #[must_use]
5004    pub fn child_caixa_invalid(caixa: &str, reason: impl Into<String>) -> Self {
5005        Self::ChildCaixaInvalid {
5006            caixa: caixa.to_string(),
5007            reason: reason.into(),
5008        }
5009    }
5010
5011    /// Construct a [`SupervisorError::ChildVersaoInvalid`] naming the
5012    /// offending `:children :caixa` and its `:versao` requirement under
5013    /// the given `reason`. Folds the uniform `Self::ChildVersaoInvalid {
5014    /// caixa: caixa.to_string(), versao: versao.to_string(), reason:
5015    /// reason.into() }` three-slot struct-literal onto one substrate
5016    /// primitive so every wire-up on this variant reads through one
5017    /// dispatch, matching the sibling `AplicacaoError::MembroVersaoInvalid
5018    /// { caixa, versao, reason }` three-slot axis on the peer
5019    /// `AplicacaoError` envelope. `reason` accepts both `&str` literals
5020    /// and `format!(…)` outputs through the `impl Into<String>` bound.
5021    #[must_use]
5022    pub fn child_versao_invalid(caixa: &str, versao: &str, reason: impl Into<String>) -> Self {
5023        Self::ChildVersaoInvalid {
5024            caixa: caixa.to_string(),
5025            versao: versao.to_string(),
5026            reason: reason.into(),
5027        }
5028    }
5029}
5030
5031// Fold the four `SupervisorError::<Variant> { <field>: <Copy> }` one-field
5032// Copy-scalar struct-variant wire-up sites at [`SupervisorSpec::validate`]'s
5033// three bracket-arms — one struct-literal at the `:children`-empty
5034// non-`SimpleOneForOne` refusal cascade (`NoChildren { estrategia }`) plus
5035// three `impl FnOnce(<ty>) -> SupervisorError` bracket-closures at the
5036// [`crate::render::require_positive_bounded_u32`] `:max-restarts` cap arm
5037// (`MaxRestartsExceedsCap { max_restarts }`) and the paired
5038// [`crate::render::require_positive_canonical_bounded_duration`]
5039// `:restart-window` canonical-form + cap arms (`RestartWindowNotCanonical
5040// { window }`, `RestartWindowExceedsCap { window }`) — onto one substrate
5041// primitive per typed variant, matching the sibling
5042// [`crate::aplicacao::aplicacao_policy_scalar_ctors!`] macro (7ef425e, 8
5043// variants on the same `{ <field>: Duration | u32 }` shape) at that
5044// discipline on the peer `AplicacaoError` envelope's per-`:politicas`
5045// scalar axis. Every variant is a one-field `Copy`-pass-through struct-
5046// literal — `RestartStrategy | u32 | Duration` — so the fold routes each
5047// wire-up site through one dispatch per typed variant without a runtime-
5048// work delta.
5049//
5050// Each of the four wire-up sites opened the identical
5051// `SupervisorError::<Variant> { <field>: <val> }` struct-literal — the
5052// exact "same block re-inlined at every consumer" shape the PRIME
5053// DIRECTIVE names as a bug, on the same altitude the peer
5054// `aplicacao_policy_scalar_ctors!` fold closed on the sibling
5055// `AplicacaoError` envelope's per-`:politicas` per-axis cap / canonical-
5056// form arms. The four variants share one `{ <field>: <Copy> }` shape, so
5057// the fold routes each wire-up site through one dispatch per typed
5058// variant.
5059//
5060// The macro below generates one static constructor per variant of shape
5061// `const fn <ctor>(<field>: <ty>) -> SupervisorError`, so every wire-up
5062// site collapses onto one dispatch: `SupervisorError::<ctor>(<val>)`,
5063// byte-equal to the pre-lift struct-literal on the same `Copy`-`<ty>`
5064// fixture — as a direct call at the [`SupervisorSpec::validate`]
5065// `:children`-empty refusal, or as a bare function pointer in the
5066// `impl FnOnce(<ty>) -> SupervisorError` bracket-closure slot every
5067// [`crate::render::require_positive_bounded_u32`] /
5068// [`crate::render::require_positive_canonical_bounded_duration`] gate
5069// carries — rather than the pre-lift open-coded one-line closure over
5070// the same one-field struct-literal. `const fn` preserves the `Copy`-
5071// pass-through's zero-runtime-work property verbatim. Every constructor
5072// is `#[must_use]` so a caller who mistakenly discards the constructed
5073// error trips a compile warning at the wire-up site.
5074//
5075// Every future consumer that wants to construct one of these four
5076// variants outside `SupervisorSpec::validate` — a deferred
5077// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
5078// webhook re-checking one edited `:estrategia` / `:max-restarts` /
5079// `:restart-window` slot against the cap + canonical-form cascade, a
5080// future `feira validate --supervisor` per-caixa admission verb re-
5081// running the shape gates on demand, a per-Supervisor overlay resolver
5082// rejecting an author-supplied slot against a cluster-local snapshot —
5083// now reaches each variant through one call rather than re-inlining the
5084// per-shape struct-literal block in lockstep with the four in-crate
5085// wire-up sites.
5086macro_rules! supervisor_scalar_ctors {
5087    ($($ctor:ident => $variant:ident { $field:ident: $ty:ty }),* $(,)?) => {
5088        impl SupervisorError {
5089            $(
5090                #[doc = concat!(
5091                    "Construct a [`SupervisorError::",
5092                    stringify!($variant),
5093                    "`] naming the offending per-`:supervisor` `",
5094                    stringify!($field),
5095                    "` scalar. Folds the uniform `Self::",
5096                    stringify!($variant),
5097                    " { ",
5098                    stringify!($field),
5099                    " }` one-field `Copy`-pass-through struct-literal onto ",
5100                    "one substrate primitive so every per-axis wire-up on ",
5101                    "this variant reads through one dispatch — as a direct ",
5102                    "call (`SupervisorError::",
5103                    stringify!($ctor),
5104                    "(<val>)`, byte-equal to the pre-lift struct-literal on ",
5105                    "the same `Copy`-`",
5106                    stringify!($ty),
5107                    "` fixture) or as a bare function pointer in the ",
5108                    "`impl FnOnce(",
5109                    stringify!($ty),
5110                    ") -> SupervisorError` bracket-closure slot every ",
5111                    "`crate::render::require_positive_bounded_*` / ",
5112                    "`crate::render::require_positive_canonical_bounded_*` ",
5113                    "gate carries — rather than the pre-lift open-coded ",
5114                    "one-line closure over the same one-field struct-",
5115                    "literal. `const fn` preserves the `Copy`-pass-through's ",
5116                    "zero-runtime-work property verbatim."
5117                )]
5118                #[must_use]
5119                pub const fn $ctor($field: $ty) -> Self {
5120                    Self::$variant { $field }
5121                }
5122            )*
5123        }
5124    };
5125}
5126
5127supervisor_scalar_ctors! {
5128    no_children => NoChildren { estrategia: RestartStrategy },
5129    max_restarts_exceeds_cap => MaxRestartsExceedsCap { max_restarts: u32 },
5130    restart_window_not_canonical => RestartWindowNotCanonical { window: Duration },
5131    restart_window_exceeds_cap => RestartWindowExceedsCap { window: Duration },
5132}
5133
5134/// Shared duration string codec for the typed slots that take a
5135/// duration (`restart_window`, `MeshPolicy::timeout`,
5136/// `CircuitBreaker::window`, …). Public so [`crate::aplicacao`] can
5137/// reuse it without duplicating the parser.
5138pub mod duration_codec {
5139    use super::Duration;
5140    use serde::{Deserializer, Serializer};
5141
5142    pub fn serialize<S: Serializer>(v: &Option<Duration>, s: S) -> Result<S::Ok, S::Error> {
5143        // Route through the canonical [`crate::render::serialize_option_via_str`]
5144        // — the substrate-side single-owner primitive for the forward
5145        // arm of the typed-magnitude codec family. See its docstring
5146        // for the full sibling roster.
5147        crate::render::serialize_option_via_str(v, s, render)
5148    }
5149
5150    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Duration>, D::Error> {
5151        // Route through the canonical [`crate::render::deserialize_option_via_str`]
5152        // — the substrate-side single-owner primitive for the reverse
5153        // arm of the typed-magnitude codec family. See its docstring
5154        // for the full sibling roster.
5155        crate::render::deserialize_option_via_str(d, parse)
5156    }
5157
5158    pub(crate) fn parse(s: &str) -> Result<Duration, String> {
5159        // Paired whitespace-rejection arm — same canonical-form
5160        // render-determinism discipline as the peer
5161        // `limits::parse_byte_size` / `limits::parse_duration` /
5162        // `limits::parse_millicores` /
5163        // `aplicacao::rate_limit_codec::parse` sites: the ASCII
5164        // byte-scan closes the WhatWG-conformant whitespace bytes
5165        // (`0x20`, `0x09`, `0x0A`, `0x0C`, `0x0D`), the non-ASCII
5166        // `char::is_whitespace` scan closes the strictly-complementary
5167        // Unicode `White_Space` class (NBSP `\u{00A0}`, LINE SEPARATOR
5168        // `\u{2028}`, EM-SPACE `\u{2003}`, and the peer typography
5169        // codepoints) that `str::trim` at parse entry silently strips.
5170        // Either drift class would round-trip through `render` to a
5171        // *different* canonical form on next emit — breaking the
5172        // THEORY.md Part V render-determinism contract on three typed-
5173        // duration slots at once (`:supervisor :restart-window`,
5174        // `:politicas :timeout`, `:politicas :circuit-breaker :window`)
5175        // via the shared codec.
5176        //
5177        // Routed through the lifted [`crate::render::reject_whitespace`]
5178        // primitive — the substrate-side single-owner paired-arm gate
5179        // every typed-magnitude codec in caixa-core shares.
5180        crate::render::reject_whitespace::<String, _, _>(
5181            s,
5182            |b| {
5183                format!(
5184                    "duration: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
5185                 authoring form for the typed duration slots routed through this shared codec \
5186                 (`:supervisor :restart-window`, `:politicas :timeout`, \
5187                 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
5188                 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no whitespace bytes \
5189                 anywhere. A whitespace-carrying shape (`\" 30s\"`, `\"30s \"`, `\"30 s\"`, \
5190                 `\"\\t30s\"`, `\"30s\\n\"`) round-trips through `render` to a *different* \
5191                 canonical form (`\"30s\"`) on first serialize — breaking the THEORY.md \
5192                 Part V render-determinism contract every typed slot carries. Strip every \
5193                 whitespace byte (write `\"30s\"` verbatim)"
5194                )
5195            },
5196            |ch| {
5197                format!(
5198                    "duration: value {s:?} contains non-ASCII Unicode whitespace character \
5199                 {ch:?} (U+{cp:04X}) — the canonical authoring form for the typed \
5200                 duration slots routed through this shared codec (`:supervisor \
5201                 :restart-window`, `:politicas :timeout`, `:politicas :circuit-breaker \
5202                 :window`) is `<integer><unit>` (e.g. `\"30s\"`, `\"500ms\"`, `\"2m\"`, \
5203                 `\"1h\"`) with no whitespace characters anywhere (ASCII or Unicode). A \
5204                 non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}30s\"`, \
5205                 `\"30s\\u{{2028}}\"`, `\"30\\u{{2003}}s\"`) survives the ASCII byte-scan \
5206                 but `str::trim` (which uses `char::is_whitespace` — the Unicode \
5207                 `White_Space` property, strictly wider than the ASCII byte set) silently \
5208                 strips it at parse entry, and the value round-trips through `render` to \
5209                 a *different* canonical form (`\"30s\"`) on first serialize — breaking \
5210                 the THEORY.md Part V render-determinism contract every typed slot \
5211                 carries. Strip every non-ASCII whitespace character (write `\"30s\"` \
5212                 verbatim with only ASCII bytes)",
5213                    cp = ch as u32
5214                )
5215            },
5216        )?;
5217        let s = s.trim();
5218        // Routed through the lifted
5219        // [`crate::render::split_magnitude_and_alpha_unit`] primitive —
5220        // the single-owner split every ASCII-alphabetic-unit typed-
5221        // magnitude codec in caixa-core (`limits::parse_byte_size` /
5222        // `limits::parse_duration` / this shared duration codec) shares.
5223        // See its docstring for the full sibling roster on the same
5224        // primitive altitude.
5225        let (num_part, unit) = crate::render::split_magnitude_and_alpha_unit(s);
5226        let num_trim = num_part.trim();
5227        // The canonical authoring form for every typed slot routed
5228        // through this shared codec — `:supervisor :restart-window`,
5229        // `:politicas :timeout`, `:politicas :circuit-breaker :window`
5230        // — is `<integer><unit>`. Every magnitude [`render`] emits is a
5231        // non-negative integer with no decimal point and no leading
5232        // sign, so the parser's accepted set must match for
5233        // serialize/deserialize to round-trip without canonical-form
5234        // drift. Until this gate landed the parser accepted any
5235        // `f64`-shaped magnitude (`"1.5s"` → 1500ms, `"1.0s"` → 1s,
5236        // `"0.5m"` → 30s, `"+30s"` → 30s) and serde silently round-
5237        // tripped the value to a *different* canonical string on the
5238        // next emit (`"1.5s"` → 1500ms → `"1500ms"`, `"1.0s"` → 1s →
5239        // `"1s"`, `"0.5m"` → 30s → `"30s"`, `"+30s"` → 30s → `"30s"`)
5240        // — breaking the THEORY.md Part V render-determinism contract
5241        // on three typed slots at once. Same canonical-form discipline
5242        // `crate::limits::parse_duration` (818dd38, the immediate
5243        // predecessor on the peer `:limits :wall-clock` codec) applies;
5244        // this gate lifts the discipline onto the shared codec that
5245        // backs the remaining three typed-duration slots in caixa-core.
5246        //
5247        // Strict canonical form: every byte of the magnitude is an
5248        // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
5249        // inputs the gate distinguishes "non-canonical-but-numeric"
5250        // (parses as f64 or i64 — surfaced with a self-locating
5251        // diagnostic naming the canonical authoring form, the
5252        // round-trip drift each rejected shape would produce on first
5253        // serialize, and the canonical-form remediation) from
5254        // "garbage" (parses as neither — surfaced with the existing
5255        // narrower "bad duration magnitude" wording so its diagnostic
5256        // shape remains stable for the parser-shape footgun case).
5257        // The pre-existing `num < 0.0` arm is now unreachable — the
5258        // digit-only gate strictly precedes magnitude parsing, and a
5259        // leading `-` is not an ASCII digit, so `"-30s"` lands on the
5260        // non-canonical-but-numeric branch with the `-30` named
5261        // verbatim in the diagnostic rather than the prior
5262        // value-laundered "negative duration in \"-30s\"" wording.
5263        //
5264        // Routed through the lifted
5265        // [`crate::render::is_digit_only_magnitude`] predicate — the
5266        // same source of truth the four peer typed-magnitude codec
5267        // sites share.
5268        let digit_only = crate::render::is_digit_only_magnitude(num_trim);
5269        if !digit_only {
5270            let numeric = num_trim.parse::<f64>().is_ok() || num_trim.parse::<i64>().is_ok();
5271            if numeric {
5272                return Err(format!(
5273                    "duration: magnitude {num_trim:?} is not a non-negative integer — the \
5274                     canonical authoring form for the typed duration slots routed through \
5275                     this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
5276                     `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
5277                     `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no decimal point and \
5278                     no leading `+` / `-` sign. A fractional / decimal-shaped magnitude \
5279                     (`\"1.5s\"`, `\"1.0s\"`, `\"0.5m\"`, `\"+30s\"`, `\"-30s\"`) round-trips \
5280                     through `render` to a *different* canonical form (`\"1500ms\"`, `\"1s\"`, \
5281                     `\"30s\"`, `\"30s\"`, `\"30s\"`) on first serialize — breaking the \
5282                     THEORY.md Part V render-determinism contract every typed slot carries. \
5283                     Pick an integer magnitude in the unit that divides cleanly (write \
5284                     `\"1500ms\"` instead of `\"1.5s\"`; `\"30s\"` instead of `\"0.5m\"`)"
5285                ));
5286            }
5287            return Err(format!("bad duration magnitude in {s:?}"));
5288        }
5289        // Leading-zero arm — peer with the `rate_limit_codec` leading-
5290        // zero arm (4f46830) on the same canonical-form render-
5291        // determinism axis. The digit-only gate accepts `"030s"`,
5292        // `"00s"`, `"01h"`, `"0500ms"` as `u64::from_str` parses them
5293        // losslessly (= 30, 0, 1, 500), but `render` emits the leading-
5294        // zero-stripped form (`"30s"`, `"0s"`, `"1h"`, `"500ms"`) — a
5295        // *different* canonical string on the next emit, breaking the
5296        // THEORY.md Part V render-determinism contract the same way
5297        // `"+30s"` did before the leading-`+` arm landed. The single-
5298        // byte magnitude `"0"` (or `"0s"` / `"0ms"`) round-trips
5299        // losslessly through `render` (`render(Duration::ZERO)` emits
5300        // `"0s"`) — the downstream semantic-zero gates (e.g.
5301        // `SupervisorError::ZeroRestartWindow` on
5302        // `:supervisor :restart-window`,
5303        // `AplicacaoError::PolicyTimeoutZero` /
5304        // `PolicyCircuitBreakerWindowZero` on the typed `:politicas`
5305        // duration slots) refuse zero-magnitude authoring at the typed-
5306        // validate layer above, so the single-byte `"0"` stays in the
5307        // accepted set at this codec layer and the diagnostic
5308        // partitioning between canonical-form drift (this arm) and
5309        // semantic-zero (the downstream gates) remains stable.
5310        // Peer with the future leading-zero arms on the two remaining
5311        // typed-magnitude codecs the trajectory acknowledges:
5312        // `limits::parse_duration` backing `:limits :wall-clock`,
5313        // `limits::parse_byte_size` backing `:limits :memory` — each
5314        // carries the same canonical-form-drift class today; this
5315        // gate lands the discipline on the shared duration codec
5316        // first because the `rate_limit_codec` predecessor on the
5317        // same canonical-form-drift axis is the closest peer on the
5318        // trajectory.
5319        //
5320        // Routed through the lifted
5321        // [`crate::render::is_leading_zero_padded_magnitude`]
5322        // predicate — the same source of truth the four peer
5323        // typed-magnitude codec sites share.
5324        if crate::render::is_leading_zero_padded_magnitude(num_trim) {
5325            return Err(format!(
5326                "duration: magnitude {num_trim:?} has a non-canonical leading zero — the \
5327                 canonical authoring form for the typed duration slots routed through \
5328                 this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
5329                 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
5330                 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no leading-zero padding \
5331                 on the magnitude. A leading-zero magnitude (`\"030s\"`, `\"00s\"`, \
5332                 `\"01h\"`, `\"0500ms\"`) round-trips through `render` to a *different* \
5333                 canonical form (`\"30s\"`, `\"0s\"`, `\"1h\"`, `\"500ms\"`) on first \
5334                 serialize — breaking the THEORY.md Part V render-determinism contract \
5335                 every typed slot carries. Strip the leading zeros (write \
5336                 `\"30s\"` instead of `\"030s\"`)"
5337            ));
5338        }
5339        // The digit-only gate guarantees every byte is `[0-9]`, and
5340        // the leading-zero arm above guarantees the magnitude is
5341        // either the single byte `"0"` or starts with `[1-9]`, so
5342        // the only way `u64::from_str` can fail here is overflow (the
5343        // magnitude exceeds `u64::MAX`). Surface that with an
5344        // overflow-shaped wording so the diagnostic names the offending
5345        // magnitude verbatim rather than collapsing onto the
5346        // non-canonical arm. The codec now operates on `u64` end-to-end
5347        // — every accepted magnitude is integer-exact; no f64 mantissa
5348        // drift between author-supplied magnitude and the consumer's
5349        // `Duration` value. Same shape `crate::limits::parse_duration`
5350        // (818dd38) carries on the peer `:limits :wall-clock` axis.
5351        let num: u64 = num_trim.parse::<u64>().map_err(|_| {
5352            format!("bad duration magnitude in {s:?} (digit-only magnitude overflows u64)")
5353        })?;
5354        // Route the `{"ms" | "s" | "" | "m" | "h"} → Duration`
5355        // unit-arm dispatch through the canonical
5356        // [`crate::render::duration_from_integer_magnitude_and_unit`]
5357        // primitive — the substrate-side single-owner unit-dispatch
5358        // table every typed-duration codec in caixa-core routes
5359        // through (peer: `crate::limits::parse_duration` backing
5360        // `:limits :wall-clock`). Every unit conversion is integer-
5361        // exact for an integer magnitude; overflow surfaces via the
5362        // typed `DurationUnitError::Overflow { multiplier }`
5363        // discriminant so this arm reconstructs the pre-lift
5364        // `"duration <num><unit> overflows u64 (magnitude × 60 …)"`
5365        // wording verbatim from `num` / `unit_trim` / the returned
5366        // `multiplier`, and the unknown-unit arm reconstructs the
5367        // pre-lift `"unknown duration unit \"<other>\""` wording from
5368        // the caller-scoped `unit_trim`. Load-bearing pinned by
5369        // `crate::render::tests::duration_from_integer_magnitude_and_unit_matches_pre_lift_unit_dispatch_table`.
5370        let unit_trim = unit.trim();
5371        let dur = crate::render::duration_from_integer_magnitude_and_unit(num, unit_trim).map_err(
5372            |e| match e {
5373                crate::render::DurationUnitError::Overflow { multiplier } => format!(
5374                    "duration {num}{unit_trim} overflows u64 (magnitude × {multiplier} > 2^64-1)"
5375                ),
5376                crate::render::DurationUnitError::UnknownUnit => {
5377                    format!("unknown duration unit {unit_trim:?}")
5378                }
5379            },
5380        )?;
5381        Ok(dur)
5382    }
5383
5384    /// Render a [`Duration`] in the canonical pleme-io duration string
5385    /// form (`"30s"`, `"1m"`, `"1h"`, `"500ms"`). The same form every
5386    /// caixa typed-duration slot serializes to and the same form K8s
5387    /// Gateway API HTTPRoute `timeouts` / `backendRequest` and Cilium
5388    /// EnvoyConfig per-route timeouts both expect (an integer
5389    /// followed by `s`/`m`/`h`/`ms`, no fractional values, no leading
5390    /// `+`). Lifted to `pub` so caixa-side renderers
5391    /// (`caixa-mesh::gateway_routes`'s :politicas :timeout overlay,
5392    /// the future per-:politicas `CiliumClusterwideEnvoyConfig`
5393    /// emitter, the future caixa-otel collector pipeline emitter) can
5394    /// consume the same canonical formatter without re-inlining the
5395    /// magnitude/unit decision tree (and inheriting the same drift
5396    /// footguns: a subtly different `300ms` vs `0.3s` rendering breaks
5397    /// downstream apply-time parsing in non-obvious ways).
5398    pub fn render(d: Duration) -> String {
5399        let total_ms = d.as_millis();
5400        if total_ms == 0 {
5401            return "0s".into();
5402        }
5403        if total_ms.is_multiple_of(3600 * 1000) {
5404            return format!("{}h", total_ms / (3600 * 1000));
5405        }
5406        if total_ms.is_multiple_of(60 * 1000) {
5407            return format!("{}m", total_ms / (60 * 1000));
5408        }
5409        if total_ms.is_multiple_of(1000) {
5410            return format!("{}s", total_ms / 1000);
5411        }
5412        format!("{total_ms}ms")
5413    }
5414
5415    /// True iff `d` round-trips losslessly through [`render`] + [`parse`].
5416    ///
5417    /// [`render`] truncates a `Duration` to `as_millis()` before picking the
5418    /// largest divisor unit, so any sub-millisecond residue
5419    /// (`d.subsec_nanos() % 1_000_000 != 0`) silently breaks the THEORY.md
5420    /// §V.2.7 render-determinism contract:
5421    ///
5422    ///   - `Duration::from_micros(1500)` (= `1_500_000` ns) → `as_millis() == 1`
5423    ///     → renders `"1ms"` → parses back to `Duration::from_millis(1)` =
5424    ///     `1_000_000` ns ≠ original `1_500_000` ns;
5425    ///   - `Duration::from_nanos(1)` (= 1 ns) → `as_millis() == 0` →
5426    ///     renders the literal `"0s"`, which the per-axis zero-floor gate
5427    ///     on every typed-`Duration` slot then rejects on re-validate.
5428    ///
5429    /// Lifted to a `pub` predicate next to the [`render`] / [`parse`] pair so
5430    /// the codec's round-trippable accepted set lives in exactly one place —
5431    /// every typed-`Duration` slot that routes through this shared codec
5432    /// (`SupervisorSpec::restart_window` via [`super::duration_codec`],
5433    /// [`crate::MeshPolicy::timeout`] / [`crate::CircuitBreaker::window`] via
5434    /// `supervisor::duration_codec` + [`super::duration_codec_required`]) and
5435    /// every typed-`Duration` slot whose own codec shares the same
5436    /// `as_millis()`-truncation shape ([`crate::LimitsSpec::wall_clock`] via
5437    /// [`crate::limits`]'s in-module `parse_duration` / `render_duration`
5438    /// pair) calls this predicate from its `validate()` to bracket the
5439    /// accepted set against the codec's accepted set, structurally. Drift
5440    /// between the codec's granularity and any typed slot's accepted set is
5441    /// then a single-source-of-truth edit at this predicate rather than a
5442    /// silent round-trip break the next consumer discovers at apply time.
5443    ///
5444    /// Peer of [`crate::aplicacao::POLICY_RETRIES_MAX`] /
5445    /// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] and the
5446    /// `is_dns_1123_label` / `is_canonical_rate_limit_window` predicate
5447    /// family — same "typed-slot's valid set matches its codec's accepted
5448    /// set, structurally" discipline carried at the codec layer.
5449    #[must_use]
5450    pub fn is_integer_millisecond_duration(d: Duration) -> bool {
5451        d.subsec_nanos().is_multiple_of(1_000_000)
5452    }
5453}
5454
5455/// Required-Duration variant for fields that aren't Option<Duration>.
5456pub mod duration_codec_required {
5457    use super::Duration;
5458    use serde::{Deserialize, Deserializer, Serializer};
5459
5460    pub fn serialize<S: Serializer>(v: &Duration, s: S) -> Result<S::Ok, S::Error> {
5461        s.serialize_str(&super::duration_codec::render(*v))
5462    }
5463
5464    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Duration, D::Error> {
5465        let s = String::deserialize(d)?;
5466        super::duration_codec::parse(&s).map_err(serde::de::Error::custom)
5467    }
5468}
5469
5470#[cfg(test)]
5471mod tests {
5472    use super::*;
5473
5474    fn child(name: &str, ver: &str, restart: RestartPolicy) -> ChildSpec {
5475        ChildSpec {
5476            caixa: name.into(),
5477            versao: ver.into(),
5478            restart,
5479        }
5480    }
5481
5482    #[test]
5483    fn child_spec_string_scalar_accessor_pair_is_const_fn() {
5484        // Fail-before-pass-after pin on [`ChildSpec::nome`] +
5485        // [`ChildSpec::versao_requirement`]'s `const`-eval-surface
5486        // posture. Each accessor projects the per-`:children :caixa`
5487        // / per-`:children :versao` [`String`] storage through the
5488        // `pub const fn` [`String::as_str`] (const-stable since Rust
5489        // 1.87, well within the workspace MSRV) — any future
5490        // accidental downgrade to non-`const` fails the corresponding
5491        // `<name>_via_const_fn` wrapper at caixa-core build time with
5492        // E0015 (`cannot call non-const method`), strictly stronger
5493        // than a runtime `assert!`. Sibling of the peer
5494        // per-M2/M3/universal-axis `String → &str` scalar-accessor
5495        // family pins on the sibling `const`-eval-surface passes
5496        // ([`crate::Caixa::nome`] / [`crate::Caixa::versao`] at the
5497        // top-level manifest, [`crate::CaixaVersion::as_str`] at the
5498        // typed-newtype wrapper, [`crate::aplicacao::Membro::nome`] /
5499        // [`crate::aplicacao::Membro::versao_requirement`] at the M3
5500        // membership axis, [`crate::aplicacao::Entrada::hostname`] /
5501        // [`crate::aplicacao::Entrada::destination`] at the M3
5502        // ingress axis,
5503        // [`crate::upgrade::UpgradeFromEntry::prior_versao`] at the
5504        // M2 upgrade axis, [`crate::dep::Dep::nome`] /
5505        // [`crate::dep::Dep::versao_requirement`] at the dep-graph
5506        // axis, and the per-`:contratos`
5507        // [`crate::aplicacao::WitContract::source`] /
5508        // [`crate::aplicacao::WitContract::destination`] /
5509        // [`crate::aplicacao::WitContract::world_ref`] trio the
5510        // sibling pin at 279823b already anchors).
5511        const fn nome_via_const_fn(c: &ChildSpec) -> &str {
5512            c.nome()
5513        }
5514        const fn versao_via_const_fn(c: &ChildSpec) -> &str {
5515            c.versao_requirement()
5516        }
5517        for (caixa, versao) in [
5518            ("worker-a", "^0.1"),
5519            ("worker-b", "~0.2.3"),
5520            ("collector", "*"),
5521        ] {
5522            let c = child(caixa, versao, RestartPolicy::Permanent);
5523            assert_eq!(nome_via_const_fn(&c), c.nome());
5524            assert_eq!(versao_via_const_fn(&c), c.versao_requirement());
5525            assert_eq!(c.nome(), caixa);
5526            assert_eq!(c.versao_requirement(), versao);
5527        }
5528    }
5529
5530    #[test]
5531    fn supervisor_children_slice_return_accessor_is_const_fn() {
5532        // Fail-before-pass-after pin on [`SupervisorSpec::children`]'s
5533        // `const`-eval-surface posture. The accessor destructures the
5534        // per-`:children` `Vec<ChildSpec>` storage through the
5535        // `pub const fn` [`Vec::as_slice`] (const-stable since Rust
5536        // 1.66, well within the workspace MSRV) — any future
5537        // accidental downgrade to non-`const` fails
5538        // `children_via_const_fn` at caixa-core build time with E0015
5539        // (`cannot call non-const method`), strictly stronger than a
5540        // runtime `assert!`. Sibling of the peer per-M3-mesh-slot
5541        // `Vec → &[T]` slice-return accessor family pin
5542        // [`crate::aplicacao::tests::m3_reference_return_accessor_family_is_const_fn`]
5543        // on the M3 mesh-slot per-`:clusters` / per-`:paths` /
5544        // per-`:membros` / per-`:contratos` slice-return axes, and of
5545        // the peer M2 upgrade-appup axis pin
5546        // [`crate::upgrade::tests::upgrade_from_entry_instructions_slice_return_accessor_is_const_fn`]
5547        // on the per-`:upgrade-from :instructions` slice-return axis.
5548        const fn children_via_const_fn(s: &SupervisorSpec) -> &[ChildSpec] {
5549            s.children()
5550        }
5551        // Sweep both the empty-children (leaf-supervisor with no
5552        // static children — the `SimpleOneForOne` dynamic-child
5553        // arm's canonical shape) and the populated-children
5554        // (`OneForOne` / `OneForAll` / `RestForOne` static-child
5555        // arm's canonical shape) axes so the accessor carries a
5556        // const-dispatch pin on both arms.
5557        let s_empty = SupervisorSpec {
5558            estrategia: RestartStrategy::SimpleOneForOne,
5559            max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
5560            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
5561            children: vec![],
5562        };
5563        assert!(children_via_const_fn(&s_empty).is_empty());
5564        assert_eq!(children_via_const_fn(&s_empty), s_empty.children());
5565        let s_full = SupervisorSpec {
5566            estrategia: RestartStrategy::OneForOne,
5567            max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
5568            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
5569            children: vec![
5570                child("worker-a", "^0.1", RestartPolicy::Permanent),
5571                child("worker-b", "~0.2.3", RestartPolicy::Transient),
5572                child("collector", "*", RestartPolicy::Temporary),
5573            ],
5574        };
5575        assert_eq!(children_via_const_fn(&s_full).len(), 3);
5576        assert_eq!(children_via_const_fn(&s_full), s_full.children());
5577    }
5578
5579    #[test]
5580    fn default_has_one_for_one_and_5_restarts_in_60s() {
5581        let s = SupervisorSpec::default();
5582        assert_eq!(s.estrategia, RestartStrategy::OneForOne);
5583        assert_eq!(s.max_restarts, 5);
5584        assert_eq!(s.restart_window, Some(Duration::from_secs(60)));
5585        assert!(s.children.is_empty());
5586    }
5587
5588    #[test]
5589    fn validate_one_for_one_requires_children() {
5590        // Explicit-empty via struct-update rather than `let mut s = default(); s.children = vec![];`
5591        // — the peer `validate_simple_one_for_one_forbids_static_children` below already uses
5592        // struct-update to name the axis under test at construction, and this shape matches
5593        // it. Also keeps the "empty children is the axis under test" intent visible at the
5594        // binding site rather than one line down, and side-steps `clippy::field_reassign_with_default`.
5595        let mut s = SupervisorSpec {
5596            children: vec![],
5597            ..SupervisorSpec::default()
5598        };
5599        assert!(matches!(
5600            s.validate().unwrap_err(),
5601            SupervisorError::NoChildren { .. }
5602        ));
5603        s.children = vec![child("worker", "^0.1", RestartPolicy::Permanent)];
5604        s.validate().unwrap();
5605    }
5606
5607    #[test]
5608    fn validate_simple_one_for_one_forbids_static_children() {
5609        let mut s = SupervisorSpec {
5610            estrategia: RestartStrategy::SimpleOneForOne,
5611            ..SupervisorSpec::default()
5612        };
5613        s.children
5614            .push(child("w", "^0.1", RestartPolicy::Permanent));
5615        assert_eq!(
5616            s.validate().unwrap_err(),
5617            SupervisorError::SimpleOneForOneWithStaticChildren
5618        );
5619        s.children.clear();
5620        s.validate().unwrap();
5621    }
5622
5623    #[test]
5624    fn validate_rejects_zero_max_restarts() {
5625        let s = SupervisorSpec {
5626            max_restarts: 0,
5627            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5628            ..SupervisorSpec::default()
5629        };
5630        assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
5631    }
5632
5633    // ── upper-cap: SUPERVISOR_MAX_RESTARTS_MAX brackets the typed slot ─────
5634    //
5635    // The cap arm lifts the `:politicas :circuit-breaker :max-failures` /
5636    // `POLICY_BREAKER_MAX_FAILURES_MAX` (2b51ace) discipline onto the peer
5637    // `:supervisor :max-restarts` axis — both fields are "trip the
5638    // next-higher protection layer after N events in a rolling window"
5639    // counters with identical degenerate-at-the-high-end shape, so the
5640    // typed-slot's accepted set lies in `1..=1000` on the supervisor side
5641    // exactly as it lies in `1..=1000` on the breaker side.
5642
5643    #[test]
5644    fn validate_rejects_max_restarts_above_cap() {
5645        // The fail-before-pass-after pin: `SUPERVISOR_MAX_RESTARTS_MAX +
5646        // 1` is structurally one past the cap and silently passed
5647        // validate on every pre-gate codebase because the typed slot's
5648        // only check was the zero-floor arm. The no-op-supervisor vector
5649        // only surfaced at the runtime substrate (Erlang/OTP
5650        // MaxIntensity/Period ratio, the future wasm-operator's
5651        // per-supervisor restart-intensity counter) far from the source
5652        // caixa.lisp with no field naming the offending supervisor.
5653        let s = SupervisorSpec {
5654            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5655            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5656            ..SupervisorSpec::default()
5657        };
5658        assert_eq!(
5659            s.validate().unwrap_err(),
5660            SupervisorError::MaxRestartsExceedsCap {
5661                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5662            }
5663        );
5664    }
5665
5666    #[test]
5667    fn validate_rejects_max_restarts_far_above_cap() {
5668        // The `u32::MAX` worst case — the four-billion-restart
5669        // threshold a typo (`:max-restarts 4294967295`) or a
5670        // struct-literal copy-paste lands in the slot. Pin the cap
5671        // arm's coverage explicitly across the full `u32` overflow so
5672        // a future relaxation that drops the upper bound surfaces
5673        // here. Same shape every other typed-cap arm on this surface
5674        // carries (POLICY_BREAKER_MAX_FAILURES_MAX,
5675        // POLICY_RETRIES_MAX, POLICY_RATE_LIMIT_MAX).
5676        let s = SupervisorSpec {
5677            max_restarts: u32::MAX,
5678            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5679            ..SupervisorSpec::default()
5680        };
5681        assert_eq!(
5682            s.validate().unwrap_err(),
5683            SupervisorError::MaxRestartsExceedsCap {
5684                max_restarts: u32::MAX,
5685            }
5686        );
5687    }
5688
5689    #[test]
5690    fn validate_accepts_max_restarts_at_cap() {
5691        // The boundary value — exactly SUPERVISOR_MAX_RESTARTS_MAX —
5692        // must validate. The cap is inclusive on the top edge,
5693        // matching the POLICY_BREAKER_MAX_FAILURES_MAX /
5694        // POLICY_RETRIES_MAX / LIMITS_MEMORY_WASM32_MAX_BYTES
5695        // discipline on the sibling capped axes. Pin the boundary
5696        // explicitly so a future off-by-one tightening
5697        // (`>= SUPERVISOR_MAX_RESTARTS_MAX` instead of `>`) surfaces
5698        // here as a test failure rather than a silent contract
5699        // narrowing.
5700        let s = SupervisorSpec {
5701            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX,
5702            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5703            ..SupervisorSpec::default()
5704        };
5705        s.validate()
5706            .expect("max_restarts == SUPERVISOR_MAX_RESTARTS_MAX must validate");
5707    }
5708
5709    #[test]
5710    fn validate_accepts_max_restarts_typical_values() {
5711        // The documented production-playbook band positive-control
5712        // sweep — every value Erlang/OTP / Elixir / Riak Core /
5713        // RabbitMQ recommend (1..=100) must pass, plus a sweep
5714        // through the hyperscale band (200, 500, 1000) the cap
5715        // accepts. Pin the inclusive validated set explicitly so a
5716        // future tightening of the ceiling surfaces here.
5717        for n in [1u32, 3, 5, 10, 20, 50, 100, 200, 500, 1000] {
5718            let s = SupervisorSpec {
5719                max_restarts: n,
5720                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5721                ..SupervisorSpec::default()
5722            };
5723            s.validate()
5724                .unwrap_or_else(|e| panic!("max_restarts={n} must validate; got {e:?}"));
5725        }
5726    }
5727
5728    #[test]
5729    fn zero_max_restarts_takes_precedence_over_cap() {
5730        // The cross-arm ordering pin: `0` is structurally outside
5731        // both `1..` (zero-floor) and `..=SUPERVISOR_MAX_RESTARTS_MAX`
5732        // (cap), but the zero-floor diagnostic is the more
5733        // self-locating one (it directly names the counter-axis
5734        // remediation), so the validate gate must fire on zero first.
5735        // Same shape every other zero-then-shape ordering on this
5736        // surface uses (PolicyRetriesZero then
5737        // PolicyRetriesExceedsCap; PolicyBreakerZeroFailures then
5738        // PolicyBreakerMaxFailuresExceedsCap).
5739        let s = SupervisorSpec {
5740            max_restarts: 0,
5741            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5742            ..SupervisorSpec::default()
5743        };
5744        assert_eq!(
5745            s.validate().unwrap_err(),
5746            SupervisorError::ZeroMaxRestarts,
5747            "max_restarts == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
5748        );
5749    }
5750
5751    #[test]
5752    fn max_restarts_cap_takes_precedence_over_restart_window_gates() {
5753        // The cross-arm ordering pin between the cap and the sibling
5754        // `:restart-window` gates (zero-window, canonical-window). A
5755        // supervisor carrying both an over-cap `max_restarts` AND a
5756        // structurally invalid window (zero, sub-ms) must surface the
5757        // cap diagnostic first — the cap arm is wired immediately
5758        // after the zero-restart arm and strictly before the window
5759        // arms, so the offending value the diagnostic names matches
5760        // the order the author would discover the gates by reading
5761        // top-to-bottom through `SupervisorSpec::validate`. Pin the
5762        // order so a future refactor that reorders the arms surfaces
5763        // here as a test failure rather than a silent diagnostic
5764        // regression. Peer of
5765        // `circuit_breaker_max_failures_cap_takes_precedence_over_window_gates`
5766        // on the sibling `:politicas :circuit-breaker` slot.
5767        let s = SupervisorSpec {
5768            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5769            restart_window: Some(Duration::ZERO),
5770            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5771            ..SupervisorSpec::default()
5772        };
5773        assert_eq!(
5774            s.validate().unwrap_err(),
5775            SupervisorError::MaxRestartsExceedsCap {
5776                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5777            },
5778            "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
5779        );
5780    }
5781
5782    #[test]
5783    fn max_restarts_cap_diagnostic_carries_offending_value() {
5784        // The diagnostic-shape pin: the offending `u32` is carried
5785        // verbatim into the `SupervisorError::MaxRestartsExceedsCap`
5786        // variant so the surfaced error message names the value the
5787        // author wrote (`":supervisor :max-restarts (50000) exceeds the
5788        // supervisor-policy ceiling …"`), not just the cap. Same
5789        // self-locating diagnostic shape every other typed-cap arm on
5790        // this surface carries
5791        // (`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap` carries
5792        // the offending failure count verbatim,
5793        // `AplicacaoError::PolicyRetriesExceedsCap` carries the offending
5794        // retries count verbatim).
5795        let s = SupervisorSpec {
5796            max_restarts: 50_000,
5797            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5798            ..SupervisorSpec::default()
5799        };
5800        let err = s.validate().unwrap_err();
5801        assert!(
5802            matches!(
5803                err,
5804                SupervisorError::MaxRestartsExceedsCap {
5805                    max_restarts: 50_000
5806                }
5807            ),
5808            "got {err:?}"
5809        );
5810        let msg = err.to_string();
5811        assert!(
5812            msg.contains("50000"),
5813            ":supervisor :max-restarts cap diagnostic must carry the offending value verbatim (got: {msg})"
5814        );
5815    }
5816
5817    #[test]
5818    fn supervisor_max_restarts_default_pins_otp_canonical_value() {
5819        // Pin [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] at `5` — the
5820        // Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
5821        // half of Learn You Some Erlang's worker-supervisor default,
5822        // sibling of the `60s` `Period` half that the paired
5823        // [`Default for SupervisorSpec`] impl already pins on the
5824        // sibling `restart_window` axis. Pinning the literal here
5825        // surfaces a future rebrand (a tightening to Elixir's `3`,
5826        // a widening to a per-cluster overlay the operator pins
5827        // through a future `:max-restarts-overrides` slot) as a
5828        // deliberate test edit, not a silent contract migration.
5829        // Peer of the sibling
5830        // [`supervisor_max_restarts_cap_pins_canonical_value`]
5831        // upper-bracket pin on the same axis.
5832        assert_eq!(SUPERVISOR_MAX_RESTARTS_DEFAULT, 5);
5833    }
5834
5835    #[test]
5836    fn default_max_restarts_helper_routes_through_lifted_default() {
5837        // Composition pin: the private `default_max_restarts()`
5838        // serde-`#[serde(default = "…")]` helper on
5839        // [`SupervisorSpec::max_restarts`] must route through the
5840        // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
5841        // typed `pub const` rather than a raw `5` literal. Prior to
5842        // the lift the helper carried an inline `5` with no compile-
5843        // time link back to the shared default, so the wire-format
5844        // author-omitted arm and the caixa-core
5845        // [`crate::manifest::Caixa::supervisor_view`] fold's `unwrap_or(5)`
5846        // arm could silently split on any future default rebrand.
5847        // Byte-parity against the lifted constant closes the split.
5848        assert_eq!(default_max_restarts(), SUPERVISOR_MAX_RESTARTS_DEFAULT);
5849    }
5850
5851    #[test]
5852    fn supervisor_spec_default_max_restarts_routes_through_lifted_default() {
5853        // Composition pin: the [`Default for SupervisorSpec`] impl's
5854        // struct-literal `max_restarts` field must route through the
5855        // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
5856        // typed `pub const` (via the private helper this test's
5857        // sibling `default_max_restarts_helper_routes_through_lifted_default`
5858        // already pins onto the constant). Structurally: every
5859        // `SupervisorSpec::default()` call must yield a
5860        // `max_restarts` field byte-equal to the lifted constant
5861        // (the two paired defaults — the serde-side wire-format arm
5862        // and the struct-literal default arm — cannot silently split
5863        // on any future default rebrand). Peer of the sibling
5864        // `default_has_one_for_one_and_5_restarts_in_60s` shape pin
5865        // — this pin closes the byte-parity arm on the two paired
5866        // altitude entry points onto the shared substrate constant.
5867        assert_eq!(
5868            SupervisorSpec::default().max_restarts(),
5869            SUPERVISOR_MAX_RESTARTS_DEFAULT,
5870        );
5871    }
5872
5873    #[test]
5874    fn supervisor_restart_window_default_pins_otp_canonical_value() {
5875        // Pin [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] at `60s` — the
5876        // Erlang/OTP-canonical `{intensity, 5, 60}` `Period` half of
5877        // Learn You Some Erlang's worker-supervisor default, paired
5878        // with the sibling `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5`
5879        // `MaxIntensity` half this constant is the sliding-window
5880        // denominator of on the same `MaxIntensity / Period`
5881        // restart-intensity ratio. Pinning the literal here surfaces a
5882        // future coherent rebrand of the paired default (Elixir's
5883        // `{max_restarts: 3, max_seconds: 5}`, a per-cluster overlay
5884        // the operator pins through a future
5885        // `:restart-window-overrides` slot) as a deliberate test edit,
5886        // not a silent contract migration. Peer of the sibling
5887        // [`supervisor_max_restarts_default_pins_otp_canonical_value`]
5888        // paired-half pin on the same OTP-canonical default and the
5889        // [`supervisor_restart_window_cap_pins_canonical_value`]
5890        // upper-bracket pin on the same axis.
5891        assert_eq!(SUPERVISOR_RESTART_WINDOW_DEFAULT, Duration::from_secs(60),);
5892    }
5893
5894    #[test]
5895    fn supervisor_spec_default_restart_window_routes_through_lifted_default() {
5896        // Composition pin: the [`Default for SupervisorSpec`] impl's
5897        // struct-literal `restart_window` field must route through the
5898        // substrate-canonical [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
5899        // typed `pub const` rather than a raw
5900        // `Duration::from_secs(60)` literal. Prior to this lift the
5901        // paired `{intensity, 5, 60}` OTP-canonical default was split
5902        // across two altitudes with no compile-time link between the
5903        // halves — the `MaxIntensity` half rode through the lifted
5904        // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant while the
5905        // `Period` half rode as an open-coded literal at the
5906        // composition site, so a future coherent rebrand of the paired
5907        // canonical would have had to migrate one half through the
5908        // constant and the other through a raw literal in lockstep.
5909        // Byte-parity against the lifted constant on the `Period` half
5910        // closes the split — the paired OTP-canonical default now
5911        // migrates as one unit on any future axis change. Peer of the
5912        // sibling
5913        // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
5914        // byte-parity pin on the paired `MaxIntensity` half.
5915        assert_eq!(
5916            SupervisorSpec::default().restart_window(),
5917            Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
5918        );
5919    }
5920
5921    #[test]
5922    fn supervisor_estrategia_default_pins_otp_canonical_value() {
5923        // Pin [`SUPERVISOR_ESTRATEGIA_DEFAULT`] at [`RestartStrategy::OneForOne`]
5924        // — the Erlang/OTP-canonical `one_for_one` half of Learn You Some
5925        // Erlang's `{one_for_one, intensity, 5, 60}` worker-supervisor
5926        // canonical default, paired with the sibling
5927        // `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5` `MaxIntensity` half and the
5928        // sibling `SUPERVISOR_RESTART_WINDOW_DEFAULT` `60s` `Period` half
5929        // this constant is the strategy discriminator of on the same
5930        // OTP-canonical worker-supervisor default. Pinning the arm here
5931        // surfaces a future coherent rebrand of the paired triple (Elixir's
5932        // `{:one_for_one, max_restarts: 3, max_seconds: 5}` on the sibling
5933        // intensity/period axes leaving this strategy arm untouched, an OTP
5934        // `rest_for_one` widening once the substrate discovers startup-
5935        // order-coupled child cohorts as the more common worker-supervisor
5936        // shape, a per-cluster overlay the operator pins through a future
5937        // `:estrategia-overrides` slot the MESH-COMPOSITION §III.2
5938        // supervision-canary roadmap acknowledges) as a deliberate test
5939        // edit, not a silent contract migration. Peer of the sibling
5940        // [`supervisor_max_restarts_default_pins_otp_canonical_value`] +
5941        // [`supervisor_restart_window_default_pins_otp_canonical_value`]
5942        // paired-half pins on the same OTP-canonical default.
5943        assert_eq!(SUPERVISOR_ESTRATEGIA_DEFAULT, RestartStrategy::OneForOne);
5944    }
5945
5946    #[test]
5947    fn restart_strategy_default_routes_through_lifted_default() {
5948        // Composition pin: the [`Default for RestartStrategy`] impl's
5949        // return arm must route through the substrate-canonical
5950        // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
5951        // a raw `Self::OneForOne` arm. Prior to the lift the impl carried
5952        // an inline `Self::OneForOne` with no compile-time link back to
5953        // the shared OTP-canonical `one_for_one` strategy the paired
5954        // [`Default for SupervisorSpec`] impl's struct-literal `estrategia`
5955        // field and the [`crate::manifest::Caixa::supervisor_view`] fold's
5956        // `.unwrap_or_default()` (now
5957        // `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)`) arm both key off —
5958        // so a future rebrand of the OTP-canonical strategy default (an
5959        // OTP `rest_for_one` widening once the substrate discovers
5960        // startup-order-coupled child cohorts as the more common worker-
5961        // supervisor shape, a per-cluster overlay the operator pins
5962        // through a future `:estrategia-overrides` slot) would have had to
5963        // be threaded through the `Default` impl and the two peer routes
5964        // in lockstep or the three consumers would silently split. Byte-
5965        // parity against the lifted constant closes the split. Peer of
5966        // the sibling
5967        // [`default_max_restarts_helper_routes_through_lifted_default`] +
5968        // [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
5969        // composition pins on the paired `MaxIntensity` + `Period` halves.
5970        assert_eq!(RestartStrategy::default(), SUPERVISOR_ESTRATEGIA_DEFAULT,);
5971    }
5972
5973    #[test]
5974    fn supervisor_spec_default_estrategia_routes_through_lifted_default() {
5975        // Composition pin: the [`Default for SupervisorSpec`] impl's
5976        // struct-literal `estrategia` field must route through the
5977        // substrate-canonical [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed
5978        // `pub const` (either directly, or via the
5979        // [`RestartStrategy::default`] impl that the sibling
5980        // `restart_strategy_default_routes_through_lifted_default` pin
5981        // already routes onto the constant). Structurally: every
5982        // `SupervisorSpec::default()` call must yield an `estrategia`
5983        // field byte-equal to the lifted constant (the three paired
5984        // defaults — the [`Default for RestartStrategy`] impl arm, the
5985        // struct-literal default arm here, and the
5986        // [`crate::manifest::Caixa::supervisor_view`] fold arm — cannot
5987        // silently split on any future default rebrand). Peer of the
5988        // sibling
5989        // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
5990        // + [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
5991        // byte-parity pins on the paired `MaxIntensity` + `Period` halves
5992        // of the same `SupervisorSpec::default()` composed altitude.
5993        assert_eq!(
5994            SupervisorSpec::default().estrategia(),
5995            SUPERVISOR_ESTRATEGIA_DEFAULT,
5996        );
5997    }
5998
5999    #[test]
6000    fn supervisor_spec_default_routes_through_otp_canonical_ctor() {
6001        // Composition pin: the [`Default for SupervisorSpec`] impl must
6002        // route through the substrate-canonical
6003        // [`SupervisorSpec::otp_canonical`] `pub const fn` constructor
6004        // rather than a re-hand-authored struct-literal cascade. Sharpens
6005        // the sibling per-arm
6006        // `supervisor_spec_default_*_routes_through_lifted_default` pins
6007        // from a per-field lift into a whole-struct one-source-of-truth
6008        // pin — the derived-until-now [`Default::default`] and the
6009        // [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
6010        // construction, not by coincidence.
6011        //
6012        // A future extension of the OTP-canonical baseline (a fifth
6013        // `restart_intensity` field the Erlang/OTP `#supervisor` record
6014        // grows, a per-child-cohort split of the `restart_window` /
6015        // `max_restarts` pair, an M4 `mesh.pleme.io/v1alpha1/Supervisor`
6016        // CR materializer's admission-time overlay pass) reaches both
6017        // paths through exactly one edit on
6018        // [`SupervisorSpec::otp_canonical`] — the derived path could
6019        // silently disagree with the constructor's shape on any new
6020        // field whose [`Default::default`] resolves to a different arm
6021        // than the OTP-canonical baseline the constructor names, while
6022        // this delegated impl reaches the constructor directly and
6023        // picks up every future extension by construction.
6024        //
6025        // Fourth peer on the M2 / M3 typed-slot-spec
6026        // [`Default`]-through-const-ctor fold family — sibling of the
6027        // [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
6028        // (abd52c2), [`crate::aplicacao::MeshPolicy`]
6029        // [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`]
6030        // (91641a4), and [`crate::BehaviorSpec`]
6031        // [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c)
6032        // per-`Option`-only-typed-slot folds — extended here onto the
6033        // M2 supervisor-slot [`SupervisorSpec`] whose canonical baseline
6034        // is not "everything `None`" but the Erlang/OTP-canonical
6035        // `{one_for_one, 5, 60}` worker-supervisor triple.
6036        assert_eq!(SupervisorSpec::default(), SupervisorSpec::otp_canonical());
6037    }
6038
6039    #[test]
6040    fn supervisor_spec_otp_canonical_byte_equals_default() {
6041        // Value pin: [`SupervisorSpec::otp_canonical`] must byte-equal
6042        // the hand-authored `{one_for_one, 5, 60, []}` OTP-canonical
6043        // baseline the sibling `default_has_one_for_one_and_5_restarts_in_60s`
6044        // pin already asserts against the [`Default::default`] path.
6045        // Sharpens the pair-invariant into a per-constructor pin so a
6046        // future extension of [`SupervisorSpec`] with a fifth field
6047        // whose OTP-canonical shape is non-`Default::default`-equivalent
6048        // trips at caixa-core test time rather than at a downstream
6049        // consumer that composed [`SupervisorSpec::otp_canonical`] with
6050        // [`SupervisorSpec::validate`] as its "canonical baseline
6051        // seed".
6052        let canonical = SupervisorSpec::otp_canonical();
6053        assert_eq!(canonical.estrategia, RestartStrategy::OneForOne);
6054        assert_eq!(canonical.max_restarts, 5);
6055        assert_eq!(canonical.restart_window, Some(Duration::from_secs(60)));
6056        assert!(canonical.children.is_empty());
6057    }
6058
6059    #[test]
6060    fn supervisor_spec_otp_canonical_is_usable_in_const_context() {
6061        // Const-context pin: [`SupervisorSpec::otp_canonical`] must
6062        // remain callable from a `const`-bound position so downstream
6063        // `const`-context callers wanting a canonical OTP-baseline seed
6064        // can construct one at compile time without runtime dispatch on
6065        // the derived [`Default::default`]. Peer of the sibling
6066        // `pub const fn` [`crate::LimitsSpec::empty`] /
6067        // [`crate::aplicacao::MeshPolicy::empty`] /
6068        // [`crate::BehaviorSpec::empty`] constructors on the sibling
6069        // typed-slot-spec `pub const fn` axis. If a future edit breaks
6070        // the `const`-eligibility of [`SupervisorSpec::otp_canonical`]
6071        // (a non-`const` field-default helper, a non-`const`-stable
6072        // container type promotion), this evaluation fails at
6073        // build time on this file rather than at a downstream
6074        // `const`-context call site.
6075        const CANONICAL: SupervisorSpec = SupervisorSpec::otp_canonical();
6076        assert_eq!(CANONICAL.estrategia, SUPERVISOR_ESTRATEGIA_DEFAULT);
6077        assert_eq!(CANONICAL.max_restarts, SUPERVISOR_MAX_RESTARTS_DEFAULT);
6078        assert_eq!(
6079            CANONICAL.restart_window,
6080            Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
6081        );
6082        assert!(CANONICAL.children.is_empty());
6083    }
6084
6085    #[test]
6086    fn supervisor_child_restart_default_pins_otp_canonical_value() {
6087        // Pin [`SUPERVISOR_CHILD_RESTART_DEFAULT`] at
6088        // [`RestartPolicy::Permanent`] — Erlang/OTP's `permanent`
6089        // worker-child restart type (`{ChildId, StartFunc, permanent, …}`
6090        // in a `supervisor`'s `init/1` child-spec tuple), the per-child
6091        // half of the same OTP-shape supervisor-tree default set whose
6092        // per-`:supervisor` halves the sibling
6093        // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
6094        // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] /
6095        // [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] constants pin. Pinning the
6096        // arm here surfaces a future rebrand of the per-child default (an
6097        // OTP-`transient` widening once the substrate discovers clean-
6098        // completion-aware children as the more common child shape, a
6099        // per-cluster overlay the operator pins through a future
6100        // `:restart-overrides` slot the MESH-COMPOSITION §III.2
6101        // supervision-canary roadmap acknowledges) as a deliberate test
6102        // edit, not a silent contract migration. Peer of the sibling
6103        // [`supervisor_estrategia_default_pins_otp_canonical_value`] /
6104        // [`supervisor_max_restarts_default_pins_otp_canonical_value`] /
6105        // [`supervisor_restart_window_default_pins_otp_canonical_value`]
6106        // value pins on the per-`:supervisor` halves.
6107        assert_eq!(SUPERVISOR_CHILD_RESTART_DEFAULT, RestartPolicy::Permanent);
6108    }
6109
6110    #[test]
6111    fn restart_policy_default_routes_through_lifted_default() {
6112        // Composition pin: the [`Default for RestartPolicy`] impl's return
6113        // arm must route through the substrate-canonical
6114        // [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const` rather
6115        // than a raw `Self::Permanent` arm. Prior to the lift the impl
6116        // carried an inline `Self::Permanent` with no compile-time link
6117        // back to the OTP-shape supervisor-tree default set whose three
6118        // per-`:supervisor` halves already rode through lifted constants
6119        // — so a future coherent rebrand of the set would have had to
6120        // migrate three halves through typed constants and this fourth
6121        // through a raw enum arm in lockstep or the supervisor-level and
6122        // child-level defaults would silently drift apart. Byte-parity
6123        // against the lifted constant closes the split. Peer of the
6124        // sibling
6125        // [`restart_strategy_default_routes_through_lifted_default`]
6126        // composition pin on the per-`:supervisor` `:estrategia` axis.
6127        assert_eq!(RestartPolicy::default(), SUPERVISOR_CHILD_RESTART_DEFAULT);
6128    }
6129
6130    #[test]
6131    fn child_spec_serde_default_restart_routes_through_lifted_default() {
6132        // Composition pin: the serde-side `#[serde(default)]` on
6133        // [`ChildSpec::restart`] — the wire-format author-omitted
6134        // `:children :restart` arm — must resolve onto the substrate-
6135        // canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const`
6136        // (via the [`Default for RestartPolicy`] impl the sibling
6137        // `restart_policy_default_routes_through_lifted_default` pin
6138        // already routes onto the constant). Structurally: a `ChildSpec`
6139        // deserialized from a payload that omits the `restart` key must
6140        // yield a `restart` field byte-equal to the lifted constant, so
6141        // the wire-format author-omitted arm and the
6142        // [`RestartPolicy::default`] impl arm cannot silently split on any
6143        // future default rebrand. Peer of the sibling
6144        // [`supervisor_spec_default_estrategia_routes_through_lifted_default`]
6145        // / [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
6146        // / [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
6147        // byte-parity pins on the per-`:supervisor` halves of the same
6148        // author-omitted-slot resolution surface.
6149        let omitted: ChildSpec = serde_json::from_str(r#"{"caixa":"worker","versao":"^0.1"}"#)
6150            .expect("ChildSpec must deserialize with the restart key omitted");
6151        assert_eq!(
6152            omitted.restart(),
6153            SUPERVISOR_CHILD_RESTART_DEFAULT,
6154            "an author-omitted :children :restart slot must degrade onto \
6155             the SUPERVISOR_CHILD_RESTART_DEFAULT typed pub const (got \
6156             {:?}, expected {:?})",
6157            omitted.restart(),
6158            SUPERVISOR_CHILD_RESTART_DEFAULT,
6159        );
6160    }
6161
6162    #[test]
6163    fn supervisor_max_restarts_cap_pins_canonical_value() {
6164        // The SUPERVISOR_MAX_RESTARTS_MAX constant pins the value at
6165        // 1000 — the same ceiling the peer
6166        // POLICY_BREAKER_MAX_FAILURES_MAX cap carries on the
6167        // `:politicas :circuit-breaker :max-failures` axis (both are
6168        // "trip the next-higher protection layer after N events in a
6169        // rolling window" counters with identical
6170        // degenerate-at-the-high-end shape; uniform top edge so the
6171        // M4 CR materializers and the wasm-operator reconciler reach
6172        // for either field knowing the value is in `1..=1000`). Two
6173        // orders of magnitude above every documented Erlang/OTP /
6174        // Elixir / Riak Core / RabbitMQ production-playbook
6175        // recommendation band and below the clearly-pathological
6176        // "effectively no escalation" floor (10_000, 100_000,
6177        // u32::MAX). Pinning the literal value here surfaces a future
6178        // drift (a relaxation to 10_000, a tightening to 100) as a
6179        // deliberate test edit, not a silent contract narrowing.
6180        assert_eq!(SUPERVISOR_MAX_RESTARTS_MAX, 1000);
6181    }
6182
6183    #[test]
6184    fn validate_rejects_empty_child_name() {
6185        let s = SupervisorSpec {
6186            children: vec![child("", "^0.1", RestartPolicy::Permanent)],
6187            ..SupervisorSpec::default()
6188        };
6189        assert_eq!(s.validate().unwrap_err(), SupervisorError::EmptyChildName);
6190    }
6191
6192    #[test]
6193    fn validate_rejects_empty_child_version() {
6194        let s = SupervisorSpec {
6195            children: vec![child("w", "", RestartPolicy::Permanent)],
6196            ..SupervisorSpec::default()
6197        };
6198        assert!(matches!(
6199            s.validate().unwrap_err(),
6200            SupervisorError::EmptyChildVersion { .. }
6201        ));
6202    }
6203
6204    // ── value-shape: parse-as-VersionReq on :children :versao ─────────────
6205
6206    #[test]
6207    fn validate_rejects_invalid_child_versao_requirement() {
6208        // The fail-before-pass-after pin: a non-empty but malformed
6209        // semver requirement (`"^bad-version"`) silently passed
6210        // `validate()` on every pre-gate codebase because the prior
6211        // shape only refused the empty string. The parse failure
6212        // surfaced far downstream at lacre-resolve time with a
6213        // `semver::Error` that didn't name which `:children` entry
6214        // carried the typo. The new gate moves the check to caixa-build
6215        // time at the source caixa.lisp — the third `:versao` typed
6216        // axis (`:children`) joins `:deps` and `:membros` (9888b13) at
6217        // structural parity.
6218        let s = SupervisorSpec {
6219            children: vec![
6220                child("worker", "^0.1", RestartPolicy::Permanent),
6221                child("cache", "^bad-version", RestartPolicy::Transient),
6222            ],
6223            ..SupervisorSpec::default()
6224        };
6225        let err = s.validate().unwrap_err();
6226        assert!(
6227            matches!(
6228                err,
6229                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
6230                    if caixa == "cache" && versao == "^bad-version"
6231            ),
6232            "got {err:?}"
6233        );
6234    }
6235
6236    #[test]
6237    fn validate_rejects_child_versao_with_double_caret_typo() {
6238        // `"^^0.1"` is the canonical doubled-caret typo — looks
6239        // Cargo-shaped on first glance but fails the parser because
6240        // semver doesn't accept stacked operators. Pin this
6241        // adjacent-shape footgun explicitly so a future relaxation that
6242        // accepts "looks-canonical-but-isn't" forms surfaces here.
6243        let s = SupervisorSpec {
6244            children: vec![child("worker", "^^0.1", RestartPolicy::Permanent)],
6245            ..SupervisorSpec::default()
6246        };
6247        let err = s.validate().unwrap_err();
6248        assert!(
6249            matches!(
6250                err,
6251                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
6252                    if caixa == "worker" && versao == "^^0.1"
6253            ),
6254            "got {err:?}"
6255        );
6256    }
6257
6258    #[test]
6259    fn validate_rejects_child_versao_with_v_prefixed_tag() {
6260        // `"v0.1"` is the canonical "git-tag-shape leaking into the
6261        // semver requirement slot" typo — an author copies the
6262        // publish-side git-tag string verbatim into `:versao`, but
6263        // Cargo's semver parser rejects the leading `v`. Same
6264        // adjacent-shape footgun pinned for `:membros :versao`
6265        // (9888b13).
6266        let s = SupervisorSpec {
6267            children: vec![child("worker", "v0.1", RestartPolicy::Permanent)],
6268            ..SupervisorSpec::default()
6269        };
6270        let err = s.validate().unwrap_err();
6271        assert!(
6272            matches!(
6273                err,
6274                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
6275                    if caixa == "worker" && versao == "v0.1"
6276            ),
6277            "got {err:?}"
6278        );
6279    }
6280
6281    #[test]
6282    fn validate_accepts_canonical_child_versao_forms() {
6283        // The Cargo-shaped requirement forms `:deps :versao` and
6284        // `:membros :versao` already accept via
6285        // `crate::parse_requirement` must pass the children gate
6286        // without re-validating at the resolver layer. Pin every leg so
6287        // a future tightening of the canonical set surfaces here as a
6288        // test failure.
6289        for form in [
6290            "^0.1",      // caret — minor-range pin (the most common shape)
6291            "~0.1.2",    // tilde — patch-range pin
6292            "0.1.0",     // exact — single-version pin
6293            "*",         // wildcard — any version (semver::VersionReq::STAR)
6294            ">=0.1, <2", // multi-range — comma-separated comparators
6295        ] {
6296            let s = SupervisorSpec {
6297                children: vec![child("worker", form, RestartPolicy::Permanent)],
6298                ..SupervisorSpec::default()
6299            };
6300            s.validate()
6301                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
6302        }
6303    }
6304
6305    #[test]
6306    fn child_versao_empty_takes_precedence_over_invalid() {
6307        // Order pin: the existing `EmptyChildVersion` diagnostic (which
6308        // doesn't try to parse) fires before the new
6309        // `ChildVersaoInvalid` parse-side diagnostic, so an empty
6310        // `:versao` keeps its narrower error message —
6311        // `parse_requirement` would also reject `""`, but the
6312        // empty-string arm is the more self-locating diagnostic for the
6313        // author. Same ordering discipline as
6314        // `membro_versao_empty_takes_precedence_over_invalid` in
6315        // aplicacao.rs.
6316        let s = SupervisorSpec {
6317            children: vec![child("worker", "", RestartPolicy::Permanent)],
6318            ..SupervisorSpec::default()
6319        };
6320        let err = s.validate().unwrap_err();
6321        assert!(
6322            matches!(err, SupervisorError::EmptyChildVersion { ref caixa } if caixa == "worker"),
6323            "got {err:?}"
6324        );
6325    }
6326
6327    #[test]
6328    fn child_versao_invalid_fires_before_duplicate_check() {
6329        // Order pin: a malformed requirement on a non-duplicate entry
6330        // surfaces *its own* diagnostic (which names the offending
6331        // `:versao` string), even when a later entry would otherwise
6332        // collapse onto an earlier name. The per-entry shape gate runs
6333        // inline before the duplicate-key insert — parallel to
6334        // `membro_versao_invalid_fires_before_duplicate_check` in
6335        // aplicacao.rs and the b0c8389 / c4213a4 ordering discipline.
6336        let s = SupervisorSpec {
6337            children: vec![
6338                child("worker", "^bad", RestartPolicy::Permanent),
6339                child("cache", "^0.1", RestartPolicy::Transient),
6340                child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
6341            ],
6342            ..SupervisorSpec::default()
6343        };
6344        let err = s.validate().unwrap_err();
6345        assert!(
6346            matches!(
6347                err,
6348                SupervisorError::ChildVersaoInvalid { ref caixa, .. } if caixa == "worker"
6349            ),
6350            "got {err:?}"
6351        );
6352    }
6353
6354    #[test]
6355    fn child_versao_invalid_diagnostic_carries_offending_versao() {
6356        // The diagnostic-shape pin: the error names the offending
6357        // `:versao` value verbatim so the author can grep their
6358        // caixa.lisp without re-running the build, and carries a
6359        // non-empty `reason` from `semver::VersionReq::parse` so the
6360        // parser's own wording flows through to the diagnostic.
6361        let s = SupervisorSpec {
6362            children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
6363            ..SupervisorSpec::default()
6364        };
6365        let err = s.validate().unwrap_err();
6366        let SupervisorError::ChildVersaoInvalid {
6367            caixa,
6368            versao,
6369            reason,
6370        } = err
6371        else {
6372            panic!("expected ChildVersaoInvalid, got other variant");
6373        };
6374        assert_eq!(caixa, "worker");
6375        assert_eq!(versao, "not-a-req");
6376        assert!(
6377            !reason.is_empty(),
6378            "ChildVersaoInvalid `reason` must carry the parser's wording verbatim"
6379        );
6380    }
6381
6382    // ── value-shape: DNS-1123 label rule on :children :caixa ──────────────
6383
6384    #[test]
6385    fn validate_rejects_child_caixa_with_uppercase() {
6386        // The canonical "I copied the Servico's display name verbatim"
6387        // typo — child caixa names are lowercase per K8s DNS-1123 label
6388        // rule. The diagnostic names the offending name and suggests the
6389        // lower-cased fix in one edit, mirroring the
6390        // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0).
6391        let s = SupervisorSpec {
6392            children: vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
6393            ..SupervisorSpec::default()
6394        };
6395        let err = s.validate().unwrap_err();
6396        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
6397            panic!("expected ChildCaixaInvalid, got other variant");
6398        };
6399        assert_eq!(caixa, "Worker");
6400        assert!(
6401            reason.contains("uppercase"),
6402            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
6403        );
6404        assert!(
6405            reason.contains("\"worker\""),
6406            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
6407        );
6408    }
6409
6410    #[test]
6411    fn validate_rejects_child_caixa_with_underscore() {
6412        // The canonical "I'm thinking of a Python module / Postgres
6413        // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
6414        // label schema. K8s rejects `metadata.name: my_worker` at
6415        // admission time with an opaque `field is invalid` (no source-
6416        // citing diagnostic). The gate moves it to caixa-build time.
6417        let s = SupervisorSpec {
6418            children: vec![child("my_worker", "^0.1", RestartPolicy::Permanent)],
6419            ..SupervisorSpec::default()
6420        };
6421        let err = s.validate().unwrap_err();
6422        assert!(
6423            matches!(
6424                err,
6425                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
6426                    if caixa == "my_worker" && reason.contains('_')
6427            ),
6428            "got {err:?}"
6429        );
6430    }
6431
6432    #[test]
6433    fn validate_rejects_child_caixa_with_dot() {
6434        // A `:children :caixa` entry is a single DNS-1123 label, not a
6435        // subdomain. The K8s Service / ComputeUnit `metadata.name` rules
6436        // forbid dots. Same shape as `rejects_membro_caixa_with_dot`
6437        // (3f9d7a0) on the peer name axis.
6438        let s = SupervisorSpec {
6439            children: vec![child("team.worker", "^0.1", RestartPolicy::Permanent)],
6440            ..SupervisorSpec::default()
6441        };
6442        let err = s.validate().unwrap_err();
6443        assert!(
6444            matches!(
6445                err,
6446                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
6447                    if caixa == "team.worker" && reason.contains('.')
6448            ),
6449            "got {err:?}"
6450        );
6451    }
6452
6453    #[test]
6454    fn validate_rejects_child_caixa_with_leading_hyphen() {
6455        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
6456        // with an alphanumeric. The K8s apiserver rejects `-worker`
6457        // outright; the renderer would emit a `metadata.name: "-worker"`
6458        // that fails admission far from the source caixa.lisp.
6459        let s = SupervisorSpec {
6460            children: vec![child("-worker", "^0.1", RestartPolicy::Permanent)],
6461            ..SupervisorSpec::default()
6462        };
6463        let err = s.validate().unwrap_err();
6464        assert!(
6465            matches!(
6466                err,
6467                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
6468                    if caixa == "-worker" && reason.contains("start and end")
6469            ),
6470            "got {err:?}"
6471        );
6472    }
6473
6474    #[test]
6475    fn validate_rejects_child_caixa_with_trailing_hyphen() {
6476        // The symmetric arm of the boundary rule. Pin separately so
6477        // both ends of the label are covered against a future relaxation
6478        // that only checks one boundary.
6479        let s = SupervisorSpec {
6480            children: vec![child("worker-", "^0.1", RestartPolicy::Permanent)],
6481            ..SupervisorSpec::default()
6482        };
6483        let err = s.validate().unwrap_err();
6484        assert!(
6485            matches!(
6486                err,
6487                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
6488                    if caixa == "worker-"
6489            ),
6490            "got {err:?}"
6491        );
6492    }
6493
6494    #[test]
6495    fn validate_rejects_child_caixa_with_unicode() {
6496        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
6497        // (`xn--…`) by the author before it reaches K8s. The byte-by-
6498        // byte ASCII validity check rejects multi-byte UTF-8 sequences
6499        // by the first byte that fails the `[a-z0-9-]` predicate.
6500        let s = SupervisorSpec {
6501            children: vec![child("café", "^0.1", RestartPolicy::Permanent)],
6502            ..SupervisorSpec::default()
6503        };
6504        let err = s.validate().unwrap_err();
6505        assert!(
6506            matches!(
6507                err,
6508                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
6509                    if caixa == "café"
6510            ),
6511            "got {err:?}"
6512        );
6513    }
6514
6515    #[test]
6516    fn validate_rejects_child_caixa_with_whitespace() {
6517        // Whitespace is the canonical "I pasted from a sketch / doc"
6518        // footgun. The apiserver rejects every `metadata.name` value
6519        // carrying whitespace; pin the gate fires at the right boundary.
6520        let s = SupervisorSpec {
6521            children: vec![child("my worker", "^0.1", RestartPolicy::Permanent)],
6522            ..SupervisorSpec::default()
6523        };
6524        let err = s.validate().unwrap_err();
6525        assert!(
6526            matches!(
6527                err,
6528                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
6529                    if caixa == "my worker"
6530            ),
6531            "got {err:?}"
6532        );
6533    }
6534
6535    #[test]
6536    fn validate_rejects_child_caixa_too_long() {
6537        // The 64-byte boundary pin. DNS-1123 / DNS-1035 cap labels at
6538        // 63 bytes; the K8s apiserver rejects every `metadata.name`
6539        // axis over the limit at admission time. The diagnostic names
6540        // both the cap and the actual length so the author can shorten
6541        // in one edit, mirroring `rejects_membro_caixa_too_long`
6542        // (3f9d7a0) and `rejects_placement_cluster_too_long` (6cbb900).
6543        let too_long = "a".repeat(64);
6544        let s = SupervisorSpec {
6545            children: vec![child(&too_long, "^0.1", RestartPolicy::Permanent)],
6546            ..SupervisorSpec::default()
6547        };
6548        let err = s.validate().unwrap_err();
6549        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
6550            panic!("expected ChildCaixaInvalid, got other variant");
6551        };
6552        assert_eq!(caixa, too_long);
6553        assert!(
6554            reason.contains("63"),
6555            "diagnostic must name the 63-byte cap (got: {reason:?})"
6556        );
6557        assert!(
6558            reason.contains("64"),
6559            "diagnostic must name the actual length (got: {reason:?})"
6560        );
6561    }
6562
6563    #[test]
6564    fn child_caixa_max_length_validates() {
6565        // The 63-byte boundary control pin — exactly-at-the-cap is
6566        // accepted, mirroring `membro_caixa_max_length_validates`
6567        // (3f9d7a0) and `placement_cluster_max_length_validates`
6568        // (6cbb900). Pinned separately so a future off-by-one tightening
6569        // surfaces here.
6570        let max_label = "a".repeat(63);
6571        let s = SupervisorSpec {
6572            children: vec![child(&max_label, "^0.1", RestartPolicy::Permanent)],
6573            ..SupervisorSpec::default()
6574        };
6575        s.validate().unwrap();
6576    }
6577
6578    #[test]
6579    fn validate_accepts_canonical_child_caixa_forms() {
6580        // The realistic shapes a supervised child's `:caixa` carries —
6581        // single-word `worker`, version-suffixed `cache-v2`, single-char
6582        // `a`, two-char `db`, digit-start `2-pool`, longer hyphen-joined
6583        // `payment-retry`, all-digit `0`. Pin every leg so a future
6584        // tightening (e.g. requiring a leading lowercase letter) surfaces
6585        // here as a test failure. Mirrors `accepts_canonical_membro_caixa_forms`
6586        // (3f9d7a0) and `accepts_canonical_placement_cluster_forms`
6587        // (6cbb900).
6588        for form in [
6589            "worker",
6590            "cache-v2",
6591            "a",
6592            "db",
6593            "2-pool",
6594            "payment-retry",
6595            "0",
6596        ] {
6597            let s = SupervisorSpec {
6598                children: vec![child(form, "^0.1", RestartPolicy::Permanent)],
6599                ..SupervisorSpec::default()
6600            };
6601            s.validate()
6602                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
6603        }
6604    }
6605
6606    #[test]
6607    fn child_caixa_empty_takes_precedence_over_invalid() {
6608        // Order pin: the existing `EmptyChildName` diagnostic (which
6609        // doesn't try to parse the DNS-1123 shape) fires before the new
6610        // `ChildCaixaInvalid` per-axis gate, so an empty `:caixa` keeps
6611        // its narrower error message — `is_dns_1123_label` would reject
6612        // the empty string too (boundary check on the first byte), but
6613        // the empty-string arm is the more self-locating diagnostic for
6614        // the author. Same ordering discipline as
6615        // `membro_caixa_empty_takes_precedence_over_invalid` in
6616        // aplicacao.rs.
6617        let s = SupervisorSpec {
6618            children: vec![child("", "^0.1", RestartPolicy::Permanent)],
6619            ..SupervisorSpec::default()
6620        };
6621        let err = s.validate().unwrap_err();
6622        assert_eq!(err, SupervisorError::EmptyChildName);
6623    }
6624
6625    #[test]
6626    fn child_caixa_invalid_fires_before_versao_check() {
6627        // Order pin: the per-axis shape gate runs inline before the
6628        // per-entry versao check, so a malformed `:caixa` on an entry
6629        // whose `:versao` would also fail surfaces the more self-
6630        // locating name-axis diagnostic first. Parallel to
6631        // `membro_versao_invalid_fires_before_duplicate_check` (9888b13)
6632        // and `placement_cluster_invalid_fires_before_duplicate_check`
6633        // (6cbb900).
6634        let s = SupervisorSpec {
6635            children: vec![child("My_Worker", "", RestartPolicy::Permanent)],
6636            ..SupervisorSpec::default()
6637        };
6638        let err = s.validate().unwrap_err();
6639        assert!(
6640            matches!(
6641                err,
6642                SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "My_Worker"
6643            ),
6644            "got {err:?}"
6645        );
6646    }
6647
6648    #[test]
6649    fn child_caixa_invalid_fires_before_duplicate_check() {
6650        // Order pin: a malformed name on a non-duplicate entry surfaces
6651        // its own diagnostic, even when a later entry would otherwise
6652        // collapse onto an earlier name. The per-entry shape gate runs
6653        // inline before the duplicate-key HashSet insert, mirroring
6654        // `placement_cluster_invalid_fires_before_duplicate_check`
6655        // (6cbb900).
6656        let s = SupervisorSpec {
6657            children: vec![
6658                child("Worker", "^0.1", RestartPolicy::Permanent),
6659                child("cache", "^0.1", RestartPolicy::Transient),
6660                child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
6661            ],
6662            ..SupervisorSpec::default()
6663        };
6664        let err = s.validate().unwrap_err();
6665        assert!(
6666            matches!(
6667                err,
6668                SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "Worker"
6669            ),
6670            "got {err:?}"
6671        );
6672    }
6673
6674    #[test]
6675    fn child_caixa_invalid_diagnostic_carries_offending_caixa() {
6676        // The diagnostic-shape pin: the error names the offending
6677        // `:caixa` verbatim plus a non-empty parser-shaped `reason` so
6678        // the author can grep their caixa.lisp without re-running the
6679        // build. Mirrors the diagnostic-shape sweep on every prior
6680        // value-shape gate (3f9d7a0, 6cbb900, c7d05ec).
6681        let s = SupervisorSpec {
6682            children: vec![child("My_Worker", "^0.1", RestartPolicy::Permanent)],
6683            ..SupervisorSpec::default()
6684        };
6685        let err = s.validate().unwrap_err();
6686        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
6687            panic!("expected ChildCaixaInvalid, got other variant");
6688        };
6689        assert_eq!(caixa, "My_Worker");
6690        assert!(
6691            !reason.is_empty(),
6692            "ChildCaixaInvalid `reason` must carry the parser's wording verbatim"
6693        );
6694    }
6695
6696    // ── value-shape: zero restart_window + duplicate child names ──────────
6697
6698    #[test]
6699    fn validate_accepts_none_restart_window() {
6700        // Omitted `:restart-window` is the "never reset" sentinel —
6701        // valid by design. Mirrors :limits axes where None = unbounded.
6702        let s = SupervisorSpec {
6703            restart_window: None,
6704            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6705            ..SupervisorSpec::default()
6706        };
6707        s.validate().unwrap();
6708    }
6709
6710    #[test]
6711    fn validate_rejects_zero_restart_window() {
6712        // Same "0 means the opposite of what you think" footgun closed
6713        // for :politicas :timeout (Envoy treats 0s as infinite) and
6714        // :limits :wall-clock (wasmtime traps before the call starts).
6715        // Erlang/OTP's MaxIntensity/Period requires Period > 0.
6716        let s = SupervisorSpec {
6717            restart_window: Some(Duration::ZERO),
6718            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6719            ..SupervisorSpec::default()
6720        };
6721        assert_eq!(
6722            s.validate().unwrap_err(),
6723            SupervisorError::RestartWindowZero
6724        );
6725    }
6726
6727    // ── value-shape: integer-ms canonical-form on :restart-window ─────────
6728    //
6729    // The fourth (and last) typed-`Duration` axis in caixa-core to get
6730    // the integer-millisecond canonical-form gate — peer with
6731    // `:limits :wall-clock` (82fc3ef), `:politicas :timeout` (a4ae535),
6732    // and `:politicas :circuit-breaker :window` (a4ae535). The serde
6733    // path is already gated at the shared codec layer (see
6734    // `restart_window_serde_rejects_fractional_seconds`); this arm
6735    // closes the programmatic-struct-literal path the codec gate can't
6736    // see.
6737
6738    #[test]
6739    fn validate_rejects_sub_millisecond_restart_window() {
6740        // The fail-before-pass-after pin: a programmatic
6741        // `Duration::from_micros(1500)` (= 1_500_000 ns) silently passed
6742        // `validate` on every pre-gate codebase, then truncated to
6743        // `as_millis() == 1` on first serialize — the shared codec
6744        // emits `"1ms"`, parses it back to `Duration::from_millis(1)` =
6745        // 1_000_000 ns, the typed `restart_window` no longer matches
6746        // its rendered form.
6747        let s = SupervisorSpec {
6748            restart_window: Some(Duration::from_micros(1500)),
6749            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6750            ..SupervisorSpec::default()
6751        };
6752        match s.validate().unwrap_err() {
6753            SupervisorError::RestartWindowNotCanonical { window } => {
6754                assert_eq!(window, Duration::from_micros(1500));
6755            }
6756            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
6757        }
6758    }
6759
6760    #[test]
6761    fn validate_rejects_one_nanosecond_restart_window() {
6762        // The far-sub-ms case: `Duration::from_nanos(1)` is non-zero
6763        // (so `RestartWindowZero` doesn't fire) but `as_millis() == 0`,
6764        // so the shared codec emits the literal `"0s"` — the next
6765        // serde round-trip would parse back to `Duration::ZERO`, which
6766        // the `RestartWindowZero` arm then rejects on re-validate. The
6767        // canonical-form gate at this layer surfaces a self-locating
6768        // diagnostic naming the offending Duration verbatim rather
6769        // than a downstream `RestartWindowZero` whose remediation
6770        // points at omitting the slot.
6771        let s = SupervisorSpec {
6772            restart_window: Some(Duration::from_nanos(1)),
6773            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6774            ..SupervisorSpec::default()
6775        };
6776        match s.validate().unwrap_err() {
6777            SupervisorError::RestartWindowNotCanonical { window } => {
6778                assert_eq!(window, Duration::from_nanos(1));
6779            }
6780            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
6781        }
6782    }
6783
6784    #[test]
6785    fn validate_rejects_nanosecond_past_canonical_boundary_restart_window() {
6786        // The 1-ns-past-1ms boundary case: a `Duration` carrying
6787        // 1_000_001 ns is structurally past the integer-ms granularity
6788        // floor — `subsec_nanos() % 1_000_000 == 1`. The codec round-
6789        // trip would truncate to `1ms` and the consumer would observe
6790        // a 1-ns drift on every emit. Same boundary the peer
6791        // `validate_rejects_nanosecond_past_canonical_boundary` test
6792        // in limits.rs pins for the `:limits :wall-clock` axis.
6793        let w = Duration::from_nanos(1_000_001);
6794        let s = SupervisorSpec {
6795            restart_window: Some(w),
6796            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6797            ..SupervisorSpec::default()
6798        };
6799        assert_eq!(
6800            s.validate().unwrap_err(),
6801            SupervisorError::RestartWindowNotCanonical { window: w }
6802        );
6803    }
6804
6805    #[test]
6806    fn validate_accepts_integer_millisecond_restart_window_values() {
6807        // The positive-control sweep: every `Duration` the shared
6808        // codec can round-trip losslessly — the canonical
6809        // `<integer>{ms,s,m,h}` set the codec's `render` / `parse`
6810        // pair emits and accepts — passes `validate` without
6811        // surfacing the new canonical-form arm. Mirrors
6812        // `validate_accepts_integer_millisecond_wall_clock_values` on
6813        // the sibling `:limits :wall-clock` axis.
6814        for w in [
6815            Duration::from_millis(1),
6816            Duration::from_millis(500),
6817            Duration::from_millis(1500),
6818            Duration::from_secs(1),
6819            Duration::from_secs(30),
6820            Duration::from_secs(60),
6821            Duration::from_secs(120),
6822            Duration::from_secs(3600),
6823        ] {
6824            let s = SupervisorSpec {
6825                restart_window: Some(w),
6826                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6827                ..SupervisorSpec::default()
6828            };
6829            s.validate()
6830                .unwrap_or_else(|e| panic!("integer-ms {w:?} must validate, got {e:?}"));
6831        }
6832    }
6833
6834    #[test]
6835    fn validate_restart_window_zero_takes_precedence_over_canonical_gate() {
6836        // Cross-arm ordering pin: `Duration::ZERO` has
6837        // `subsec_nanos() == 0` and would otherwise pass the
6838        // canonical-form arm — the zero-floor arm must fire first so
6839        // the more self-locating `RestartWindowZero` diagnostic (with
6840        // its omit-axis remediation directly named) leads. Same
6841        // posture every peer zero-then-shape gate uses
6842        // (`WallClockZero` → `WallClockNotCanonical`,
6843        // `PolicyTimeoutZero` → `PolicyTimeoutNotCanonical`,
6844        // `PolicyBreakerZeroWindow` → `PolicyBreakerWindowNotCanonical`).
6845        let s = SupervisorSpec {
6846            restart_window: Some(Duration::ZERO),
6847            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6848            ..SupervisorSpec::default()
6849        };
6850        assert_eq!(
6851            s.validate().unwrap_err(),
6852            SupervisorError::RestartWindowZero
6853        );
6854    }
6855
6856    #[test]
6857    fn restart_window_canonical_diagnostic_carries_offending_duration() {
6858        // Diagnostic-shape pin: the canonical-form arm names the
6859        // offending `Duration` verbatim so the author's grep lands on
6860        // the field's value, not a generic "duration not canonical"
6861        // message. Same shape every other typed-canonical-form arm
6862        // on this surface carries (`WallClockNotCanonical` carries
6863        // the offending `Duration` verbatim,
6864        // `PolicyTimeoutNotCanonical` carries the offending
6865        // `Duration` verbatim).
6866        let w = Duration::from_micros(500);
6867        let s = SupervisorSpec {
6868            restart_window: Some(w),
6869            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6870            ..SupervisorSpec::default()
6871        };
6872        let err = s.validate().unwrap_err();
6873        let msg = err.to_string();
6874        assert!(
6875            msg.contains("500"),
6876            "diagnostic must carry the offending magnitude verbatim (got {msg:?})"
6877        );
6878        assert!(
6879            msg.contains("sub-millisecond"),
6880            "diagnostic must name the sub-millisecond residue class (got {msg:?})"
6881        );
6882    }
6883
6884    #[test]
6885    fn restart_window_validated_value_round_trips_through_codec() {
6886        // The structural property the canonical-ms gate enforces:
6887        // every `SupervisorSpec::restart_window` past
6888        // `SupervisorSpec::validate` round-trips losslessly through
6889        // the shared duration codec (serialize → string →
6890        // deserialize → equal value). Pin this end-to-end so a future
6891        // change to either side (the validate gate's accepted
6892        // granularity, the codec's parse/render unit set) that breaks
6893        // the alignment surfaces here. Peer of
6894        // `wall_clock_validated_value_round_trips_through_codec` on
6895        // the sibling `:limits :wall-clock` axis.
6896        for w in [
6897            Duration::from_millis(1),
6898            Duration::from_millis(1500),
6899            Duration::from_secs(30),
6900            Duration::from_secs(3600),
6901        ] {
6902            let s = SupervisorSpec {
6903                restart_window: Some(w),
6904                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6905                ..SupervisorSpec::default()
6906            };
6907            s.validate().unwrap();
6908            let json = serde_json::to_string(&s).unwrap();
6909            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6910            assert_eq!(back.restart_window, Some(w));
6911        }
6912    }
6913
6914    // ── value-shape: upper cap on :restart-window ─────────────────────────
6915    //
6916    // The fourth (and last) typed-`Duration` axis in caixa-core to get
6917    // the 1h upper cap — peer with `:limits :wall-clock` (51e0dbd),
6918    // `:politicas :timeout` (2e8ee7e), and `:politicas
6919    // :circuit-breaker :window` (379a814). Brackets the typed
6920    // `:restart-window` axis structurally: every validated value lies
6921    // in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`, integer-millisecond
6922    // granularity, closing the
6923    // rolling-window-degenerates-to-lifetime-counter footgun the prior
6924    // zero-floor-and-canonical-form-only checks left open.
6925
6926    #[test]
6927    fn validate_rejects_restart_window_above_cap() {
6928        // The fail-before-pass-after pin: 3601s = 1h + 1s is
6929        // structurally one canonical-tick past the
6930        // [`SUPERVISOR_RESTART_WINDOW_MAX`] ceiling (1h = 3600s) — an
6931        // integer-millisecond magnitude the canonical-form arm above
6932        // accepts cleanly, that the shared duration codec round-trips
6933        // losslessly as `"3601s"`, and that silently passed validate on
6934        // every pre-gate codebase because the typed slot's only checks
6935        // were the zero-floor and canonical-form arms. The runtime
6936        // substrate consuming the value (Erlang/OTP's MaxIntensity/
6937        // Period reconciler, the future wasm-operator's per-supervisor
6938        // restart-intensity counter) reaches for a `Duration` so long
6939        // no realistic restart-recovery pattern resets the counter,
6940        // far from the source caixa.lisp.
6941        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
6942        let s = SupervisorSpec {
6943            restart_window: Some(w),
6944            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6945            ..SupervisorSpec::default()
6946        };
6947        assert_eq!(
6948            s.validate().unwrap_err(),
6949            SupervisorError::RestartWindowExceedsCap { window: w }
6950        );
6951    }
6952
6953    #[test]
6954    fn validate_rejects_restart_window_one_millisecond_above_cap() {
6955        // Boundary case: exactly 1ms past the cap (the granularity the
6956        // canonical-form gate enforces). Catches a future "strictly
6957        // less than" half-measure and pins the diagnostic to name the
6958        // offending `Duration` verbatim. Peer of
6959        // `validate_rejects_wall_clock_one_millisecond_above_cap` /
6960        // `rejects_policy_timeout_one_millisecond_above_cap` /
6961        // `rejects_circuit_breaker_window_one_millisecond_above_cap`
6962        // on the sibling typed-`Duration` axes' top edges.
6963        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
6964        let s = SupervisorSpec {
6965            restart_window: Some(w),
6966            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6967            ..SupervisorSpec::default()
6968        };
6969        assert_eq!(
6970            s.validate().unwrap_err(),
6971            SupervisorError::RestartWindowExceedsCap { window: w }
6972        );
6973    }
6974
6975    #[test]
6976    fn validate_rejects_restart_window_far_above_cap() {
6977        // The "obvious authoring footgun" case: a `(:restart-window "24h")`,
6978        // `(:restart-window "7d")`, or any "I want a lifetime counter
6979        // but wrote a `<integer>h` magnitude anyway" typo — values the
6980        // canonical-form arm accepts as integer-millisecond magnitudes,
6981        // the codec round-trips losslessly through serde, but the
6982        // operator's `MaxIntensity / Period` reconciler cannot honor
6983        // as a meaningful rolling window. Until this gate landed
6984        // validate accepted them. Pin the common above-cap values (24h,
6985        // 7d, ~11.5d) so a future relaxation that drops the upper bound
6986        // surfaces here.
6987        for w in [
6988            Duration::from_secs(86_400),    // 24h
6989            Duration::from_secs(604_800),   // 7d
6990            Duration::from_secs(1_000_000), // ~11.5 days
6991        ] {
6992            let s = SupervisorSpec {
6993                restart_window: Some(w),
6994                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6995                ..SupervisorSpec::default()
6996            };
6997            assert_eq!(
6998                s.validate().unwrap_err(),
6999                SupervisorError::RestartWindowExceedsCap { window: w }
7000            );
7001        }
7002    }
7003
7004    #[test]
7005    fn validate_accepts_restart_window_at_cap() {
7006        // The boundary value — exactly [`SUPERVISOR_RESTART_WINDOW_MAX`]
7007        // (1h) — must validate. The cap is inclusive on the top edge,
7008        // matching the [`crate::LIMITS_WALL_CLOCK_MAX`] /
7009        // [`crate::POLICY_TIMEOUT_MAX`] /
7010        // [`crate::POLICY_BREAKER_WINDOW_MAX`] discipline on the sibling
7011        // capped axes. Pin the boundary explicitly so a future
7012        // off-by-one tightening (`>= SUPERVISOR_RESTART_WINDOW_MAX`
7013        // instead of `>`) surfaces here as a test failure rather than a
7014        // silent contract narrowing.
7015        let s = SupervisorSpec {
7016            restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
7017            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7018            ..SupervisorSpec::default()
7019        };
7020        s.validate()
7021            .expect("restart_window == SUPERVISOR_RESTART_WINDOW_MAX must validate");
7022    }
7023
7024    #[test]
7025    fn validate_accepts_restart_window_typical_values() {
7026        // The documented Erlang/OTP / Elixir / Riak Core / RabbitMQ
7027        // per-supervisor production-playbook band positive-control
7028        // sweep — every value Learn You Some Erlang's `{intensity, 5,
7029        // 60}` worker-supervisor `Period = 60s` default, Elixir's
7030        // `Supervisor` `max_seconds: 5` default, OTP's `supervisor`
7031        // callback module `MaxT = 5..=60` typical, Riak Core's `MaxT ∈
7032        // 10s..=300s`, and RabbitMQ broker-supervisor `MaxT = 5s`
7033        // default recommend (5s..=300s) must pass, plus a sweep
7034        // through the long-tail-flaky-pool band (5m, 15m, 30m, 1h) the
7035        // cap accepts. Mirrors `validate_accepts_wall_clock_typical_values`
7036        // on the sibling `:limits :wall-clock` axis.
7037        for w in [
7038            Duration::from_millis(1),
7039            Duration::from_millis(500),
7040            Duration::from_secs(1),
7041            Duration::from_secs(5),  // RabbitMQ broker-supervisor default
7042            Duration::from_secs(10), // Riak Core lower
7043            Duration::from_secs(30),
7044            Duration::from_secs(60),  // Learn You Some Erlang default
7045            Duration::from_secs(120), // OTP supervisor MaxT typical
7046            Duration::from_secs(300), // Riak Core upper
7047            Duration::from_secs(900), // 15m
7048            Duration::from_secs(1800),
7049            Duration::from_secs(3600), // exactly 1h, the cap
7050        ] {
7051            let s = SupervisorSpec {
7052                restart_window: Some(w),
7053                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7054                ..SupervisorSpec::default()
7055            };
7056            s.validate()
7057                .unwrap_or_else(|e| panic!("restart_window={w:?} must validate; got {e:?}"));
7058        }
7059    }
7060
7061    #[test]
7062    fn restart_window_zero_takes_precedence_over_cap() {
7063        // The cross-arm ordering pin: `Duration::ZERO` is structurally
7064        // outside both `>= 1ms` (zero-floor) and `<=
7065        // SUPERVISOR_RESTART_WINDOW_MAX` (cap), but the zero-floor
7066        // diagnostic is the more self-locating one (it directly names
7067        // the omit-axis remediation), so the validate gate must fire
7068        // on zero first. Same shape every other zero-then-cap ordering
7069        // on this surface uses (`WallClockZero` then
7070        // `WallClockExceedsCap`, `PolicyTimeoutZero` then
7071        // `PolicyTimeoutExceedsCap`, `PolicyBreakerZeroWindow` then
7072        // `PolicyBreakerWindowExceedsCap`).
7073        let s = SupervisorSpec {
7074            restart_window: Some(Duration::ZERO),
7075            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7076            ..SupervisorSpec::default()
7077        };
7078        assert_eq!(
7079            s.validate().unwrap_err(),
7080            SupervisorError::RestartWindowZero,
7081            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
7082        );
7083    }
7084
7085    #[test]
7086    fn restart_window_canonical_takes_precedence_over_cap() {
7087        // The cross-arm ordering pin: a `Duration` that is *both*
7088        // sub-millisecond (non-canonical-form) and structurally above
7089        // the cap surfaces the canonical-form diagnostic first,
7090        // because the round-trip-shape break is the more fundamental
7091        // issue (the value can't even round-trip through the codec,
7092        // so the cap diagnostic naming `1ms..=1h` would be misleading
7093        // — there's no integer-ms form of the offending value). Pin
7094        // the order so a future refactor that reorders the arms
7095        // surfaces here as a test failure rather than a silent
7096        // diagnostic regression. Peer of
7097        // `wall_clock_canonical_takes_precedence_over_cap` /
7098        // `policy_timeout_canonical_takes_precedence_over_cap`.
7099        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_nanos(1);
7100        let s = SupervisorSpec {
7101            restart_window: Some(w),
7102            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7103            ..SupervisorSpec::default()
7104        };
7105        assert_eq!(
7106            s.validate().unwrap_err(),
7107            SupervisorError::RestartWindowNotCanonical { window: w },
7108            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
7109        );
7110    }
7111
7112    #[test]
7113    fn max_restarts_cap_takes_precedence_over_restart_window_cap() {
7114        // The cross-arm ordering pin between the `:max-restarts` cap
7115        // and the sibling `:restart-window` cap. A supervisor carrying
7116        // both an over-cap `max_restarts` AND an over-cap window must
7117        // surface the `MaxRestartsExceedsCap` diagnostic first — the
7118        // cap arm is wired immediately after the zero-restart arm and
7119        // strictly before every window-axis arm (zero / canonical /
7120        // cap), so the offending value the diagnostic names matches
7121        // the order the author would discover the gates by reading
7122        // top-to-bottom through `SupervisorSpec::validate`. Pin the
7123        // order so a future refactor that reorders the arms surfaces
7124        // here as a test failure rather than a silent diagnostic
7125        // regression. Peer of
7126        // `max_restarts_cap_takes_precedence_over_restart_window_gates`
7127        // on the sibling zero / canonical window arms.
7128        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
7129        let s = SupervisorSpec {
7130            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
7131            restart_window: Some(w),
7132            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7133            ..SupervisorSpec::default()
7134        };
7135        assert_eq!(
7136            s.validate().unwrap_err(),
7137            SupervisorError::MaxRestartsExceedsCap {
7138                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
7139            },
7140            "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
7141        );
7142    }
7143
7144    #[test]
7145    fn restart_window_cap_diagnostic_carries_offending_value() {
7146        // The diagnostic-shape pin: the offending `Duration` is
7147        // carried verbatim into the
7148        // [`SupervisorError::RestartWindowExceedsCap`] variant so the
7149        // surfaced error message names the value the author wrote,
7150        // not just the cap. Same self-locating diagnostic shape every
7151        // other typed-cap arm on this surface carries
7152        // (`WallClockExceedsCap` carries the offending `Duration`
7153        // verbatim, `PolicyTimeoutExceedsCap` carries the offending
7154        // `Duration` verbatim, `PolicyBreakerWindowExceedsCap` carries
7155        // the offending `Duration` verbatim).
7156        let w = Duration::from_secs(7200); // 2h
7157        let s = SupervisorSpec {
7158            restart_window: Some(w),
7159            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7160            ..SupervisorSpec::default()
7161        };
7162        let err = s.validate().unwrap_err();
7163        assert!(
7164            matches!(err, SupervisorError::RestartWindowExceedsCap { window } if window == w),
7165            "got {err:?}"
7166        );
7167        let msg = err.to_string();
7168        assert!(
7169            msg.contains("7200"),
7170            ":supervisor :restart-window cap diagnostic must carry the offending value verbatim (got: {msg})"
7171        );
7172    }
7173
7174    #[test]
7175    fn supervisor_restart_window_cap_pins_canonical_value() {
7176        // The SUPERVISOR_RESTART_WINDOW_MAX constant pins the value at
7177        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
7178        // shared duration codec emits as a clean canonical string
7179        // (`"<n>h"`). Pinning the literal value here surfaces a future
7180        // drift (a relaxation to 24h, a tightening to 5m) as a
7181        // deliberate test edit, not a silent contract narrowing.
7182        //
7183        // The four typed-`Duration` caps on the validation surface
7184        // (`LIMITS_WALL_CLOCK_MAX` per-process, `POLICY_TIMEOUT_MAX`
7185        // per-edge, `POLICY_BREAKER_WINDOW_MAX` per-breaker,
7186        // `SUPERVISOR_RESTART_WINDOW_MAX` per-supervisor) share a
7187        // single uniform top edge at the codec's largest emitted unit
7188        // — a structural-property invariant the equality assertions
7189        // here enshrine, so a future drift on any of the four
7190        // surfaces as a deliberate test edit. Same shape every other
7191        // typed-cap value pin uses
7192        // (`wall_clock_cap_pins_canonical_value`,
7193        // `policy_timeout_cap_pins_canonical_value`,
7194        // `circuit_breaker_window_cap_pins_canonical_value`).
7195        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, Duration::from_secs(3600));
7196        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX.as_millis(), 3_600_000);
7197        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::LIMITS_WALL_CLOCK_MAX);
7198        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::POLICY_TIMEOUT_MAX);
7199        assert_eq!(
7200            SUPERVISOR_RESTART_WINDOW_MAX,
7201            crate::POLICY_BREAKER_WINDOW_MAX
7202        );
7203    }
7204
7205    #[test]
7206    fn restart_window_cap_value_round_trips_through_codec() {
7207        // The codec round-trip property the cap arm preserves: the
7208        // [`SUPERVISOR_RESTART_WINDOW_MAX`] constant itself round-trips
7209        // through the shared duration codec — every value at the cap
7210        // serializes to the canonical `"1h"` form and parses back
7211        // identically. Pin the round-trip so a future change to the
7212        // codec's unit set or to the cap's magnitude that breaks the
7213        // round-trip property surfaces here. Peer of
7214        // `wall_clock_cap_value_round_trips_through_codec` on the
7215        // sibling `:limits :wall-clock` axis.
7216        let s = SupervisorSpec {
7217            restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
7218            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7219            ..SupervisorSpec::default()
7220        };
7221        s.validate().unwrap();
7222        let json = serde_json::to_string(&s).unwrap();
7223        assert!(
7224            json.contains("\"1h\""),
7225            "SUPERVISOR_RESTART_WINDOW_MAX must serialize to the canonical `\"1h\"` form (got {json})"
7226        );
7227        let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
7228        assert_eq!(back.restart_window, Some(SUPERVISOR_RESTART_WINDOW_MAX));
7229    }
7230
7231    #[test]
7232    fn validate_rejects_duplicate_child_caixa() {
7233        // Two children with the same :caixa render to two ComputeUnits
7234        // with the same name in the cluster's HelmRelease values —
7235        // one silently overwrites the other. Erlang/OTP's child_spec.id
7236        // is required-unique per supervisor; same set-not-multiset
7237        // discipline applied here as for :membros / :placement
7238        // :clusters / :entrada :paths.
7239        let s = SupervisorSpec {
7240            children: vec![
7241                child("worker", "^0.1", RestartPolicy::Permanent),
7242                child("cache", "^0.1", RestartPolicy::Transient),
7243                child("worker", "^0.2", RestartPolicy::Permanent),
7244            ],
7245            ..SupervisorSpec::default()
7246        };
7247        let err = s.validate().unwrap_err();
7248        assert!(
7249            matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "worker"),
7250            "got {err:?}"
7251        );
7252    }
7253
7254    #[test]
7255    fn validate_duplicate_child_diagnostic_names_first_collision() {
7256        // Iteration walks the :children list in declaration order —
7257        // the diagnostic names the first repeat, deterministically,
7258        // even when multiple names duplicate.
7259        let s = SupervisorSpec {
7260            children: vec![
7261                child("a", "^0.1", RestartPolicy::Permanent),
7262                child("b", "^0.1", RestartPolicy::Permanent),
7263                child("a", "^0.1", RestartPolicy::Permanent),
7264                child("b", "^0.1", RestartPolicy::Permanent),
7265            ],
7266            ..SupervisorSpec::default()
7267        };
7268        let err = s.validate().unwrap_err();
7269        assert!(
7270            matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "a"),
7271            "got {err:?}"
7272        );
7273    }
7274
7275    // ── self-supervision cross-slot gate ──────────────────────────
7276
7277    #[test]
7278    fn validate_no_self_supervision_rejects_self_referential_child() {
7279        // A supervisor whose `:children` lists its own `:nome` is a
7280        // one-node reconciliation cycle — rejected, naming the parent.
7281        let children = vec![
7282            child("worker", "^0.1", RestartPolicy::Permanent),
7283            child("orquestra", "^0.1", RestartPolicy::Permanent),
7284        ];
7285        let err = validate_no_self_supervision(&children, "orquestra").unwrap_err();
7286        assert!(
7287            matches!(err, SupervisorError::ChildSupervisesSelf { ref caixa } if caixa == "orquestra"),
7288            "got {err:?}"
7289        );
7290    }
7291
7292    #[test]
7293    fn validate_no_self_supervision_accepts_distinct_children() {
7294        // Positive control: distinct child names (including a child that
7295        // is itself a supervisor — nested trees are valid OTP) pass.
7296        let children = vec![
7297            child("worker", "^0.1", RestartPolicy::Permanent),
7298            child("sub-tree", "^0.1", RestartPolicy::Permanent),
7299        ];
7300        validate_no_self_supervision(&children, "orquestra").unwrap();
7301    }
7302
7303    #[test]
7304    fn validate_no_self_supervision_empty_children_is_ok() {
7305        // SimpleOneForOne / no-static-children supervisors have nothing
7306        // to self-reference — the gate is vacuously satisfied.
7307        validate_no_self_supervision(&[], "orquestra").unwrap();
7308    }
7309
7310    #[test]
7311    fn validate_simple_one_for_one_skips_uniqueness_check() {
7312        // SimpleOneForOne supervisors carry no static children — the
7313        // duplicate-child loop never runs. A zero-window declaration
7314        // on a SimpleOneForOne supervisor still trips the window check
7315        // (window applies to dynamic children too).
7316        let s = SupervisorSpec {
7317            estrategia: RestartStrategy::SimpleOneForOne,
7318            restart_window: None,
7319            children: vec![],
7320            ..SupervisorSpec::default()
7321        };
7322        s.validate().unwrap();
7323        let s_zero = SupervisorSpec {
7324            estrategia: RestartStrategy::SimpleOneForOne,
7325            restart_window: Some(Duration::ZERO),
7326            children: vec![],
7327            ..SupervisorSpec::default()
7328        };
7329        assert_eq!(
7330            s_zero.validate().unwrap_err(),
7331            SupervisorError::RestartWindowZero
7332        );
7333    }
7334
7335    #[test]
7336    fn validate_zero_window_runs_after_max_restarts_check() {
7337        // Pin the order: max_restarts == 0 fires before
7338        // restart_window == 0s, so an author with both wrong sees the
7339        // counter-axis diagnostic first (matches the order in the
7340        // struct and in the doc comment).
7341        let s = SupervisorSpec {
7342            max_restarts: 0,
7343            restart_window: Some(Duration::ZERO),
7344            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7345            ..SupervisorSpec::default()
7346        };
7347        assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
7348    }
7349
7350    #[test]
7351    fn round_trip_all_strategies() {
7352        for &strat in RestartStrategy::ALL {
7353            // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
7354            // shape partition through the [`gen_platform::IsVariant`]
7355            // derive-generated [`RestartStrategy::is_simple_one_for_one`]
7356            // predicate rather than the raw
7357            // `matches!(strat, RestartStrategy::SimpleOneForOne)`
7358            // open-coded pattern-match — same closed-set-typed-enum
7359            // arm-discriminator dispatch discipline the sibling
7360            // [`crate::upgrade::UpgradeInstruction::is_restart`] convergence
7361            // (915a934) extended onto its two paired positive / negated
7362            // `matches!` filter sites, and the sibling
7363            // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
7364            // predicate convergence (766ec63) extended onto the M3 mesh-
7365            // slot per-`:placement` distribution-strategy `matches!`
7366            // discriminator axis. See the sibling
7367            // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
7368            // fixture and the peer `manifest::tests::
7369            // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
7370            // fixture — all three sites (the last unlifted
7371            // `matches!`-based arm-discriminator axis on the OTP-shape
7372            // supervisor sibling-restart-strategy closed-set typed enum,
7373            // acknowledged in 915a934's Prior-commits footnote as the
7374            // outstanding follow-up) now consult one typed dispatch on
7375            // the substrate primitive.
7376            let s = SupervisorSpec {
7377                estrategia: strat,
7378                children: if strat.is_simple_one_for_one() {
7379                    vec![]
7380                } else {
7381                    vec![child("w", "^0.1", RestartPolicy::Permanent)]
7382                },
7383                ..SupervisorSpec::default()
7384            };
7385            let json = serde_json::to_string(&s).unwrap();
7386            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
7387            assert_eq!(s, back);
7388        }
7389    }
7390
7391    #[test]
7392    fn round_trip_all_restart_policies() {
7393        for policy in [
7394            RestartPolicy::Permanent,
7395            RestartPolicy::Temporary,
7396            RestartPolicy::Transient,
7397        ] {
7398            let c = child("w", "^0.1", policy);
7399            let json = serde_json::to_string(&c).unwrap();
7400            let back: ChildSpec = serde_json::from_str(&json).unwrap();
7401            assert_eq!(c, back);
7402        }
7403    }
7404
7405    #[test]
7406    fn restart_strategy_is_simple_one_for_one_predicate_partitions_the_arm_set() {
7407        // The fail-before-pass-after pin on the `gen_platform::IsVariant`
7408        // derive's [`RestartStrategy::is_simple_one_for_one`] arm-
7409        // discriminator predicate: [`RestartStrategy::SimpleOneForOne`]
7410        // is the only variant that satisfies `.is_simple_one_for_one()`;
7411        // every static-children-bearing arm (`OneForOne` / `OneForAll`
7412        // / `RestForOne`) returns `false`. This pin makes the partition
7413        // invariant load-bearing at caixa-core test time so a future
7414        // derive regression (a hole that returns `false` for
7415        // `SimpleOneForOne` too, or a byte-collision that flips a second
7416        // variant to `true`) trips here rather than laundering the arm
7417        // at the three test-fixture builder sites (a hole flips the
7418        // `SimpleOneForOne` fixture to carry a non-empty children list
7419        // and the subsequent `SupervisorSpec::validate` would refuse the
7420        // fixture with [`SupervisorError::SimpleOneForOneWithStaticChildren`];
7421        // a collision flips a peer strategy's fixture to carry an empty
7422        // children list and the subsequent `validate` would refuse with
7423        // [`SupervisorError::NoChildren`] — either way, the pin fires
7424        // here, at the derive site, rather than at the fixture-refusal
7425        // site far away). Peer of the sibling
7426        // [`crate::upgrade::tests::upgrade_instruction_is_restart_predicate_partitions_the_arm_set`]
7427        // (915a934) pin on the M2 OTP-appup axis and the sibling
7428        // [`crate::kind::tests::caixa_kind_is_variant_predicates_partition_the_arm_set`]
7429        // pin on the M0 `:kind` axis.
7430        let cases: &[(RestartStrategy, bool)] = &[
7431            (RestartStrategy::OneForOne, false),
7432            (RestartStrategy::OneForAll, false),
7433            (RestartStrategy::RestForOne, false),
7434            (RestartStrategy::SimpleOneForOne, true),
7435        ];
7436        for (variant, expected) in cases {
7437            assert_eq!(
7438                variant.is_simple_one_for_one(),
7439                *expected,
7440                "RestartStrategy::{variant:?}.is_simple_one_for_one() must \
7441                 return {expected} (partition invariant on the \
7442                 IsVariant-derived arm-discriminator predicate — every \
7443                 test-fixture site that partitions the `:children` slot \
7444                 shape on `SimpleOneForOne ↔ non-SimpleOneForOne` keys \
7445                 off this typed dispatch, so a derive regression must \
7446                 surface here rather than at the fixture-refusal site)"
7447            );
7448        }
7449    }
7450
7451    #[test]
7452    fn restart_strategy_fixture_partition_routes_through_is_simple_one_for_one_predicate() {
7453        // Byte-identity pin on the `SimpleOneForOne ↔ non-SimpleOneForOne`
7454        // fixture-shape partition against the pre-lift
7455        // `matches!(strat, RestartStrategy::SimpleOneForOne)` open-coded
7456        // pattern-match every test-fixture builder site previously
7457        // coupled to inline. Asserts the two projections agree byte-for-
7458        // byte on every arm of the enum, so a future derive regression
7459        // that flipped either predicate's arm-set would surface here at
7460        // caixa-core test time rather than at the three fixture-builder
7461        // sites (`supervisor::tests::round_trip_all_strategies`,
7462        // `supervisor::tests::supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`,
7463        // `manifest::tests::caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`)
7464        // far from the derive site. Same peer-shape byte-identity pin
7465        // every sibling `IsVariant`-derive-routed convergence carries on
7466        // the substrate's closed-set typed-enum surface (peer of
7467        // [`crate::upgrade::tests::validate_restart_exclusive_routes_through_is_restart_predicate`]
7468        // on the M2 OTP-appup axis).
7469        for &strat in RestartStrategy::ALL {
7470            let via_predicate = strat.is_simple_one_for_one();
7471            let via_matches = matches!(strat, RestartStrategy::SimpleOneForOne);
7472            assert_eq!(
7473                via_predicate, via_matches,
7474                "RestartStrategy::{strat:?}: is_simple_one_for_one() must \
7475                 byte-equal matches!(_, RestartStrategy::SimpleOneForOne) — \
7476                 the pre-lift open-coded pattern and the \
7477                 IsVariant-derived predicate are the same axis, \
7478                 one typed dispatch"
7479            );
7480        }
7481    }
7482
7483    #[test]
7484    fn duration_codec_round_trip_canonical_units() {
7485        // Note the canonical-form rule: durations serialize to the
7486        // *largest* unit that divides cleanly, so 60s ↔ "1m" and not
7487        // "60s" — but the round-trip preserves the underlying Duration.
7488        let cases = [
7489            ("30s", Duration::from_secs(30)),
7490            ("5m", Duration::from_secs(300)),
7491            ("1h", Duration::from_secs(3600)),
7492            ("500ms", Duration::from_millis(500)),
7493        ];
7494        for (lit, dur) in cases {
7495            let s = SupervisorSpec {
7496                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7497                restart_window: Some(dur),
7498                ..SupervisorSpec::default()
7499            };
7500            let json = serde_json::to_string(&s).unwrap();
7501            assert!(
7502                json.contains(&format!("\"{lit}\"")),
7503                "expected \"{lit}\" in {json}"
7504            );
7505            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
7506            assert_eq!(back.restart_window, Some(dur));
7507        }
7508    }
7509
7510    #[test]
7511    fn duration_canonicalizes_to_largest_unit() {
7512        // 60 seconds → "1m" (largest cleanly-divisible unit), but the
7513        // typed Duration still equals 60s on the way back.
7514        let s = SupervisorSpec {
7515            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7516            restart_window: Some(Duration::from_secs(60)),
7517            ..SupervisorSpec::default()
7518        };
7519        let json = serde_json::to_string(&s).unwrap();
7520        assert!(json.contains("\"1m\""), "{json}");
7521        let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
7522        assert_eq!(back.restart_window, Some(Duration::from_secs(60)));
7523    }
7524
7525    #[test]
7526    fn three_child_one_for_one_validates() {
7527        let s = SupervisorSpec {
7528            estrategia: RestartStrategy::OneForOne,
7529            max_restarts: 5,
7530            restart_window: Some(Duration::from_secs(60)),
7531            children: vec![
7532                child("worker", "^0.1", RestartPolicy::Permanent),
7533                child("cache", "^0.1", RestartPolicy::Transient),
7534                child("scratch", "^0.1", RestartPolicy::Temporary),
7535            ],
7536        };
7537        s.validate().unwrap();
7538    }
7539
7540    #[test]
7541    fn json_uses_pascal_case_for_strategy_and_policy() {
7542        // Variant names are PascalCase by default in serde, matching
7543        // tatara-lisp's enum convention (`:estrategia OneForOne`).
7544        let c = child("w", "^0.1", RestartPolicy::Permanent);
7545        let json = serde_json::to_string(&c).unwrap();
7546        assert!(json.contains("\"Permanent\""));
7547        assert!(!json.contains("\"permanent\""));
7548
7549        let s = SupervisorSpec {
7550            estrategia: RestartStrategy::OneForOne,
7551            children: vec![c],
7552            ..SupervisorSpec::default()
7553        };
7554        let json = serde_json::to_string(&s).unwrap();
7555        assert!(json.contains("\"estrategia\":\"OneForOne\""));
7556    }
7557
7558    // ── shared duration codec: integer-magnitude canonical-form gate ──
7559    //
7560    // The gate lifts the discipline `crate::limits::parse_duration`
7561    // (818dd38) carries on the peer `:limits :wall-clock` codec onto
7562    // the shared codec backing the remaining three typed-duration
7563    // slots: `:supervisor :restart-window`, `:politicas :timeout`, and
7564    // `:politicas :circuit-breaker :window`. Every magnitude `render`
7565    // emits is a non-negative integer with no decimal point and no
7566    // leading sign, so the codec's accepted set must match for
7567    // serialize/deserialize to round-trip without canonical-form
7568    // drift.
7569
7570    #[test]
7571    fn parse_accepts_integer_canonical_units() {
7572        // Pin the happy-path: every canonical author shape `render`
7573        // ever emits parses to the same `Duration` value, so the
7574        // codec's accepted set is at least a superset of its emitted
7575        // set on the canonical-unit axis.
7576        for (lit, dur) in [
7577            ("30s", Duration::from_secs(30)),
7578            ("500ms", Duration::from_millis(500)),
7579            ("2m", Duration::from_secs(120)),
7580            ("1h", Duration::from_secs(3600)),
7581            ("0s", Duration::ZERO),
7582        ] {
7583            assert_eq!(
7584                duration_codec::parse(lit).unwrap(),
7585                dur,
7586                "parse({lit:?}) should be {dur:?}"
7587            );
7588        }
7589    }
7590
7591    #[test]
7592    fn parse_accepts_bare_integer_as_seconds() {
7593        // The `"s" | ""` arm: a bare integer with no unit is read as
7594        // seconds. Pin this so the unit-empty form keeps parsing (it
7595        // renders to `"<n>s"` on serialize — that's a unit-choice
7596        // drift the integer-magnitude gate does NOT close, matching
7597        // the `parse_byte_size` `"1024"` → `"1KiB"` scope decision in
7598        // the peer `:limits :memory` codec).
7599        assert_eq!(
7600            duration_codec::parse("30").unwrap(),
7601            Duration::from_secs(30)
7602        );
7603    }
7604
7605    #[test]
7606    fn parse_rejects_fractional_seconds_with_canonical_form_diagnostic() {
7607        // `"1.5s"` parses as f64 to 1.5 → renders back as `"1500ms"`
7608        // on first serialize — DRIFT. The integer-magnitude gate names
7609        // the offending `"1.5"` verbatim and points at the canonical
7610        // remediation `"1500ms"`.
7611        let err = duration_codec::parse("1.5s").unwrap_err();
7612        assert!(err.contains("\"1.5\""), "missing magnitude in {err:?}");
7613        assert!(
7614            err.contains("not a non-negative integer"),
7615            "missing canonical-form reason in {err:?}"
7616        );
7617        assert!(
7618            err.contains("\"1500ms\""),
7619            "missing canonical-form remediation in {err:?}"
7620        );
7621    }
7622
7623    #[test]
7624    fn parse_rejects_decimal_shaped_integer_seconds() {
7625        // `"1.0s"` is the trickiest drift class: numerically `1.0s` is
7626        // `1s` exactly, so the round-trip looks correct — but the
7627        // emitted canonical form is `"1s"`, not `"1.0s"`. Gate the
7628        // decimal-shape-with-integer-value form so author intent is
7629        // never silently rewritten.
7630        let err = duration_codec::parse("1.0s").unwrap_err();
7631        assert!(err.contains("\"1.0\""), "missing magnitude in {err:?}");
7632        assert!(
7633            err.contains("not a non-negative integer"),
7634            "missing canonical-form reason in {err:?}"
7635        );
7636    }
7637
7638    #[test]
7639    fn parse_rejects_half_unit_minute() {
7640        // `"0.5m"` is the unit-fraction footgun — author writes a
7641        // human-readable half-minute, serde silently rewrites to
7642        // `"30s"` on next emit. The gate names the offending
7643        // magnitude `"0.5"` and points at the integer-in-smaller-unit
7644        // form.
7645        let err = duration_codec::parse("0.5m").unwrap_err();
7646        assert!(err.contains("\"0.5\""), "missing magnitude in {err:?}");
7647        assert!(
7648            err.contains("\"30s\""),
7649            "missing canonical-form remediation in {err:?}"
7650        );
7651    }
7652
7653    #[test]
7654    fn parse_rejects_leading_plus_sign() {
7655        // `u64::from_str` rejects `"+30"` but `f64::from_str` accepts
7656        // it as `30.0` — the prior parser used f64 so `"+30s"` parsed
7657        // cleanly to 30s and round-tripped to `"30s"` on next emit
7658        // (DRIFT). The digit-only gate closes the leading-sign class
7659        // first; the diagnostic names `"+30"` verbatim.
7660        let err = duration_codec::parse("+30s").unwrap_err();
7661        assert!(err.contains("\"+30\""), "missing magnitude in {err:?}");
7662        assert!(
7663            err.contains("not a non-negative integer"),
7664            "missing canonical-form reason in {err:?}"
7665        );
7666    }
7667
7668    #[test]
7669    fn parse_rejects_leading_minus_sign() {
7670        // The former `num < 0.0` arm: `"-30s"` parsed as f64 to -30,
7671        // rejected with `"negative duration in \"-30s\""`. Under the
7672        // integer-magnitude gate the diagnostic is unified — `-30` is
7673        // non-digit-only, f64-numeric, and surfaces with the canonical-
7674        // form reason (no leading `+` / `-` sign) naming the offending
7675        // `"-30"` verbatim. Same diagnostic shape as every other
7676        // rejected non-integer magnitude.
7677        let err = duration_codec::parse("-30s").unwrap_err();
7678        assert!(err.contains("\"-30\""), "missing magnitude in {err:?}");
7679        assert!(
7680            err.contains("not a non-negative integer"),
7681            "missing canonical-form reason in {err:?}"
7682        );
7683    }
7684
7685    #[test]
7686    fn parse_garbage_still_falls_through_to_bad_magnitude() {
7687        // Non-digit-only AND non-numeric (`"--1s"`, `"abc"`) falls
7688        // through to the narrower "bad duration magnitude" arm — the
7689        // canonical-form diagnostic is reserved for the parser-shape
7690        // footgun case, not the "not a number at all" case. Same
7691        // shape `parse_byte_size`'s `BadByteMagnitude` arm carries on
7692        // the peer `:limits :memory` codec.
7693        let err = duration_codec::parse("--1s").unwrap_err();
7694        assert!(
7695            err.contains("bad duration magnitude"),
7696            "expected bad-magnitude wording in {err:?}"
7697        );
7698    }
7699
7700    #[test]
7701    fn parse_digit_only_magnitude_carries_zero_f64_drift() {
7702        // The accepted set is now closed under `u64`-exact integer
7703        // arithmetic: `"500ms"` → `Duration::from_millis(500)` exactly,
7704        // `"3600s"` → `Duration::from_secs(3600)` exactly, `"1h"` →
7705        // `Duration::from_secs(3600)` exactly, no f64 mantissa drift
7706        // possible. Pin the integer-exact arms across the four unit
7707        // suffixes so a future refactor that reaches back for f64
7708        // (`from_secs_f64`, `mul_f64`) surfaces here.
7709        assert_eq!(
7710            duration_codec::parse("3600s").unwrap(),
7711            Duration::from_secs(3600)
7712        );
7713        assert_eq!(
7714            duration_codec::parse("60m").unwrap(),
7715            Duration::from_secs(3600)
7716        );
7717        assert_eq!(
7718            duration_codec::parse("1h").unwrap(),
7719            Duration::from_secs(3600)
7720        );
7721        assert_eq!(
7722            duration_codec::parse("999ms").unwrap(),
7723            Duration::from_millis(999)
7724        );
7725    }
7726
7727    #[test]
7728    fn restart_window_serde_rejects_fractional_seconds() {
7729        // The shared codec backs `SupervisorSpec::restart_window`
7730        // (`with = "duration_codec"`) — so the gate applies on serde
7731        // deserialize for the typed Supervisor slot. A
7732        // `{"restartWindow":"1.5s"}` payload that previously round-
7733        // tripped to a different canonical string on next serialize
7734        // is now refused at deserialize with the integer-magnitude
7735        // diagnostic.
7736        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
7737            "restartWindow":"1.5s",
7738            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
7739        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
7740        let msg = err.to_string();
7741        assert!(
7742            msg.contains("not a non-negative integer"),
7743            "expected integer-magnitude diagnostic in {msg:?}"
7744        );
7745        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
7746    }
7747
7748    #[test]
7749    fn restart_window_serde_rejects_leading_plus() {
7750        // The `u64::from_str` leading-`+` permissiveness gap that
7751        // motivated the digit-only gate (the `f64`-side accepted
7752        // `"+30"`, the prior parser silently round-tripped to `"30s"`)
7753        // is now closed on the shared codec — surfaces as a structured
7754        // diagnostic at the serde layer for every typed-duration slot.
7755        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
7756            "restartWindow":"+30s",
7757            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
7758        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
7759        let msg = err.to_string();
7760        assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
7761        assert!(
7762            msg.contains("not a non-negative integer"),
7763            "missing canonical-form reason in {msg:?}"
7764        );
7765    }
7766
7767    #[test]
7768    fn parse_rejects_leading_zero_magnitude() {
7769        // `"030s"` is digit-only, so the existing non-digit-only / sign
7770        // / fractional arm doesn't catch it — `u64::from_str("030")`
7771        // returns `Ok(30)`, so before this gate `"030s"` parsed to
7772        // `Duration::from_secs(30)` and round-tripped through `render`
7773        // to `"30s"` — a *different* canonical string on the next emit,
7774        // breaking the THEORY.md Part V render-determinism contract
7775        // exactly the way `"+30s"` did before the leading-`+` arm
7776        // landed. Peer with the `rate_limit_codec` leading-zero arm
7777        // (4f46830) on the same canonical-form-drift axis.
7778        let err = duration_codec::parse("030s").unwrap_err();
7779        assert!(
7780            err.contains("non-canonical leading zero"),
7781            "expected leading-zero diagnostic in {err:?}"
7782        );
7783        assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
7784        assert!(
7785            err.contains("\"30s\""),
7786            "missing canonical-form remediation in {err:?}"
7787        );
7788        assert!(
7789            err.contains("THEORY.md"),
7790            "missing render-determinism citation in {err:?}"
7791        );
7792    }
7793
7794    #[test]
7795    fn parse_rejects_multi_digit_zero_magnitude() {
7796        // `"00s"` and `"00ms"` are the all-zero leading-zero footgun —
7797        // digit-only, parse losslessly to `Duration::ZERO`, but render
7798        // back to `"0s"` (the single-byte canonical form) on the next
7799        // emit. The leading-zero arm refuses the drift class at the
7800        // codec layer; the semantic-zero gate downstream
7801        // (`SupervisorError::ZeroRestartWindow`, etc.) would refuse
7802        // the single-byte canonical form `"0s"` separately on the
7803        // typed-validate layer.
7804        let err = duration_codec::parse("00s").unwrap_err();
7805        assert!(
7806            err.contains("non-canonical leading zero"),
7807            "expected leading-zero diagnostic in {err:?}"
7808        );
7809        assert!(err.contains("\"00\""), "missing magnitude in {err:?}");
7810    }
7811
7812    #[test]
7813    fn parse_rejects_leading_zero_per_hour_window() {
7814        // `"01h"` is the per-hour-window footgun — multi-byte magnitude
7815        // starting with `0`, parses losslessly to `Duration::from_secs(3600)`,
7816        // renders to `"1h"` (DRIFT). The arm is unit-agnostic: every
7817        // canonical unit suffix the codec accepts (`ms` / `s` / `m` /
7818        // `h` / bare-integer-as-seconds) inherits the same gate.
7819        let err = duration_codec::parse("01h").unwrap_err();
7820        assert!(
7821            err.contains("non-canonical leading zero"),
7822            "expected leading-zero diagnostic in {err:?}"
7823        );
7824        assert!(err.contains("\"01\""), "missing magnitude in {err:?}");
7825    }
7826
7827    #[test]
7828    fn parse_rejects_leading_zero_bare_integer_as_seconds() {
7829        // The `parse_accepts_bare_integer_as_seconds` happy-path
7830        // (`"30"` → 30s) inherits the leading-zero arm: `"030"` is
7831        // multi-byte starts-with-`0`, parses losslessly to
7832        // `Duration::from_secs(30)`, renders to `"30s"` (DRIFT). The
7833        // bare-integer surface accepts permissive unit-empty
7834        // shorthand but still must reject leading-zero padding.
7835        let err = duration_codec::parse("030").unwrap_err();
7836        assert!(
7837            err.contains("non-canonical leading zero"),
7838            "expected leading-zero diagnostic in {err:?}"
7839        );
7840        assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
7841    }
7842
7843    #[test]
7844    fn parse_accepts_single_zero_magnitude_at_codec_layer() {
7845        // The codec-layer / typed-validate-layer boundary: `"0s"` /
7846        // `"0ms"` / `"0"` are the single-byte canonical-zero forms —
7847        // each round-trips losslessly through `render`
7848        // (`render(Duration::ZERO)` → `"0s"`), so the codec layer
7849        // accepts them. The downstream semantic-zero gates
7850        // (`SupervisorError::ZeroRestartWindow`,
7851        // `AplicacaoError::PolicyTimeoutZero`,
7852        // `AplicacaoError::PolicyCircuitBreakerWindowZero`) refuse
7853        // zero-magnitude authoring at the typed-validate layer above,
7854        // peer with the `rate_limit_codec` codec-layer / typed-
7855        // validate-layer partition for `"0/s"`.
7856        assert_eq!(duration_codec::parse("0s").unwrap(), Duration::ZERO);
7857        assert_eq!(duration_codec::parse("0ms").unwrap(), Duration::ZERO);
7858        assert_eq!(duration_codec::parse("0").unwrap(), Duration::ZERO);
7859    }
7860
7861    #[test]
7862    fn parse_accepts_canonical_magnitude_with_leading_one() {
7863        // The complementary boundary: a future tightening cannot
7864        // drift into rejecting valid canonical magnitudes that
7865        // happen to start with `1` (or any digit `[1-9]`). Pin
7866        // every canonical-unit suffix so the leading-zero arm
7867        // remains strictly narrower than the digit-only arm.
7868        assert_eq!(
7869            duration_codec::parse("100ms").unwrap(),
7870            Duration::from_millis(100)
7871        );
7872        assert_eq!(
7873            duration_codec::parse("100s").unwrap(),
7874            Duration::from_secs(100)
7875        );
7876        assert_eq!(
7877            duration_codec::parse("10m").unwrap(),
7878            Duration::from_secs(600)
7879        );
7880        assert_eq!(
7881            duration_codec::parse("10h").unwrap(),
7882            Duration::from_secs(36_000)
7883        );
7884    }
7885
7886    #[test]
7887    fn restart_window_serde_rejects_leading_zero() {
7888        // The shared codec backs `SupervisorSpec::restart_window`
7889        // (`with = "duration_codec"`) — so the leading-zero arm
7890        // applies on serde deserialize for the typed Supervisor slot.
7891        // A `{"restartWindow":"030s"}` payload that previously round-
7892        // tripped to a different canonical string on next serialize
7893        // is now refused at deserialize with the leading-zero
7894        // diagnostic. Peer with `restart_window_serde_rejects_leading_plus`
7895        // / `restart_window_serde_rejects_fractional_seconds` on the
7896        // same canonical-form-drift axis.
7897        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
7898            "restartWindow":"030s",
7899            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
7900        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
7901        let msg = err.to_string();
7902        assert!(
7903            msg.contains("non-canonical leading zero"),
7904            "expected leading-zero diagnostic in {msg:?}"
7905        );
7906        assert!(msg.contains("\"030\""), "missing magnitude in {msg:?}");
7907    }
7908
7909    #[test]
7910    fn parse_rejects_leading_whitespace() {
7911        // `" 30s"` — the canonical paste-from-aligned-doc /
7912        // paste-from-YAML-quoted-plain-scalar footgun. Before this
7913        // gate the top-level `s.trim()` at parse entry silently ate
7914        // the leading space and parsed the value to
7915        // `Duration::from_secs(30)`, which then round-tripped through
7916        // `render` to `"30s"` (a *different* canonical string on the
7917        // next emit) — the exact canonical-form-drift class the
7918        // leading-`+` / leading-zero arms already close, extended
7919        // to the whitespace-byte class. Peer with the sibling
7920        // `rate_limit_codec` whitespace-rejection arm (1ad7755) on
7921        // the M3 `:politicas` axis.
7922        let err = duration_codec::parse(" 30s").unwrap_err();
7923        assert!(
7924            err.contains("contains whitespace byte"),
7925            "expected whitespace diagnostic in {err:?}"
7926        );
7927        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
7928        assert!(
7929            err.contains("THEORY.md"),
7930            "missing render-determinism contract citation in {err:?}"
7931        );
7932    }
7933
7934    #[test]
7935    fn parse_rejects_trailing_whitespace() {
7936        // `"30s "` — the canonical shell-history / trailing-space
7937        // paste footgun. Before this gate the top-level `s.trim()`
7938        // silently ate the trailing space and parsed to
7939        // `Duration::from_secs(30)`, round-tripping to `"30s"` on the
7940        // next emit — same canonical-form drift as the leading-space
7941        // sibling, closed on the same whitespace-byte arm.
7942        let err = duration_codec::parse("30s ").unwrap_err();
7943        assert!(
7944            err.contains("contains whitespace byte"),
7945            "expected whitespace diagnostic in {err:?}"
7946        );
7947        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
7948    }
7949
7950    #[test]
7951    fn parse_rejects_internal_whitespace_between_magnitude_and_unit() {
7952        // `"30 s"` — the canonical typographically-spaced author
7953        // shape (the same idiom every prose reference to a duration
7954        // renders as, mistakenly retained when the value is pasted
7955        // into a codec-shaped slot). Before this gate the per-part
7956        // `num_part.trim()` / `unit.trim()` calls silently ate the
7957        // whitespace between the magnitude and the unit and parsed
7958        // the value to `Duration::from_secs(30)`, round-tripping to
7959        // `"30s"` — the codec's *internal* whitespace-tolerance
7960        // vector, orthogonal to the leading / trailing surface but
7961        // the same canonical-form-drift class. Pins the arm as
7962        // strictly stronger than the pre-existing top-level
7963        // `s.trim()` behavior: it fires on whitespace anywhere in
7964        // the value, not just at the string boundary.
7965        let err = duration_codec::parse("30 s").unwrap_err();
7966        assert!(
7967            err.contains("contains whitespace byte"),
7968            "expected whitespace diagnostic in {err:?}"
7969        );
7970        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
7971    }
7972
7973    #[test]
7974    fn parse_rejects_tab_byte() {
7975        // `"\t30s"` — the canonical paste-from-indented-doc /
7976        // paste-from-YAML-block-scalar footgun where a tab byte leads
7977        // the magnitude. Pins that the gate covers tab (`0x09`) as
7978        // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
7979        // members and both would be silently swallowed by `s.trim()`
7980        // pre-gate. The `is_ascii_whitespace` coverage extends beyond
7981        // space alone to the full ASCII-whitespace set (space `0x20`,
7982        // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
7983        // the tab arm as a representative of the non-space members.
7984        let err = duration_codec::parse("\t30s").unwrap_err();
7985        assert!(
7986            err.contains("contains whitespace byte"),
7987            "expected whitespace diagnostic in {err:?}"
7988        );
7989        assert!(
7990            err.contains("0x09"),
7991            "missing offending tab byte in {err:?}"
7992        );
7993    }
7994
7995    #[test]
7996    fn restart_window_serde_rejects_whitespace() {
7997        // The shared codec backs `SupervisorSpec::restart_window`
7998        // (`with = "duration_codec"`) — so the whitespace arm
7999        // applies on serde deserialize for the typed Supervisor slot.
8000        // A `{"restartWindow":" 30s"}` payload that previously round-
8001        // tripped to a different canonical string on next serialize
8002        // is now refused at deserialize with the whitespace-byte
8003        // diagnostic. Peer with `restart_window_serde_rejects_leading_zero`
8004        // / `restart_window_serde_rejects_leading_plus` /
8005        // `restart_window_serde_rejects_fractional_seconds` on the
8006        // same canonical-form-drift axis.
8007        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
8008            "restartWindow":" 30s",
8009            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
8010        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
8011        let msg = err.to_string();
8012        assert!(
8013            msg.contains("contains whitespace byte"),
8014            "expected whitespace diagnostic in {msg:?}"
8015        );
8016        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
8017    }
8018
8019    // ── canonical-form: non-ASCII Unicode `White_Space` duration gate ─────
8020    //
8021    // Successor to the ASCII-whitespace arm (a7ae622) on the shared
8022    // duration codec — closes the strictly-complementary class the
8023    // byte-scan cannot see, through the lifted
8024    // [`crate::render::find_non_ascii_whitespace_char`] predicate.
8025    // Applies to `:supervisor :restart-window`, `:politicas :timeout`,
8026    // and `:politicas :circuit-breaker :window` simultaneously via
8027    // this shared codec.
8028
8029    #[test]
8030    fn duration_codec_parse_rejects_leading_nbsp() {
8031        // NBSP prefix — the strictly-complementary drift class the
8032        // ASCII byte-scan cannot see. `str::trim` strips it silently
8033        // and the value drifts to `"30s"` on next serialize.
8034        let err = duration_codec::parse("\u{00A0}30s").unwrap_err();
8035        assert!(
8036            err.contains("non-ASCII Unicode whitespace character"),
8037            "expected non-ASCII whitespace diagnostic in {err:?}"
8038        );
8039        assert!(err.contains("U+00A0"), "missing codepoint in {err:?}");
8040    }
8041
8042    #[test]
8043    fn duration_codec_parse_rejects_trailing_line_separator() {
8044        // LINE SEPARATOR (`\u{2028}`) trailing — paste-from-web-doc
8045        // footgun.
8046        let err = duration_codec::parse("30s\u{2028}").unwrap_err();
8047        assert!(
8048            err.contains("non-ASCII Unicode whitespace character"),
8049            "expected non-ASCII whitespace diagnostic in {err:?}"
8050        );
8051        assert!(err.contains("U+2028"), "missing codepoint in {err:?}");
8052    }
8053
8054    #[test]
8055    fn duration_codec_parse_accepts_ascii_only_forms_after_unicode_arm() {
8056        // Positive-control pin: every ASCII-only canonical form the
8057        // renderer emits stays accepted through the new arm.
8058        assert_eq!(
8059            duration_codec::parse("30s").unwrap(),
8060            Duration::from_secs(30)
8061        );
8062        assert_eq!(
8063            duration_codec::parse("500ms").unwrap(),
8064            Duration::from_millis(500)
8065        );
8066        assert_eq!(
8067            duration_codec::parse("1h").unwrap(),
8068            Duration::from_secs(3600)
8069        );
8070    }
8071
8072    #[test]
8073    fn restart_window_serde_rejects_non_ascii_whitespace() {
8074        // The shared codec backs `SupervisorSpec::restart_window` — so
8075        // the new non-ASCII Unicode whitespace arm applies on serde
8076        // deserialize for the typed Supervisor slot. A
8077        // `{"restartWindow":" 30s"}` payload that previously
8078        // survived the ASCII byte-scan (only ASCII whitespace was
8079        // refused) is now refused at deserialize with the
8080        // non-ASCII-whitespace-and-codepoint diagnostic.
8081        let payload = "{\"estrategia\":\"OneForOne\",\"maxRestarts\":5,\
8082            \"restartWindow\":\"\u{00A0}30s\",\
8083            \"children\":[{\"caixa\":\"w\",\"versao\":\"^0.1\",\"restart\":\"Permanent\"}]}";
8084        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
8085        let msg = err.to_string();
8086        assert!(
8087            msg.contains("non-ASCII Unicode whitespace character"),
8088            "expected non-ASCII whitespace diagnostic in {msg:?}"
8089        );
8090        assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
8091    }
8092
8093    // ── drift-detection: serde-derive-to-SUPERVISOR_KEY_* identity ────────
8094
8095    #[test]
8096    fn supervisor_spec_serde_keys_match_lifted_supervisor_key_consts() {
8097        // Load-bearing invariant: the four `SUPERVISOR_KEY_*` consts
8098        // (`SUPERVISOR_KEY_ESTRATEGIA` / `SUPERVISOR_KEY_MAX_RESTARTS` /
8099        // `SUPERVISOR_KEY_RESTART_WINDOW` / `SUPERVISOR_KEY_CHILDREN`)
8100        // name the exact camelCase JSON keys the
8101        // `#[serde(rename_all = "camelCase")]` attribute on
8102        // `SupervisorSpec` emits. Serialize a fully-populated spec (each
8103        // field carries `Some(_)` / non-empty) and pin that each canonical
8104        // byte-sequence appears verbatim in the JSON — a future accidental
8105        // `rename_all = "snake_case"` / `"kebab-case"` / verbatim-field-
8106        // name flip at the derive attribute (any of which would silently
8107        // break every downstream JSON consumer that reaches for one of the
8108        // four consts via `Value::get(...)`) surfaces here as a build-time
8109        // test failure at `supervisor.rs`, not as an apply-time
8110        // `.get(<stale-canonical-const>)` returning `None` far from the
8111        // derive-attr drift's commit. Peer with the sibling
8112        // `limits_spec_serde_keys_match_lifted_m2_limits_key_consts`
8113        // (d8b8b4f) pin on the M2 `:limits` axis — same discipline the
8114        // M2 typed-slot family established, extended here to close the
8115        // top-level Supervisor axis.
8116        let spec = SupervisorSpec {
8117            estrategia: RestartStrategy::OneForOne,
8118            max_restarts: 5,
8119            restart_window: Some(Duration::from_secs(60)),
8120            children: vec![ChildSpec {
8121                caixa: "w".into(),
8122                versao: "^0.1".into(),
8123                restart: RestartPolicy::Permanent,
8124            }],
8125        };
8126        let json = serde_json::to_string(&spec).unwrap();
8127        for key in [
8128            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
8129            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
8130            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
8131            crate::render::SUPERVISOR_KEY_CHILDREN,
8132        ] {
8133            let quoted = format!("\"{key}\"");
8134            assert!(
8135                json.contains(&quoted),
8136                "serialized SupervisorSpec must carry the lifted \
8137                 SUPERVISOR_KEY_* byte-sequence {quoted} verbatim in \
8138                 the JSON emission (got: {json})",
8139            );
8140        }
8141    }
8142
8143    #[test]
8144    fn supervisor_key_consts_are_pairwise_distinct() {
8145        // Cross-axis drift-detection pin: a future collapse of two
8146        // canonical top-level byte-strings onto the same value (e.g. an
8147        // accidental copy-paste flip of `SUPERVISOR_KEY_CHILDREN` to
8148        // also read `"estrategia"`) would silently reroute every
8149        // downstream probe on one axis onto the sibling axis's overlay
8150        // entry and pass every propagation-probe test that expected only
8151        // the stale axis's value. Peer of the sibling four-way distinct
8152        // pin on the `M2_LIMITS_KEY_*` tetrad (d8b8b4f).
8153        let all = [
8154            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
8155            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
8156            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
8157            crate::render::SUPERVISOR_KEY_CHILDREN,
8158        ];
8159        for (i, a) in all.iter().enumerate() {
8160            for b in all.iter().skip(i + 1) {
8161                assert_ne!(
8162                    a, b,
8163                    "SUPERVISOR_KEY_* consts must be pairwise-distinct \
8164                     canonical byte-sequences — got `{a}` == `{b}`",
8165                );
8166            }
8167        }
8168    }
8169
8170    #[test]
8171    fn supervisor_key_consts_are_lower_camel_case_shape() {
8172        // Shape-pin: every `SUPERVISOR_KEY_*` const must be a
8173        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
8174        // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
8175        // capital, no whitespace / dots) — the canonical shape the
8176        // `#[serde(rename_all = "camelCase")]` derive produces on
8177        // `SupervisorSpec`. A future flip to a non-camelCase attribute
8178        // at the derive surfaces both here (this test fails on the
8179        // stale-constant shape) and at
8180        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
8181        // (that test fails on the mismatch between const and derive).
8182        // Peer with `m2_limits_key_consts_are_lower_camel_case_shape`
8183        // (d8b8b4f) on the sibling M2 `:limits` axis.
8184        for key in [
8185            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
8186            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
8187            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
8188            crate::render::SUPERVISOR_KEY_CHILDREN,
8189        ] {
8190            assert!(
8191                !key.is_empty(),
8192                "SUPERVISOR_KEY_* must be non-empty (got {key:?})"
8193            );
8194            let first = key.chars().next().unwrap();
8195            assert!(
8196                first.is_ascii_lowercase(),
8197                "SUPERVISOR_KEY_* must lead with an ASCII-lowercase byte \
8198                 (got {key:?}, leads with {first:?})",
8199            );
8200            assert!(
8201                key.chars().all(|c| c.is_ascii_alphanumeric()),
8202                "SUPERVISOR_KEY_* must be ASCII-alphanumeric only \
8203                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
8204            );
8205        }
8206    }
8207
8208    #[test]
8209    fn supervisor_key_consts_are_byte_distinct_from_supervisor_author_key_peers() {
8210        // Cross-axis drift pin: the four `SUPERVISOR_KEY_*` consts
8211        // (camelCase JSON keys, no leading colon) must never collide
8212        // byte-for-byte with the four peer `SUPERVISOR_AUTHOR_KEY_*`
8213        // consts (kebab-case author-facing labels with leading colon)
8214        // that sit next to them at `caixa_core::render`. Both families
8215        // cover the same four typed Supervisor slots on two distinct
8216        // axes (author-side kebab vs renderer-side camelCase);
8217        // collapsing either family onto the other's byte-shape would
8218        // silently reroute the render-side probe onto the author-facing
8219        // surface, or vice versa. Peer of the byte-distinctness
8220        // discipline the `M3_PLACEMENT_KEY_ESTRATEGIA` docstring names
8221        // against the peer `M3_AUTHOR_KEY_PLACEMENT`.
8222        let pairs = [
8223            (
8224                crate::render::SUPERVISOR_KEY_ESTRATEGIA,
8225                crate::render::SUPERVISOR_AUTHOR_KEY_ESTRATEGIA,
8226            ),
8227            (
8228                crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
8229                crate::render::SUPERVISOR_AUTHOR_KEY_MAX_RESTARTS,
8230            ),
8231            (
8232                crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
8233                crate::render::SUPERVISOR_AUTHOR_KEY_RESTART_WINDOW,
8234            ),
8235            (
8236                crate::render::SUPERVISOR_KEY_CHILDREN,
8237                crate::render::SUPERVISOR_AUTHOR_KEY_CHILDREN,
8238            ),
8239        ];
8240        for (json_key, author_key) in pairs {
8241            assert_ne!(
8242                json_key, author_key,
8243                "SUPERVISOR_KEY_* (JSON side) must differ byte-for-byte \
8244                 from the peer SUPERVISOR_AUTHOR_KEY_* (author side); \
8245                 got JSON `{json_key}` == author `{author_key}`",
8246            );
8247        }
8248    }
8249
8250    // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_KEY_* identity ──
8251
8252    #[test]
8253    fn child_spec_serde_keys_match_lifted_supervisor_child_key_consts() {
8254        // Load-bearing invariant: the three `SUPERVISOR_CHILD_KEY_*` consts
8255        // (`SUPERVISOR_CHILD_KEY_CAIXA` / `SUPERVISOR_CHILD_KEY_VERSAO` /
8256        // `SUPERVISOR_CHILD_KEY_RESTART`) name the exact camelCase JSON
8257        // keys the `#[serde(rename_all = "camelCase")]` attribute on
8258        // `ChildSpec` emits. Serialize a fully-populated `ChildSpec` and
8259        // pin that each canonical byte-sequence appears verbatim in the
8260        // JSON — a future accidental `rename_all = "snake_case"` /
8261        // `"kebab-case"` / verbatim-field-name flip at the derive
8262        // attribute (any of which would silently break every downstream
8263        // JSON consumer that reaches for one of the three consts via
8264        // `Value::get(...)`) surfaces here as a build-time test failure at
8265        // `supervisor.rs`, not as an apply-time
8266        // `.get(<stale-canonical-const>)` returning `None` far from the
8267        // derive-attr drift's commit. Peer with the enclosing
8268        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
8269        // (40cc4e5) pin on the M2 supervision-tree top-level axis — same
8270        // discipline the SupervisorSpec top-level lift established,
8271        // extended here to the sibling per-`:children` entry `ChildSpec`
8272        // derive so the last M2 typed-struct sub-block
8273        // `#[serde(rename_all = "camelCase")]` axis on the Supervisor
8274        // surface without a lifted serde-key peer joins the substrate's
8275        // "one canonical byte-string per typed serialized-key axis"
8276        // discipline.
8277        let c = ChildSpec {
8278            caixa: "worker".into(),
8279            versao: "^0.1".into(),
8280            restart: RestartPolicy::Permanent,
8281        };
8282        let json = serde_json::to_string(&c).unwrap();
8283        for key in [
8284            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
8285            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
8286            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
8287        ] {
8288            let quoted = format!("\"{key}\"");
8289            assert!(
8290                json.contains(&quoted),
8291                "serialized ChildSpec must carry the lifted \
8292                 SUPERVISOR_CHILD_KEY_* byte-sequence {quoted} verbatim \
8293                 in the JSON emission (got: {json})",
8294            );
8295        }
8296    }
8297
8298    #[test]
8299    fn supervisor_child_key_consts_are_pairwise_distinct() {
8300        // Cross-axis drift-detection pin: a future collapse of two
8301        // canonical `ChildSpec` per-entry byte-strings onto the same
8302        // value (e.g. an accidental copy-paste flip of
8303        // `SUPERVISOR_CHILD_KEY_RESTART` to also read `"caixa"`) would
8304        // silently reroute every downstream probe on one axis onto the
8305        // sibling axis's overlay entry and pass every propagation-probe
8306        // test that expected only the stale axis's value. Peer of the
8307        // sibling three-way distinct pin on the `CONTRATO_KEY_*` triad
8308        // (ca463a4) and the two-way distinct pin on the `MEMBRO_KEY_*`
8309        // pair (ce80ca0).
8310        let all = [
8311            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
8312            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
8313            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
8314        ];
8315        for (i, a) in all.iter().enumerate() {
8316            for b in all.iter().skip(i + 1) {
8317                assert_ne!(
8318                    a, b,
8319                    "SUPERVISOR_CHILD_KEY_* consts must be pairwise-\
8320                     distinct canonical byte-sequences — got `{a}` == `{b}`",
8321                );
8322            }
8323        }
8324    }
8325
8326    #[test]
8327    fn supervisor_child_key_consts_are_lower_camel_case_shape() {
8328        // Shape-pin: every `SUPERVISOR_CHILD_KEY_*` const must be a
8329        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
8330        // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
8331        // capital, no whitespace / dots) — the canonical shape the
8332        // `#[serde(rename_all = "camelCase")]` derive produces on
8333        // `ChildSpec`. A future flip to a non-camelCase attribute at the
8334        // derive surfaces both here (this test fails on the
8335        // stale-constant shape) and at
8336        // `child_spec_serde_keys_match_lifted_supervisor_child_key_consts`
8337        // (that test fails on the mismatch between const and derive).
8338        // Peer with `supervisor_key_consts_are_lower_camel_case_shape`
8339        // (40cc4e5) on the sibling `SupervisorSpec` top-level axis.
8340        for key in [
8341            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
8342            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
8343            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
8344        ] {
8345            assert!(
8346                !key.is_empty(),
8347                "SUPERVISOR_CHILD_KEY_* must be non-empty (got {key:?})"
8348            );
8349            let first = key.chars().next().unwrap();
8350            assert!(
8351                first.is_ascii_lowercase(),
8352                "SUPERVISOR_CHILD_KEY_* must lead with an ASCII-lowercase \
8353                 byte (got {key:?}, leads with {first:?})",
8354            );
8355            assert!(
8356                key.chars().all(|c| c.is_ascii_alphanumeric()),
8357                "SUPERVISOR_CHILD_KEY_* must be ASCII-alphanumeric only \
8358                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
8359            );
8360        }
8361    }
8362
8363    // ── drift-detection: serde-derive-to-SUPERVISOR_ESTRATEGIA_* identity ────
8364
8365    #[test]
8366    fn restart_strategy_variants_serialize_to_lifted_scalar_values() {
8367        // The fail-before-pass-after pin: pre-lift there was no
8368        // single-source binding between the [`RestartStrategy`] variant
8369        // name the un-`rename`d `Serialize` derive emits under
8370        // [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`] and the byte-string
8371        // every downstream cluster-side dispatcher (the future
8372        // wasm-operator's per-supervisor sibling-restart branch, the
8373        // future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
8374        // admission-time enum-arm bind, the `caixa-operator`'s
8375        // hierarchical reconciliation scheduler's per-strategy fan-out)
8376        // probes verbatim. A future `#[serde(rename_all = "kebab-case")]`
8377        // attribute on the enum — or a per-variant `#[serde(rename = "…")]`
8378        // override, or a variant rename in the source — would silently
8379        // rebrand the emitted scalar under one spelling while every
8380        // downstream dispatcher still probed the other, with the failure
8381        // surfacing at the operator's reconcile posture (subtrees coming
8382        // up under the `default()` `OneForOne` arm rather than the typed
8383        // slot's declared strategy — a bad child would then only take
8384        // itself down instead of the sibling set the author intended, so
8385        // shared-state children fall out of sync) far from the source
8386        // rebrand commit and with no field naming the drift. Pinning the
8387        // two paths (the `Serialize` derive's serialized string AND the
8388        // [`RestartStrategy::as_str`] helper) to the same four lifted
8389        // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
8390        // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
8391        // [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
8392        // [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
8393        // byte-strings makes any future drift on either endpoint fail
8394        // here at caixa-core build time. Peer of the M3
8395        // `placement_strategy_variants_serialize_to_lifted_scalar_values`
8396        // (3f0e21c) on the sibling `PlacementStrategy` axis — same
8397        // three-path-convergence discipline, extended to close the
8398        // OTP-shaped per-supervisor sibling-restart axis.
8399        for (variant, expected) in [
8400            (
8401                RestartStrategy::OneForOne,
8402                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
8403            ),
8404            (
8405                RestartStrategy::OneForAll,
8406                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
8407            ),
8408            (
8409                RestartStrategy::RestForOne,
8410                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
8411            ),
8412            (
8413                RestartStrategy::SimpleOneForOne,
8414                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
8415            ),
8416        ] {
8417            let json = serde_json::to_string(&variant).unwrap();
8418            assert_eq!(
8419                json,
8420                format!("\"{expected}\""),
8421                "RestartStrategy::{variant:?} must serialize to {expected:?}"
8422            );
8423            assert_eq!(
8424                variant.as_str(),
8425                expected,
8426                "RestartStrategy::{variant:?}.as_str() must return the lifted \
8427                 SUPERVISOR_ESTRATEGIA_* constant"
8428            );
8429        }
8430    }
8431
8432    #[test]
8433    fn supervisor_estrategia_consts_are_pairwise_distinct() {
8434        // Cross-arm drift-detection pin: a future collapse of two
8435        // canonical variant byte-strings onto the same value (e.g. an
8436        // accidental copy-paste flip of `SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`
8437        // to also read `"OneForOne"`) would silently reroute every
8438        // downstream operator's per-strategy dispatch onto the sibling
8439        // arm's reconcile branch and pass every propagation-probe test
8440        // that expected only the stale arm's value — the mis-strategied
8441        // subtree would come up with the wrong sibling-restart posture
8442        // on every subsequent failure. Peer of the sibling four-way
8443        // distinct pin `supervisor_key_consts_are_pairwise_distinct`
8444        // (40cc4e5) on the top-level `SUPERVISOR_KEY_*` axis.
8445        let all = [
8446            crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
8447            crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
8448            crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
8449            crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
8450        ];
8451        for (i, a) in all.iter().enumerate() {
8452            for (j, b) in all.iter().enumerate() {
8453                if i != j {
8454                    assert_ne!(
8455                        a, b,
8456                        "SUPERVISOR_ESTRATEGIA_* consts must be pairwise distinct \
8457                         — got duplicate {a:?} at indices {i} and {j}",
8458                    );
8459                }
8460            }
8461        }
8462    }
8463
8464    #[test]
8465    fn restart_strategy_display_routes_through_as_str_helper() {
8466        // The fail-before-pass-after pin on the first half of the
8467        // three-path convergence: pre-convergence the sibling
8468        // OTP-shape typed enum [`RestartStrategy`] carried a
8469        // [`std::fmt::Display`] surface via its
8470        // `#[discriminant(also_display)]` gen-platform derive route,
8471        // which arrived kebab-case as `"one-for-one"` /
8472        // `"one-for-all"` / `"rest-for-one"` /
8473        // `"simple-one-for-one"` while the wire format ran as
8474        // PascalCase `"OneForOne"` / `"OneForAll"` / `"RestForOne"` /
8475        // `"SimpleOneForOne"` through the un-`rename`d serde derive.
8476        // Every consumer reaching for a strategy byte-string past the
8477        // wire format had to pick between three paths
8478        // ([`RestartStrategy::as_str`], the `Serialize` derive's
8479        // serialized string, or `format!("{v}")` on the
8480        // discriminant-Display route), any two of which a future
8481        // variant rename or `#[serde(rename_all = "kebab-case")]`
8482        // attribute would silently desynchronize. Wiring
8483        // [`std::fmt::Display`] through [`RestartStrategy::as_str`]
8484        // closes the third path: every `format!("{v}")` call reaches
8485        // the same lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
8486        // const the wire format and the [`RestartStrategy::as_str`]
8487        // helper already route through, so a future variant rename
8488        // lands at exactly one place. Pin the routing here so a future
8489        // `impl std::fmt::Display for RestartStrategy`
8490        // reimplementation that hand-rolls the arms instead of
8491        // delegating to [`RestartStrategy::as_str`] fails at
8492        // caixa-core build time. Peer of the M3
8493        // `placement_strategy_display_routes_through_as_str_helper`
8494        // (cc8f749) which the M3 axis converged first.
8495        for &variant in RestartStrategy::ALL {
8496            assert_eq!(
8497                variant.to_string(),
8498                variant.as_str(),
8499                "RestartStrategy::{variant:?} Display must route through \
8500                 RestartStrategy::as_str (single source of truth: the lifted \
8501                 SUPERVISOR_ESTRATEGIA_* const the wire format also emits)"
8502            );
8503        }
8504    }
8505
8506    #[test]
8507    fn restart_strategy_display_matches_serialized_wire_byte_string() {
8508        // The fail-before-pass-after pin on the second half of the
8509        // three-path convergence: `Display` (user-facing text) agrees
8510        // byte-for-byte with the `Serialize` derive's wire format
8511        // (canonical camelCase-schema `SUPERVISOR_KEY_ESTRATEGIA`
8512        // scalar) on every variant. Pre-convergence the two paths
8513        // were structurally independent — a future
8514        // `#[serde(rename_all = "kebab-case")]` attribute on the
8515        // enum would silently rebrand the emitted wire scalar
8516        // (`one-for-one`, `one-for-all`, `rest-for-one`,
8517        // `simple-one-for-one`) while every consumer that
8518        // pretty-prints the strategy (the future wasm-operator's
8519        // per-supervisor sibling-restart-strategy diagnostic line,
8520        // the future `feira app graph` per-supervisor strategy line,
8521        // the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
8522        // materializer's admission-webhook rejection body) would
8523        // still emit the PascalCase form the `as_str` / `Display`
8524        // route returns, with the mismatch surfacing at consumer
8525        // parse time / operator dispatch time far from the source
8526        // rebrand commit. Pin the two paths byte-for-byte here so any
8527        // future serde-attribute or variant-rename drift is a
8528        // caixa-core-build-time test failure at this call, not a
8529        // silent per-consumer dispatch miss. Peer of the M3
8530        // `placement_strategy_display_matches_serialized_wire_byte_string`
8531        // (cc8f749) which the M3 axis converged first.
8532        for &variant in RestartStrategy::ALL {
8533            let wire = serde_json::to_string(&variant).unwrap();
8534            let unquoted = wire
8535                .strip_prefix('"')
8536                .and_then(|s| s.strip_suffix('"'))
8537                .expect("serialized RestartStrategy is a JSON string");
8538            assert_eq!(
8539                variant.to_string(),
8540                unquoted,
8541                "RestartStrategy::{variant:?} Display byte-string must match the \
8542                 Serialize derive's wire byte-string (three-path convergence: \
8543                 Display + as_str + Serialize all resolve to the same \
8544                 SUPERVISOR_ESTRATEGIA_* const)"
8545            );
8546        }
8547    }
8548
8549    #[test]
8550    fn restart_strategy_as_ref_str_routes_through_as_str_accessor() {
8551        // Fail-before-pass-after byte-parity pin on the lifted
8552        // `impl AsRef<str> for RestartStrategy` — asserts the
8553        // standard-library trait impl and the substrate-primitive
8554        // [`RestartStrategy::as_str`] `pub const fn` accessor resolve
8555        // to the same `&str` per instance across the four-arm
8556        // closed set, so any future silent detour that routes the
8557        // impl through a divergent projection (a per-arm inline
8558        // `match self { RestartStrategy::OneForOne => "OneForOne", … }`
8559        // re-inlining that opens a compile-time link to the un-lifted
8560        // arm-literal, a swap onto the kebab-case
8561        // [`gen_platform::Discriminant`] catalog identity that would
8562        // collide the wire axis with the dispatcher-catalog axis) trips
8563        // at caixa-core test time under `PartialEq` rather than at a
8564        // downstream `impl AsRef<str>`-bound consumer's silent split.
8565        // Sweeps every one of the four arms
8566        // [`RestartStrategy::ALL`] carries so no arm's projection is
8567        // covered only by the sibling wire-format `Serialize` derive
8568        // path. Peer of the sibling
8569        // [`crate::version::tests::caixa_version_as_ref_str_routes_through_as_str_accessor`]
8570        // (16d5c7e) `AsRef<str>`-byte-parity pin on the paired
8571        // top-level `:versao` typed newtype — the two pins together
8572        // cover the substrate primitive's `AsRef<str>` projection axis
8573        // on the paired newtype + closed-set-typed-enum surface.
8574        for &variant in RestartStrategy::ALL {
8575            assert_eq!(
8576                <RestartStrategy as AsRef<str>>::as_ref(&variant),
8577                variant.as_str(),
8578                "AsRef<str> impl on RestartStrategy::{variant:?} must \
8579                 byte-equal RestartStrategy::as_str on the same instance \
8580                 — divergence signals a silent detour off the substrate-\
8581                 primitive accessor"
8582            );
8583        }
8584    }
8585
8586    #[test]
8587    fn restart_strategy_as_ref_str_routes_through_display_via_shared_accessor() {
8588        // Fail-before-pass-after byte-parity pin on the three-path
8589        // convergence discipline the M2 sibling-restart primitive now
8590        // carries on the `&str`-projection axis:
8591        // `<RestartStrategy as AsRef<str>>::as_ref(&s)` (the newly
8592        // lifted impl), `format!("{s}")` (the pre-existing
8593        // [`fmt::Display`] impl), and `s.as_str()` (the substrate-
8594        // primitive `pub const fn` accessor both trait impls delegate
8595        // through) must resolve to the same byte-string on every
8596        // instance across the four-arm closed set. Refuses any future
8597        // divergence between the two trait impls (a stray
8598        // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
8599        // rather than delegating through the shared accessor; a
8600        // hypothetical `AsRef<str>` rewrite that inlines a per-arm
8601        // literal cascade) that would silently split the two
8602        // projection paths of the same closed-set typed enum. Mirrors
8603        // the sibling three-path-convergence discipline the peer
8604        // [`crate::CaixaVersion`] typed newtype carries on its
8605        // `AsRef<str>` / `Display` / `as_str` triple
8606        // (version.rs pin
8607        // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
8608        // 16d5c7e).
8609        for &variant in RestartStrategy::ALL {
8610            let via_as_ref: &str = <RestartStrategy as AsRef<str>>::as_ref(&variant);
8611            let via_display: String = format!("{variant}");
8612            let via_accessor: &str = variant.as_str();
8613            assert_eq!(via_as_ref, via_accessor);
8614            assert_eq!(via_display, via_accessor);
8615            assert_eq!(via_as_ref, via_display.as_str());
8616        }
8617    }
8618
8619    #[test]
8620    fn restart_strategy_all_enumerates_every_variant_exactly_once() {
8621        // Fail-before-pass-after pin on the [`RestartStrategy::ALL`]
8622        // exhaustive-iteration surface: every variant appears exactly
8623        // once, and the slice length matches the arm count of the
8624        // closed set. Every consumer that walks the accepted-strategy
8625        // set (a future `feira supervisor --estrategia …` CLI-side
8626        // arg-parse's "did you mean" hint, a future M4 admission-
8627        // webhook's rejection body naming the accepted-`:estrategia`
8628        // list, the [`RestartStrategy::from_wire`] reverse-projection
8629        // consumers that iterate the accept-set for diagnostic
8630        // rendering) reads through this slice, so a future arm addition
8631        // that grows the enum but forgets to grow [`Self::ALL`]
8632        // silently truncates every downstream consumer's accept-set at
8633        // the same pre-addition boundary — this pin fails at caixa-core
8634        // build time on the pairwise-distinct + arm-count invariants.
8635        //
8636        // Peer of the sibling [`crate::CaixaKind::ALL`] (6b1f4fb) /
8637        // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
8638        // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
8639        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
8640        // pins on the peer closed-set typed-enum axes.
8641        let all: &[RestartStrategy] = RestartStrategy::ALL;
8642        assert_eq!(
8643            all.len(),
8644            4,
8645            "RestartStrategy::ALL must enumerate every variant of the \
8646             four-arm closed set (OneForOne, OneForAll, RestForOne, \
8647             SimpleOneForOne); got {all:?}"
8648        );
8649        for (i, a) in all.iter().enumerate() {
8650            for (j, b) in all.iter().enumerate() {
8651                if i != j {
8652                    assert_ne!(
8653                        a, b,
8654                        "RestartStrategy::ALL must carry every variant exactly \
8655                         once — got duplicate {a:?} at indices {i} and {j}"
8656                    );
8657                }
8658            }
8659        }
8660        for variant in [
8661            RestartStrategy::OneForOne,
8662            RestartStrategy::OneForAll,
8663            RestartStrategy::RestForOne,
8664            RestartStrategy::SimpleOneForOne,
8665        ] {
8666            assert!(
8667                all.contains(&variant),
8668                "RestartStrategy::ALL must contain {variant:?} — a future arm \
8669                 addition that grows the enum but forgets to grow the ALL slice \
8670                 silently truncates every downstream consumer's accept-set at \
8671                 the pre-addition boundary"
8672            );
8673        }
8674    }
8675
8676    #[test]
8677    fn restart_strategy_wire_names_covers_every_arm() {
8678        // Load-bearing pin on the substrate-canonical
8679        // [`RestartStrategy::WIRE_NAMES`] exhaustive accept-set roster
8680        // on the `PascalCase` wire byte-string axis: every variant of
8681        // the sibling [`RestartStrategy::ALL`] exhaustive-iteration
8682        // surface must project through [`RestartStrategy::as_str`] onto
8683        // an entry the [`RestartStrategy::WIRE_NAMES`] roster carries,
8684        // and the roster's length must byte-equal
8685        // `RestartStrategy::ALL.len()` so a silent skew between the
8686        // [`RestartStrategy::as_str`] match's arm-set and the roster's
8687        // arm-set trips here at caixa-core test time rather than at a
8688        // downstream M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
8689        // admission-webhook rejection body's wire-form `:estrategia`
8690        // accepted-set enumeration miss / a `feira supervisor
8691        // --estrategia …` "did you mean" hint drift / a future
8692        // wasm-operator per-reconcile-step diagnostic log line's
8693        // accepted-wire-form enumeration miss. A future arm addition
8694        // (an OTP-`rest_for_all` arm the theory
8695        // [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
8696        // might reach for once the four canonical OTP strategies stop
8697        // covering the substrate's discovered load-shape) extends
8698        // [`RestartStrategy::ALL`] as a single edit and this pin
8699        // sweeps the new arm by iteration; the paired
8700        // [`RestartStrategy::WIRE_NAMES`] roster must grow in lockstep
8701        // or this assertion trips. Every entry is further pinned to
8702        // open with an ASCII uppercase byte so a silent collapse of
8703        // the wire-form axis with the peer kebab-case
8704        // dispatcher-catalog axis (an entry byte-identical to a
8705        // sibling [`Self::discriminant`] kebab byte-string that would
8706        // let a wire-axis consumer accept the dispatcher-catalog
8707        // vocabulary) trips here rather than at a downstream K8s-CR
8708        // round-trip miss.
8709        //
8710        // Peer of the sibling
8711        // [`crate::kind::tests::caixa_kind_wire_names_covers_every_arm`]
8712        // (bd708bd) pin on the top-level typed-kind discriminator's
8713        // `PascalCase` wire byte-string axis, and of the sibling
8714        // [`crate::upgrade::tests::upgrade_instruction_wire_forms_covers_every_arm`]
8715        // (cc42c0e) /
8716        // [`crate::upgrade::tests::upgrade_instruction_lisp_forms_covers_every_arm`]
8717        // (1898d77) pins on the OTP-appup discriminator's two-axis
8718        // roster split — the same closed-set exhaustive-roster
8719        // coverage discipline extended here onto the first M2
8720        // OTP-shape sibling-restart closed-set typed enum.
8721        //
8722        // Fail-before-pass-after locally verified by mutating one arm
8723        // of the paired [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
8724        // const family (e.g. dropping the trailing `e` from
8725        // `"OneForOne"` → `"OneForOn"`) — the length pin still passes
8726        // but the `contains` check fires on the mutated arm; and by
8727        // shortening the roster to three entries — the length pin
8728        // fires first.
8729        assert_eq!(
8730            RestartStrategy::WIRE_NAMES.len(),
8731            RestartStrategy::ALL.len(),
8732            "RestartStrategy::WIRE_NAMES.len() must byte-equal \
8733             RestartStrategy::ALL.len() — a mismatch means the roster \
8734             and the enum's arm-set have drifted; downstream consumers \
8735             that fan through both will silently disagree on the \
8736             accepted arm-set"
8737        );
8738        for &variant in RestartStrategy::ALL {
8739            let wire = variant.as_str();
8740            assert!(
8741                RestartStrategy::WIRE_NAMES.contains(&wire),
8742                "RestartStrategy::{variant:?}.as_str() = {wire:?} must \
8743                 be a member of RestartStrategy::WIRE_NAMES — the \
8744                 emitter and the roster have drifted out of lockstep"
8745            );
8746        }
8747        for tag in RestartStrategy::WIRE_NAMES {
8748            let first = tag.chars().next().unwrap_or_else(|| {
8749                panic!(
8750                    "RestartStrategy::WIRE_NAMES entry {tag:?} must be \
8751                     a non-empty PascalCase byte-string"
8752                )
8753            });
8754            assert!(
8755                first.is_ascii_uppercase(),
8756                "RestartStrategy::WIRE_NAMES entry {tag:?} must open \
8757                 with an ASCII uppercase byte (PascalCase wire form) — \
8758                 a lowercase entry would collide the wire-form axis \
8759                 with the peer kebab-case dispatcher-catalog axis \
8760                 [`RestartStrategy::discriminant`] serves"
8761            );
8762        }
8763    }
8764
8765    #[test]
8766    fn restart_strategy_from_wire_accepts_every_lifted_constant() {
8767        // Fail-before-pass-after pin on the forward accept-set of the
8768        // [`RestartStrategy::from_wire`] reverse projection: every
8769        // canonical [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
8770        // constant the [`RestartStrategy::as_str`] emitter walks parses
8771        // back to its paired variant. Any future arm addition that
8772        // grows the emitter's `as_str` match but forgets to grow the
8773        // parser's `from_wire` match silently splits the two halves of
8774        // the round-trip — the wire byte-string one non-serde consumer
8775        // parses from the one the emitter wrote — with the failure
8776        // surfacing at parse time far from the rebrand commit. Pinning
8777        // the four-arm accept-set here catches the drift at caixa-core
8778        // build time.
8779        //
8780        // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
8781        // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
8782        // accept-set pins on the peer closed-set typed-enum `str → Self`
8783        // axes.
8784        for (wire, expected) in [
8785            (
8786                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
8787                RestartStrategy::OneForOne,
8788            ),
8789            (
8790                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
8791                RestartStrategy::OneForAll,
8792            ),
8793            (
8794                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
8795                RestartStrategy::RestForOne,
8796            ),
8797            (
8798                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
8799                RestartStrategy::SimpleOneForOne,
8800            ),
8801        ] {
8802            let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
8803                panic!(
8804                    "RestartStrategy::from_wire({wire:?}) must accept every \
8805                     SUPERVISOR_ESTRATEGIA_* constant — got None for the \
8806                     lifted canonical byte-string that RestartStrategy::{expected:?} \
8807                     serializes as under SUPERVISOR_KEY_ESTRATEGIA"
8808                )
8809            });
8810            assert_eq!(
8811                parsed, expected,
8812                "RestartStrategy::from_wire({wire:?}) must return \
8813                 RestartStrategy::{expected:?}; got RestartStrategy::{parsed:?}"
8814            );
8815        }
8816    }
8817
8818    #[test]
8819    fn restart_strategy_from_wire_round_trips_through_as_str() {
8820        // Fail-before-pass-after pin on the closed round-trip between
8821        // the forward [`RestartStrategy::as_str`] emitter and the
8822        // reverse [`RestartStrategy::from_wire`] parser: for every
8823        // variant in [`RestartStrategy::ALL`], parsing the emitter's
8824        // output must return exactly the same variant. Any per-arm
8825        // divergence — a future arm added to `as_str` but not
8826        // `from_wire`, an accidental copy-paste flip in one but not
8827        // the other — silently splits the emit and parse halves and
8828        // the failure surfaces at consumer parse time far from the
8829        // drift site. The `ALL`-iterating shape means a future arm
8830        // addition picks up the coverage by construction.
8831        //
8832        // Peer of the sibling
8833        // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
8834        // (18c7342) round-trip pin on
8835        // [`crate::aplicacao::PlacementStrategy::from_wire`] and
8836        // [`crate::kind::tests::caixa_kind_wire_round_trips_through_from_wire`]
8837        // (6b1f4fb) round-trip pin on [`crate::CaixaKind::from_wire`].
8838        for &variant in RestartStrategy::ALL {
8839            let wire = variant.as_str();
8840            let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
8841                panic!(
8842                    "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
8843                     must be Some({variant:?}) — the two halves of the round-trip \
8844                     dispatch on the same lifted SUPERVISOR_ESTRATEGIA_* consts; \
8845                     got None on wire byte-string {wire:?}"
8846                )
8847            });
8848            assert_eq!(
8849                parsed, variant,
8850                "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
8851                 must round-trip to the same variant; got {parsed:?}"
8852            );
8853        }
8854    }
8855
8856    #[test]
8857    fn restart_strategy_from_wire_rejects_unknown_byte_strings() {
8858        // Fail-before-pass-after pin on the closed-set refusal
8859        // discipline of [`RestartStrategy::from_wire`]: every
8860        // byte-string outside the four-arm accept-set returns `None`
8861        // rather than silently collapsing onto the [`Default`]
8862        // (`OneForOne`) arm or an arbitrary neighbor. The refusal set
8863        // exercised here sweeps the load-bearing drift shapes: the
8864        // empty string (a stripped serde-attribute drift), all-
8865        // whitespace strings (the canonical text-editor accidental
8866        // padding shape), the kebab-case dispatcher-catalog identities
8867        // (`"one-for-one"` / `"one-for-all"` / `"rest-for-one"` /
8868        // `"simple-one-for-one"` — the [`gen_platform::FromStrKind`]-
8869        // derived [`std::str::FromStr`] accept-set, which parses the
8870        // *other* axis of this enum's two-axis split and must not leak
8871        // into the `from_wire` PascalCase-wire accept-set), the
8872        // lowercased single-word forms (`"oneforone"`), the padded
8873        // canonical scalar (`" OneForOne "`), the trailing-newline
8874        // shapes (`"OneForOne\n"`), and neighboring-but-unknown arms
8875        // (`"AllForOne"` — the canonical typo direction).
8876        //
8877        // Peer of the sibling
8878        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
8879        // (2aa6d23) +
8880        // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
8881        // (18c7342) refusal pins on the peer closed-set typed-enum
8882        // axes.
8883        for bad in [
8884            "",
8885            " ",
8886            "\n",
8887            "\t",
8888            "one-for-one",
8889            "one-for-all",
8890            "rest-for-one",
8891            "simple-one-for-one",
8892            "oneforone",
8893            "OneForOnes",
8894            "one_for_one",
8895            "one for one",
8896            "ONEFORONE",
8897            "OneForOne ",
8898            " OneForOne",
8899            " SimpleOneForOne ",
8900            "OneForOne\n",
8901            "restforone",
8902            "REST_FOR_ONE",
8903            "AllForOne",
8904            "Simple",
8905            "?",
8906        ] {
8907            assert!(
8908                RestartStrategy::from_wire(bad).is_none(),
8909                "RestartStrategy::from_wire({bad:?}) must return None — the \
8910                 parser's accept-set is exactly the four RestartStrategy::as_str \
8911                 outputs (OneForOne, OneForAll, RestForOne, SimpleOneForOne), \
8912                 and this byte-string is outside that closed set"
8913            );
8914        }
8915    }
8916
8917    #[test]
8918    fn restart_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
8919        // Fail-before-pass-after pin on the fourth path of the four-path
8920        // convergence: `from_wire` (the reverse projection) inverts the
8921        // `Serialize` derive's wire byte-string on every variant.
8922        // Together with the pre-existing three-path convergence
8923        // (`Display` + `as_str` + `Serialize` all resolve to the same
8924        // lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const,
8925        // pinned by
8926        // [`restart_strategy_display_matches_serialized_wire_byte_string`])
8927        // this closes the round-trip: the wire byte-string the
8928        // `Serialize` derive emits parses back to the same variant
8929        // through `from_wire`, so any future serde-attribute or variant-
8930        // rename drift on the emit half now surfaces as a matched drift
8931        // on the parse half at caixa-core build time — the two halves
8932        // migrate as a unit through the lifted consts on any future
8933        // rename, and the round-trip cannot silently split.
8934        //
8935        // Peer of the sibling
8936        // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
8937        // (18c7342) wire-format pin on
8938        // [`crate::aplicacao::PlacementStrategy::from_wire`].
8939        for &variant in RestartStrategy::ALL {
8940            let wire = serde_json::to_string(&variant).unwrap();
8941            let unquoted = wire
8942                .strip_prefix('"')
8943                .and_then(|s| s.strip_suffix('"'))
8944                .expect("serialized RestartStrategy is a JSON string");
8945            let parsed = RestartStrategy::from_wire(unquoted).unwrap_or_else(|| {
8946                panic!(
8947                    "RestartStrategy::from_wire({unquoted:?}) must accept the \
8948                     Serialize derive's wire byte-string for \
8949                     RestartStrategy::{variant:?} — the four-path convergence \
8950                     (Display + as_str + Serialize + from_wire) resolves through \
8951                     the same lifted SUPERVISOR_ESTRATEGIA_* const; got None"
8952                )
8953            });
8954            assert_eq!(
8955                parsed, variant,
8956                "RestartStrategy::from_wire of the Serialize derive's wire \
8957                 byte-string for RestartStrategy::{variant:?} must round-trip \
8958                 to the same variant; got {parsed:?}"
8959            );
8960        }
8961    }
8962
8963    #[test]
8964    fn restart_strategy_try_from_str_routes_through_from_wire_accessor() {
8965        // Fail-before-pass-after byte-parity pin on the newly lifted
8966        // `impl TryFrom<&str> for RestartStrategy` — asserts the standard-
8967        // library trait impl and the substrate-primitive
8968        // [`RestartStrategy::from_wire`] `Option<Self>` accessor resolve to
8969        // the same four-arm accept-set across every arm the exhaustive
8970        // [`RestartStrategy::ALL`] slice enumerates. Any future silent
8971        // detour that routes the trait impl through a divergent projection
8972        // (a per-arm inline `match s { "OneForOne" => Ok(Self::OneForOne),
8973        // … }` re-inlining that opens a compile-time link to the un-
8974        // lifted arm-literal, a hypothetical `#[serde(rename_all = "…")]`
8975        // attribute drift that silently splits the wire byte-string from
8976        // every consumer that reaches for this typed dispatch, an
8977        // accidental swap onto the kebab-case dispatcher-catalog axis the
8978        // pre-existing [`std::str::FromStr`] impl parses through and which
8979        // would collide the two-axis wire/catalog split the sibling
8980        // [`RestartStrategy::from_wire`] doc block makes load-bearing)
8981        // trips at caixa-core test time under `assert_eq!` rather than at
8982        // a downstream `impl TryFrom<&str>`-bound consumer's silent split.
8983        // Sweeps every one of the four arms [`RestartStrategy::ALL`]
8984        // carries so no arm's projection is covered only by the sibling
8985        // method-named `from_wire` path. Peer of the sibling
8986        // [`crate::kind::tests::caixa_kind_try_from_str_routes_through_from_wire_accessor`]
8987        // (3c83606),
8988        // [`crate::dialeto::tests::caixa_dialeto_try_from_str_routes_through_from_wire_accessor`]
8989        // (bf33136), and the M3
8990        // [`crate::aplicacao::tests::placement_strategy_try_from_str_routes_through_from_wire_accessor`]
8991        // (6fd00cd) — extends the trait-idiomatic reverse-projection axis
8992        // onto the first M2-OTP-shape closed-set typed enum on the caixa
8993        // surface.
8994        for &variant in RestartStrategy::ALL {
8995            let wire = variant.as_str();
8996            assert_eq!(
8997                <RestartStrategy as TryFrom<&str>>::try_from(wire),
8998                Ok(variant),
8999                "TryFrom<&str> impl on RestartStrategy must round-trip \
9000                 RestartStrategy::{variant:?}.as_str() = {wire:?} back to \
9001                 Ok(RestartStrategy::{variant:?}) — divergence from \
9002                 RestartStrategy::from_wire signals a silent detour off \
9003                 the substrate-primitive accessor"
9004            );
9005            assert_eq!(
9006                <RestartStrategy as TryFrom<&str>>::try_from(wire).ok(),
9007                RestartStrategy::from_wire(wire),
9008                "TryFrom<&str> ok()-projection on {wire:?} must byte-equal \
9009                 RestartStrategy::from_wire on the same input"
9010            );
9011        }
9012    }
9013
9014    #[test]
9015    fn restart_strategy_try_from_str_rejects_unknown_byte_strings() {
9016        // Rejection witness on the `impl TryFrom<&str> for
9017        // RestartStrategy` — sweeps a candidate set of byte-strings
9018        // outside the four-arm PascalCase wire accept-set the sibling
9019        // [`RestartStrategy::as_str`] emits and asserts every one lands on
9020        // `Err(())`, so a future accidental widening of the trait impl's
9021        // accept-set (a stray additional
9022        // `_ if s.eq_ignore_ascii_case("OneForOne") => Ok(…)` case-fold
9023        // path, a silent inclusion of the kebab-case dispatcher-catalog
9024        // byte-string the pre-existing [`std::str::FromStr`] impl the
9025        // [`gen_platform::FromStrKind`] derive installs parses onto the
9026        // wire axis — which would collide the two-axis
9027        // wire/dispatcher-catalog split the sibling
9028        // [`RestartStrategy::from_wire`] doc block makes load-bearing —
9029        // an English-rebrand or plural-arm silent alias that would
9030        // widen the wire accept-set past the OTP-canonical four) trips at
9031        // caixa-core test time. The candidate set includes the empty
9032        // string, whitespace-only padding, the kebab-case dispatcher-
9033        // catalog byte-strings on the sibling axis (a caller who confuses
9034        // the two axes trips here rather than at a downstream consumer's
9035        // silent reject), a lowercase / uppercase / mixed-case fold of
9036        // each PascalCase arm (a caller who assumes case-fold acceptance
9037        // trips here), leading/trailing whitespace padding, the trailing-
9038        // newline shape, quote-wrapped candidates, and a residual set of
9039        // plausible-but-wrong English rebrand candidates. Peer of the
9040        // sibling
9041        // [`crate::kind::tests::caixa_kind_try_from_str_rejects_unknown_byte_strings`]
9042        // (3c83606) and
9043        // [`crate::aplicacao::tests::placement_strategy_try_from_str_rejects_unknown_byte_strings`]
9044        // (6fd00cd) rejection witnesses.
9045        let rejected: &[&str] = &[
9046            "",
9047            " ",
9048            "\n",
9049            "\t",
9050            "one-for-one",
9051            "one-for-all",
9052            "rest-for-one",
9053            "simple-one-for-one",
9054            "oneforone",
9055            "one_for_one",
9056            "OneForOnes",
9057            "ONEFORONE",
9058            "oneforall",
9059            "restforone",
9060            "simpleoneforone",
9061            "OneForOne ",
9062            " OneForOne",
9063            " OneForAll ",
9064            "OneForOne\n",
9065            "RestForOne\t",
9066            "OneForEach",
9067            "AllForOne",
9068            "one for one",
9069            "\"OneForOne\"",
9070            "?",
9071        ];
9072        for &input in rejected {
9073            assert_eq!(
9074                <RestartStrategy as TryFrom<&str>>::try_from(input),
9075                Err(()),
9076                "TryFrom<&str> impl on RestartStrategy must reject the \
9077                 non-wire byte-string {input:?} — silent acceptance signals \
9078                 an accept-set widening off the paired \
9079                 RestartStrategy::from_wire resolver"
9080            );
9081        }
9082    }
9083
9084    #[test]
9085    fn restart_strategy_try_from_str_and_from_wire_partition_the_accept_set() {
9086        // Cross-axis partition pin: the paired `TryFrom<&str>` and
9087        // `from_wire` reverse projections must resolve identically on
9088        // *every* input, not just the ones [`RestartStrategy::ALL`]
9089        // enumerates. Sweeps a mixed candidate set spanning accepted
9090        // (four-arm PascalCase wire byte-strings) and rejected (kebab-case
9091        // dispatcher-catalog byte-strings, empty, whitespace-padded,
9092        // quoted, English-rebrand candidates) inputs and asserts the
9093        // trait's `Result::ok()` projection byte-equals the method-named
9094        // resolver's `Option<Self>` return-shape on each, locking the two
9095        // paths together by construction so any future detour (a stray
9096        // `try_from` special-case that widens or narrows the accept-set
9097        // outside the paired `from_wire` resolver, an accidental swap
9098        // onto the kebab-case [`std::str::FromStr`] impl the
9099        // [`gen_platform::FromStrKind`] derive installs on the sibling
9100        // dispatcher-catalog axis) trips at caixa-core test time. Peer of
9101        // the sibling
9102        // [`crate::kind::tests::caixa_kind_try_from_str_and_from_wire_partition_the_accept_set`]
9103        // pin — extends the round-trip discipline onto the M2-OTP-shape
9104        // sibling-restart axis.
9105        let candidates: &[&str] = &[
9106            "OneForOne",
9107            "OneForAll",
9108            "RestForOne",
9109            "SimpleOneForOne",
9110            "",
9111            "one-for-one",
9112            "one-for-all",
9113            "rest-for-one",
9114            "simple-one-for-one",
9115            "oneforone",
9116            "unknown",
9117            "OneForOne ",
9118            " OneForOne",
9119            "\"OneForOne\"",
9120            "OneForEach",
9121            "?",
9122        ];
9123        for &input in candidates {
9124            let via_trait: Option<RestartStrategy> =
9125                <RestartStrategy as TryFrom<&str>>::try_from(input).ok();
9126            let via_method: Option<RestartStrategy> = RestartStrategy::from_wire(input);
9127            assert_eq!(
9128                via_trait, via_method,
9129                "TryFrom<&str> and from_wire must resolve identically on \
9130                 input {input:?} — divergence signals the two reverse-\
9131                 projection paths have drifted onto different accept-sets"
9132            );
9133        }
9134    }
9135
9136    #[test]
9137    fn restart_strategy_from_into_static_str_routes_through_as_str_accessor() {
9138        // Fail-before-pass-after byte-parity pin on the newly lifted
9139        // `impl From<RestartStrategy> for &'static str` — asserts the
9140        // standard-library trait impl and the substrate-primitive
9141        // [`RestartStrategy::as_str`] `pub const fn` accessor resolve to
9142        // the same four-arm emit-set across every arm the exhaustive
9143        // [`RestartStrategy::ALL`] slice enumerates. Any future silent
9144        // detour that routes the trait impl through a divergent
9145        // projection (a per-arm inline `match strategy { OneForOne =>
9146        // "OneForOne", … }` re-inlining that opens a compile-time link to
9147        // the un-lifted arm-literal, an accidental swap onto the sibling
9148        // kebab-case [`Self::discriminant`] dispatcher-catalog axis that
9149        // would collide the two-axis wire/catalog split the sibling
9150        // [`RestartStrategy::from_wire`] doc block makes load-bearing) trips
9151        // at caixa-core test time under `assert_eq!` rather than at a
9152        // downstream `impl Into<&'static str>`-bound consumer's silent
9153        // split. Sweeps every one of the four arms
9154        // [`RestartStrategy::ALL`] carries so no arm's projection is
9155        // covered only by the sibling method-named `as_str` /
9156        // [`std::fmt::Display`] / [`AsRef<str>`] paths. Materializes the
9157        // `<&'static str as From<RestartStrategy>>::from` output in a
9158        // `const`-shape binding to make the `'static` lifetime promise a
9159        // build-time invariant — a future accidental downgrade of any of
9160        // the four arms' [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
9161        // constants to a non-`&'static str` (a `String::leak()`-produced
9162        // return, a `Box::leak`-cast) trips at caixa-core build time
9163        // rather than at a downstream `'static`-bound consumer.
9164        const ONE_FOR_ONE: &str = RestartStrategy::OneForOne.as_str();
9165        const ONE_FOR_ALL: &str = RestartStrategy::OneForAll.as_str();
9166        const REST_FOR_ONE: &str = RestartStrategy::RestForOne.as_str();
9167        const SIMPLE_ONE_FOR_ONE: &str = RestartStrategy::SimpleOneForOne.as_str();
9168        for &variant in RestartStrategy::ALL {
9169            let via_trait: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
9170            let via_method: &'static str = variant.as_str();
9171            assert_eq!(
9172                via_trait, via_method,
9173                "From<RestartStrategy> for &'static str impl must round-trip \
9174                 RestartStrategy::{variant:?} to the same lifted \
9175                 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str returns — \
9176                 divergence signals a silent detour off the substrate-primitive \
9177                 accessor"
9178            );
9179            let via_into: &'static str = variant.into();
9180            assert_eq!(
9181                via_into, via_method,
9182                "Into<&'static str>::into on RestartStrategy::{variant:?} must \
9183                 byte-equal RestartStrategy::as_str on the same input — the \
9184                 blanket-derived Into shape must resolve to the same as_str \
9185                 dispatch as the explicit From impl"
9186            );
9187        }
9188        assert_eq!(
9189            [ONE_FOR_ONE, ONE_FOR_ALL, REST_FOR_ONE, SIMPLE_ONE_FOR_ONE],
9190            [
9191                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
9192                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
9193                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
9194                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
9195            ],
9196            "const-context RestartStrategy::as_str must resolve to the four \
9197             lifted SUPERVISOR_ESTRATEGIA_* consts — a future accidental \
9198             downgrade of any arm to a non-const or non-static byte-string \
9199             breaks the `&'static str`-lifetime promise the paired \
9200             From<RestartStrategy> for &'static str impl carries by \
9201             construction"
9202        );
9203    }
9204
9205    #[test]
9206    fn restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set() {
9207        // Cross-axis partition pin: the paired trait-idiomatic
9208        // `From<RestartStrategy> for &'static str` forward projection and
9209        // the method-named [`RestartStrategy::as_str`] forward projection
9210        // must resolve identically on *every* arm, not just the ones
9211        // named in the primary byte-parity pin above. Sweeps every
9212        // [`RestartStrategy::ALL`] arm and asserts the trait's `From::from`
9213        // output byte-equals the method-named accessor's return-value on
9214        // each, locking the two forward-projection paths together by
9215        // construction so any future detour (a stray `From` special-case
9216        // that lands on a divergent per-arm literal outside the paired
9217        // `as_str` dispatch, a hypothetical rebrand touching one axis
9218        // without the other) trips at caixa-core test time. Peer of the
9219        // sibling reverse-projection partition pin
9220        // [`restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
9221        // — extends the round-trip discipline onto the trait-idiomatic
9222        // *forward* axis, closing the two-way `Self ↔ &'static str`
9223        // round-trip on the trait-idiomatic pair
9224        // (`From<Self> for &'static str` + `TryFrom<&str> for Self`) as
9225        // well as the pre-existing method-named pair
9226        // (`as_str` + `from_wire`).
9227        for &variant in RestartStrategy::ALL {
9228            let via_trait: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
9229            let via_method: &'static str = variant.as_str();
9230            assert_eq!(
9231                via_trait, via_method,
9232                "From<RestartStrategy> for &'static str and \
9233                 RestartStrategy::as_str must resolve identically on \
9234                 RestartStrategy::{variant:?} — divergence signals the \
9235                 two forward-projection paths have drifted onto different \
9236                 emit-sets"
9237            );
9238        }
9239        // Round-trip witness: every arm's forward `From` output re-parses
9240        // through the paired trait-idiomatic reverse `TryFrom<&str>` back
9241        // to the original variant. Closes the two-way `RestartStrategy ↔
9242        // &'static str` round-trip on the trait-idiomatic axis pair,
9243        // mirroring the pre-existing method-named `as_str` + `from_wire`
9244        // round-trip on the substrate-primitive axis pair.
9245        for &variant in RestartStrategy::ALL {
9246            let emitted: &'static str = variant.into();
9247            let re_parsed: Result<RestartStrategy, ()> =
9248                <RestartStrategy as TryFrom<&str>>::try_from(emitted);
9249            assert_eq!(
9250                re_parsed,
9251                Ok(variant),
9252                "trait-idiomatic axis pair must round-trip \
9253                 RestartStrategy::{variant:?} through `.into::<&'static \
9254                 str>()` and back through `TryFrom<&str>` — a break signals \
9255                 the forward-emit and reverse-parse axes have drifted onto \
9256                 different vocabularies"
9257            );
9258        }
9259    }
9260
9261    #[test]
9262    fn restart_strategy_from_borrowed_into_static_str_routes_through_as_str_accessor() {
9263        // Fail-before-pass-after byte-parity pin on the newly lifted
9264        // `impl From<&RestartStrategy> for &'static str` — asserts the
9265        // borrowed-input standard-library trait impl and the substrate-
9266        // primitive [`RestartStrategy::as_str`] `pub const fn` accessor
9267        // resolve to the same four-arm emit-set across every arm the
9268        // exhaustive [`RestartStrategy::ALL`] slice enumerates. Rust's
9269        // `From` trait does not auto-derive the borrowed-input sibling
9270        // from a paired owned-input impl (no `impl<T, U> From<&T> for U
9271        // where T: Copy, U: From<T>` blanket in `core`), so the
9272        // borrowed-input axis is a distinct trait-idiomatic surface
9273        // that a `.iter().map(Into::into)` shape over
9274        // [`RestartStrategy::ALL`] (whose iterator yields
9275        // `&RestartStrategy`, not `RestartStrategy`) reaches through
9276        // this impl and no other — the paired owned-input
9277        // [`From<RestartStrategy>`] impl requires an explicit
9278        // `.copied()` / dereference before the trait fires.
9279        // Materializes the `<&'static str as
9280        // From<&RestartStrategy>>::from` output in a `const`-shape
9281        // binding to make the `'static` lifetime promise a build-time
9282        // invariant.
9283        const ONE_FOR_ONE: &str = RestartStrategy::OneForOne.as_str();
9284        const ONE_FOR_ALL: &str = RestartStrategy::OneForAll.as_str();
9285        const REST_FOR_ONE: &str = RestartStrategy::RestForOne.as_str();
9286        const SIMPLE_ONE_FOR_ONE: &str = RestartStrategy::SimpleOneForOne.as_str();
9287        for variant in RestartStrategy::ALL {
9288            let via_trait: &'static str = <&'static str as From<&RestartStrategy>>::from(variant);
9289            let via_method: &'static str = variant.as_str();
9290            assert_eq!(
9291                via_trait, via_method,
9292                "From<&RestartStrategy> for &'static str impl must \
9293                 round-trip &RestartStrategy::{variant:?} to the same \
9294                 lifted SUPERVISOR_ESTRATEGIA_* const \
9295                 RestartStrategy::as_str returns — divergence signals a \
9296                 silent detour off the substrate-primitive accessor"
9297            );
9298            let via_into: &'static str = variant.into();
9299            assert_eq!(
9300                via_into, via_method,
9301                "Into<&'static str>::into on &RestartStrategy::{variant:?} \
9302                 must byte-equal RestartStrategy::as_str on the same input — \
9303                 the blanket-derived Into shape must resolve to the same \
9304                 as_str dispatch as the explicit From impl"
9305            );
9306        }
9307        assert_eq!(
9308            [ONE_FOR_ONE, ONE_FOR_ALL, REST_FOR_ONE, SIMPLE_ONE_FOR_ONE],
9309            [
9310                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
9311                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
9312                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
9313                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
9314            ],
9315            "const-context RestartStrategy::as_str must resolve to the \
9316             four lifted SUPERVISOR_ESTRATEGIA_* consts — the borrowed-\
9317             input From<&RestartStrategy> for &'static str impl inherits \
9318             its `'static` lifetime promise from the same accessor the \
9319             owned-input sibling routes through"
9320        );
9321    }
9322
9323    #[test]
9324    fn restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
9325        // Cross-axis partition pin: the paired trait-idiomatic
9326        // owned-input `From<RestartStrategy> for &'static str` (523157d
9327        // campaign-shape) and borrowed-input `From<&RestartStrategy> for
9328        // &'static str` (this lift) forward projections must resolve
9329        // identically on every arm, locking the two input-shape paths
9330        // together so any future detour trips at caixa-core test time.
9331        // Then a witness that a `.iter().map(Into::into)` pipe over
9332        // [`RestartStrategy::ALL`] (whose iterator yields
9333        // `&RestartStrategy`) materializes the four-arm accept-set
9334        // through the borrowed-input axis alone — the exact shape a
9335        // future wasm-operator per-supervisor sibling-restart-strategy
9336        // diagnostic line, a future substrate-wide per-arm diagnostic
9337        // column, or a
9338        // `HashMap::<&'static str, RestartStrategy>::from_iter(
9339        //     RestartStrategy::ALL.iter().map(|s| (s.into(), *s)))`-style
9340        // per-strategy lookup reaches through — closing the two-way
9341        // owned/borrowed input-shape symmetry on the forward-projection
9342        // trait-idiomatic axis. Peer of the sibling
9343        // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
9344        // (64aa742) /
9345        // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
9346        // (5ab993a) /
9347        // [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
9348        // (807b0b5) partition pins on the sibling closed-set typed-enum
9349        // discriminator axes — extends the borrowed-input axis
9350        // discipline onto the first M2 OTP-shape sibling-restart
9351        // closed-set typed enum on the caixa surface. Also closes the
9352        // direct two-way `&Self → &'static str → Self` round-trip via
9353        // the paired [`TryFrom<&str>`] axis — unlike the peer
9354        // [`crate::CaixaKind`] axis pair (whose forward `From` emits
9355        // lowercase Portuguese diagnostic bytes while the reverse
9356        // `TryFrom` parses `PascalCase` wire bytes, forcing the round-
9357        // trip through an intermediate wire-vocab hop), the
9358        // [`RestartStrategy::as_str`] emit and
9359        // [`RestartStrategy::from_wire`] parse share the same
9360        // `PascalCase` vocabulary by construction, so the borrowed-
9361        // input forward axis and the reverse axis compose directly.
9362        for &variant in RestartStrategy::ALL {
9363            let owned: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
9364            let borrowed: &'static str = <&'static str as From<&RestartStrategy>>::from(&variant);
9365            assert_eq!(
9366                owned, borrowed,
9367                "From<RestartStrategy> and From<&RestartStrategy> for \
9368                 &'static str must resolve identically on \
9369                 RestartStrategy::{variant:?} — divergence signals the \
9370                 owned-input and borrowed-input forward-projection paths \
9371                 have drifted onto different emit-sets"
9372            );
9373        }
9374        let via_iter: Vec<&'static str> = RestartStrategy::ALL.iter().map(Into::into).collect();
9375        let via_method: Vec<&'static str> =
9376            RestartStrategy::ALL.iter().map(|s| s.as_str()).collect();
9377        assert_eq!(
9378            via_iter, via_method,
9379            "`.iter().map(Into::into)` over RestartStrategy::ALL must \
9380             byte-equal `.iter().map(|s| s.as_str())` on every arm — the \
9381             borrowed-input `From<&RestartStrategy> for &'static str` \
9382             axis is what makes the `.iter().map(Into::into)` shape route \
9383             through the substrate-primitive `RestartStrategy::as_str` \
9384             accessor rather than through a per-call-site `.copied()` / \
9385             dereference detour"
9386        );
9387        for variant in RestartStrategy::ALL {
9388            let emitted: &'static str = variant.into();
9389            let re_parsed: Result<RestartStrategy, ()> =
9390                <RestartStrategy as TryFrom<&str>>::try_from(emitted);
9391            assert_eq!(
9392                re_parsed,
9393                Ok(*variant),
9394                "trait-idiomatic borrowed-input forward-projection + \
9395                 reverse-projection axis pair must round-trip \
9396                 &RestartStrategy::{variant:?} through `.into::<&'static \
9397                 str>()` (via the borrowed-input axis) and back through \
9398                 `TryFrom<&str>` — a break signals the borrowed-input \
9399                 forward-emit and reverse-parse axes have drifted onto \
9400                 different vocabularies"
9401            );
9402        }
9403    }
9404
9405    #[test]
9406    fn restart_strategy_from_into_owned_string_routes_through_as_str_accessor() {
9407        // Fail-before-pass-after byte-parity pin on the newly lifted
9408        // `impl From<RestartStrategy> for String` — asserts the
9409        // owned-`String`-returning standard-library trait impl and the
9410        // substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
9411        // accessor resolve to the same four-arm emit-set across every
9412        // arm the exhaustive [`RestartStrategy::ALL`] slice enumerates.
9413        // Rust's standard library does not carry a blanket
9414        // `impl<T: AsRef<str>> From<T> for String` (nor an
9415        // `impl<T: fmt::Display> From<T> for String`), so the
9416        // owned-`String` forward-projection axis is a distinct
9417        // trait-idiomatic surface that a
9418        // `let key: String = strategy.into();`-shaped call site
9419        // reaches through this impl and no other — the paired sibling
9420        // `From<RestartStrategy> for &'static str` impl forces every
9421        // owned-`String` call site through an explicit
9422        // `.to_owned()` / `String::from` restatement.
9423        for &variant in RestartStrategy::ALL {
9424            let via_trait: String = <String as From<RestartStrategy>>::from(variant);
9425            let via_method: &'static str = variant.as_str();
9426            assert_eq!(
9427                via_trait.as_str(),
9428                via_method,
9429                "From<RestartStrategy> for String impl must round-trip \
9430                 RestartStrategy::{variant:?} to the same lifted \
9431                 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
9432                 returns — divergence signals a silent detour off the \
9433                 substrate-primitive accessor"
9434            );
9435            let via_into: String = variant.into();
9436            assert_eq!(
9437                via_into.as_str(),
9438                via_method,
9439                "Into<String>::into on RestartStrategy::{variant:?} must \
9440                 byte-equal RestartStrategy::as_str on the same input — the \
9441                 blanket-derived Into shape must resolve to the same as_str \
9442                 dispatch as the explicit From impl"
9443            );
9444        }
9445    }
9446
9447    #[test]
9448    fn restart_strategy_from_into_owned_string_and_static_str_agree_on_every_arm() {
9449        // Cross-axis partition pin: the paired trait-idiomatic
9450        // owned-`String` `From<RestartStrategy> for String` (this lift)
9451        // and owned-`&'static str` `From<RestartStrategy> for &'static
9452        // str` (523157d) forward projections must resolve identically
9453        // on every arm, locking the two return-type-shape paths
9454        // together so any future detour trips at caixa-core test time.
9455        // Also byte-parity witness against the sibling
9456        // [`ToString::to_string`] surface routed through
9457        // [`std::fmt::Display`] — the three owned-heap-string paths
9458        // (`.into::<String>()`, `String::from`, `.to_string()`) must
9459        // resolve identically on every arm so a future consumer that
9460        // picks any of the three lands on the same lifted
9461        // SUPERVISOR_ESTRATEGIA_* const. Then a direct round-trip
9462        // witness through the paired trait-idiomatic reverse
9463        // [`TryFrom<&str>`] axis on the owned-`String`'s
9464        // [`String::as_str`] borrow that closes the two-way
9465        // `Self → String → Self` round-trip on the trait-idiomatic
9466        // owned-`String` forward + reverse axis pair.
9467        for &variant in RestartStrategy::ALL {
9468            let owned_string: String = <String as From<RestartStrategy>>::from(variant);
9469            let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
9470            assert_eq!(
9471                owned_string.as_str(),
9472                owned_static,
9473                "From<RestartStrategy> for String and From<RestartStrategy> \
9474                 for &'static str must resolve identically on \
9475                 RestartStrategy::{variant:?} — divergence signals the \
9476                 owned-`String` and owned-`&'static str` forward-projection \
9477                 return-type-shape paths have drifted onto different \
9478                 emit-sets"
9479            );
9480            let via_to_string: String = variant.to_string();
9481            assert_eq!(
9482                owned_string, via_to_string,
9483                "From<RestartStrategy> for String must byte-equal \
9484                 RestartStrategy::to_string on RestartStrategy::{variant:?} — \
9485                 divergence signals the trait-idiomatic owned-`String` \
9486                 forward-projection axis and the ToString-through-Display \
9487                 axis have drifted onto different emit-sets"
9488            );
9489        }
9490        let via_iter: Vec<String> = RestartStrategy::ALL
9491            .iter()
9492            .copied()
9493            .map(String::from)
9494            .collect();
9495        let via_method: Vec<String> = RestartStrategy::ALL
9496            .iter()
9497            .map(|s| s.as_str().to_owned())
9498            .collect();
9499        assert_eq!(
9500            via_iter, via_method,
9501            "`.iter().copied().map(String::from)` over RestartStrategy::ALL \
9502             must byte-equal `.iter().map(|s| s.as_str().to_owned())` on \
9503             every arm — the owned-`String` `From<RestartStrategy> for \
9504             String` axis is what makes the `String::from` composition \
9505             route through the substrate-primitive `RestartStrategy::as_str` \
9506             accessor rather than through a per-call-site `.to_owned()` / \
9507             `String::from(strategy.as_str())` detour"
9508        );
9509        for &variant in RestartStrategy::ALL {
9510            let emitted: String = variant.into();
9511            let re_parsed: Result<RestartStrategy, ()> =
9512                <RestartStrategy as TryFrom<&str>>::try_from(emitted.as_str());
9513            assert_eq!(
9514                re_parsed,
9515                Ok(variant),
9516                "trait-idiomatic owned-`String` forward-projection + \
9517                 reverse-projection axis pair must round-trip \
9518                 RestartStrategy::{variant:?} through `.into::<String>()` \
9519                 and back through `TryFrom<&str>` on the owned-`String`'s \
9520                 String::as_str borrow — a break signals the owned-`String` \
9521                 forward-emit and reverse-parse axes have drifted onto \
9522                 different vocabularies"
9523            );
9524        }
9525    }
9526
9527    #[test]
9528    fn restart_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor() {
9529        // Fail-before-pass-after byte-parity pin on the newly lifted
9530        // `impl From<&RestartStrategy> for String` — asserts the
9531        // borrowed-input owned-`String`-returning standard-library trait
9532        // impl and the substrate-primitive [`RestartStrategy::as_str`]
9533        // `pub const fn` accessor resolve to the same four-arm emit-set
9534        // across every arm the exhaustive [`RestartStrategy::ALL`] slice
9535        // enumerates. Rust's standard library does not carry a blanket
9536        // `impl<T: AsRef<str>> From<&T> for String` (nor an
9537        // `impl<T: fmt::Display> From<&T> for String`), so the
9538        // borrowed-input owned-`String` forward-projection axis is a
9539        // distinct trait-idiomatic surface that a
9540        // `let key: String = (&strategy).into();`-shaped call site
9541        // reaches through this impl and no other — the paired sibling
9542        // `From<RestartStrategy> for String` impl forces every
9543        // borrowed-input call site through an explicit `Copy` deref
9544        // (`String::from(*strategy)`) or an `.as_str().to_owned()` /
9545        // `.to_string()` detour.
9546        for &variant in RestartStrategy::ALL {
9547            let via_trait: String = <String as From<&RestartStrategy>>::from(&variant);
9548            let via_method: &'static str = variant.as_str();
9549            assert_eq!(
9550                via_trait.as_str(),
9551                via_method,
9552                "From<&RestartStrategy> for String impl must round-trip \
9553                 &RestartStrategy::{variant:?} to the same lifted \
9554                 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
9555                 returns — divergence signals a silent detour off the \
9556                 substrate-primitive accessor"
9557            );
9558            let via_into: String = (&variant).into();
9559            assert_eq!(
9560                via_into.as_str(),
9561                via_method,
9562                "Into<String>::into on &RestartStrategy::{variant:?} must \
9563                 byte-equal RestartStrategy::as_str on the same input — the \
9564                 blanket-derived Into shape must resolve to the same as_str \
9565                 dispatch as the explicit From impl"
9566            );
9567        }
9568    }
9569
9570    #[test]
9571    fn restart_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm() {
9572        // Cross-axis partition pin: the newly lifted trait-idiomatic
9573        // borrowed-input owned-`String` `From<&RestartStrategy> for
9574        // String` (this lift), the paired owned-input owned-`String`
9575        // `From<RestartStrategy> for String` (7baa18a), the paired
9576        // borrowed-input owned-`&'static str` `From<&RestartStrategy>
9577        // for &'static str` (e941836), and the paired owned-input
9578        // owned-`&'static str` `From<RestartStrategy> for &'static str`
9579        // (523157d) — every corner of the `{Self, &Self} × {&'static
9580        // str, String}` 2×2 trait-idiomatic projection family — must
9581        // resolve identically on every arm, locking the four
9582        // return-shape × input-shape paths together so any future
9583        // detour trips at caixa-core test time. Also byte-parity
9584        // witness against the sibling [`ToString::to_string`] surface
9585        // routed through [`std::fmt::Display`] and a direct round-trip
9586        // witness through the paired trait-idiomatic reverse
9587        // [`TryFrom<&str>`] axis on the owned-`String`'s
9588        // [`String::as_str`] borrow that closes the two-way
9589        // `&Self → String → Self` round-trip on the trait-idiomatic
9590        // borrowed-input owned-`String` forward + reverse axis pair.
9591        for &variant in RestartStrategy::ALL {
9592            let borrowed_string: String = <String as From<&RestartStrategy>>::from(&variant);
9593            let owned_string: String = <String as From<RestartStrategy>>::from(variant);
9594            let borrowed_static: &'static str =
9595                <&'static str as From<&RestartStrategy>>::from(&variant);
9596            let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
9597            assert_eq!(
9598                borrowed_string, owned_string,
9599                "From<&RestartStrategy> for String and From<RestartStrategy> \
9600                 for String must resolve identically on \
9601                 RestartStrategy::{variant:?} — divergence signals the \
9602                 borrowed-input and owned-input owned-`String` \
9603                 forward-projection input-shape paths have drifted onto \
9604                 different emit-sets"
9605            );
9606            assert_eq!(
9607                borrowed_string.as_str(),
9608                borrowed_static,
9609                "From<&RestartStrategy> for String and From<&RestartStrategy> \
9610                 for &'static str must resolve identically on \
9611                 RestartStrategy::{variant:?} — divergence signals the \
9612                 borrowed-input `&'static str` and owned-`String` \
9613                 return-shape paths have drifted onto different emit-sets"
9614            );
9615            assert_eq!(
9616                borrowed_string.as_str(),
9617                owned_static,
9618                "From<&RestartStrategy> for String and From<RestartStrategy> \
9619                 for &'static str must resolve identically on \
9620                 RestartStrategy::{variant:?} — divergence signals a break \
9621                 in the diagonal corner of the {{Self, &Self}} × \
9622                 {{&'static str, String}} 2×2 trait-idiomatic \
9623                 projection family"
9624            );
9625            let via_to_string: String = variant.to_string();
9626            assert_eq!(
9627                borrowed_string, via_to_string,
9628                "From<&RestartStrategy> for String must byte-equal \
9629                 RestartStrategy::to_string on RestartStrategy::{variant:?} — \
9630                 divergence signals the trait-idiomatic borrowed-input \
9631                 owned-`String` forward-projection axis and the \
9632                 ToString-through-Display axis have drifted onto different \
9633                 emit-sets"
9634            );
9635        }
9636        let via_iter: Vec<String> = RestartStrategy::ALL.iter().map(String::from).collect();
9637        let via_method: Vec<String> = RestartStrategy::ALL
9638            .iter()
9639            .map(|s| s.as_str().to_owned())
9640            .collect();
9641        assert_eq!(
9642            via_iter, via_method,
9643            "`.iter().map(String::from)` over RestartStrategy::ALL — a \
9644             call site whose iteration axis holds `&RestartStrategy` by \
9645             construction — must byte-equal `.iter().map(|s| \
9646             s.as_str().to_owned())` on every arm — the borrowed-input \
9647             owned-`String` `From<&RestartStrategy> for String` axis is \
9648             what makes the `String::from` composition route through the \
9649             substrate-primitive `RestartStrategy::as_str` accessor \
9650             without a spurious `Copy` deref (which would only be \
9651             reachable through the owned-input `From<RestartStrategy> for \
9652             String` axis by first calling `.copied()` on the iterator)"
9653        );
9654        for &variant in RestartStrategy::ALL {
9655            let emitted: String = (&variant).into();
9656            let re_parsed: Result<RestartStrategy, ()> =
9657                <RestartStrategy as TryFrom<&str>>::try_from(emitted.as_str());
9658            assert_eq!(
9659                re_parsed,
9660                Ok(variant),
9661                "trait-idiomatic borrowed-input owned-`String` \
9662                 forward-projection + reverse-projection axis pair must \
9663                 round-trip &RestartStrategy::{variant:?} through \
9664                 `.into::<String>()` on the borrowed-input surface and \
9665                 back through `TryFrom<&str>` on the owned-`String`'s \
9666                 String::as_str borrow — a break signals the \
9667                 borrowed-input owned-`String` forward-emit and \
9668                 reverse-parse axes have drifted onto different \
9669                 vocabularies"
9670            );
9671        }
9672    }
9673
9674    #[test]
9675    fn restart_strategy_from_into_static_cow_str_routes_through_as_str_accessor() {
9676        // Fail-before-pass-after byte-parity pin on the newly lifted
9677        // `impl From<RestartStrategy> for std::borrow::Cow<'static, str>` —
9678        // asserts the standard-library trait impl and the substrate-
9679        // primitive [`super::RestartStrategy::as_str`] `pub const fn`
9680        // accessor resolve to the same four-arm emit-set across every
9681        // arm the exhaustive [`super::RestartStrategy::ALL`] slice
9682        // enumerates. Rust's standard library does not carry a blanket
9683        // `impl<T: AsRef<str>> From<T> for Cow<'static, str>` (nor an
9684        // `impl<T: fmt::Display> From<T> for Cow<'static, str>`), so
9685        // the `Cow<'static, str>` forward-projection axis is a
9686        // distinct trait-idiomatic surface that a
9687        // `let key: Cow<'static, str> = strategy.into();`-shaped call
9688        // site reaches through this impl and no other — the paired
9689        // sibling `From<RestartStrategy> for &'static str` and
9690        // `From<RestartStrategy> for String` impls force every
9691        // `Cow<'static, str>`-parameterized call site through a
9692        // `Cow::Borrowed(strategy.as_str())` /
9693        // `Cow::Owned(strategy.to_string())` composition whose type
9694        // bounds have no compile-time link back to the substrate
9695        // primitive.
9696        //
9697        // Also asserts the projection lands on the zero-alloc
9698        // [`std::borrow::Cow::Borrowed`] arm (not the
9699        // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
9700        // [`super::RestartStrategy::as_str`] accessor's `&'static str`
9701        // return lifetime by construction makes the borrowed arm the
9702        // type-correct projection with no runtime allocation. Any
9703        // future silent detour that routes the impl through the owned
9704        // arm (an accidental `Cow::Owned(strategy.to_string())` rewrite
9705        // that would allocate on every call site where the
9706        // `&'static str` return of [`super::RestartStrategy::as_str`]
9707        // makes the zero-alloc borrowed projection type-correct) trips
9708        // at caixa-core test time under the
9709        // [`std::borrow::Cow::Borrowed`] discriminator witness rather
9710        // than at a downstream `Cow<'static, str>`-bound consumer's
9711        // silent allocation.
9712        //
9713        // First peer on the substrate-wide trait-idiomatic
9714        // [`std::borrow::Cow<'static, str>`] forward-projection family
9715        // to extend the axis off the top-level [`super::CaixaKind`]
9716        // enum (99c1735 owned-input, d45c409 borrowed-input) onto the
9717        // first M2 OTP-shape closed-set fieldless typed enum on the
9718        // caixa surface.
9719        for &variant in RestartStrategy::ALL {
9720            let via_trait: std::borrow::Cow<'static, str> =
9721                <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
9722            let via_method: &'static str = variant.as_str();
9723            assert_eq!(
9724                via_trait.as_ref(),
9725                via_method,
9726                "From<RestartStrategy> for Cow<'static, str> impl must \
9727                 round-trip RestartStrategy::{variant:?} to the same \
9728                 lifted SUPERVISOR_ESTRATEGIA_* const \
9729                 RestartStrategy::as_str returns — divergence signals a \
9730                 silent detour off the substrate-primitive accessor"
9731            );
9732            assert!(
9733                matches!(via_trait, std::borrow::Cow::Borrowed(_)),
9734                "From<RestartStrategy> for Cow<'static, str> impl must \
9735                 land on the zero-alloc Cow::Borrowed arm on \
9736                 RestartStrategy::{variant:?} — a Cow::Owned outcome \
9737                 signals the projection has silently allocated where \
9738                 the substrate-primitive RestartStrategy::as_str \
9739                 `&'static str` return makes the borrowed arm the \
9740                 type-correct projection"
9741            );
9742            let via_into: std::borrow::Cow<'static, str> = variant.into();
9743            assert_eq!(
9744                via_into.as_ref(),
9745                via_method,
9746                "Into<Cow<'static, str>>::into on \
9747                 RestartStrategy::{variant:?} must byte-equal \
9748                 RestartStrategy::as_str on the same input — the \
9749                 blanket-derived Into shape must resolve to the same \
9750                 as_str dispatch as the explicit From impl"
9751            );
9752            assert!(
9753                matches!(via_into, std::borrow::Cow::Borrowed(_)),
9754                "Into<Cow<'static, str>>::into on \
9755                 RestartStrategy::{variant:?} must land on the \
9756                 zero-alloc Cow::Borrowed arm — the blanket-derived \
9757                 Into shape must resolve to the same Cow::Borrowed \
9758                 dispatch as the explicit From impl"
9759            );
9760        }
9761    }
9762
9763    #[test]
9764    fn restart_strategy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
9765        // Cross-axis partition pin: the newly lifted trait-idiomatic
9766        // `From<RestartStrategy> for std::borrow::Cow<'static, str>`
9767        // (this lift), the paired owned-input `From<RestartStrategy>
9768        // for &'static str` (523157d), and the paired owned-input
9769        // `From<RestartStrategy> for String` (7baa18a) forward
9770        // projections must resolve identically on every arm, locking
9771        // the three return-shape paths together by construction so any
9772        // future detour trips at caixa-core test time. Also byte-parity
9773        // witness against the sibling [`ToString::to_string`] surface
9774        // routed through [`std::fmt::Display`] — every owned-heap-
9775        // string path (the `Cow::Owned` promotion of this axis's
9776        // `.into_owned()`, `From<RestartStrategy> for String`, and
9777        // `.to_string()`) resolves to the same lifted
9778        // [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const per arm.
9779        //
9780        // Then a `.iter().copied().map(std::borrow::Cow::from)` pipe
9781        // witness over [`super::RestartStrategy::ALL`] that
9782        // materializes the four-arm accept-set through the
9783        // [`std::borrow::Cow<'static, str>`] axis alone — the exact
9784        // shape a future `axum::response::IntoResponse` per-strategy
9785        // rejection-body composer, a future M4 admission-webhook
9786        // per-strategy rejection-reason emitter whose typing rules out
9787        // the sibling [`AsRef<str>`] borrowed return, or a future
9788        // substrate-wide per-strategy diagnostic surface that binds
9789        // through a [`Cow<'static, str>`] boundary reaches through.
9790        // The pipe witness also pins the zero-alloc discipline: every
9791        // element in the collected vector satisfies the
9792        // [`std::borrow::Cow::Borrowed`] arm predicate, so a future
9793        // accidental silent-allocation regression on the pipe's
9794        // iteration axis is a caixa-core-test-time failure.
9795        for &variant in RestartStrategy::ALL {
9796            let via_cow: std::borrow::Cow<'static, str> =
9797                <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
9798            let via_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
9799            let via_string: String = <String as From<RestartStrategy>>::from(variant);
9800            assert_eq!(
9801                via_cow.as_ref(),
9802                via_static,
9803                "From<RestartStrategy> for Cow<'static, str> and \
9804                 From<RestartStrategy> for &'static str must resolve \
9805                 identically on RestartStrategy::{variant:?} — \
9806                 divergence signals the Cow<'static, str> and \
9807                 &'static str return-shape paths have drifted onto \
9808                 different emit-sets"
9809            );
9810            assert_eq!(
9811                via_cow.as_ref(),
9812                via_string.as_str(),
9813                "From<RestartStrategy> for Cow<'static, str> and \
9814                 From<RestartStrategy> for String must resolve \
9815                 identically on RestartStrategy::{variant:?} — \
9816                 divergence signals the Cow<'static, str> and String \
9817                 return-shape paths have drifted onto different \
9818                 emit-sets"
9819            );
9820            let via_to_string: String = variant.to_string();
9821            assert_eq!(
9822                via_cow.as_ref(),
9823                via_to_string.as_str(),
9824                "From<RestartStrategy> for Cow<'static, str> must \
9825                 byte-equal RestartStrategy::to_string on \
9826                 RestartStrategy::{variant:?} — divergence signals the \
9827                 trait-idiomatic Cow<'static, str> forward-projection \
9828                 axis and the ToString-through-Display axis have \
9829                 drifted onto different emit-sets"
9830            );
9831        }
9832        let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
9833            .iter()
9834            .copied()
9835            .map(std::borrow::Cow::from)
9836            .collect();
9837        let via_method: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
9838            .iter()
9839            .map(|s| std::borrow::Cow::Borrowed(s.as_str()))
9840            .collect();
9841        assert_eq!(
9842            via_iter, via_method,
9843            "`.iter().copied().map(Cow::from)` over \
9844             RestartStrategy::ALL must byte-equal `.iter().map(|s| \
9845             Cow::Borrowed(s.as_str()))` on every arm — the \
9846             trait-idiomatic `From<RestartStrategy> for Cow<'static, \
9847             str>` axis is what makes the `Cow::from` composition \
9848             route through the substrate-primitive \
9849             `RestartStrategy::as_str` accessor with the zero-alloc \
9850             Cow::Borrowed arm by construction, rather than a \
9851             per-call-site `Cow::Owned(strategy.to_string())` \
9852             allocation"
9853        );
9854        for cow in &via_iter {
9855            assert!(
9856                matches!(cow, std::borrow::Cow::Borrowed(_)),
9857                "every element of the \
9858                 .iter().copied().map(Cow::from) pipe over \
9859                 RestartStrategy::ALL must land on the zero-alloc \
9860                 Cow::Borrowed arm — a Cow::Owned outcome on any arm \
9861                 signals the pipe's iteration axis has silently \
9862                 allocated where the substrate-primitive \
9863                 RestartStrategy::as_str `&'static str` return makes \
9864                 the borrowed arm the type-correct projection"
9865            );
9866        }
9867    }
9868
9869    #[test]
9870    fn restart_strategy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor() {
9871        // Fail-before-pass-after byte-parity pin on the newly lifted
9872        // `impl From<&RestartStrategy> for std::borrow::Cow<'static, str>` —
9873        // asserts the borrowed-input standard-library trait impl and
9874        // the substrate-primitive [`super::RestartStrategy::as_str`]
9875        // `pub const fn` accessor resolve to the same four-arm emit-
9876        // set across every arm the exhaustive
9877        // [`super::RestartStrategy::ALL`] slice enumerates. Rust's
9878        // standard library does not carry a blanket
9879        // `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor a
9880        // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`), so
9881        // the borrowed-input `Cow<'static, str>` forward-projection
9882        // axis is a distinct trait-idiomatic surface that a
9883        // `let key: Cow<'static, str> = (&strategy).into();`-shaped
9884        // call site or a
9885        // `RestartStrategy::ALL.iter().map(Cow::from)`-shaped pipe
9886        // reaches through this impl and no other — the paired owned-
9887        // input `From<RestartStrategy> for Cow<'static, str>` impl
9888        // (7dd28b3) forces every borrowed-input call site through an
9889        // explicit `Copy` deref (`Cow::from(*strategy)`) or a
9890        // `Cow::Borrowed(strategy.as_str())` open-code whose type
9891        // bounds have no compile-time link back to the substrate
9892        // primitive.
9893        //
9894        // Also asserts the projection lands on the zero-alloc
9895        // [`std::borrow::Cow::Borrowed`] arm (not the
9896        // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
9897        // [`super::RestartStrategy::as_str`] accessor's `&'static str`
9898        // return lifetime by construction makes the borrowed arm the
9899        // type-correct projection with no runtime allocation on the
9900        // borrowed-input surface just as on the paired owned-input
9901        // surface.
9902        //
9903        // Second peer on the substrate-wide trait-idiomatic
9904        // [`std::borrow::Cow<'static, str>`] forward-projection family
9905        // on this enum — closes the `{Self, &Self}` input-shape
9906        // corner of the [`Cow<'static, str>`] axis on the first M2
9907        // OTP-shape closed-set fieldless typed enum peer on the caixa
9908        // surface (`:supervisor :estrategia`), exactly as d45c409
9909        // closed it on the top-level [`super::CaixaKind`] one commit
9910        // after the owning half (99c1735) landed. Every future
9911        // closed-set fieldless typed enum peer on the substrate is a
9912        // future target of the campaign.
9913        for &variant in RestartStrategy::ALL {
9914            let via_trait: std::borrow::Cow<'static, str> =
9915                <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&variant);
9916            let via_method: &'static str = variant.as_str();
9917            assert_eq!(
9918                via_trait.as_ref(),
9919                via_method,
9920                "From<&RestartStrategy> for Cow<'static, str> impl must \
9921                 round-trip &RestartStrategy::{variant:?} to the same \
9922                 lifted SUPERVISOR_ESTRATEGIA_* const \
9923                 RestartStrategy::as_str returns — divergence signals a \
9924                 silent detour off the substrate-primitive accessor"
9925            );
9926            assert!(
9927                matches!(via_trait, std::borrow::Cow::Borrowed(_)),
9928                "From<&RestartStrategy> for Cow<'static, str> impl must \
9929                 land on the zero-alloc Cow::Borrowed arm on \
9930                 &RestartStrategy::{variant:?} — a Cow::Owned outcome \
9931                 signals the projection has silently allocated where \
9932                 the substrate-primitive RestartStrategy::as_str \
9933                 `&'static str` return makes the borrowed arm the \
9934                 type-correct projection"
9935            );
9936            let via_into: std::borrow::Cow<'static, str> = (&variant).into();
9937            assert_eq!(
9938                via_into.as_ref(),
9939                via_method,
9940                "Into<Cow<'static, str>>::into on \
9941                 &RestartStrategy::{variant:?} must byte-equal \
9942                 RestartStrategy::as_str on the same input — the \
9943                 blanket-derived Into shape must resolve to the same \
9944                 as_str dispatch as the explicit From impl"
9945            );
9946            assert!(
9947                matches!(via_into, std::borrow::Cow::Borrowed(_)),
9948                "Into<Cow<'static, str>>::into on \
9949                 &RestartStrategy::{variant:?} must land on the \
9950                 zero-alloc Cow::Borrowed arm — the blanket-derived \
9951                 Into shape must resolve to the same Cow::Borrowed \
9952                 dispatch as the explicit From impl"
9953            );
9954        }
9955    }
9956
9957    #[test]
9958    fn restart_strategy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
9959        // Cross-axis partition pin: the newly lifted trait-idiomatic
9960        // borrowed-input `From<&RestartStrategy> for
9961        // std::borrow::Cow<'static, str>` (this lift), the paired
9962        // owned-input `From<RestartStrategy> for
9963        // std::borrow::Cow<'static, str>` (7dd28b3), the paired
9964        // borrowed-input owned-`&'static str` `From<&RestartStrategy>
9965        // for &'static str`, and the paired borrowed-input owned-
9966        // `String` `From<&RestartStrategy> for String` must resolve
9967        // identically on every arm, locking the four
9968        // return-shape × input-shape paths together by construction so
9969        // any future detour trips at caixa-core test time. Also byte-
9970        // parity witness against the sibling [`ToString::to_string`]
9971        // surface routed through [`std::fmt::Display`] — every owned-
9972        // heap-string path (this axis's `.into_owned()` promotion, the
9973        // paired [`From<&RestartStrategy> for String`], and
9974        // `.to_string()`) resolves to the same lifted
9975        // [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const per arm.
9976        //
9977        // Then a `.iter().map(std::borrow::Cow::from)` pipe witness
9978        // over [`super::RestartStrategy::ALL`] — whose iterator yields
9979        // `&RestartStrategy` by construction, so the borrowed-input
9980        // [`Cow<'static, str>`] axis is what routes the pipe through
9981        // the substrate-primitive [`super::RestartStrategy::as_str`]
9982        // accessor without a spurious [`Copy`] deref (which would only
9983        // be reachable through the owned-input
9984        // [`From<RestartStrategy> for Cow<'static, str>`] axis by
9985        // first calling `.copied()` on the iterator). The pipe witness
9986        // also pins the zero-alloc discipline: every element in the
9987        // collected vector satisfies the [`std::borrow::Cow::Borrowed`]
9988        // arm predicate, so a future accidental silent-allocation
9989        // regression on the pipe's iteration axis is a caixa-core-
9990        // test-time failure.
9991        for &strategy in RestartStrategy::ALL {
9992            let borrowed_cow: std::borrow::Cow<'static, str> =
9993                <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&strategy);
9994            let owned_cow: std::borrow::Cow<'static, str> =
9995                <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(strategy);
9996            let borrowed_static: &'static str =
9997                <&'static str as From<&RestartStrategy>>::from(&strategy);
9998            let borrowed_string: String = <String as From<&RestartStrategy>>::from(&strategy);
9999            assert_eq!(
10000                borrowed_cow, owned_cow,
10001                "From<&RestartStrategy> for Cow<'static, str> and \
10002                 From<RestartStrategy> for Cow<'static, str> must \
10003                 resolve identically on RestartStrategy::{strategy:?} — \
10004                 divergence signals the borrowed-input and owned-input \
10005                 Cow<'static, str> forward-projection input-shape \
10006                 paths have drifted onto different emit-sets"
10007            );
10008            assert_eq!(
10009                borrowed_cow.as_ref(),
10010                borrowed_static,
10011                "From<&RestartStrategy> for Cow<'static, str> and \
10012                 From<&RestartStrategy> for &'static str must resolve \
10013                 identically on RestartStrategy::{strategy:?} — \
10014                 divergence signals the borrowed-input Cow<'static, \
10015                 str> and &'static str return-shape paths have drifted \
10016                 onto different emit-sets"
10017            );
10018            assert_eq!(
10019                borrowed_cow.as_ref(),
10020                borrowed_string.as_str(),
10021                "From<&RestartStrategy> for Cow<'static, str> and \
10022                 From<&RestartStrategy> for String must resolve \
10023                 identically on RestartStrategy::{strategy:?} — \
10024                 divergence signals the borrowed-input Cow<'static, \
10025                 str> and owned-`String` return-shape paths have \
10026                 drifted onto different emit-sets"
10027            );
10028            let via_to_string: String = strategy.to_string();
10029            assert_eq!(
10030                borrowed_cow.as_ref(),
10031                via_to_string.as_str(),
10032                "From<&RestartStrategy> for Cow<'static, str> must \
10033                 byte-equal RestartStrategy::to_string on \
10034                 RestartStrategy::{strategy:?} — divergence signals \
10035                 the trait-idiomatic borrowed-input Cow<'static, str> \
10036                 forward-projection axis and the ToString-through-\
10037                 Display axis have drifted onto different emit-sets"
10038            );
10039        }
10040        let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
10041            .iter()
10042            .map(std::borrow::Cow::from)
10043            .collect();
10044        let via_method: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
10045            .iter()
10046            .map(|s| std::borrow::Cow::Borrowed(s.as_str()))
10047            .collect();
10048        assert_eq!(
10049            via_iter, via_method,
10050            "`.iter().map(Cow::from)` over RestartStrategy::ALL — a \
10051             call site whose iteration axis holds `&RestartStrategy` \
10052             by construction — must byte-equal `.iter().map(|s| \
10053             Cow::Borrowed(s.as_str()))` on every arm — the borrowed-\
10054             input Cow<'static, str> `From<&RestartStrategy> for \
10055             Cow<'static, str>` axis is what makes the `Cow::from` \
10056             composition route through the substrate-primitive \
10057             `RestartStrategy::as_str` accessor with the zero-alloc \
10058             Cow::Borrowed arm by construction and without a spurious \
10059             `Copy` deref (which would only be reachable through the \
10060             owned-input `From<RestartStrategy> for Cow<'static, str>` \
10061             axis by first calling `.copied()` on the iterator)"
10062        );
10063        for cow in &via_iter {
10064            assert!(
10065                matches!(cow, std::borrow::Cow::Borrowed(_)),
10066                "every element of the .iter().map(Cow::from) pipe \
10067                 over RestartStrategy::ALL must land on the zero-\
10068                 alloc Cow::Borrowed arm — a Cow::Owned outcome on \
10069                 any arm signals the pipe's iteration axis has \
10070                 silently allocated where the substrate-primitive \
10071                 RestartStrategy::as_str `&'static str` return makes \
10072                 the borrowed arm the type-correct projection"
10073            );
10074        }
10075    }
10076
10077    #[test]
10078    fn restart_strategy_from_into_box_str_routes_through_as_str_accessor() {
10079        // Fail-before-pass-after byte-parity pin on the newly lifted
10080        // `impl From<RestartStrategy> for Box<str>` — asserts the
10081        // owned-input standard-library trait impl and the
10082        // substrate-primitive [`super::RestartStrategy::as_str`]
10083        // `pub const fn` accessor resolve to the same four-arm emit-
10084        // set across every arm the exhaustive
10085        // [`super::RestartStrategy::ALL`] slice enumerates. Opens the
10086        // substrate-wide `Box<str>` forward-projection campaign tier
10087        // on the first M2 OTP-shape closed-set fieldless typed enum
10088        // peer on the caixa surface (`:supervisor :estrategia`),
10089        // immediately after the paired `Cow<'static, str>` axis
10090        // (7dd28b3 / ee577fd) closed the
10091        // `{Self, &Self} × {&'static str, String, Cow<'static, str>}`
10092        // 2×3 corner on this enum. Rust's standard library carries
10093        // `impl From<&str> for Box<str>` and
10094        // `impl From<String> for Box<str>` but no blanket
10095        // `impl<T: AsRef<str>> From<T> for Box<str>`, so this axis is
10096        // a distinct trait-idiomatic surface that a
10097        // `let key: Box<str> = strategy.into();`-shaped call site
10098        // reaches through this impl and no other — a paired
10099        // `Box::from(strategy.as_str())` open-code has no compile-
10100        // time link back to the substrate primitive.
10101        for &variant in RestartStrategy::ALL {
10102            let via_trait: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
10103            let via_method: &'static str = variant.as_str();
10104            assert_eq!(
10105                via_trait.as_ref(),
10106                via_method,
10107                "From<RestartStrategy> for Box<str> impl must round-\
10108                 trip RestartStrategy::{variant:?} to the same lifted \
10109                 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
10110                 returns — divergence signals a silent detour off the \
10111                 substrate-primitive accessor"
10112            );
10113            let via_into: Box<str> = variant.into();
10114            assert_eq!(
10115                via_into.as_ref(),
10116                via_method,
10117                "Into<Box<str>>::into on RestartStrategy::{variant:?} \
10118                 must byte-equal RestartStrategy::as_str on the same \
10119                 input — the blanket-derived Into shape must resolve \
10120                 to the same as_str dispatch as the explicit From impl"
10121            );
10122        }
10123    }
10124
10125    #[test]
10126    fn restart_strategy_from_borrowed_into_box_str_routes_through_as_str_accessor() {
10127        // Fail-before-pass-after byte-parity pin on the newly lifted
10128        // `impl From<&RestartStrategy> for Box<str>` — asserts the
10129        // borrowed-input standard-library trait impl and the
10130        // substrate-primitive [`super::RestartStrategy::as_str`]
10131        // `pub const fn` accessor resolve to the same four-arm emit-
10132        // set across every arm the exhaustive
10133        // [`super::RestartStrategy::ALL`] slice enumerates. Rust's
10134        // standard library does not carry a blanket
10135        // `impl<T: AsRef<str>> From<&T> for Box<str>` (nor a
10136        // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`),
10137        // so the borrowed-input `Box<str>` forward-projection axis
10138        // is a distinct trait-idiomatic surface that a
10139        // `let key: Box<str> = (&strategy).into();`-shaped call site
10140        // or a `RestartStrategy::ALL.iter().map(Box::<str>::from)`-
10141        // shaped pipe reaches through this impl and no other — the
10142        // paired owned-input `From<RestartStrategy> for Box<str>`
10143        // impl (69ef45c) forces every borrowed-input call site
10144        // through an explicit `Copy` deref
10145        // (`Box::<str>::from((*strategy).as_str())`) or a
10146        // `Box::<str>::from(strategy.as_str())` open-code whose
10147        // type bounds have no compile-time link back to the
10148        // substrate primitive.
10149        //
10150        // Second peer on the substrate-wide trait-idiomatic
10151        // [`Box<str>`] forward-projection family on this enum —
10152        // closes the `{Self, &Self}` input-shape corner of the
10153        // [`Box<str>`] axis on the first M2 OTP-shape closed-set
10154        // fieldless typed enum peer on the caixa surface
10155        // (`:supervisor :estrategia`), exactly as ee577fd closed
10156        // the paired [`Cow<'static, str>`] axis one commit after
10157        // its owning half (7dd28b3) landed. Every future closed-
10158        // set fieldless typed enum peer on the substrate is a
10159        // future target of the campaign.
10160        //
10161        // Also byte-parity witness against the paired owned-input
10162        // [`From<RestartStrategy> for Box<str>`] and the sibling
10163        // borrowed-input [`From<&RestartStrategy> for &'static str`],
10164        // [`From<&RestartStrategy> for String`], and
10165        // [`From<&RestartStrategy> for Cow<'static, str>`]
10166        // return-shape axes — locking the four
10167        // return-shape × input-shape paths together by construction
10168        // so any future detour trips at caixa-core test time. Then a
10169        // `.iter().map(Box::<str>::from)` pipe witness over
10170        // [`super::RestartStrategy::ALL`] — whose iterator yields
10171        // `&RestartStrategy` by construction, so the borrowed-input
10172        // [`Box<str>`] axis is what routes the pipe through the
10173        // substrate-primitive [`super::RestartStrategy::as_str`]
10174        // accessor without a spurious [`Copy`] deref (which would
10175        // only be reachable through the owned-input
10176        // [`From<RestartStrategy> for Box<str>`] axis by first
10177        // calling `.copied()` on the iterator).
10178        for &variant in RestartStrategy::ALL {
10179            let via_trait: Box<str> = <Box<str> as From<&RestartStrategy>>::from(&variant);
10180            let via_method: &'static str = variant.as_str();
10181            assert_eq!(
10182                via_trait.as_ref(),
10183                via_method,
10184                "From<&RestartStrategy> for Box<str> impl must \
10185                 round-trip &RestartStrategy::{variant:?} to the same \
10186                 lifted SUPERVISOR_ESTRATEGIA_* const \
10187                 RestartStrategy::as_str returns — divergence signals \
10188                 a silent detour off the substrate-primitive accessor"
10189            );
10190            let via_into: Box<str> = (&variant).into();
10191            assert_eq!(
10192                via_into.as_ref(),
10193                via_method,
10194                "Into<Box<str>>::into on &RestartStrategy::{variant:?} \
10195                 must byte-equal RestartStrategy::as_str on the same \
10196                 input — the blanket-derived Into shape must resolve \
10197                 to the same as_str dispatch as the explicit From impl"
10198            );
10199            let owned_box: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
10200            assert_eq!(
10201                via_trait, owned_box,
10202                "From<&RestartStrategy> for Box<str> and \
10203                 From<RestartStrategy> for Box<str> must resolve \
10204                 identically on RestartStrategy::{variant:?} — \
10205                 divergence signals the borrowed-input and owned-input \
10206                 Box<str> forward-projection input-shape paths have \
10207                 drifted onto different emit-sets"
10208            );
10209            let borrowed_static: &'static str =
10210                <&'static str as From<&RestartStrategy>>::from(&variant);
10211            assert_eq!(
10212                via_trait.as_ref(),
10213                borrowed_static,
10214                "From<&RestartStrategy> for Box<str> and \
10215                 From<&RestartStrategy> for &'static str must resolve \
10216                 identically on RestartStrategy::{variant:?} — \
10217                 divergence signals the borrowed-input Box<str> and \
10218                 &'static str return-shape paths have drifted onto \
10219                 different emit-sets"
10220            );
10221            let borrowed_string: String = <String as From<&RestartStrategy>>::from(&variant);
10222            assert_eq!(
10223                via_trait.as_ref(),
10224                borrowed_string.as_str(),
10225                "From<&RestartStrategy> for Box<str> and \
10226                 From<&RestartStrategy> for String must resolve \
10227                 identically on RestartStrategy::{variant:?} — \
10228                 divergence signals the borrowed-input Box<str> and \
10229                 owned-`String` return-shape paths have drifted onto \
10230                 different emit-sets"
10231            );
10232            let borrowed_cow: std::borrow::Cow<'static, str> =
10233                <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&variant);
10234            assert_eq!(
10235                via_trait.as_ref(),
10236                borrowed_cow.as_ref(),
10237                "From<&RestartStrategy> for Box<str> and \
10238                 From<&RestartStrategy> for Cow<'static, str> must \
10239                 resolve identically on RestartStrategy::{variant:?} — \
10240                 divergence signals the borrowed-input Box<str> and \
10241                 Cow<'static, str> return-shape paths have drifted \
10242                 onto different emit-sets"
10243            );
10244        }
10245        let via_iter: Vec<Box<str>> = RestartStrategy::ALL.iter().map(Box::<str>::from).collect();
10246        let via_method: Vec<Box<str>> = RestartStrategy::ALL
10247            .iter()
10248            .map(|s| Box::<str>::from(s.as_str()))
10249            .collect();
10250        assert_eq!(
10251            via_iter, via_method,
10252            "`.iter().map(Box::<str>::from)` over \
10253             RestartStrategy::ALL — a call site whose iteration axis \
10254             holds `&RestartStrategy` by construction — must byte-\
10255             equal `.iter().map(|s| Box::<str>::from(s.as_str()))` \
10256             on every arm — the borrowed-input Box<str> \
10257             `From<&RestartStrategy> for Box<str>` axis is what \
10258             makes the `Box::<str>::from` composition route through \
10259             the substrate-primitive `RestartStrategy::as_str` \
10260             accessor without a spurious `Copy` deref (which would \
10261             only be reachable through the owned-input \
10262             `From<RestartStrategy> for Box<str>` axis by first \
10263             calling `.copied()` on the iterator)"
10264        );
10265    }
10266
10267    #[test]
10268    fn restart_strategy_from_into_arc_str_routes_through_as_str_accessor() {
10269        // Fail-before-pass-after byte-parity pin on the newly lifted
10270        // `impl From<RestartStrategy> for std::sync::Arc<str>` — asserts
10271        // the owned-input standard-library trait impl and the
10272        // substrate-primitive [`super::RestartStrategy::as_str`]
10273        // `pub const fn` accessor resolve to the same four-arm emit-
10274        // set across every arm the exhaustive
10275        // [`super::RestartStrategy::ALL`] slice enumerates. Opens the
10276        // substrate-wide [`std::sync::Arc<str>`] forward-projection
10277        // campaign tier on the first M2 OTP-shape closed-set fieldless
10278        // typed enum peer on the caixa surface
10279        // (`:supervisor :estrategia`), immediately after the paired
10280        // [`Box<str>`] axis (69ef45c / 59ae5dc) closed the
10281        // `{Self, &Self} × {&'static str, String, Cow<'static, str>,
10282        // Box<str>}` 2×4 corner on this enum. Rust's standard library
10283        // carries `impl From<&str> for std::sync::Arc<str>` and
10284        // `impl From<String> for std::sync::Arc<str>` but no blanket
10285        // `impl<T: AsRef<str>> From<T> for std::sync::Arc<str>` (nor
10286        // an `impl<T: fmt::Display> From<T> for std::sync::Arc<str>`),
10287        // so this axis is a distinct trait-idiomatic surface that a
10288        // `let key: std::sync::Arc<str> = strategy.into();`-shaped call
10289        // site reaches through this impl and no other — a paired
10290        // `std::sync::Arc::<str>::from(strategy.as_str())` open-code
10291        // has no compile-time link back to the substrate primitive,
10292        // and a two-step `std::sync::Arc::<str>::from(String::from(
10293        // strategy))` composition through the owned-`String` axis
10294        // allocates twice (once into the intermediate `String`, once
10295        // into the [`Arc<str>`] on the `From<String>` conversion)
10296        // where the single-step trait impl allocates once.
10297        //
10298        // Cross-axis byte-parity witness against the sibling owned-
10299        // input `{&'static str, String, Cow<'static, str>, Box<str>}`
10300        // return-shape axes — locking the five return-shape paths on
10301        // the owned-input surface together by construction so any
10302        // future detour off the substrate-primitive
10303        // [`super::RestartStrategy::as_str`] accessor trips at caixa-
10304        // core test time.
10305        for &variant in RestartStrategy::ALL {
10306            let via_trait: std::sync::Arc<str> =
10307                <std::sync::Arc<str> as From<RestartStrategy>>::from(variant);
10308            let via_method: &'static str = variant.as_str();
10309            assert_eq!(
10310                via_trait.as_ref(),
10311                via_method,
10312                "From<RestartStrategy> for std::sync::Arc<str> impl \
10313                 must round-trip RestartStrategy::{variant:?} to the \
10314                 same lifted SUPERVISOR_ESTRATEGIA_* const \
10315                 RestartStrategy::as_str returns — divergence signals \
10316                 a silent detour off the substrate-primitive accessor"
10317            );
10318            let via_into: std::sync::Arc<str> = variant.into();
10319            assert_eq!(
10320                via_into.as_ref(),
10321                via_method,
10322                "Into<std::sync::Arc<str>>::into on \
10323                 RestartStrategy::{variant:?} must byte-equal \
10324                 RestartStrategy::as_str on the same input — the \
10325                 blanket-derived Into shape must resolve to the same \
10326                 as_str dispatch as the explicit From impl"
10327            );
10328            let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
10329            assert_eq!(
10330                via_trait.as_ref(),
10331                owned_static,
10332                "From<RestartStrategy> for std::sync::Arc<str> and \
10333                 From<RestartStrategy> for &'static str must resolve \
10334                 identically on RestartStrategy::{variant:?} — \
10335                 divergence signals the owned-input std::sync::Arc<str> \
10336                 and &'static str return-shape paths have drifted onto \
10337                 different emit-sets"
10338            );
10339            let owned_string: String = <String as From<RestartStrategy>>::from(variant);
10340            assert_eq!(
10341                via_trait.as_ref(),
10342                owned_string.as_str(),
10343                "From<RestartStrategy> for std::sync::Arc<str> and \
10344                 From<RestartStrategy> for String must resolve \
10345                 identically on RestartStrategy::{variant:?} — \
10346                 divergence signals the owned-input std::sync::Arc<str> \
10347                 and owned-`String` return-shape paths have drifted \
10348                 onto different emit-sets"
10349            );
10350            let owned_cow: std::borrow::Cow<'static, str> =
10351                <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
10352            assert_eq!(
10353                via_trait.as_ref(),
10354                owned_cow.as_ref(),
10355                "From<RestartStrategy> for std::sync::Arc<str> and \
10356                 From<RestartStrategy> for Cow<'static, str> must \
10357                 resolve identically on RestartStrategy::{variant:?} — \
10358                 divergence signals the owned-input std::sync::Arc<str> \
10359                 and Cow<'static, str> return-shape paths have drifted \
10360                 onto different emit-sets"
10361            );
10362            let owned_box: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
10363            assert_eq!(
10364                via_trait.as_ref(),
10365                owned_box.as_ref(),
10366                "From<RestartStrategy> for std::sync::Arc<str> and \
10367                 From<RestartStrategy> for Box<str> must resolve \
10368                 identically on RestartStrategy::{variant:?} — \
10369                 divergence signals the owned-input std::sync::Arc<str> \
10370                 and Box<str> return-shape paths have drifted onto \
10371                 different emit-sets"
10372            );
10373        }
10374    }
10375
10376    #[test]
10377    fn restart_strategy_from_borrowed_into_arc_str_routes_through_as_str_accessor() {
10378        // Fail-before-pass-after byte-parity pin on the newly lifted
10379        // `impl From<&RestartStrategy> for std::sync::Arc<str>` —
10380        // asserts the borrowed-input standard-library trait impl and
10381        // the substrate-primitive [`super::RestartStrategy::as_str`]
10382        // `pub const fn` accessor resolve to the same four-arm emit-
10383        // set across every arm the exhaustive
10384        // [`super::RestartStrategy::ALL`] slice enumerates. Rust's
10385        // standard library does not carry a blanket
10386        // `impl<T: AsRef<str>> From<&T> for std::sync::Arc<str>` (nor
10387        // a `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`),
10388        // so the borrowed-input [`std::sync::Arc<str>`] forward-
10389        // projection axis is a distinct trait-idiomatic surface that a
10390        // `let key: std::sync::Arc<str> = (&strategy).into();`-shaped
10391        // call site or a
10392        // `RestartStrategy::ALL.iter().map(std::sync::Arc::<str>::from)`-
10393        // shaped pipe reaches through this impl and no other — the
10394        // paired owned-input
10395        // `From<RestartStrategy> for std::sync::Arc<str>` impl
10396        // (bca2ec8) forces every borrowed-input call site through an
10397        // explicit `Copy` deref
10398        // (`std::sync::Arc::<str>::from((*strategy).as_str())`) or a
10399        // `std::sync::Arc::<str>::from(strategy.as_str())` open-code
10400        // whose type bounds have no compile-time link back to the
10401        // substrate primitive.
10402        //
10403        // Second peer on the substrate-wide trait-idiomatic
10404        // [`std::sync::Arc<str>`] forward-projection family on this
10405        // enum — closes the `{Self, &Self}` input-shape corner of
10406        // the [`std::sync::Arc<str>`] axis on the first M2 OTP-shape
10407        // closed-set fieldless typed enum peer on the caixa surface
10408        // (`:supervisor :estrategia`), exactly as 59ae5dc closed the
10409        // paired [`Box<str>`] axis one commit after its owning half
10410        // (69ef45c) landed. Every future closed-set fieldless typed
10411        // enum peer on the substrate is a future target of the
10412        // campaign.
10413        //
10414        // Also byte-parity witness against the paired owned-input
10415        // [`From<RestartStrategy> for std::sync::Arc<str>`] and the
10416        // sibling borrowed-input
10417        // [`From<&RestartStrategy> for &'static str`],
10418        // [`From<&RestartStrategy> for String`],
10419        // [`From<&RestartStrategy> for Cow<'static, str>`], and
10420        // [`From<&RestartStrategy> for Box<str>`] return-shape axes —
10421        // locking the five return-shape × input-shape paths together
10422        // by construction so any future detour trips at caixa-core
10423        // test time. Then a
10424        // `.iter().map(std::sync::Arc::<str>::from)` pipe witness over
10425        // [`super::RestartStrategy::ALL`] — whose iterator yields
10426        // `&RestartStrategy` by construction, so the borrowed-input
10427        // [`std::sync::Arc<str>`] axis is what routes the pipe
10428        // through the substrate-primitive
10429        // [`super::RestartStrategy::as_str`] accessor without a
10430        // spurious [`Copy`] deref (which would only be reachable
10431        // through the owned-input
10432        // [`From<RestartStrategy> for std::sync::Arc<str>`] axis by
10433        // first calling `.copied()` on the iterator).
10434        for &variant in RestartStrategy::ALL {
10435            let via_trait: std::sync::Arc<str> =
10436                <std::sync::Arc<str> as From<&RestartStrategy>>::from(&variant);
10437            let via_method: &'static str = variant.as_str();
10438            assert_eq!(
10439                via_trait.as_ref(),
10440                via_method,
10441                "From<&RestartStrategy> for std::sync::Arc<str> impl \
10442                 must round-trip &RestartStrategy::{variant:?} to the \
10443                 same lifted SUPERVISOR_ESTRATEGIA_* const \
10444                 RestartStrategy::as_str returns — divergence signals \
10445                 a silent detour off the substrate-primitive accessor"
10446            );
10447            let via_into: std::sync::Arc<str> = (&variant).into();
10448            assert_eq!(
10449                via_into.as_ref(),
10450                via_method,
10451                "Into<std::sync::Arc<str>>::into on \
10452                 &RestartStrategy::{variant:?} must byte-equal \
10453                 RestartStrategy::as_str on the same input — the \
10454                 blanket-derived Into shape must resolve to the same \
10455                 as_str dispatch as the explicit From impl"
10456            );
10457            let owned_arc: std::sync::Arc<str> =
10458                <std::sync::Arc<str> as From<RestartStrategy>>::from(variant);
10459            assert_eq!(
10460                via_trait, owned_arc,
10461                "From<&RestartStrategy> for std::sync::Arc<str> and \
10462                 From<RestartStrategy> for std::sync::Arc<str> must \
10463                 resolve identically on RestartStrategy::{variant:?} — \
10464                 divergence signals the borrowed-input and owned-input \
10465                 std::sync::Arc<str> forward-projection input-shape \
10466                 paths have drifted onto different emit-sets"
10467            );
10468            let borrowed_static: &'static str =
10469                <&'static str as From<&RestartStrategy>>::from(&variant);
10470            assert_eq!(
10471                via_trait.as_ref(),
10472                borrowed_static,
10473                "From<&RestartStrategy> for std::sync::Arc<str> and \
10474                 From<&RestartStrategy> for &'static str must resolve \
10475                 identically on RestartStrategy::{variant:?} — \
10476                 divergence signals the borrowed-input \
10477                 std::sync::Arc<str> and &'static str return-shape \
10478                 paths have drifted onto different emit-sets"
10479            );
10480            let borrowed_string: String = <String as From<&RestartStrategy>>::from(&variant);
10481            assert_eq!(
10482                via_trait.as_ref(),
10483                borrowed_string.as_str(),
10484                "From<&RestartStrategy> for std::sync::Arc<str> and \
10485                 From<&RestartStrategy> for String must resolve \
10486                 identically on RestartStrategy::{variant:?} — \
10487                 divergence signals the borrowed-input \
10488                 std::sync::Arc<str> and owned-`String` return-shape \
10489                 paths have drifted onto different emit-sets"
10490            );
10491            let borrowed_cow: std::borrow::Cow<'static, str> =
10492                <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&variant);
10493            assert_eq!(
10494                via_trait.as_ref(),
10495                borrowed_cow.as_ref(),
10496                "From<&RestartStrategy> for std::sync::Arc<str> and \
10497                 From<&RestartStrategy> for Cow<'static, str> must \
10498                 resolve identically on RestartStrategy::{variant:?} — \
10499                 divergence signals the borrowed-input \
10500                 std::sync::Arc<str> and Cow<'static, str> return-shape \
10501                 paths have drifted onto different emit-sets"
10502            );
10503            let borrowed_box: Box<str> = <Box<str> as From<&RestartStrategy>>::from(&variant);
10504            assert_eq!(
10505                via_trait.as_ref(),
10506                borrowed_box.as_ref(),
10507                "From<&RestartStrategy> for std::sync::Arc<str> and \
10508                 From<&RestartStrategy> for Box<str> must resolve \
10509                 identically on RestartStrategy::{variant:?} — \
10510                 divergence signals the borrowed-input \
10511                 std::sync::Arc<str> and Box<str> return-shape paths \
10512                 have drifted onto different emit-sets"
10513            );
10514        }
10515        let via_iter: Vec<std::sync::Arc<str>> = RestartStrategy::ALL
10516            .iter()
10517            .map(std::sync::Arc::<str>::from)
10518            .collect();
10519        let via_method: Vec<std::sync::Arc<str>> = RestartStrategy::ALL
10520            .iter()
10521            .map(|s| std::sync::Arc::<str>::from(s.as_str()))
10522            .collect();
10523        assert_eq!(
10524            via_iter, via_method,
10525            "`.iter().map(std::sync::Arc::<str>::from)` over \
10526             RestartStrategy::ALL — a call site whose iteration axis \
10527             holds `&RestartStrategy` by construction — must byte-\
10528             equal `.iter().map(|s| std::sync::Arc::<str>::from(s.as_str()))` \
10529             on every arm — the borrowed-input std::sync::Arc<str> \
10530             `From<&RestartStrategy> for std::sync::Arc<str>` axis is \
10531             what makes the `std::sync::Arc::<str>::from` composition \
10532             route through the substrate-primitive \
10533             `RestartStrategy::as_str` accessor without a spurious \
10534             `Copy` deref (which would only be reachable through the \
10535             owned-input `From<RestartStrategy> for std::sync::Arc<str>` \
10536             axis by first calling `.copied()` on the iterator)"
10537        );
10538    }
10539
10540    #[test]
10541    #[allow(
10542        clippy::too_many_lines,
10543        reason = "cross-axis partition pin folds the substrate-primitive \
10544                  as_str accessor's `.as_bytes()` byte-tail plus the \
10545                  paired str-view (AsRef<str>, Display, as_str) and \
10546                  reverse-projection ({&'static str, String, Cow<'static, \
10547                  str>, Box<str>, std::sync::Arc<str>}) return-shape \
10548                  axes' `.as_bytes()` byte-tails plus a <T: AsRef<[u8]>>\
10549                  -bound-consumer witness plus a blake3::Hasher::update-\
10550                  shape byte-input surface witness into one exhaustive \
10551                  round-trip over RestartStrategy::ALL — the accepted \
10552                  line-count cost of opening the byte-view axis keyed \
10553                  to the substrate-primitive as_str accessor at the \
10554                  same test-site"
10555    )]
10556    #[allow(
10557        clippy::needless_borrows_for_generic_args,
10558        reason = "the borrowed-input surface (&variant) is exercised \
10559                  deliberately: the `<T: AsRef<[u8]>>`-bound consumer \
10560                  and the `blake3::Hasher::update`-shape byte-input \
10561                  surface both accept either owned or borrowed input \
10562                  through the standard-library blanket \
10563                  `impl<T: ?Sized + AsRef<[u8]>> AsRef<[u8]> for &T`, \
10564                  and this pin round-trips both input shapes to lock \
10565                  the borrowed-input path load-bearing against a \
10566                  future silent regression"
10567    )]
10568    fn restart_strategy_as_ref_bytes_routes_through_as_str_accessor() {
10569        // `<T: AsRef<[u8]>>`-bound generic-consumer witness: a byte-input
10570        // function that binds its argument through the standard-library
10571        // [`AsRef<[u8]>`] trait bound accepts a [`super::RestartStrategy`]
10572        // directly, without the caller open-coding the two-hop
10573        // `estrategia.as_str().as_bytes()` composition. Lifted to the top
10574        // of the function per `clippy::items_after_statements`.
10575        fn generic_bytes_sink<T: AsRef<[u8]>>(t: T) -> Vec<u8> {
10576            t.as_ref().to_vec()
10577        }
10578        // `blake3::Hasher::update`-shape byte-input surface mock: mirrors
10579        // `blake3::Hasher::update` / `ring::digest::Context::update` /
10580        // `sha2::Sha256::update`'s `impl AsRef<[u8]>`-bound `update`
10581        // signature so a per-supervisor BLAKE3 content-address closure
10582        // that composes `hasher.update(estrategia)` on the
10583        // [`crate::Lacre`] closure builder reaches the substrate-primitive
10584        // `as_str` accessor through the [`super::RestartStrategy`]
10585        // `AsRef<[u8]>` axis and no other. Lifted to the top of the
10586        // function per `clippy::items_after_statements`.
10587        struct MockHasher(Vec<u8>);
10588        impl MockHasher {
10589            fn new() -> Self {
10590                Self(Vec::new())
10591            }
10592            fn update(&mut self, bytes: impl AsRef<[u8]>) -> &mut Self {
10593                self.0.extend_from_slice(bytes.as_ref());
10594                self
10595            }
10596            fn finalize(self) -> Vec<u8> {
10597                self.0
10598            }
10599        }
10600
10601        // Fail-before-pass-after byte-parity pin on the newly lifted
10602        // `impl AsRef<[u8]> for RestartStrategy` — asserts the trait-
10603        // idiomatic byte-view standard-library impl and the substrate-
10604        // primitive [`super::RestartStrategy::as_str`] `pub const fn`
10605        // accessor's `.as_bytes()` byte-tail resolve to the same four-arm
10606        // `PascalCase` wire byte-string emit-set across every arm the
10607        // exhaustive [`super::RestartStrategy::ALL`] slice enumerates.
10608        // Opens the trait-idiomatic byte-view axis onto the first M2
10609        // OTP-shape closed-set fieldless typed enum peer on the caixa
10610        // surface (`:supervisor :estrategia`), extending the substrate-
10611        // wide byte-view campaign the sibling
10612        // [`super::crate::CaixaKind`] first-mover (69d8d86) opened.
10613        //
10614        // Rust's standard library carries `impl AsRef<[u8]> for str` and
10615        // `impl AsRef<[u8]> for String`, so a two-hop composition
10616        // `estrategia.as_str().as_bytes()` (or the equally two-hop
10617        // `AsRef::<str>::as_ref(&estrategia).as_bytes()`) is reachable
10618        // through the pre-existing str-view axis alone. But that two-hop
10619        // shape has no compile-time link back to the byte-projection
10620        // axis, forces every downstream `<T: AsRef<[u8]>>`-bound
10621        // consumer to open-code the two-hop composition at every call
10622        // site, and admits a silent split whenever a future call site
10623        // takes a sibling reverse-projection axis whose `.as_bytes()`
10624        // byte-tail carries no compile-time byte-view surface. This
10625        // impl closes the byte-view axis at the substrate-primitive
10626        // [`super::RestartStrategy::as_str`] accessor so every future
10627        // `<T: AsRef<[u8]>>`-bound consumer reaches the same lifted
10628        // [`super::crate::render::SUPERVISOR_ESTRATEGIA_*`] const roster
10629        // the paired str-view axes already return through — through one
10630        // trait dispatch.
10631        for &variant in RestartStrategy::ALL {
10632            let via_trait: &[u8] = <RestartStrategy as AsRef<[u8]>>::as_ref(&variant);
10633            let via_method_bytes: &[u8] = variant.as_str().as_bytes();
10634            assert_eq!(
10635                via_trait, via_method_bytes,
10636                "AsRef<[u8]> for RestartStrategy impl must byte-equal \
10637                 RestartStrategy::as_str().as_bytes() on \
10638                 RestartStrategy::{variant:?} — divergence signals a \
10639                 silent detour off the substrate-primitive accessor"
10640            );
10641            // Cross-axis witness against the paired str-view axes'
10642            // `.as_bytes()` byte-tails: [`AsRef<str>`] /
10643            // [`std::fmt::Display`] / [`super::RestartStrategy::as_str`]
10644            // all resolve to the same lifted
10645            // [`super::crate::render::SUPERVISOR_ESTRATEGIA_*`] const
10646            // roster, and the byte-view axis must byte-equal each of
10647            // their `.as_bytes()` byte-tails by construction — locking
10648            // the str-view and byte-view axes together at the
10649            // substrate-primitive accessor.
10650            let str_view_ref: &str = <RestartStrategy as AsRef<str>>::as_ref(&variant);
10651            assert_eq!(
10652                via_trait,
10653                str_view_ref.as_bytes(),
10654                "AsRef<[u8]> for RestartStrategy and AsRef<str> for \
10655                 RestartStrategy must resolve to byte-equal byte-tails \
10656                 on RestartStrategy::{variant:?} — divergence signals \
10657                 the byte-view and str-view axes have drifted off the \
10658                 same substrate-primitive as_str accessor"
10659            );
10660            let display_bytes = variant.to_string();
10661            assert_eq!(
10662                via_trait,
10663                display_bytes.as_bytes(),
10664                "AsRef<[u8]> for RestartStrategy and \
10665                 <RestartStrategy as std::fmt::Display>::to_string must \
10666                 resolve to byte-equal byte-tails on \
10667                 RestartStrategy::{variant:?} — divergence signals the \
10668                 byte-view axis and the Display formatter axis have \
10669                 drifted off the same substrate-primitive as_str \
10670                 accessor"
10671            );
10672            // Cross-axis witness against the paired reverse-projection
10673            // axes' `.as_bytes()` byte-tails: every one of `{&'static
10674            // str, String, Cow<'static, str>, Box<str>,
10675            // std::sync::Arc<str>}` allocates (or borrows) the same
10676            // `PascalCase` wire byte-string the substrate-primitive
10677            // accessor emits, so the byte-view axis must byte-equal
10678            // each of their `.as_bytes()` byte-tails by construction.
10679            let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
10680            assert_eq!(
10681                via_trait,
10682                owned_static.as_bytes(),
10683                "AsRef<[u8]> for RestartStrategy and From<RestartStrategy> \
10684                 for &'static str must resolve to byte-equal byte-tails \
10685                 on RestartStrategy::{variant:?}"
10686            );
10687            let owned_string: String = <String as From<RestartStrategy>>::from(variant);
10688            assert_eq!(
10689                via_trait,
10690                owned_string.as_bytes(),
10691                "AsRef<[u8]> for RestartStrategy and From<RestartStrategy> \
10692                 for String must resolve to byte-equal byte-tails on \
10693                 RestartStrategy::{variant:?}"
10694            );
10695            let owned_cow: std::borrow::Cow<'static, str> =
10696                <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
10697            assert_eq!(
10698                via_trait,
10699                owned_cow.as_bytes(),
10700                "AsRef<[u8]> for RestartStrategy and From<RestartStrategy> \
10701                 for Cow<'static, str> must resolve to byte-equal byte-\
10702                 tails on RestartStrategy::{variant:?}"
10703            );
10704            let owned_box: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
10705            assert_eq!(
10706                via_trait,
10707                owned_box.as_bytes(),
10708                "AsRef<[u8]> for RestartStrategy and From<RestartStrategy> \
10709                 for Box<str> must resolve to byte-equal byte-tails on \
10710                 RestartStrategy::{variant:?}"
10711            );
10712            let owned_arc: std::sync::Arc<str> =
10713                <std::sync::Arc<str> as From<RestartStrategy>>::from(variant);
10714            assert_eq!(
10715                via_trait,
10716                owned_arc.as_bytes(),
10717                "AsRef<[u8]> for RestartStrategy and From<RestartStrategy> \
10718                 for std::sync::Arc<str> must resolve to byte-equal byte-\
10719                 tails on RestartStrategy::{variant:?}"
10720            );
10721        }
10722        // `<T: AsRef<[u8]>>`-bound-consumer witness: the generic byte-
10723        // input function `generic_bytes_sink` (lifted above per
10724        // `clippy::items_after_statements`) accepts a
10725        // [`super::RestartStrategy`] directly through the trait bound,
10726        // without the caller open-coding the two-hop
10727        // `estrategia.as_str().as_bytes()` composition. This is the
10728        // shape that reaches the caixa-lacre BLAKE3 content-address
10729        // closure's `blake3::Hasher::update(impl AsRef<[u8]>)` byte-
10730        // input surface through this impl and no other.
10731        for &variant in RestartStrategy::ALL {
10732            let via_generic = generic_bytes_sink(variant);
10733            let via_borrowed_generic = generic_bytes_sink(&variant);
10734            let via_method_bytes = variant.as_str().as_bytes().to_vec();
10735            assert_eq!(
10736                via_generic, via_method_bytes,
10737                "generic `<T: AsRef<[u8]>>`-bound consumer on \
10738                 RestartStrategy::{variant:?} must yield the same byte-\
10739                 tail RestartStrategy::as_str().as_bytes() returns — \
10740                 divergence signals the byte-view axis fails to bridge \
10741                 a generic byte-input trait bound to the substrate-\
10742                 primitive accessor"
10743            );
10744            assert_eq!(
10745                via_borrowed_generic, via_method_bytes,
10746                "generic `<T: AsRef<[u8]>>`-bound consumer on \
10747                 &RestartStrategy::{variant:?} must yield the same byte-\
10748                 tail RestartStrategy::as_str().as_bytes() returns — \
10749                 the borrowed-input surface must resolve to the same \
10750                 as_str dispatch"
10751            );
10752        }
10753        // `blake3::Hasher::update`-shape byte-input surface witness on
10754        // the caixa-lacre compounding target: the `MockHasher` (lifted
10755        // above per `clippy::items_after_statements`) mirrors
10756        // `blake3::Hasher::update` / `ring::digest::Context::update` /
10757        // `sha2::Sha256::update`'s `impl AsRef<[u8]>`-bound update
10758        // signature and accepts a [`super::RestartStrategy`] directly,
10759        // routing its byte-tail through the substrate-primitive
10760        // `as_str` accessor — the shape a future per-supervisor BLAKE3
10761        // content-address closure composes to fold an `:estrategia`
10762        // discriminator byte-tag into the [`crate::Lacre`] closure
10763        // body.
10764        for &variant in RestartStrategy::ALL {
10765            let mut owned_hasher = MockHasher::new();
10766            owned_hasher.update(variant);
10767            let owned_folded = owned_hasher.finalize();
10768            assert_eq!(
10769                owned_folded,
10770                variant.as_str().as_bytes(),
10771                "`hasher.update(estrategia)`-shape composition on \
10772                 RestartStrategy::{variant:?} must fold the same byte-\
10773                 tail RestartStrategy::as_str().as_bytes() returns — \
10774                 the shape a future per-supervisor BLAKE3 content-\
10775                 address closure composes to fold an `:estrategia` \
10776                 discriminator byte-tag into the Lacre closure body"
10777            );
10778            let mut borrowed_hasher = MockHasher::new();
10779            borrowed_hasher.update(&variant);
10780            let borrowed_folded = borrowed_hasher.finalize();
10781            assert_eq!(
10782                borrowed_folded,
10783                variant.as_str().as_bytes(),
10784                "`hasher.update(&estrategia)`-shape composition on \
10785                 &RestartStrategy::{variant:?} must fold the same byte-\
10786                 tail RestartStrategy::as_str().as_bytes() returns — \
10787                 the borrowed-input surface must resolve to the same \
10788                 as_str dispatch"
10789            );
10790        }
10791    }
10792
10793    #[test]
10794    #[expect(
10795        clippy::too_many_lines,
10796        reason = "the byte-owned reverse-projection axis is extended \
10797                  here onto the first M2-OTP-shape closed-set fieldless \
10798                  typed-enum peer, so the pin binds the new impl against \
10799                  every paired byte-view and str-owned axis on the same \
10800                  enum plus a generic <T: Into<Vec<u8>>>-bound consumer \
10801                  witness and a std::io::Write::write_all-shape owned-\
10802                  byte-sink surface witness on both owned and borrowed \
10803                  input shapes to lock the whole family against a future \
10804                  silent regression"
10805    )]
10806    fn restart_strategy_from_into_owned_vec_bytes_routes_through_as_str_accessor() {
10807        // `<T: Into<Vec<u8>>>`-bound-consumer witness helper: a generic
10808        // owned-byte-input function accepts a [`super::RestartStrategy`]
10809        // directly through the trait bound, without the caller open-
10810        // coding the three-hop `strategy.as_str().as_bytes().to_vec()`
10811        // composition. Lifted to the top of the function per
10812        // `clippy::items_after_statements`.
10813        fn generic_owned_bytes_sink<T: Into<Vec<u8>>>(t: T) -> Vec<u8> {
10814            t.into()
10815        }
10816        // `std::io::Write::write_all`-shape owned-byte-sink surface
10817        // mock: mirrors `std::io::Write::write_all` /
10818        // `bytes::BytesMut::extend_from_slice` / any per-arm audit-log
10819        // byte-sink that consumes a `Vec<u8>` payload via
10820        // `Into<Vec<u8>>`, so a future per-supervisor per-`:estrategia`
10821        // audit-log emit reaches the substrate-primitive `as_str`
10822        // accessor through the byte-owned reverse-projection axis and
10823        // no other. Lifted to the top of the function per
10824        // `clippy::items_after_statements`.
10825        struct MockOwnedByteSink(Vec<u8>);
10826        impl MockOwnedByteSink {
10827            fn new() -> Self {
10828                Self(Vec::new())
10829            }
10830            fn write_all(&mut self, bytes: impl Into<Vec<u8>>) -> &mut Self {
10831                self.0.extend_from_slice(&bytes.into());
10832                self
10833            }
10834            fn finalize(self) -> Vec<u8> {
10835                self.0
10836            }
10837        }
10838
10839        // Fail-before-pass-after byte-parity pin on the newly lifted
10840        // `impl From<RestartStrategy> for Vec<u8>` and
10841        // `impl From<&RestartStrategy> for Vec<u8>` — asserts the trait-
10842        // idiomatic byte-owned reverse-projection standard-library
10843        // impls and the substrate-primitive
10844        // [`super::RestartStrategy::as_str`] `pub const fn` accessor's
10845        // `.as_bytes().to_vec()` byte-tail resolve to the same four-arm
10846        // PascalCase wire byte-string emit-set across every arm the
10847        // exhaustive [`super::RestartStrategy::ALL`] slice enumerates.
10848        // Extends the substrate-wide trait-idiomatic byte-owned
10849        // reverse-projection axis onto the first M2-OTP-shape closed-
10850        // set fieldless typed-enum peer on the caixa surface
10851        // (`:supervisor :estrategia`), matching the trajectory the
10852        // first-mover [`super::crate::CaixaKind`] lift (b245fd6), the
10853        // second-mover [`super::crate::dialeto::CaixaDialeto`] lift
10854        // (4cceaf5), and the third-mover
10855        // [`super::crate::dep::DepList`] lift (e974ca2) established
10856        // across the caixa-core-internal tier.
10857        for &variant in RestartStrategy::ALL {
10858            let via_owned_from: Vec<u8> = <Vec<u8> as From<RestartStrategy>>::from(variant);
10859            let via_borrowed_from: Vec<u8> = <Vec<u8> as From<&RestartStrategy>>::from(&variant);
10860            let via_method_bytes: Vec<u8> = variant.as_str().as_bytes().to_vec();
10861            assert_eq!(
10862                via_owned_from, via_method_bytes,
10863                "From<RestartStrategy> for Vec<u8> impl must byte-equal \
10864                 RestartStrategy::as_str().as_bytes().to_vec() on \
10865                 RestartStrategy::{variant:?} — divergence signals a \
10866                 silent detour off the substrate-primitive accessor"
10867            );
10868            assert_eq!(
10869                via_borrowed_from, via_method_bytes,
10870                "From<&RestartStrategy> for Vec<u8> impl must byte-\
10871                 equal RestartStrategy::as_str().as_bytes().to_vec() \
10872                 on RestartStrategy::{variant:?} — divergence signals \
10873                 a silent detour off the substrate-primitive accessor"
10874            );
10875            assert_eq!(
10876                via_owned_from, via_borrowed_from,
10877                "From<RestartStrategy> for Vec<u8> and \
10878                 From<&RestartStrategy> for Vec<u8> must byte-equal \
10879                 each other on RestartStrategy::{variant:?} — \
10880                 divergence signals the owned-input and borrowed-input \
10881                 paths have drifted off the same substrate-primitive \
10882                 as_str accessor"
10883            );
10884            // Cross-axis witness against the paired [`AsRef<[u8]>`]
10885            // borrowed byte-view axis (cd4c4e0): the byte-owned
10886            // reverse-projection axis must byte-equal the paired
10887            // borrowed byte-view axis by construction — locking the
10888            // byte-view and byte-owned axes together at the substrate-
10889            // primitive accessor.
10890            let borrowed_bytes: &[u8] = <RestartStrategy as AsRef<[u8]>>::as_ref(&variant);
10891            assert_eq!(
10892                via_owned_from,
10893                borrowed_bytes.to_vec(),
10894                "From<RestartStrategy> for Vec<u8> and AsRef<[u8]> \
10895                 for RestartStrategy must resolve to byte-equal byte-\
10896                 tails on RestartStrategy::{variant:?} — divergence \
10897                 signals the byte-owned and byte-view axes have \
10898                 drifted off the same substrate-primitive as_str \
10899                 accessor"
10900            );
10901            // Cross-axis witness against the str-owned reverse-
10902            // projection family's `.into_bytes()` / `.as_bytes().to_vec()`
10903            // byte-tails: every one of `{String, Cow<'static, str>,
10904            // Box<str>, std::sync::Arc<str>, std::rc::Rc<str>}`
10905            // allocates (or borrows) the same PascalCase wire byte-
10906            // string the substrate-primitive accessor emits, so the
10907            // byte-owned axis must byte-equal each of their owned
10908            // byte-tails by construction.
10909            let owned_string: String = <String as From<RestartStrategy>>::from(variant);
10910            assert_eq!(
10911                via_owned_from,
10912                owned_string.into_bytes(),
10913                "From<RestartStrategy> for Vec<u8> and \
10914                 String::from(strategy).into_bytes() must resolve to \
10915                 byte-equal byte-tails on RestartStrategy::{variant:?}"
10916            );
10917            let owned_cow: std::borrow::Cow<'static, str> =
10918                <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
10919            assert_eq!(
10920                via_owned_from,
10921                owned_cow.as_bytes().to_vec(),
10922                "From<RestartStrategy> for Vec<u8> and \
10923                 From<RestartStrategy> for Cow<'static, str> must \
10924                 resolve to byte-equal byte-tails on \
10925                 RestartStrategy::{variant:?}"
10926            );
10927            let owned_box: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
10928            assert_eq!(
10929                via_owned_from,
10930                owned_box.as_bytes().to_vec(),
10931                "From<RestartStrategy> for Vec<u8> and \
10932                 From<RestartStrategy> for Box<str> must resolve to \
10933                 byte-equal byte-tails on RestartStrategy::{variant:?}"
10934            );
10935            let owned_arc: std::sync::Arc<str> =
10936                <std::sync::Arc<str> as From<RestartStrategy>>::from(variant);
10937            assert_eq!(
10938                via_owned_from,
10939                owned_arc.as_bytes().to_vec(),
10940                "From<RestartStrategy> for Vec<u8> and \
10941                 From<RestartStrategy> for std::sync::Arc<str> must \
10942                 resolve to byte-equal byte-tails on \
10943                 RestartStrategy::{variant:?}"
10944            );
10945        }
10946        // `<T: Into<Vec<u8>>>`-bound-consumer witness on both owned
10947        // and borrowed input shapes: the generic owned-byte-input
10948        // function `generic_owned_bytes_sink` (lifted above per
10949        // `clippy::items_after_statements`) accepts a
10950        // [`super::RestartStrategy`] and a `&RestartStrategy`
10951        // directly through the trait bound, without the caller open-
10952        // coding the three-hop `strategy.as_str().as_bytes().to_vec()`
10953        // composition.
10954        for &variant in RestartStrategy::ALL {
10955            let via_generic_owned = generic_owned_bytes_sink(variant);
10956            // Bind the borrowed-input path through an explicit
10957            // `&RestartStrategy` local so the generic-consumer witness
10958            // routes through `From<&RestartStrategy> for Vec<u8>` (T
10959            // binds to `&RestartStrategy`) rather than clippy-collapsing
10960            // the borrow onto the owned-input peer.
10961            let variant_ref: &RestartStrategy = &variant;
10962            let via_generic_borrowed = generic_owned_bytes_sink(variant_ref);
10963            let via_method_bytes = variant.as_str().as_bytes().to_vec();
10964            assert_eq!(
10965                via_generic_owned, via_method_bytes,
10966                "generic `<T: Into<Vec<u8>>>`-bound consumer on \
10967                 RestartStrategy::{variant:?} must yield the same byte-\
10968                 tail RestartStrategy::as_str().as_bytes() returns — \
10969                 divergence signals the byte-owned axis fails to bridge \
10970                 a generic owned-byte-input trait bound to the \
10971                 substrate-primitive accessor"
10972            );
10973            assert_eq!(
10974                via_generic_borrowed, via_method_bytes,
10975                "generic `<T: Into<Vec<u8>>>`-bound consumer on \
10976                 &RestartStrategy::{variant:?} must yield the same byte-\
10977                 tail RestartStrategy::as_str().as_bytes() returns — \
10978                 the borrowed-input surface must resolve to the same \
10979                 as_str dispatch"
10980            );
10981        }
10982        // `std::io::Write::write_all`-shape owned-byte-sink surface
10983        // witness: the `MockOwnedByteSink` (lifted above per
10984        // `clippy::items_after_statements`) mirrors
10985        // `std::io::Write::write_all` /
10986        // `bytes::BytesMut::extend_from_slice`'s `impl Into<Vec<u8>>`-
10987        // bound owned-byte input signature and accepts a
10988        // [`super::RestartStrategy`] directly on both owned and
10989        // borrowed input shapes, routing its byte-tail through the
10990        // substrate-primitive `as_str` accessor — the shape a future
10991        // per-supervisor per-`:estrategia` audit-log emit composes to
10992        // fold an `:estrategia` discriminator byte-tag into a
10993        // downstream owned-byte-sink surface.
10994        for &variant in RestartStrategy::ALL {
10995            let mut owned_sink = MockOwnedByteSink::new();
10996            owned_sink.write_all(variant);
10997            let owned_folded = owned_sink.finalize();
10998            assert_eq!(
10999                owned_folded,
11000                variant.as_str().as_bytes(),
11001                "`sink.write_all(strategy)`-shape composition on \
11002                 RestartStrategy::{variant:?} must fold the same byte-\
11003                 tail RestartStrategy::as_str().as_bytes() returns"
11004            );
11005            let mut borrowed_sink = MockOwnedByteSink::new();
11006            let variant_ref: &RestartStrategy = &variant;
11007            borrowed_sink.write_all(variant_ref);
11008            let borrowed_folded = borrowed_sink.finalize();
11009            assert_eq!(
11010                borrowed_folded,
11011                variant.as_str().as_bytes(),
11012                "`sink.write_all(&strategy)`-shape composition on \
11013                 &RestartStrategy::{variant:?} must fold the same byte-\
11014                 tail RestartStrategy::as_str().as_bytes() returns — \
11015                 the borrowed-input surface must resolve to the same \
11016                 as_str dispatch"
11017            );
11018        }
11019    }
11020
11021    #[test]
11022    fn restart_policy_try_from_str_routes_through_from_wire_accessor() {
11023        // Fail-before-pass-after byte-parity pin on the newly lifted
11024        // `impl TryFrom<&str> for RestartPolicy` — asserts the standard-
11025        // library trait impl and the substrate-primitive
11026        // [`RestartPolicy::from_wire`] `Option<Self>` accessor resolve to
11027        // the same three-arm accept-set across every arm the exhaustive
11028        // [`RestartPolicy::ALL`] slice enumerates. Any future silent
11029        // detour that routes the trait impl through a divergent
11030        // projection (a per-arm inline `match s { "Permanent" =>
11031        // Ok(Self::Permanent), … }` re-inlining that opens a compile-time
11032        // link to the un-lifted arm-literal, a hypothetical
11033        // `#[serde(rename_all = "…")]` attribute drift that silently
11034        // splits the wire byte-string from every consumer that reaches
11035        // for this typed dispatch, an accidental swap onto the kebab-case
11036        // dispatcher-catalog axis the pre-existing [`std::str::FromStr`]
11037        // impl parses through and which would collide the two-axis
11038        // wire/catalog split the sibling [`RestartPolicy::from_wire`]
11039        // doc block makes load-bearing) trips at caixa-core test time
11040        // under `assert_eq!` rather than at a downstream
11041        // `impl TryFrom<&str>`-bound consumer's silent split. Sweeps
11042        // every one of the three arms [`RestartPolicy::ALL`] carries so
11043        // no arm's projection is covered only by the sibling method-
11044        // named `from_wire` path. Peer of the sibling
11045        // [`restart_strategy_try_from_str_routes_through_from_wire_accessor`]
11046        // (5b828ed) — extends the trait-idiomatic reverse-projection
11047        // axis onto the third and final M2-OTP-shape closed-set typed
11048        // enum on the caixa surface (the paired per-child restart-
11049        // decision-policy sibling on the same M2 `:supervisor` slot).
11050        for &variant in RestartPolicy::ALL {
11051            let wire = variant.as_str();
11052            assert_eq!(
11053                <RestartPolicy as TryFrom<&str>>::try_from(wire),
11054                Ok(variant),
11055                "TryFrom<&str> impl on RestartPolicy must round-trip \
11056                 RestartPolicy::{variant:?}.as_str() = {wire:?} back to \
11057                 Ok(RestartPolicy::{variant:?}) — divergence from \
11058                 RestartPolicy::from_wire signals a silent detour off \
11059                 the substrate-primitive accessor"
11060            );
11061            assert_eq!(
11062                <RestartPolicy as TryFrom<&str>>::try_from(wire).ok(),
11063                RestartPolicy::from_wire(wire),
11064                "TryFrom<&str> ok()-projection on {wire:?} must byte-\
11065                 equal RestartPolicy::from_wire on the same input"
11066            );
11067        }
11068    }
11069
11070    #[test]
11071    fn restart_policy_try_from_str_rejects_unknown_byte_strings() {
11072        // Rejection witness on the `impl TryFrom<&str> for
11073        // RestartPolicy` — sweeps a candidate set of byte-strings
11074        // outside the three-arm PascalCase wire accept-set the sibling
11075        // [`RestartPolicy::as_str`] emits and asserts every one lands on
11076        // `Err(())`, so a future accidental widening of the trait impl's
11077        // accept-set (a stray additional
11078        // `_ if s.eq_ignore_ascii_case("Permanent") => Ok(…)` case-fold
11079        // path, a silent inclusion of the kebab-case dispatcher-catalog
11080        // byte-string the pre-existing [`std::str::FromStr`] impl the
11081        // [`gen_platform::FromStrKind`] derive installs parses onto the
11082        // wire axis — which would collide the two-axis
11083        // wire/dispatcher-catalog split the sibling
11084        // [`RestartPolicy::from_wire`] doc block makes load-bearing —
11085        // an English-rebrand or plural-arm silent alias that would widen
11086        // the wire accept-set past the OTP-canonical three) trips at
11087        // caixa-core test time. The candidate set includes the empty
11088        // string, whitespace-only padding, the kebab-case dispatcher-
11089        // catalog byte-strings on the sibling axis (a caller who
11090        // confuses the two axes trips here rather than at a downstream
11091        // consumer's silent reject), a lowercase / uppercase / mixed-case
11092        // fold of each PascalCase arm (a caller who assumes case-fold
11093        // acceptance trips here), leading/trailing whitespace padding,
11094        // the trailing-newline shape, quote-wrapped candidates, and a
11095        // residual set of plausible-but-wrong English rebrand
11096        // candidates. Peer of the sibling
11097        // [`restart_strategy_try_from_str_rejects_unknown_byte_strings`]
11098        // (5b828ed) rejection witness.
11099        let rejected: &[&str] = &[
11100            "",
11101            " ",
11102            "\n",
11103            "\t",
11104            "permanent",
11105            "temporary",
11106            "transient",
11107            "PERMANENT",
11108            "TEMPORARY",
11109            "TRANSIENT",
11110            "Permanents",
11111            "Permanent ",
11112            " Permanent",
11113            " Temporary ",
11114            "Permanent\n",
11115            "Transient\t",
11116            "\"Permanent\"",
11117            "Ephemeral",
11118            "Always",
11119            "Never",
11120            "OnAbnormalExit",
11121            "intrinsic",
11122            "?",
11123        ];
11124        for &input in rejected {
11125            assert_eq!(
11126                <RestartPolicy as TryFrom<&str>>::try_from(input),
11127                Err(()),
11128                "TryFrom<&str> impl on RestartPolicy must reject the \
11129                 non-wire byte-string {input:?} — silent acceptance \
11130                 signals an accept-set widening off the paired \
11131                 RestartPolicy::from_wire resolver"
11132            );
11133        }
11134    }
11135
11136    #[test]
11137    fn restart_policy_try_from_str_and_from_wire_partition_the_accept_set() {
11138        // Cross-axis partition pin: the paired `TryFrom<&str>` and
11139        // `from_wire` reverse projections must resolve identically on
11140        // *every* input, not just the ones [`RestartPolicy::ALL`]
11141        // enumerates. Sweeps a mixed candidate set spanning accepted
11142        // (three-arm PascalCase wire byte-strings) and rejected (kebab-
11143        // case dispatcher-catalog byte-strings, empty, whitespace-
11144        // padded, quoted, English-rebrand candidates) inputs and asserts
11145        // the trait's `Result::ok()` projection byte-equals the method-
11146        // named resolver's `Option<Self>` return-shape on each, locking
11147        // the two paths together by construction so any future detour
11148        // (a stray `try_from` special-case that widens or narrows the
11149        // accept-set outside the paired `from_wire` resolver, an
11150        // accidental swap onto the kebab-case [`std::str::FromStr`]
11151        // impl the [`gen_platform::FromStrKind`] derive installs on the
11152        // sibling dispatcher-catalog axis) trips at caixa-core test
11153        // time. Peer of the sibling
11154        // [`restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
11155        // pin — extends the round-trip discipline onto the M2-OTP-shape
11156        // per-child restart-policy axis.
11157        let candidates: &[&str] = &[
11158            "Permanent",
11159            "Temporary",
11160            "Transient",
11161            "",
11162            "permanent",
11163            "temporary",
11164            "transient",
11165            "PERMANENT",
11166            "unknown",
11167            "Permanent ",
11168            " Permanent",
11169            "\"Permanent\"",
11170            "Ephemeral",
11171            "OnAbnormalExit",
11172            "?",
11173        ];
11174        for &input in candidates {
11175            let via_trait: Option<RestartPolicy> =
11176                <RestartPolicy as TryFrom<&str>>::try_from(input).ok();
11177            let via_method: Option<RestartPolicy> = RestartPolicy::from_wire(input);
11178            assert_eq!(
11179                via_trait, via_method,
11180                "TryFrom<&str> and from_wire must resolve identically on \
11181                 input {input:?} — divergence signals the two reverse-\
11182                 projection paths have drifted onto different accept-sets"
11183            );
11184        }
11185    }
11186
11187    #[test]
11188    fn restart_policy_from_into_static_str_routes_through_as_str_accessor() {
11189        // Fail-before-pass-after byte-parity pin on the newly lifted
11190        // `impl From<RestartPolicy> for &'static str` — asserts the
11191        // standard-library trait impl and the substrate-primitive
11192        // [`RestartPolicy::as_str`] `pub const fn` accessor resolve to
11193        // the same three-arm emit-set across every arm the exhaustive
11194        // [`RestartPolicy::ALL`] slice enumerates. Any future silent
11195        // detour that routes the trait impl through a divergent
11196        // projection (a per-arm inline `match policy { Permanent =>
11197        // "Permanent", … }` re-inlining that opens a compile-time link
11198        // to the un-lifted arm-literal, an accidental swap onto the
11199        // sibling kebab-case [`Self::discriminant`] dispatcher-catalog
11200        // axis that would collide the two-axis wire/catalog split the
11201        // sibling [`RestartPolicy::from_wire`] doc block makes
11202        // load-bearing) trips at caixa-core test time under
11203        // `assert_eq!` rather than at a downstream
11204        // `impl Into<&'static str>`-bound consumer's silent split.
11205        // Sweeps every one of the three arms [`RestartPolicy::ALL`]
11206        // carries so no arm's projection is covered only by the sibling
11207        // method-named `as_str` / [`std::fmt::Display`] / [`AsRef<str>`]
11208        // paths. Materializes the `<&'static str as
11209        // From<RestartPolicy>>::from` output in a `const`-shape binding
11210        // to make the `'static` lifetime promise a build-time invariant
11211        // — a future accidental downgrade of any of the three arms'
11212        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] constants to a
11213        // non-`&'static str` (a `String::leak()`-produced return, a
11214        // `Box::leak`-cast) trips at caixa-core build time rather than
11215        // at a downstream `'static`-bound consumer. Peer of the sibling
11216        // [`restart_strategy_from_into_static_str_routes_through_as_str_accessor`]
11217        // (523157d) — extends the trait-idiomatic forward-projection
11218        // axis onto the second (and second-of-two-in-M2) closed-set
11219        // typed enum on the caixa surface (the paired per-child
11220        // restart-decision-policy sibling on the same M2 `:supervisor`
11221        // slot).
11222        const PERMANENT: &str = RestartPolicy::Permanent.as_str();
11223        const TEMPORARY: &str = RestartPolicy::Temporary.as_str();
11224        const TRANSIENT: &str = RestartPolicy::Transient.as_str();
11225        for &variant in RestartPolicy::ALL {
11226            let via_trait: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
11227            let via_method: &'static str = variant.as_str();
11228            assert_eq!(
11229                via_trait, via_method,
11230                "From<RestartPolicy> for &'static str impl must round-trip \
11231                 RestartPolicy::{variant:?} to the same lifted \
11232                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str returns — \
11233                 divergence signals a silent detour off the substrate-primitive \
11234                 accessor"
11235            );
11236            let via_into: &'static str = variant.into();
11237            assert_eq!(
11238                via_into, via_method,
11239                "Into<&'static str>::into on RestartPolicy::{variant:?} must \
11240                 byte-equal RestartPolicy::as_str on the same input — the \
11241                 blanket-derived Into shape must resolve to the same as_str \
11242                 dispatch as the explicit From impl"
11243            );
11244        }
11245        assert_eq!(
11246            [PERMANENT, TEMPORARY, TRANSIENT],
11247            [
11248                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
11249                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
11250                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
11251            ],
11252            "const-context RestartPolicy::as_str must resolve to the three \
11253             lifted SUPERVISOR_CHILD_RESTART_* consts — a future accidental \
11254             downgrade of any arm to a non-const or non-static byte-string \
11255             breaks the `&'static str`-lifetime promise the paired \
11256             From<RestartPolicy> for &'static str impl carries by \
11257             construction"
11258        );
11259    }
11260
11261    #[test]
11262    fn restart_policy_from_into_static_str_and_as_str_partition_the_emit_set() {
11263        // Cross-axis partition pin: the paired trait-idiomatic
11264        // `From<RestartPolicy> for &'static str` forward projection and
11265        // the method-named [`RestartPolicy::as_str`] forward projection
11266        // must resolve identically on *every* arm, not just the ones
11267        // named in the primary byte-parity pin above. Sweeps every
11268        // [`RestartPolicy::ALL`] arm and asserts the trait's `From::from`
11269        // output byte-equals the method-named accessor's return-value on
11270        // each, locking the two forward-projection paths together by
11271        // construction so any future detour (a stray `From` special-case
11272        // that lands on a divergent per-arm literal outside the paired
11273        // `as_str` dispatch, a hypothetical rebrand touching one axis
11274        // without the other) trips at caixa-core test time. Peer of the
11275        // sibling forward-projection partition pin
11276        // [`restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
11277        // (523157d) — extends the round-trip discipline onto the
11278        // second-of-two M2-OTP-shape closed-set typed enum on the caixa
11279        // surface, closing the two-way `Self ↔ &'static str` round-trip
11280        // on the trait-idiomatic pair (`From<Self> for &'static str` +
11281        // `TryFrom<&str> for Self`) as well as the pre-existing method-
11282        // named pair (`as_str` + `from_wire`).
11283        for &variant in RestartPolicy::ALL {
11284            let via_trait: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
11285            let via_method: &'static str = variant.as_str();
11286            assert_eq!(
11287                via_trait, via_method,
11288                "From<RestartPolicy> for &'static str and \
11289                 RestartPolicy::as_str must resolve identically on \
11290                 RestartPolicy::{variant:?} — divergence signals the \
11291                 two forward-projection paths have drifted onto different \
11292                 emit-sets"
11293            );
11294        }
11295        // Round-trip witness: every arm's forward `From` output re-parses
11296        // through the paired trait-idiomatic reverse `TryFrom<&str>` back
11297        // to the original variant. Closes the two-way `RestartPolicy ↔
11298        // &'static str` round-trip on the trait-idiomatic axis pair,
11299        // mirroring the pre-existing method-named `as_str` + `from_wire`
11300        // round-trip on the substrate-primitive axis pair.
11301        for &variant in RestartPolicy::ALL {
11302            let emitted: &'static str = variant.into();
11303            let re_parsed: Result<RestartPolicy, ()> =
11304                <RestartPolicy as TryFrom<&str>>::try_from(emitted);
11305            assert_eq!(
11306                re_parsed,
11307                Ok(variant),
11308                "trait-idiomatic axis pair must round-trip \
11309                 RestartPolicy::{variant:?} through `.into::<&'static \
11310                 str>()` and back through `TryFrom<&str>` — a break signals \
11311                 the forward-emit and reverse-parse axes have drifted onto \
11312                 different vocabularies"
11313            );
11314        }
11315    }
11316
11317    #[test]
11318    fn restart_policy_from_borrowed_into_static_str_routes_through_as_str_accessor() {
11319        // Fail-before-pass-after byte-parity pin on the newly lifted
11320        // `impl From<&RestartPolicy> for &'static str` — asserts the
11321        // borrowed-input standard-library trait impl and the substrate-
11322        // primitive [`RestartPolicy::as_str`] `pub const fn` accessor
11323        // resolve to the same three-arm emit-set across every arm the
11324        // exhaustive [`RestartPolicy::ALL`] slice enumerates. Rust's
11325        // `From` trait does not auto-derive the borrowed-input sibling
11326        // from a paired owned-input impl (no `impl<T, U> From<&T> for U
11327        // where T: Copy, U: From<T>` blanket in `core`), so the
11328        // borrowed-input axis is a distinct trait-idiomatic surface
11329        // that a `.iter().map(Into::into)` shape over
11330        // [`RestartPolicy::ALL`] (whose iterator yields
11331        // `&RestartPolicy`, not `RestartPolicy`) reaches through this
11332        // impl and no other — the paired owned-input
11333        // [`From<RestartPolicy>`] impl requires an explicit `.copied()`
11334        // / dereference before the trait fires. Materializes the
11335        // `<&'static str as From<&RestartPolicy>>::from` output in a
11336        // `const`-shape binding to make the `'static` lifetime promise
11337        // a build-time invariant.
11338        const PERMANENT: &str = RestartPolicy::Permanent.as_str();
11339        const TEMPORARY: &str = RestartPolicy::Temporary.as_str();
11340        const TRANSIENT: &str = RestartPolicy::Transient.as_str();
11341        for variant in RestartPolicy::ALL {
11342            let via_trait: &'static str = <&'static str as From<&RestartPolicy>>::from(variant);
11343            let via_method: &'static str = variant.as_str();
11344            assert_eq!(
11345                via_trait, via_method,
11346                "From<&RestartPolicy> for &'static str impl must round-trip \
11347                 &RestartPolicy::{variant:?} to the same lifted \
11348                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
11349                 returns — divergence signals a silent detour off the \
11350                 substrate-primitive accessor"
11351            );
11352            let via_into: &'static str = variant.into();
11353            assert_eq!(
11354                via_into, via_method,
11355                "Into<&'static str>::into on &RestartPolicy::{variant:?} \
11356                 must byte-equal RestartPolicy::as_str on the same input — \
11357                 the blanket-derived Into shape must resolve to the same \
11358                 as_str dispatch as the explicit From impl"
11359            );
11360        }
11361        assert_eq!(
11362            [PERMANENT, TEMPORARY, TRANSIENT],
11363            [
11364                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
11365                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
11366                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
11367            ],
11368            "const-context RestartPolicy::as_str must resolve to the three \
11369             lifted SUPERVISOR_CHILD_RESTART_* consts — the borrowed-input \
11370             From<&RestartPolicy> for &'static str impl inherits its \
11371             `'static` lifetime promise from the same accessor the \
11372             owned-input sibling routes through"
11373        );
11374    }
11375
11376    #[test]
11377    fn restart_policy_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
11378        // Cross-axis partition pin: the paired trait-idiomatic
11379        // owned-input `From<RestartPolicy> for &'static str` (9fb37d0
11380        // campaign-shape) and borrowed-input `From<&RestartPolicy> for
11381        // &'static str` (this lift) forward projections must resolve
11382        // identically on every arm, locking the two input-shape paths
11383        // together so any future detour trips at caixa-core test time.
11384        // Then a witness that a `.iter().map(Into::into)` pipe over
11385        // [`RestartPolicy::ALL`] (whose iterator yields
11386        // `&RestartPolicy`) materializes the three-arm accept-set
11387        // through the borrowed-input axis alone — the exact shape a
11388        // future wasm-operator per-child post-exit restart-decision
11389        // diagnostic line, a future substrate-wide per-arm diagnostic
11390        // column, or a
11391        // `HashMap::<&'static str, RestartPolicy>::from_iter(
11392        //     RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))`-style
11393        // per-policy lookup reaches through — closing the two-way
11394        // owned/borrowed input-shape symmetry on the forward-projection
11395        // trait-idiomatic axis. Peer of the sibling
11396        // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
11397        // (64aa742) /
11398        // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
11399        // (5ab993a) /
11400        // [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
11401        // (807b0b5) /
11402        // [`restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
11403        // (e941836) partition pins on the sibling closed-set typed-enum
11404        // discriminator axes — extends the borrowed-input axis
11405        // discipline onto the second-of-two M2 OTP-shape closed-set
11406        // typed enum on the caixa surface (per-child restart-decision
11407        // policy). Also closes the direct two-way `&Self → &'static
11408        // str → Self` round-trip via the paired [`TryFrom<&str>`] axis
11409        // — unlike the peer [`crate::CaixaKind`] axis pair (whose
11410        // forward `From` emits lowercase Portuguese diagnostic bytes
11411        // while the reverse `TryFrom` parses `PascalCase` wire bytes,
11412        // forcing the round-trip through an intermediate wire-vocab
11413        // hop), the [`RestartPolicy::as_str`] emit and
11414        // [`RestartPolicy::from_wire`] parse share the same
11415        // `PascalCase` vocabulary by construction, so the borrowed-
11416        // input forward axis and the reverse axis compose directly.
11417        for &variant in RestartPolicy::ALL {
11418            let owned: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
11419            let borrowed: &'static str = <&'static str as From<&RestartPolicy>>::from(&variant);
11420            assert_eq!(
11421                owned, borrowed,
11422                "From<RestartPolicy> and From<&RestartPolicy> for \
11423                 &'static str must resolve identically on \
11424                 RestartPolicy::{variant:?} — divergence signals the \
11425                 owned-input and borrowed-input forward-projection paths \
11426                 have drifted onto different emit-sets"
11427            );
11428        }
11429        let via_iter: Vec<&'static str> = RestartPolicy::ALL.iter().map(Into::into).collect();
11430        let via_method: Vec<&'static str> = RestartPolicy::ALL.iter().map(|p| p.as_str()).collect();
11431        assert_eq!(
11432            via_iter, via_method,
11433            "`.iter().map(Into::into)` over RestartPolicy::ALL must \
11434             byte-equal `.iter().map(|p| p.as_str())` on every arm — the \
11435             borrowed-input `From<&RestartPolicy> for &'static str` axis \
11436             is what makes the `.iter().map(Into::into)` shape route \
11437             through the substrate-primitive `RestartPolicy::as_str` \
11438             accessor rather than through a per-call-site `.copied()` / \
11439             dereference detour"
11440        );
11441        for variant in RestartPolicy::ALL {
11442            let emitted: &'static str = variant.into();
11443            let re_parsed: Result<RestartPolicy, ()> =
11444                <RestartPolicy as TryFrom<&str>>::try_from(emitted);
11445            assert_eq!(
11446                re_parsed,
11447                Ok(*variant),
11448                "trait-idiomatic borrowed-input forward-projection + \
11449                 reverse-projection axis pair must round-trip \
11450                 &RestartPolicy::{variant:?} through `.into::<&'static \
11451                 str>()` (via the borrowed-input axis) and back through \
11452                 `TryFrom<&str>` — a break signals the borrowed-input \
11453                 forward-emit and reverse-parse axes have drifted onto \
11454                 different vocabularies"
11455            );
11456        }
11457    }
11458
11459    #[test]
11460    fn restart_policy_from_into_owned_string_routes_through_as_str_accessor() {
11461        // Fail-before-pass-after byte-parity pin on the newly lifted
11462        // `impl From<RestartPolicy> for String` — asserts the
11463        // owned-`String`-returning standard-library trait impl and the
11464        // substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
11465        // accessor resolve to the same three-arm emit-set across every
11466        // arm the exhaustive [`RestartPolicy::ALL`] slice enumerates.
11467        // Rust's standard library does not carry a blanket
11468        // `impl<T: AsRef<str>> From<T> for String` (nor an
11469        // `impl<T: fmt::Display> From<T> for String`), so the
11470        // owned-`String` forward-projection axis is a distinct
11471        // trait-idiomatic surface that a `let key: String =
11472        // policy.into();`-shaped call site reaches through this impl
11473        // and no other — the paired sibling `From<RestartPolicy> for
11474        // &'static str` impl forces every owned-`String` call site
11475        // through an explicit `.to_owned()` / `String::from`
11476        // restatement. Peer of the first-mover
11477        // [`restart_strategy_from_into_owned_string_routes_through_as_str_accessor`]
11478        // (7baa18a) — extends the trait-idiomatic owned-`String`
11479        // forward-projection axis onto the second-of-two M2 OTP-shape
11480        // closed-set typed enums on the caixa surface (per-child
11481        // restart-decision-policy sibling on the same M2 `:supervisor`
11482        // slot).
11483        for &variant in RestartPolicy::ALL {
11484            let via_trait: String = <String as From<RestartPolicy>>::from(variant);
11485            let via_method: &'static str = variant.as_str();
11486            assert_eq!(
11487                via_trait.as_str(),
11488                via_method,
11489                "From<RestartPolicy> for String impl must round-trip \
11490                 RestartPolicy::{variant:?} to the same lifted \
11491                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
11492                 returns — divergence signals a silent detour off the \
11493                 substrate-primitive accessor"
11494            );
11495            let via_into: String = variant.into();
11496            assert_eq!(
11497                via_into.as_str(),
11498                via_method,
11499                "Into<String>::into on RestartPolicy::{variant:?} must \
11500                 byte-equal RestartPolicy::as_str on the same input — the \
11501                 blanket-derived Into shape must resolve to the same as_str \
11502                 dispatch as the explicit From impl"
11503            );
11504        }
11505    }
11506
11507    #[test]
11508    fn restart_policy_from_into_owned_string_and_static_str_agree_on_every_arm() {
11509        // Cross-axis partition pin: the paired trait-idiomatic
11510        // owned-`String` `From<RestartPolicy> for String` (this lift)
11511        // and owned-`&'static str` `From<RestartPolicy> for &'static
11512        // str` (9fb37d0) forward projections must resolve identically
11513        // on every arm, locking the two return-type-shape paths
11514        // together so any future detour trips at caixa-core test time.
11515        // Also byte-parity witness against the sibling
11516        // [`ToString::to_string`] surface routed through
11517        // [`std::fmt::Display`] — the three owned-heap-string paths
11518        // (`.into::<String>()`, `String::from`, `.to_string()`) must
11519        // resolve identically on every arm so a future consumer that
11520        // picks any of the three lands on the same lifted
11521        // SUPERVISOR_CHILD_RESTART_* const. Then a `.iter().copied()
11522        // .map(String::from)` pipe witness over [`RestartPolicy::ALL`]
11523        // that materializes the three-arm accept-set through the
11524        // owned-`String` axis alone — the exact shape a future
11525        // wasm-operator per-child post-exit restart-decision
11526        // diagnostic line composer or a
11527        // `HashMap::<String, RestartPolicy>::from_iter(
11528        //     RestartPolicy::ALL.iter().copied().map(|p| (p.into(), p)))`-style
11529        // owned-key per-policy lookup reaches through — closing the
11530        // owned-`String` forward-projection axis's iterator-pipe
11531        // shape. Then a direct round-trip witness through the paired
11532        // trait-idiomatic reverse [`TryFrom<&str>`] axis on the
11533        // owned-`String`'s [`String::as_str`] borrow that closes the
11534        // two-way `Self → String → Self` round-trip on the trait-
11535        // idiomatic owned-`String` forward + reverse axis pair —
11536        // unlike the peer [`crate::CaixaKind`] axis pair (whose
11537        // forward `From` emits lowercase Portuguese diagnostic bytes
11538        // while the reverse `TryFrom` parses `PascalCase` wire bytes,
11539        // forcing the round-trip through an intermediate wire-vocab
11540        // hop), the [`RestartPolicy::as_str`] emit and
11541        // [`RestartPolicy::from_wire`] parse share the same
11542        // `PascalCase` vocabulary by construction, so the owned-
11543        // `String` forward axis and the reverse axis compose directly.
11544        for &variant in RestartPolicy::ALL {
11545            let owned_string: String = <String as From<RestartPolicy>>::from(variant);
11546            let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
11547            assert_eq!(
11548                owned_string.as_str(),
11549                owned_static,
11550                "From<RestartPolicy> for String and From<RestartPolicy> \
11551                 for &'static str must resolve identically on \
11552                 RestartPolicy::{variant:?} — divergence signals the \
11553                 owned-`String` and owned-`&'static str` forward-projection \
11554                 return-type-shape paths have drifted onto different \
11555                 emit-sets"
11556            );
11557            let via_to_string: String = variant.to_string();
11558            assert_eq!(
11559                owned_string, via_to_string,
11560                "From<RestartPolicy> for String must byte-equal \
11561                 RestartPolicy::to_string on RestartPolicy::{variant:?} — \
11562                 divergence signals the trait-idiomatic owned-`String` \
11563                 forward-projection axis and the ToString-through-Display \
11564                 axis have drifted onto different emit-sets"
11565            );
11566        }
11567        let via_iter: Vec<String> = RestartPolicy::ALL
11568            .iter()
11569            .copied()
11570            .map(String::from)
11571            .collect();
11572        let via_method: Vec<String> = RestartPolicy::ALL
11573            .iter()
11574            .map(|p| p.as_str().to_owned())
11575            .collect();
11576        assert_eq!(
11577            via_iter, via_method,
11578            "`.iter().copied().map(String::from)` over RestartPolicy::ALL \
11579             must byte-equal `.iter().map(|p| p.as_str().to_owned())` on \
11580             every arm — the owned-`String` `From<RestartPolicy> for \
11581             String` axis is what makes the `String::from` composition \
11582             route through the substrate-primitive `RestartPolicy::as_str` \
11583             accessor rather than through a per-call-site `.to_owned()` / \
11584             `String::from(policy.as_str())` detour"
11585        );
11586        for &variant in RestartPolicy::ALL {
11587            let emitted: String = variant.into();
11588            let re_parsed: Result<RestartPolicy, ()> =
11589                <RestartPolicy as TryFrom<&str>>::try_from(emitted.as_str());
11590            assert_eq!(
11591                re_parsed,
11592                Ok(variant),
11593                "trait-idiomatic owned-`String` forward-projection + \
11594                 reverse-projection axis pair must round-trip \
11595                 RestartPolicy::{variant:?} through `.into::<String>()` \
11596                 and back through `TryFrom<&str>` on the owned-`String`'s \
11597                 String::as_str borrow — a break signals the owned-`String` \
11598                 forward-emit and reverse-parse axes have drifted onto \
11599                 different vocabularies"
11600            );
11601        }
11602    }
11603
11604    #[test]
11605    fn restart_policy_from_into_borrowed_owned_string_routes_through_as_str_accessor() {
11606        // Fail-before-pass-after byte-parity pin on the newly lifted
11607        // `impl From<&RestartPolicy> for String` — asserts the
11608        // borrowed-input owned-`String`-returning standard-library
11609        // trait impl and the substrate-primitive
11610        // [`RestartPolicy::as_str`] `pub const fn` accessor resolve to
11611        // the same three-arm emit-set across every arm the exhaustive
11612        // [`RestartPolicy::ALL`] slice enumerates. Rust's standard
11613        // library does not carry a blanket `impl<T: AsRef<str>>
11614        // From<&T> for String` (nor an `impl<T: fmt::Display> From<&T>
11615        // for String`), so the borrowed-input owned-`String` forward-
11616        // projection axis is a distinct trait-idiomatic surface that a
11617        // `let key: String = (&policy).into();`-shaped call site
11618        // reaches through this impl and no other — the paired sibling
11619        // `From<RestartPolicy> for String` impl forces every borrowed-
11620        // input call site through an explicit `Copy` deref
11621        // (`String::from(*policy)`) or an `.as_str().to_owned()` /
11622        // `.to_string()` detour. Peer of the first-mover
11623        // [`restart_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
11624        // (579385f) — extends the trait-idiomatic borrowed-input
11625        // owned-`String` forward-projection axis onto the second-of-
11626        // two M2 OTP-shape closed-set typed enums on the caixa surface
11627        // (per-child restart-decision-policy sibling on the same M2
11628        // `:supervisor` slot).
11629        for &variant in RestartPolicy::ALL {
11630            let via_trait: String = <String as From<&RestartPolicy>>::from(&variant);
11631            let via_method: &'static str = variant.as_str();
11632            assert_eq!(
11633                via_trait.as_str(),
11634                via_method,
11635                "From<&RestartPolicy> for String impl must round-trip \
11636                 &RestartPolicy::{variant:?} to the same lifted \
11637                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
11638                 returns — divergence signals a silent detour off the \
11639                 substrate-primitive accessor"
11640            );
11641            let via_into: String = (&variant).into();
11642            assert_eq!(
11643                via_into.as_str(),
11644                via_method,
11645                "Into<String>::into on &RestartPolicy::{variant:?} must \
11646                 byte-equal RestartPolicy::as_str on the same input — \
11647                 the blanket-derived Into shape must resolve to the \
11648                 same as_str dispatch as the explicit From impl"
11649            );
11650        }
11651    }
11652
11653    #[test]
11654    fn restart_policy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm() {
11655        // Cross-axis partition pin: the newly lifted trait-idiomatic
11656        // borrowed-input owned-`String` `From<&RestartPolicy> for
11657        // String` (this lift), the paired owned-input owned-`String`
11658        // `From<RestartPolicy> for String` (7851725), the paired
11659        // borrowed-input owned-`&'static str` `From<&RestartPolicy>
11660        // for &'static str` (842c7f3), and the paired owned-input
11661        // owned-`&'static str` `From<RestartPolicy> for &'static str`
11662        // (9fb37d0) — every corner of the `{Self, &Self} × {&'static
11663        // str, String}` 2×2 trait-idiomatic projection family — must
11664        // resolve identically on every arm, locking the four
11665        // return-shape × input-shape paths together so any future
11666        // detour trips at caixa-core test time. Also byte-parity
11667        // witness against the sibling [`ToString::to_string`] surface
11668        // routed through [`std::fmt::Display`] and a direct round-trip
11669        // witness through the paired trait-idiomatic reverse
11670        // [`TryFrom<&str>`] axis on the owned-`String`'s
11671        // [`String::as_str`] borrow that closes the two-way
11672        // `&Self → String → Self` round-trip on the trait-idiomatic
11673        // borrowed-input owned-`String` forward + reverse axis pair.
11674        // Peer of the first-mover
11675        // [`restart_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
11676        // (579385f) — closes the whole `{Self, &Self} × {&'static str,
11677        // String}` 2×2 projection corner on both M2 OTP-shape sibling
11678        // peers.
11679        for &variant in RestartPolicy::ALL {
11680            let borrowed_string: String = <String as From<&RestartPolicy>>::from(&variant);
11681            let owned_string: String = <String as From<RestartPolicy>>::from(variant);
11682            let borrowed_static: &'static str =
11683                <&'static str as From<&RestartPolicy>>::from(&variant);
11684            let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
11685            assert_eq!(
11686                borrowed_string, owned_string,
11687                "From<&RestartPolicy> for String and From<RestartPolicy> \
11688                 for String must resolve identically on \
11689                 RestartPolicy::{variant:?} — divergence signals the \
11690                 borrowed-input and owned-input owned-`String` \
11691                 forward-projection input-shape paths have drifted onto \
11692                 different emit-sets"
11693            );
11694            assert_eq!(
11695                borrowed_string.as_str(),
11696                borrowed_static,
11697                "From<&RestartPolicy> for String and From<&RestartPolicy> \
11698                 for &'static str must resolve identically on \
11699                 RestartPolicy::{variant:?} — divergence signals the \
11700                 borrowed-input `&'static str` and owned-`String` \
11701                 return-shape paths have drifted onto different \
11702                 emit-sets"
11703            );
11704            assert_eq!(
11705                borrowed_string.as_str(),
11706                owned_static,
11707                "From<&RestartPolicy> for String and From<RestartPolicy> \
11708                 for &'static str must resolve identically on \
11709                 RestartPolicy::{variant:?} — divergence signals a \
11710                 break in the diagonal corner of the {{Self, &Self}} × \
11711                 {{&'static str, String}} 2×2 trait-idiomatic \
11712                 projection family"
11713            );
11714            let via_to_string: String = variant.to_string();
11715            assert_eq!(
11716                borrowed_string, via_to_string,
11717                "From<&RestartPolicy> for String must byte-equal \
11718                 RestartPolicy::to_string on RestartPolicy::{variant:?} \
11719                 — divergence signals the trait-idiomatic borrowed-input \
11720                 owned-`String` forward-projection axis and the \
11721                 ToString-through-Display axis have drifted onto \
11722                 different emit-sets"
11723            );
11724        }
11725        let via_iter: Vec<String> = RestartPolicy::ALL.iter().map(String::from).collect();
11726        let via_method: Vec<String> = RestartPolicy::ALL
11727            .iter()
11728            .map(|p| p.as_str().to_owned())
11729            .collect();
11730        assert_eq!(
11731            via_iter, via_method,
11732            "`.iter().map(String::from)` over RestartPolicy::ALL — a \
11733             call site whose iteration axis holds `&RestartPolicy` by \
11734             construction — must byte-equal `.iter().map(|p| \
11735             p.as_str().to_owned())` on every arm — the borrowed-input \
11736             owned-`String` `From<&RestartPolicy> for String` axis is \
11737             what makes the `String::from` composition route through \
11738             the substrate-primitive `RestartPolicy::as_str` accessor \
11739             without a spurious `Copy` deref (which would only be \
11740             reachable through the owned-input `From<RestartPolicy> \
11741             for String` axis by first calling `.copied()` on the \
11742             iterator)"
11743        );
11744        for &variant in RestartPolicy::ALL {
11745            let emitted: String = (&variant).into();
11746            let re_parsed: Result<RestartPolicy, ()> =
11747                <RestartPolicy as TryFrom<&str>>::try_from(emitted.as_str());
11748            assert_eq!(
11749                re_parsed,
11750                Ok(variant),
11751                "trait-idiomatic borrowed-input owned-`String` \
11752                 forward-projection + reverse-projection axis pair must \
11753                 round-trip &RestartPolicy::{variant:?} through \
11754                 `.into::<String>()` on the borrowed-input surface and \
11755                 back through `TryFrom<&str>` on the owned-`String`'s \
11756                 String::as_str borrow — a break signals the \
11757                 borrowed-input owned-`String` forward-emit and \
11758                 reverse-parse axes have drifted onto different \
11759                 vocabularies"
11760            );
11761        }
11762    }
11763
11764    #[test]
11765    fn restart_policy_from_into_static_cow_str_routes_through_as_str_accessor() {
11766        // Fail-before-pass-after byte-parity pin on the newly lifted
11767        // `impl From<RestartPolicy> for std::borrow::Cow<'static, str>` —
11768        // asserts the standard-library trait impl and the substrate-
11769        // primitive [`super::RestartPolicy::as_str`] `pub const fn`
11770        // accessor resolve to the same three-arm emit-set across every
11771        // arm the exhaustive [`super::RestartPolicy::ALL`] slice
11772        // enumerates. Rust's standard library does not carry a blanket
11773        // `impl<T: AsRef<str>> From<T> for Cow<'static, str>` (nor an
11774        // `impl<T: fmt::Display> From<T> for Cow<'static, str>`), so
11775        // the `Cow<'static, str>` forward-projection axis is a
11776        // distinct trait-idiomatic surface that a
11777        // `let key: Cow<'static, str> = policy.into();`-shaped call
11778        // site reaches through this impl and no other — the paired
11779        // sibling `From<RestartPolicy> for &'static str` and
11780        // `From<RestartPolicy> for String` impls force every
11781        // `Cow<'static, str>`-parameterized call site through a
11782        // `Cow::Borrowed(policy.as_str())` /
11783        // `Cow::Owned(policy.to_string())` composition whose type
11784        // bounds have no compile-time link back to the substrate
11785        // primitive.
11786        //
11787        // Also asserts the projection lands on the zero-alloc
11788        // [`std::borrow::Cow::Borrowed`] arm (not the
11789        // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
11790        // [`super::RestartPolicy::as_str`] accessor's `&'static str`
11791        // return lifetime by construction makes the borrowed arm the
11792        // type-correct projection with no runtime allocation. Any
11793        // future silent detour that routes the impl through the owned
11794        // arm (an accidental `Cow::Owned(policy.to_string())` rewrite
11795        // that would allocate on every call site where the
11796        // `&'static str` return of [`super::RestartPolicy::as_str`]
11797        // makes the zero-alloc borrowed projection type-correct) trips
11798        // at caixa-core test time under the
11799        // [`std::borrow::Cow::Borrowed`] discriminator witness rather
11800        // than at a downstream `Cow<'static, str>`-bound consumer's
11801        // silent allocation.
11802        //
11803        // Second peer on the substrate-wide trait-idiomatic
11804        // [`std::borrow::Cow<'static, str>`] forward-projection family
11805        // to extend the axis off the top-level [`super::CaixaKind`]
11806        // enum (99c1735 owned-input, d45c409 borrowed-input) onto the
11807        // second (and second-of-two-in-M2) M2 OTP-shape closed-set
11808        // fieldless typed enum peer on the caixa surface — closes the
11809        // M2 OTP-shape tier of the campaign on the owned-input axis
11810        // (both sibling peers, `RestartStrategy` and `RestartPolicy`,
11811        // now carry the owned-input Cow<'static, str> forward
11812        // projection).
11813        for &variant in RestartPolicy::ALL {
11814            let via_trait: std::borrow::Cow<'static, str> =
11815                <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
11816            let via_method: &'static str = variant.as_str();
11817            assert_eq!(
11818                via_trait.as_ref(),
11819                via_method,
11820                "From<RestartPolicy> for Cow<'static, str> impl must \
11821                 round-trip RestartPolicy::{variant:?} to the same \
11822                 lifted SUPERVISOR_CHILD_RESTART_* const \
11823                 RestartPolicy::as_str returns — divergence signals a \
11824                 silent detour off the substrate-primitive accessor"
11825            );
11826            assert!(
11827                matches!(via_trait, std::borrow::Cow::Borrowed(_)),
11828                "From<RestartPolicy> for Cow<'static, str> impl must \
11829                 land on the zero-alloc Cow::Borrowed arm on \
11830                 RestartPolicy::{variant:?} — a Cow::Owned outcome \
11831                 signals the projection has silently allocated where \
11832                 the substrate-primitive RestartPolicy::as_str \
11833                 `&'static str` return makes the borrowed arm the \
11834                 type-correct projection"
11835            );
11836            let via_into: std::borrow::Cow<'static, str> = variant.into();
11837            assert_eq!(
11838                via_into.as_ref(),
11839                via_method,
11840                "Into<Cow<'static, str>>::into on \
11841                 RestartPolicy::{variant:?} must byte-equal \
11842                 RestartPolicy::as_str on the same input — the \
11843                 blanket-derived Into shape must resolve to the same \
11844                 as_str dispatch as the explicit From impl"
11845            );
11846            assert!(
11847                matches!(via_into, std::borrow::Cow::Borrowed(_)),
11848                "Into<Cow<'static, str>>::into on \
11849                 RestartPolicy::{variant:?} must land on the \
11850                 zero-alloc Cow::Borrowed arm — the blanket-derived \
11851                 Into shape must resolve to the same Cow::Borrowed \
11852                 dispatch as the explicit From impl"
11853            );
11854        }
11855    }
11856
11857    #[test]
11858    fn restart_policy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
11859        // Cross-axis partition pin: the newly lifted trait-idiomatic
11860        // `From<RestartPolicy> for std::borrow::Cow<'static, str>`
11861        // (this lift), the paired owned-input `From<RestartPolicy>
11862        // for &'static str` (9fb37d0), and the paired owned-input
11863        // `From<RestartPolicy> for String` (7851725) forward
11864        // projections must resolve identically on every arm, locking
11865        // the three return-shape paths together by construction so any
11866        // future detour trips at caixa-core test time. Also byte-parity
11867        // witness against the sibling [`ToString::to_string`] surface
11868        // routed through [`std::fmt::Display`] — every owned-heap-
11869        // string path (the `Cow::Owned` promotion of this axis's
11870        // `.into_owned()`, `From<RestartPolicy> for String`, and
11871        // `.to_string()`) resolves to the same lifted
11872        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const per arm.
11873        //
11874        // Then a `.iter().copied().map(std::borrow::Cow::from)` pipe
11875        // witness over [`super::RestartPolicy::ALL`] that
11876        // materializes the three-arm accept-set through the
11877        // [`std::borrow::Cow<'static, str>`] axis alone — the exact
11878        // shape a future `axum::response::IntoResponse` per-policy
11879        // rejection-body composer, a future M4 admission-webhook
11880        // per-policy rejection-reason emitter whose typing rules out
11881        // the sibling [`AsRef<str>`] borrowed return, or a future
11882        // substrate-wide per-policy diagnostic surface that binds
11883        // through a [`Cow<'static, str>`] boundary reaches through.
11884        // The pipe witness also pins the zero-alloc discipline: every
11885        // element in the collected vector satisfies the
11886        // [`std::borrow::Cow::Borrowed`] arm predicate, so a future
11887        // accidental silent-allocation regression on the pipe's
11888        // iteration axis is a caixa-core-test-time failure. Peer of
11889        // the first-mover
11890        // [`restart_strategy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
11891        // (7dd28b3) on the sibling M2 OTP-shape sibling-restart axis
11892        // — closes the whole owned-input `Cow<'static, str>` +
11893        // paired `{&'static str, String}` cross-axis-parity corner on
11894        // both M2 OTP-shape sibling peers.
11895        for &variant in RestartPolicy::ALL {
11896            let via_cow: std::borrow::Cow<'static, str> =
11897                <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
11898            let via_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
11899            let via_string: String = <String as From<RestartPolicy>>::from(variant);
11900            assert_eq!(
11901                via_cow.as_ref(),
11902                via_static,
11903                "From<RestartPolicy> for Cow<'static, str> and \
11904                 From<RestartPolicy> for &'static str must resolve \
11905                 identically on RestartPolicy::{variant:?} — \
11906                 divergence signals the Cow<'static, str> and \
11907                 &'static str return-shape paths have drifted onto \
11908                 different emit-sets"
11909            );
11910            assert_eq!(
11911                via_cow.as_ref(),
11912                via_string.as_str(),
11913                "From<RestartPolicy> for Cow<'static, str> and \
11914                 From<RestartPolicy> for String must resolve \
11915                 identically on RestartPolicy::{variant:?} — \
11916                 divergence signals the Cow<'static, str> and String \
11917                 return-shape paths have drifted onto different \
11918                 emit-sets"
11919            );
11920            let via_to_string: String = variant.to_string();
11921            assert_eq!(
11922                via_cow.as_ref(),
11923                via_to_string.as_str(),
11924                "From<RestartPolicy> for Cow<'static, str> must \
11925                 byte-equal RestartPolicy::to_string on \
11926                 RestartPolicy::{variant:?} — divergence signals the \
11927                 trait-idiomatic Cow<'static, str> forward-projection \
11928                 axis and the ToString-through-Display axis have \
11929                 drifted onto different emit-sets"
11930            );
11931        }
11932        let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
11933            .iter()
11934            .copied()
11935            .map(std::borrow::Cow::from)
11936            .collect();
11937        let via_method: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
11938            .iter()
11939            .map(|p| std::borrow::Cow::Borrowed(p.as_str()))
11940            .collect();
11941        assert_eq!(
11942            via_iter, via_method,
11943            "`.iter().copied().map(Cow::from)` over \
11944             RestartPolicy::ALL must byte-equal `.iter().map(|p| \
11945             Cow::Borrowed(p.as_str()))` on every arm — the \
11946             trait-idiomatic `From<RestartPolicy> for Cow<'static, \
11947             str>` axis is what makes the `Cow::from` composition \
11948             route through the substrate-primitive \
11949             `RestartPolicy::as_str` accessor with the zero-alloc \
11950             Cow::Borrowed arm by construction, rather than a \
11951             per-call-site `Cow::Owned(policy.to_string())` \
11952             allocation"
11953        );
11954        for cow in &via_iter {
11955            assert!(
11956                matches!(cow, std::borrow::Cow::Borrowed(_)),
11957                "every element of the \
11958                 .iter().copied().map(Cow::from) pipe over \
11959                 RestartPolicy::ALL must land on the zero-alloc \
11960                 Cow::Borrowed arm — a Cow::Owned outcome on any arm \
11961                 signals the pipe's iteration axis has silently \
11962                 allocated where the substrate-primitive \
11963                 RestartPolicy::as_str `&'static str` return makes \
11964                 the borrowed arm the type-correct projection"
11965            );
11966        }
11967    }
11968
11969    #[test]
11970    fn restart_policy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor() {
11971        // Fail-before-pass-after byte-parity pin on the newly lifted
11972        // `impl From<&RestartPolicy> for std::borrow::Cow<'static, str>` —
11973        // asserts the borrowed-input standard-library trait impl and
11974        // the substrate-primitive [`super::RestartPolicy::as_str`]
11975        // `pub const fn` accessor resolve to the same three-arm emit-
11976        // set across every arm the exhaustive
11977        // [`super::RestartPolicy::ALL`] slice enumerates. Rust's
11978        // standard library does not carry a blanket
11979        // `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor a
11980        // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`), so
11981        // the borrowed-input `Cow<'static, str>` forward-projection
11982        // axis is a distinct trait-idiomatic surface that a
11983        // `let key: Cow<'static, str> = (&policy).into();`-shaped
11984        // call site or a
11985        // `RestartPolicy::ALL.iter().map(Cow::from)`-shaped pipe
11986        // reaches through this impl and no other — the paired owned-
11987        // input `From<RestartPolicy> for Cow<'static, str>` impl
11988        // (0612398) forces every borrowed-input call site through an
11989        // explicit `Copy` deref (`Cow::from(*policy)`) or a
11990        // `Cow::Borrowed(policy.as_str())` open-code whose type
11991        // bounds have no compile-time link back to the substrate
11992        // primitive.
11993        //
11994        // Also asserts the projection lands on the zero-alloc
11995        // [`std::borrow::Cow::Borrowed`] arm (not the
11996        // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
11997        // [`super::RestartPolicy::as_str`] accessor's `&'static str`
11998        // return lifetime by construction makes the borrowed arm the
11999        // type-correct projection with no runtime allocation on the
12000        // borrowed-input surface just as on the paired owned-input
12001        // surface.
12002        //
12003        // Closes the `{Self, &Self}` input-shape corner on the M2
12004        // OTP-shape per-child-restart [`Cow<'static, str>`] axis on
12005        // the second-of-two-in-M2 closed-set fieldless typed enum peer
12006        // on the caixa surface (`:supervisor :children :restart`),
12007        // exactly as d45c409 closed it on the top-level
12008        // [`super::CaixaKind`] one commit after the owning half
12009        // (99c1735) landed and as 9b3e4b3 closed it on the sibling
12010        // M2 OTP-shape [`super::RestartStrategy`] one commit after
12011        // (7dd28b3) landed. This lift closes the whole M2 OTP-shape
12012        // tier of the substrate-wide Cow<'static, str> forward-
12013        // projection campaign on both input-shape corners
12014        // ({Self, &Self}) of both M2 OTP-shape sibling peers.
12015        for &variant in RestartPolicy::ALL {
12016            let via_trait: std::borrow::Cow<'static, str> =
12017                <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&variant);
12018            let via_method: &'static str = variant.as_str();
12019            assert_eq!(
12020                via_trait.as_ref(),
12021                via_method,
12022                "From<&RestartPolicy> for Cow<'static, str> impl must \
12023                 round-trip &RestartPolicy::{variant:?} to the same \
12024                 lifted SUPERVISOR_CHILD_RESTART_* const \
12025                 RestartPolicy::as_str returns — divergence signals a \
12026                 silent detour off the substrate-primitive accessor"
12027            );
12028            assert!(
12029                matches!(via_trait, std::borrow::Cow::Borrowed(_)),
12030                "From<&RestartPolicy> for Cow<'static, str> impl must \
12031                 land on the zero-alloc Cow::Borrowed arm on \
12032                 &RestartPolicy::{variant:?} — a Cow::Owned outcome \
12033                 signals the projection has silently allocated where \
12034                 the substrate-primitive RestartPolicy::as_str \
12035                 `&'static str` return makes the borrowed arm the \
12036                 type-correct projection"
12037            );
12038            let via_into: std::borrow::Cow<'static, str> = (&variant).into();
12039            assert_eq!(
12040                via_into.as_ref(),
12041                via_method,
12042                "Into<Cow<'static, str>>::into on \
12043                 &RestartPolicy::{variant:?} must byte-equal \
12044                 RestartPolicy::as_str on the same input — the \
12045                 blanket-derived Into shape must resolve to the same \
12046                 as_str dispatch as the explicit From impl"
12047            );
12048            assert!(
12049                matches!(via_into, std::borrow::Cow::Borrowed(_)),
12050                "Into<Cow<'static, str>>::into on \
12051                 &RestartPolicy::{variant:?} must land on the \
12052                 zero-alloc Cow::Borrowed arm — the blanket-derived \
12053                 Into shape must resolve to the same Cow::Borrowed \
12054                 dispatch as the explicit From impl"
12055            );
12056        }
12057    }
12058
12059    #[test]
12060    fn restart_policy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
12061        // Cross-axis partition pin: the newly lifted trait-idiomatic
12062        // borrowed-input `From<&RestartPolicy> for
12063        // std::borrow::Cow<'static, str>` (this lift), the paired
12064        // owned-input `From<RestartPolicy> for
12065        // std::borrow::Cow<'static, str>` (0612398), the paired
12066        // borrowed-input owned-`&'static str` `From<&RestartPolicy>
12067        // for &'static str`, and the paired borrowed-input owned-
12068        // `String` `From<&RestartPolicy> for String` must resolve
12069        // identically on every arm, locking the four
12070        // return-shape × input-shape paths together by construction so
12071        // any future detour trips at caixa-core test time. Also byte-
12072        // parity witness against the sibling [`ToString::to_string`]
12073        // surface routed through [`std::fmt::Display`] — every owned-
12074        // heap-string path (this axis's `.into_owned()` promotion, the
12075        // paired [`From<&RestartPolicy> for String`], and
12076        // `.to_string()`) resolves to the same lifted
12077        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const per arm.
12078        //
12079        // Then a `.iter().map(std::borrow::Cow::from)` pipe witness
12080        // over [`super::RestartPolicy::ALL`] — whose iterator yields
12081        // `&RestartPolicy` by construction, so the borrowed-input
12082        // [`Cow<'static, str>`] axis is what routes the pipe through
12083        // the substrate-primitive [`super::RestartPolicy::as_str`]
12084        // accessor without a spurious [`Copy`] deref (which would only
12085        // be reachable through the owned-input
12086        // [`From<RestartPolicy> for Cow<'static, str>`] axis by first
12087        // calling `.copied()` on the iterator). The pipe witness also
12088        // pins the zero-alloc discipline: every element in the
12089        // collected vector satisfies the [`std::borrow::Cow::Borrowed`]
12090        // arm predicate, so a future accidental silent-allocation
12091        // regression on the pipe's iteration axis is a caixa-core-
12092        // test-time failure. Peer of the sibling
12093        // [`restart_strategy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
12094        // (9b3e4b3) on the M2 OTP-shape sibling-restart axis — closes
12095        // the whole borrowed-input `Cow<'static, str>` +
12096        // paired `{&'static str, String}` cross-axis-parity corner on
12097        // both M2 OTP-shape sibling peers.
12098        for &policy in RestartPolicy::ALL {
12099            let borrowed_cow: std::borrow::Cow<'static, str> =
12100                <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&policy);
12101            let owned_cow: std::borrow::Cow<'static, str> =
12102                <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(policy);
12103            let borrowed_static: &'static str =
12104                <&'static str as From<&RestartPolicy>>::from(&policy);
12105            let borrowed_string: String = <String as From<&RestartPolicy>>::from(&policy);
12106            assert_eq!(
12107                borrowed_cow, owned_cow,
12108                "From<&RestartPolicy> for Cow<'static, str> and \
12109                 From<RestartPolicy> for Cow<'static, str> must \
12110                 resolve identically on RestartPolicy::{policy:?} — \
12111                 divergence signals the borrowed-input and owned-input \
12112                 Cow<'static, str> forward-projection input-shape \
12113                 paths have drifted onto different emit-sets"
12114            );
12115            assert_eq!(
12116                borrowed_cow.as_ref(),
12117                borrowed_static,
12118                "From<&RestartPolicy> for Cow<'static, str> and \
12119                 From<&RestartPolicy> for &'static str must resolve \
12120                 identically on RestartPolicy::{policy:?} — \
12121                 divergence signals the borrowed-input Cow<'static, \
12122                 str> and &'static str return-shape paths have drifted \
12123                 onto different emit-sets"
12124            );
12125            assert_eq!(
12126                borrowed_cow.as_ref(),
12127                borrowed_string.as_str(),
12128                "From<&RestartPolicy> for Cow<'static, str> and \
12129                 From<&RestartPolicy> for String must resolve \
12130                 identically on RestartPolicy::{policy:?} — \
12131                 divergence signals the borrowed-input Cow<'static, \
12132                 str> and owned-`String` return-shape paths have \
12133                 drifted onto different emit-sets"
12134            );
12135            let via_to_string: String = policy.to_string();
12136            assert_eq!(
12137                borrowed_cow.as_ref(),
12138                via_to_string.as_str(),
12139                "From<&RestartPolicy> for Cow<'static, str> must \
12140                 byte-equal RestartPolicy::to_string on \
12141                 RestartPolicy::{policy:?} — divergence signals \
12142                 the trait-idiomatic borrowed-input Cow<'static, str> \
12143                 forward-projection axis and the ToString-through-\
12144                 Display axis have drifted onto different emit-sets"
12145            );
12146        }
12147        let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
12148            .iter()
12149            .map(std::borrow::Cow::from)
12150            .collect();
12151        let via_method: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
12152            .iter()
12153            .map(|p| std::borrow::Cow::Borrowed(p.as_str()))
12154            .collect();
12155        assert_eq!(
12156            via_iter, via_method,
12157            "`.iter().map(Cow::from)` over RestartPolicy::ALL — a \
12158             call site whose iteration axis holds `&RestartPolicy` \
12159             by construction — must byte-equal `.iter().map(|p| \
12160             Cow::Borrowed(p.as_str()))` on every arm — the borrowed-\
12161             input Cow<'static, str> `From<&RestartPolicy> for \
12162             Cow<'static, str>` axis is what makes the `Cow::from` \
12163             composition route through the substrate-primitive \
12164             `RestartPolicy::as_str` accessor with the zero-alloc \
12165             Cow::Borrowed arm by construction and without a spurious \
12166             `Copy` deref (which would only be reachable through the \
12167             owned-input `From<RestartPolicy> for Cow<'static, str>` \
12168             axis by first calling `.copied()` on the iterator)"
12169        );
12170        for cow in &via_iter {
12171            assert!(
12172                matches!(cow, std::borrow::Cow::Borrowed(_)),
12173                "every element of the .iter().map(Cow::from) pipe \
12174                 over RestartPolicy::ALL must land on the zero-\
12175                 alloc Cow::Borrowed arm — a Cow::Owned outcome on \
12176                 any arm signals the pipe's iteration axis has \
12177                 silently allocated where the substrate-primitive \
12178                 RestartPolicy::as_str `&'static str` return makes \
12179                 the borrowed arm the type-correct projection"
12180            );
12181        }
12182    }
12183
12184    #[test]
12185    fn restart_policy_from_into_box_str_routes_through_as_str_accessor() {
12186        // Fail-before-pass-after byte-parity pin on the newly lifted
12187        // `impl From<RestartPolicy> for Box<str>` — asserts the
12188        // owned-input standard-library trait impl and the
12189        // substrate-primitive [`super::RestartPolicy::as_str`]
12190        // `pub const fn` accessor resolve to the same three-arm emit-
12191        // set across every arm the exhaustive
12192        // [`super::RestartPolicy::ALL`] slice enumerates. Extends the
12193        // substrate-wide `Box<str>` forward-projection campaign tier
12194        // opened one commit prior (69ef45c) on the paired sibling-
12195        // restart [`RestartStrategy`] onto the second (and third-and-
12196        // final) M2 OTP-shape closed-set fieldless typed enum peer on
12197        // the caixa surface (`:children :restart`), immediately after
12198        // the paired `Cow<'static, str>` axis (0612398 / b4dc55c)
12199        // closed the
12200        // `{Self, &Self} × {&'static str, String, Cow<'static, str>}`
12201        // 2×3 corner on this enum. Rust's standard library carries
12202        // `impl From<&str> for Box<str>` and
12203        // `impl From<String> for Box<str>` but no blanket
12204        // `impl<T: AsRef<str>> From<T> for Box<str>`, so this axis is
12205        // a distinct trait-idiomatic surface that a
12206        // `let key: Box<str> = policy.into();`-shaped call site
12207        // reaches through this impl and no other — a paired
12208        // `Box::from(policy.as_str())` open-code has no compile-time
12209        // link back to the substrate primitive. Peer of the sibling
12210        // [`restart_strategy_from_into_box_str_routes_through_as_str_accessor`]
12211        // (69ef45c) — extends the trait-idiomatic owned-input
12212        // [`Box<str>`] forward-projection axis onto the third and
12213        // final M2-OTP-shape closed-set typed enum on the caixa
12214        // surface.
12215        for &variant in RestartPolicy::ALL {
12216            let via_trait: Box<str> = <Box<str> as From<RestartPolicy>>::from(variant);
12217            let via_method: &'static str = variant.as_str();
12218            assert_eq!(
12219                via_trait.as_ref(),
12220                via_method,
12221                "From<RestartPolicy> for Box<str> impl must round-\
12222                 trip RestartPolicy::{variant:?} to the same lifted \
12223                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
12224                 returns — divergence signals a silent detour off the \
12225                 substrate-primitive accessor"
12226            );
12227            let via_into: Box<str> = variant.into();
12228            assert_eq!(
12229                via_into.as_ref(),
12230                via_method,
12231                "Into<Box<str>>::into on RestartPolicy::{variant:?} \
12232                 must byte-equal RestartPolicy::as_str on the same \
12233                 input — the blanket-derived Into shape must resolve \
12234                 to the same as_str dispatch as the explicit From impl"
12235            );
12236        }
12237    }
12238
12239    #[test]
12240    fn restart_policy_from_borrowed_into_box_str_routes_through_as_str_accessor() {
12241        // Fail-before-pass-after byte-parity pin on the newly lifted
12242        // `impl From<&RestartPolicy> for Box<str>` — asserts the
12243        // borrowed-input standard-library trait impl and the
12244        // substrate-primitive [`super::RestartPolicy::as_str`]
12245        // `pub const fn` accessor resolve to the same three-arm emit-
12246        // set across every arm the exhaustive
12247        // [`super::RestartPolicy::ALL`] slice enumerates. Rust's
12248        // standard library does not carry a blanket
12249        // `impl<T: AsRef<str>> From<&T> for Box<str>` (nor a
12250        // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`),
12251        // so the borrowed-input `Box<str>` forward-projection axis
12252        // is a distinct trait-idiomatic surface that a
12253        // `let key: Box<str> = (&policy).into();`-shaped call site
12254        // or a `RestartPolicy::ALL.iter().map(Box::<str>::from)`-
12255        // shaped pipe reaches through this impl and no other — the
12256        // paired owned-input `From<RestartPolicy> for Box<str>`
12257        // impl (0a1b313) forces every borrowed-input call site
12258        // through an explicit `Copy` deref
12259        // (`Box::<str>::from((*policy).as_str())`) or a
12260        // `Box::<str>::from(policy.as_str())` open-code whose
12261        // type bounds have no compile-time link back to the
12262        // substrate primitive.
12263        //
12264        // Fourth (and closing) peer on the substrate-wide trait-
12265        // idiomatic [`Box<str>`] forward-projection family on the
12266        // M2 OTP-shape tier — closes the `{Self, &Self}` input-
12267        // shape corner of the [`Box<str>`] axis on the second (and
12268        // third-and-final) M2 OTP-shape closed-set fieldless typed
12269        // enum peer on the caixa surface (`:children :restart`),
12270        // exactly as b4dc55c closed the paired [`Cow<'static, str>`]
12271        // axis one commit after its owning half (0612398) landed
12272        // on this enum. Every remaining closed-set fieldless typed
12273        // enum peer on the M3 mesh-shape / outside-M3 caixa-core /
12274        // render-side / outside-caixa-core tiers is a future
12275        // target of the campaign.
12276        //
12277        // Also byte-parity witness against the paired owned-input
12278        // [`From<RestartPolicy> for Box<str>`] and the sibling
12279        // borrowed-input [`From<&RestartPolicy> for &'static str`],
12280        // [`From<&RestartPolicy> for String`], and
12281        // [`From<&RestartPolicy> for Cow<'static, str>`]
12282        // return-shape axes — locking the four
12283        // return-shape × input-shape paths together by construction
12284        // so any future detour trips at caixa-core test time. Then a
12285        // `.iter().map(Box::<str>::from)` pipe witness over
12286        // [`super::RestartPolicy::ALL`] — whose iterator yields
12287        // `&RestartPolicy` by construction, so the borrowed-input
12288        // [`Box<str>`] axis is what routes the pipe through the
12289        // substrate-primitive [`super::RestartPolicy::as_str`]
12290        // accessor without a spurious [`Copy`] deref (which would
12291        // only be reachable through the owned-input
12292        // [`From<RestartPolicy> for Box<str>`] axis by first
12293        // calling `.copied()` on the iterator).
12294        for &variant in RestartPolicy::ALL {
12295            let via_trait: Box<str> = <Box<str> as From<&RestartPolicy>>::from(&variant);
12296            let via_method: &'static str = variant.as_str();
12297            assert_eq!(
12298                via_trait.as_ref(),
12299                via_method,
12300                "From<&RestartPolicy> for Box<str> impl must round-\
12301                 trip &RestartPolicy::{variant:?} to the same lifted \
12302                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
12303                 returns — divergence signals a silent detour off the \
12304                 substrate-primitive accessor"
12305            );
12306            let via_into: Box<str> = (&variant).into();
12307            assert_eq!(
12308                via_into.as_ref(),
12309                via_method,
12310                "Into<Box<str>>::into on &RestartPolicy::{variant:?} \
12311                 must byte-equal RestartPolicy::as_str on the same \
12312                 input — the blanket-derived Into shape must resolve \
12313                 to the same as_str dispatch as the explicit From impl"
12314            );
12315            let owned_box: Box<str> = <Box<str> as From<RestartPolicy>>::from(variant);
12316            assert_eq!(
12317                via_trait, owned_box,
12318                "From<&RestartPolicy> for Box<str> and \
12319                 From<RestartPolicy> for Box<str> must resolve \
12320                 identically on RestartPolicy::{variant:?} — \
12321                 divergence signals the borrowed-input and owned-input \
12322                 Box<str> forward-projection input-shape paths have \
12323                 drifted onto different emit-sets"
12324            );
12325            let borrowed_static: &'static str =
12326                <&'static str as From<&RestartPolicy>>::from(&variant);
12327            assert_eq!(
12328                via_trait.as_ref(),
12329                borrowed_static,
12330                "From<&RestartPolicy> for Box<str> and \
12331                 From<&RestartPolicy> for &'static str must resolve \
12332                 identically on RestartPolicy::{variant:?} — \
12333                 divergence signals the borrowed-input Box<str> and \
12334                 &'static str return-shape paths have drifted onto \
12335                 different emit-sets"
12336            );
12337            let borrowed_string: String = <String as From<&RestartPolicy>>::from(&variant);
12338            assert_eq!(
12339                via_trait.as_ref(),
12340                borrowed_string.as_str(),
12341                "From<&RestartPolicy> for Box<str> and \
12342                 From<&RestartPolicy> for String must resolve \
12343                 identically on RestartPolicy::{variant:?} — \
12344                 divergence signals the borrowed-input Box<str> and \
12345                 owned-`String` return-shape paths have drifted onto \
12346                 different emit-sets"
12347            );
12348            let borrowed_cow: std::borrow::Cow<'static, str> =
12349                <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&variant);
12350            assert_eq!(
12351                via_trait.as_ref(),
12352                borrowed_cow.as_ref(),
12353                "From<&RestartPolicy> for Box<str> and \
12354                 From<&RestartPolicy> for Cow<'static, str> must \
12355                 resolve identically on RestartPolicy::{variant:?} — \
12356                 divergence signals the borrowed-input Box<str> and \
12357                 Cow<'static, str> return-shape paths have drifted \
12358                 onto different emit-sets"
12359            );
12360        }
12361        let via_iter: Vec<Box<str>> = RestartPolicy::ALL.iter().map(Box::<str>::from).collect();
12362        let via_method: Vec<Box<str>> = RestartPolicy::ALL
12363            .iter()
12364            .map(|p| Box::<str>::from(p.as_str()))
12365            .collect();
12366        assert_eq!(
12367            via_iter, via_method,
12368            "`.iter().map(Box::<str>::from)` over \
12369             RestartPolicy::ALL — a call site whose iteration axis \
12370             holds `&RestartPolicy` by construction — must byte-\
12371             equal `.iter().map(|p| Box::<str>::from(p.as_str()))` \
12372             on every arm — the borrowed-input Box<str> \
12373             `From<&RestartPolicy> for Box<str>` axis is what \
12374             makes the `Box::<str>::from` composition route through \
12375             the substrate-primitive `RestartPolicy::as_str` \
12376             accessor without a spurious `Copy` deref (which would \
12377             only be reachable through the owned-input \
12378             `From<RestartPolicy> for Box<str>` axis by first \
12379             calling `.copied()` on the iterator)"
12380        );
12381    }
12382
12383    #[test]
12384    fn restart_policy_from_into_arc_str_routes_through_as_str_accessor() {
12385        // Fail-before-pass-after byte-parity pin on the newly lifted
12386        // `impl From<RestartPolicy> for std::sync::Arc<str>` — asserts
12387        // the owned-input standard-library trait impl and the
12388        // substrate-primitive [`super::RestartPolicy::as_str`]
12389        // `pub const fn` accessor resolve to the same three-arm emit-
12390        // set across every arm the exhaustive
12391        // [`super::RestartPolicy::ALL`] slice enumerates. Extends the
12392        // substrate-wide [`std::sync::Arc<str>`] forward-projection
12393        // campaign tier opened one projection tier prior (bca2ec8) on
12394        // the paired sibling-restart [`RestartStrategy`] owned-input
12395        // first-mover onto the second (and third-and-final) M2 OTP-
12396        // shape closed-set fieldless typed enum peer on the caixa
12397        // surface (`:children :restart`), immediately after the paired
12398        // [`Box<str>`] axis (0a1b313 / cb1d068) closed the
12399        // `{Self, &Self} × {&'static str, String, Cow<'static, str>,
12400        // Box<str>}` 2×4 corner on this enum. Rust's standard library
12401        // carries `impl From<&str> for std::sync::Arc<str>` and
12402        // `impl From<String> for std::sync::Arc<str>` but no blanket
12403        // `impl<T: AsRef<str>> From<T> for std::sync::Arc<str>` (nor
12404        // an `impl<T: fmt::Display> From<T> for std::sync::Arc<str>`),
12405        // so this axis is a distinct trait-idiomatic surface that a
12406        // `let key: std::sync::Arc<str> = policy.into();`-shaped call
12407        // site reaches through this impl and no other — a paired
12408        // `std::sync::Arc::<str>::from(policy.as_str())` open-code
12409        // has no compile-time link back to the substrate primitive,
12410        // and a two-step `std::sync::Arc::<str>::from(String::from(
12411        // policy))` composition through the owned-`String` axis
12412        // allocates twice (once into the intermediate `String`, once
12413        // into the [`Arc<str>`] on the `From<String>` conversion)
12414        // where the single-step trait impl allocates once.
12415        //
12416        // Cross-axis byte-parity witness against the sibling owned-
12417        // input `{&'static str, String, Cow<'static, str>, Box<str>}`
12418        // return-shape axes — locking the five return-shape paths on
12419        // the owned-input surface together by construction so any
12420        // future detour off the substrate-primitive
12421        // [`super::RestartPolicy::as_str`] accessor trips at caixa-
12422        // core test time.
12423        for &variant in RestartPolicy::ALL {
12424            let via_trait: std::sync::Arc<str> =
12425                <std::sync::Arc<str> as From<RestartPolicy>>::from(variant);
12426            let via_method: &'static str = variant.as_str();
12427            assert_eq!(
12428                via_trait.as_ref(),
12429                via_method,
12430                "From<RestartPolicy> for std::sync::Arc<str> impl \
12431                 must round-trip RestartPolicy::{variant:?} to the \
12432                 same lifted SUPERVISOR_CHILD_RESTART_* const \
12433                 RestartPolicy::as_str returns — divergence signals \
12434                 a silent detour off the substrate-primitive accessor"
12435            );
12436            let via_into: std::sync::Arc<str> = variant.into();
12437            assert_eq!(
12438                via_into.as_ref(),
12439                via_method,
12440                "Into<std::sync::Arc<str>>::into on \
12441                 RestartPolicy::{variant:?} must byte-equal \
12442                 RestartPolicy::as_str on the same input — the \
12443                 blanket-derived Into shape must resolve to the same \
12444                 as_str dispatch as the explicit From impl"
12445            );
12446            let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
12447            assert_eq!(
12448                via_trait.as_ref(),
12449                owned_static,
12450                "From<RestartPolicy> for std::sync::Arc<str> and \
12451                 From<RestartPolicy> for &'static str must resolve \
12452                 identically on RestartPolicy::{variant:?} — \
12453                 divergence signals the owned-input std::sync::Arc<str> \
12454                 and &'static str return-shape paths have drifted onto \
12455                 different emit-sets"
12456            );
12457            let owned_string: String = <String as From<RestartPolicy>>::from(variant);
12458            assert_eq!(
12459                via_trait.as_ref(),
12460                owned_string.as_str(),
12461                "From<RestartPolicy> for std::sync::Arc<str> and \
12462                 From<RestartPolicy> for String must resolve \
12463                 identically on RestartPolicy::{variant:?} — \
12464                 divergence signals the owned-input std::sync::Arc<str> \
12465                 and owned-`String` return-shape paths have drifted \
12466                 onto different emit-sets"
12467            );
12468            let owned_cow: std::borrow::Cow<'static, str> =
12469                <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
12470            assert_eq!(
12471                via_trait.as_ref(),
12472                owned_cow.as_ref(),
12473                "From<RestartPolicy> for std::sync::Arc<str> and \
12474                 From<RestartPolicy> for Cow<'static, str> must \
12475                 resolve identically on RestartPolicy::{variant:?} — \
12476                 divergence signals the owned-input std::sync::Arc<str> \
12477                 and Cow<'static, str> return-shape paths have drifted \
12478                 onto different emit-sets"
12479            );
12480            let owned_box: Box<str> = <Box<str> as From<RestartPolicy>>::from(variant);
12481            assert_eq!(
12482                via_trait.as_ref(),
12483                owned_box.as_ref(),
12484                "From<RestartPolicy> for std::sync::Arc<str> and \
12485                 From<RestartPolicy> for Box<str> must resolve \
12486                 identically on RestartPolicy::{variant:?} — \
12487                 divergence signals the owned-input std::sync::Arc<str> \
12488                 and Box<str> return-shape paths have drifted onto \
12489                 different emit-sets"
12490            );
12491        }
12492    }
12493
12494    #[test]
12495    fn restart_policy_from_borrowed_into_arc_str_routes_through_as_str_accessor() {
12496        // Fail-before-pass-after byte-parity pin on the newly lifted
12497        // `impl From<&RestartPolicy> for std::sync::Arc<str>` —
12498        // asserts the borrowed-input standard-library trait impl and
12499        // the substrate-primitive [`super::RestartPolicy::as_str`]
12500        // `pub const fn` accessor resolve to the same three-arm
12501        // emit-set across every arm the exhaustive
12502        // [`super::RestartPolicy::ALL`] slice enumerates. Rust's
12503        // standard library carries `impl From<&str> for
12504        // std::sync::Arc<str>` and `impl From<String> for
12505        // std::sync::Arc<str>` but no blanket
12506        // `impl<T: AsRef<str>> From<&T> for std::sync::Arc<str>` (nor
12507        // a `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`),
12508        // so the borrowed-input [`std::sync::Arc<str>`] forward-
12509        // projection axis is a distinct trait-idiomatic surface that
12510        // a `let key: std::sync::Arc<str> = (&policy).into();`-shaped
12511        // call site or a
12512        // `RestartPolicy::ALL.iter().map(std::sync::Arc::<str>::from)`-
12513        // shaped pipe reaches through this impl and no other — the
12514        // paired owned-input [`From<RestartPolicy> for
12515        // std::sync::Arc<str>`] impl (b05724e) forces every borrowed-
12516        // input call site through an explicit [`Copy`] deref
12517        // (`std::sync::Arc::<str>::from((*policy).as_str())`) or a
12518        // `std::sync::Arc::<str>::from(policy.as_str())` open-code
12519        // whose type bounds have no compile-time link back to the
12520        // substrate primitive.
12521        //
12522        // Closes the `{Self, &Self}` input-shape corner of the
12523        // substrate-wide trait-idiomatic [`std::sync::Arc<str>`]
12524        // forward-projection family on the second (and third-and-
12525        // final) M2 OTP-shape closed-set fieldless typed enum peer
12526        // on the caixa surface (`:children :restart`), one commit
12527        // after b05724e opened the owned-input half — exactly as
12528        // b3e72d7 closed the paired [`std::sync::Arc<str>`] corner on
12529        // the sibling-restart [`RestartStrategy`] first-mover one
12530        // commit after its owning half (bca2ec8) landed, and as
12531        // cb1d068 closed the paired [`Box<str>`] corner on this
12532        // enum one commit after its owning half (0a1b313) landed.
12533        //
12534        // Also byte-parity witness against the paired owned-input
12535        // [`From<RestartPolicy> for std::sync::Arc<str>`] and the
12536        // sibling borrowed-input [`From<&RestartPolicy> for
12537        // &'static str`], [`From<&RestartPolicy> for String`],
12538        // [`From<&RestartPolicy> for Cow<'static, str>`], and
12539        // [`From<&RestartPolicy> for Box<str>`] return-shape axes —
12540        // locking the five return-shape × input-shape paths together
12541        // by construction so any future detour off the substrate-
12542        // primitive [`super::RestartPolicy::as_str`] accessor trips
12543        // at caixa-core test time. Then a
12544        // `.iter().map(std::sync::Arc::<str>::from)` pipe witness
12545        // over [`super::RestartPolicy::ALL`] — whose iterator yields
12546        // `&RestartPolicy` by construction, so the borrowed-input
12547        // [`std::sync::Arc<str>`] axis is what routes the pipe
12548        // through the substrate-primitive
12549        // [`super::RestartPolicy::as_str`] accessor without a
12550        // spurious [`Copy`] deref (which would only be reachable
12551        // through the owned-input
12552        // [`From<RestartPolicy> for std::sync::Arc<str>`] axis by
12553        // first calling `.copied()` on the iterator).
12554        for &variant in RestartPolicy::ALL {
12555            let via_trait: std::sync::Arc<str> =
12556                <std::sync::Arc<str> as From<&RestartPolicy>>::from(&variant);
12557            let via_method: &'static str = variant.as_str();
12558            assert_eq!(
12559                via_trait.as_ref(),
12560                via_method,
12561                "From<&RestartPolicy> for std::sync::Arc<str> impl \
12562                 must round-trip &RestartPolicy::{variant:?} to the \
12563                 same lifted SUPERVISOR_CHILD_RESTART_* const \
12564                 RestartPolicy::as_str returns — divergence signals \
12565                 a silent detour off the substrate-primitive accessor"
12566            );
12567            let via_into: std::sync::Arc<str> = (&variant).into();
12568            assert_eq!(
12569                via_into.as_ref(),
12570                via_method,
12571                "Into<std::sync::Arc<str>>::into on \
12572                 &RestartPolicy::{variant:?} must byte-equal \
12573                 RestartPolicy::as_str on the same input — the \
12574                 blanket-derived Into shape must resolve to the same \
12575                 as_str dispatch as the explicit From impl"
12576            );
12577            let owned_arc: std::sync::Arc<str> =
12578                <std::sync::Arc<str> as From<RestartPolicy>>::from(variant);
12579            assert_eq!(
12580                via_trait, owned_arc,
12581                "From<&RestartPolicy> for std::sync::Arc<str> and \
12582                 From<RestartPolicy> for std::sync::Arc<str> must \
12583                 resolve identically on RestartPolicy::{variant:?} — \
12584                 divergence signals the borrowed-input and owned-input \
12585                 std::sync::Arc<str> forward-projection input-shape \
12586                 paths have drifted onto different emit-sets"
12587            );
12588            let borrowed_static: &'static str =
12589                <&'static str as From<&RestartPolicy>>::from(&variant);
12590            assert_eq!(
12591                via_trait.as_ref(),
12592                borrowed_static,
12593                "From<&RestartPolicy> for std::sync::Arc<str> and \
12594                 From<&RestartPolicy> for &'static str must resolve \
12595                 identically on RestartPolicy::{variant:?} — \
12596                 divergence signals the borrowed-input std::sync::Arc<str> \
12597                 and &'static str return-shape paths have drifted onto \
12598                 different emit-sets"
12599            );
12600            let borrowed_string: String = <String as From<&RestartPolicy>>::from(&variant);
12601            assert_eq!(
12602                via_trait.as_ref(),
12603                borrowed_string.as_str(),
12604                "From<&RestartPolicy> for std::sync::Arc<str> and \
12605                 From<&RestartPolicy> for String must resolve \
12606                 identically on RestartPolicy::{variant:?} — \
12607                 divergence signals the borrowed-input std::sync::Arc<str> \
12608                 and owned-`String` return-shape paths have drifted \
12609                 onto different emit-sets"
12610            );
12611            let borrowed_cow: std::borrow::Cow<'static, str> =
12612                <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&variant);
12613            assert_eq!(
12614                via_trait.as_ref(),
12615                borrowed_cow.as_ref(),
12616                "From<&RestartPolicy> for std::sync::Arc<str> and \
12617                 From<&RestartPolicy> for Cow<'static, str> must \
12618                 resolve identically on RestartPolicy::{variant:?} — \
12619                 divergence signals the borrowed-input std::sync::Arc<str> \
12620                 and Cow<'static, str> return-shape paths have drifted \
12621                 onto different emit-sets"
12622            );
12623            let borrowed_box: Box<str> = <Box<str> as From<&RestartPolicy>>::from(&variant);
12624            assert_eq!(
12625                via_trait.as_ref(),
12626                borrowed_box.as_ref(),
12627                "From<&RestartPolicy> for std::sync::Arc<str> and \
12628                 From<&RestartPolicy> for Box<str> must resolve \
12629                 identically on RestartPolicy::{variant:?} — \
12630                 divergence signals the borrowed-input std::sync::Arc<str> \
12631                 and Box<str> return-shape paths have drifted onto \
12632                 different emit-sets"
12633            );
12634        }
12635        let via_iter: Vec<std::sync::Arc<str>> = RestartPolicy::ALL
12636            .iter()
12637            .map(std::sync::Arc::<str>::from)
12638            .collect();
12639        let via_method: Vec<std::sync::Arc<str>> = RestartPolicy::ALL
12640            .iter()
12641            .map(|p| std::sync::Arc::<str>::from(p.as_str()))
12642            .collect();
12643        assert_eq!(
12644            via_iter, via_method,
12645            "`.iter().map(std::sync::Arc::<str>::from)` over \
12646             RestartPolicy::ALL — a call site whose iteration axis \
12647             holds `&RestartPolicy` by construction — must byte-\
12648             equal `.iter().map(|p| std::sync::Arc::<str>::from(p.as_str()))` \
12649             on every arm — the borrowed-input std::sync::Arc<str> \
12650             `From<&RestartPolicy> for std::sync::Arc<str>` axis is \
12651             what makes the `std::sync::Arc::<str>::from` composition \
12652             route through the substrate-primitive \
12653             `RestartPolicy::as_str` accessor without a spurious \
12654             `Copy` deref (which would only be reachable through the \
12655             owned-input `From<RestartPolicy> for std::sync::Arc<str>` \
12656             axis by first calling `.copied()` on the iterator)"
12657        );
12658    }
12659
12660    // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_RESTART_* identity ─
12661
12662    #[test]
12663    fn restart_policy_variants_serialize_to_lifted_scalar_values() {
12664        // The fail-before-pass-after pin: pre-lift there was no
12665        // single-source binding between the [`RestartPolicy`] variant
12666        // name the un-`rename`d `Serialize` derive emits under
12667        // [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
12668        // byte-string every downstream cluster-side dispatcher (the
12669        // future wasm-operator's per-child post-exit restart-decision
12670        // branch, the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
12671        // materializer's admission-time enum-arm bind, the
12672        // `caixa-operator`'s hierarchical reconciliation scheduler's
12673        // per-child-policy fan-out) probes verbatim. A future
12674        // `#[serde(rename_all = "kebab-case")]` attribute on the enum —
12675        // or a per-variant `#[serde(rename = "…")]` override, or a
12676        // variant rename in the source — would silently rebrand the
12677        // emitted scalar under one spelling while every downstream
12678        // dispatcher still probed the other, with the failure surfacing
12679        // at the operator's reconcile posture (children coming up under
12680        // the `default()` `Permanent` arm rather than the typed slot's
12681        // declared policy — a `:temporary` `oneShot` child would be
12682        // restarted on clean exit, treating the successful-completion
12683        // signal as failure and re-running the completion-terminal
12684        // one-shot indefinitely; a `:transient` child that clean-exited
12685        // would be restarted, masking the clean-completion contract)
12686        // far from the source rebrand commit and with no field naming
12687        // the drift. Pinning the two paths (the `Serialize` derive's
12688        // serialized string AND the [`RestartPolicy::as_str`] helper)
12689        // to the same three lifted
12690        // [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
12691        // [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
12692        // [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
12693        // byte-strings makes any future drift on either endpoint fail
12694        // here at caixa-core build time. Peer of the sibling
12695        // [`restart_strategy_variants_serialize_to_lifted_scalar_values`]
12696        // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
12697        // and the M3
12698        // `placement_strategy_variants_serialize_to_lifted_scalar_values`
12699        // (3f0e21c) on the per-Aplicacao distribution-strategy axis —
12700        // same three-path-convergence discipline, extended to close the
12701        // third OTP-shaped closed-enum discriminator axis on the caixa
12702        // typed surface (per-child restart-decision policy).
12703        for (variant, expected) in [
12704            (
12705                RestartPolicy::Permanent,
12706                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
12707            ),
12708            (
12709                RestartPolicy::Temporary,
12710                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
12711            ),
12712            (
12713                RestartPolicy::Transient,
12714                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
12715            ),
12716        ] {
12717            let json = serde_json::to_string(&variant).unwrap();
12718            assert_eq!(
12719                json,
12720                format!("\"{expected}\""),
12721                "RestartPolicy::{variant:?} must serialize to {expected:?}"
12722            );
12723            assert_eq!(
12724                variant.as_str(),
12725                expected,
12726                "RestartPolicy::{variant:?}.as_str() must return the lifted \
12727                 SUPERVISOR_CHILD_RESTART_* constant"
12728            );
12729        }
12730    }
12731
12732    #[test]
12733    fn supervisor_child_restart_consts_are_pairwise_distinct() {
12734        // Cross-arm drift-detection pin: a future collapse of two
12735        // canonical variant byte-strings onto the same value (e.g. an
12736        // accidental copy-paste flip of `SUPERVISOR_CHILD_RESTART_TRANSIENT`
12737        // to also read `"Permanent"`) would silently reroute every
12738        // downstream operator's per-child-policy dispatch onto the
12739        // sibling arm's reconcile branch and pass every propagation-probe
12740        // test that expected only the stale arm's value — a `:transient`
12741        // child would come up under the `:permanent` restart-decision
12742        // posture on every subsequent clean exit, so a completion-terminal
12743        // child would be restarted indefinitely against its declared
12744        // policy. Peer of the sibling
12745        // [`supervisor_estrategia_consts_are_pairwise_distinct`]
12746        // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
12747        // and the four-way distinct pin
12748        // `supervisor_key_consts_are_pairwise_distinct` (40cc4e5) on the
12749        // top-level `SUPERVISOR_KEY_*` axis.
12750        let all = [
12751            crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
12752            crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
12753            crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
12754        ];
12755        for (i, a) in all.iter().enumerate() {
12756            for (j, b) in all.iter().enumerate() {
12757                if i != j {
12758                    assert_ne!(
12759                        a, b,
12760                        "SUPERVISOR_CHILD_RESTART_* consts must be pairwise distinct \
12761                         — got duplicate {a:?} at indices {i} and {j}",
12762                    );
12763                }
12764            }
12765        }
12766    }
12767
12768    #[test]
12769    fn restart_policy_display_routes_through_as_str_helper() {
12770        // The fail-before-pass-after pin on the first half of the
12771        // three-path convergence: pre-convergence [`RestartPolicy`]
12772        // carried a [`std::fmt::Display`] surface via its
12773        // `#[discriminant(also_display)]` gen-platform derive route,
12774        // which arrived kebab-case as `"permanent"` / `"temporary"`
12775        // / `"transient"` on this three-arm enum (whose variant
12776        // names each collapse to their own lowercase form under the
12777        // kebab-case transform) while the wire format ran as
12778        // PascalCase `"Permanent"` / `"Temporary"` / `"Transient"`
12779        // through the un-`rename`d serde derive. Every consumer
12780        // reaching for a policy byte-string past the wire format had
12781        // to pick between three paths ([`RestartPolicy::as_str`],
12782        // the `Serialize` derive's serialized string, or
12783        // `format!("{v}")` on the discriminant-Display route), any
12784        // two of which a future variant rename or
12785        // `#[serde(rename_all = "kebab-case")]` attribute would
12786        // silently desynchronize. Wiring [`std::fmt::Display`]
12787        // through [`RestartPolicy::as_str`] closes the third path:
12788        // every `format!("{v}")` call reaches the same lifted
12789        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the
12790        // wire format and the [`RestartPolicy::as_str`] helper
12791        // already route through, so a future variant rename lands at
12792        // exactly one place. Pin the routing here so a future
12793        // `impl std::fmt::Display for RestartPolicy`
12794        // reimplementation that hand-rolls the arms instead of
12795        // delegating to [`RestartPolicy::as_str`] fails at
12796        // caixa-core build time. Peer of the sibling
12797        // [`restart_strategy_display_routes_through_as_str_helper`]
12798        // on the per-supervisor sibling-restart-strategy axis and
12799        // the M3
12800        // `placement_strategy_display_routes_through_as_str_helper`
12801        // (cc8f749) — the third of three OTP-shape closed-enum
12802        // discriminator axes on the caixa typed surface now
12803        // converged onto the same three-path
12804        // (Display → as_str → lifted const) discipline.
12805        for variant in [
12806            RestartPolicy::Permanent,
12807            RestartPolicy::Temporary,
12808            RestartPolicy::Transient,
12809        ] {
12810            assert_eq!(
12811                variant.to_string(),
12812                variant.as_str(),
12813                "RestartPolicy::{variant:?} Display must route through \
12814                 RestartPolicy::as_str (single source of truth: the lifted \
12815                 SUPERVISOR_CHILD_RESTART_* const the wire format also emits)"
12816            );
12817        }
12818    }
12819
12820    #[test]
12821    fn restart_policy_display_matches_serialized_wire_byte_string() {
12822        // The fail-before-pass-after pin on the second half of the
12823        // three-path convergence: `Display` (user-facing text) agrees
12824        // byte-for-byte with the `Serialize` derive's wire format
12825        // (canonical camelCase-schema `SUPERVISOR_CHILD_KEY_RESTART`
12826        // scalar) on every variant. Pre-convergence the two paths
12827        // were structurally independent — a future
12828        // `#[serde(rename_all = "kebab-case")]` attribute on the
12829        // enum would silently rebrand the emitted wire scalar
12830        // (`permanent`, `temporary`, `transient`) while every
12831        // consumer that pretty-prints the policy (the future
12832        // wasm-operator's per-child post-exit restart-decision
12833        // diagnostic line, the future `feira app graph` per-child
12834        // restart column, the future M4
12835        // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
12836        // per-child admission-webhook rejection body) would still
12837        // emit the PascalCase form the `as_str` / `Display` route
12838        // returns, with the mismatch surfacing at consumer parse
12839        // time / operator dispatch time far from the source rebrand
12840        // commit. Pin the two paths byte-for-byte here so any future
12841        // serde-attribute or variant-rename drift is a
12842        // caixa-core-build-time test failure at this call, not a
12843        // silent per-consumer dispatch miss. Peer of the sibling
12844        // [`restart_strategy_display_matches_serialized_wire_byte_string`]
12845        // on the per-supervisor sibling-restart-strategy axis and
12846        // the M3
12847        // `placement_strategy_display_matches_serialized_wire_byte_string`
12848        // (cc8f749).
12849        for variant in [
12850            RestartPolicy::Permanent,
12851            RestartPolicy::Temporary,
12852            RestartPolicy::Transient,
12853        ] {
12854            let wire = serde_json::to_string(&variant).unwrap();
12855            let unquoted = wire
12856                .strip_prefix('"')
12857                .and_then(|s| s.strip_suffix('"'))
12858                .expect("serialized RestartPolicy is a JSON string");
12859            assert_eq!(
12860                variant.to_string(),
12861                unquoted,
12862                "RestartPolicy::{variant:?} Display byte-string must match the \
12863                 Serialize derive's wire byte-string (three-path convergence: \
12864                 Display + as_str + Serialize all resolve to the same \
12865                 SUPERVISOR_CHILD_RESTART_* const)"
12866            );
12867        }
12868    }
12869
12870    #[test]
12871    fn restart_policy_as_ref_str_routes_through_as_str_accessor() {
12872        // Fail-before-pass-after byte-parity pin on the lifted
12873        // `impl AsRef<str> for RestartPolicy` — asserts the
12874        // standard-library trait impl and the substrate-primitive
12875        // [`RestartPolicy::as_str`] `pub const fn` accessor resolve
12876        // to the same `&str` per instance across the three-arm
12877        // closed set, so any future silent detour that routes the
12878        // impl through a divergent projection (a per-arm inline
12879        // `match self { RestartPolicy::Permanent => "Permanent", … }`
12880        // re-inlining that opens a compile-time link to the un-lifted
12881        // arm-literal, a swap onto the kebab-case
12882        // [`gen_platform::Discriminant`] catalog identity that would
12883        // collide the wire axis with the dispatcher-catalog axis) trips
12884        // at caixa-core test time under `PartialEq` rather than at a
12885        // downstream `impl AsRef<str>`-bound consumer's silent split.
12886        // Sweeps every one of the three arms
12887        // [`RestartPolicy::ALL`] carries so no arm's projection is
12888        // covered only by the sibling wire-format `Serialize` derive
12889        // path. Peer of the sibling
12890        // [`restart_strategy_as_ref_str_routes_through_as_str_accessor`]
12891        // (63eb1a4) on the paired per-supervisor sibling-restart-
12892        // strategy axis and the [`crate::CaixaVersion`]
12893        // `AsRef<str>`-byte-parity pin (16d5c7e) on the paired
12894        // top-level `:versao` typed newtype — the three pins together
12895        // cover the substrate primitive's `AsRef<str>` projection axis
12896        // on the paired newtype + M2 closed-set-typed-enum surface.
12897        for &variant in RestartPolicy::ALL {
12898            assert_eq!(
12899                <RestartPolicy as AsRef<str>>::as_ref(&variant),
12900                variant.as_str(),
12901                "AsRef<str> impl on RestartPolicy::{variant:?} must \
12902                 byte-equal RestartPolicy::as_str on the same instance \
12903                 — divergence signals a silent detour off the substrate-\
12904                 primitive accessor"
12905            );
12906        }
12907    }
12908
12909    #[test]
12910    fn restart_policy_as_ref_str_routes_through_display_via_shared_accessor() {
12911        // Fail-before-pass-after byte-parity pin on the three-path
12912        // convergence discipline the M2 per-child-restart-policy
12913        // primitive now carries on the `&str`-projection axis:
12914        // `<RestartPolicy as AsRef<str>>::as_ref(&v)` (the newly
12915        // lifted impl), `format!("{v}")` (the pre-existing
12916        // [`fmt::Display`] impl), and `v.as_str()` (the substrate-
12917        // primitive `pub const fn` accessor both trait impls delegate
12918        // through) must resolve to the same byte-string on every
12919        // instance across the three-arm closed set. Refuses any future
12920        // divergence between the two trait impls (a stray
12921        // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
12922        // rather than delegating through the shared accessor; a
12923        // hypothetical `AsRef<str>` rewrite that inlines a per-arm
12924        // literal cascade) that would silently split the two
12925        // projection paths of the same closed-set typed enum. Mirrors
12926        // the sibling three-path-convergence discipline the peer
12927        // [`RestartStrategy`] typed enum carries on its
12928        // `AsRef<str>` / `Display` / `as_str` triple
12929        // (supervisor.rs pin
12930        // `restart_strategy_as_ref_str_routes_through_display_via_shared_accessor`,
12931        // 63eb1a4) and the [`crate::CaixaVersion`] typed newtype
12932        // carries on the same triple (version.rs pin
12933        // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
12934        // 16d5c7e).
12935        for &variant in RestartPolicy::ALL {
12936            let via_as_ref: &str = <RestartPolicy as AsRef<str>>::as_ref(&variant);
12937            let via_display: String = format!("{variant}");
12938            let via_accessor: &str = variant.as_str();
12939            assert_eq!(via_as_ref, via_accessor);
12940            assert_eq!(via_display, via_accessor);
12941            assert_eq!(via_as_ref, via_display.as_str());
12942        }
12943    }
12944
12945    // The `generic_bytes_sink(&variant)` and `borrowed_hasher.update(&variant)`
12946    // shapes below are the borrowed-input witness half of the by-value +
12947    // by-reference partition the paired witness pair carries: the pair proves
12948    // the trait bound accepts both owned (`variant`) and borrowed (`&variant`)
12949    // shapes through the same substrate-primitive `as_str` accessor, which is
12950    // the shape the caixa-lacre BLAKE3 content-address closure composes.
12951    // `clippy::needless_borrows_for_generic_args` would fold the borrowed half
12952    // into the owned half and collapse the by-value/by-reference partition
12953    // this test load-bears; the `#[allow]` documents that the partition is
12954    // deliberate, not an oversight.
12955    #[allow(clippy::needless_borrows_for_generic_args)]
12956    #[test]
12957    fn restart_policy_as_ref_bytes_routes_through_as_str_accessor() {
12958        // `<T: AsRef<[u8]>>`-bound generic-consumer witness: a byte-input
12959        // function that binds its argument through the standard-library
12960        // [`AsRef<[u8]>`] trait bound accepts a [`super::RestartPolicy`]
12961        // directly, without the caller open-coding the two-hop
12962        // `restart.as_str().as_bytes()` composition. Lifted to the top
12963        // of the function per `clippy::items_after_statements`.
12964        fn generic_bytes_sink<T: AsRef<[u8]>>(t: T) -> Vec<u8> {
12965            t.as_ref().to_vec()
12966        }
12967        // `blake3::Hasher::update`-shape byte-input surface mock: mirrors
12968        // `blake3::Hasher::update` / `ring::digest::Context::update` /
12969        // `sha2::Sha256::update`'s `impl AsRef<[u8]>`-bound `update`
12970        // signature so a per-child BLAKE3 content-address closure that
12971        // composes `hasher.update(restart)` on the [`crate::Lacre`]
12972        // closure builder reaches the substrate-primitive `as_str`
12973        // accessor through the [`super::RestartPolicy`] `AsRef<[u8]>`
12974        // axis and no other. Lifted to the top of the function per
12975        // `clippy::items_after_statements`.
12976        struct MockHasher(Vec<u8>);
12977        impl MockHasher {
12978            fn new() -> Self {
12979                Self(Vec::new())
12980            }
12981            fn update(&mut self, bytes: impl AsRef<[u8]>) -> &mut Self {
12982                self.0.extend_from_slice(bytes.as_ref());
12983                self
12984            }
12985            fn finalize(self) -> Vec<u8> {
12986                self.0
12987            }
12988        }
12989
12990        // Fail-before-pass-after byte-parity pin on the newly lifted
12991        // `impl AsRef<[u8]> for RestartPolicy` — asserts the trait-
12992        // idiomatic byte-view standard-library impl and the substrate-
12993        // primitive [`super::RestartPolicy::as_str`] `pub const fn`
12994        // accessor's `.as_bytes()` byte-tail resolve to the same three-
12995        // arm `PascalCase` wire byte-string emit-set across every arm
12996        // the exhaustive [`super::RestartPolicy::ALL`] slice enumerates.
12997        // Extends the trait-idiomatic byte-view axis onto the second
12998        // (and final) M2 OTP-shape closed-set fieldless typed enum peer
12999        // on the caixa surface (the paired per-child restart-decision
13000        // policy sibling on the same M2 `:supervisor` slot), closing
13001        // the byte-view axis across the `:supervisor :estrategia` +
13002        // `:children :restart` M2 slot pair the sibling
13003        // [`super::RestartStrategy`] first-mover (cd4c4e0) opened.
13004        //
13005        // Rust's standard library carries `impl AsRef<[u8]> for str` and
13006        // `impl AsRef<[u8]> for String`, so a two-hop composition
13007        // `restart.as_str().as_bytes()` (or the equally two-hop
13008        // `AsRef::<str>::as_ref(&restart).as_bytes()`) is reachable
13009        // through the pre-existing str-view axis alone. But that two-hop
13010        // shape has no compile-time link back to the byte-projection
13011        // axis, forces every downstream `<T: AsRef<[u8]>>`-bound
13012        // consumer to open-code the two-hop composition at every call
13013        // site, and admits a silent split whenever a future call site
13014        // takes a sibling reverse-projection axis whose `.as_bytes()`
13015        // byte-tail carries no compile-time byte-view surface. This
13016        // impl closes the byte-view axis at the substrate-primitive
13017        // [`super::RestartPolicy::as_str`] accessor so every future
13018        // `<T: AsRef<[u8]>>`-bound consumer reaches the same lifted
13019        // [`super::crate::render::SUPERVISOR_CHILD_RESTART_*`] const
13020        // roster the paired str-view axes already return through —
13021        // through one trait dispatch.
13022        for &variant in RestartPolicy::ALL {
13023            let via_trait: &[u8] = <RestartPolicy as AsRef<[u8]>>::as_ref(&variant);
13024            let via_method_bytes: &[u8] = variant.as_str().as_bytes();
13025            assert_eq!(
13026                via_trait, via_method_bytes,
13027                "AsRef<[u8]> for RestartPolicy impl must byte-equal \
13028                 RestartPolicy::as_str().as_bytes() on \
13029                 RestartPolicy::{variant:?} — divergence signals a \
13030                 silent detour off the substrate-primitive accessor"
13031            );
13032            // Cross-axis witness against the paired str-view axes'
13033            // `.as_bytes()` byte-tails: [`AsRef<str>`] /
13034            // [`std::fmt::Display`] / [`super::RestartPolicy::as_str`]
13035            // all resolve to the same lifted
13036            // [`super::crate::render::SUPERVISOR_CHILD_RESTART_*`] const
13037            // roster, and the byte-view axis must byte-equal each of
13038            // their `.as_bytes()` byte-tails by construction — locking
13039            // the str-view and byte-view axes together at the
13040            // substrate-primitive accessor.
13041            let str_view_ref: &str = <RestartPolicy as AsRef<str>>::as_ref(&variant);
13042            assert_eq!(
13043                via_trait,
13044                str_view_ref.as_bytes(),
13045                "AsRef<[u8]> for RestartPolicy and AsRef<str> for \
13046                 RestartPolicy must resolve to byte-equal byte-tails \
13047                 on RestartPolicy::{variant:?} — divergence signals \
13048                 the byte-view and str-view axes have drifted off the \
13049                 same substrate-primitive as_str accessor"
13050            );
13051            let display_bytes = variant.to_string();
13052            assert_eq!(
13053                via_trait,
13054                display_bytes.as_bytes(),
13055                "AsRef<[u8]> for RestartPolicy and \
13056                 <RestartPolicy as std::fmt::Display>::to_string must \
13057                 resolve to byte-equal byte-tails on \
13058                 RestartPolicy::{variant:?} — divergence signals the \
13059                 byte-view axis and the Display formatter axis have \
13060                 drifted off the same substrate-primitive as_str \
13061                 accessor"
13062            );
13063            // Cross-axis witness against the paired reverse-projection
13064            // axes' `.as_bytes()` byte-tails: every one of `{&'static
13065            // str, String, Cow<'static, str>, Box<str>,
13066            // std::sync::Arc<str>}` allocates (or borrows) the same
13067            // `PascalCase` wire byte-string the substrate-primitive
13068            // accessor emits, so the byte-view axis must byte-equal
13069            // each of their `.as_bytes()` byte-tails by construction.
13070            let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
13071            assert_eq!(
13072                via_trait,
13073                owned_static.as_bytes(),
13074                "AsRef<[u8]> for RestartPolicy and From<RestartPolicy> \
13075                 for &'static str must resolve to byte-equal byte-tails \
13076                 on RestartPolicy::{variant:?}"
13077            );
13078            let owned_string: String = <String as From<RestartPolicy>>::from(variant);
13079            assert_eq!(
13080                via_trait,
13081                owned_string.as_bytes(),
13082                "AsRef<[u8]> for RestartPolicy and From<RestartPolicy> \
13083                 for String must resolve to byte-equal byte-tails on \
13084                 RestartPolicy::{variant:?}"
13085            );
13086            let owned_cow: std::borrow::Cow<'static, str> =
13087                <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
13088            assert_eq!(
13089                via_trait,
13090                owned_cow.as_bytes(),
13091                "AsRef<[u8]> for RestartPolicy and From<RestartPolicy> \
13092                 for Cow<'static, str> must resolve to byte-equal byte-\
13093                 tails on RestartPolicy::{variant:?}"
13094            );
13095            let owned_box: Box<str> = <Box<str> as From<RestartPolicy>>::from(variant);
13096            assert_eq!(
13097                via_trait,
13098                owned_box.as_bytes(),
13099                "AsRef<[u8]> for RestartPolicy and From<RestartPolicy> \
13100                 for Box<str> must resolve to byte-equal byte-tails on \
13101                 RestartPolicy::{variant:?}"
13102            );
13103            let owned_arc: std::sync::Arc<str> =
13104                <std::sync::Arc<str> as From<RestartPolicy>>::from(variant);
13105            assert_eq!(
13106                via_trait,
13107                owned_arc.as_bytes(),
13108                "AsRef<[u8]> for RestartPolicy and From<RestartPolicy> \
13109                 for std::sync::Arc<str> must resolve to byte-equal \
13110                 byte-tails on RestartPolicy::{variant:?}"
13111            );
13112        }
13113        // `<T: AsRef<[u8]>>`-bound-consumer witness: the generic byte-
13114        // input function `generic_bytes_sink` (lifted above per
13115        // `clippy::items_after_statements`) accepts a
13116        // [`super::RestartPolicy`] directly through the trait bound,
13117        // without the caller open-coding the two-hop
13118        // `restart.as_str().as_bytes()` composition. This is the shape
13119        // that reaches the caixa-lacre BLAKE3 content-address closure's
13120        // `blake3::Hasher::update(impl AsRef<[u8]>)` byte-input surface
13121        // through this impl and no other.
13122        for &variant in RestartPolicy::ALL {
13123            let via_generic = generic_bytes_sink(variant);
13124            let via_borrowed_generic = generic_bytes_sink(&variant);
13125            let via_method_bytes = variant.as_str().as_bytes().to_vec();
13126            assert_eq!(
13127                via_generic, via_method_bytes,
13128                "generic `<T: AsRef<[u8]>>`-bound consumer on \
13129                 RestartPolicy::{variant:?} must yield the same byte-\
13130                 tail RestartPolicy::as_str().as_bytes() returns — \
13131                 divergence signals the byte-view axis fails to bridge \
13132                 a generic byte-input trait bound to the substrate-\
13133                 primitive accessor"
13134            );
13135            assert_eq!(
13136                via_borrowed_generic, via_method_bytes,
13137                "generic `<T: AsRef<[u8]>>`-bound consumer on \
13138                 &RestartPolicy::{variant:?} must yield the same byte-\
13139                 tail RestartPolicy::as_str().as_bytes() returns — the \
13140                 borrowed-input surface must resolve to the same as_str \
13141                 dispatch"
13142            );
13143        }
13144        // `blake3::Hasher::update`-shape byte-input surface witness on
13145        // the caixa-lacre compounding target: the `MockHasher` (lifted
13146        // above per `clippy::items_after_statements`) mirrors
13147        // `blake3::Hasher::update` / `ring::digest::Context::update` /
13148        // `sha2::Sha256::update`'s `impl AsRef<[u8]>`-bound update
13149        // signature and accepts a [`super::RestartPolicy`] directly,
13150        // routing its byte-tail through the substrate-primitive
13151        // `as_str` accessor — the shape a future per-child BLAKE3
13152        // content-address closure composes to fold a `:restart`
13153        // discriminator byte-tag into the [`crate::Lacre`] closure
13154        // body.
13155        for &variant in RestartPolicy::ALL {
13156            let mut owned_hasher = MockHasher::new();
13157            owned_hasher.update(variant);
13158            let owned_folded = owned_hasher.finalize();
13159            assert_eq!(
13160                owned_folded,
13161                variant.as_str().as_bytes(),
13162                "`hasher.update(restart)`-shape composition on \
13163                 RestartPolicy::{variant:?} must fold the same byte-\
13164                 tail RestartPolicy::as_str().as_bytes() returns — the \
13165                 shape a future per-child BLAKE3 content-address \
13166                 closure composes to fold a `:restart` discriminator \
13167                 byte-tag into the Lacre closure body"
13168            );
13169            let mut borrowed_hasher = MockHasher::new();
13170            borrowed_hasher.update(&variant);
13171            let borrowed_folded = borrowed_hasher.finalize();
13172            assert_eq!(
13173                borrowed_folded,
13174                variant.as_str().as_bytes(),
13175                "`hasher.update(&restart)`-shape composition on \
13176                 &RestartPolicy::{variant:?} must fold the same byte-\
13177                 tail RestartPolicy::as_str().as_bytes() returns — the \
13178                 borrowed-input surface must resolve to the same as_str \
13179                 dispatch"
13180            );
13181        }
13182    }
13183
13184    #[test]
13185    #[expect(
13186        clippy::too_many_lines,
13187        reason = "the byte-owned reverse-projection axis is closed \
13188                  here across the M2-OTP-shape :supervisor slot pair by \
13189                  extending onto the second and final M2-OTP-shape \
13190                  closed-set fieldless typed-enum peer, so the pin \
13191                  binds the new impl against every paired byte-view \
13192                  and str-owned axis on the same enum plus a generic \
13193                  <T: Into<Vec<u8>>>-bound consumer witness and a \
13194                  std::io::Write::write_all-shape owned-byte-sink \
13195                  surface witness on both owned and borrowed input \
13196                  shapes to lock the whole family against a future \
13197                  silent regression"
13198    )]
13199    fn restart_policy_from_into_owned_vec_bytes_routes_through_as_str_accessor() {
13200        // `<T: Into<Vec<u8>>>`-bound-consumer witness helper: a generic
13201        // owned-byte-input function accepts a [`super::RestartPolicy`]
13202        // directly through the trait bound, without the caller open-
13203        // coding the three-hop `restart.as_str().as_bytes().to_vec()`
13204        // composition. Lifted to the top of the function per
13205        // `clippy::items_after_statements`.
13206        fn generic_owned_bytes_sink<T: Into<Vec<u8>>>(t: T) -> Vec<u8> {
13207            t.into()
13208        }
13209        // `std::io::Write::write_all`-shape owned-byte-sink surface
13210        // mock: mirrors `std::io::Write::write_all` /
13211        // `bytes::BytesMut::extend_from_slice` / any per-arm audit-log
13212        // byte-sink that consumes a `Vec<u8>` payload via
13213        // `Into<Vec<u8>>`, so a future per-child per-`:restart` audit-
13214        // log emit reaches the substrate-primitive `as_str` accessor
13215        // through the byte-owned reverse-projection axis and no
13216        // other. Lifted to the top of the function per
13217        // `clippy::items_after_statements`.
13218        struct MockOwnedByteSink(Vec<u8>);
13219        impl MockOwnedByteSink {
13220            fn new() -> Self {
13221                Self(Vec::new())
13222            }
13223            fn write_all(&mut self, bytes: impl Into<Vec<u8>>) -> &mut Self {
13224                self.0.extend(bytes.into());
13225                self
13226            }
13227            fn finalize(self) -> Vec<u8> {
13228                self.0
13229            }
13230        }
13231
13232        // Fail-before-pass-after byte-parity pin on the newly lifted
13233        // `impl From<RestartPolicy> for Vec<u8>` and
13234        // `impl From<&RestartPolicy> for Vec<u8>` — asserts the trait-
13235        // idiomatic byte-owned reverse-projection standard-library
13236        // impls and the substrate-primitive
13237        // [`super::RestartPolicy::as_str`] `pub const fn` accessor's
13238        // `.as_bytes().to_vec()` byte-tail resolve to the same three-
13239        // arm PascalCase wire byte-string emit-set across every arm
13240        // the exhaustive [`super::RestartPolicy::ALL`] slice
13241        // enumerates. Closes the substrate-wide trait-idiomatic byte-
13242        // owned reverse-projection axis on the M2-OTP-shape closed-
13243        // set typed-enum pair the sibling first-mover
13244        // [`super::RestartStrategy`] `From<{Self, &Self}> for Vec<u8>`
13245        // lift (63e5dd0) opened one commit prior, matching the
13246        // trajectory the paired [`AsRef<[u8]>`] borrowed byte-view
13247        // axis campaign already tracked across the same slot pair
13248        // (cd4c4e0 → 98b08fa).
13249        for &variant in RestartPolicy::ALL {
13250            let via_owned_from: Vec<u8> = <Vec<u8> as From<RestartPolicy>>::from(variant);
13251            let via_borrowed_from: Vec<u8> = <Vec<u8> as From<&RestartPolicy>>::from(&variant);
13252            let via_method_bytes: Vec<u8> = variant.as_str().as_bytes().to_vec();
13253            assert_eq!(
13254                via_owned_from, via_method_bytes,
13255                "From<RestartPolicy> for Vec<u8> impl must byte-equal \
13256                 RestartPolicy::as_str().as_bytes().to_vec() on \
13257                 RestartPolicy::{variant:?} — divergence signals a \
13258                 silent detour off the substrate-primitive accessor"
13259            );
13260            assert_eq!(
13261                via_borrowed_from, via_method_bytes,
13262                "From<&RestartPolicy> for Vec<u8> impl must byte-\
13263                 equal RestartPolicy::as_str().as_bytes().to_vec() \
13264                 on RestartPolicy::{variant:?} — divergence signals \
13265                 a silent detour off the substrate-primitive accessor"
13266            );
13267            assert_eq!(
13268                via_owned_from, via_borrowed_from,
13269                "From<RestartPolicy> for Vec<u8> and \
13270                 From<&RestartPolicy> for Vec<u8> must byte-equal \
13271                 each other on RestartPolicy::{variant:?} — \
13272                 divergence signals the owned-input and borrowed-input \
13273                 paths have drifted off the same substrate-primitive \
13274                 as_str accessor"
13275            );
13276            // Cross-axis witness against the paired [`AsRef<[u8]>`]
13277            // borrowed byte-view axis (98b08fa): the byte-owned
13278            // reverse-projection axis must byte-equal the paired
13279            // borrowed byte-view axis by construction — locking the
13280            // byte-view and byte-owned axes together at the substrate-
13281            // primitive accessor.
13282            let borrowed_bytes: &[u8] = <RestartPolicy as AsRef<[u8]>>::as_ref(&variant);
13283            assert_eq!(
13284                via_owned_from,
13285                borrowed_bytes.to_vec(),
13286                "From<RestartPolicy> for Vec<u8> and AsRef<[u8]> for \
13287                 RestartPolicy must resolve to byte-equal byte-tails \
13288                 on RestartPolicy::{variant:?} — divergence signals \
13289                 the byte-owned and byte-view axes have drifted off \
13290                 the same substrate-primitive as_str accessor"
13291            );
13292            // Cross-axis witness against the str-owned reverse-
13293            // projection family's `.into_bytes()` / `.as_bytes().to_vec()`
13294            // byte-tails: every one of `{String, Cow<'static, str>,
13295            // Box<str>, std::sync::Arc<str>}` allocates (or borrows)
13296            // the same PascalCase wire byte-string the substrate-
13297            // primitive accessor emits, so the byte-owned axis must
13298            // byte-equal each of their owned byte-tails by
13299            // construction.
13300            let owned_string: String = <String as From<RestartPolicy>>::from(variant);
13301            assert_eq!(
13302                via_owned_from,
13303                owned_string.into_bytes(),
13304                "From<RestartPolicy> for Vec<u8> and \
13305                 String::from(policy).into_bytes() must resolve to \
13306                 byte-equal byte-tails on RestartPolicy::{variant:?}"
13307            );
13308            let owned_cow: std::borrow::Cow<'static, str> =
13309                <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
13310            assert_eq!(
13311                via_owned_from,
13312                owned_cow.as_bytes().to_vec(),
13313                "From<RestartPolicy> for Vec<u8> and \
13314                 From<RestartPolicy> for Cow<'static, str> must \
13315                 resolve to byte-equal byte-tails on \
13316                 RestartPolicy::{variant:?}"
13317            );
13318            let owned_box: Box<str> = <Box<str> as From<RestartPolicy>>::from(variant);
13319            assert_eq!(
13320                via_owned_from,
13321                owned_box.as_bytes().to_vec(),
13322                "From<RestartPolicy> for Vec<u8> and \
13323                 From<RestartPolicy> for Box<str> must resolve to \
13324                 byte-equal byte-tails on RestartPolicy::{variant:?}"
13325            );
13326            let owned_arc: std::sync::Arc<str> =
13327                <std::sync::Arc<str> as From<RestartPolicy>>::from(variant);
13328            assert_eq!(
13329                via_owned_from,
13330                owned_arc.as_bytes().to_vec(),
13331                "From<RestartPolicy> for Vec<u8> and \
13332                 From<RestartPolicy> for std::sync::Arc<str> must \
13333                 resolve to byte-equal byte-tails on \
13334                 RestartPolicy::{variant:?}"
13335            );
13336        }
13337        // `<T: Into<Vec<u8>>>`-bound-consumer witness on both owned
13338        // and borrowed input shapes: the generic owned-byte-input
13339        // function `generic_owned_bytes_sink` (lifted above per
13340        // `clippy::items_after_statements`) accepts a
13341        // [`super::RestartPolicy`] and a `&RestartPolicy` directly
13342        // through the trait bound, without the caller open-coding
13343        // the three-hop `restart.as_str().as_bytes().to_vec()`
13344        // composition.
13345        for &variant in RestartPolicy::ALL {
13346            let via_generic_owned = generic_owned_bytes_sink(variant);
13347            // Bind the borrowed-input path through an explicit
13348            // `&RestartPolicy` local so the generic-consumer witness
13349            // routes through `From<&RestartPolicy> for Vec<u8>` (T
13350            // binds to `&RestartPolicy`) rather than clippy-collapsing
13351            // the borrow onto the owned-input peer.
13352            let variant_ref: &RestartPolicy = &variant;
13353            let via_generic_borrowed = generic_owned_bytes_sink(variant_ref);
13354            let via_method_bytes = variant.as_str().as_bytes().to_vec();
13355            assert_eq!(
13356                via_generic_owned, via_method_bytes,
13357                "generic `<T: Into<Vec<u8>>>`-bound consumer on \
13358                 RestartPolicy::{variant:?} must yield the same byte-\
13359                 tail RestartPolicy::as_str().as_bytes() returns — \
13360                 divergence signals the byte-owned axis fails to bridge \
13361                 a generic owned-byte-input trait bound to the \
13362                 substrate-primitive accessor"
13363            );
13364            assert_eq!(
13365                via_generic_borrowed, via_method_bytes,
13366                "generic `<T: Into<Vec<u8>>>`-bound consumer on \
13367                 &RestartPolicy::{variant:?} must yield the same byte-\
13368                 tail RestartPolicy::as_str().as_bytes() returns — \
13369                 the borrowed-input surface must resolve to the same \
13370                 as_str dispatch"
13371            );
13372        }
13373        // `std::io::Write::write_all`-shape owned-byte-sink surface
13374        // witness: the `MockOwnedByteSink` (lifted above per
13375        // `clippy::items_after_statements`) mirrors
13376        // `std::io::Write::write_all` /
13377        // `bytes::BytesMut::extend_from_slice`'s `impl Into<Vec<u8>>`-
13378        // bound owned-byte input signature and accepts a
13379        // [`super::RestartPolicy`] directly on both owned and
13380        // borrowed input shapes, routing its byte-tail through the
13381        // substrate-primitive `as_str` accessor — the shape a future
13382        // per-child per-`:restart` audit-log emit composes to fold a
13383        // `:restart` discriminator byte-tag into a downstream owned-
13384        // byte-sink surface.
13385        for &variant in RestartPolicy::ALL {
13386            let mut owned_sink = MockOwnedByteSink::new();
13387            owned_sink.write_all(variant);
13388            let owned_folded = owned_sink.finalize();
13389            assert_eq!(
13390                owned_folded,
13391                variant.as_str().as_bytes(),
13392                "`sink.write_all(restart)`-shape composition on \
13393                 RestartPolicy::{variant:?} must fold the same byte-\
13394                 tail RestartPolicy::as_str().as_bytes() returns"
13395            );
13396            let mut borrowed_sink = MockOwnedByteSink::new();
13397            let variant_ref: &RestartPolicy = &variant;
13398            borrowed_sink.write_all(variant_ref);
13399            let borrowed_folded = borrowed_sink.finalize();
13400            assert_eq!(
13401                borrowed_folded,
13402                variant.as_str().as_bytes(),
13403                "`sink.write_all(&restart)`-shape composition on \
13404                 &RestartPolicy::{variant:?} must fold the same byte-\
13405                 tail RestartPolicy::as_str().as_bytes() returns — \
13406                 the borrowed-input surface must resolve to the same \
13407                 as_str dispatch"
13408            );
13409        }
13410    }
13411
13412    #[test]
13413    fn restart_policy_all_enumerates_every_variant_exactly_once() {
13414        // Fail-before-pass-after pin on the [`RestartPolicy::ALL`]
13415        // exhaustive-iteration surface: every variant appears exactly
13416        // once, and the slice length matches the arm count of the
13417        // closed set. Every consumer that walks the accepted-policy
13418        // set (a future `feira supervisor --restart …` CLI-side
13419        // arg-parse's "did you mean" hint, a future M4 admission-
13420        // webhook's per-child rejection body naming the accepted-
13421        // `:restart` list, the [`RestartPolicy::from_wire`] reverse-
13422        // projection consumers that iterate the accept-set for
13423        // diagnostic rendering) reads through this slice, so a future
13424        // arm addition that grows the enum but forgets to grow
13425        // [`Self::ALL`] silently truncates every downstream consumer's
13426        // accept-set at the same pre-addition boundary — this pin
13427        // fails at caixa-core build time on the pairwise-distinct +
13428        // arm-count invariants.
13429        //
13430        // Peer of the sibling [`RestartStrategy::ALL`] (4eec29c) /
13431        // [`crate::CaixaKind::ALL`] (6b1f4fb) /
13432        // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
13433        // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
13434        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
13435        // pins on the peer closed-set typed-enum axes.
13436        let all: &[RestartPolicy] = RestartPolicy::ALL;
13437        assert_eq!(
13438            all.len(),
13439            3,
13440            "RestartPolicy::ALL must enumerate every variant of the \
13441             three-arm closed set (Permanent, Temporary, Transient); \
13442             got {all:?}"
13443        );
13444        for (i, a) in all.iter().enumerate() {
13445            for (j, b) in all.iter().enumerate() {
13446                if i != j {
13447                    assert_ne!(
13448                        a, b,
13449                        "RestartPolicy::ALL must carry every variant exactly \
13450                         once — got duplicate {a:?} at indices {i} and {j}"
13451                    );
13452                }
13453            }
13454        }
13455        for variant in [
13456            RestartPolicy::Permanent,
13457            RestartPolicy::Temporary,
13458            RestartPolicy::Transient,
13459        ] {
13460            assert!(
13461                all.contains(&variant),
13462                "RestartPolicy::ALL must contain {variant:?} — a future arm \
13463                 addition that grows the enum but forgets to grow the ALL slice \
13464                 silently truncates every downstream consumer's accept-set at \
13465                 the pre-addition boundary"
13466            );
13467        }
13468    }
13469
13470    #[test]
13471    fn restart_policy_wire_names_covers_every_arm() {
13472        // Load-bearing pin on the substrate-canonical
13473        // [`RestartPolicy::WIRE_NAMES`] exhaustive accept-set roster on
13474        // the `PascalCase` wire byte-string axis: every variant of the
13475        // sibling [`RestartPolicy::ALL`] exhaustive-iteration surface
13476        // must project through [`RestartPolicy::as_str`] onto an entry
13477        // the [`RestartPolicy::WIRE_NAMES`] roster carries, and the
13478        // roster's length must byte-equal `RestartPolicy::ALL.len()` so
13479        // a silent skew between the [`RestartPolicy::as_str`] match's
13480        // arm-set and the roster's arm-set trips here at caixa-core
13481        // test time rather than at a downstream M4
13482        // `mesh.pleme.io/v1alpha1/Supervisor` CR admission-webhook
13483        // rejection body's wire-form `:restart` accepted-set
13484        // enumeration miss / a `feira supervisor --restart …` "did you
13485        // mean" hint drift / a future wasm-operator per-reconcile-step
13486        // diagnostic log line's accepted-wire-form enumeration miss.
13487        // A future arm addition (an OTP-`intrinsic` fourth arm the
13488        // theory
13489        // [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
13490        // might reach for once the three canonical OTP restart policies
13491        // stop covering the substrate's discovered load-shape) extends
13492        // [`RestartPolicy::ALL`] as a single edit and this pin sweeps
13493        // the new arm by iteration; the paired
13494        // [`RestartPolicy::WIRE_NAMES`] roster must grow in lockstep or
13495        // this assertion trips. Every entry is further pinned to open
13496        // with an ASCII uppercase byte so a silent collapse of the
13497        // wire-form axis with the peer kebab-case dispatcher-catalog
13498        // axis (an entry byte-identical to a sibling
13499        // [`RestartPolicy::discriminant`] kebab byte-string that would
13500        // let a wire-axis consumer accept the dispatcher-catalog
13501        // vocabulary) trips here rather than at a downstream K8s-CR
13502        // round-trip miss.
13503        //
13504        // Peer of the sibling
13505        // [`restart_strategy_wire_names_covers_every_arm`] (3033f45)
13506        // pin on the first M2 OTP-shape sibling-restart closed-set
13507        // typed enum, the sibling
13508        // [`crate::aplicacao::tests::placement_strategy_wire_names_covers_every_arm`]
13509        // (3e5b194) pin on the first M3 mesh-shape distribution-strategy
13510        // closed-set typed enum, the sibling
13511        // [`crate::kind::tests::caixa_kind_wire_names_covers_every_arm`]
13512        // (bd708bd) pin on the top-level typed-kind discriminator's
13513        // `PascalCase` wire byte-string axis, and the sibling
13514        // [`crate::upgrade::tests::upgrade_instruction_wire_forms_covers_every_arm`]
13515        // (cc42c0e) /
13516        // [`crate::upgrade::tests::upgrade_instruction_lisp_forms_covers_every_arm`]
13517        // (1898d77) pins on the OTP-appup discriminator's two-axis
13518        // roster split — the same closed-set exhaustive-roster coverage
13519        // discipline extended here onto the second and final M2
13520        // OTP-shape sibling-enum on the caixa surface, closing the
13521        // per-child restart-decision-policy axis paired with the peer
13522        // per-supervisor sibling-restart-strategy axis on the same M2
13523        // `:supervisor` slot.
13524        //
13525        // Fail-before-pass-after locally verified by mutating one arm
13526        // of the paired [`crate::render::SUPERVISOR_CHILD_RESTART_*`]
13527        // const family (e.g. dropping the trailing `t` from
13528        // `"Permanent"` → `"Permanen"`) — the length pin still passes
13529        // but the `contains` check fires on the mutated arm; and by
13530        // shortening the roster to two entries — the length pin fires
13531        // first.
13532        assert_eq!(
13533            RestartPolicy::WIRE_NAMES.len(),
13534            RestartPolicy::ALL.len(),
13535            "RestartPolicy::WIRE_NAMES.len() must byte-equal \
13536             RestartPolicy::ALL.len() — a mismatch means the roster \
13537             and the enum's arm-set have drifted; downstream consumers \
13538             that fan through both will silently disagree on the \
13539             accepted arm-set"
13540        );
13541        for &variant in RestartPolicy::ALL {
13542            let wire = variant.as_str();
13543            assert!(
13544                RestartPolicy::WIRE_NAMES.contains(&wire),
13545                "RestartPolicy::{variant:?}.as_str() = {wire:?} must \
13546                 be a member of RestartPolicy::WIRE_NAMES — the \
13547                 emitter and the roster have drifted out of lockstep"
13548            );
13549        }
13550        for tag in RestartPolicy::WIRE_NAMES {
13551            let first = tag.chars().next().unwrap_or_else(|| {
13552                panic!(
13553                    "RestartPolicy::WIRE_NAMES entry {tag:?} must be \
13554                     a non-empty PascalCase byte-string"
13555                )
13556            });
13557            assert!(
13558                first.is_ascii_uppercase(),
13559                "RestartPolicy::WIRE_NAMES entry {tag:?} must open \
13560                 with an ASCII uppercase byte (PascalCase wire form) — \
13561                 a lowercase entry would collide the wire-form axis \
13562                 with the peer kebab-case dispatcher-catalog axis \
13563                 [`RestartPolicy::discriminant`] serves"
13564            );
13565        }
13566    }
13567
13568    #[test]
13569    fn restart_policy_from_wire_accepts_every_lifted_constant() {
13570        // Fail-before-pass-after pin on the forward accept-set of the
13571        // [`RestartPolicy::from_wire`] reverse projection: every
13572        // canonical [`crate::render::SUPERVISOR_CHILD_RESTART_*`]
13573        // constant the [`RestartPolicy::as_str`] emitter walks parses
13574        // back to its paired variant. Any future arm addition that
13575        // grows the emitter's `as_str` match but forgets to grow the
13576        // parser's `from_wire` match silently splits the two halves of
13577        // the round-trip — the wire byte-string one non-serde consumer
13578        // parses from the one the emitter wrote — with the failure
13579        // surfacing at the operator's reconcile posture (a `:temporary`
13580        // `oneShot` child restarted on clean exit, a `:transient` child
13581        // restarted after clean completion) far from the rebrand
13582        // commit. Pinning the three-arm accept-set here catches the
13583        // drift at caixa-core build time.
13584        //
13585        // Peer of the sibling [`RestartStrategy::from_wire`] (4eec29c)
13586        // + [`crate::CaixaKind::from_wire`] (2aa6d23)
13587        // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
13588        // accept-set pins on the peer closed-set typed-enum `str → Self`
13589        // axes.
13590        for (wire, expected) in [
13591            (
13592                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
13593                RestartPolicy::Permanent,
13594            ),
13595            (
13596                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
13597                RestartPolicy::Temporary,
13598            ),
13599            (
13600                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
13601                RestartPolicy::Transient,
13602            ),
13603        ] {
13604            let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
13605                panic!(
13606                    "RestartPolicy::from_wire({wire:?}) must accept every \
13607                     SUPERVISOR_CHILD_RESTART_* constant — got None for the \
13608                     lifted canonical byte-string that RestartPolicy::{expected:?} \
13609                     serializes as under SUPERVISOR_CHILD_KEY_RESTART"
13610                )
13611            });
13612            assert_eq!(
13613                parsed, expected,
13614                "RestartPolicy::from_wire({wire:?}) must return \
13615                 RestartPolicy::{expected:?}; got RestartPolicy::{parsed:?}"
13616            );
13617        }
13618    }
13619
13620    #[test]
13621    fn restart_policy_from_wire_round_trips_through_as_str() {
13622        // Fail-before-pass-after pin on the closed round-trip between
13623        // the forward [`RestartPolicy::as_str`] emitter and the
13624        // reverse [`RestartPolicy::from_wire`] parser: for every
13625        // variant in [`RestartPolicy::ALL`], parsing the emitter's
13626        // output must return exactly the same variant. Any per-arm
13627        // divergence — a future arm added to `as_str` but not
13628        // `from_wire`, an accidental copy-paste flip in one but not
13629        // the other — silently splits the emit and parse halves and
13630        // the failure surfaces at consumer parse time far from the
13631        // drift site. The `ALL`-iterating shape means a future arm
13632        // addition picks up the coverage by construction.
13633        //
13634        // Peer of the sibling
13635        // [`restart_strategy_from_wire_round_trips_through_as_str`]
13636        // (4eec29c) round-trip pin on
13637        // [`RestartStrategy::from_wire`] and the M3
13638        // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
13639        // (18c7342) round-trip pin on
13640        // [`crate::aplicacao::PlacementStrategy::from_wire`].
13641        for &variant in RestartPolicy::ALL {
13642            let wire = variant.as_str();
13643            let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
13644                panic!(
13645                    "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
13646                     must be Some({variant:?}) — the two halves of the round-trip \
13647                     dispatch on the same lifted SUPERVISOR_CHILD_RESTART_* consts; \
13648                     got None on wire byte-string {wire:?}"
13649                )
13650            });
13651            assert_eq!(
13652                parsed, variant,
13653                "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
13654                 must round-trip to the same variant; got {parsed:?}"
13655            );
13656        }
13657    }
13658
13659    #[test]
13660    fn restart_policy_from_wire_rejects_unknown_byte_strings() {
13661        // Fail-before-pass-after pin on the closed-set refusal
13662        // discipline of [`RestartPolicy::from_wire`]: every
13663        // byte-string outside the three-arm accept-set returns `None`
13664        // rather than silently collapsing onto the [`Default`]
13665        // (`Permanent`) arm or an arbitrary neighbor. The refusal set
13666        // exercised here sweeps the load-bearing drift shapes: the
13667        // empty string (a stripped serde-attribute drift), all-
13668        // whitespace strings (the canonical text-editor accidental
13669        // padding shape), the kebab-case dispatcher-catalog identities
13670        // (`"permanent"` / `"temporary"` / `"transient"` — the
13671        // [`gen_platform::FromStrKind`]-derived [`std::str::FromStr`]
13672        // accept-set, which parses the *other* axis of this enum's
13673        // two-axis split and must not leak into the `from_wire`
13674        // PascalCase-wire accept-set — a lowercase leak here would
13675        // silently accept the operator's kebab-case
13676        // dispatcher-catalog probe under the wire-axis parser and mis-
13677        // route a `:permanent` intent), the padded canonical scalar
13678        // (`" Permanent "`), the trailing-newline shapes
13679        // (`"Permanent\n"`), the uppercase-single-word forms
13680        // (`"PERMANENT"`), and neighboring-but-unknown arms
13681        // (`"Restart"` — the canonical typo direction toward the
13682        // sibling [`RestartStrategy`] enum's own wire-arm namespace).
13683        //
13684        // Peer of the sibling
13685        // [`restart_strategy_from_wire_rejects_unknown_byte_strings`]
13686        // (4eec29c) +
13687        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
13688        // (2aa6d23) +
13689        // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
13690        // (18c7342) refusal pins on the peer closed-set typed-enum
13691        // axes.
13692        for bad in [
13693            "",
13694            " ",
13695            "\n",
13696            "\t",
13697            "permanent",
13698            "temporary",
13699            "transient",
13700            "PERMANENT",
13701            "TEMPORARY",
13702            "TRANSIENT",
13703            "Permanents",
13704            "Permanent ",
13705            " Permanent",
13706            " Transient ",
13707            "Permanent\n",
13708            "perma",
13709            "Trans",
13710            "OneForOne",
13711            "Restart",
13712            "?",
13713        ] {
13714            assert!(
13715                RestartPolicy::from_wire(bad).is_none(),
13716                "RestartPolicy::from_wire({bad:?}) must return None — the \
13717                 parser's accept-set is exactly the three RestartPolicy::as_str \
13718                 outputs (Permanent, Temporary, Transient), and this \
13719                 byte-string is outside that closed set"
13720            );
13721        }
13722    }
13723
13724    #[test]
13725    fn restart_policy_from_wire_matches_serialize_derive_wire_byte_string() {
13726        // Fail-before-pass-after pin on the fourth path of the four-path
13727        // convergence: `from_wire` (the reverse projection) inverts the
13728        // `Serialize` derive's wire byte-string on every variant.
13729        // Together with the pre-existing three-path convergence
13730        // (`Display` + `as_str` + `Serialize` all resolve to the same
13731        // lifted [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const,
13732        // pinned by
13733        // [`restart_policy_display_matches_serialized_wire_byte_string`])
13734        // this closes the round-trip: the wire byte-string the
13735        // `Serialize` derive emits parses back to the same variant
13736        // through `from_wire`, so any future serde-attribute or variant-
13737        // rename drift on the emit half now surfaces as a matched drift
13738        // on the parse half at caixa-core build time — the two halves
13739        // migrate as a unit through the lifted consts on any future
13740        // rename, and the round-trip cannot silently split.
13741        //
13742        // Peer of the sibling
13743        // [`restart_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
13744        // (4eec29c) wire-format pin on
13745        // [`RestartStrategy::from_wire`] and the M3
13746        // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
13747        // (18c7342) wire-format pin on
13748        // [`crate::aplicacao::PlacementStrategy::from_wire`].
13749        for &variant in RestartPolicy::ALL {
13750            let wire = serde_json::to_string(&variant).unwrap();
13751            let unquoted = wire
13752                .strip_prefix('"')
13753                .and_then(|s| s.strip_suffix('"'))
13754                .expect("serialized RestartPolicy is a JSON string");
13755            let parsed = RestartPolicy::from_wire(unquoted).unwrap_or_else(|| {
13756                panic!(
13757                    "RestartPolicy::from_wire({unquoted:?}) must accept the \
13758                     Serialize derive's wire byte-string for \
13759                     RestartPolicy::{variant:?} — the four-path convergence \
13760                     (Display + as_str + Serialize + from_wire) resolves through \
13761                     the same lifted SUPERVISOR_CHILD_RESTART_* const; got None"
13762                )
13763            });
13764            assert_eq!(
13765                parsed, variant,
13766                "RestartPolicy::from_wire of the Serialize derive's wire \
13767                 byte-string for RestartPolicy::{variant:?} must round-trip \
13768                 to the same variant; got {parsed:?}"
13769            );
13770        }
13771    }
13772
13773    // ── drift-detection: ChildSpec::nome accessor pins ────────────────────
13774    //
13775    // The M2 supervisor-tree sibling of the M3 `Membro::nome` (4a32abf) pin
13776    // pair (`membro_nome_returns_caixa_byte_equal_across_permutations` +
13777    // `membro_nome_borrows_from_caixa_storage`) — extended here to the M2
13778    // per-`:children` child-caixa `:nome` axis, sibling to the first M2
13779    // slot scalar accessor `UpgradeFromEntry::prior_versao` (75d27a8) on
13780    // the peer per-`:upgrade-from :from` axis. The three pins jointly
13781    // brace the accessor against every future silent detour that would
13782    // desynchronize it from the raw `.caixa` field access every consumer
13783    // previously open-coded.
13784
13785    #[test]
13786    fn child_spec_nome_returns_caixa_byte_equal_across_permutations() {
13787        // The canonical per-`:children` child-caixa `:nome`-scalar pin:
13788        // [`ChildSpec::nome`] must return the `:children :caixa` field
13789        // byte-for-byte across every DNS-1123-label value the upstream
13790        // [`crate::render::require_valid_dns_1123_label`] gate at
13791        // `SupervisorSpec::validate` admits. Peer of the sibling
13792        // `membro_nome_returns_caixa_byte_equal_across_permutations`
13793        // (4a32abf) pin on the M3 per-`:membros` axis — same "the
13794        // substrate-primitive accessor must byte-equal the raw field
13795        // access verbatim across every author-declared value" discipline
13796        // extended to the M2 supervisor-tree per-`:children` arm. Pins
13797        // against a future silent detour that re-normalized the child
13798        // identity (an accidental `.to_lowercase()` — every `:children
13799        // :caixa` is validated as a DNS-1123 label upstream, so any
13800        // re-normalization is redundant + a drift surface between the
13801        // validator and the accessor), a namespace-prefix rewrite (an
13802        // accidental `format!("{namespace}/{caixa}")` per-CR
13803        // fully-qualified rewrite that didn't land on the peer axes), or
13804        // a per-cluster alias stamp the future wasm-operator's
13805        // hierarchical reconciliation scheduler authors on one consumer
13806        // without the others. Five values sweep the accept-set the
13807        // DNS-1123 gate upstream admits (short single-word / dashed /
13808        // v-suffixed / mixed-digit child names).
13809        for name in [
13810            "worker",
13811            "cache-server",
13812            "scratch-job",
13813            "orders-v2",
13814            "session-8080",
13815        ] {
13816            let c = ChildSpec {
13817                caixa: name.into(),
13818                versao: "^0.1".into(),
13819                restart: RestartPolicy::Permanent,
13820            };
13821            assert_eq!(
13822                c.nome(),
13823                name,
13824                "ChildSpec::nome must return :children :caixa verbatim \
13825                 (got {:?}, expected {name:?})",
13826                c.nome(),
13827            );
13828            assert_eq!(
13829                c.nome(),
13830                c.caixa.as_str(),
13831                "ChildSpec::nome must byte-equal the .caixa field access",
13832            );
13833        }
13834    }
13835
13836    #[test]
13837    fn child_spec_nome_borrows_from_caixa_storage() {
13838        // The borrow-not-copy pin: [`ChildSpec::nome`] must return a
13839        // `&str` slice that borrows from the typed slot's own [`String`]
13840        // storage — same-address invariant with `c.caixa.as_str()`. Pins
13841        // against a future silent detour that allocated a fresh `String`
13842        // (`self.caixa.clone()` in the body would type-check but silently
13843        // drop the borrow, and every downstream consumer that assumed
13844        // the returned slice outlives `&self` would break on a stale-
13845        // reference use-after-free — the [`crate::render::insert_first_seen`]
13846        // dedup key at [`SupervisorSpec::validate`], the
13847        // [`validate_no_self_supervision`] equality check against the
13848        // parent's `:nome` string slice, the DNS-1123 gate's `&str`
13849        // borrow — each would silently misbehave if this accessor
13850        // produced a detached copy). Peer of the sibling
13851        // `membro_nome_borrows_from_caixa_storage` (4a32abf) pin on the
13852        // M3 per-`:membros` axis and the
13853        // `prior_versao_borrows_from_from_storage` (75d27a8) pin on the
13854        // first M2 slot scalar accessor.
13855        let c = ChildSpec {
13856            caixa: "worker".into(),
13857            versao: "^0.1".into(),
13858            restart: RestartPolicy::Permanent,
13859        };
13860        let name = c.nome();
13861        let caixa_slice = c.caixa.as_str();
13862        assert_eq!(
13863            name.as_ptr(),
13864            caixa_slice.as_ptr(),
13865            "ChildSpec::nome must borrow from the .caixa String's backing \
13866             storage — a fresh allocation here means the accessor no \
13867             longer names the substrate-primitive typed dispatch and \
13868             every downstream consumer would silently carry a detached \
13869             copy",
13870        );
13871        assert_eq!(
13872            name.len(),
13873            caixa_slice.len(),
13874            "ChildSpec::nome and .caixa.as_str() must byte-equal in length \
13875             as well as in address",
13876        );
13877    }
13878
13879    #[test]
13880    fn validate_gates_child_nome_through_lifted_accessor() {
13881        // Bilateral coherence pin: every `:children :caixa` that
13882        // [`SupervisorSpec::validate`] accepts is one
13883        // [`crate::render::require_valid_dns_1123_label`] accepts on the
13884        // accessor-projected value, and vice versa on the reject side.
13885        // This closes the "the validator reads through the accessor"
13886        // contract structurally — a future silent detour that made the
13887        // accessor return a different byte-string than the validator
13888        // gates against would surface here as a coverage mismatch, not
13889        // as an apply-time DNS-1123 rejection at
13890        // `metadata.name: Invalid value` far from the caixa.lisp source.
13891        // Peer of the M2 sibling
13892        // `validate_parses_prior_versao_through_lifted_accessor`
13893        // (75d27a8) on the per-`:upgrade-from :from` axis and the M3
13894        // `validate_membros` peer discipline.
13895        //
13896        // Accept-set sweep: five DNS-1123-label values the upstream gate
13897        // admits.
13898        for ok_name in ["a", "worker", "cache-server", "orders-v2", "svc-8080"] {
13899            let s = SupervisorSpec {
13900                children: vec![ChildSpec {
13901                    caixa: ok_name.into(),
13902                    versao: "^0.1".into(),
13903                    restart: RestartPolicy::Permanent,
13904                }],
13905                ..SupervisorSpec::default()
13906            };
13907            s.validate().unwrap_or_else(|e| {
13908                panic!(
13909                    "SupervisorSpec::validate must accept :children :caixa {ok_name:?} \
13910                     (upstream DNS-1123 gate accepts it): got {e:?}",
13911                );
13912            });
13913            let c = ChildSpec {
13914                caixa: ok_name.into(),
13915                versao: "^0.1".into(),
13916                restart: RestartPolicy::Permanent,
13917            };
13918            crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| ())
13919                .unwrap_or_else(|()| {
13920                    panic!(
13921                        "require_valid_dns_1123_label must accept the accessor-projected \
13922                     :children :caixa {ok_name:?}",
13923                    );
13924                });
13925        }
13926        // Reject-set sweep: five DNS-1123-label-violating shapes the
13927        // upstream gate refuses (empty / uppercase / underscore / dot /
13928        // leading-hyphen). Every rejection at the validator must
13929        // correspond to a rejection when the accessor's projected value
13930        // is fed back through the shared gate.
13931        for bad_name in ["", "Worker", "my_worker", "team.worker", "-worker"] {
13932            let s = SupervisorSpec {
13933                children: vec![ChildSpec {
13934                    caixa: bad_name.into(),
13935                    versao: "^0.1".into(),
13936                    restart: RestartPolicy::Permanent,
13937                }],
13938                ..SupervisorSpec::default()
13939            };
13940            let err = s.validate().unwrap_err();
13941            assert!(
13942                matches!(
13943                    err,
13944                    SupervisorError::EmptyChildName | SupervisorError::ChildCaixaInvalid { .. }
13945                ),
13946                "SupervisorSpec::validate must reject :children :caixa {bad_name:?} \
13947                 via the DNS-1123 gate: got {err:?}",
13948            );
13949            let c = ChildSpec {
13950                caixa: bad_name.into(),
13951                versao: "^0.1".into(),
13952                restart: RestartPolicy::Permanent,
13953            };
13954            assert!(
13955                crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| (),)
13956                    .is_err(),
13957                "require_valid_dns_1123_label must reject the accessor-projected \
13958                 :children :caixa {bad_name:?}",
13959            );
13960        }
13961    }
13962
13963    // ── drift-detection: ChildSpec::versao_requirement accessor pins ──────
13964    //
13965    // Sibling of the peer per-`:membros` `membro_versao_requirement_*`
13966    // (a40b0e3) pin pair on the M3 mesh-slot surface — extended here to the
13967    // M2 supervisor-tree per-`:children` child-`:versao` axis, sibling to
13968    // the just-landed [`ChildSpec::nome`] (57c61d0) child-`:nome` pin
13969    // trio on the peer per-`:children` `String`-carry axis. The three pins
13970    // jointly brace the accessor against every future silent detour that
13971    // would desynchronize it from the raw `.versao` field access the
13972    // requirement gate + error carrier previously open-coded.
13973    //
13974    // Closes the last unlifted per-`:children` `String`-carry axis: the
13975    // pair (`nome`, `versao_requirement`) now jointly projects the
13976    // (`.caixa`, `.versao`) field pair every OTP-shape supervisor-tree
13977    // consumer that fans on per-child identity + version pin reads,
13978    // matching the peer M3 (`Membro::nome`, `Membro::versao_requirement`)
13979    // pair discipline verbatim.
13980    #[test]
13981    fn child_spec_versao_requirement_returns_versao_byte_equal_across_permutations() {
13982        // The canonical per-`:children` child-`:versao`-scalar pin:
13983        // [`ChildSpec::versao_requirement`] must return the `:children
13984        // :versao` field byte-for-byte across every Cargo-shaped semver
13985        // requirement value the upstream
13986        // [`crate::render::require_valid_versao_requirement`] gate admits.
13987        // Peer of the sibling
13988        // `membro_versao_requirement_returns_versao_byte_equal_across_permutations`
13989        // (a40b0e3) pin on the M3 per-`:membros` axis — same "the
13990        // substrate-primitive accessor must byte-equal the raw field
13991        // access verbatim across every author-declared value" discipline
13992        // extended to the M2 supervisor-tree per-`:children` arm. Pins
13993        // against a future silent detour that re-canonicalized the
13994        // requirement (an accidental `.to_string()` via
13995        // [`crate::version::parse_requirement`] → [`std::fmt::Display`]
13996        // round-trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and
13997        // silently drifted the error carrier's quoted requirement away
13998        // from the source `caixa.lisp`, an accidental whitespace trim on
13999        // `"^ 0.1"` that no consumer ever produced from the field-access
14000        // side, an accidental per-cluster lacre-projected concrete-version
14001        // rewrite that didn't land on the peer requirement-gate call).
14002        // Five values sweep the accept-set the shared
14003        // [`crate::render::require_valid_versao_requirement`] gate admits
14004        // (caret / tilde / exact / wildcard / bare-major).
14005        for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
14006            let c = ChildSpec {
14007                caixa: "worker".into(),
14008                versao: req.into(),
14009                restart: RestartPolicy::Permanent,
14010            };
14011            assert_eq!(
14012                c.versao_requirement(),
14013                req,
14014                "ChildSpec::versao_requirement must return :children :versao \
14015                 verbatim (got {:?}, expected {req:?})",
14016                c.versao_requirement(),
14017            );
14018            assert_eq!(
14019                c.versao_requirement(),
14020                c.versao.as_str(),
14021                "ChildSpec::versao_requirement must byte-equal the .versao \
14022                 field access",
14023            );
14024        }
14025    }
14026
14027    #[test]
14028    fn child_spec_versao_requirement_borrows_from_versao_storage() {
14029        // The borrow-not-copy pin: [`ChildSpec::versao_requirement`] must
14030        // return a `&str` slice that borrows from the typed slot's own
14031        // [`String`] storage — same-address invariant with
14032        // `c.versao.as_str()`. Pins against a future silent detour that
14033        // allocated a fresh `String` (`self.versao.clone()` in the body
14034        // would type-check but silently drop the borrow, and every
14035        // downstream consumer that assumed the returned slice outlives
14036        // `&self` — the [`crate::render::require_valid_versao_requirement`]
14037        // gate's `&str` borrow, the [`SupervisorError::ChildVersaoInvalid`]
14038        // `.to_string()` carrier's byte-length assumption — would silently
14039        // misbehave if this accessor produced a detached copy). Peer of
14040        // the sibling `child_spec_nome_borrows_from_caixa_storage`
14041        // (57c61d0) pin on the per-`:children` `:nome` axis and the M3
14042        // `membro_versao_requirement_borrows_from_versao_storage` (a40b0e3)
14043        // pin on the peer per-`:membros` `:versao` axis.
14044        let c = ChildSpec {
14045            caixa: "worker".into(),
14046            versao: "^0.1".into(),
14047            restart: RestartPolicy::Permanent,
14048        };
14049        let req = c.versao_requirement();
14050        let versao_slice = c.versao.as_str();
14051        assert_eq!(
14052            req.as_ptr(),
14053            versao_slice.as_ptr(),
14054            "ChildSpec::versao_requirement must borrow from the .versao \
14055             String's backing storage — a fresh allocation here means the \
14056             accessor no longer names the substrate-primitive typed \
14057             dispatch and every downstream consumer would silently carry \
14058             a detached copy",
14059        );
14060        assert_eq!(
14061            req.len(),
14062            versao_slice.len(),
14063            "ChildSpec::versao_requirement and .versao.as_str() must \
14064             byte-equal in length as well as in address",
14065        );
14066    }
14067
14068    #[test]
14069    fn validate_gates_child_versao_through_lifted_accessor() {
14070        // Bilateral coherence pin: every `:children :versao` that
14071        // [`SupervisorSpec::validate`] accepts is one
14072        // [`crate::render::require_valid_versao_requirement`] accepts on
14073        // the accessor-projected value, and vice versa on the reject side.
14074        // This closes the "the validator reads through the accessor"
14075        // contract structurally — a future silent detour that made the
14076        // accessor return a different byte-string than the validator gates
14077        // against would surface here as a coverage mismatch, not as a
14078        // resolver-time semver-parse rejection at lacre-closure time far
14079        // from the caixa.lisp source. Peer of the sibling
14080        // `validate_gates_child_nome_through_lifted_accessor` (57c61d0) on
14081        // the per-`:children :caixa` axis and the M2
14082        // `validate_parses_prior_versao_through_lifted_accessor` (75d27a8)
14083        // on the peer per-`:upgrade-from :from` axis.
14084        //
14085        // Accept-set sweep: five Cargo-shaped semver requirement values
14086        // the upstream gate admits (caret / tilde / exact / wildcard /
14087        // bare-major).
14088        for ok_req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
14089            let s = SupervisorSpec {
14090                children: vec![ChildSpec {
14091                    caixa: "worker".into(),
14092                    versao: ok_req.into(),
14093                    restart: RestartPolicy::Permanent,
14094                }],
14095                ..SupervisorSpec::default()
14096            };
14097            s.validate().unwrap_or_else(|e| {
14098                panic!(
14099                    "SupervisorSpec::validate must accept :children :versao {ok_req:?} \
14100                     (upstream versao-requirement gate accepts it): got {e:?}",
14101                );
14102            });
14103            let c = ChildSpec {
14104                caixa: "worker".into(),
14105                versao: ok_req.into(),
14106                restart: RestartPolicy::Permanent,
14107            };
14108            crate::render::require_valid_versao_requirement(
14109                c.versao_requirement(),
14110                || (),
14111                |_reason| (),
14112            )
14113            .unwrap_or_else(|()| {
14114                panic!(
14115                    "require_valid_versao_requirement must accept the accessor-projected \
14116                     :children :versao {ok_req:?}",
14117                );
14118            });
14119        }
14120        // Reject-set sweep: five requirement-violating shapes the upstream
14121        // gate refuses. The empty string closes the empty-first arm of the
14122        // shared [`crate::render::require_valid_versao_requirement`]
14123        // cascade; the four non-empty arms exercise distinct semver-parse
14124        // failure modes the M3 peer per-`:membros` reject-set already pins
14125        // (`rejects_invalid_membro_versao_requirement` on `^bad-version`,
14126        // `rejects_membro_versao_with_double_caret_typo` on `^^0.1`,
14127        // `rejects_membro_versao_with_v_prefixed_tag` on `v0.1`) — the
14128        // shared parser routing means the same reject-set must fail
14129        // identically at the M2 supervisor-tree per-`:children` accessor
14130        // arm here. Every rejection at the validator must correspond to a
14131        // rejection when the accessor's projected value is fed back
14132        // through the shared gate.
14133        //
14134        // (Bare partial magnitudes like `"0.1"` and bare identifiers like
14135        // `"not-a-semver"` are intentionally *not* in the reject-set: the
14136        // semver crate accepts `"0.1"` as an implicit `^0.1` requirement,
14137        // and the identifier-tail arm's grammar admits some non-canonical
14138        // shapes — matching what the M3 peer test suite already documents
14139        // as the shared parser's accept-set edges.)
14140        for bad_req in ["", "v0.1.0", "^bad-version", "^^0.1", "v0.1"] {
14141            let s = SupervisorSpec {
14142                children: vec![ChildSpec {
14143                    caixa: "worker".into(),
14144                    versao: bad_req.into(),
14145                    restart: RestartPolicy::Permanent,
14146                }],
14147                ..SupervisorSpec::default()
14148            };
14149            let err = s.validate().unwrap_err();
14150            assert!(
14151                matches!(
14152                    err,
14153                    SupervisorError::EmptyChildVersion { .. }
14154                        | SupervisorError::ChildVersaoInvalid { .. }
14155                ),
14156                "SupervisorSpec::validate must reject :children :versao {bad_req:?} \
14157                 via the versao-requirement gate: got {err:?}",
14158            );
14159            let c = ChildSpec {
14160                caixa: "worker".into(),
14161                versao: bad_req.into(),
14162                restart: RestartPolicy::Permanent,
14163            };
14164            assert!(
14165                crate::render::require_valid_versao_requirement(
14166                    c.versao_requirement(),
14167                    || (),
14168                    |_reason| (),
14169                )
14170                .is_err(),
14171                "require_valid_versao_requirement must reject the accessor-projected \
14172                 :children :versao {bad_req:?}",
14173            );
14174        }
14175    }
14176
14177    // ── per-`:children` `:restart` typed-accessor coherence pins ──────────
14178    //
14179    // The [`ChildSpec::restart`] accessor lift closes the last unlifted
14180    // per-`:children` axis (the pair `nome()` + `versao_requirement()`
14181    // already project the `String`-carry `(caixa, versao)` fields; the
14182    // `Copy`-composite-enum `restart` field is the third and final axis).
14183    // Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
14184    // (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
14185    // scalar accessor and the M3 mesh-slot [`crate::Placement::estrategia`]
14186    // (921fe1b) `Copy`-return [`crate::PlacementStrategy`] distribution-
14187    // strategy scalar accessor — same "one typed dispatch on the substrate
14188    // primitive, `Copy`-projected closed-set enum-arm discriminator" shape
14189    // extended onto the M2 supervisor-slot per-`:children` restart-decision
14190    // axis. The pin below covers the accessor's byte-equal projection
14191    // against the raw field access across every variant in the closed
14192    // accept-set (`Permanent`, `Transient`, `Temporary`).
14193
14194    #[test]
14195    fn child_spec_restart_returns_restart_verbatim_across_permutations() {
14196        // The canonical per-`:children` restart-decision-policy-scalar
14197        // pin: [`ChildSpec::restart`] must return the `:children :restart`
14198        // field verbatim as a [`RestartPolicy`], `Copy`-projected from the
14199        // typed slot's own [`RestartPolicy`] storage across every variant
14200        // in the closed accept-set (`Permanent`, `Transient`, `Temporary`).
14201        // Pins against a future silent detour that re-derived the policy
14202        // from a peer axis (an accidental fallback to
14203        // `if is_supervisor_child { Permanent } else { Temporary }` that
14204        // collapsed the child's kind axis into the restart discriminator),
14205        // a variant remap the operator authors on one consumer without the
14206        // other, or a stale-derive detour that substituted
14207        // [`RestartPolicy::default`] when the field held any explicit
14208        // variant (which would silently collapse the distinction between
14209        // "author explicitly declared `:restart Permanent`" and "author
14210        // omitted the slot and inherited the default" the future
14211        // per-cluster restart-decision override slot depends on).
14212        //
14213        // Peer of the sibling per-`:supervisor`
14214        // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
14215        // (eafb619) pin on the M2 supervisor-slot sibling-restart-strategy
14216        // axis and the M3
14217        // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
14218        // (921fe1b) pin on the per-`:placement` distribution-strategy axis
14219        // — same "the substrate-primitive accessor must byte-equal the raw
14220        // field access verbatim across every author-declared value"
14221        // discipline extended onto the M2 supervisor-slot per-`:children`
14222        // restart-decision-policy axis, closing the last unlifted axis on
14223        // the per-`:children` [`ChildSpec`] type.
14224        for restart in [
14225            RestartPolicy::Permanent,
14226            RestartPolicy::Transient,
14227            RestartPolicy::Temporary,
14228        ] {
14229            let c = ChildSpec {
14230                caixa: "worker".into(),
14231                versao: "^0.1".into(),
14232                restart,
14233            };
14234            assert_eq!(
14235                c.restart(),
14236                restart,
14237                "ChildSpec::restart must return :children :restart \
14238                 verbatim (got {:?}, expected {restart:?})",
14239                c.restart(),
14240            );
14241            assert_eq!(
14242                c.restart(),
14243                c.restart,
14244                "ChildSpec::restart accessor and .restart field access \
14245                 must byte-equal — the accessor is the substrate-primitive \
14246                 typed dispatch every downstream per-child restart-\
14247                 decision consumer must route through",
14248            );
14249        }
14250    }
14251
14252    // ── per-`:supervisor` `:estrategia` typed-accessor coherence pins ─────
14253    //
14254    // The [`SupervisorSpec::estrategia`] accessor lift extends the peer M3
14255    // [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
14256    // distribution-strategy accessor discipline onto the M2 supervisor-slot
14257    // per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
14258    // scalar axis. The two pins below cover (1) the accessor's byte-equal
14259    // projection against the raw field access across every variant in the
14260    // closed accept-set, and (2) the two-consumer coherence between the
14261    // [`SupervisorSpec::validate`] partition-dispatch `match` arm and the
14262    // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
14263    // carrier's `estrategia:` field — peer of the sibling M3
14264    // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
14265    // / `validate_placement_reads_through_lifted_estrategia_accessor` pin
14266    // pair on the per-`:placement` distribution-strategy axis.
14267
14268    #[test]
14269    fn supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations() {
14270        // The canonical per-`:supervisor` sibling-restart-strategy-scalar
14271        // pin: [`SupervisorSpec::estrategia`] must return the
14272        // `:supervisor :estrategia` field verbatim as a
14273        // [`RestartStrategy`], `Copy`-projected from the typed slot's own
14274        // [`RestartStrategy`] storage across every variant in the closed
14275        // accept-set (`OneForOne`, `OneForAll`, `RestForOne`,
14276        // `SimpleOneForOne`). Pins against a future silent detour that
14277        // re-derived the strategy from a peer axis (an accidental
14278        // fallback to `if children.is_empty() { SimpleOneForOne } else {
14279        // OneForOne }` collapse that read the children-count axis into
14280        // the strategy discriminator), a variant remap the operator
14281        // authors on one consumer without the other, or a stale-derive
14282        // detour that substituted [`RestartStrategy::default`] when the
14283        // field held any explicit variant (which would silently collapse
14284        // the distinction between "author explicitly declared
14285        // `:estrategia OneForOne`" and "author omitted the slot and
14286        // inherited the default" the future per-cluster strategy override
14287        // slot depends on). Peer of the sibling M3
14288        // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
14289        // (921fe1b) pin on the M3 mesh-slot `Copy`-composite-enum scalar
14290        // axis — same "the substrate-primitive accessor must byte-equal
14291        // the raw field access verbatim across every author-declared
14292        // value" discipline extended onto the M2 supervisor-slot
14293        // per-`:supervisor` sibling-restart-strategy axis.
14294        for &estrategia in RestartStrategy::ALL {
14295            // `SimpleOneForOne` requires `children.is_empty()`; the peer
14296            // three strategies require a non-empty static children list.
14297            // Build each shape coherently so the pin's fixture would
14298            // itself pass [`SupervisorSpec::validate`] once fed through
14299            // the sibling coherence pin below — the byte-equal projection
14300            // asserted here is a strictly weaker property (a `Copy` field
14301            // read) that does not depend on `validate` running, but
14302            // keeping the fixture validate-clean means a future extension
14303            // of the pin to exercise `validate` end-to-end does not have
14304            // to re-author the children shape.
14305            //
14306            // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
14307            // shape partition through the [`gen_platform::IsVariant`]
14308            // derive-generated
14309            // [`RestartStrategy::is_simple_one_for_one`] predicate rather
14310            // than the raw `matches!(estrategia, RestartStrategy::
14311            // SimpleOneForOne)` open-coded pattern-match — same closed-
14312            // set-typed-enum arm-discriminator dispatch discipline the
14313            // sibling [`crate::upgrade::UpgradeInstruction::is_restart`]
14314            // convergence (915a934) extended onto its two paired positive
14315            // / negated `matches!` sites and the peer
14316            // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
14317            // predicate convergence (766ec63) extended onto the M3 mesh-
14318            // slot per-`:placement` distribution-strategy discriminator
14319            // axis. See the sibling `round_trip_all_strategies` and the
14320            // peer `manifest::tests::
14321            // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
14322            // fixture for the two peer sites the same lift closes on.
14323            let children = if estrategia.is_simple_one_for_one() {
14324                Vec::new()
14325            } else {
14326                vec![ChildSpec {
14327                    caixa: "worker".into(),
14328                    versao: "^0.1".into(),
14329                    restart: RestartPolicy::Permanent,
14330                }]
14331            };
14332            let s = SupervisorSpec {
14333                estrategia,
14334                children,
14335                ..SupervisorSpec::default()
14336            };
14337            assert_eq!(
14338                s.estrategia(),
14339                estrategia,
14340                "SupervisorSpec::estrategia must return :supervisor :estrategia \
14341                 verbatim (got {:?}, expected {estrategia:?})",
14342                s.estrategia(),
14343            );
14344            assert_eq!(
14345                s.estrategia(),
14346                s.estrategia,
14347                "SupervisorSpec::estrategia accessor and .estrategia field \
14348                 access must byte-equal — the accessor is the substrate-\
14349                 primitive typed dispatch every downstream sibling-restart-\
14350                 strategy consumer must route through",
14351            );
14352        }
14353    }
14354
14355    #[test]
14356    fn validate_reads_through_lifted_estrategia_accessor() {
14357        // Two-consumer coherence pin: the [`SupervisorSpec::validate`]
14358        // `SimpleOneForOne ↔ non-SimpleOneForOne` `match` partition
14359        // dispatch (which reads through [`SupervisorSpec::estrategia`]
14360        // to fan across the strategy-arm shape-gate cascades) and the
14361        // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
14362        // error carrier's `estrategia:` field (which reads through
14363        // [`SupervisorSpec::estrategia`] to name the strategy the empty
14364        // `:children` list was declared against) must both key off the
14365        // lifted accessor, so any future rebrand on the typed slot's
14366        // reader shape lands at exactly one place. Pins the two-site
14367        // coherence by exercising the `NoChildren` error surface end-to-
14368        // end across every non-`SimpleOneForOne` variant and asserting
14369        // the surfaced `estrategia:` field byte-equals the accessor's
14370        // return. Peer of the sibling M3
14371        // `validate_placement_reads_through_lifted_estrategia_accessor`
14372        // (921fe1b) three-consumer coherence pin on the per-`:placement`
14373        // distribution-strategy axis.
14374        for estrategia in [
14375            RestartStrategy::OneForOne,
14376            RestartStrategy::OneForAll,
14377            RestartStrategy::RestForOne,
14378        ] {
14379            let s = SupervisorSpec {
14380                estrategia,
14381                children: Vec::new(),
14382                ..SupervisorSpec::default()
14383            };
14384            let err = s.validate().unwrap_err();
14385            match err {
14386                SupervisorError::NoChildren { estrategia: e } => {
14387                    assert_eq!(
14388                        e,
14389                        s.estrategia(),
14390                        "NoChildren.estrategia must byte-equal \
14391                         SupervisorSpec::estrategia() — the empty-`:children` \
14392                         refusal reads through the lifted accessor",
14393                    );
14394                    assert_eq!(
14395                        e, estrategia,
14396                        "NoChildren.estrategia must carry the author-declared \
14397                         :supervisor :estrategia variant verbatim (got {e:?}, \
14398                         expected {estrategia:?})",
14399                    );
14400                }
14401                other => panic!("expected NoChildren, got {other:?} for estrategia={estrategia:?}"),
14402            }
14403        }
14404    }
14405
14406    // ── per-`:supervisor` `:max-restarts` typed-accessor coherence pins ────
14407    //
14408    // The [`SupervisorSpec::max_restarts`] accessor lift extends the peer M3
14409    // [`crate::CircuitBreaker::max_failures`] (3a74062) `Copy`-return
14410    // required-`u32` scalar accessor discipline onto the M2 supervisor-slot
14411    // per-`:supervisor` restart-budget-count `Copy`-`u32` scalar axis.
14412    // The two pins below cover (1) the accessor's byte-equal projection
14413    // against the raw field access across every representative value in
14414    // the `u32` accept-set (`1` lower boundary, `SUPERVISOR_MAX_RESTARTS_MAX`
14415    // upper boundary, `0` past-the-guard zero sentinel, `u32::MAX`
14416    // past-the-guard cap sentinel), and (2) the [`SupervisorSpec::validate`]
14417    // zero-floor / cap composition — the validate gate and the accessor
14418    // must route through the same substrate-primitive typed dispatch, so
14419    // any future silent detour that had the accessor perform a
14420    // bounds-collapsing clamp would fail here at caixa-core build time.
14421    // Peer of the sibling M3
14422    // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
14423    // (3a74062) pin on the per-`CircuitBreaker :max-failures` axis.
14424
14425    #[test]
14426    fn supervisor_spec_max_restarts_returns_max_restarts_u32_byte_equal_across_permutations() {
14427        // The canonical per-`:supervisor` restart-budget-count scalar pin:
14428        // [`SupervisorSpec::max_restarts`] must return the `:supervisor
14429        // :max-restarts` typed `u32` verbatim, `Copy`-projected from the
14430        // typed slot's own `u32` storage, byte-equal to the raw field
14431        // access across every representative value in the accept-set —
14432        // `1` (the lower boundary of the `1..=SUPERVISOR_MAX_RESTARTS_MAX`
14433        // accept-set the surrounding [`SupervisorSpec::validate`] gate
14434        // carves out on the sibling `ZeroMaxRestarts` refusal),
14435        // `SUPERVISOR_MAX_RESTARTS_MAX` (the upper boundary the same gate
14436        // carves out on the sibling `MaxRestartsExceedsCap` refusal), `0`
14437        // (a past-the-guard sentinel that pins the accessor doesn't
14438        // perform a silent bounds-collapse into `1` on the zero arm —
14439        // validate rejects zero but the accessor must ship the raw slot
14440        // verbatim so a validate-time gate regression surfaces at the
14441        // emit boundary rather than being silently absorbed), `u32::MAX`
14442        // (a past-the-guard sentinel that pins the accessor doesn't
14443        // perform a silent bounds-collapse through
14444        // `SUPERVISOR_MAX_RESTARTS_MAX` at the return path).
14445        //
14446        // Peer of the sibling M3
14447        // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
14448        // (3a74062) pin on the M3 mesh-slot `Copy`-`u32` sub-struct
14449        // required-scalar axis — same "the substrate-primitive accessor
14450        // must byte-equal the raw field access verbatim across every
14451        // value in the `u32` accept-set" discipline extended onto the M2
14452        // supervisor-slot per-`:supervisor` restart-budget-count axis.
14453        for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX, 0, u32::MAX] {
14454            let s = SupervisorSpec {
14455                max_restarts,
14456                ..SupervisorSpec::default()
14457            };
14458            assert_eq!(
14459                s.max_restarts(),
14460                max_restarts,
14461                "SupervisorSpec::max_restarts must return :supervisor \
14462                 :max-restarts verbatim (got {}, expected {max_restarts})",
14463                s.max_restarts(),
14464            );
14465            assert_eq!(
14466                s.max_restarts(),
14467                s.max_restarts,
14468                "SupervisorSpec::max_restarts accessor and .max_restarts \
14469                 field access must byte-equal — the accessor is the \
14470                 substrate-primitive typed dispatch every downstream \
14471                 restart-budget-count consumer must route through",
14472            );
14473        }
14474    }
14475
14476    #[test]
14477    fn validate_max_restarts_zero_floor_and_cap_arms_route_through_accessor() {
14478        // Composition pin: [`SupervisorSpec::validate`]'s `:max-restarts`
14479        // zero-floor + upper-cap bracket must key off
14480        // [`SupervisorSpec::max_restarts`], not the raw `.max_restarts`
14481        // field access. Structurally: a `SupervisorSpec { max_restarts:
14482        // 0, .. }` must surface the `ZeroMaxRestarts` refusal exactly, a
14483        // `SupervisorSpec { max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
14484        // .. }` must surface the `MaxRestartsExceedsCap` refusal exactly
14485        // (with the offending count carried verbatim from the accessor
14486        // return), and a `SupervisorSpec { max_restarts: 1, .. }` (the
14487        // lower boundary of the accept-set) plus a `SupervisorSpec {
14488        // max_restarts: SUPERVISOR_MAX_RESTARTS_MAX, .. }` (the upper
14489        // boundary) must pass validate. The four together jointly pin the
14490        // accessor + validate-gate composition: any future silent detour
14491        // that had the accessor return a fresh `1` on the zero arm (a
14492        // `.max_restarts().max(1)` collapse) would silently absorb the
14493        // `ZeroMaxRestarts` refusal at the accessor boundary and the
14494        // validate gate would accept a struct-literal `SupervisorSpec {
14495        // max_restarts: 0, .. }` — the composition pin catches that at
14496        // caixa-core build time.
14497        //
14498        // Peer of the sibling M3
14499        // `validate_politicas_max_failures_zero_floor_arm_routes_through_accessor`
14500        // (3a74062) pin on the sibling per-`CircuitBreaker :max-failures`
14501        // composition axis — same "the validate / shape-gate predicate
14502        // must route through the substrate-primitive typed dispatch"
14503        // discipline extended onto the peer M2 supervisor-slot
14504        // required-`u32` composition axis.
14505        let child = ChildSpec {
14506            caixa: "worker".into(),
14507            versao: "^0.1".into(),
14508            restart: RestartPolicy::Permanent,
14509        };
14510        // Zero-floor arm.
14511        let s = SupervisorSpec {
14512            max_restarts: 0,
14513            children: vec![child.clone()],
14514            ..SupervisorSpec::default()
14515        };
14516        assert_eq!(
14517            s.validate().unwrap_err(),
14518            SupervisorError::ZeroMaxRestarts,
14519            "validate must reject max_restarts == 0 with ZeroMaxRestarts \
14520             — the accessor and the validate gate must route through the \
14521             same substrate-primitive typed dispatch on the zero-floor arm",
14522        );
14523        // Cap arm — the surfaced `max_restarts:` field must byte-equal
14524        // the accessor's return so a future rebrand on the accessor
14525        // lands in the diagnostic without a coordinated rewrite.
14526        let over_cap = SUPERVISOR_MAX_RESTARTS_MAX + 1;
14527        let s = SupervisorSpec {
14528            max_restarts: over_cap,
14529            children: vec![child.clone()],
14530            ..SupervisorSpec::default()
14531        };
14532        match s.validate().unwrap_err() {
14533            SupervisorError::MaxRestartsExceedsCap { max_restarts } => {
14534                assert_eq!(
14535                    max_restarts,
14536                    s.max_restarts(),
14537                    "MaxRestartsExceedsCap.max_restarts must byte-equal \
14538                     SupervisorSpec::max_restarts() — the cap-arm refusal \
14539                     reads through the lifted accessor",
14540                );
14541                assert_eq!(
14542                    max_restarts, over_cap,
14543                    "MaxRestartsExceedsCap.max_restarts must carry the \
14544                     author-declared :supervisor :max-restarts value \
14545                     verbatim (got {max_restarts}, expected {over_cap})",
14546                );
14547            }
14548            other => panic!("expected MaxRestartsExceedsCap, got {other:?}"),
14549        }
14550        // Lower + upper accept-set boundaries.
14551        for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX] {
14552            let s = SupervisorSpec {
14553                max_restarts,
14554                children: vec![child.clone()],
14555                ..SupervisorSpec::default()
14556            };
14557            assert!(
14558                s.validate().is_ok(),
14559                "validate must accept max_restarts == {max_restarts} \
14560                 (an accept-set boundary of \
14561                 1..=SUPERVISOR_MAX_RESTARTS_MAX)",
14562            );
14563        }
14564    }
14565
14566    // ── per-`:supervisor` `:restart-window` typed-accessor coherence pins ─
14567    //
14568    // The [`SupervisorSpec::restart_window`] accessor lift extends the peer
14569    // M2 [`crate::LimitsSpec::wall_clock`] (8cb717b) `Option<Duration>`
14570    // accessor discipline and the peer M3 [`crate::MeshPolicy::timeout`]
14571    // (7073d0f) `Option<Duration>` accessor discipline onto the M2
14572    // supervisor-slot per-`:supervisor` restart-intensity-denominator
14573    // `Option<Duration>` scalar axis — third `Copy`-return accessor on the
14574    // M2 supervisor-slot `SupervisorSpec` type, closing the last unlifted
14575    // per-`:supervisor` scalar-value axis. The three pins below cover
14576    // (1) the accessor's byte-equal projection against the raw field
14577    // access across every representative value in the `Option<Duration>`
14578    // accept-set (`None` never-reset sentinel, `Some(Duration::from_millis(1))`
14579    // lower boundary, `Some(SUPERVISOR_RESTART_WINDOW_MAX)` upper boundary,
14580    // `Some(Duration::ZERO)` past-the-guard zero sentinel, `Some(Duration::MAX)`
14581    // past-the-guard above-cap sentinel), (2) the [`SupervisorSpec::validate`]
14582    // `if let Some(w) = self.restart_window() { … }` bracket-arm
14583    // composition — the validate gate and the accessor must route through
14584    // the same substrate-primitive typed dispatch, so any future silent
14585    // detour that had the accessor perform a bounds-collapsing clamp
14586    // would fail here at caixa-core build time, and (3) the accessor's
14587    // by-copy idempotence pin — the returned `Option<Duration>` must
14588    // outlive `&self` and two successive calls must return byte-equal
14589    // values. Peer of the sibling M2
14590    // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
14591    // (8cb717b) pin on the per-`:limits :wall-clock` axis and the sibling
14592    // M3 `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
14593    // (7073d0f) pin on the per-`:politicas :timeout` axis.
14594
14595    #[test]
14596    fn supervisor_spec_restart_window_returns_option_duration_byte_equal_across_permutations() {
14597        // The canonical per-`:supervisor` restart-intensity-denominator
14598        // scalar pin: [`SupervisorSpec::restart_window`] must return the
14599        // `:supervisor :restart-window` typed [`Duration`] verbatim as an
14600        // `Option<Duration>`, `Copy`-projected from the typed slot's own
14601        // `Option<Duration>` storage, byte-equal to the raw field access
14602        // across every representative value in the accept-set — `None`
14603        // (the "never reset — every restart across the supervisor's
14604        // lifetime counts against the sibling `:max-restarts` budget"
14605        // sentinel the field's own docstring names and the peer
14606        // `validate_accepts_none_restart_window` pin locks in on the
14607        // [`SupervisorSpec::validate`] entry-side),
14608        // `Some(Duration::from_millis(1))` (the structural minimum a
14609        // validated `:restart-window` may carry, the integer-millisecond
14610        // floor [`SupervisorError::RestartWindowNotCanonical`] rejects
14611        // everything sub-ms; `Duration::ZERO` is separately rejected by
14612        // [`SupervisorError::RestartWindowZero`]),
14613        // `Some(SUPERVISOR_RESTART_WINDOW_MAX)` (the upper boundary the
14614        // surrounding [`SupervisorSpec::validate`] gate carves out on the
14615        // sibling [`SupervisorError::RestartWindowExceedsCap`] refusal),
14616        // `Some(Duration::ZERO)` (a past-the-guard sentinel that pins the
14617        // accessor doesn't perform a silent bounds-collapse into `None` on
14618        // the zero-Duration arm — validate rejects zero but the accessor
14619        // must ship the raw slot verbatim so a validate-time gate
14620        // regression surfaces at the emit boundary rather than being
14621        // silently absorbed), and `Some(Duration::MAX)` (a past-the-guard
14622        // sentinel that pins the accessor doesn't perform a silent
14623        // bounds-collapse through [`SUPERVISOR_RESTART_WINDOW_MAX`] at the
14624        // return path).
14625        //
14626        // Peer of the sibling M2
14627        // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
14628        // (8cb717b) pin on the per-`:limits :wall-clock` axis and the
14629        // sibling M3
14630        // `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
14631        // (7073d0f) pin on the per-`:politicas :timeout` axis — same "the
14632        // substrate-primitive accessor must byte-equal the raw field
14633        // access verbatim across every value in the `Option<Duration>`
14634        // accept-set" discipline extended onto the M2 supervisor-slot
14635        // per-`:supervisor` `Option<Duration>` axis. Pins against a future
14636        // silent detour that re-derived the restart-window from a peer
14637        // axis (an accidental `.max_restarts.into()` collapse that read
14638        // the restart-budget-count as a duration — the two axes serve
14639        // different halves of the `MaxIntensity / Period` restart-
14640        // intensity ratio, and confusing them silently inverts the
14641        // ratio's numerator and denominator), a `None → Some(Duration::ZERO)`
14642        // "zero means never reset" collapse (the canonical
14643        // `Option<Duration>` → `Duration` collapse footgun the
14644        // [`SupervisorError::RestartWindowZero`] validate arm guards on
14645        // the peer zero-floor axis; a zero period either trips on the
14646        // first failure or never trips depending on operator
14647        // interpretation, neither of which is the author's "never reset"
14648        // intent that `None` expresses structurally), or a per-arm
14649        // variant swap that landed on one consumer without the other.
14650        for restart_window in [
14651            None,
14652            Some(Duration::from_millis(1)),
14653            Some(SUPERVISOR_RESTART_WINDOW_MAX),
14654            Some(Duration::ZERO),
14655            Some(Duration::MAX),
14656        ] {
14657            let s = SupervisorSpec {
14658                restart_window,
14659                ..SupervisorSpec::default()
14660            };
14661            assert_eq!(
14662                s.restart_window(),
14663                restart_window,
14664                "SupervisorSpec::restart_window must return :supervisor \
14665                 :restart-window verbatim (got {:?}, expected {restart_window:?})",
14666                s.restart_window(),
14667            );
14668            assert_eq!(
14669                s.restart_window(),
14670                s.restart_window,
14671                "SupervisorSpec::restart_window accessor and \
14672                 .restart_window field access must byte-equal — the \
14673                 accessor is the substrate-primitive typed dispatch every \
14674                 downstream restart-intensity-denominator consumer must \
14675                 route through",
14676            );
14677        }
14678    }
14679
14680    #[test]
14681    fn validate_restart_window_bracket_arm_routes_through_accessor() {
14682        // Composition pin: [`SupervisorSpec::validate`]'s
14683        // `:restart-window` `if let Some(w) = self.restart_window() { … }`
14684        // zero-floor + integer-millisecond canonical-form + upper-cap
14685        // bracket-arm must key off [`SupervisorSpec::restart_window`], not
14686        // the raw `.restart_window` field access. Structurally: a
14687        // `SupervisorSpec { restart_window: None, .. }` must pass the
14688        // arm gate structurally (the `if let Some(_)` shape returns
14689        // early on the `None` arm — the accessor and the validate gate
14690        // must agree on `None → skip the bracket cascade` so an authored
14691        // `:restart-window ()` structurally routes through the "never
14692        // reset" sentinel path), a `SupervisorSpec { restart_window:
14693        // Some(Duration::ZERO), .. }` must surface the `RestartWindowZero`
14694        // refusal exactly, a `SupervisorSpec { restart_window:
14695        // Some(Duration::from_micros(1500)), .. }` must surface the
14696        // `RestartWindowNotCanonical` refusal exactly (with the offending
14697        // duration carried verbatim from the accessor return), a
14698        // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX
14699        // + Duration::from_millis(1)), .. }` must surface the
14700        // `RestartWindowExceedsCap` refusal exactly (with the offending
14701        // duration carried verbatim from the accessor return), and a
14702        // `SupervisorSpec { restart_window: Some(Duration::from_millis(1)),
14703        // .. }` (the lower boundary of the accept-set) plus a
14704        // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
14705        // .. }` (the upper boundary) must pass validate. The six together
14706        // jointly pin the accessor + validate-gate composition: any future
14707        // silent detour that had the accessor return a fresh `None` on any
14708        // `Some` arm (a `.restart_window().filter(|w| !w.is_zero())`
14709        // collapse) would silently absorb the `RestartWindowZero` refusal
14710        // at the accessor boundary and the validate gate would accept a
14711        // struct-literal `SupervisorSpec { restart_window:
14712        // Some(Duration::ZERO), .. }` — the composition pin catches that
14713        // at caixa-core build time.
14714        //
14715        // Peer of the sibling M2 [`crate::LimitsSpec::wall_clock`]
14716        // (8cb717b) validate-arm-route pin on the per-`:limits :wall-clock`
14717        // axis and the peer M3 [`crate::MeshPolicy::timeout`] (7073d0f)
14718        // accessor-composition pin on the per-`:politicas :timeout` axis —
14719        // same "the validate / shape-gate predicate must route through
14720        // the substrate-primitive typed dispatch" discipline extended
14721        // onto the peer M2 supervisor-slot optional-`Duration` axis.
14722        let child = ChildSpec {
14723            caixa: "worker".into(),
14724            versao: "^0.1".into(),
14725            restart: RestartPolicy::Permanent,
14726        };
14727        // None arm — must not surface any :restart-window-shaped refusal;
14728        // the `if let Some(_)` bracket returns early on `None` structurally.
14729        let s = SupervisorSpec {
14730            restart_window: None,
14731            children: vec![child.clone()],
14732            ..SupervisorSpec::default()
14733        };
14734        assert!(
14735            s.validate().is_ok(),
14736            "validate must accept restart_window: None (the never-reset \
14737             sentinel) — the `if let Some(_)` bracket returns early on \
14738             the None arm and the accessor must agree",
14739        );
14740        // Zero-floor arm.
14741        let s = SupervisorSpec {
14742            restart_window: Some(Duration::ZERO),
14743            children: vec![child.clone()],
14744            ..SupervisorSpec::default()
14745        };
14746        assert_eq!(
14747            s.validate().unwrap_err(),
14748            SupervisorError::RestartWindowZero,
14749            "validate must reject restart_window == Some(Duration::ZERO) \
14750             with RestartWindowZero — the accessor and the validate gate \
14751             must route through the same substrate-primitive typed \
14752             dispatch on the zero-floor arm",
14753        );
14754        // Non-canonical (sub-ms) arm — the surfaced `window:` field must
14755        // byte-equal the accessor's return so a future rebrand on the
14756        // accessor lands in the diagnostic without a coordinated rewrite.
14757        let sub_ms = Duration::from_micros(1500);
14758        let s = SupervisorSpec {
14759            restart_window: Some(sub_ms),
14760            children: vec![child.clone()],
14761            ..SupervisorSpec::default()
14762        };
14763        match s.validate().unwrap_err() {
14764            SupervisorError::RestartWindowNotCanonical { window } => {
14765                assert_eq!(
14766                    Some(window),
14767                    s.restart_window(),
14768                    "RestartWindowNotCanonical.window must byte-equal \
14769                     SupervisorSpec::restart_window().unwrap() — the \
14770                     non-canonical-arm refusal reads through the lifted \
14771                     accessor",
14772                );
14773                assert_eq!(
14774                    window, sub_ms,
14775                    "RestartWindowNotCanonical.window must carry the \
14776                     author-declared :supervisor :restart-window value \
14777                     verbatim (got {window:?}, expected {sub_ms:?})",
14778                );
14779            }
14780            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
14781        }
14782        // Cap arm — the surfaced `window:` field must byte-equal the
14783        // accessor's return.
14784        let over_cap = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
14785        let s = SupervisorSpec {
14786            restart_window: Some(over_cap),
14787            children: vec![child.clone()],
14788            ..SupervisorSpec::default()
14789        };
14790        match s.validate().unwrap_err() {
14791            SupervisorError::RestartWindowExceedsCap { window } => {
14792                assert_eq!(
14793                    Some(window),
14794                    s.restart_window(),
14795                    "RestartWindowExceedsCap.window must byte-equal \
14796                     SupervisorSpec::restart_window().unwrap() — the \
14797                     cap-arm refusal reads through the lifted accessor",
14798                );
14799                assert_eq!(
14800                    window, over_cap,
14801                    "RestartWindowExceedsCap.window must carry the \
14802                     author-declared :supervisor :restart-window value \
14803                     verbatim (got {window:?}, expected {over_cap:?})",
14804                );
14805            }
14806            other => panic!("expected RestartWindowExceedsCap, got {other:?}"),
14807        }
14808        // Lower + upper accept-set boundaries.
14809        for restart_window in [Duration::from_millis(1), SUPERVISOR_RESTART_WINDOW_MAX] {
14810            let s = SupervisorSpec {
14811                restart_window: Some(restart_window),
14812                children: vec![child.clone()],
14813                ..SupervisorSpec::default()
14814            };
14815            assert!(
14816                s.validate().is_ok(),
14817                "validate must accept restart_window == Some({restart_window:?}) \
14818                 (an accept-set boundary of \
14819                 1ms..=SUPERVISOR_RESTART_WINDOW_MAX)",
14820            );
14821        }
14822    }
14823
14824    #[test]
14825    fn supervisor_spec_restart_window_projects_option_duration_by_copy() {
14826        // The by-copy pin: [`SupervisorSpec::restart_window`] returns
14827        // `Option<Duration>` by copy — `Duration` is `Copy` (so
14828        // `Option<Duration>` is `Copy`) and the accessor must return by
14829        // value, not by reference. Peer of the sibling M2
14830        // [`crate::LimitsSpec::wall_clock`] (8cb717b) by-copy pin on the
14831        // per-`:limits :wall-clock` axis and the sibling M3
14832        // [`crate::MeshPolicy::timeout`] (7073d0f) by-copy pin on the
14833        // per-`:politicas :timeout` axis, extended onto the peer M2
14834        // supervisor-slot `Option<Duration>` copy-invariant shape — the
14835        // accessor's returned `Option<Duration>` must outlive `&self`
14836        // (multiple calls must return equal values from a dropped-`&self`
14837        // copy, since the returned Option carries no borrow), and calling
14838        // the accessor twice on the same SupervisorSpec must yield the
14839        // same `Option<Duration>` verbatim (idempotent, no side effects
14840        // on `&self`).
14841        //
14842        // Pins against a future silent detour that returned
14843        // `Option<&Duration>` (which would type-check but silently break
14844        // every downstream caller — the future wasm-operator's
14845        // per-supervisor restart-intensity counter consumes `Duration` by
14846        // value and `&Duration` would fold to a detached copy at the call
14847        // site), an accidental `Option::as_ref()` projection
14848        // (`self.restart_window.as_ref()` would also type-check but
14849        // return `Option<&Duration>`), or a one-arm-only accessor that
14850        // reads `Some(*w)` in the Some arm but reads a fresh
14851        // `Default::default()` (which would collapse to `Duration::ZERO`,
14852        // not `None`) in the None arm — a footgun the
14853        // [`SupervisorError::RestartWindowZero`] validate arm explicitly
14854        // closes since Erlang/OTP's `MaxIntensity / Period` invariant
14855        // requires `Period > 0` and `None` structurally expresses "never
14856        // reset" instead.
14857        for restart_window in [
14858            None,
14859            Some(Duration::from_millis(1)),
14860            Some(Duration::from_secs(60)),
14861            Some(SUPERVISOR_RESTART_WINDOW_MAX),
14862        ] {
14863            let s = SupervisorSpec {
14864                restart_window,
14865                ..SupervisorSpec::default()
14866            };
14867            let first = s.restart_window();
14868            let second = s.restart_window();
14869            assert_eq!(
14870                first, second,
14871                "SupervisorSpec::restart_window must be idempotent — two \
14872                 successive calls on the same &self must return the \
14873                 same Option<Duration>",
14874            );
14875            assert_eq!(
14876                first, restart_window,
14877                "SupervisorSpec::restart_window must return :supervisor \
14878                 :restart-window verbatim by copy — got {first:?}, \
14879                 expected {restart_window:?}",
14880            );
14881        }
14882    }
14883
14884    // ── per-`:supervisor` `:children` typed-accessor coherence pins ─────────
14885    //
14886    // The [`SupervisorSpec::children`] accessor lift is the seed of the
14887    // slice-return (`&[T]`) accessor discipline on the substrate — the four
14888    // peer `Vec`-carry axes ([`crate::Placement::clusters`],
14889    // [`crate::AplicacaoSpec::membros`], [`crate::AplicacaoSpec::contratos`],
14890    // [`crate::UpgradeFromEntry::instructions`]) still key off the raw field
14891    // access at the time of this seed, and inherit this pin family's
14892    // discipline as future compounding runs migrate their consumers. The
14893    // three pins below cover (1) the accessor's byte-equal projection
14894    // against the raw field access across the empty / singleton / cohort
14895    // fixtures the [`SupervisorSpec::validate`] partition-dispatch fans
14896    // between, (2) the [`SupervisorSpec::validate`] `SimpleOneForOne ↔
14897    // non-SimpleOneForOne` partition dispatch's paired `.is_empty()`
14898    // consumer routing through the accessor on both arms, and (3) the
14899    // per-child validate loop's traversal reading the same slice-view the
14900    // accessor projects. Peer of the sibling M2
14901    // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
14902    // two-consumer coherence pin on the per-`:supervisor`
14903    // sibling-restart-strategy `Copy`-composite-enum scalar axis, extended
14904    // onto the per-`:supervisor` static-child-list `Vec`-carry axis.
14905
14906    #[test]
14907    fn supervisor_spec_children_returns_children_slice_byte_equal_across_permutations() {
14908        // The canonical per-`:supervisor` static-child-list scalar-shape
14909        // pin: [`SupervisorSpec::children`] must return the `:supervisor
14910        // :children` typed `Vec<ChildSpec>` verbatim as a `&[ChildSpec]`
14911        // slice-view over the same backing buffer the raw
14912        // `self.children.as_slice()` field access borrows from, byte-
14913        // equal across every representative fixture in the accept-set —
14914        // the empty slice (the `SimpleOneForOne`-arm sentinel),
14915        // the singleton slice (the minimal non-`SimpleOneForOne` shape),
14916        // and a two-child cohort (a peer non-`SimpleOneForOne` shape
14917        // with the peer three restart-policy variants in play).
14918        //
14919        // Pins against a future silent detour that returned
14920        // `&Vec<ChildSpec>` (which would type-check but leak the
14921        // storage-side `Vec`'s grow/push/reserve surface no consumer of
14922        // the typed view reaches for), a fresh-allocated
14923        // `Vec<ChildSpec>` copy (which would type-check via a coercion
14924        // but silently break every downstream caller that relied on the
14925        // slice sharing the backing buffer's identity), or an
14926        // out-of-order or length-drifted projection (which would silently
14927        // split the per-child validate loop's traversal input from the
14928        // paired partition-dispatch `.is_empty()` probe's input).
14929        //
14930        // Peer of the sibling
14931        // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
14932        // (eafb619) `Copy`-composite-enum byte-equal pin on the
14933        // per-`:supervisor` sibling-restart-strategy axis, extended onto
14934        // the per-`:supervisor` static-child-list `Vec`-carry axis.
14935        let fixtures: Vec<Vec<ChildSpec>> = vec![
14936            Vec::new(),
14937            vec![child("worker", "^0.1", RestartPolicy::Permanent)],
14938            vec![
14939                child("worker", "^0.1", RestartPolicy::Permanent),
14940                child("cache-server", "^0.1", RestartPolicy::Transient),
14941            ],
14942            vec![
14943                child("worker", "^0.1", RestartPolicy::Permanent),
14944                child("cache-server", "^0.1", RestartPolicy::Transient),
14945                child("scratch-job", "^0.1", RestartPolicy::Temporary),
14946            ],
14947        ];
14948        for children in fixtures {
14949            let s = SupervisorSpec {
14950                children: children.clone(),
14951                ..SupervisorSpec::default()
14952            };
14953            assert_eq!(
14954                s.children(),
14955                children.as_slice(),
14956                "SupervisorSpec::children must return :supervisor \
14957                 :children verbatim (got {:?}, expected {:?})",
14958                s.children(),
14959                children.as_slice(),
14960            );
14961            assert_eq!(
14962                s.children(),
14963                s.children.as_slice(),
14964                "SupervisorSpec::children accessor and \
14965                 .children.as_slice() field access must byte-equal — \
14966                 the accessor is the substrate-primitive typed \
14967                 dispatch every downstream static-child-list consumer \
14968                 must route through",
14969            );
14970            assert_eq!(
14971                s.children().len(),
14972                s.children.len(),
14973                "SupervisorSpec::children().len() must byte-equal \
14974                 self.children.len() — a length-drift would silently \
14975                 split the paired partition-dispatch `.is_empty()` \
14976                 probe input from the per-child validate loop's \
14977                 traversal input",
14978            );
14979        }
14980    }
14981
14982    #[test]
14983    fn validate_reads_through_lifted_children_accessor() {
14984        // Three-consumer coherence pin: the [`SupervisorSpec::validate`]
14985        // `SimpleOneForOne`-arm `!self.children().is_empty()` refusal
14986        // probe (which must trip [`SupervisorError::SimpleOneForOneWithStaticChildren`]
14987        // when the accessor projects a non-empty slice under a
14988        // `SimpleOneForOne` estrategia), the peer non-`SimpleOneForOne`-arm
14989        // `self.children().is_empty()` refusal probe (which must trip
14990        // [`SupervisorError::NoChildren`] when the accessor projects the
14991        // empty slice under any peer estrategia), and the per-child
14992        // validate loop's `for child in self.children()` traversal
14993        // (which must reach every entry in the same order the accessor
14994        // projects) must all key off the lifted accessor, so any future
14995        // rebrand on the typed slot's reader shape lands at exactly one
14996        // place. Pins the three-site coherence by exercising each
14997        // production consumer end-to-end: (1) the
14998        // `SimpleOneForOneWithStaticChildren` refusal under a non-empty
14999        // slice + `SimpleOneForOne` estrategia, (2) the `NoChildren`
15000        // refusal under the empty slice + non-`SimpleOneForOne`
15001        // estrategia across every peer variant, and (3) the per-child
15002        // duplicate-detection surface fires on the second entry of a
15003        // two-child cohort that shares a `:caixa` name (which requires
15004        // the loop to reach both entries — a first-entry-only projection
15005        // would silently pass since the dedup HashSet has room for the
15006        // first insert).
15007        //
15008        // Peer of the sibling M2
15009        // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
15010        // two-consumer coherence pin on the per-`:supervisor`
15011        // sibling-restart-strategy axis, extended onto the
15012        // per-`:supervisor` static-child-list `Vec`-carry axis.
15013
15014        // (1) `SimpleOneForOne`-arm probe: a non-empty slice under a
15015        // `SimpleOneForOne` estrategia must trip
15016        // `SimpleOneForOneWithStaticChildren`.
15017        let s = SupervisorSpec {
15018            estrategia: RestartStrategy::SimpleOneForOne,
15019            children: vec![child("worker", "^0.1", RestartPolicy::Permanent)],
15020            ..SupervisorSpec::default()
15021        };
15022        assert_eq!(
15023            s.validate().unwrap_err(),
15024            SupervisorError::SimpleOneForOneWithStaticChildren,
15025            "SimpleOneForOne + non-empty children must trip \
15026             SimpleOneForOneWithStaticChildren — the accessor projects \
15027             a non-empty slice, and the SimpleOneForOne-arm refusal \
15028             probe reads through the lifted accessor",
15029        );
15030        assert!(
15031            !s.children().is_empty(),
15032            "the SimpleOneForOne-arm refusal input must be a non-empty \
15033             slice per the accessor's projection",
15034        );
15035
15036        // (2) Peer non-`SimpleOneForOne`-arm probe: the empty slice
15037        // under any peer estrategia must trip `NoChildren`.
15038        for estrategia in [
15039            RestartStrategy::OneForOne,
15040            RestartStrategy::OneForAll,
15041            RestartStrategy::RestForOne,
15042        ] {
15043            let s = SupervisorSpec {
15044                estrategia,
15045                children: Vec::new(),
15046                ..SupervisorSpec::default()
15047            };
15048            match s.validate().unwrap_err() {
15049                SupervisorError::NoChildren { estrategia: e } => {
15050                    assert_eq!(
15051                        e, estrategia,
15052                        "NoChildren.estrategia must carry the author-\
15053                         declared :supervisor :estrategia variant \
15054                         verbatim (got {e:?}, expected {estrategia:?})",
15055                    );
15056                }
15057                other => panic!(
15058                    "expected NoChildren, got {other:?} for \
15059                     estrategia={estrategia:?}"
15060                ),
15061            }
15062            assert!(
15063                s.children().is_empty(),
15064                "the non-SimpleOneForOne-arm refusal input must be the \
15065                 empty slice per the accessor's projection",
15066            );
15067        }
15068
15069        // (3) Per-child validate loop: a two-child cohort that shares a
15070        // `:caixa` name must trip `DuplicateChildCaixa` — the loop must
15071        // reach both entries through the accessor.
15072        let s = SupervisorSpec {
15073            estrategia: RestartStrategy::OneForOne,
15074            children: vec![
15075                child("worker", "^0.1", RestartPolicy::Permanent),
15076                child("worker", "^0.2", RestartPolicy::Transient),
15077            ],
15078            ..SupervisorSpec::default()
15079        };
15080        match s.validate().unwrap_err() {
15081            SupervisorError::DuplicateChildCaixa { caixa } => {
15082                assert_eq!(
15083                    caixa, "worker",
15084                    "DuplicateChildCaixa.caixa must carry the shared \
15085                     child `:caixa` name verbatim",
15086                );
15087            }
15088            other => panic!("expected DuplicateChildCaixa, got {other:?}"),
15089        }
15090        assert_eq!(
15091            s.children().len(),
15092            2,
15093            "the per-child validate loop's traversal input must be a \
15094             two-element slice per the accessor's projection",
15095        );
15096    }
15097
15098    // Shared helper for the M2 per-`:children` per-slot-gate ≡
15099    // `validate` equivalence pins: builds an `OneForOne`-estrategia
15100    // one-cohort spec whose peer `:estrategia`↔`:children.is_empty()`
15101    // partition, `:max-restarts` zero-floor/cap, and `:restart-window`
15102    // bracket all pass cleanly so the sole failing surface is the
15103    // per-child cascade [`SupervisorSpec::validate_children`] owns, and
15104    // pins the two-altitude equivalence on the paired probe.
15105    fn assert_validate_children_matches_gate(children: Vec<ChildSpec>, expected: &SupervisorError) {
15106        let s = SupervisorSpec {
15107            estrategia: RestartStrategy::OneForOne,
15108            children,
15109            ..SupervisorSpec::default()
15110        };
15111        let via_gate = s.validate_children().unwrap_err();
15112        let via_validate = s.validate().unwrap_err();
15113        assert_eq!(&via_gate, expected, "validate_children direct dispatch",);
15114        assert_eq!(&via_validate, expected, "validate() end-to-end dispatch",);
15115        assert_eq!(
15116            via_gate, via_validate,
15117            "per-slot gate ≡ validate() must discriminate the same \
15118             refusal shape",
15119        );
15120    }
15121
15122    #[test]
15123    fn validate_children_matches_gate_on_per_axis_refusal_shapes() {
15124        // Fail-before-pass-after equivalence pin on the M2
15125        // per-`:children` per-slot gate ≡ [`SupervisorSpec::validate`]
15126        // convergence — sibling of the M3 mesh-slot
15127        // `validate_membros_*` / `validate_contratos_*` /
15128        // `validate_entrada_*` per-slot-gate ≡ `validate` pins on the
15129        // peer per-entry axes. Sweeps four of the five refusal shapes
15130        // the per-slot gate owns: (1) `EmptyChildName` on an empty-
15131        // `:caixa` child, (2) `ChildCaixaInvalid` on a structurally
15132        // invalid `:caixa` DNS-1123 label, (3) `EmptyChildVersion` on
15133        // an empty-`:versao` child, (4) `DuplicateChildCaixa` on a
15134        // duplicate-`:caixa` fan-out. Companion pin
15135        // `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
15136        // covers `ChildVersaoInvalid` (whose parser-owned reason string
15137        // needs pattern-matching, not equality) and the clean-pass
15138        // canonical fixture; together the two pins guarantee the
15139        // per-slot gate and `validate` discriminate the same set on
15140        // every per-child-covered input.
15141        assert_validate_children_matches_gate(
15142            vec![child("", "^0.1", RestartPolicy::Permanent)],
15143            &SupervisorError::EmptyChildName,
15144        );
15145        assert_validate_children_matches_gate(
15146            vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
15147            &SupervisorError::ChildCaixaInvalid {
15148                caixa: "Worker".into(),
15149                reason: "contains uppercase character 'W' (K8s DNS-1123 label names are lowercase-only; use \"worker\")".into(),
15150            },
15151        );
15152        assert_validate_children_matches_gate(
15153            vec![child("worker", "", RestartPolicy::Permanent)],
15154            &SupervisorError::EmptyChildVersion {
15155                caixa: "worker".into(),
15156            },
15157        );
15158        assert_validate_children_matches_gate(
15159            vec![
15160                child("worker", "^0.1", RestartPolicy::Permanent),
15161                child("worker", "^0.2", RestartPolicy::Transient),
15162            ],
15163            &SupervisorError::DuplicateChildCaixa {
15164                caixa: "worker".into(),
15165            },
15166        );
15167    }
15168
15169    #[test]
15170    fn validate_children_matches_gate_on_versao_invalid_and_clean_pass() {
15171        // Second half of the two-altitude equivalence pin — covers the
15172        // one refusal shape whose reason string is parser-owned
15173        // (`ChildVersaoInvalid`, whose reason comes from the shared
15174        // [`crate::version::parse_requirement`] impl and may drift) and
15175        // the clean-pass canonical fixture. Sibling pin
15176        // `validate_children_matches_gate_on_per_axis_refusal_shapes`
15177        // covers the four equality-comparable refusal shapes.
15178        let s_bad_versao = SupervisorSpec {
15179            estrategia: RestartStrategy::OneForOne,
15180            children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
15181            ..SupervisorSpec::default()
15182        };
15183        let via_gate = s_bad_versao.validate_children().unwrap_err();
15184        let via_validate = s_bad_versao.validate().unwrap_err();
15185        match (&via_gate, &via_validate) {
15186            (
15187                SupervisorError::ChildVersaoInvalid {
15188                    caixa: cg,
15189                    versao: vg,
15190                    ..
15191                },
15192                SupervisorError::ChildVersaoInvalid {
15193                    caixa: cv,
15194                    versao: vv,
15195                    ..
15196                },
15197            ) => {
15198                assert_eq!(cg, "worker", "per-slot gate :caixa carrier");
15199                assert_eq!(vg, "not-a-req", "per-slot gate :versao carrier");
15200                assert_eq!(cv, "worker", "validate() :caixa carrier");
15201                assert_eq!(vv, "not-a-req", "validate() :versao carrier");
15202            }
15203            other => panic!("expected ChildVersaoInvalid on both altitudes, got {other:?}"),
15204        }
15205        assert_eq!(
15206            via_gate, via_validate,
15207            "per-slot gate ≡ validate() on ChildVersaoInvalid full envelope",
15208        );
15209
15210        let s_ok = SupervisorSpec {
15211            estrategia: RestartStrategy::OneForOne,
15212            children: vec![
15213                child("worker-a", "^0.1", RestartPolicy::Permanent),
15214                child("worker-b", "~0.2.3", RestartPolicy::Transient),
15215                child("collector", "*", RestartPolicy::Temporary),
15216            ],
15217            ..SupervisorSpec::default()
15218        };
15219        s_ok.validate_children()
15220            .expect("per-slot gate must accept the clean-pass fixture");
15221        s_ok.validate()
15222            .expect("validate() must accept the clean-pass fixture");
15223    }
15224
15225    #[test]
15226    fn validate_children_is_self_contained_on_children_slot() {
15227        // Self-containment pin: [`SupervisorSpec::validate_children`]
15228        // resolves the per-child cascade against `&self` alone, without
15229        // depending on the peer `:estrategia`/`:max-restarts`/
15230        // `:restart-window` gates having run first — same posture the M3
15231        // peer per-slot gates carry (`validate_membros`,
15232        // `validate_contratos`, `validate_entrada`, `validate_placement`,
15233        // routing through their own oracles rather than borrowing state
15234        // threaded down from `validate`). A future consumer that reaches
15235        // the per-slot gate directly on a spec whose peer slots would
15236        // fail `validate` still surfaces the per-child refusal, not the
15237        // peer refusal.
15238        //
15239        // Construct a spec whose `:max-restarts` is `0` (which would
15240        // trip [`SupervisorError::ZeroMaxRestarts`] at `validate` after
15241        // the partition-dispatch) and whose `:children` carries a
15242        // `DuplicateChildCaixa` shape: the per-slot gate called directly
15243        // must surface `DuplicateChildCaixa`, proving it does not depend
15244        // on the peer `:max-restarts` gate running first.
15245        let s = SupervisorSpec {
15246            estrategia: RestartStrategy::OneForOne,
15247            max_restarts: 0,
15248            restart_window: Some(Duration::from_secs(60)),
15249            children: vec![
15250                child("worker", "^0.1", RestartPolicy::Permanent),
15251                child("worker", "^0.2", RestartPolicy::Transient),
15252            ],
15253        };
15254        assert_eq!(
15255            s.validate_children().unwrap_err(),
15256            SupervisorError::DuplicateChildCaixa {
15257                caixa: "worker".into(),
15258            },
15259            "per-slot gate must resolve per-child refusal directly against \
15260             `&self` — a dependency on the peer `:max-restarts` gate \
15261             running first would surface ZeroMaxRestarts here instead",
15262        );
15263        // The peer gate is still the surface `validate` reaches — pin
15264        // the ordering to establish that `validate_children` truly runs
15265        // last in `validate`'s dispatch, so a direct call bypasses the
15266        // peer gates on any spec whose per-child cascade would fail.
15267        assert_eq!(
15268            s.validate().unwrap_err(),
15269            SupervisorError::ZeroMaxRestarts,
15270            "validate() must surface the peer `:max-restarts` gate before \
15271             reaching the per-child cascade — this pins the dispatch \
15272             ordering the per-slot gate's self-containment complements",
15273        );
15274    }
15275
15276    #[test]
15277    fn child_spec_restart_accessor_is_const_fn() {
15278        // The [`ChildSpec::restart`] per-`:children` restart-decision-
15279        // policy `Copy`-return scalar accessor is declared
15280        // `#[must_use] pub const fn` — matching the sibling M2
15281        // per-`:supervisor` [`SupervisorSpec::estrategia`] (pinned by
15282        // [`supervisor_spec_estrategia_accessor_is_const_fn`] below,
15283        // both converted in this commit), the sibling M2
15284        // per-`:supervisor` [`SupervisorSpec::max_restarts`] (b698ec0)
15285        // `Copy`-`u32` accessor already `pub const fn`, and the peer M3
15286        // mesh-slot per-`:entrada` [`crate::Entrada::port`] (bafa004) /
15287        // per-`:placement` [`crate::Placement::estrategia`] (bafa004)
15288        // `Copy`-return `pub const fn` scalar accessors on the sibling
15289        // M3 surface. Pin the `const`-eval posture here so a future
15290        // accidental downgrade to non-`const` (an added runtime helper
15291        // reachable only from a non-`const` context, an
15292        // `Option<RestartPolicy>`-shape migration on the per-child
15293        // restart-decision axis once heterogeneous per-cluster
15294        // restart-policy overlays land that would silently drop the
15295        // `const` qualifier, a manual hand-rolled shadow) trips at
15296        // caixa-core build time rather than surfacing as a downstream
15297        // `const`-context regression far from the declaration.
15298        //
15299        // Same shape as the sibling M3
15300        // [`crate::aplicacao::tests::placement_estrategia_accessor_is_const_fn`]
15301        // and [`crate::aplicacao::tests::entrada_port_accessor_is_const_fn`]
15302        // (bafa004) pins on the peer M3 mesh-slot `Copy`-return scalar
15303        // accessor axis — the load-bearing witness lives in the
15304        // module-scope `const fn` wrapper `restart_via_const_fn` below:
15305        // a body that calls [`ChildSpec::restart`] under a `const fn`
15306        // signature is well-formed only when the callee is itself
15307        // `const fn`, so any future accidental downgrade of
15308        // [`ChildSpec::restart`] to non-`const` fails at caixa-core
15309        // build time (const-eval E0015 `cannot call non-const method`),
15310        // strictly stronger than a runtime `assert!(CONST)` and
15311        // side-stepping the destructor-in-const restriction that
15312        // blocks direct `const _: RestartPolicy = FIXTURE.restart()`
15313        // items on `ChildSpec`'s `String` carriers.
15314        //
15315        // The runtime body sweeps every closed-set [`RestartPolicy`]
15316        // arm and asserts the wrapped and direct dispatches agree.
15317        const fn restart_via_const_fn(c: &ChildSpec) -> RestartPolicy {
15318            c.restart()
15319        }
15320        for restart in [
15321            RestartPolicy::Permanent,
15322            RestartPolicy::Transient,
15323            RestartPolicy::Temporary,
15324        ] {
15325            let c = ChildSpec {
15326                caixa: "worker".into(),
15327                versao: "^0.1".into(),
15328                restart,
15329            };
15330            assert_eq!(
15331                restart_via_const_fn(&c),
15332                c.restart(),
15333                "const-fn-wrapped and direct dispatch on \
15334                 ChildSpec::restart must agree for {restart:?}",
15335            );
15336            assert_eq!(
15337                c.restart(),
15338                restart,
15339                "ChildSpec::restart must return the storage-side \
15340                 RestartPolicy verbatim for {restart:?} (a violation \
15341                 means the accessor stopped being a raw field-return \
15342                 copy)",
15343            );
15344        }
15345    }
15346
15347    #[test]
15348    fn supervisor_spec_estrategia_accessor_is_const_fn() {
15349        // The [`SupervisorSpec::estrategia`] per-`:supervisor`
15350        // sibling-restart-strategy `Copy`-return scalar accessor is
15351        // declared `#[must_use] pub const fn` — matching the sibling M2
15352        // per-`:children` [`ChildSpec::restart`] (pinned by
15353        // [`child_spec_restart_accessor_is_const_fn`] above, both
15354        // converted in this commit), the sibling M2 per-`:supervisor`
15355        // [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32`
15356        // accessor already `pub const fn`, and mirroring the peer M3
15357        // mesh-slot per-`:placement`
15358        // [`crate::Placement::estrategia`] (bafa004) `Copy`-return
15359        // `pub const fn` scalar accessor whose method-name discipline
15360        // the [`SupervisorSpec::estrategia`] method was authored to
15361        // match. Pin the `const`-eval posture here so a future
15362        // accidental downgrade to non-`const` (an added runtime helper
15363        // reachable only from a non-`const` context, an
15364        // `Option<RestartStrategy>`-shape migration once the substrate
15365        // grows per-cluster strategy overlays that would silently drop
15366        // the `const` qualifier, a manual hand-rolled shadow) trips at
15367        // caixa-core build time rather than surfacing as a downstream
15368        // `const`-context regression far from the declaration.
15369        //
15370        // Same shape as the sibling
15371        // [`child_spec_restart_accessor_is_const_fn`] pin above — the
15372        // load-bearing witness lives in the module-scope `const fn`
15373        // wrapper `estrategia_via_const_fn` below: a body that calls
15374        // [`SupervisorSpec::estrategia`] under a `const fn` signature
15375        // is well-formed only when the callee is itself `const fn`,
15376        // side-stepping the destructor-in-const restriction that would
15377        // otherwise block a direct
15378        // `const _: RestartStrategy = FIXTURE.estrategia()` item on
15379        // `SupervisorSpec`'s `Vec<ChildSpec>` / `Option<Duration>`
15380        // carriers.
15381        //
15382        // The runtime body sweeps every closed-set [`RestartStrategy`]
15383        // arm via [`RestartStrategy::ALL`] and asserts the wrapped and
15384        // direct dispatches agree.
15385        const fn estrategia_via_const_fn(s: &SupervisorSpec) -> RestartStrategy {
15386            s.estrategia()
15387        }
15388        for &estrategia in RestartStrategy::ALL {
15389            let s = SupervisorSpec {
15390                estrategia,
15391                max_restarts: 5,
15392                restart_window: Some(Duration::from_secs(60)),
15393                children: Vec::new(),
15394            };
15395            assert_eq!(
15396                estrategia_via_const_fn(&s),
15397                s.estrategia(),
15398                "const-fn-wrapped and direct dispatch on \
15399                 SupervisorSpec::estrategia must agree for {estrategia:?}",
15400            );
15401            assert_eq!(
15402                s.estrategia(),
15403                estrategia,
15404                "SupervisorSpec::estrategia must return the storage-side \
15405                 RestartStrategy verbatim for {estrategia:?} (a violation \
15406                 means the accessor stopped being a raw field-return \
15407                 copy)",
15408            );
15409        }
15410    }
15411
15412    // Per-variant equivalence pins for the [`supervisor_caixa_only_ctors!`]
15413    // macro definition (see the paired doc-block above the macro
15414    // definition) — every generated `<ctor>(caixa: &str) -> Self`
15415    // constructor folds the uniform `Self::<Variant> { caixa:
15416    // caixa.to_string() }` one-field struct-literal onto one substrate
15417    // primitive. The three per-variant equivalence pins below
15418    // (fail-before-pass-after by construction — a byte-mismatched macro
15419    // arm would trip its equivalence pin first) lock each generated
15420    // constructor to its struct-literal peer under `PartialEq`, so
15421    // every wire-up in [`SupervisorSpec::validate_children`] and
15422    // [`validate_no_self_supervision`] on that variant produces a
15423    // byte-equal `SupervisorError` to the pre-lift open-coded
15424    // struct-literal. The cross-axis pin that follows (non-default
15425    // caixa name) routes the sole constructor input axis through
15426    // `.to_string()`, so the fold does not silently collapse onto a
15427    // fixed name.
15428    //
15429    // Peer of the sibling `<slot>_ctor_matches_tuple_literal_wrap` /
15430    // `<slot>_violation_ctor_matches_struct_literal_wrap` /
15431    // `<slot>_slots_on_non_<owner>_ctor_matches_struct_literal_wrap` /
15432    // `missing_entry_ctor_matches_struct_literal_wrap` /
15433    // `entrada_host_invalid_ctor_matches_struct_literal_wrap` /
15434    // `contrato_wrong_target_ctor_matches_struct_literal_wrap` /
15435    // `contrato_missing_target_ctor_matches_struct_literal_wrap` /
15436    // `<variant>_ctor_matches_struct_literal_wrap` equivalence pins
15437    // on the six sibling ctor families the recent trajectory closed
15438    // on the peer `LayoutError` / `AplicacaoError` envelopes.
15439
15440    #[test]
15441    fn empty_child_version_ctor_matches_struct_literal_wrap() {
15442        assert_eq!(
15443            SupervisorError::empty_child_version("worker"),
15444            SupervisorError::EmptyChildVersion {
15445                caixa: "worker".to_string(),
15446            },
15447            "generated empty_child_version ctor must produce byte-equal \
15448             SupervisorError to the open-coded struct-literal wrap on the \
15449             same &str fixture",
15450        );
15451    }
15452
15453    #[test]
15454    fn duplicate_child_caixa_ctor_matches_struct_literal_wrap() {
15455        assert_eq!(
15456            SupervisorError::duplicate_child_caixa("worker"),
15457            SupervisorError::DuplicateChildCaixa {
15458                caixa: "worker".to_string(),
15459            },
15460            "generated duplicate_child_caixa ctor must produce byte-equal \
15461             SupervisorError to the open-coded struct-literal wrap on the \
15462             same &str fixture",
15463        );
15464    }
15465
15466    #[test]
15467    fn child_supervises_self_ctor_matches_struct_literal_wrap() {
15468        assert_eq!(
15469            SupervisorError::child_supervises_self("orquestra"),
15470            SupervisorError::ChildSupervisesSelf {
15471                caixa: "orquestra".to_string(),
15472            },
15473            "generated child_supervises_self ctor must produce byte-equal \
15474             SupervisorError to the open-coded struct-literal wrap on the \
15475             same &str fixture",
15476        );
15477    }
15478
15479    // Per-variant equivalence pins for the two lifted
15480    // [`SupervisorError::child_caixa_invalid`] /
15481    // [`SupervisorError::child_versao_invalid`] inherent constructors
15482    // (fail-before-pass-after by construction — a byte-mismatched ctor body
15483    // would trip its equivalence pin first). Each pins the ctor output to
15484    // its pre-lift struct-literal peer under `PartialEq`, so every wire-up
15485    // in [`SupervisorSpec::validate_children`] on the two variants
15486    // produces a byte-equal `SupervisorError` to the pre-lift open-coded
15487    // struct-literal on the same scalar fixtures. Peers of the sibling
15488    // `membro_caixa_invalid_ctor_matches_struct_literal_wrap` /
15489    // `entrada_para_invalid_ctor_matches_struct_literal_wrap` / … pins on
15490    // the peer `AplicacaoError` envelope's
15491    // [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold.
15492
15493    #[test]
15494    fn child_caixa_invalid_ctor_matches_struct_literal_wrap() {
15495        let caixa = "Worker";
15496        let reason = "sample reason text";
15497        assert_eq!(
15498            SupervisorError::child_caixa_invalid(caixa, reason),
15499            SupervisorError::ChildCaixaInvalid {
15500                caixa: caixa.to_string(),
15501                reason: reason.to_string(),
15502            },
15503            "lifted child_caixa_invalid ctor must produce byte-equal \
15504             SupervisorError to the open-coded struct-literal wrap on the \
15505             same (&str, reason) fixture",
15506        );
15507    }
15508
15509    #[test]
15510    fn child_versao_invalid_ctor_matches_struct_literal_wrap() {
15511        let caixa = "worker";
15512        let versao = "not-a-req";
15513        let reason = "sample reason text";
15514        assert_eq!(
15515            SupervisorError::child_versao_invalid(caixa, versao, reason),
15516            SupervisorError::ChildVersaoInvalid {
15517                caixa: caixa.to_string(),
15518                versao: versao.to_string(),
15519                reason: reason.to_string(),
15520            },
15521            "lifted child_versao_invalid ctor must produce byte-equal \
15522             SupervisorError to the open-coded struct-literal wrap on the \
15523             same (&str, &str, reason) fixture",
15524        );
15525    }
15526
15527    #[test]
15528    fn supervisor_child_reason_ctors_route_reason_through_into_uniformly() {
15529        // Cross-axis pin: sweep the two lifted `{ …, reason }` ctors
15530        // against a `&str`-literal vs. `format!(…)` reason input to pin
15531        // both constructors accept the `impl Into<String>` bound
15532        // uniformly, so neither wire-up site drifts under a per-arm
15533        // wrapper transformation on the caller-side `reason` axis. Peer
15534        // of the sibling
15535        // `aplicacao_field_reason_ctors_route_reason_through_into_uniformly`
15536        // sweep on the peer `AplicacaoError` envelope.
15537        let via_literal = "literal reason text";
15538        let via_format = format!("{} reason text", "literal");
15539        assert_eq!(
15540            SupervisorError::child_caixa_invalid("Worker", via_literal),
15541            SupervisorError::child_caixa_invalid("Worker", via_format.clone()),
15542        );
15543        assert_eq!(
15544            SupervisorError::child_versao_invalid("worker", "not-a-req", via_literal),
15545            SupervisorError::child_versao_invalid("worker", "not-a-req", via_format),
15546        );
15547    }
15548
15549    #[test]
15550    fn supervisor_caixa_only_ctors_route_caixa_through_to_string() {
15551        // Cross-axis pin: sweep the sole constructor input axis (`caixa:
15552        // &str`) through a non-default fixture name against every
15553        // generated arm in the [`supervisor_caixa_only_ctors!`] macro,
15554        // so any wrapper-side lowercase / trim / truncate / re-order on
15555        // the `caixa.to_string()` sole-field construction surfaces
15556        // here rather than at a downstream diagnostic-shape mismatch.
15557        // Peer of the sibling `nome_only_ctor_routes_caixa_through_
15558        // nome_accessor` / `entrada_host_invalid_ctor_routes_host_
15559        // through_to_string` / `contrato_target_ctors_route_edge_
15560        // triple_through_verbatim` / `contrato_empty_pair_ctors_
15561        // route_edge_pair_through_verbatim` cross-axis routing pins on
15562        // the peer `LayoutError` / `AplicacaoError` envelopes; extended
15563        // here onto the `SupervisorError` `{ caixa: String }` envelope
15564        // so every substrate-primitive ctor family in caixa-core
15565        // guarantees the sole-field construction routes the caller's
15566        // `&str` through `.to_string()` verbatim.
15567        let name = "cache-v2";
15568        assert_eq!(
15569            SupervisorError::empty_child_version(name),
15570            SupervisorError::EmptyChildVersion {
15571                caixa: name.to_string(),
15572            },
15573        );
15574        assert_eq!(
15575            SupervisorError::duplicate_child_caixa(name),
15576            SupervisorError::DuplicateChildCaixa {
15577                caixa: name.to_string(),
15578            },
15579        );
15580        assert_eq!(
15581            SupervisorError::child_supervises_self(name),
15582            SupervisorError::ChildSupervisesSelf {
15583                caixa: name.to_string(),
15584            },
15585        );
15586    }
15587
15588    // ── supervisor_scalar_ctors! per-variant + cross-axis pins ──────────────
15589    //
15590    // Per-variant byte-equality pins guaranteeing every generated ctor arm in
15591    // the [`supervisor_scalar_ctors!`] macro produces a `SupervisorError`
15592    // structurally identical to the pre-lift `Self::<variant> { <field>: <val> }`
15593    // one-line struct-literal on the same `Copy`-`RestartStrategy | u32 |
15594    // Duration` fixture, plus one cross-axis sweep that routes each per-variant
15595    // `<field>: <ty>` scalar through the sole `$field:ident: $ty:ty` axis the
15596    // macro exposes so any wrapper-side truncation / re-order / silent `.into()`
15597    // / silent constant-substitution on any one variant surfaces here rather
15598    // than at a downstream per-`:supervisor` diagnostic-shape drift. Peer of the
15599    // sibling per-variant pins on `aplicacao_policy_scalar_ctors!` (7ef425e,
15600    // the 8-variant `AplicacaoError` `{ <field>: Duration | u32 }` fold on the
15601    // per-`:politicas` per-axis cap / canonical-form arms), plus the sibling
15602    // `supervisor_caixa_only_ctors!` (db09650), `SupervisorError::
15603    // {child_caixa_invalid,child_versao_invalid}` (d2ef2ec), and the peer
15604    // `DepError` / `AplicacaoError` / `LayoutError` / `LimitsError` /
15605    // `BehaviorError` / `UpgradeError` per-envelope ctor-macro pins.
15606    #[test]
15607    fn no_children_ctor_matches_struct_literal_wrap() {
15608        let estrategia = RestartStrategy::OneForAll;
15609        assert_eq!(
15610            SupervisorError::no_children(estrategia),
15611            SupervisorError::NoChildren { estrategia },
15612            "generated no_children ctor must produce byte-equal \
15613             `SupervisorError::NoChildren` to the pre-lift struct-literal wrap \
15614             on the same `Copy`-`RestartStrategy` fixture",
15615        );
15616    }
15617
15618    #[test]
15619    fn max_restarts_exceeds_cap_ctor_matches_struct_literal_wrap() {
15620        let max_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 1;
15621        assert_eq!(
15622            SupervisorError::max_restarts_exceeds_cap(max_restarts),
15623            SupervisorError::MaxRestartsExceedsCap { max_restarts },
15624            "generated max_restarts_exceeds_cap ctor must produce byte-equal \
15625             `SupervisorError::MaxRestartsExceedsCap` to the pre-lift \
15626             struct-literal wrap on the same `Copy`-`u32` fixture",
15627        );
15628    }
15629
15630    #[test]
15631    fn restart_window_not_canonical_ctor_matches_struct_literal_wrap() {
15632        let window = Duration::from_micros(1_500);
15633        assert_eq!(
15634            SupervisorError::restart_window_not_canonical(window),
15635            SupervisorError::RestartWindowNotCanonical { window },
15636            "generated restart_window_not_canonical ctor must produce \
15637             byte-equal `SupervisorError::RestartWindowNotCanonical` to the \
15638             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
15639        );
15640    }
15641
15642    #[test]
15643    fn restart_window_exceeds_cap_ctor_matches_struct_literal_wrap() {
15644        let window = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
15645        assert_eq!(
15646            SupervisorError::restart_window_exceeds_cap(window),
15647            SupervisorError::RestartWindowExceedsCap { window },
15648            "generated restart_window_exceeds_cap ctor must produce \
15649             byte-equal `SupervisorError::RestartWindowExceedsCap` to the \
15650             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
15651        );
15652    }
15653
15654    #[test]
15655    fn supervisor_scalar_ctors_route_field_through_copy_uniformly() {
15656        // Cross-axis routing pin: sweep each generated `<field>: <ty>`
15657        // constructor input axis through a non-default `Copy` fixture against
15658        // every arm in the [`supervisor_scalar_ctors!`] macro, so any wrapper-
15659        // side silent `.into()` / silent constant-substitution / silent field
15660        // re-name away from the canonical `estrategia | max_restarts | window`
15661        // axes on any one variant, or a `RestartStrategy | u32 | Duration`
15662        // axis silently rerouted through some other `Copy` coercion, surfaces
15663        // here rather than at a downstream per-`:supervisor` diagnostic-shape
15664        // drift. Peer of the sibling
15665        // `aplicacao_policy_scalar_ctors_route_field_through_copy_uniformly`
15666        // (7ef425e) cross-axis routing pin on the peer `AplicacaoError`
15667        // envelope's per-`:politicas` per-axis ctor family, extended here onto
15668        // the last M2 per-`:supervisor` `Copy`-scalar `SupervisorError`
15669        // variant family folded onto a substrate primitive.
15670        //
15671        // Fixtures picked out of each variant's accept-set boundary rather
15672        // than the default value so a silent constant-substitution to a per-
15673        // variant sentinel surfaces here on the structural-equality assertion.
15674        // The `RestartStrategy` fixture picks `RestForOne` (a non-default arm
15675        // that isn't the `OneForOne` [`SUPERVISOR_ESTRATEGIA_DEFAULT`] and
15676        // isn't the `SimpleOneForOne` arm the sibling
15677        // `SimpleOneForOneWithStaticChildren` unit variant intercepts). The
15678        // `max_restarts` fixture picks an above-cap magnitude the cap arm
15679        // rejects; the two `Duration` fixtures pick the sub-millisecond and
15680        // above-cap ends of the `:restart-window` canonical-form + cap
15681        // bracket respectively.
15682        let estrategia = RestartStrategy::RestForOne;
15683        let above_cap_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 137;
15684        let sub_ms = Duration::from_micros(1_500);
15685        let above_hour = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
15686        assert_eq!(
15687            SupervisorError::no_children(estrategia),
15688            SupervisorError::NoChildren { estrategia },
15689        );
15690        assert_eq!(
15691            SupervisorError::max_restarts_exceeds_cap(above_cap_restarts),
15692            SupervisorError::MaxRestartsExceedsCap {
15693                max_restarts: above_cap_restarts,
15694            },
15695        );
15696        assert_eq!(
15697            SupervisorError::restart_window_not_canonical(sub_ms),
15698            SupervisorError::RestartWindowNotCanonical { window: sub_ms },
15699        );
15700        assert_eq!(
15701            SupervisorError::restart_window_exceeds_cap(above_hour),
15702            SupervisorError::RestartWindowExceedsCap { window: above_hour },
15703        );
15704    }
15705
15706    #[test]
15707    fn restart_strategy_try_from_bytes_routes_through_from_wire_accessor() {
15708        // Fail-before-pass-after byte-parity pin on the newly lifted
15709        // `impl TryFrom<&[u8]> for RestartStrategy` — asserts the trait-
15710        // idiomatic byte-view reverse-projection standard-library impl
15711        // and the substrate-primitive [`RestartStrategy::from_wire`]
15712        // `Option<Self>` accessor resolve to the same four-arm
15713        // `PascalCase` wire accept-set across every arm the exhaustive
15714        // [`RestartStrategy::ALL`] slice enumerates. Extends the
15715        // substrate-wide trait-idiomatic byte-view reverse-projection
15716        // axis onto the first M2-OTP-shape supervisor-slot closed-set
15717        // fieldless typed enum peer — mirror of the paired
15718        // [`TryFrom<&str> for RestartStrategy`] str-view reverse-
15719        // projection axis on the same enum, and the byte-view companion
15720        // of the pre-existing byte-owned reverse-projection family
15721        // ([`AsRef<[u8]>`], [`From<RestartStrategy> for Vec<u8>`],
15722        // [`From<&RestartStrategy> for Vec<u8>`]) on this same enum.
15723        // Peer of the sibling
15724        // [`crate::kind::tests::caixa_kind_try_from_bytes_routes_through_from_wire_accessor`]
15725        // (18d1940),
15726        // [`crate::dialeto::tests::caixa_dialeto_try_from_bytes_routes_through_from_wire_accessor`]
15727        // (d102cb8), and
15728        // [`crate::dep::tests::dep_list_try_from_bytes_routes_through_from_wire_accessor`]
15729        // (b8f25d5) — tracks the "route through `from_wire` via
15730        // `std::str::from_utf8`" discipline the first-mover established.
15731        //
15732        // Rust's standard library carries no blanket
15733        // `impl<T: for<'a> TryFrom<&'a str>> TryFrom<&[u8]> for T`, so
15734        // a two-hop composition through [`std::str::from_utf8`] + the
15735        // paired [`TryFrom<&str>`] axis is reachable through the pre-
15736        // existing str-view reverse-projection axis alone. But that
15737        // two-hop shape has no compile-time link back to the byte-view
15738        // reverse-projection axis, forces every downstream
15739        // `<T: for<'a> TryFrom<&'a [u8]>>`-bound consumer to open-code
15740        // the composition at every call site, and admits a silent split
15741        // whenever a future call site takes a sibling byte-projection
15742        // axis whose parse arm-set carries no compile-time byte-view
15743        // surface. This impl closes the byte-view reverse-projection
15744        // axis at the substrate-primitive [`RestartStrategy::from_wire`]
15745        // accessor so every future `<T: for<'a> TryFrom<&'a [u8]>>`-
15746        // bound consumer reaches the same four-arm `PascalCase` wire
15747        // accept-set through one trait dispatch.
15748        for &variant in RestartStrategy::ALL {
15749            let wire_bytes: &[u8] = variant.as_str().as_bytes();
15750            assert_eq!(
15751                <RestartStrategy as TryFrom<&[u8]>>::try_from(wire_bytes),
15752                Ok(variant),
15753                "TryFrom<&[u8]> impl on RestartStrategy must round-trip \
15754                 RestartStrategy::{variant:?}.as_str().as_bytes() back to \
15755                 Ok(RestartStrategy::{variant:?}) — divergence from \
15756                 RestartStrategy::from_wire signals a silent detour off \
15757                 the substrate-primitive accessor"
15758            );
15759            assert_eq!(
15760                <RestartStrategy as TryFrom<&[u8]>>::try_from(wire_bytes).ok(),
15761                RestartStrategy::from_wire(variant.as_str()),
15762                "TryFrom<&[u8]> ok()-projection on \
15763                 RestartStrategy::{variant:?}.as_str().as_bytes() must \
15764                 byte-equal RestartStrategy::from_wire on the paired \
15765                 &str input"
15766            );
15767            // Cross-axis witness: the byte-view reverse-projection axis
15768            // must agree with the paired str-view reverse-projection
15769            // axis ([`TryFrom<&str>`]) on every accepted arm — the two
15770            // reverse paths share one `PascalCase` accept-set through
15771            // the substrate-primitive `from_wire` accessor.
15772            let via_str: Result<RestartStrategy, ()> =
15773                <RestartStrategy as TryFrom<&str>>::try_from(variant.as_str());
15774            let via_bytes: Result<RestartStrategy, ()> =
15775                <RestartStrategy as TryFrom<&[u8]>>::try_from(wire_bytes);
15776            assert_eq!(
15777                via_bytes, via_str,
15778                "TryFrom<&[u8]> and TryFrom<&str> reverse-projection \
15779                 axes on RestartStrategy must agree on \
15780                 RestartStrategy::{variant:?} — divergence signals the \
15781                 byte-view and str-view reverse paths have drifted off \
15782                 the same substrate-primitive from_wire accessor"
15783            );
15784            // Forward/reverse byte-view cross-axis witness: feed the
15785            // paired [`AsRef<[u8]>`] byte-tail back through the new
15786            // impl and assert it round-trips to the originating arm.
15787            let via_asref: &[u8] = <RestartStrategy as AsRef<[u8]>>::as_ref(&variant);
15788            assert_eq!(
15789                <RestartStrategy as TryFrom<&[u8]>>::try_from(via_asref),
15790                Ok(variant),
15791                "TryFrom<&[u8]> ∘ AsRef<[u8]> must round-trip \
15792                 RestartStrategy::{variant:?} — divergence signals the \
15793                 forward and reverse byte-view axes have drifted off \
15794                 the same substrate-primitive as_str/from_wire pair"
15795            );
15796        }
15797    }
15798
15799    #[test]
15800    fn restart_strategy_try_from_bytes_rejects_unknown_and_non_utf8_bytes() {
15801        // Rejection witness on the `impl TryFrom<&[u8]> for
15802        // RestartStrategy` — sweeps two rejection paths the byte-view
15803        // reverse-projection axis collapses onto the single unit-error
15804        // `Err(())` return: the invalid-UTF-8 rejection path
15805        // ([`std::str::from_utf8`] returns `Err` before
15806        // [`RestartStrategy::from_wire`] runs) and the valid-UTF-8-but-
15807        // unknown-wire rejection path ([`RestartStrategy::from_wire`]
15808        // returns `None` on a byte-string outside the four-arm
15809        // `PascalCase` accept-set). Both must reject, so a future
15810        // accidental widening of the trait impl's accept-set (a case-
15811        // fold path, a silent acceptance of the kebab-case dispatcher-
15812        // catalog byte-strings on this axis — which would collide the
15813        // two-axis wire/catalog split the sibling
15814        // [`RestartStrategy::from_wire`] doc block makes load-bearing —
15815        // a `#[serde(rename_all = "…")]` attribute drift that widens
15816        // the parse arm-set silently, a stray fallback that maps
15817        // invalid UTF-8 onto a default arm rather than the trait-
15818        // idiomatic `Err(())`) trips at caixa-core test time. Peer of
15819        // the sibling
15820        // [`crate::kind::tests::caixa_kind_try_from_bytes_rejects_unknown_and_non_utf8_bytes`]
15821        // (18d1940),
15822        // [`crate::dialeto::tests::caixa_dialeto_try_from_bytes_rejects_unknown_and_non_utf8_bytes`]
15823        // (d102cb8), and
15824        // [`crate::dep::tests::dep_list_try_from_bytes_rejects_unknown_and_non_utf8_bytes`]
15825        // (b8f25d5) rejection witnesses.
15826        //
15827        // Non-UTF-8 candidates:
15828        //   - a lone 0xFF byte (never valid as a UTF-8 leading byte)
15829        //   - a lone 0x80 continuation byte with no leading byte
15830        //   - a truncated multi-byte sequence (0xC3 without its continuation)
15831        //   - a UTF-16 BOM-style byte pair the UTF-8 validator rejects
15832        //   - a UTF-16 surrogate half rejected by UTF-8
15833        let non_utf8_rejected: &[&[u8]] = &[
15834            &[0xFF],
15835            &[0x80],
15836            &[0xC3],
15837            &[0xFF, 0xFE],
15838            &[0xED, 0xA0, 0x80],
15839        ];
15840        for &input in non_utf8_rejected {
15841            assert_eq!(
15842                <RestartStrategy as TryFrom<&[u8]>>::try_from(input),
15843                Err(()),
15844                "TryFrom<&[u8]> impl on RestartStrategy must reject the \
15845                 non-UTF-8 byte-sequence {input:?} with Err(()) — \
15846                 silent acceptance signals the UTF-8 validation path \
15847                 collapsed onto a default arm rather than the trait-\
15848                 idiomatic unit-error"
15849            );
15850        }
15851        // Valid-UTF-8-but-unknown-wire candidates mirror the corpus
15852        // the sibling `restart_strategy_try_from_str_rejects_unknown_byte_strings`
15853        // (5b828ed) str-view rejection witness already pins on the
15854        // paired [`TryFrom<&str>`] axis: the empty byte-string,
15855        // whitespace-only padding, the kebab-case dispatcher-catalog
15856        // byte-strings on the sibling axis the pre-existing
15857        // [`std::str::FromStr`] impl the [`gen_platform::FromStrKind`]
15858        // derive installs parses onto (a caller who confuses the two
15859        // axes trips here rather than at a downstream K8s-CR round-
15860        // trip miss), lowercase / uppercase / mixed-case folds of each
15861        // `PascalCase` arm, whitespace-padded / trailing-newline /
15862        // quote-wrapped forms, and plausible-but-wrong English rebrand
15863        // candidates.
15864        let unknown_wire_rejected: &[&[u8]] = &[
15865            b"",
15866            b" ",
15867            b"\n",
15868            b"\t",
15869            b"one-for-one",
15870            b"one-for-all",
15871            b"rest-for-one",
15872            b"simple-one-for-one",
15873            b"oneforone",
15874            b"one_for_one",
15875            b"OneForOnes",
15876            b"ONEFORONE",
15877            b"oneforall",
15878            b"restforone",
15879            b"simpleoneforone",
15880            b"OneForOne ",
15881            b" OneForOne",
15882            b" OneForAll ",
15883            b"OneForOne\n",
15884            b"RestForOne\t",
15885            b"OneForEach",
15886            b"AllForOne",
15887            b"one for one",
15888            b"\"OneForOne\"",
15889            b"?",
15890        ];
15891        for &input in unknown_wire_rejected {
15892            assert_eq!(
15893                <RestartStrategy as TryFrom<&[u8]>>::try_from(input),
15894                Err(()),
15895                "TryFrom<&[u8]> impl on RestartStrategy must reject the \
15896                 valid-UTF-8-but-unknown-wire byte-string {input:?} \
15897                 with Err(()) — silent acceptance signals an accept-\
15898                 set widening off the paired RestartStrategy::from_wire \
15899                 resolver"
15900            );
15901            // Cross-axis witness: on a byte-string that is valid UTF-8,
15902            // the byte-view reverse-projection axis must agree with the
15903            // paired str-view reverse-projection axis
15904            // ([`TryFrom<&str>`]) — both route through the same
15905            // [`RestartStrategy::from_wire`] resolver, so the two
15906            // rejection paths align by construction.
15907            if let Ok(s) = std::str::from_utf8(input) {
15908                assert_eq!(
15909                    <RestartStrategy as TryFrom<&[u8]>>::try_from(input),
15910                    <RestartStrategy as TryFrom<&str>>::try_from(s),
15911                    "TryFrom<&[u8]> and TryFrom<&str> reverse-\
15912                     projection axes on RestartStrategy must agree on \
15913                     the valid-UTF-8 input {input:?} — divergence \
15914                     signals the two reverse paths have drifted off \
15915                     the same substrate-primitive from_wire accessor"
15916                );
15917            }
15918        }
15919    }
15920
15921    #[test]
15922    fn supervisor_scalar_ctors_are_const_zero_runtime_work() {
15923        // Const-eval pin: the [`supervisor_scalar_ctors!`] macro spells every
15924        // generated ctor `const fn` so a caller can pin a `SupervisorError`
15925        // at compile time — the same zero-runtime-work property the pre-lift
15926        // `|<slot>| SupervisorError::<Variant> { <slot> }` closure carried on
15927        // its `Copy`-pass-through construction path (no `.to_string()` /
15928        // `.into()` allocation, no branching). If any future edit silently
15929        // drops the `const` qualifier from the macro body the per-arm `const`
15930        // bindings below fail to compile, which surfaces the regression at
15931        // the substrate-primitive definition rather than at some downstream
15932        // consumer that had come to rely on the `const`-constructibility.
15933        // Peer of the sibling
15934        // `aplicacao_policy_scalar_ctors_are_const_zero_runtime_work`
15935        // (7ef425e) const-eval pin on the peer `AplicacaoError` envelope's
15936        // per-`:politicas` per-axis ctor family.
15937        const NO_CHILDREN: SupervisorError =
15938            SupervisorError::no_children(RestartStrategy::OneForAll);
15939        const MAX_RESTARTS_CAP: SupervisorError = SupervisorError::max_restarts_exceeds_cap(1_337);
15940        const WINDOW_NC: SupervisorError =
15941            SupervisorError::restart_window_not_canonical(Duration::from_micros(1));
15942        const WINDOW_CAP: SupervisorError =
15943            SupervisorError::restart_window_exceeds_cap(Duration::from_secs(3_601));
15944        assert!(matches!(NO_CHILDREN, SupervisorError::NoChildren { .. }));
15945        assert!(matches!(
15946            MAX_RESTARTS_CAP,
15947            SupervisorError::MaxRestartsExceedsCap { .. }
15948        ));
15949        assert!(matches!(
15950            WINDOW_NC,
15951            SupervisorError::RestartWindowNotCanonical { .. }
15952        ));
15953        assert!(matches!(
15954            WINDOW_CAP,
15955            SupervisorError::RestartWindowExceedsCap { .. }
15956        ));
15957    }
15958}