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    /// Canonical PascalCase discriminator scalar this variant serializes
113    /// as under [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`]. The four arms
114    /// return the paired [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`]
115    /// / [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
116    /// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
117    /// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] lifted
118    /// constants so every substrate consumer that dispatches on the
119    /// per-supervisor sibling-restart strategy (the future
120    /// wasm-operator's per-supervisor sibling-restart branch, the future
121    /// M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
122    /// admission-time enum-arm bind, the `caixa-operator`'s hierarchical
123    /// reconciliation scheduler's per-strategy fan-out) reads the same
124    /// byte-string the `Serialize` derive emits — the pin test in
125    /// [`tests::restart_strategy_variants_serialize_to_lifted_scalar_values`]
126    /// asserts the two paths agree, peer of the M3
127    /// `PlacementStrategy::as_str` (cc8f749) on the sibling per-Aplicacao
128    /// distribution-strategy axis.
129    #[must_use]
130    pub const fn as_str(self) -> &'static str {
131        match self {
132            Self::OneForOne => crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
133            Self::OneForAll => crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
134            Self::RestForOne => crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
135            Self::SimpleOneForOne => crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
136        }
137    }
138
139    /// Substrate-canonical reverse projection on the `:supervisor
140    /// :estrategia` closed-set axis — parses the `PascalCase`
141    /// discriminator scalar back to the typed variant, or `None` when
142    /// `s` is outside
143    /// the closed-set arm-string set [`Self::as_str`] emits. Dispatches
144    /// on the same lifted
145    /// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
146    /// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
147    /// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
148    /// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
149    /// constants the [`Self::as_str`] emitter walks, so the parse and
150    /// emit halves of the round-trip migrate through one caixa-core
151    /// edit on any future arm addition.
152    ///
153    /// Prior to this lift the substrate carried only the forward
154    /// `Self → &str` projection on the OTP sibling-restart axis (the
155    /// [`Self::as_str`] emitter, the [`std::fmt::Display`] impl routed
156    /// through it, the `Serialize` derive that emits the same
157    /// byte-string under [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`])
158    /// plus the kebab-case dispatcher-catalog identity via
159    /// [`Self::discriminant`] — every non-serde consumer that wanted to
160    /// parse a wire-form `PascalCase` strategy scalar had to re-inline
161    /// a four-arm `match s { "OneForOne" => …, "OneForAll" => …,
162    /// "RestForOne" => …, "SimpleOneForOne" => …, _ => … }` cascade
163    /// that expressed no compile-time link back to the typed variant's
164    /// canonical lifted constant. A future variant rename or per-arm
165    /// serde-attribute drift would silently split the wire byte-string
166    /// one non-serde consumer parsed from the one the emitter wrote,
167    /// with the failure surfacing at parse time far from the rebrand
168    /// commit.
169    ///
170    /// Distinct axis from the [`std::str::FromStr`] impl the
171    /// [`gen_platform::FromStrKind`] derive already installs on this
172    /// enum by design, not by drift: `FromStr` parses the *kebab-case*
173    /// dispatcher-catalog identity (`"one-for-one"` / `"one-for-all"` /
174    /// `"rest-for-one"` / `"simple-one-for-one"` — the inverse of
175    /// [`Self::discriminant`]), while this method inverts the
176    /// `PascalCase` wire byte-string [`Self::as_str`] emits. The
177    /// two-axis split lets the dispatcher-catalog identity live in
178    /// kebab-case
179    /// (where every peer catalog identifier already lives) without
180    /// forcing a wire-format rename on the tatara-lisp author surface
181    /// (`:estrategia OneForOne`, `PascalCase`) — the same two-axis
182    /// distinction the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
183    /// / [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
184    /// carry on their peer closed-set typed-enum wire round-trips.
185    ///
186    /// Same closed-set-reverse-projection discipline the sibling
187    /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
188    /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342) /
189    /// [`crate::aplicacao::RateLimitUnit::from_suffix`] typed enums
190    /// carry on the peer wire-side `str → Self` axes — extended onto
191    /// the M2 OTP-shape sibling-restart-strategy closed-set axis, the
192    /// fifth substrate-side closed-set typed enum to converge on the
193    /// two-way `str ↔ Self` round-trip. Method-named `from_wire` (not
194    /// `from_str`) to match the peer [`crate::CaixaKind::from_wire`]
195    /// shape verbatim and side-step the [`std::str::FromStr`] impl the
196    /// derive already installs on the sibling kebab-case axis. Returns
197    /// `Option<Self>` (rather than `Result<Self, _>`) to match the peer
198    /// shapes: the caller picks the diagnostic form appropriate for
199    /// its use site.
200    #[must_use]
201    pub fn from_wire(s: &str) -> Option<Self> {
202        match s {
203            crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE => Some(Self::OneForOne),
204            crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL => Some(Self::OneForAll),
205            crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE => Some(Self::RestForOne),
206            crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE => Some(Self::SimpleOneForOne),
207            _ => None,
208        }
209    }
210}
211
212/// [`std::fmt::Display`] routed through [`RestartStrategy::as_str`], so the
213/// pretty-printed byte-string every consumer that formats the strategy as
214/// user-facing text lands on (the future wasm-operator's per-supervisor
215/// sibling-restart-strategy diagnostic line, the future `feira app graph`
216/// per-supervisor strategy line, the future M4
217/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission-webhook
218/// rejection body) reaches for the same lifted
219/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
220/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
221/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
222/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const the
223/// wire-format `Serialize` derive already emits under
224/// [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`] and the
225/// [`RestartStrategy::as_str`] helper already returns.
226///
227/// Pre-convergence the two paths structurally disagreed — the
228/// `#[derive(gen_platform::Discriminant)]` + `#[discriminant(also_display)]`
229/// route (now retired here) sent [`std::fmt::Display`] through the
230/// gen-platform discriminant catalog string, which arrives kebab-case as
231/// `"one-for-one"` / `"one-for-all"` / `"rest-for-one"` /
232/// `"simple-one-for-one"`, while the wire format ran as `PascalCase`
233/// `"OneForOne"` / `"OneForAll"` / `"RestForOne"` / `"SimpleOneForOne"`
234/// through the un-`rename`d serde derive. Every consumer that formatted
235/// the strategy for a diagnostic line, a graph, or a rejection body under
236/// `format!("{v}")` therefore landed under a different byte-string than
237/// the wire format the operator's per-strategy dispatch keyed off — a
238/// silent split whose apply-time symptom (a `format!("{v}")`-carrying
239/// diagnostic quoting `"one-for-one"` while the wire scalar the operator
240/// probed was `"OneForOne"`) surfaced as a confused correlate at
241/// operator-log time far from the two-declaration site.
242///
243/// Routing `Display` through [`RestartStrategy::as_str`] closes the third
244/// path: every `format!("{v}")` call reaches the same lifted
245/// [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const the wire format and
246/// the [`RestartStrategy::as_str`] helper route through — `Debug` (the
247/// compiler-derived variant name), `Display` (via `as_str`), and `Serialize`
248/// (via the un-`rename`d derive) all resolve to the same `PascalCase`
249/// byte-string per variant. A future variant rename or
250/// `#[serde(rename_all = "kebab-case")]` attribute reaches every path at
251/// exactly one place, structurally.
252///
253/// The dispatcher-catalog identity remains kebab-case — [`Self::discriminant`]
254/// (from `#[derive(gen_platform::Discriminant)]`) still returns
255/// `"one-for-one"` / etc., and the fleet-wide
256/// [`gen_platform::register_dispatcher!("caixa.restart-strategy", …)`]
257/// registration keys the catalog off the same kebab identity. The two
258/// naming worlds now live on separate typed methods (`Display` /
259/// `as_str` for the wire byte-string, `discriminant` for the catalog
260/// identity) rather than sharing one `Display` route that structurally
261/// disagrees with the wire format.
262///
263/// Pin tests
264/// [`tests::restart_strategy_display_routes_through_as_str_helper`]
265/// and
266/// [`tests::restart_strategy_display_matches_serialized_wire_byte_string`]
267/// assert the three paths agree byte-for-byte on every variant, so a
268/// future variant rename or per-arm serde attribute drift is a build
269/// error visible at caixa-core test time, not a silent per-consumer
270/// dispatch miss at apply / reconcile time.
271///
272/// Mirrors the M3 [`crate::aplicacao::PlacementStrategy`] `Display` impl
273/// (aplicacao.rs:2306) on the sibling per-Aplicacao distribution-strategy
274/// axis — same three-path-convergence discipline, extended to close the
275/// second of three OTP-shaped closed-enum discriminator axes on the
276/// caixa typed surface.
277impl std::fmt::Display for RestartStrategy {
278    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
279        f.write_str(self.as_str())
280    }
281}
282
283/// Substrate-canonical [`AsRef<str>`] projection on the M2
284/// per-supervisor sibling-restart [`RestartStrategy`] closed-set typed
285/// enum — routes through the same [`RestartStrategy::as_str`]
286/// `pub const fn` scalar accessor the paired [`std::fmt::Display`]
287/// impl and the un-`rename`d [`serde::Serialize`] derive already key
288/// off, so any future consumer that binds a [`RestartStrategy`]
289/// through the standard-library `impl AsRef<str>` bound (a future
290/// [`caixa-feira`] `feira supervisor --estrategia <arm>` verb that
291/// composes the emitted `PascalCase` wire scalar into a
292/// [`std::process::Command::arg`] shell-out of the future
293/// wasm-operator's admission gate, a per-supervisor structured-log
294/// recorder on the future `caixa-operator`'s hierarchical
295/// reconciliation surface that accepts `impl AsRef<str>` at the
296/// `tracing::field::Value` `Str`-arm, a [`std::collections::HashMap`]
297/// lookup keyed on the estrategia wire byte through
298/// `map.get::<str>(strategy.as_ref())` on a future per-strategy
299/// dispatch table) reaches the paired [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`]
300/// / [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
301/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
302/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
303/// lifted-const through one substrate-primitive dispatch rather
304/// than an open-coded `.as_str()` projection at every wire-up.
305///
306/// Peer of the sibling [`std::fmt::Display`] impl on the same
307/// primitive — both delegate to the shared
308/// [`RestartStrategy::as_str`] `pub const fn` accessor, so
309/// [`format!("{s}")`], `s.as_str()`, and
310/// `<RestartStrategy as AsRef<str>>::as_ref(&s)` resolve to the same
311/// byte-string per instance by construction. A future variant rename
312/// or `#[serde(rename_all = "kebab-case")]` attribute-drift on the
313/// enum reaches every one of the three paths (plus the wire-format
314/// `Serialize` derive that already routes through the same lifted
315/// const) through exactly one caixa-core edit.
316///
317/// Same "route the trait impl through the substrate-primitive
318/// accessor" discipline the sibling [`crate::CaixaVersion`]
319/// [`AsRef<str>`] impl (16d5c7e) carries on the paired top-level
320/// `:versao` typed newtype — extends it onto the second `AsRef<str>`
321/// axis on the caixa typed surface (the first M2 OTP-shape
322/// closed-set typed enum to converge onto the standard-library
323/// [`AsRef<str>`] projection). Rust-side newtype/typed-enum
324/// convention pairs [`AsRef<str>`] and [`fmt::Display`] on the same
325/// primitive so a caller who has one has both; before this lift,
326/// [`RestartStrategy`] carried [`fmt::Display`] but not the paired
327/// [`AsRef<str>`] impl the convention names.
328///
329/// Pinned load-bearing by
330/// [`tests::restart_strategy_as_ref_str_routes_through_as_str_accessor`]
331/// (byte-parity pin against [`RestartStrategy::as_str`] across the
332/// four-arm closed set) — any future silent detour that routes the
333/// impl through a divergent projection (a per-arm inline
334/// `match self { … }` re-inlining that opens a compile-time link to
335/// the un-lifted arm-literal, a swap onto the kebab-case
336/// [`gen_platform::Discriminant`] catalog identity that would collide
337/// the wire axis with the dispatcher-catalog axis) trips at
338/// caixa-core test time under `assert_eq!` rather than at a
339/// downstream `impl AsRef<str>`-bound consumer's silent split.
340impl AsRef<str> for RestartStrategy {
341    fn as_ref(&self) -> &str {
342        self.as_str()
343    }
344}
345
346/// Trait-idiomatic reverse projection on the M2-OTP-shape sibling-restart
347/// [`RestartStrategy`] closed-set typed enum — routes byte-for-byte through
348/// the paired substrate-primitive [`RestartStrategy::from_wire`]
349/// `Option<Self>` accessor so every future consumer that binds a
350/// `PascalCase` `:supervisor :estrategia` wire byte-string through the
351/// standard-library `.try_into()` / [`TryFrom`] axis (a future
352/// [`caixa-feira`] `feira supervisor --estrategia <OneForOne|OneForAll|
353/// RestForOne|SimpleOneForOne>` CLI arg-parse that composes into
354/// `let estrategia: RestartStrategy = s.try_into()?`, a future
355/// `mesh.pleme.io/v1alpha1/Supervisor` CR admission-webhook that folds a
356/// `spec.estrategia: String` field through
357/// `RestartStrategy::try_from(&s)?`, a generic
358/// `<T: TryFrom<&str>>`-bound loader over any of the substrate's closed-
359/// set typed enums) reaches the same four-arm accept-set the sibling
360/// [`RestartStrategy::from_wire`] resolver parses through and the sibling
361/// [`RestartStrategy::as_str`] emits, rather than an open-coded per-arm
362/// `match s { "OneForOne" => …, "OneForAll" => …, "RestForOne" => …,
363/// "SimpleOneForOne" => …, _ => … }` cascade whose arm-set has no
364/// compile-time link back to the substrate primitive.
365///
366/// Complements the pre-existing forward-projection triple
367/// ([`std::fmt::Display`], [`AsRef<str>`], [`RestartStrategy::as_str`])
368/// with the paired trait-idiomatic reverse-projection axis: Rust-side
369/// newtype/typed-enum convention pairs [`AsRef<str>`] with either
370/// [`std::str::FromStr`] or [`TryFrom<&str>`] on the same primitive so a
371/// caller who can project *out to* a `&str` can also project *in from*
372/// one. The [`TryFrom<&str>`] axis is deliberately chosen over
373/// [`std::str::FromStr`] to sidestep the `clippy::should_implement_trait`
374/// lint the sibling method-named [`RestartStrategy::from_wire`] would
375/// trigger under a `FromStr` impl and to avoid colliding with the
376/// [`std::str::FromStr`] impl the [`gen_platform::FromStrKind`] derive
377/// already installs on the paired *kebab-case dispatcher-catalog* axis
378/// (which parses `"one-for-one"` / `"one-for-all"` / `"rest-for-one"` /
379/// `"simple-one-for-one"`, the inverse of [`Self::discriminant`]) — this
380/// impl closes the trait-idiomatic reverse axis on the *`PascalCase` wire*
381/// half without disturbing either the method-named `from_wire` shape every
382/// sibling closed-set typed enum on the substrate already carries or the
383/// pre-existing `FromStr` on the dispatcher-catalog half, keeping the
384/// two-axis split the sibling [`Self::from_wire`] doc block motivates.
385///
386/// `type Error = ()` matches the sibling [`RestartStrategy::from_wire`]'s
387/// `Option<Self>` return-shape's deliberate deferral of error typing: the
388/// caller picks the diagnostic form appropriate for its use site (a future
389/// `feira supervisor --estrategia` arg-parse composes its own per-verb
390/// "unknown strategy: <arg> — accepted: {…}" message enumerating
391/// [`RestartStrategy::ALL`], a future M4 admission-webhook rejection body
392/// wraps the `Err(())` outcome with the accepted-set enumeration for
393/// operator diagnostics, a `Result::map_err` at the call site lifts the
394/// unit-error to a per-verb error type). Same shape the peer
395/// [`crate::CaixaKind`] (3c83606), [`crate::CaixaDialeto`] (bf33136),
396/// [`crate::aplicacao::PlacementStrategy`] (6fd00cd), and
397/// [`crate::provedor::ferrite::FerriteRuntime::from_wire`] blocks motivate
398/// on their peer closed-set typed enums' reverse projections.
399///
400/// The paired [`TryFrom<&str>`] impl reaches the same four-arm accept-set
401/// the [`RestartStrategy::from_wire`] resolver dispatches through, so any
402/// future arm addition (an OTP-`rest_for_all` fifth arm the theory
403/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
404/// might reach for once the four canonical OTP strategies stop covering
405/// the substrate's discovered load-shape) grows the trait-idiomatic axis
406/// by construction — one caixa-core edit on
407/// [`RestartStrategy::from_wire`] extends both the method-named reverse
408/// projection every existing consumer keys off and the trait-idiomatic
409/// reverse projection this impl exposes, without a coordinated rewrite
410/// across every future `TryFrom<&str>`-bound consumer's arm-set.
411///
412/// Extends the substrate-wide closed-set-enum reverse-projection family
413/// ([`crate::CaixaKind`] via 3c83606, [`crate::CaixaDialeto`] via bf33136,
414/// [`crate::aplicacao::PlacementStrategy`] via 6fd00cd) onto the first
415/// M2-OTP-shape closed-set typed enum on the caixa surface — the
416/// `:supervisor :estrategia` closed set the future wasm-operator's
417/// hierarchical reconciliation scheduler keys off end-to-end.
418///
419/// Pinned load-bearing by
420/// [`tests::restart_strategy_try_from_str_routes_through_from_wire_accessor`]
421/// (byte-parity pin against [`RestartStrategy::from_wire`] across the
422/// four-arm accept-set) and
423/// [`tests::restart_strategy_try_from_str_rejects_unknown_byte_strings`]
424/// (rejection witness against silent accept-set widening).
425impl TryFrom<&str> for RestartStrategy {
426    type Error = ();
427
428    fn try_from(s: &str) -> Result<Self, Self::Error> {
429        Self::from_wire(s).ok_or(())
430    }
431}
432
433/// Trait-idiomatic *forward* projection on the M2-OTP-shape sibling-restart
434/// [`RestartStrategy`] closed-set typed enum onto the `&'static str` axis —
435/// routes byte-for-byte through the paired substrate-primitive
436/// [`RestartStrategy::as_str`] `pub const fn` accessor so every future
437/// consumer that binds a [`RestartStrategy`] through the standard-library
438/// `.into()` / [`From<Self> for &'static str`] (equivalently
439/// [`Into<&'static str>`]) axis (a future
440/// `tracing::field::valuable::Value::Str(strategy.into())` structured-log
441/// recorder where the `Str` arm typing demands `&'static str` and the
442/// sibling [`AsRef<str>`] impl's borrowed `&str` return-type does not
443/// satisfy the bound, a future `Cow::Borrowed::<'static, str>(strategy.into())`
444/// composer on the future M4 admission-webhook rejection body where the
445/// `Cow<'static, str>` typing rules out the sibling [`AsRef<str>`] borrowed
446/// return, a generic `<T: Into<&'static str>>`-bound serializer on a
447/// per-strategy diagnostic column) reaches the same lifted
448/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
449/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
450/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
451/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const the
452/// paired [`std::fmt::Display`], [`AsRef<str>`], and
453/// [`RestartStrategy::as_str`] surfaces already return, rather than an
454/// open-coded per-arm `match s { OneForOne => "OneForOne", … }` cascade
455/// whose arm-set has no compile-time link back to the substrate primitive.
456///
457/// Complements the pre-existing quadruple
458/// ([`std::fmt::Display`], [`AsRef<str>`], [`RestartStrategy::as_str`],
459/// [`TryFrom<&str>`] via 5b828ed) with the paired trait-idiomatic
460/// forward-projection axis: Rust-side newtype/typed-enum convention pairs
461/// [`TryFrom<&str>`] (trait-idiomatic reverse) with [`From<Self> for
462/// &'static str`] (trait-idiomatic forward) on the same primitive so a
463/// caller who can project *in from* a `&str` via the trait axis can also
464/// project *out to* one — mirroring the `strum::IntoStaticStr` /
465/// `serde::Serialize`-shape idiom where both projection halves share one
466/// trait-driven vocabulary. Before this lift the substrate carried a
467/// `&str`-returning [`AsRef<str>`] but not the paired `&'static str`-
468/// returning [`From<Self> for &'static str`] axis every downstream
469/// generic that specifically needs `'static` byte-string bytes reaches for.
470///
471/// The paired [`RestartStrategy::as_str`] returns `&'static str` by
472/// construction (each `match` arm resolves to a
473/// [`crate::render::SUPERVISOR_ESTRATEGIA_*`] `pub const &str` with static
474/// lifetime), so the trait's return-type promise is upheld structurally.
475/// Any future silent detour that routes the impl through a non-static
476/// projection (a per-arm inline `String::from("OneForOne")`-shaped
477/// re-inlining that would `.leak()`-cast for the `'static` bound, a
478/// hypothetical rebrand of one arm's [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
479/// const to a non-`const &str`) is a caixa-core-build-time failure through
480/// the `pub const fn as_str` signature the trait routes through.
481///
482/// The paired impl reaches the same four-arm emit-set the
483/// [`RestartStrategy::as_str`] accessor dispatches through, so any future
484/// 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
488/// forward axis by construction — one caixa-core edit on
489/// [`RestartStrategy::as_str`] extends every one of the five sibling
490/// forward-projection paths ([`std::fmt::Display`], [`AsRef<str>`],
491/// [`RestartStrategy::as_str`] itself, this [`From<Self> for &'static str`],
492/// and the un-`rename`d [`serde::Serialize`] derive that also emits
493/// [`Self::as_str`]'s bytes) without a coordinated rewrite across every
494/// future `Into<&'static str>`-bound consumer's arm-set.
495///
496/// Opens the substrate-wide trait-idiomatic *forward*-projection family on
497/// closed-set fieldless typed enums — the mirror of the recently-closed
498/// trait-idiomatic *reverse*-projection family ([`crate::CaixaKind`] via
499/// 3c83606, [`crate::CaixaDialeto`] via bf33136,
500/// [`crate::aplicacao::PlacementStrategy`] via 6fd00cd, this enum via
501/// 5b828ed, [`crate::supervisor::RestartPolicy`] via 6fdd0d9,
502/// [`crate::aplicacao::WitShape`] via 5472902,
503/// [`crate::aplicacao::RateLimitUnit`] via bf78400,
504/// [`crate::render::PathShapeViolation`] via e67e48a, and the four
505/// downstream-crate peers — [`caixa_arch::InvariantKind`] via e21a857,
506/// [`caixa_arch::ArchVerdict`] via 0a4cc45, [`caixa_lint::Severity`] via
507/// a7bf74c, [`caixa_lint::FixSafety`] via df86c94,
508/// [`caixa_theme::Semantic`] via bd7da69, and
509/// [`caixa_provedor::ferrite::FerriteRuntime`] via 42ab951). This lift
510/// picks [`RestartStrategy`] as the first-mover on the forward-projection
511/// family because its wire byte-string (`PascalCase`) and diagnostic
512/// byte-string ([`as_str`] return) coincide by construction — the sibling
513/// [`crate::CaixaKind`] two-axis split (lowercase Portuguese diagnostic
514/// vs `PascalCase` wire) would leave a first-mover peer arbitrarily
515/// picking one axis; on [`RestartStrategy`] the choice is unambiguous.
516///
517/// Pinned load-bearing by
518/// [`tests::restart_strategy_from_into_static_str_routes_through_as_str_accessor`]
519/// (byte-parity pin against [`RestartStrategy::as_str`] across the
520/// four-arm emit-set, plus a `const`-context materialization witness for
521/// the `&'static str` lifetime promise) and
522/// [`tests::restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
523/// (partition pin asserting `<&'static str as From<RestartStrategy>>::from`
524/// and [`RestartStrategy::as_str`] agree on every arm, so no future
525/// silent bifurcation of the two forward-projection paths can land
526/// silently).
527impl From<RestartStrategy> for &'static str {
528    fn from(strategy: RestartStrategy) -> &'static str {
529        strategy.as_str()
530    }
531}
532
533/// Trait-idiomatic *forward* projection on [`RestartStrategy`] from a
534/// *borrowed* input onto the `&'static str` axis — the borrowed-input
535/// companion to the paired owned-input [`From<RestartStrategy> for
536/// &'static str`] impl immediately above. Routes byte-for-byte through
537/// the same substrate-primitive [`RestartStrategy::as_str`] `pub const
538/// fn` accessor so every consumer that binds a `&RestartStrategy`
539/// through the standard-library `.into()` / [`From<&Self> for &'static
540/// str`] axis (a `RestartStrategy::ALL.iter().map(<&'static
541/// str>::from).collect::<Vec<_>>()` per-arm accept-set materializer —
542/// whose iterator over `&'static [RestartStrategy]` yields
543/// `&RestartStrategy`, not `RestartStrategy`, so the owned-input
544/// [`From<RestartStrategy>`] axis alone forces every call site through
545/// an explicit `.copied()` / dereference / [`Copy`]-bound restatement
546/// rather than the direct trait-idiomatic projection; a future generic
547/// `<T: Copy + for<'a> Into<&'static str>>`-bound diagnostic column
548/// that walks the `iter().map(Into::into)` shape verbatim across every
549/// substrate-wide closed-set typed enum; the future wasm-operator's
550/// per-supervisor sibling-restart-strategy diagnostic line that
551/// composes the accepted-set enumeration from an iterated
552/// `RestartStrategy::ALL.iter().map(|s| s.into())` pipe rather than a
553/// per-arm `match s { … }` cascade; a future
554/// `HashMap::<&'static str, RestartStrategy>::from_iter(
555///     RestartStrategy::ALL.iter().map(|s| (s.into(), *s)))`-style
556/// per-strategy reverse-lookup table the sibling [`TryFrom<&str>`]
557/// impl cannot compose without this borrowed-input axis in place)
558/// reaches the same four-arm lifted
559/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
560/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
561/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
562/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const
563/// the paired owned-input [`From<RestartStrategy> for &'static str`],
564/// the sibling [`std::fmt::Display`], [`AsRef<str>`], and
565/// [`RestartStrategy::as_str`] surfaces already return.
566///
567/// Fourth peer on the substrate-wide trait-idiomatic *borrowed-input*
568/// forward-projection family opened on [`crate::dep::DepList`]
569/// (64aa742) and extended onto [`crate::CaixaKind`] (5ab993a) and
570/// [`crate::CaixaDialeto`] (807b0b5). Rust's `From` trait does not
571/// auto-derive the `From<&Self>` sibling from a `From<Self>` impl (the
572/// blanket `impl<T, U> From<&T> for U where T: Copy, U: From<T>` does
573/// not exist in `core`), so every closed-set typed enum that carries
574/// the owned-input axis but not the borrowed-input axis forces every
575/// borrowed-input call site through a `.copied()` /
576/// `<&'static str>::from(*strategy)` / `strategy.as_str()` detour whose
577/// type bounds have no compile-time link to the substrate primitive.
578/// [`RestartStrategy`] is the first M2 OTP-shape peer to converge onto
579/// this campaign (mirroring the first-mover role it played on the
580/// owned-input axis in 523157d); the remaining eleven substrate-wide
581/// closed-set fieldless typed enum peers (`RestartPolicy`, `WitShape`,
582/// `RateLimitUnit`, `PlacementStrategy`, `PathShapeViolation`,
583/// `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`,
584/// `FerriteRuntime`) are the future targets of this campaign.
585///
586/// Unlike the peer [`crate::CaixaKind`] axis pair (whose forward
587/// [`From<Self> for &'static str`] emits the lowercase Portuguese
588/// [`Self::as_str`] diagnostic vocabulary while the reverse
589/// [`TryFrom<&str>`] parses the `PascalCase` [`Self::wire_name`]
590/// author-surface vocabulary, forcing the round-trip through an
591/// intermediate wire-vocab hop), [`RestartStrategy`]'s
592/// [`Self::as_str`] emit and [`Self::from_wire`] parse share the same
593/// `PascalCase` vocabulary by construction, so the borrowed-input
594/// forward axis and the reverse axis compose directly — the round-trip
595/// witness pin below locks this direct composition without the
596/// intermediate hop the peer axis requires.
597///
598/// Pinned load-bearing by
599/// [`tests::restart_strategy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
600/// (byte-parity pin against [`RestartStrategy::as_str`] across the
601/// four-arm emit-set via a borrowed input, plus a `const`-context
602/// materialization witness for the `&'static str` lifetime promise,
603/// plus a blanket `.into()` shape) and
604/// [`tests::restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
605/// (cross-axis partition pin against the paired owned-input
606/// [`From<RestartStrategy> for &'static str`] impl, plus a
607/// `.iter().map(Into::into)` pipe witness over
608/// [`RestartStrategy::ALL`], plus a direct round-trip witness through
609/// [`TryFrom<&str>`] that closes the two-way `&Self → &'static str →
610/// Self` round-trip without the wire-vocab intermediate the peer
611/// [`crate::CaixaKind`] axis pair requires).
612impl From<&RestartStrategy> for &'static str {
613    fn from(strategy: &RestartStrategy) -> &'static str {
614        strategy.as_str()
615    }
616}
617
618/// Trait-idiomatic *owned-`String`* forward projection on the M2
619/// OTP-shape sibling-restart-strategy closed-set typed enum — the
620/// owned-heap-string companion to the paired `&'static str`-returning
621/// [`From<RestartStrategy> for &'static str`] / [`From<&RestartStrategy>
622/// for &'static str`] impls immediately above. Routes byte-for-byte
623/// through the substrate-primitive [`RestartStrategy::as_str`]
624/// `pub const fn` accessor (via [`str::to_owned`]) so every consumer
625/// that binds a [`RestartStrategy`] through the standard-library
626/// `.into()` / [`From<Self> for String`] (equivalently
627/// [`Into<String>`]) axis — a future
628/// `serde_json::Value::String(strategy.into())` structured-payload
629/// composer where the `Value::String` arm typing demands an owned
630/// [`String`] and the sibling [`&'static str`]-returning axis forces an
631/// explicit `.to_owned()` / `String::from` restatement at every call
632/// site, a future
633/// `HashMap::<String, RestartStrategy>::from_iter(RestartStrategy::ALL
634/// .iter().map(|s| (s.into(), *s)))` per-strategy lookup where the
635/// map's key type is owned [`String`] rather than [`&'static str`], a
636/// future `Cow::<'static, str>::Owned(strategy.into())` composer on
637/// the future M4 admission-webhook rejection body's owned-arm, the
638/// future wasm-operator's per-supervisor `serde_json::json!({
639/// "estrategia": strategy })` diagnostic emit where the JSON
640/// serializer's `Serialize` impl on [`String`] owns the emit-path — reaches
641/// the same four-arm lifted
642/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
643/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
644/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
645/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const the
646/// paired [`std::fmt::Display`], [`AsRef<str>`],
647/// [`RestartStrategy::as_str`], and the two `&'static str`-returning
648/// forward-projection impls already return.
649///
650/// Opens the trait-idiomatic *owned-`String`* forward-projection axis
651/// on the closed-set fieldless typed enum surface — first-mover on the
652/// M2 OTP-shape sibling-restart-strategy axis, mirror of the
653/// [`crate::supervisor::RestartStrategy`] first-mover position that
654/// opened the paired owned-`&'static str` axis (523157d) and the
655/// borrowed-input `&'static str` axis on
656/// [`crate::dep::DepList`] (64aa742). Rust's standard library does not
657/// carry a blanket `impl<T: AsRef<str>> From<T> for String` (nor an
658/// `impl<T: fmt::Display> From<T> for String`), so every closed-set
659/// typed enum that carries the paired `AsRef<str>` / `Display` /
660/// `From<Self> for &'static str` triple but not the owned-[`String`]
661/// axis forces every owned-string call site through a `.to_string()` /
662/// `.as_str().to_owned()` / `String::from(strategy.as_str())` detour
663/// whose type bounds have no compile-time link to the substrate
664/// primitive.
665///
666/// Deliberately routes through the human-readable
667/// [`RestartStrategy::as_str`] axis — for this enum the wire format
668/// (`PascalCase`, tatara-lisp author surface `:estrategia OneForOne`)
669/// and the diagnostic byte-string share the same vocabulary by
670/// construction (unlike the sibling [`crate::CaixaKind`] enum whose two
671/// axes diverge), so the owned-[`String`] projection lands
672/// byte-identically on both the wire vocabulary the paired
673/// [`serde::Serialize`] derive emits and the diagnostic vocabulary the
674/// [`RestartStrategy::as_str`] helper returns.
675///
676/// The remaining fourteen closed-set typed enums on the caixa
677/// substrate surface (`RestartPolicy`, `CaixaKind`, `CaixaDialeto`,
678/// `DepList`, `PlacementStrategy`, `WitShape`, `RateLimitUnit`,
679/// `PathShapeViolation`, `InvariantKind`, `ArchVerdict`, `Severity`,
680/// `FixSafety`, `Semantic`, `FerriteRuntime`) are the future targets of
681/// this campaign — each carries the same paired `AsRef<str>` /
682/// `Display` / `From<Self> for &'static str` / `From<&Self> for
683/// &'static str` quadruple that this owned-[`String`] axis extends onto.
684///
685/// Pinned load-bearing by
686/// [`tests::restart_strategy_from_into_owned_string_routes_through_as_str_accessor`]
687/// (byte-parity pin against [`RestartStrategy::as_str`] across the
688/// four-arm emit-set, plus a blanket `.into::<String>()` shape witness)
689/// and
690/// [`tests::restart_strategy_from_into_owned_string_and_static_str_agree_on_every_arm`]
691/// (cross-axis partition pin against the paired owned-input
692/// [`From<RestartStrategy> for &'static str`] impl and the sibling
693/// [`ToString::to_string`] surface routed through [`std::fmt::Display`],
694/// plus a direct round-trip witness through [`TryFrom<&str>`] on the
695/// owned-[`String`]'s [`String::as_str`] borrow that closes the two-way
696/// `Self → String → Self` round-trip on the trait-idiomatic
697/// owned-[`String`] forward + reverse axis pair).
698impl From<RestartStrategy> for String {
699    fn from(strategy: RestartStrategy) -> String {
700        strategy.as_str().to_owned()
701    }
702}
703
704/// Trait-idiomatic *borrowed-input, owned-`String` output* forward
705/// projection on the M2 OTP-shape sibling-restart-strategy closed-set
706/// typed enum — the fourth (and closing) corner of the
707/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
708/// projection family. Routes byte-for-byte through the
709/// substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
710/// accessor (via [`str::to_owned`]) so every consumer that holds a
711/// borrowed [`&RestartStrategy`] and needs an owned [`String`] — a
712/// future `serde_json::Value::String(String::from(&strategy))`
713/// structured-payload composer over a borrowed field, a future
714/// `Iterator::map` over `&[RestartStrategy]` that projects to owned
715/// keys through `.iter().map(String::from)`, a future
716/// `HashMap::<String, RestartStrategy>::from_iter` that keys off a
717/// borrowed-iteration axis where dereferencing the strategy would force
718/// an unnecessary `Copy` at every step, the future wasm-operator's
719/// per-supervisor `strategies.iter().map(String::from).collect()`
720/// diagnostic emit whose iteration axis is borrowed by construction —
721/// reaches the same four-arm lifted
722/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
723/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
724/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
725/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const the
726/// paired [`std::fmt::Display`], [`AsRef<str>`],
727/// [`RestartStrategy::as_str`], and the three other trait-idiomatic
728/// forward-projection impls
729/// ([`From<RestartStrategy> for &'static str`],
730/// [`From<&RestartStrategy> for &'static str`],
731/// [`From<RestartStrategy> for String`]) already return.
732///
733/// Opens the trait-idiomatic *borrowed-input, owned-`String` output*
734/// forward-projection axis on closed-set fieldless typed enums —
735/// first-mover on the 2×2 completion corner, mirror of the
736/// [`crate::supervisor::RestartStrategy`] first-mover position that
737/// opened the paired owned-input owned-`String` axis (7baa18a), the
738/// owned-input owned-`&'static str` axis (523157d), and the paired
739/// [`crate::dep::DepList`] first-mover position that opened the
740/// borrowed-input `&'static str` axis (64aa742). Rust's standard
741/// library does not carry a blanket `impl<T: AsRef<str>> From<&T> for
742/// String` (nor an `impl<T: fmt::Display> From<&T> for String`), so
743/// every closed-set typed enum that carries the paired `AsRef<str>` /
744/// `Display` / `From<Self> for &'static str` / `From<&Self> for
745/// &'static str` / `From<Self> for String` quintuple but not the
746/// borrowed-input owned-[`String`] axis forces every borrowed-input
747/// owned-string call site through a `strategy.as_str().to_owned()` /
748/// `String::from(*strategy)` (with a spurious `Copy`) /
749/// `strategy.to_string()` (through `Display`) detour whose type bounds
750/// have no compile-time link to the substrate primitive.
751///
752/// Deliberately routes through the human-readable
753/// [`RestartStrategy::as_str`] axis — for this enum the wire format
754/// (`PascalCase`, tatara-lisp author surface `:estrategia OneForOne`)
755/// and the diagnostic byte-string share the same vocabulary by
756/// construction (unlike the sibling [`crate::CaixaKind`] enum whose two
757/// axes diverge), so the borrowed-input owned-[`String`] projection
758/// lands byte-identically on both the wire vocabulary the paired
759/// [`serde::Serialize`] derive emits and the diagnostic vocabulary the
760/// [`RestartStrategy::as_str`] helper returns.
761///
762/// The remaining fourteen closed-set typed enums on the caixa
763/// substrate surface (`RestartPolicy`, `CaixaKind`, `CaixaDialeto`,
764/// `DepList`, `PlacementStrategy`, `WitShape`, `RateLimitUnit`,
765/// `PathShapeViolation`, `InvariantKind`, `ArchVerdict`, `Severity`,
766/// `FixSafety`, `Semantic`, `FerriteRuntime`) are the future targets of
767/// this 2×2-completion campaign — each carries the same paired
768/// quintuple that this borrowed-input owned-[`String`] axis extends onto.
769///
770/// Pinned load-bearing by
771/// [`tests::restart_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
772/// (byte-parity pin against [`RestartStrategy::as_str`] across the
773/// four-arm emit-set through the borrowed-input surface) and
774/// [`tests::restart_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
775/// (cross-axis partition pin against the paired owned-input owned-
776/// [`String`] [`From<RestartStrategy> for String`] impl, the paired
777/// borrowed-input owned-[`&'static str`] [`From<&RestartStrategy> for
778/// &'static str`] impl, and the sibling [`ToString::to_string`] surface
779/// routed through [`std::fmt::Display`], plus a direct round-trip
780/// witness through [`TryFrom<&str>`] on the owned-[`String`]'s
781/// [`String::as_str`] borrow that closes the two-way
782/// `&Self → String → Self` round-trip on the trait-idiomatic
783/// borrowed-input owned-[`String`] forward + reverse axis pair).
784impl From<&RestartStrategy> for String {
785    fn from(strategy: &RestartStrategy) -> String {
786        strategy.as_str().to_owned()
787    }
788}
789
790/// Trait-idiomatic *owned-input, [`std::borrow::Cow<'static, str>`]
791/// output* forward projection on the M2 OTP-shape sibling-restart
792/// [`RestartStrategy`] closed-set typed enum — extends the substrate-
793/// wide [`std::borrow::Cow<'static, str>`] forward-projection family
794/// opened on [`crate::CaixaKind`] (99c1735) onto the first M2 OTP-
795/// shape closed-set fieldless typed enum peer on the caixa surface
796/// (`:supervisor :estrategia`). Routes byte-for-byte through the
797/// substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
798/// accessor (via [`std::borrow::Cow::Borrowed`]) so every consumer
799/// that binds a [`RestartStrategy`] through the trait-idiomatic
800/// [`std::borrow::Cow<'static, str>`] axis — a future
801/// `axum::response::IntoResponse` composer whose per-strategy
802/// diagnostic-body typing rules out the sibling [`AsRef<str>`]
803/// borrowed return, a future M4 admission-webhook rejection body
804/// that composes the accepted-strategy enumeration through the same
805/// `RestartStrategy::ALL.iter().map(Cow::from)` shape [`CaixaKind`]
806/// already routes through, a generic `<T: for<'a>
807/// Into<std::borrow::Cow<'static, str>>>`-bound structured-log
808/// emitter on a per-supervisor diagnostic column — reaches the same
809/// four-arm lifted [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`]
810/// / [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
811/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
812/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const
813/// the paired [`std::fmt::Display`], [`AsRef<str>`],
814/// [`RestartStrategy::as_str`], and the four
815/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
816/// forward-projection corners already return.
817///
818/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
819/// [`std::borrow::Cow::Owned`] — the substrate-primitive
820/// [`RestartStrategy::as_str`] accessor's return carries the
821/// `&'static str` lifetime by construction (each `match` arm resolves
822/// to a [`crate::render::SUPERVISOR_ESTRATEGIA_*`] `pub const &str`
823/// with static lifetime), so the zero-alloc borrowed arm is the
824/// type-correct projection with no runtime allocation.
825///
826/// Rust's standard library carries no blanket `impl<T: AsRef<str>>
827/// From<T> for Cow<'static, str>` (nor an `impl<T: fmt::Display>
828/// From<T> for Cow<'static, str>`), so the paired sibling
829/// [`From<RestartStrategy> for &'static str`],
830/// [`From<RestartStrategy> for String`], [`AsRef<str>`], and
831/// [`std::fmt::Display`] surfaces do not implicitly extend to a
832/// [`Cow<'static, str>`]-bound call site — every such site is forced
833/// through a `Cow::Borrowed(strategy.as_str())` /
834/// `Cow::Owned(strategy.to_string())` open-code whose type bounds
835/// have no compile-time link back to the substrate primitive until
836/// this lift.
837///
838/// First peer to extend the substrate-wide trait-idiomatic
839/// [`std::borrow::Cow<'static, str>`] forward-projection axis off the
840/// top-level [`crate::CaixaKind`] enum (99c1735 owned-input,
841/// d45c409 borrowed-input) onto the wider substrate — the remaining
842/// twelve peers (`RestartPolicy`, `PlacementStrategy`, `RateLimitUnit`,
843/// `DepList`, `CaixaDialeto`, and the outside-`caixa-core` peers
844/// `WitShape`, `PathShapeViolation`, `InvariantKind`, `ArchVerdict`,
845/// `Severity`, `FixSafety`, `Semantic`, `FerriteRuntime`) are the
846/// future targets of this campaign.
847///
848/// Pinned load-bearing by
849/// [`tests::restart_strategy_from_into_static_cow_str_routes_through_as_str_accessor`]
850/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
851/// against [`RestartStrategy::as_str`] across the four-arm
852/// [`RestartStrategy::ALL`]) and
853/// [`tests::restart_strategy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
854/// (cross-axis partition pin against the paired [`From<RestartStrategy>
855/// for &'static str`], [`From<RestartStrategy> for String`], and
856/// [`ToString`]-through-[`std::fmt::Display`] axes, plus a
857/// `.iter().copied().map(Cow::from)` pipe witness over
858/// [`RestartStrategy::ALL`] that materializes the four-arm accept-set
859/// through the [`Cow<'static, str>`] axis alone and pins the
860/// zero-alloc discipline on every element).
861impl From<RestartStrategy> for std::borrow::Cow<'static, str> {
862    fn from(strategy: RestartStrategy) -> std::borrow::Cow<'static, str> {
863        std::borrow::Cow::Borrowed(strategy.as_str())
864    }
865}
866
867/// Trait-idiomatic *borrowed-input, [`std::borrow::Cow<'static, str>`]
868/// output* forward projection on the M2 OTP-shape sibling-restart
869/// [`RestartStrategy`] closed-set typed enum — the borrowed-input
870/// companion to the paired owned-input
871/// [`From<RestartStrategy> for std::borrow::Cow<'static, str>`] impl
872/// immediately above (7dd28b3). Routes byte-for-byte through the same
873/// substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
874/// accessor (via [`std::borrow::Cow::Borrowed`]) so every consumer
875/// that holds a `&RestartStrategy` and needs a
876/// [`std::borrow::Cow<'static, str>`] — a
877/// `RestartStrategy::ALL.iter().map(std::borrow::Cow::from).collect::<Vec<_>>()`
878/// per-arm accept-set materializer (whose iterator over
879/// `&'static [RestartStrategy]` yields `&RestartStrategy`, not
880/// `RestartStrategy`, so the paired owned-input
881/// [`From<RestartStrategy> for std::borrow::Cow<'static, str>`] axis
882/// alone forces every call site through an explicit `.copied()` /
883/// dereference / [`Copy`]-bound restatement rather than the direct
884/// trait-idiomatic projection), a future generic
885/// `<T: for<'a> Into<std::borrow::Cow<'static, str>>>`-bound emitter
886/// on a per-strategy diagnostic column that walks the
887/// `iter().map(Into::into)` shape verbatim, the future M4 admission-
888/// webhook rejection body that composes the accepted-strategy
889/// enumeration from an iterated
890/// `RestartStrategy::ALL.iter().map(|s| s.into())` pipe rather than a
891/// per-arm `match s { … }` cascade — reaches the same four-arm lifted
892/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
893/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
894/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
895/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const
896/// the paired [`std::fmt::Display`], [`AsRef<str>`],
897/// [`RestartStrategy::as_str`], the four
898/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
899/// forward-projection corners, and the paired owned-input
900/// [`From<RestartStrategy> for std::borrow::Cow<'static, str>`] impl
901/// already return.
902///
903/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
904/// [`std::borrow::Cow::Owned`] — the substrate-primitive
905/// [`RestartStrategy::as_str`] accessor's return carries the
906/// `&'static str` lifetime by construction (each `match` arm resolves
907/// to a [`crate::render::SUPERVISOR_ESTRATEGIA_*`] `pub const &str`
908/// with static lifetime), so the zero-alloc borrowed arm is the
909/// type-correct projection with no runtime allocation.
910///
911/// Second peer on the substrate-wide trait-idiomatic
912/// [`std::borrow::Cow<'static, str>`] forward-projection family
913/// opened one commit prior (7dd28b3) on the paired owned-input
914/// [`From<RestartStrategy> for std::borrow::Cow<'static, str>`] impl
915/// — closes the `{Self, &Self}` input-shape corner of the
916/// [`Cow<'static, str>`] axis on the first M2 OTP-shape closed-set
917/// fieldless typed enum peer on the caixa surface, exactly as
918/// d45c409 closed it on the top-level [`crate::CaixaKind`] one commit
919/// after the owning half (99c1735) landed. Rust's standard library
920/// does not carry a blanket `impl<T: AsRef<str>> From<&T> for
921/// Cow<'static, str>` (nor an `impl<T: fmt::Display> From<&T> for
922/// Cow<'static, str>`), so every closed-set fieldless typed enum peer
923/// on the substrate that carries the paired owned-input
924/// [`Cow<'static, str>`] axis but not the borrowed-input axis forces
925/// every borrowed-input [`Cow<'static, str>`]-parameterized call site
926/// through a spurious [`Copy`] deref
927/// (`std::borrow::Cow::from(*strategy)`) or a
928/// `std::borrow::Cow::Borrowed(strategy.as_str())` open-code whose
929/// type bounds have no compile-time link to the substrate primitive.
930///
931/// Pinned load-bearing by
932/// [`tests::restart_strategy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor`]
933/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
934/// against [`RestartStrategy::as_str`] across the four-arm
935/// [`RestartStrategy::ALL`] through the borrowed-input surface) and
936/// [`tests::restart_strategy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
937/// (cross-axis partition pin against the paired owned-input
938/// [`From<RestartStrategy> for std::borrow::Cow<'static, str>`], the
939/// paired borrowed-input owned-`&'static str`
940/// [`From<&RestartStrategy> for &'static str`], and the paired
941/// borrowed-input owned-`String` [`From<&RestartStrategy> for String`]
942/// impls, plus a `.iter().map(std::borrow::Cow::from)` pipe witness
943/// over [`RestartStrategy::ALL`] — whose iterator yields
944/// `&RestartStrategy` by construction, so the borrowed-input
945/// [`Cow<'static, str>`] axis is what routes the pipe through the
946/// substrate-primitive [`RestartStrategy::as_str`] accessor with the
947/// zero-alloc [`Cow::Borrowed`] arm by construction and without a
948/// spurious [`Copy`] deref).
949impl From<&RestartStrategy> for std::borrow::Cow<'static, str> {
950    fn from(strategy: &RestartStrategy) -> std::borrow::Cow<'static, str> {
951        std::borrow::Cow::Borrowed(strategy.as_str())
952    }
953}
954
955/// Trait-idiomatic *owned-input, [`Box<str>`] output* forward
956/// projection on the M2 OTP-shape sibling-restart [`RestartStrategy`]
957/// closed-set fieldless typed enum — opens a fresh
958/// substrate-wide `Box<str>` forward-projection campaign tier on the
959/// first M2 OTP-shape closed-set fieldless typed enum peer on the
960/// caixa surface, immediately after the paired `Cow<'static, str>`
961/// axis (7dd28b3 / ee577fd) closed the
962/// `{Self, &Self} × {&'static str, String, Cow<'static, str>}` 2×3
963/// corner on this enum. Routes byte-for-byte through the
964/// substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
965/// accessor via [`Box::<str>::from`] on the returned `&'static str`,
966/// so every consumer that binds a
967/// `let key: Box<str> = strategy.into();`-shaped call site — a
968/// per-supervisor metric-key materializer that stashes the strategy
969/// discriminator in a `Box<str>`-typed heap-owned scalar for cheap
970/// clone (a shared-nothing per-strategy accept-set the
971/// `caixa-operator` reconciliation scheduler carries), a future
972/// admission-webhook rejection body whose per-arm `Box<str>` field
973/// composes from an owned `RestartStrategy` handle — reaches the
974/// same four-arm lifted
975/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
976/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
977/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
978/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const
979/// the sibling
980/// `{Self, &Self} × {&'static str, String, Cow<'static, str>}`
981/// forward-projection corner already returns. Rust's standard
982/// library carries `impl From<&str> for Box<str>` and
983/// `impl From<String> for Box<str>` but no blanket
984/// `impl<T: AsRef<str>> From<T> for Box<str>`, so this axis is a
985/// distinct trait-idiomatic surface that a downstream
986/// `RestartStrategy → Box<str>` `.into()` reaches through this impl
987/// and no other — without a
988/// `Box::from(strategy.as_str())` open-code whose type bounds have
989/// no compile-time link back to the substrate primitive.
990///
991/// Pinned load-bearing by
992/// [`tests::restart_strategy_from_into_box_str_routes_through_as_str_accessor`]
993/// (byte-parity pin against [`RestartStrategy::as_str`] across the
994/// four-arm [`RestartStrategy::ALL`] emit-set on the owned-input
995/// surface, plus a blanket-derived [`Into`] shape witness).
996impl From<RestartStrategy> for Box<str> {
997    fn from(strategy: RestartStrategy) -> Box<str> {
998        Box::<str>::from(strategy.as_str())
999    }
1000}
1001
1002/// Trait-idiomatic *borrowed-input, [`Box<str>`] output* forward
1003/// projection on the M2 OTP-shape sibling-restart [`RestartStrategy`]
1004/// closed-set fieldless typed enum — closes the `{Self, &Self}`
1005/// input-shape corner of the substrate-wide `Box<str>`
1006/// forward-projection axis opened one commit prior (69ef45c) on the
1007/// paired owned-input [`From<RestartStrategy> for Box<str>`] impl.
1008/// Routes byte-for-byte through the same substrate-primitive
1009/// [`RestartStrategy::as_str`] `pub const fn` accessor via
1010/// [`Box::<str>::from`] on the returned `&'static str`, so every
1011/// consumer that holds a `&RestartStrategy` and needs a
1012/// [`Box<str>`] — a
1013/// `RestartStrategy::ALL.iter().map(Box::<str>::from).collect::<Vec<_>>()`
1014/// per-arm accept-set materializer (whose iterator over
1015/// `&'static [RestartStrategy]` yields `&RestartStrategy`, not
1016/// `RestartStrategy`, so the paired owned-input
1017/// [`From<RestartStrategy> for Box<str>`] axis alone forces every
1018/// call site through an explicit `.copied()` / dereference /
1019/// [`Copy`]-bound restatement rather than the direct trait-idiomatic
1020/// projection), a per-supervisor metric-key materializer holding
1021/// `&RestartStrategy` through a `caixa-operator` reconciliation
1022/// scheduler's borrow lifetime, a future admission-webhook rejection
1023/// body whose per-arm `Box<str>` field composes from a borrowed
1024/// `&RestartStrategy` handle without a spurious [`Copy`] deref —
1025/// reaches the same four-arm lifted
1026/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
1027/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
1028/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
1029/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const
1030/// the paired owned-input [`From<RestartStrategy> for Box<str>`] and
1031/// the sibling
1032/// `{Self, &Self} × {&'static str, String, Cow<'static, str>}`
1033/// forward-projection corner already return.
1034///
1035/// Second peer on the substrate-wide trait-idiomatic
1036/// [`Box<str>`] forward-projection family opened one commit prior
1037/// (69ef45c) on the paired owned-input
1038/// [`From<RestartStrategy> for Box<str>`] impl — closes the
1039/// `{Self, &Self}` input-shape corner of the [`Box<str>`] axis on
1040/// the first M2 OTP-shape closed-set fieldless typed enum peer on
1041/// the caixa surface (`:supervisor :estrategia`), exactly as
1042/// ee577fd closed the paired [`Cow<'static, str>`] axis one commit
1043/// after its owning half (7dd28b3) landed. Rust's standard library
1044/// carries `impl From<&str> for Box<str>` and
1045/// `impl From<String> for Box<str>` but no blanket
1046/// `impl<T: AsRef<str>> From<&T> for Box<str>` (nor a
1047/// `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`), so
1048/// every closed-set fieldless typed enum peer on the substrate that
1049/// carries the paired owned-input `Box<str>` axis but not the
1050/// borrowed-input axis forces every borrowed-input
1051/// `Box<str>`-parameterized call site through a spurious [`Copy`]
1052/// deref (`Box::<str>::from((*strategy).as_str())`) or a
1053/// `Box::<str>::from(strategy.as_str())` open-code whose type bounds
1054/// have no compile-time link back to the substrate primitive.
1055///
1056/// Pinned load-bearing by
1057/// [`tests::restart_strategy_from_borrowed_into_box_str_routes_through_as_str_accessor`]
1058/// (byte-parity pin against [`RestartStrategy::as_str`] across the
1059/// four-arm [`RestartStrategy::ALL`] emit-set on the borrowed-input
1060/// surface, plus a blanket-derived [`Into`] shape witness and a
1061/// cross-axis pin against the paired owned-input
1062/// [`From<RestartStrategy> for Box<str>`] and the sibling
1063/// borrowed-input `{&'static str, String, Cow<'static, str>}`
1064/// return-shape axes).
1065impl From<&RestartStrategy> for Box<str> {
1066    fn from(strategy: &RestartStrategy) -> Box<str> {
1067        Box::<str>::from(strategy.as_str())
1068    }
1069}
1070
1071/// Trait-idiomatic *owned-input, [`std::sync::Arc<str>`] output*
1072/// forward projection on the M2 OTP-shape sibling-restart
1073/// [`RestartStrategy`] closed-set fieldless typed enum — opens the
1074/// substrate-wide [`std::sync::Arc<str>`] forward-projection campaign
1075/// tier on the first M2 OTP-shape closed-set fieldless typed enum peer
1076/// on the caixa surface (`:supervisor :estrategia`), immediately after
1077/// the paired [`Box<str>`] axis (69ef45c / 59ae5dc) closed the
1078/// `{Self, &Self} × {&'static str, String, Cow<'static, str>, Box<str>}`
1079/// 2×4 corner on this enum. Routes byte-for-byte through the
1080/// substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
1081/// accessor (via [`std::sync::Arc::<str>::from`] on the returned
1082/// `&'static str`), so every consumer that binds a
1083/// [`RestartStrategy`] through the standard-library `.into()` /
1084/// [`From<Self> for std::sync::Arc<str>`] (equivalently
1085/// [`Into<std::sync::Arc<str>>`]) axis — a future admission-webhook
1086/// running under `axum` + `tokio` whose per-arm structured-log field
1087/// crosses an `.await` boundary and demands the [`Sync`] +
1088/// [`Send`]-safe shared-ownership envelope [`std::sync::Arc<str>`]
1089/// provides (the sibling [`Box<str>`] axis's owned-move return-shape
1090/// forces every downstream `.clone()` through a heap allocation, while
1091/// [`std::sync::Arc<str>`]'s reference-counted shared-ownership
1092/// resolves the same `.clone()` through a refcount bump), a future
1093/// wasm-operator's per-supervisor reconciliation scheduler that
1094/// dispatches the same per-strategy diagnostic key onto multiple
1095/// concurrent reconcile-loop tasks holding shared-ownership through
1096/// [`std::sync::Arc<str>`], a future
1097/// `tracing::field::valuable::Value::Str(strategy.into())` structured-
1098/// log recorder whose typing folds a shared-ownership envelope onto
1099/// the span-context axis, a generic
1100/// `<T: Into<std::sync::Arc<str>>>`-bound diagnostic column on a
1101/// shared-ownership per-strategy cache — reaches the same four-arm
1102/// lifted [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
1103/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
1104/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
1105/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const
1106/// the sibling
1107/// `{Self, &Self} × {&'static str, String, Cow<'static, str>, Box<str>}`
1108/// forward-projection corner already returns.
1109///
1110/// First-mover on the substrate-wide trait-idiomatic
1111/// [`std::sync::Arc<str>`] forward-projection family — Rust's
1112/// standard library carries `impl From<&str> for std::sync::Arc<str>`
1113/// and `impl From<String> for std::sync::Arc<str>` but no blanket
1114/// `impl<T: AsRef<str>> From<T> for std::sync::Arc<str>` (nor an
1115/// `impl<T: fmt::Display> From<T> for std::sync::Arc<str>`), so every
1116/// closed-set fieldless typed enum on the substrate that carries the
1117/// paired [`AsRef<str>`] / [`std::fmt::Display`] /
1118/// [`From<Self> for &'static str`] / [`From<&Self> for &'static str`] /
1119/// [`From<Self> for String`] / [`From<&Self> for String`] /
1120/// [`From<Self> for Cow<'static, str>`] /
1121/// [`From<&Self> for Cow<'static, str>`] /
1122/// [`From<Self> for Box<str>`] / [`From<&Self> for Box<str>`] decet
1123/// but not the [`std::sync::Arc<str>`] axis forces every
1124/// `std::sync::Arc<str>`-parameterized call site through a
1125/// `std::sync::Arc::<str>::from(strategy.as_str())` open-code (or a
1126/// `std::sync::Arc::<str>::from(String::from(strategy))` two-step
1127/// composition through the owned-`String` axis that allocates
1128/// twice — once into the intermediate `String`, once into the
1129/// [`Arc<str>`] on the `From<String>` conversion) whose type bounds
1130/// have no compile-time link back to the substrate primitive. Opening
1131/// the axis on the first M2 OTP-shape closed-set fieldless typed enum
1132/// peer on the caixa substrate surface establishes the "route through
1133/// `as_str` via [`std::sync::Arc::<str>::from`] on the returned
1134/// `&'static str`" discipline; every future closed-set fieldless
1135/// typed enum peer on the substrate ([`RestartPolicy`],
1136/// [`crate::aplicacao::PlacementStrategy`],
1137/// [`crate::aplicacao::RateLimitUnit`], [`crate::aplicacao::WitShape`],
1138/// [`crate::dep::DepList`], [`crate::dialeto::CaixaDialeto`],
1139/// [`crate::kind::CaixaKind`],
1140/// [`crate::render::PathShapeViolation`], and the outside-`caixa-core`
1141/// peers `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`,
1142/// `Semantic`, `FerriteRuntime`) is a future target of the campaign,
1143/// tracking the same 14-peer emit-set every prior projection tier
1144/// ([`&'static str`], [`String`], [`Cow<'static, str>`], [`Box<str>`])
1145/// converged onto.
1146///
1147/// Peer of the sibling [`Box<str>`] forward-projection first-mover
1148/// (69ef45c) — same "opens a new substrate-wide projection tier"
1149/// discipline, extended onto the [`std::sync::Arc<str>`] axis whose
1150/// shared-ownership + [`Sync`] + [`Send`] contract is the distinct
1151/// value the [`Box<str>`] axis's owned-move return-shape cannot
1152/// provide.
1153///
1154/// Pinned load-bearing by
1155/// [`tests::restart_strategy_from_into_arc_str_routes_through_as_str_accessor`]
1156/// (byte-parity pin against [`RestartStrategy::as_str`] across the
1157/// four-arm [`RestartStrategy::ALL`] emit-set on the owned-input
1158/// surface, plus a blanket-derived [`Into`] shape witness and cross-
1159/// axis byte-parity pins against the sibling owned-input
1160/// `{&'static str, String, Cow<'static, str>, Box<str>}` return-shape
1161/// axes).
1162impl From<RestartStrategy> for std::sync::Arc<str> {
1163    fn from(strategy: RestartStrategy) -> std::sync::Arc<str> {
1164        std::sync::Arc::<str>::from(strategy.as_str())
1165    }
1166}
1167
1168/// Trait-idiomatic *borrowed-input, [`std::sync::Arc<str>`] output*
1169/// forward projection on the M2 OTP-shape sibling-restart
1170/// [`RestartStrategy`] closed-set fieldless typed enum — closes the
1171/// `{Self, &Self}` input-shape corner of the [`std::sync::Arc<str>`]
1172/// forward-projection axis on the first M2 OTP-shape closed-set
1173/// fieldless typed enum peer on the caixa surface
1174/// (`:supervisor :estrategia`), companion to the paired owned-input
1175/// [`From<RestartStrategy> for std::sync::Arc<str>`] impl one commit
1176/// prior (bca2ec8). Routes byte-for-byte through the
1177/// substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
1178/// accessor (via [`std::sync::Arc::<str>::from`] on the returned
1179/// `&'static str`), so every consumer that binds a
1180/// [`&RestartStrategy`] through the standard-library `.into()` /
1181/// [`From<&Self> for std::sync::Arc<str>`] (equivalently
1182/// [`Into<std::sync::Arc<str>>`]) axis — a future admission-webhook's
1183/// per-request borrowed-`&RestartStrategy` handle rendering a per-arm
1184/// `Sync` + `Send`-safe structured-log field across an `.await`
1185/// boundary through a `<T: Into<std::sync::Arc<str>>>`-bound
1186/// diagnostic-column dispatch, a future wasm-operator's per-
1187/// supervisor reconciliation pipeline whose
1188/// `.iter().map(std::sync::Arc::<str>::from)` collector reaches into
1189/// the shared-ownership per-strategy key without a spurious [`Copy`]
1190/// deref (which would only be reachable through the owned-input
1191/// [`From<RestartStrategy> for std::sync::Arc<str>`] axis by first
1192/// calling `.copied()` on the iterator), a future
1193/// `<T: Into<std::sync::Arc<str>>>`-bound `tracing`-span attributes
1194/// collector recording a borrowed-`&RestartStrategy` per-arm field
1195/// onto the parent span's shared-ownership context — reaches the
1196/// same four-arm lifted
1197/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
1198/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
1199/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
1200/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const
1201/// the paired owned-input
1202/// [`From<RestartStrategy> for std::sync::Arc<str>`] impl and the
1203/// sibling `{&'static str, String, Cow<'static, str>, Box<str>}`
1204/// forward-projection corner already return.
1205///
1206/// Second peer on the substrate-wide trait-idiomatic
1207/// [`std::sync::Arc<str>`] forward-projection family opened one
1208/// commit prior (bca2ec8) on the paired owned-input
1209/// [`From<RestartStrategy> for std::sync::Arc<str>`] impl — closes
1210/// the `{Self, &Self}` input-shape corner of the
1211/// [`std::sync::Arc<str>`] axis on the first M2 OTP-shape closed-set
1212/// fieldless typed enum peer on the caixa surface, exactly as
1213/// 59ae5dc closed the paired [`Box<str>`] axis one commit after its
1214/// owning half (69ef45c) landed. Rust's standard library carries
1215/// `impl From<&str> for std::sync::Arc<str>` and
1216/// `impl From<String> for std::sync::Arc<str>` but no blanket
1217/// `impl<T: AsRef<str>> From<&T> for std::sync::Arc<str>` (nor a
1218/// `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`), so
1219/// every closed-set fieldless typed enum peer on the substrate that
1220/// carries the paired owned-input [`std::sync::Arc<str>`] axis but
1221/// not the borrowed-input axis forces every borrowed-input
1222/// [`std::sync::Arc<str>`]-parameterized call site through a
1223/// spurious [`Copy`] deref
1224/// (`std::sync::Arc::<str>::from((*strategy).as_str())`) or a
1225/// `std::sync::Arc::<str>::from(strategy.as_str())` open-code whose
1226/// type bounds have no compile-time link back to the substrate
1227/// primitive.
1228///
1229/// Pinned load-bearing by
1230/// [`tests::restart_strategy_from_borrowed_into_arc_str_routes_through_as_str_accessor`]
1231/// (byte-parity pin against [`RestartStrategy::as_str`] across the
1232/// four-arm [`RestartStrategy::ALL`] emit-set on the borrowed-input
1233/// surface, plus a blanket-derived [`Into`] shape witness and a
1234/// cross-axis pin against the paired owned-input
1235/// [`From<RestartStrategy> for std::sync::Arc<str>`] and the sibling
1236/// borrowed-input `{&'static str, String, Cow<'static, str>,
1237/// Box<str>}` return-shape axes).
1238impl From<&RestartStrategy> for std::sync::Arc<str> {
1239    fn from(strategy: &RestartStrategy) -> std::sync::Arc<str> {
1240        std::sync::Arc::<str>::from(strategy.as_str())
1241    }
1242}
1243
1244/// Per-child restart policy.
1245///
1246/// Permanent / Temporary / Transient match Erlang/OTP semantics 1:1.
1247#[derive(
1248    Serialize,
1249    Deserialize,
1250    Debug,
1251    Clone,
1252    Copy,
1253    PartialEq,
1254    Eq,
1255    Hash,
1256    gen_platform::TypedDispatcher,
1257    gen_platform::Discriminant,
1258    gen_platform::IsVariant,
1259    gen_platform::FromStrKind,
1260)]
1261pub enum RestartPolicy {
1262    /// Always restart the child, regardless of how it died. Used for
1263    /// long-running services that must always be up.
1264    Permanent,
1265    /// Never restart. Used for one-shot work whose completion is
1266    /// itself the success signal (`oneShot` triggers map here).
1267    Temporary,
1268    /// Restart only when the child died *abnormally* (non-zero exit
1269    /// or unhandled exception). A clean exit completes the child.
1270    Transient,
1271}
1272
1273impl Default for RestartPolicy {
1274    fn default() -> Self {
1275        // Route the [`Default for RestartPolicy`] impl's return arm through
1276        // the substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed
1277        // `pub const` rather than a raw `Self::Permanent` arm — one source
1278        // of truth for the Erlang/OTP-canonical `permanent` worker-child
1279        // default across the two production consumers that currently
1280        // dispatch on it (this impl at the [`RestartPolicy::default`] call
1281        // and the serde-side `#[serde(default)]` on
1282        // [`ChildSpec::restart`] that resolves an author-omitted
1283        // `:children :restart` slot through `RestartPolicy::default()`).
1284        // Peer of the sibling per-`:supervisor` axis
1285        // [`Default for RestartStrategy`] → [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
1286        // route (95ffacc) — the two impls now share one substrate-primitive
1287        // lift discipline, so any future coherent rebrand of the OTP-shape
1288        // supervisor+child default set migrates through typed constants in
1289        // lockstep instead of splitting a lifted supervisor half against
1290        // an open-coded child half. Pinned by
1291        // `restart_policy_default_routes_through_lifted_default` +
1292        // `child_spec_serde_default_restart_routes_through_lifted_default`
1293        // in the tests module.
1294        SUPERVISOR_CHILD_RESTART_DEFAULT
1295    }
1296}
1297
1298impl RestartPolicy {
1299    /// Exhaustive iteration surface for every consumer that walks the
1300    /// closed three-arm [`RestartPolicy`] discriminator set (the future
1301    /// M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
1302    /// per-child admission-webhook rejection body naming the accepted-
1303    /// `:restart` list, a future `feira supervisor --restart …` CLI
1304    /// arg-parse's "did you mean" hint via a [`Self::from_wire`]-scan
1305    /// over the slice, the future `feira app graph` per-child restart
1306    /// column, any future round-trip fuzz harness that sweeps every
1307    /// arm). A future arm addition (an OTP-`intrinsic` fourth arm the
1308    /// theory
1309    /// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1310    /// might reach for once the three canonical OTP restart policies
1311    /// stop covering the substrate's discovered load-shape) extends
1312    /// this slice as one edit and every consumer picks up the new entry
1313    /// by construction; the compiler-checked exhaustiveness on the
1314    /// sibling method `match` arms ([`Self::as_str`] / [`Self::from_wire`])
1315    /// is the build-time guarantee that no arm forgets to grow.
1316    ///
1317    /// Peer of the sibling closed-set typed enums'
1318    /// [`RestartStrategy::ALL`] (4eec29c) /
1319    /// [`crate::CaixaKind::ALL`] (6b1f4fb) /
1320    /// [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
1321    /// [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
1322    /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
1323    /// surfaces — the sixth (and the third and final M2 OTP-shape)
1324    /// closed-set typed enum on the caixa surface to converge onto the
1325    /// same one-canonical-arm-list-per-enum discipline. Sibling axis to
1326    /// the peer [`RestartStrategy::ALL`] on the per-supervisor
1327    /// sibling-restart-strategy axis; this closes the per-child
1328    /// restart-decision-policy axis on the same M2 `:supervisor` slot.
1329    pub const ALL: &'static [Self] = &[Self::Permanent, Self::Temporary, Self::Transient];
1330
1331    /// Canonical PascalCase discriminator scalar this variant serializes
1332    /// as under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`]. The three
1333    /// arms return the paired
1334    /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1335    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1336    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] lifted
1337    /// constants so every substrate consumer that dispatches on the
1338    /// per-child restart-decision policy (the future wasm-operator's
1339    /// per-child post-exit restart-decision branch, the future M4
1340    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
1341    /// admission-time enum-arm bind, the `caixa-operator`'s hierarchical
1342    /// reconciliation scheduler's per-child-policy fan-out) reads the
1343    /// same byte-string the `Serialize` derive emits — the pin test in
1344    /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
1345    /// asserts the two paths agree, peer of the M2
1346    /// [`RestartStrategy::as_str`] (09ffb2d) on the sibling per-supervisor
1347    /// sibling-restart-strategy axis and the M3
1348    /// [`crate::aplicacao::PlacementStrategy::as_str`] (cc8f749) on the
1349    /// per-Aplicacao distribution-strategy axis — the third of three
1350    /// OTP-shaped closed-enum discriminator axes on the caixa typed
1351    /// surface to converge onto the same three-path-convergence
1352    /// (`Serialize` derive → `as_str` helper → lifted constant)
1353    /// drift-detection posture.
1354    #[must_use]
1355    pub const fn as_str(self) -> &'static str {
1356        match self {
1357            Self::Permanent => crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
1358            Self::Temporary => crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
1359            Self::Transient => crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
1360        }
1361    }
1362
1363    /// Substrate-canonical reverse projection on the `:children :restart`
1364    /// closed-set axis — parses the `PascalCase` discriminator scalar
1365    /// back to the typed variant, or `None` when `s` is outside the
1366    /// closed-set arm-string set [`Self::as_str`] emits. Dispatches on
1367    /// the same lifted
1368    /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1369    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1370    /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] constants
1371    /// the [`Self::as_str`] emitter walks, so the parse and emit halves
1372    /// of the round-trip migrate through one caixa-core edit on any
1373    /// future arm addition.
1374    ///
1375    /// Prior to this lift the substrate carried only the forward
1376    /// `Self → &str` projection on the OTP per-child restart-policy
1377    /// axis (the [`Self::as_str`] emitter, the [`std::fmt::Display`]
1378    /// impl routed through it, the `Serialize` derive that emits the
1379    /// same byte-string under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`])
1380    /// plus the kebab-case dispatcher-catalog identity via
1381    /// [`Self::discriminant`] — every non-serde consumer that wanted to
1382    /// parse a wire-form `PascalCase` policy scalar had to re-inline a
1383    /// three-arm `match s { "Permanent" => …, "Temporary" => …,
1384    /// "Transient" => …, _ => … }` cascade that expressed no
1385    /// compile-time link back to the typed variant's canonical lifted
1386    /// constant. A future variant rename or per-arm serde-attribute
1387    /// drift would silently split the wire byte-string one non-serde
1388    /// consumer parsed from the one the emitter wrote, with the failure
1389    /// surfacing at the operator's reconcile posture (a `:temporary`
1390    /// `oneShot` child being restarted on clean exit, treating the
1391    /// successful-completion signal as failure and re-running the
1392    /// completion-terminal one-shot indefinitely; a `:transient` child
1393    /// that clean-exited being restarted, masking the clean-completion
1394    /// contract) far from the rebrand commit and with no field naming
1395    /// the drift.
1396    ///
1397    /// Distinct axis from the [`std::str::FromStr`] impl the
1398    /// [`gen_platform::FromStrKind`] derive already installs on this
1399    /// enum by design, not by drift: `FromStr` parses the *kebab-case*
1400    /// dispatcher-catalog identity (`"permanent"` / `"temporary"` /
1401    /// `"transient"` — the inverse of [`Self::discriminant`]), while
1402    /// this method inverts the `PascalCase` wire byte-string
1403    /// [`Self::as_str`] emits. The two-axis split lets the dispatcher-
1404    /// catalog identity live in kebab-case (where every peer catalog
1405    /// identifier already lives) without forcing a wire-format rename
1406    /// on the tatara-lisp author surface (`:restart Permanent`,
1407    /// `PascalCase`) — the same two-axis distinction the sibling
1408    /// [`RestartStrategy::from_wire`] (4eec29c) /
1409    /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
1410    /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
1411    /// carry on their peer closed-set typed-enum wire round-trips.
1412    ///
1413    /// Same closed-set-reverse-projection discipline the sibling
1414    /// [`RestartStrategy::from_wire`] (4eec29c) /
1415    /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
1416    /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342) /
1417    /// [`crate::aplicacao::RateLimitUnit::from_suffix`] typed enums
1418    /// carry on the peer wire-side `str → Self` axes — extended onto
1419    /// the M2 OTP-shape per-child restart-policy closed-set axis, the
1420    /// sixth substrate-side closed-set typed enum (and the third and
1421    /// final OTP-shape closed-enum discriminator axis) to converge on
1422    /// the two-way `str ↔ Self` round-trip. Method-named `from_wire`
1423    /// (not `from_str`) to match the peer [`RestartStrategy::from_wire`]
1424    /// shape verbatim and side-step the [`std::str::FromStr`] impl the
1425    /// derive already installs on the sibling kebab-case axis. Returns
1426    /// `Option<Self>` (rather than `Result<Self, _>`) to match the peer
1427    /// shapes: the caller picks the diagnostic form appropriate for
1428    /// its use site.
1429    #[must_use]
1430    pub fn from_wire(s: &str) -> Option<Self> {
1431        match s {
1432            crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT => Some(Self::Permanent),
1433            crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY => Some(Self::Temporary),
1434            crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT => Some(Self::Transient),
1435            _ => None,
1436        }
1437    }
1438}
1439
1440/// [`std::fmt::Display`] routed through [`RestartPolicy::as_str`], so the
1441/// pretty-printed byte-string every consumer that formats the policy as
1442/// user-facing text lands on (the future wasm-operator's per-child
1443/// post-exit restart-decision diagnostic line, the future `feira app
1444/// graph` per-child restart column, the future M4
1445/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
1446/// admission-webhook rejection body) reaches for the same lifted
1447/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1448/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1449/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1450/// wire-format `Serialize` derive already emits under
1451/// [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
1452/// [`RestartPolicy::as_str`] helper already returns.
1453///
1454/// Pre-convergence the two paths structurally disagreed — the
1455/// `#[derive(gen_platform::Discriminant)]` + `#[discriminant(also_display)]`
1456/// route (now retired here) sent [`std::fmt::Display`] through the
1457/// gen-platform discriminant catalog string, which arrives kebab-case as
1458/// `"permanent"` / `"temporary"` / `"transient"` on this three-arm enum
1459/// (whose variant names each collapse to their own lowercase form under
1460/// the kebab-case transform), while the wire format ran as `PascalCase`
1461/// `"Permanent"` / `"Temporary"` / `"Transient"` through the un-`rename`d
1462/// serde derive. Every consumer that formatted the policy for a
1463/// diagnostic line, a graph column, or a rejection body under
1464/// `format!("{v}")` therefore landed under a different byte-string than
1465/// the wire format the operator's per-child-policy dispatch keyed off —
1466/// a silent split whose apply-time symptom (a `format!("{v}")`-carrying
1467/// diagnostic quoting `"permanent"` while the wire scalar the operator
1468/// probed was `"Permanent"`) surfaced as a confused correlate at
1469/// operator-log time far from the two-declaration site.
1470///
1471/// Routing `Display` through [`RestartPolicy::as_str`] closes the third
1472/// path: every `format!("{v}")` call reaches the same lifted
1473/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the wire format
1474/// and the [`RestartPolicy::as_str`] helper route through — `Debug` (the
1475/// compiler-derived variant name), `Display` (via `as_str`), and `Serialize`
1476/// (via the un-`rename`d derive) all resolve to the same `PascalCase`
1477/// byte-string per variant. A future variant rename or
1478/// `#[serde(rename_all = "kebab-case")]` attribute reaches every path at
1479/// exactly one place, structurally.
1480///
1481/// The dispatcher-catalog identity remains kebab-case — [`Self::discriminant`]
1482/// (from `#[derive(gen_platform::Discriminant)]`) still returns
1483/// `"permanent"` / `"temporary"` / `"transient"`, and the fleet-wide
1484/// [`gen_platform::register_dispatcher!("caixa.restart-policy", …)`]
1485/// registration keys the catalog off the same kebab identity. The two
1486/// naming worlds now live on separate typed methods (`Display` /
1487/// `as_str` for the wire byte-string, `discriminant` for the catalog
1488/// identity) rather than sharing one `Display` route that structurally
1489/// disagrees with the wire format.
1490///
1491/// Pin tests
1492/// [`tests::restart_policy_display_routes_through_as_str_helper`]
1493/// and
1494/// [`tests::restart_policy_display_matches_serialized_wire_byte_string`]
1495/// assert the three paths agree byte-for-byte on every variant, so a
1496/// future variant rename or per-arm serde attribute drift is a build
1497/// error visible at caixa-core test time, not a silent per-consumer
1498/// dispatch miss at apply / reconcile time.
1499///
1500/// Mirrors the M3 [`crate::aplicacao::PlacementStrategy`] `Display` impl
1501/// (aplicacao.rs:2306) on the per-Aplicacao distribution-strategy axis
1502/// and the sibling [`RestartStrategy`] `Display` impl on the
1503/// per-supervisor sibling-restart-strategy axis — same three-path-
1504/// convergence discipline, extended to close the third and final of
1505/// three OTP-shaped closed-enum discriminator axes on the caixa typed
1506/// surface.
1507impl std::fmt::Display for RestartPolicy {
1508    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1509        f.write_str(self.as_str())
1510    }
1511}
1512
1513/// Substrate-canonical [`AsRef<str>`] projection on the M2
1514/// per-child-restart-policy [`RestartPolicy`] closed-set typed enum —
1515/// routes through the same [`RestartPolicy::as_str`] `pub const fn`
1516/// scalar accessor the paired [`std::fmt::Display`] impl and the
1517/// un-`rename`d [`serde::Serialize`] derive already key off, so any
1518/// future consumer that binds a [`RestartPolicy`] through the
1519/// standard-library `impl AsRef<str>` bound (a future
1520/// [`caixa-feira`] `feira supervisor --restart <arm>` verb that
1521/// composes the emitted `PascalCase` wire scalar into a
1522/// [`std::process::Command::arg`] shell-out of the future
1523/// wasm-operator's per-child admission gate, a per-child structured-
1524/// log recorder on the future `caixa-operator`'s hierarchical
1525/// reconciliation surface that accepts `impl AsRef<str>` at the
1526/// `tracing::field::Value` `Str`-arm, a [`std::collections::HashMap`]
1527/// lookup keyed on the restart-policy wire byte through
1528/// `map.get::<str>(policy.as_ref())` on a future per-policy
1529/// dispatch table) reaches the paired
1530/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1531/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1532/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
1533/// lifted-const through one substrate-primitive dispatch rather
1534/// than an open-coded `.as_str()` projection at every wire-up.
1535///
1536/// Peer of the sibling [`std::fmt::Display`] impl on the same
1537/// primitive — both delegate to the shared [`RestartPolicy::as_str`]
1538/// `pub const fn` accessor, so [`format!("{v}")`], `v.as_str()`, and
1539/// `<RestartPolicy as AsRef<str>>::as_ref(&v)` resolve to the same
1540/// byte-string per instance by construction. A future variant rename
1541/// or `#[serde(rename_all = "kebab-case")]` attribute-drift on the
1542/// enum reaches every one of the three paths (plus the wire-format
1543/// `Serialize` derive that already routes through the same lifted
1544/// const) through exactly one caixa-core edit.
1545///
1546/// Same "route the trait impl through the substrate-primitive
1547/// accessor" discipline the sibling [`crate::CaixaVersion`]
1548/// [`AsRef<str>`] impl (16d5c7e) and the paired M2
1549/// [`RestartStrategy`] [`AsRef<str>`] impl (63eb1a4) carry — extends
1550/// the axis onto the paired per-child-restart-decision-policy
1551/// sibling on the same M2 `:supervisor` slot (the second M2
1552/// OTP-shape closed-set typed enum to converge onto the standard-
1553/// library [`AsRef<str>`] projection). Rust-side newtype/typed-enum
1554/// convention pairs [`AsRef<str>`] and [`fmt::Display`] on the same
1555/// primitive so a caller who has one has both; before this lift,
1556/// [`RestartPolicy`] carried [`fmt::Display`] but not the paired
1557/// [`AsRef<str>`] impl the convention names.
1558///
1559/// Pinned load-bearing by
1560/// [`tests::restart_policy_as_ref_str_routes_through_as_str_accessor`]
1561/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1562/// three-arm closed set) and
1563/// [`tests::restart_policy_as_ref_str_routes_through_display_via_shared_accessor`]
1564/// (three-path convergence: `AsRef<str>` + `Display` + `as_str` all
1565/// resolve to the same lifted `SUPERVISOR_CHILD_RESTART_*` const per
1566/// arm) — any future silent detour that routes the impl through a
1567/// divergent projection (a per-arm inline `match self { … }`
1568/// re-inlining that opens a compile-time link to the un-lifted
1569/// arm-literal, a swap onto the kebab-case
1570/// [`gen_platform::Discriminant`] catalog identity that would
1571/// collide the wire axis with the dispatcher-catalog axis) trips at
1572/// caixa-core test time under `assert_eq!` rather than at a
1573/// downstream `impl AsRef<str>`-bound consumer's silent split.
1574impl AsRef<str> for RestartPolicy {
1575    fn as_ref(&self) -> &str {
1576        self.as_str()
1577    }
1578}
1579
1580/// Trait-idiomatic reverse projection on the M2-OTP-shape per-child
1581/// restart-policy [`RestartPolicy`] closed-set typed enum — routes
1582/// byte-for-byte through the paired substrate-primitive
1583/// [`RestartPolicy::from_wire`] `Option<Self>` accessor so every future
1584/// consumer that binds a `PascalCase` `:children :restart` wire
1585/// byte-string through the standard-library `.try_into()` / [`TryFrom`]
1586/// axis (a future [`caixa-feira`] `feira supervisor --restart
1587/// <Permanent|Temporary|Transient>` CLI arg-parse that composes into
1588/// `let restart: RestartPolicy = s.try_into()?`, a future
1589/// `mesh.pleme.io/v1alpha1/Supervisor` CR admission-webhook that folds a
1590/// `spec.children[*].restart: String` field through
1591/// `RestartPolicy::try_from(&s)?`, a generic
1592/// `<T: TryFrom<&str>>`-bound loader over any of the substrate's closed-
1593/// set typed enums) reaches the same three-arm accept-set the sibling
1594/// [`RestartPolicy::from_wire`] resolver parses through and the sibling
1595/// [`RestartPolicy::as_str`] emits, rather than an open-coded per-arm
1596/// `match s { "Permanent" => …, "Temporary" => …, "Transient" => …, _ =>
1597/// … }` cascade whose arm-set has no compile-time link back to the
1598/// substrate primitive.
1599///
1600/// Complements the pre-existing forward-projection triple
1601/// ([`std::fmt::Display`], [`AsRef<str>`], [`RestartPolicy::as_str`])
1602/// with the paired trait-idiomatic reverse-projection axis: Rust-side
1603/// newtype/typed-enum convention pairs [`AsRef<str>`] with either
1604/// [`std::str::FromStr`] or [`TryFrom<&str>`] on the same primitive so a
1605/// caller who can project *out to* a `&str` can also project *in from*
1606/// one. The [`TryFrom<&str>`] axis is deliberately chosen over
1607/// [`std::str::FromStr`] to sidestep the `clippy::should_implement_trait`
1608/// lint the sibling method-named [`RestartPolicy::from_wire`] would
1609/// trigger under a `FromStr` impl and to avoid colliding with the
1610/// [`std::str::FromStr`] impl the [`gen_platform::FromStrKind`] derive
1611/// already installs on the paired *kebab-case dispatcher-catalog* axis
1612/// (which parses `"permanent"` / `"temporary"` / `"transient"`, the
1613/// inverse of [`Self::discriminant`]) — this impl closes the trait-
1614/// idiomatic reverse axis on the *`PascalCase` wire* half without
1615/// disturbing either the method-named `from_wire` shape every sibling
1616/// closed-set typed enum on the substrate already carries or the
1617/// pre-existing `FromStr` on the dispatcher-catalog half, keeping the
1618/// two-axis split the sibling [`Self::from_wire`] doc block motivates.
1619///
1620/// `type Error = ()` matches the sibling [`RestartPolicy::from_wire`]'s
1621/// `Option<Self>` return-shape's deliberate deferral of error typing: the
1622/// caller picks the diagnostic form appropriate for its use site (a
1623/// future `feira supervisor --restart` arg-parse composes its own
1624/// per-verb "unknown restart: <arg> — accepted: {…}" message enumerating
1625/// [`RestartPolicy::ALL`], a future M4 admission-webhook rejection body
1626/// wraps the `Err(())` outcome with the accepted-set enumeration for
1627/// operator diagnostics, a `Result::map_err` at the call site lifts the
1628/// unit-error to a per-verb error type). Same shape the peer
1629/// [`RestartStrategy`] (5b828ed) on the sibling per-supervisor axis,
1630/// [`crate::CaixaKind`] (3c83606), [`crate::CaixaDialeto`] (bf33136), and
1631/// [`crate::aplicacao::PlacementStrategy`] (6fd00cd) blocks motivate on
1632/// their peer closed-set typed enums' reverse projections.
1633///
1634/// The paired [`TryFrom<&str>`] impl reaches the same three-arm accept-
1635/// set the [`RestartPolicy::from_wire`] resolver dispatches through, so
1636/// any future arm addition (an OTP-`intrinsic` fourth arm the theory
1637/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1638/// might reach for once the three canonical OTP restart policies stop
1639/// covering the substrate's discovered load-shape) grows the trait-
1640/// idiomatic axis by construction — one caixa-core edit on
1641/// [`RestartPolicy::from_wire`] extends both the method-named reverse
1642/// projection every existing consumer keys off and the trait-idiomatic
1643/// reverse projection this impl exposes, without a coordinated rewrite
1644/// across every future `TryFrom<&str>`-bound consumer's arm-set.
1645///
1646/// Extends the substrate-wide closed-set-enum reverse-projection family
1647/// ([`crate::CaixaKind`] via 3c83606, [`crate::CaixaDialeto`] via
1648/// bf33136, [`crate::aplicacao::PlacementStrategy`] via 6fd00cd, and
1649/// [`RestartStrategy`] via 5b828ed) onto the third and final OTP-shape
1650/// closed-enum discriminator axis on the caixa surface — the paired
1651/// per-child `:children :restart` closed set the future wasm-operator's
1652/// hierarchical reconciliation scheduler's per-child post-exit
1653/// restart-decision branch keys off end-to-end.
1654///
1655/// Pinned load-bearing by
1656/// [`tests::restart_policy_try_from_str_routes_through_from_wire_accessor`]
1657/// (byte-parity pin against [`RestartPolicy::from_wire`] across the
1658/// three-arm accept-set),
1659/// [`tests::restart_policy_try_from_str_rejects_unknown_byte_strings`]
1660/// (rejection witness against silent accept-set widening), and
1661/// [`tests::restart_policy_try_from_str_and_from_wire_partition_the_accept_set`]
1662/// (cross-axis partition pin locking the trait and method-named
1663/// projections onto one accept-set).
1664impl TryFrom<&str> for RestartPolicy {
1665    type Error = ();
1666
1667    fn try_from(s: &str) -> Result<Self, Self::Error> {
1668        Self::from_wire(s).ok_or(())
1669    }
1670}
1671
1672/// Trait-idiomatic forward projection on the M2-OTP-shape per-child
1673/// restart-policy [`RestartPolicy`] closed-set typed enum — routes
1674/// byte-for-byte through the paired substrate-primitive
1675/// [`RestartPolicy::as_str`] `pub const fn` accessor. Return type is
1676/// `&'static str` by construction — every [`RestartPolicy::as_str`] arm
1677/// resolves to a [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const
1678/// &str` with `'static` lifetime, so the trait's return-type promise is
1679/// upheld structurally without a [`String::leak`] cast or a per-arm inline
1680/// literal.
1681///
1682/// Every future consumer that specifically needs `&'static str` lifetime
1683/// bytes on the per-child restart-decision axis (a
1684/// [`tracing::field::valuable::Value::Str`] recording where the `Str`
1685/// arm's typing demands `&'static str`, a
1686/// [`std::borrow::Cow::Borrowed`]`::<'static, str>(policy.into())` composer
1687/// on the future M4 admission-webhook rejection body where the
1688/// `Cow<'static, str>` typing rules out the sibling [`AsRef<str>`]
1689/// borrowed return, a generic `<T: Into<&'static str>>`-bound serializer
1690/// or error formatter that requires the `'static` bound) reaches the same
1691/// lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1692/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1693/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] substrate-
1694/// primitive dispatch rather than an open-coded per-arm literal cascade
1695/// whose arm-set has no compile-time link back to the substrate primitive.
1696///
1697/// Peer of the sibling M2-OTP-shape [`RestartStrategy`] forward-projection
1698/// impl (523157d) on the per-supervisor sibling-restart-strategy axis —
1699/// the second (and second-of-two-in-M2) closed-set typed enum on the
1700/// caixa surface to converge onto the paired trait-idiomatic forward-
1701/// projection axis. With this lift the paired per-child
1702/// `:children :restart` closed-set typed enum carries the full sibling
1703/// quintet ([`std::fmt::Display`], [`AsRef<str>`], [`Self::as_str`],
1704/// [`TryFrom<&str>`] via 6fdd0d9, `From<Self> for &'static str` via this
1705/// lift) plus the round-trip witness through both the trait-idiomatic
1706/// (`From<Self> for &'static str` + `TryFrom<&str>`) and the method-named
1707/// (`as_str` + `from_wire`) axis pairs — mirrors the sibling
1708/// [`RestartStrategy`] surface arm-for-arm, so every future arm addition
1709/// (an OTP-`intrinsic` fourth arm the theory
1710/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1711/// might reach for once the three canonical OTP restart policies stop
1712/// covering the substrate's discovered load-shape) grows the trait-
1713/// idiomatic forward axis by construction: one caixa-core edit on
1714/// [`RestartPolicy::as_str`] extends every one of the five sibling
1715/// forward-projection paths ([`std::fmt::Display`], [`AsRef<str>`],
1716/// [`Self::as_str`] itself, this `From<Self> for &'static str`, and the
1717/// un-`rename`d [`serde::Serialize`] derive that also emits `as_str`'s
1718/// bytes) without a coordinated rewrite across every future
1719/// `Into<&'static str>`-bound consumer's arm-set.
1720///
1721/// Pinned load-bearing by
1722/// [`tests::restart_policy_from_into_static_str_routes_through_as_str_accessor`]
1723/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1724/// three-arm emit-set, plus a `const`-context materialization witness for
1725/// the `&'static str` lifetime promise) and
1726/// [`tests::restart_policy_from_into_static_str_and_as_str_partition_the_emit_set`]
1727/// (partition pin asserting `<&'static str as From<RestartPolicy>>::from`
1728/// and [`RestartPolicy::as_str`] agree on every arm, plus a two-way
1729/// round-trip witness through the paired trait-idiomatic reverse-
1730/// projection axis [`TryFrom<&str>`] (6fdd0d9): every
1731/// `policy.into::<&'static str>()` output re-parses back through
1732/// [`RestartPolicy::try_from`] to the original variant, closing the two-
1733/// way `Self ↔ &'static str` round-trip on the trait-idiomatic axis pair).
1734impl From<RestartPolicy> for &'static str {
1735    fn from(policy: RestartPolicy) -> &'static str {
1736        policy.as_str()
1737    }
1738}
1739
1740/// Trait-idiomatic *forward* projection on [`RestartPolicy`] from a
1741/// *borrowed* input onto the `&'static str` axis — the borrowed-input
1742/// companion to the paired owned-input [`From<RestartPolicy> for
1743/// &'static str`] impl immediately above. Routes byte-for-byte through
1744/// the same substrate-primitive [`RestartPolicy::as_str`] `pub const
1745/// fn` accessor so every consumer that binds a `&RestartPolicy`
1746/// through the standard-library `.into()` / [`From<&Self> for &'static
1747/// str`] axis (a `RestartPolicy::ALL.iter().map(<&'static
1748/// str>::from).collect::<Vec<_>>()` per-arm accept-set materializer —
1749/// whose iterator over `&'static [RestartPolicy]` yields
1750/// `&RestartPolicy`, not `RestartPolicy`, so the owned-input
1751/// [`From<RestartPolicy>`] axis alone forces every call site through
1752/// an explicit `.copied()` / dereference / [`Copy`]-bound restatement
1753/// rather than the direct trait-idiomatic projection; a future generic
1754/// `<T: Copy + for<'a> Into<&'static str>>`-bound diagnostic column
1755/// that walks the `iter().map(Into::into)` shape verbatim across every
1756/// substrate-wide closed-set typed enum; the future wasm-operator's
1757/// per-child post-exit restart-decision diagnostic line that composes
1758/// the accepted-set enumeration from an iterated
1759/// `RestartPolicy::ALL.iter().map(|p| p.into())` pipe rather than a
1760/// per-arm `match p { … }` cascade; a future
1761/// `HashMap::<&'static str, RestartPolicy>::from_iter(
1762///     RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))`-style
1763/// per-policy reverse-lookup table the sibling [`TryFrom<&str>`] impl
1764/// cannot compose without this borrowed-input axis in place) reaches
1765/// the same three-arm lifted
1766/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1767/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1768/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1769/// paired owned-input [`From<RestartPolicy> for &'static str`], the
1770/// sibling [`std::fmt::Display`], [`AsRef<str>`], and
1771/// [`RestartPolicy::as_str`] surfaces already return.
1772///
1773/// Fifth peer on the substrate-wide trait-idiomatic *borrowed-input*
1774/// forward-projection family opened on [`crate::dep::DepList`]
1775/// (64aa742) and extended onto [`crate::CaixaKind`] (5ab993a),
1776/// [`crate::CaixaDialeto`] (807b0b5), and the paired
1777/// per-supervisor sibling-restart-strategy [`RestartStrategy`]
1778/// (e941836). Rust's `From` trait does not auto-derive the
1779/// `From<&Self>` sibling from a `From<Self>` impl (the blanket
1780/// `impl<T, U> From<&T> for U where T: Copy, U: From<T>` does not
1781/// exist in `core`), so every closed-set typed enum that carries the
1782/// owned-input axis but not the borrowed-input axis forces every
1783/// borrowed-input call site through a `.copied()` /
1784/// `<&'static str>::from(*policy)` / `policy.as_str()` detour whose
1785/// type bounds have no compile-time link to the substrate primitive.
1786/// [`RestartPolicy`] is the second (and second-of-two-in-M2)
1787/// OTP-shape peer to converge onto this campaign — sibling of the
1788/// paired per-supervisor [`RestartStrategy`] borrowed-input axis, so
1789/// with this lift both closed-set typed enums on the M2 `:supervisor`
1790/// slot now carry the full sibling quintet ([`std::fmt::Display`],
1791/// [`AsRef<str>`], [`Self::as_str`], `From<Self> for &'static str`,
1792/// `From<&Self> for &'static str`) plus the paired trait-idiomatic
1793/// reverse projection [`TryFrom<&str>`], closing the borrowed-input
1794/// forward-projection axis on the M2 OTP-shape slot as a unit.
1795///
1796/// Same three-path convergence discipline as the paired owned-input
1797/// impl (this borrowed-input axis, the paired owned-input
1798/// [`From<RestartPolicy> for &'static str`], and
1799/// [`RestartPolicy::as_str`] all route through the same lifted
1800/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const), so a future
1801/// variant rename or per-arm serde-attribute drift reaches every one
1802/// of the six sibling forward-projection paths
1803/// ([`std::fmt::Display`], [`AsRef<str>`], [`Self::as_str`],
1804/// [`From<Self> for &'static str`], this [`From<&Self> for &'static
1805/// str`], and the un-`rename`d [`serde::Serialize`] derive that also
1806/// emits [`Self::as_str`]'s bytes) through exactly one caixa-core
1807/// edit.
1808///
1809/// The [`RestartPolicy::as_str`] emit and [`RestartPolicy::from_wire`]
1810/// parse share the same `PascalCase` vocabulary by construction, so
1811/// the borrowed-input forward axis and the reverse axis compose
1812/// directly — the round-trip witness pin below locks this direct
1813/// composition without the intermediate wire-vocab hop the peer
1814/// [`crate::CaixaKind`] axis pair requires.
1815///
1816/// Pinned load-bearing by
1817/// [`tests::restart_policy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
1818/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1819/// three-arm emit-set via a borrowed input, plus a `const`-context
1820/// materialization witness for the `&'static str` lifetime promise,
1821/// plus a blanket `.into()` shape) and
1822/// [`tests::restart_policy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
1823/// (cross-axis partition pin against the paired owned-input
1824/// [`From<RestartPolicy> for &'static str`] impl, plus a
1825/// `.iter().map(Into::into)` pipe witness over
1826/// [`RestartPolicy::ALL`], plus a direct round-trip witness through
1827/// [`TryFrom<&str>`] that closes the two-way `&Self → &'static str →
1828/// Self` round-trip without the wire-vocab intermediate the peer
1829/// [`crate::CaixaKind`] axis pair requires).
1830impl From<&RestartPolicy> for &'static str {
1831    fn from(policy: &RestartPolicy) -> &'static str {
1832        policy.as_str()
1833    }
1834}
1835
1836/// Trait-idiomatic *owned-`String`* forward projection on the second
1837/// M2 OTP-shape closed-set typed enum ([`RestartPolicy`]) — the
1838/// owned-heap-string companion to the paired `&'static str`-returning
1839/// [`From<RestartPolicy> for &'static str`] / [`From<&RestartPolicy>
1840/// for &'static str`] impls immediately above. Routes byte-for-byte
1841/// through the substrate-primitive [`RestartPolicy::as_str`] `pub
1842/// const fn` accessor (via [`str::to_owned`]) so every consumer that
1843/// binds a [`RestartPolicy`] through the standard-library `.into()` /
1844/// [`From<Self> for String`] (equivalently [`Into<String>`]) axis — a
1845/// future `serde_json::Value::String(policy.into())` structured-payload
1846/// composer where the `Value::String` arm typing demands an owned
1847/// [`String`] and the sibling [`&'static str`]-returning axis forces
1848/// an explicit `.to_owned()` / `String::from` restatement at every
1849/// call site, a future `HashMap::<String, RestartPolicy>::from_iter(
1850/// RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))` per-policy
1851/// lookup where the map's key type is owned [`String`] rather than
1852/// [`&'static str`], a future `Cow::<'static, str>::Owned(policy.into())`
1853/// composer on the future M4 admission-webhook rejection body's
1854/// owned-arm, the future wasm-operator's per-child post-exit
1855/// diagnostic emit `serde_json::json!({ "restart": policy })` where the
1856/// JSON serializer's `Serialize` impl on [`String`] owns the emit-path
1857/// — reaches the same three-arm lifted
1858/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1859/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1860/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1861/// paired [`std::fmt::Display`], [`AsRef<str>`],
1862/// [`RestartPolicy::as_str`], and the two `&'static str`-returning
1863/// forward-projection impls already return.
1864///
1865/// Extends the trait-idiomatic *owned-`String`* forward-projection
1866/// axis onto the second-of-two M2 OTP-shape closed-set typed enums on
1867/// the caixa surface — mirror of the first-mover
1868/// [`From<RestartStrategy> for String`] (7baa18a) that opened this
1869/// axis on the sibling supervisor-level strategy enum. Rust's standard
1870/// library does not carry a blanket `impl<T: AsRef<str>> From<T> for
1871/// String` (nor an `impl<T: fmt::Display> From<T> for String`), so
1872/// every closed-set typed enum that carries the paired `AsRef<str>` /
1873/// `Display` / `From<Self> for &'static str` triple but not the
1874/// owned-[`String`] axis forces every owned-string call site through a
1875/// `.to_string()` / `.as_str().to_owned()` / `String::from(policy.as_str())`
1876/// detour whose type bounds have no compile-time link to the
1877/// substrate primitive.
1878///
1879/// Deliberately routes through the human-readable
1880/// [`RestartPolicy::as_str`] axis — for this enum the wire format
1881/// (`PascalCase`, tatara-lisp author surface `:restart Permanent`) and
1882/// the diagnostic byte-string share the same vocabulary by
1883/// construction (unlike the sibling [`crate::CaixaKind`] enum whose
1884/// two axes diverge), so the owned-[`String`] projection lands
1885/// byte-identically on both the wire vocabulary the paired
1886/// [`serde::Serialize`] derive emits and the diagnostic vocabulary the
1887/// [`RestartPolicy::as_str`] helper returns, and — because the paired
1888/// [`TryFrom<&str>`] / [`RestartPolicy::from_wire`] reverse-projection
1889/// axis parses the same `PascalCase` vocabulary — the direct two-way
1890/// `Self → String → Self` round-trip composes without the wire-vocab
1891/// intermediate hop the peer [`crate::CaixaKind`] owned-[`String`]
1892/// axis pair requires.
1893///
1894/// Pinned load-bearing by
1895/// [`tests::restart_policy_from_into_owned_string_routes_through_as_str_accessor`]
1896/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1897/// three-arm emit-set, plus a blanket `.into::<String>()` shape
1898/// witness) and
1899/// [`tests::restart_policy_from_into_owned_string_and_static_str_agree_on_every_arm`]
1900/// (cross-axis partition pin against the paired owned-input
1901/// [`From<RestartPolicy> for &'static str`] impl and the sibling
1902/// [`ToString::to_string`] surface routed through [`std::fmt::Display`],
1903/// plus a `.iter().copied().map(String::from)` pipe witness over
1904/// [`RestartPolicy::ALL`], plus a direct round-trip witness through
1905/// [`TryFrom<&str>`] on the owned-[`String`]'s [`String::as_str`]
1906/// borrow that closes the two-way `Self → String → Self` round-trip
1907/// on the trait-idiomatic owned-[`String`] forward + reverse axis
1908/// pair).
1909impl From<RestartPolicy> for String {
1910    fn from(policy: RestartPolicy) -> String {
1911        policy.as_str().to_owned()
1912    }
1913}
1914
1915/// Trait-idiomatic *borrowed-input, owned-`String` output* forward
1916/// projection on the second-of-two M2 OTP-shape closed-set typed enum
1917/// ([`RestartPolicy`]) — the fourth (and closing) corner of the
1918/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
1919/// projection family on this enum, mirror of the first-mover
1920/// [`From<&RestartStrategy> for String`] (579385f) that opened the
1921/// 2×2-completion corner on the sibling supervisor-level strategy
1922/// enum. Routes byte-for-byte through the substrate-primitive
1923/// [`RestartPolicy::as_str`] `pub const fn` accessor (via
1924/// [`str::to_owned`]) so every consumer that holds a borrowed
1925/// [`&RestartPolicy`] and needs an owned [`String`] — a future
1926/// `serde_json::Value::String(String::from(&policy))` structured-payload
1927/// composer over a borrowed field, a future `Iterator::map` over
1928/// `&[RestartPolicy]` that projects to owned keys through
1929/// `.iter().map(String::from)`, a future `HashMap::<String,
1930/// RestartPolicy>::from_iter` that keys off a borrowed-iteration axis
1931/// where dereferencing the policy would force an unnecessary `Copy` at
1932/// every step, the future wasm-operator's per-supervisor
1933/// `child_policies.iter().map(String::from).collect()` per-child post-
1934/// exit restart-decision diagnostic emit whose iteration axis is
1935/// borrowed by construction — reaches the same three-arm lifted
1936/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1937/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1938/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1939/// paired [`std::fmt::Display`], [`AsRef<str>`],
1940/// [`RestartPolicy::as_str`], and the three other trait-idiomatic
1941/// forward-projection impls
1942/// ([`From<RestartPolicy> for &'static str`],
1943/// [`From<&RestartPolicy> for &'static str`],
1944/// [`From<RestartPolicy> for String`]) already return.
1945///
1946/// Second peer on the substrate-wide trait-idiomatic *borrowed-input,
1947/// owned-`String` output* forward-projection family opened on
1948/// [`crate::supervisor::RestartStrategy`] (579385f) — closes the
1949/// `{Self, &Self} × {&'static str, String}` 2×2 projection corner on
1950/// both M2 OTP-shape sibling peers (the paired supervisor-level
1951/// sibling-restart-strategy axis and the per-child restart-decision-
1952/// policy axis), so the whole M2 OTP-shape axis pair now carries the
1953/// full four-corner family by construction. Rust's standard library
1954/// does not carry a blanket `impl<T: AsRef<str>> From<&T> for String`
1955/// (nor an `impl<T: fmt::Display> From<&T> for String`), so every
1956/// closed-set typed enum that carries the paired `AsRef<str>` /
1957/// `Display` / `From<Self> for &'static str` / `From<&Self> for
1958/// &'static str` / `From<Self> for String` quintuple but not the
1959/// borrowed-input owned-[`String`] axis forces every borrowed-input
1960/// owned-string call site through a `policy.as_str().to_owned()` /
1961/// `String::from(*policy)` (with a spurious `Copy`) /
1962/// `policy.to_string()` (through `Display`) detour whose type bounds
1963/// have no compile-time link to the substrate primitive.
1964///
1965/// Deliberately routes through the human-readable
1966/// [`RestartPolicy::as_str`] axis — for this enum the wire format
1967/// (`PascalCase`, tatara-lisp author surface `:restart Permanent`) and
1968/// the diagnostic byte-string share the same vocabulary by
1969/// construction (unlike the sibling [`crate::CaixaKind`] enum whose
1970/// two axes diverge), so the borrowed-input owned-[`String`]
1971/// projection lands byte-identically on both the wire vocabulary the
1972/// paired [`serde::Serialize`] derive emits and the diagnostic
1973/// vocabulary the [`RestartPolicy::as_str`] helper returns, and —
1974/// because the paired [`TryFrom<&str>`] / [`RestartPolicy::from_wire`]
1975/// reverse-projection axis parses the same `PascalCase` vocabulary —
1976/// the direct two-way `&Self → String → Self` round-trip composes
1977/// without the wire-vocab intermediate hop the peer
1978/// [`crate::CaixaKind`] axis pair requires.
1979///
1980/// The remaining thirteen closed-set typed enums on the caixa
1981/// substrate surface (`CaixaKind`, `CaixaDialeto`, `DepList`,
1982/// `PlacementStrategy`, `WitShape`, `RateLimitUnit`,
1983/// `PathShapeViolation`, `InvariantKind`, `ArchVerdict`, `Severity`,
1984/// `FixSafety`, `Semantic`, `FerriteRuntime`) are the future targets
1985/// of this 2×2-completion campaign — each carries the same paired
1986/// quintuple that this borrowed-input owned-[`String`] axis extends
1987/// onto.
1988///
1989/// Pinned load-bearing by
1990/// [`tests::restart_policy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
1991/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1992/// three-arm emit-set through the borrowed-input surface) and
1993/// [`tests::restart_policy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
1994/// (cross-axis partition pin against the paired owned-input owned-
1995/// [`String`] [`From<RestartPolicy> for String`] impl, the paired
1996/// borrowed-input owned-[`&'static str`] [`From<&RestartPolicy> for
1997/// &'static str`] impl, and the sibling [`ToString::to_string`]
1998/// surface routed through [`std::fmt::Display`], plus a direct round-
1999/// trip witness through [`TryFrom<&str>`] on the owned-[`String`]'s
2000/// [`String::as_str`] borrow that closes the two-way
2001/// `&Self → String → Self` round-trip on the trait-idiomatic
2002/// borrowed-input owned-[`String`] forward + reverse axis pair).
2003impl From<&RestartPolicy> for String {
2004    fn from(policy: &RestartPolicy) -> String {
2005        policy.as_str().to_owned()
2006    }
2007}
2008
2009/// Trait-idiomatic *owned-input, [`std::borrow::Cow<'static, str>`]
2010/// output* forward projection on the M2 OTP-shape per-child-restart
2011/// [`RestartPolicy`] closed-set typed enum — extends the substrate-
2012/// wide [`std::borrow::Cow<'static, str>`] forward-projection family
2013/// opened on [`crate::CaixaKind`] (99c1735 owned-input, d45c409
2014/// borrowed-input) and first extended off it onto the sibling M2
2015/// OTP-shape sibling-restart [`RestartStrategy`] (7dd28b3 owned-input,
2016/// 9b3e4b3 borrowed-input) onto the second (and second-of-two-in-M2)
2017/// M2 OTP-shape closed-set fieldless typed enum peer on the caixa
2018/// surface (`:children :restart`). Routes byte-for-byte through the
2019/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
2020/// accessor (via [`std::borrow::Cow::Borrowed`]) so every consumer
2021/// that binds a [`RestartPolicy`] through the trait-idiomatic
2022/// [`std::borrow::Cow<'static, str>`] axis — a future
2023/// `axum::response::IntoResponse` composer whose per-policy
2024/// diagnostic-body typing rules out the sibling [`AsRef<str>`]
2025/// borrowed return, a future M4 admission-webhook rejection body
2026/// that composes the accepted-policy enumeration through the same
2027/// `RestartPolicy::ALL.iter().map(Cow::from)` shape [`crate::CaixaKind`]
2028/// and [`RestartStrategy`] already route through, a generic `<T: for<'a>
2029/// Into<std::borrow::Cow<'static, str>>>`-bound structured-log
2030/// emitter on a per-child-policy diagnostic column — reaches the same
2031/// three-arm lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`]
2032/// / [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2033/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2034/// paired [`std::fmt::Display`], [`AsRef<str>`],
2035/// [`RestartPolicy::as_str`], and the four
2036/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
2037/// forward-projection corners already return.
2038///
2039/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
2040/// [`std::borrow::Cow::Owned`] — the substrate-primitive
2041/// [`RestartPolicy::as_str`] accessor's return carries the `&'static
2042/// str` lifetime by construction (each `match` arm resolves to a
2043/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const &str`
2044/// with static lifetime), so the zero-alloc borrowed arm is the
2045/// type-correct projection with no runtime allocation.
2046///
2047/// Rust's standard library carries no blanket `impl<T: AsRef<str>>
2048/// From<T> for Cow<'static, str>` (nor an `impl<T: fmt::Display>
2049/// From<T> for Cow<'static, str>`), so the paired sibling
2050/// [`From<RestartPolicy> for &'static str`] (9fb37d0),
2051/// [`From<RestartPolicy> for String`] (7851725), [`AsRef<str>`], and
2052/// [`std::fmt::Display`] surfaces do not implicitly extend to a
2053/// [`Cow<'static, str>`]-bound call site — every such site is forced
2054/// through a `Cow::Borrowed(policy.as_str())` /
2055/// `Cow::Owned(policy.to_string())` open-code whose type bounds have
2056/// no compile-time link back to the substrate primitive until this
2057/// lift.
2058///
2059/// Second peer to extend the substrate-wide trait-idiomatic
2060/// [`std::borrow::Cow<'static, str>`] forward-projection axis off the
2061/// top-level [`crate::CaixaKind`] enum (99c1735 owned-input, d45c409
2062/// borrowed-input) onto the wider substrate — closes the M2 OTP-shape
2063/// tier of the campaign (both sibling peers, `RestartStrategy` and
2064/// `RestartPolicy`, now carry the owned-input Cow<'static, str>
2065/// forward projection) so the remaining eleven peers
2066/// (`PlacementStrategy`, `RateLimitUnit`, `DepList`, `CaixaDialeto`,
2067/// and the outside-`caixa-core` peers `WitShape`, `PathShapeViolation`,
2068/// `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`,
2069/// `FerriteRuntime`) are the future targets. Every future arm addition
2070/// (an OTP-`intrinsic` fourth restart policy the ABSORPTION-ROADMAP
2071/// might reach for once the three canonical OTP restart policies stop
2072/// covering the substrate's discovered load-shape) grows the
2073/// Cow<'static, str> axis by construction through one caixa-core edit
2074/// on [`RestartPolicy::as_str`] — rather than a coordinated rewrite
2075/// across every future Cow<'static, str>-bound consumer site.
2076///
2077/// Pinned load-bearing by
2078/// [`tests::restart_policy_from_into_static_cow_str_routes_through_as_str_accessor`]
2079/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
2080/// against [`RestartPolicy::as_str`] across the three-arm
2081/// [`RestartPolicy::ALL`]) and
2082/// [`tests::restart_policy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
2083/// (cross-axis partition pin against the paired [`From<RestartPolicy>
2084/// for &'static str`], [`From<RestartPolicy> for String`], and
2085/// [`ToString`]-through-[`std::fmt::Display`] axes, plus a
2086/// `.iter().copied().map(Cow::from)` pipe witness over
2087/// [`RestartPolicy::ALL`] that materializes the three-arm accept-set
2088/// through the [`Cow<'static, str>`] axis alone and pins the
2089/// zero-alloc discipline on every element).
2090impl From<RestartPolicy> for std::borrow::Cow<'static, str> {
2091    fn from(policy: RestartPolicy) -> std::borrow::Cow<'static, str> {
2092        std::borrow::Cow::Borrowed(policy.as_str())
2093    }
2094}
2095
2096/// Trait-idiomatic *borrowed-input, [`std::borrow::Cow<'static, str>`]
2097/// output* forward projection on the M2 OTP-shape per-child-restart
2098/// [`RestartPolicy`] closed-set typed enum — the borrowed-input
2099/// companion to the paired owned-input
2100/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] impl
2101/// immediately above (0612398). Routes byte-for-byte through the same
2102/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
2103/// accessor (via [`std::borrow::Cow::Borrowed`]) so every consumer
2104/// that holds a `&RestartPolicy` and needs a
2105/// [`std::borrow::Cow<'static, str>`] — a
2106/// `RestartPolicy::ALL.iter().map(std::borrow::Cow::from).collect::<Vec<_>>()`
2107/// per-arm accept-set materializer (whose iterator over
2108/// `&'static [RestartPolicy]` yields `&RestartPolicy`, not
2109/// `RestartPolicy`, so the paired owned-input
2110/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] axis
2111/// alone forces every call site through an explicit `.copied()` /
2112/// dereference / [`Copy`]-bound restatement rather than the direct
2113/// trait-idiomatic projection), a future generic
2114/// `<T: for<'a> Into<std::borrow::Cow<'static, str>>>`-bound emitter
2115/// on a per-child-policy diagnostic column that walks the
2116/// `iter().map(Into::into)` shape verbatim, the future M4 admission-
2117/// webhook rejection body that composes the accepted-policy
2118/// enumeration from an iterated
2119/// `RestartPolicy::ALL.iter().map(|p| p.into())` pipe rather than a
2120/// per-arm `match p { … }` cascade — reaches the same three-arm
2121/// lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2122/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2123/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2124/// paired [`std::fmt::Display`], [`AsRef<str>`],
2125/// [`RestartPolicy::as_str`], the four
2126/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
2127/// forward-projection corners, and the paired owned-input
2128/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] impl
2129/// already return.
2130///
2131/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
2132/// [`std::borrow::Cow::Owned`] — the substrate-primitive
2133/// [`RestartPolicy::as_str`] accessor's return carries the
2134/// `&'static str` lifetime by construction (each `match` arm resolves
2135/// to a [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const &str`
2136/// with static lifetime), so the zero-alloc borrowed arm is the
2137/// type-correct projection with no runtime allocation.
2138///
2139/// Closes the `{Self, &Self}` input-shape corner on the M2 OTP-shape
2140/// per-child-restart [`std::borrow::Cow<'static, str>`] axis opened
2141/// one commit prior (0612398) on the paired owned-input
2142/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] impl —
2143/// second-of-two-in-M2 closed-set fieldless typed enum peer on the
2144/// caixa surface (paired with the sibling-restart [`RestartStrategy`]
2145/// which carries both {Self, &Self} × Cow<'static, str> corners since
2146/// 7dd28b3 owned-input, 9b3e4b3 borrowed-input), exactly as d45c409
2147/// closed it on the top-level [`crate::CaixaKind`] one commit after
2148/// the owning half (99c1735) landed. This lift closes the whole M2
2149/// OTP-shape tier of the substrate-wide [`Cow<'static, str>`]
2150/// forward-projection campaign on both input-shape corners
2151/// ({Self, &Self}) of both M2 OTP-shape sibling peers
2152/// ([`RestartStrategy`] and [`RestartPolicy`]), so the remaining
2153/// eleven substrate-wide peers (`PlacementStrategy`, `RateLimitUnit`,
2154/// `DepList`, `CaixaDialeto`, `WitShape`, `PathShapeViolation`,
2155/// `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`,
2156/// `FerriteRuntime`) become the future targets of the campaign. Rust's
2157/// standard library does not carry a blanket
2158/// `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor an
2159/// `impl<T: fmt::Display> From<&T> for Cow<'static, str>`), so every
2160/// closed-set fieldless typed enum peer on the substrate that carries
2161/// the paired owned-input [`Cow<'static, str>`] axis but not the
2162/// borrowed-input axis forces every borrowed-input
2163/// [`Cow<'static, str>`]-parameterized call site through a spurious
2164/// [`Copy`] deref (`std::borrow::Cow::from(*policy)`) or a
2165/// `std::borrow::Cow::Borrowed(policy.as_str())` open-code whose type
2166/// bounds have no compile-time link to the substrate primitive.
2167///
2168/// Pinned load-bearing by
2169/// [`tests::restart_policy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor`]
2170/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
2171/// against [`RestartPolicy::as_str`] across the three-arm
2172/// [`RestartPolicy::ALL`] through the borrowed-input surface) and
2173/// [`tests::restart_policy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
2174/// (cross-axis partition pin against the paired owned-input
2175/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`], the
2176/// paired borrowed-input owned-`&'static str`
2177/// [`From<&RestartPolicy> for &'static str`], and the paired
2178/// borrowed-input owned-`String` [`From<&RestartPolicy> for String`]
2179/// impls, plus a `.iter().map(std::borrow::Cow::from)` pipe witness
2180/// over [`RestartPolicy::ALL`] — whose iterator yields
2181/// `&RestartPolicy` by construction, so the borrowed-input
2182/// [`Cow<'static, str>`] axis is what routes the pipe through the
2183/// substrate-primitive [`RestartPolicy::as_str`] accessor with the
2184/// zero-alloc [`Cow::Borrowed`] arm by construction and without a
2185/// spurious [`Copy`] deref).
2186impl From<&RestartPolicy> for std::borrow::Cow<'static, str> {
2187    fn from(policy: &RestartPolicy) -> std::borrow::Cow<'static, str> {
2188        std::borrow::Cow::Borrowed(policy.as_str())
2189    }
2190}
2191
2192/// Trait-idiomatic *owned-input, [`Box<str>`] output* forward
2193/// projection on the M2 OTP-shape per-child-restart [`RestartPolicy`]
2194/// closed-set fieldless typed enum — extends the substrate-wide
2195/// `Box<str>` forward-projection campaign tier opened one commit prior
2196/// (69ef45c) on the paired sibling-restart [`RestartStrategy`] onto
2197/// the second (and third-and-final) M2 OTP-shape closed-set fieldless
2198/// typed enum peer on the caixa surface (`:children :restart`),
2199/// immediately after the paired `Cow<'static, str>` axis (0612398 /
2200/// b4dc55c) closed the
2201/// `{Self, &Self} × {&'static str, String, Cow<'static, str>}` 2×3
2202/// corner on this enum. Routes byte-for-byte through the
2203/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
2204/// accessor via [`Box::<str>::from`] on the returned `&'static str`,
2205/// so every consumer that binds a
2206/// `let key: Box<str> = policy.into();`-shaped call site — a
2207/// per-child metric-key materializer that stashes the policy
2208/// discriminator in a `Box<str>`-typed heap-owned scalar for cheap
2209/// clone (a shared-nothing per-policy accept-set the `caixa-operator`
2210/// hierarchical reconciliation scheduler's per-child restart-decision
2211/// fan-out carries), a future admission-webhook rejection body whose
2212/// per-arm `Box<str>` field composes from an owned `RestartPolicy`
2213/// handle — reaches the same three-arm lifted
2214/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2215/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2216/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2217/// sibling
2218/// `{Self, &Self} × {&'static str, String, Cow<'static, str>}`
2219/// forward-projection corner already returns. Rust's standard library
2220/// carries `impl From<&str> for Box<str>` and
2221/// `impl From<String> for Box<str>` but no blanket
2222/// `impl<T: AsRef<str>> From<T> for Box<str>` (nor any
2223/// `impl<T: Copy, U: From<T>> From<T> for U` route from the enum), so
2224/// this axis is a distinct trait-idiomatic surface that a downstream
2225/// `RestartPolicy → Box<str>` `.into()` reaches through this impl and
2226/// no other — without a `Box::from(policy.as_str())` open-code whose
2227/// type bounds have no compile-time link back to the substrate
2228/// primitive.
2229///
2230/// Second peer on the substrate-wide trait-idiomatic [`Box<str>`]
2231/// forward-projection family opened on the sibling-restart
2232/// [`RestartStrategy`] (69ef45c / 59ae5dc) — closes the whole M2
2233/// OTP-shape tier of the substrate-wide [`Box<str>`] forward-
2234/// projection campaign's owned-input corner on both M2 OTP-shape
2235/// sibling peers ([`RestartStrategy`] and [`RestartPolicy`]), the
2236/// paired borrowed-input `From<&RestartPolicy> for Box<str>` closer
2237/// and the remaining fieldless-enum peers on the M3 mesh-shape /
2238/// outside-M3 caixa-core / render-side / outside-caixa-core tiers
2239/// are the future targets of the campaign.
2240///
2241/// Pinned load-bearing by
2242/// [`tests::restart_policy_from_into_box_str_routes_through_as_str_accessor`]
2243/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2244/// three-arm [`RestartPolicy::ALL`] emit-set on the owned-input
2245/// surface, plus a blanket-derived [`Into`] shape witness).
2246impl From<RestartPolicy> for Box<str> {
2247    fn from(policy: RestartPolicy) -> Box<str> {
2248        Box::<str>::from(policy.as_str())
2249    }
2250}
2251
2252/// Trait-idiomatic *borrowed-input, [`Box<str>`] output* forward
2253/// projection on the M2 OTP-shape per-child-restart [`RestartPolicy`]
2254/// closed-set fieldless typed enum — the borrowed-input companion to
2255/// the paired owned-input [`From<RestartPolicy> for Box<str>`] impl
2256/// (0a1b313, one commit prior) that closes the `{Self, &Self}`
2257/// input-shape corner of the substrate-wide [`Box<str>`] forward-
2258/// projection axis on the second (and third-and-final) M2 OTP-shape
2259/// closed-set fieldless typed enum peer on the caixa surface
2260/// (`:children :restart`), routing byte-for-byte through the
2261/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
2262/// accessor via [`Box::<str>::from`] on the returned `&'static str`.
2263/// Every consumer that holds a `&RestartPolicy` and needs a
2264/// [`Box<str>`] — a
2265/// `RestartPolicy::ALL.iter().map(Box::<str>::from).collect::<Vec<_>>()`
2266/// per-arm accept-set materializer (whose iterator over
2267/// `&'static [RestartPolicy]` yields `&RestartPolicy`, not
2268/// `RestartPolicy`, so the paired owned-input
2269/// [`From<RestartPolicy> for Box<str>`] axis alone forces every
2270/// call site through an explicit [`Copy`] deref or a
2271/// `.copied()` restatement rather than the direct trait-idiomatic
2272/// projection), a per-child metric-key materializer holding
2273/// `&RestartPolicy` through a `caixa-operator` hierarchical
2274/// reconciliation scheduler's borrow lifetime, a future admission-
2275/// webhook rejection body whose per-arm `Box<str>` field composes
2276/// from a borrowed `&RestartPolicy` handle — reaches the
2277/// substrate-primitive [`RestartPolicy::as_str`] accessor through
2278/// this impl and no other, without a
2279/// `Box::<str>::from(policy.as_str())` open-code whose type bounds
2280/// have no compile-time link back to the substrate primitive.
2281///
2282/// Rust's standard library carries `impl From<&str> for Box<str>`
2283/// and `impl From<String> for Box<str>` but no blanket
2284/// `impl<T: AsRef<str>> From<&T> for Box<str>` (nor a
2285/// `Copy`-based `impl<T: Copy, U: From<&T> for U`), so every closed-
2286/// set fieldless typed enum peer on the substrate that carries the
2287/// paired owned-input `Box<str>` axis but not the borrowed-input
2288/// axis forces every borrowed-input `Box<str>`-parameterized call
2289/// site through a spurious [`Copy`] deref
2290/// (`Box::<str>::from((*policy).as_str())`) or a
2291/// `Box::<str>::from(policy.as_str())` open-code whose type bounds
2292/// have no compile-time link back to the substrate primitive.
2293///
2294/// Fourth (and closing) peer on the substrate-wide trait-idiomatic
2295/// [`Box<str>`] forward-projection family on the M2 OTP-shape tier
2296/// — closes the whole `{Self, &Self}` input-shape corner of the
2297/// [`Box<str>`] axis on both M2 OTP-shape sibling peers
2298/// ([`RestartStrategy`] and [`RestartPolicy`]), exactly as b4dc55c
2299/// closed the paired [`Cow<'static, str>`] axis one commit after
2300/// its owning half (0612398) landed on this enum. The remaining
2301/// fieldless-enum peers on the M3 mesh-shape / outside-M3 caixa-
2302/// core / render-side / outside-caixa-core tiers are the future
2303/// targets of the [`Box<str>`] campaign.
2304///
2305/// Pinned load-bearing by
2306/// [`tests::restart_policy_from_borrowed_into_box_str_routes_through_as_str_accessor`]
2307/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2308/// three-arm [`RestartPolicy::ALL`] emit-set on the borrowed-input
2309/// surface, plus a blanket-derived [`Into`] shape witness, a
2310/// cross-axis partition pin against the paired owned-input
2311/// [`From<RestartPolicy> for Box<str>`] and the sibling borrowed-
2312/// input `{&'static str, String, Cow<'static, str>}` return-shape
2313/// axes, and a `.iter().map(Box::<str>::from)` pipe witness over
2314/// [`RestartPolicy::ALL`] — whose iterator yields `&RestartPolicy`
2315/// by construction, so the borrowed-input [`Box<str>`] axis is
2316/// what routes the pipe through the substrate-primitive
2317/// [`RestartPolicy::as_str`] accessor without a spurious [`Copy`]
2318/// deref).
2319impl From<&RestartPolicy> for Box<str> {
2320    fn from(policy: &RestartPolicy) -> Box<str> {
2321        Box::<str>::from(policy.as_str())
2322    }
2323}
2324
2325/// Trait-idiomatic *owned-input, [`std::sync::Arc<str>`] output*
2326/// forward projection on the M2 OTP-shape per-child-restart
2327/// [`RestartPolicy`] closed-set fieldless typed enum — routes byte-
2328/// for-byte through the substrate-primitive [`RestartPolicy::as_str`]
2329/// `pub const fn` accessor via [`std::sync::Arc::<str>::from`] on the
2330/// returned `&'static str`, so every consumer that binds a
2331/// [`RestartPolicy`] through the standard-library `.into()` /
2332/// [`From<Self> for std::sync::Arc<str>`] (equivalently
2333/// [`Into<std::sync::Arc<str>>`]) axis — a future admission-webhook's
2334/// per-request `Sync` + `Send`-safe structured-log field composed
2335/// across an `.await` boundary through a
2336/// `<T: Into<std::sync::Arc<str>>>`-bound diagnostic-column dispatch,
2337/// a future wasm-operator's per-child post-exit restart-decision
2338/// pipeline holding a shared-ownership per-arm cache key, a
2339/// `<T: Into<std::sync::Arc<str>>>`-bound `tracing`-span attributes
2340/// collector recording a per-child-policy field onto the parent
2341/// span's shared-ownership context — reaches the same three-arm
2342/// lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2343/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2344/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2345/// sibling
2346/// `{Self, &Self} × {&'static str, String, Cow<'static, str>, Box<str>}`
2347/// forward-projection corner already returns.
2348///
2349/// Second peer on the substrate-wide trait-idiomatic
2350/// [`std::sync::Arc<str>`] forward-projection family opened one
2351/// projection tier prior (bca2ec8) on the paired sibling-restart
2352/// [`RestartStrategy`] owned-input first-mover — extends the tier
2353/// onto the second (and third-and-final) M2 OTP-shape closed-set
2354/// fieldless typed enum peer on the caixa surface
2355/// (`:children :restart`), immediately after the paired [`Box<str>`]
2356/// axis (0a1b313 / cb1d068) closed the whole
2357/// `{Self, &Self} × {&'static str, String, Cow<'static, str>, Box<str>}`
2358/// 2×4 corner on this enum. Rust's standard library carries
2359/// `impl From<&str> for std::sync::Arc<str>` and
2360/// `impl From<String> for std::sync::Arc<str>` but no blanket
2361/// `impl<T: AsRef<str>> From<T> for std::sync::Arc<str>` (nor an
2362/// `impl<T: fmt::Display> From<T> for std::sync::Arc<str>`), so this
2363/// axis is a distinct trait-idiomatic surface that a
2364/// `let key: std::sync::Arc<str> = policy.into();`-shaped call site
2365/// reaches through this impl and no other — a paired
2366/// `std::sync::Arc::<str>::from(policy.as_str())` open-code has no
2367/// compile-time link back to the substrate primitive, and a two-step
2368/// `std::sync::Arc::<str>::from(String::from(policy))` composition
2369/// through the owned-`String` axis allocates twice (once into the
2370/// intermediate `String`, once into the [`Arc<str>`] on the
2371/// `From<String>` conversion) where the single-step trait impl
2372/// allocates once.
2373///
2374/// Peer of the sibling [`Box<str>`] second-tier extender (0a1b313) —
2375/// same "extends the substrate-wide projection tier onto the next
2376/// M2 OTP-shape peer" discipline, extended onto the
2377/// [`std::sync::Arc<str>`] axis whose shared-ownership + [`Sync`] +
2378/// [`Send`] contract is the distinct value the [`Box<str>`] axis's
2379/// owned-move return-shape cannot provide.
2380///
2381/// Pinned load-bearing by
2382/// [`tests::restart_policy_from_into_arc_str_routes_through_as_str_accessor`]
2383/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2384/// three-arm [`RestartPolicy::ALL`] emit-set on the owned-input
2385/// surface, plus a blanket-derived [`Into`] shape witness and cross-
2386/// axis byte-parity pins against the sibling owned-input
2387/// `{&'static str, String, Cow<'static, str>, Box<str>}` return-shape
2388/// axes).
2389impl From<RestartPolicy> for std::sync::Arc<str> {
2390    fn from(policy: RestartPolicy) -> std::sync::Arc<str> {
2391        std::sync::Arc::<str>::from(policy.as_str())
2392    }
2393}
2394
2395/// Trait-idiomatic *borrowed-input, [`std::sync::Arc<str>`] output*
2396/// forward projection on the M2 OTP-shape per-child-restart
2397/// [`RestartPolicy`] closed-set fieldless typed enum — closes the
2398/// `{Self, &Self}` input-shape corner of the [`std::sync::Arc<str>`]
2399/// forward-projection axis on the second (and third-and-final) M2
2400/// OTP-shape closed-set fieldless typed enum peer on the caixa
2401/// surface (`:children :restart`), companion to the paired
2402/// owned-input [`From<RestartPolicy> for std::sync::Arc<str>`] impl
2403/// one commit prior (b05724e). Routes byte-for-byte through the
2404/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
2405/// accessor (via [`std::sync::Arc::<str>::from`] on the returned
2406/// `&'static str`), so every consumer that binds a
2407/// [`&RestartPolicy`] through the standard-library `.into()` /
2408/// [`From<&Self> for std::sync::Arc<str>`] (equivalently
2409/// [`Into<std::sync::Arc<str>>`]) axis — a future admission-webhook's
2410/// per-request borrowed-`&RestartPolicy` handle rendering a per-arm
2411/// `Sync` + `Send`-safe structured-log field across an `.await`
2412/// boundary through a `<T: Into<std::sync::Arc<str>>>`-bound
2413/// diagnostic-column dispatch, a future wasm-operator's per-child
2414/// post-exit restart-decision pipeline whose
2415/// `.iter().map(std::sync::Arc::<str>::from)` collector reaches
2416/// into the shared-ownership per-arm key without a spurious [`Copy`]
2417/// deref (which would only be reachable through the owned-input
2418/// [`From<RestartPolicy> for std::sync::Arc<str>`] axis by first
2419/// calling `.copied()` on the iterator), a future
2420/// `<T: Into<std::sync::Arc<str>>>`-bound `tracing`-span attributes
2421/// collector recording a borrowed-`&RestartPolicy` per-arm field
2422/// onto the parent span's shared-ownership context — reaches the
2423/// same three-arm lifted
2424/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2425/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2426/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2427/// paired owned-input [`From<RestartPolicy> for std::sync::Arc<str>`]
2428/// impl and the sibling `{&'static str, String, Cow<'static, str>,
2429/// Box<str>}` forward-projection corner already return.
2430///
2431/// Closes the substrate-wide trait-idiomatic
2432/// [`std::sync::Arc<str>`] forward-projection family opened one
2433/// commit prior (b05724e) on the paired owned-input
2434/// [`From<RestartPolicy> for std::sync::Arc<str>`] impl — closes
2435/// the `{Self, &Self}` input-shape corner of the
2436/// [`std::sync::Arc<str>`] axis on the second (and third-and-final)
2437/// M2 OTP-shape closed-set fieldless typed enum peer on the caixa
2438/// surface, exactly as b3e72d7 closed the paired
2439/// [`std::sync::Arc<str>`] corner on the sibling-restart
2440/// [`RestartStrategy`] first-mover one commit after its owning half
2441/// (bca2ec8) landed, and as cb1d068 closed the paired [`Box<str>`]
2442/// corner on this enum one commit after its owning half (0a1b313)
2443/// landed. Rust's standard library carries `impl From<&str> for
2444/// std::sync::Arc<str>` and `impl From<String> for
2445/// std::sync::Arc<str>` but no blanket `impl<T: AsRef<str>> From<&T>
2446/// for std::sync::Arc<str>` (nor a `Copy`-based `impl<T: Copy,
2447/// U: From<T>> From<&T> for U`), so every closed-set fieldless typed
2448/// enum peer on the substrate that carries the paired owned-input
2449/// [`std::sync::Arc<str>`] axis but not the borrowed-input axis
2450/// forces every borrowed-input [`std::sync::Arc<str>`]-parameterized
2451/// call site through a spurious [`Copy`] deref
2452/// (`std::sync::Arc::<str>::from((*policy).as_str())`) or a
2453/// `std::sync::Arc::<str>::from(policy.as_str())` open-code whose
2454/// type bounds have no compile-time link back to the substrate
2455/// primitive.
2456///
2457/// Pinned load-bearing by
2458/// [`tests::restart_policy_from_borrowed_into_arc_str_routes_through_as_str_accessor`]
2459/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2460/// three-arm [`RestartPolicy::ALL`] emit-set on the borrowed-input
2461/// surface, plus a blanket-derived [`Into`] shape witness, a
2462/// cross-axis pin against the paired owned-input
2463/// [`From<RestartPolicy> for std::sync::Arc<str>`] and the sibling
2464/// borrowed-input `{&'static str, String, Cow<'static, str>,
2465/// Box<str>}` return-shape axes, and a
2466/// `.iter().map(std::sync::Arc::<str>::from)` pipe witness over
2467/// [`RestartPolicy::ALL`]).
2468impl From<&RestartPolicy> for std::sync::Arc<str> {
2469    fn from(policy: &RestartPolicy) -> std::sync::Arc<str> {
2470        std::sync::Arc::<str>::from(policy.as_str())
2471    }
2472}
2473
2474// Fleet-wide dispatcher-catalog registrations for caixa's OTP
2475// supervisor surface — two more typed shadows over Erlang/OTP
2476// primitives the substrate now mechanically tracks (see
2477// theory/UNIFIED-COMPUTING-MODEL.md §VI for the roadmap +
2478// theory/TYPED-ABSORPTION.md for the absorption arc).
2479gen_platform::register_dispatcher!("caixa.restart-strategy", RestartStrategy);
2480gen_platform::register_dispatcher!("caixa.restart-policy", RestartPolicy);
2481
2482/// One child entry in the supervisor's `:children` list.
2483///
2484/// Every child references another caixa by `:caixa <nome>` + version
2485/// constraint. The supervisor materializes one ComputeUnit per entry.
2486#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
2487#[serde(rename_all = "camelCase")]
2488pub struct ChildSpec {
2489    /// The child caixa's `:nome`. Must resolve via the same dependency
2490    /// resolution path as `:deps` (caixa-resolver).
2491    pub caixa: String,
2492
2493    /// Semver constraint (`"^0.1"`, `"~0.1.2"`, etc.) — same shape as
2494    /// [`crate::dep::Dep::versao`].
2495    pub versao: String,
2496
2497    /// Restart policy — an author-omitted slot degrades onto the
2498    /// substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`]
2499    /// (`permanent`, the Erlang/OTP worker-child default) through the
2500    /// [`Default for RestartPolicy`] impl this `#[serde(default)]` routes
2501    /// to.
2502    #[serde(default)]
2503    pub restart: RestartPolicy,
2504}
2505
2506impl ChildSpec {
2507    /// Substrate-canonical per-`:children` child-caixa `:nome` scalar
2508    /// accessor every consumer that reads the OTP-shape supervised
2509    /// child's identity keys off — returns the author-declared
2510    /// `:children :caixa` byte-string verbatim as a `&str`, borrowed
2511    /// from the typed slot's own [`String`] storage.
2512    ///
2513    /// The `:children :caixa` slot carries the DNS-1123 label — the
2514    /// child caixa's `:nome` — that every emitted cluster artifact
2515    /// derives its `metadata.name` from verbatim: the rendered
2516    /// `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name` per child, the
2517    /// [`crate::LABEL_PROGRAM`] label value on every child's pod
2518    /// identity, and the per-child K8s Service `metadata.name` the
2519    /// future wasm-operator (M3) provisions for inter-child supervision-
2520    /// tree wiring. Every downstream consumer that fans on the child's
2521    /// caixa-name keys off this scalar (the [`SupervisorSpec::validate`]
2522    /// per-child DNS-1123 gate at
2523    /// `require_valid_dns_1123_label(child.nome(), …)`, the per-child
2524    /// duplicate-detection [`crate::render::insert_first_seen`] key, the
2525    /// [`validate_no_self_supervision`] cross-slot equality check
2526    /// against the parent's `:nome`, every `SupervisorError` variant
2527    /// carrying the offending child caixa verbatim for `feira lint`
2528    /// rendering, the future wasm-operator's hierarchical reconciliation
2529    /// scheduler's per-child ComputeUnit-name projection, the future M4
2530    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
2531    /// admission webhook).
2532    ///
2533    /// Prior to this lift the `.caixa` byte-string was accessed inline
2534    /// at seven sites in `supervisor.rs` — the DNS-1123 gate's
2535    /// `&child.caixa`, the four `SupervisorError::{ChildCaixaInvalid,
2536    /// EmptyChildVersion, ChildVersaoInvalid, DuplicateChildCaixa}`
2537    /// carriers' `child.caixa.clone()`, the dedup key's
2538    /// `child.caixa.as_str()`, and the [`validate_no_self_supervision`]
2539    /// `child.caixa == parent_nome` cross-slot check — seven open-coded
2540    /// field-accesses that expressed no compile-time link back to the
2541    /// typed slot. A future extension of the `:children :caixa` axis to
2542    /// a richer author surface (a per-cluster alias table the operator
2543    /// pins through a future `:placement`-scoped slot on the supervisor
2544    /// tree, a namespace-qualified rewrite the M4 CR materializer
2545    /// applies per-CR, a per-child overlay from the future `:children
2546    /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
2547    /// acknowledges) would have had to be threaded through every
2548    /// open-coded copy in lockstep or one consumer would silently
2549    /// disagree with the peers on which caixa a given child resolves to
2550    /// — a child-set lookup that treated the name as `"cart-worker"`
2551    /// while the peer duplicate-detector treated it as
2552    /// `"tenant-a/cart-worker"` would silently split the
2553    /// `DuplicateChildCaixa` membership-lookup diagnostic from the
2554    /// self-supervision detector's parent-equality check, a two-consumer
2555    /// split at the validator far from the source `caixa.lisp` with no
2556    /// field naming the identity-drift root cause. Lifting the resolution
2557    /// rule to a typed method on the substrate primitive means every
2558    /// downstream consumer of the Supervisor's per-`:children` identity
2559    /// surface reaches for exactly one typed dispatch — the resolver's
2560    /// accept-set migrates as a unit on any future axis addition.
2561    ///
2562    /// Sibling of the peer per-`:membros` [`crate::Membro::nome`]
2563    /// (4a32abf) member-caixa `:nome` scalar accessor on the M3
2564    /// mesh-slot surface — same "one typed dispatch on the substrate
2565    /// primitive, thin projections at each consumer" discipline extended
2566    /// onto the M2 supervisor-tree per-`:children` child-identity axis.
2567    /// The two typed axes (`Membro::nome` on the M3 Aplicacao side,
2568    /// `ChildSpec::nome` on the M2 Supervisor side) now share one
2569    /// accessor discipline for the shared substrate concept "another
2570    /// caixa referenced by `:nome`". Peer of the second M2 slot scalar
2571    /// accessor [`crate::UpgradeFromEntry::prior_versao`] (75d27a8) on
2572    /// the sibling per-`:upgrade-from :from` OTP-appup axis — the M2
2573    /// slot family's typed-accessor discipline now spans both the
2574    /// upgrade axis (`:upgrade-from`) and the supervision axis
2575    /// (`:children`), matching the closed M3 mesh-slot accessor family's
2576    /// shape. Named `nome()` to match the tatara-lisp author-surface
2577    /// term the field's docstring already reaches for ("The child
2578    /// caixa's `:nome`") and the peer [`crate::Membro::nome`] /
2579    /// [`crate::Caixa::nome`] / [`crate::dep::Dep::nome`] field-name
2580    /// discipline the substrate already carries — the accessor's name
2581    /// maps directly onto the canonical caixa-identity vocabulary rather
2582    /// than shadowing the field's storage-side `caixa` label.
2583    #[must_use]
2584    pub const fn nome(&self) -> &str {
2585        self.caixa.as_str()
2586    }
2587
2588    /// Substrate-canonical per-`:children` child-caixa `:versao` semver-
2589    /// requirement scalar accessor every consumer that reads the OTP-shape
2590    /// supervised child's version pin keys off — returns the author-declared
2591    /// `:children :versao` byte-string verbatim as a `&str`, borrowed from
2592    /// the typed slot's own [`String`] storage.
2593    ///
2594    /// The `:children :versao` slot carries the Cargo-shaped semver
2595    /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that pins
2596    /// which release of the supervised child caixa the OTP-shape supervisor
2597    /// tree materializes against — the same requirement grammar the peer
2598    /// `:deps :versao` / `:membros :versao` axes carry, resolved through the
2599    /// shared [`crate::render::require_valid_versao_requirement`] cascade
2600    /// and the shared [`crate::version::parse_requirement`] parser. Every
2601    /// downstream consumer that fans on the child's version pin keys off
2602    /// this scalar (the [`SupervisorSpec::validate`] per-child requirement
2603    /// gate at `require_valid_versao_requirement(child.versao_requirement(),
2604    /// …)`, the [`SupervisorError::ChildVersaoInvalid`] variant's carrier
2605    /// for `feira lint` rendering, every future per-cluster version-lock
2606    /// overlay the caixa-operator's hierarchical reconciliation scheduler
2607    /// pins through a future `:placement`-scoped supervisor-tree slot, the
2608    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
2609    /// per-child version resolver, the future wasm-operator's per-child
2610    /// lacre BLAKE3-closure lookup at `ComputeUnit` materialization time).
2611    ///
2612    /// Prior to this lift the `.versao` byte-string was accessed inline at
2613    /// two `&str`-shaped sites in `caixa-core/src/supervisor.rs` — the
2614    /// [`SupervisorSpec::validate`] requirement-gate call
2615    /// `require_valid_versao_requirement(&child.versao, …)` and the
2616    /// [`SupervisorError::ChildVersaoInvalid`] carrier at
2617    /// `versao: child.versao.clone()` — two open-coded field-accesses that
2618    /// expressed no compile-time link back to the typed slot. A future
2619    /// extension of the `:children :versao` axis to a richer author surface
2620    /// (a per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
2621    /// flow, a lacre-projected concrete-version rewrite the operator
2622    /// materializes at CR-admission time, a future `:children :versao-lock`
2623    /// per-cluster override slot the wasm-operator's hierarchical
2624    /// reconciliation scheduler authors per-CR) would have had to be
2625    /// threaded through both open-coded copies in lockstep or one consumer
2626    /// would silently disagree with the peer on which release constraint a
2627    /// given child resolves to — the requirement-gate call reading
2628    /// `"^0.1"` while the error-body carrier read `"tenant-a-pin/^0.1"`
2629    /// would silently split the `ChildVersaoInvalid` diagnostic quote from
2630    /// the actual gate rejection input, a two-consumer split at the
2631    /// validator far from the source `caixa.lisp` with no field naming the
2632    /// version-pin drift root cause. Lifting the resolution rule to a typed
2633    /// method on the substrate primitive means every downstream
2634    /// requirement-facing consumer of the Supervisor's per-`:children`
2635    /// version-pin surface reaches for exactly one typed dispatch — the
2636    /// resolver's accept-set migrates as a unit on any future axis addition.
2637    ///
2638    /// Sibling of the peer per-`:membros` [`crate::Membro::versao_requirement`]
2639    /// (a40b0e3) member-caixa `:versao` scalar accessor on the M3 mesh-slot
2640    /// surface — same "one typed dispatch on the substrate primitive, thin
2641    /// projections at each consumer" discipline extended onto the M2
2642    /// supervisor-tree per-`:children` child-version-pin axis. The two typed
2643    /// axes (`Membro::versao_requirement` on the M3 Aplicacao side,
2644    /// `ChildSpec::versao_requirement` on the M2 Supervisor side) now share
2645    /// one accessor discipline for the shared substrate concept "another
2646    /// caixa referenced by a Cargo-shaped semver requirement". Peer of the
2647    /// sibling per-`:children` [`ChildSpec::nome`] (57c61d0) child-caixa
2648    /// `:nome` scalar accessor — the pair
2649    /// `(nome(), versao_requirement())` jointly projects the
2650    /// `(caixa, versao)` field pair every OTP-shape supervisor-tree consumer
2651    /// that fans on per-child identity + version pin keys off, closing the
2652    /// last unlifted per-`:children` `String`-carry axis so every downstream
2653    /// per-`:children` reader now routes through a typed dispatch on the
2654    /// substrate primitive. Named `versao_requirement()` rather than
2655    /// `versao()` because the field's storage-side `.versao` label is
2656    /// already the author-surface term (`:versao`); the accessor's name
2657    /// carries the semantic role — the semver *requirement* string the
2658    /// shared [`crate::version::parse_requirement`] entry-point consumes —
2659    /// so a raw field access and a typed dispatch read differently at every
2660    /// consumer site. Matches the peer [`crate::Membro::versao_requirement`]
2661    /// naming discipline verbatim.
2662    #[must_use]
2663    pub const fn versao_requirement(&self) -> &str {
2664        self.versao.as_str()
2665    }
2666
2667    /// Substrate-canonical per-`:children` `:restart` OTP-shaped
2668    /// per-child post-exit restart-decision policy scalar accessor every
2669    /// consumer that dispatches on the supervised child's post-exit
2670    /// reconcile posture keys off — returns the author-declared
2671    /// `:children :restart` variant verbatim as a [`RestartPolicy`],
2672    /// `Copy`-projected from the typed slot's own [`RestartPolicy`]
2673    /// storage.
2674    ///
2675    /// The `:children :restart` slot carries the closed-set OTP-shaped
2676    /// per-child restart-decision policy discriminator
2677    /// ([`RestartPolicy::Permanent`] — always restart, the OTP `permanent`
2678    /// worker-child default; [`RestartPolicy::Transient`] — restart only
2679    /// on abnormal exit, the OTP `transient` clean-completion-aware
2680    /// default; [`RestartPolicy::Temporary`] — never restart, the OTP
2681    /// `temporary` one-shot default) that every downstream consumer of
2682    /// the Supervisor's per-child post-exit reconcile branch keys off.
2683    /// Every future downstream consumer that fans on the per-child
2684    /// restart-decision keys off this scalar (the future `feira app
2685    /// graph` per-child restart column, the future wasm-operator's
2686    /// per-child post-exit restart-decision branch, the future M4
2687    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
2688    /// admission webhook, the `caixa-operator`'s hierarchical
2689    /// reconciliation scheduler's per-child post-exit reconcile branch,
2690    /// the [`RestartPolicy::as_str`] `Serialize`-derive-pinning path the
2691    /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
2692    /// pin threads through).
2693    ///
2694    /// Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
2695    /// (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
2696    /// scalar accessor and the M3 mesh-slot
2697    /// [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
2698    /// [`crate::PlacementStrategy`] distribution-strategy scalar accessor
2699    /// — same "one typed dispatch on the substrate primitive,
2700    /// `Copy`-projected closed-set enum-arm discriminator that partitions
2701    /// the downstream renderer's per-arm fan-out" discipline extended
2702    /// onto the M2 supervisor-slot per-`:children` restart-decision-policy
2703    /// `Copy`-composite-enum scalar axis. Third axis on the per-`:children`
2704    /// [`ChildSpec`] type — companion to the sibling per-`:children`
2705    /// [`ChildSpec::nome`] (57c61d0) child-caixa `:nome` scalar accessor
2706    /// and the per-`:children` [`ChildSpec::versao_requirement`]
2707    /// (2c053c8) child-caixa `:versao` semver-requirement scalar accessor
2708    /// on the sibling `String`-carry axes. The triple
2709    /// `(nome(), versao_requirement(), restart())` jointly projects the
2710    /// `(caixa, versao, restart)` field trio every OTP-shape supervisor-
2711    /// tree consumer that fans on per-child identity + version pin +
2712    /// restart-decision keys off, closing the last unlifted per-`:children`
2713    /// axis so every downstream per-`:children` reader now routes through
2714    /// a typed dispatch on the substrate primitive. Named `restart()` to
2715    /// match the storage field's name and the author-surface
2716    /// `:children :restart` slot term verbatim; the accessor's identity
2717    /// name maps onto the canonical OTP-shape per-child restart-decision-
2718    /// policy vocabulary the [`RestartPolicy`] enum's docstring already
2719    /// carries.
2720    ///
2721    /// Declared `pub const fn` to close the last non-`const`
2722    /// `Copy`-return raw-field-getter posture on the M2
2723    /// per-`:children` [`ChildSpec`] substrate-primitive surface — peer
2724    /// of the sibling M2 per-`:supervisor`
2725    /// [`SupervisorSpec::estrategia`] (converted in this commit)
2726    /// `Copy`-composite-enum accessor, the sibling M2 per-`:supervisor`
2727    /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
2728    /// already lifted, and the peer M3 mesh-slot per-`:entrada`
2729    /// [`crate::Entrada::port`] (bafa004) / per-`:placement`
2730    /// [`crate::Placement::estrategia`] (bafa004) `Copy`-return
2731    /// `pub const fn` scalar accessors on the sibling M3 surface. Every
2732    /// downstream substrate-side `const`-context consumer of the
2733    /// per-`:children` restart-decision-policy scalar (a future
2734    /// module-scope `const _:() = assert!(matches!(child.restart(),
2735    /// RestartPolicy::Permanent))` invariant pin on a typed fixture, a
2736    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
2737    /// admission-webhook `const fn` per-child restart-decision floor
2738    /// over a typed [`ChildSpec`], any future `const fn` supervisor-tree
2739    /// composer over the substrate primitive that fans on the per-child
2740    /// restart-decision policy at compile time) now reaches through the
2741    /// same typed dispatch on the substrate primitive at const-eval
2742    /// time as at runtime. A future non-`Copy`-return promotion of the
2743    /// scalar (an `Option<RestartPolicy>`-shape migration on the
2744    /// per-child restart-decision axis once heterogeneous per-cluster
2745    /// restart-policy overlays land, a per-tenant restart-policy-alias
2746    /// table the M4 CR materializer resolves per-CR) that would drop
2747    /// the `const` qualifier fails the fail-before-pass-after pin
2748    /// [`tests::child_spec_restart_accessor_is_const_fn`] at caixa-core
2749    /// build time rather than surfacing as a downstream consumer
2750    /// regression.
2751    #[must_use]
2752    pub const fn restart(&self) -> RestartPolicy {
2753        self.restart
2754    }
2755}
2756
2757/// Supervisor-typed slots that live alongside the standard Caixa
2758/// fields when `:kind Supervisor`. Held flat in [`crate::Caixa`] so
2759/// the manifest stays a single typed form; this struct exists for
2760/// validation + conversion.
2761#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
2762#[serde(rename_all = "camelCase")]
2763pub struct SupervisorSpec {
2764    /// Restart strategy. Defaults to [`RestartStrategy::OneForOne`].
2765    #[serde(default)]
2766    pub estrategia: RestartStrategy,
2767
2768    /// Max restarts within [`Self::restart_window`] before the
2769    /// supervisor itself terminates (and its parent supervisor decides
2770    /// what to do). Default 5.
2771    #[serde(default = "default_max_restarts")]
2772    pub max_restarts: u32,
2773
2774    /// Sliding window for `max_restarts`. Authored as a duration
2775    /// string (`"60s"`, `"5m"`); absent = "never reset". A `Some(0s)`
2776    /// is rejected by [`Self::validate`] — Erlang/OTP's
2777    /// `MaxIntensity / Period` invariant requires a positive window
2778    /// (a zero-period supervisor either trips on the first failure or
2779    /// never trips, depending on operator interpretation, neither of
2780    /// which is the author's intent). Omit the slot to express "no
2781    /// reset"; carry a positive duration to express the sliding window.
2782    #[serde(
2783        default,
2784        skip_serializing_if = "Option::is_none",
2785        with = "duration_codec"
2786    )]
2787    pub restart_window: Option<Duration>,
2788
2789    /// Static children. Empty for `SimpleOneForOne` (children added
2790    /// dynamically); required for the other three strategies.
2791    #[serde(default)]
2792    pub children: Vec<ChildSpec>,
2793}
2794
2795const fn default_max_restarts() -> u32 {
2796    // Route the private serde-`#[serde(default = "…")]` helper through
2797    // the substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] typed
2798    // `pub const` rather than the raw `5` literal — one source of truth
2799    // for the Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
2800    // default across the two production consumers that currently
2801    // dispatch on it (this helper via `#[serde(default = "…")]` on
2802    // `SupervisorSpec::max_restarts` and the [`Default for SupervisorSpec`]
2803    // impl at line 962). Pinned by
2804    // `default_max_restarts_helper_routes_through_lifted_default` +
2805    // `supervisor_spec_default_max_restarts_routes_through_lifted_default`
2806    // in the tests module; peer of the sibling caixa-core
2807    // [`crate::manifest::Caixa::supervisor_view`] `unwrap_or(…)` fold
2808    // that now routes its author-omitted `:max-restarts` arm through
2809    // the same lifted constant.
2810    SUPERVISOR_MAX_RESTARTS_DEFAULT
2811}
2812
2813/// Substrate-canonical Erlang/OTP-shaped `MaxIntensity` restart-budget-
2814/// count default for the `:supervisor :max-restarts` axis — the
2815/// canonical `{intensity, 5, 60}` `MaxIntensity` half of Learn You Some
2816/// Erlang's worker-supervisor default, extracted as a typed `pub const`
2817/// so every substrate-side consumer that resolves "what
2818/// [`SupervisorSpec::max_restarts`] value does an author-omitted
2819/// `:max-restarts` slot degrade onto?" reaches for exactly one
2820/// substrate-primitive `u32`.
2821///
2822/// The `:max-restarts` default axis has two production consumers on the
2823/// substrate side today (both prior to this lift folded onto raw `5`
2824/// literals with no compile-time link back to a shared truth): the
2825/// serde-`#[serde(default = "default_max_restarts")]` helper on
2826/// [`SupervisorSpec::max_restarts`] that every author-omitted
2827/// `:supervisor :max-restarts` slot lands in past the derive-macro's
2828/// wire-format compose, and the [`crate::manifest::Caixa::supervisor_view`]
2829/// `.max_restarts().unwrap_or(5)` fold that every downstream consumer of
2830/// the composed [`SupervisorSpec`] altitude reaches through
2831/// (`feira app graph`, the future wasm-operator's per-supervisor
2832/// restart-intensity counter, the future M4
2833/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
2834/// webhook, the caixa-operator's hierarchical reconciliation scheduler).
2835/// A pair of open-coded `5`s across two files that expressed no
2836/// compile-time link back to the shared OTP-canonical default — a
2837/// future rebrand of the default (a tightening to Elixir's
2838/// `Supervisor.max_restarts: 3`, a widening to a per-cluster overlay
2839/// the operator pins through a future
2840/// `:supervisor :max-restarts-overrides` slot the MESH-COMPOSITION
2841/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
2842/// plain `u32` count to a richer `{MaxR, MaxT}` per-child-cohort
2843/// restart-budget-partition once the INSPIRATIONS §II.2 Erlang/OTP
2844/// per-child-cohort roadmap lands) would have had to be threaded
2845/// through both open-coded copies in lockstep or the wire-format
2846/// author-omitted arm and the view-construction author-omitted arm
2847/// would silently disagree on which restart-budget an omitted
2848/// `:max-restarts` resolves to (an author writing `:supervisor
2849/// (:max-restarts ())` would round-trip through serde with the new
2850/// default while `supervisor_view` silently continued to compose the
2851/// stale `5`, or vice versa), a two-consumer split at the composition
2852/// boundary far from the source `caixa.lisp` with no field naming the
2853/// default-drift root cause. Lifting the resolution rule to a typed
2854/// `pub const` on the substrate primitive means every downstream
2855/// consumer of the per-Supervisor default-restart-budget-count surface
2856/// reaches for exactly one substrate-primitive `u32` — the resolver's
2857/// accepted value migrates as a unit on any future axis change.
2858///
2859/// The `5` value pins Learn You Some Erlang's `{intensity, 5, 60}`
2860/// worker-supervisor default (the closest canonical OTP-shape
2861/// production reference the substrate carries, matching the sibling
2862/// `60s` `Period` default the [`Default for SupervisorSpec`] impl pairs
2863/// this constant with on the paired sliding-window axis). Two orders of
2864/// magnitude below the [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` ceiling
2865/// (the upper bracket on the same axis, sibling of this lower default;
2866/// both are typed `u32` const bounds on the `:supervisor :max-restarts`
2867/// axis and now share one accessor discipline on the substrate) and
2868/// above the OTP-`supervisor` callback-module `MaxR = 1` minimum-
2869/// restart floor — the "one restart, then escalate" default is
2870/// deliberately loose enough to absorb a short burst of transient
2871/// child failures without escalating past the supervisor's parent
2872/// while remaining tight enough to trip the `MaxIntensity / Period`
2873/// ratio's escalation on a genuinely-stuck child within the sibling
2874/// `60s` sliding window.
2875///
2876/// Lifted as a typed `pub const` so the bound has exactly one source
2877/// of truth — the serde-side wire-format author-omitted arm at
2878/// [`default_max_restarts`], the [`Default for SupervisorSpec`] impl's
2879/// struct-literal default field, and the caixa-core
2880/// [`crate::manifest::Caixa::supervisor_view`] fold's author-omitted
2881/// arm all read from one place. Same shape every other typed default
2882/// in this crate carries (the sibling
2883/// [`SUPERVISOR_MAX_RESTARTS_MAX`] upper cap on the same axis, the
2884/// paired [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the
2885/// sibling `:restart-window` axis, and the peer
2886/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
2887/// per-renderer defaults on the caixa-flux / caixa-helm rendering
2888/// axes).
2889pub const SUPERVISOR_MAX_RESTARTS_DEFAULT: u32 = 5;
2890
2891/// Upper-bound ceiling on the `:supervisor :max-restarts` axis — every
2892/// validated [`SupervisorSpec::max_restarts`] past
2893/// [`SupervisorSpec::validate`] lies in `1..=SUPERVISOR_MAX_RESTARTS_MAX`.
2894///
2895/// The typed field is `u32` (the zero-floor arm
2896/// [`SupervisorError::ZeroMaxRestarts`] already brackets the bottom edge),
2897/// so a programmatic struct literal
2898/// (`SupervisorSpec { max_restarts: u32::MAX, .. }`) and the equivalent
2899/// author-surface form (`:max-restarts 4294967295` or any
2900/// `:max-restarts 100000`-shape typo landing in the slot) both round-trip
2901/// cleanly through serde — a structurally unbounded `u32` ceiling. The
2902/// runtime substrate consuming the value (Erlang/OTP's
2903/// `MaxIntensity / Period` ratio, the future wasm-operator's
2904/// per-supervisor restart-intensity counter, the M4
2905/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook)
2906/// then turned a typed `:max-restarts` policy into a no-op supervisor: the
2907/// escalation threshold is structurally so high that no realistic
2908/// restarts-per-`:restart-window` traffic shape can reach it, the
2909/// supervisor never escalates to its parent, and a bad child can loop
2910/// inside the window indefinitely with the parent supervisor structurally
2911/// never receiving the "this subtree has exceeded its restart budget"
2912/// signal the typed slot is meant to express — the canonical
2913/// "supervisor intensity declared, no escalation" footgun, exactly the
2914/// peer of the [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap
2915/// on the `:politicas :circuit-breaker :max-failures` axis (both are
2916/// "trip the next-higher protection layer after N events in a rolling
2917/// window" counters with identical degenerate-at-the-high-end shape).
2918///
2919/// The `1000` ceiling matches the sibling
2920/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] (the closest
2921/// peer — same "events-per-window trip threshold" semantics, same `u32`
2922/// type, same no-op-at-the-high-end failure mode) so the M4
2923/// `mesh.pleme.io/v1alpha1/Supervisor` / `.../Aplicacao` CR materializers
2924/// and the future wasm-operator's per-supervisor restart-intensity
2925/// counter reach for either field knowing the value is in `1..=1000`
2926/// without re-validating at the reconciler layer. The cap sits two
2927/// orders of magnitude above every documented Erlang/OTP production
2928/// playbook recommendation (Learn You Some Erlang's
2929/// `{intensity, 5, 60}` worker-supervisor default, Elixir's `Supervisor`
2930/// `max_restarts: 3` default, OTP's `supervisor` callback module
2931/// `MaxR = 1` / `MaxT = 5` "minimal-restart" default, Riak Core's
2932/// typical `MaxR ∈ 5..=100`, RabbitMQ's broker-supervisor `MaxR = 5`
2933/// default) and below the clearly-pathological "effectively no
2934/// escalation" floor (`10_000`, `100_000`, `u32::MAX`): a value the
2935/// author can plausibly want at hyperscale (a long-running supervisor
2936/// over a very-flaky pool tolerating thousands of transient restarts
2937/// before escalating), but a hard wall above which the typed policy is
2938/// structurally a no-op carried verbatim on every emitted child-restart
2939/// reconciliation contract.
2940///
2941/// Lifted as a typed `pub const` so the bound has exactly one source of
2942/// truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
2943/// materializer's admission webhook and the wasm-operator-side
2944/// per-supervisor restart-intensity reconciler read from one place. Same
2945/// shape every other typed upper bound in this crate carries
2946/// ([`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
2947/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
2948/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
2949/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
2950/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
2951/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
2952pub const SUPERVISOR_MAX_RESTARTS_MAX: u32 = 1000;
2953
2954/// Upper-bound ceiling on the `:supervisor :restart-window` axis —
2955/// every validated `Some(`[`SupervisorSpec::restart_window`]`)` past
2956/// [`SupervisorSpec::validate`] lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
2957/// (inclusive on both ends, integer-millisecond magnitudes by the
2958/// canonical-form gate immediately preceding).
2959///
2960/// The typed field is `Option<Duration>` (the zero-floor arm
2961/// [`SupervisorError::RestartWindowZero`] already rejects
2962/// `Some(Duration::ZERO)`, and the canonical-form arm
2963/// [`SupervisorError::RestartWindowNotCanonical`] already rejects
2964/// sub-millisecond residue), so a programmatic struct literal
2965/// (`SupervisorSpec { restart_window: Some(Duration::from_secs(86_400)),
2966/// .. }` — 24h) and the equivalent author-surface form
2967/// (`(:supervisor (:restart-window "24h"))` — the shared duration codec
2968/// emits `"<n>h"` for any integer-hour magnitude) both round-trip
2969/// cleanly through serde — a structurally unbounded `Duration` ceiling.
2970/// A `:restart-window` value far above the documented Erlang/OTP
2971/// `MaxIntensity / Period` production-playbook band (Learn You Some
2972/// Erlang's `{intensity, 5, 60}` worker-supervisor `Period = 60s`
2973/// default, Elixir's `Supervisor` `max_seconds: 5` default, OTP's
2974/// `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's
2975/// `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default)
2976/// degenerates the supervisor's restart-intensity counter into a
2977/// lifetime counter: the rolling failure-counting window is structurally
2978/// so long that transient restarts are never forgotten, so the
2979/// `MaxIntensity / Period` ratio degenerates from "trip the parent
2980/// supervisor when the child has exceeded its restart budget *within
2981/// the recent window*" to "trip the parent when the child has exceeded
2982/// its restart budget *over its lifetime*" — every transient restart
2983/// counts against the budget forever, the supervisor's reset semantic
2984/// never reaches the child, and the typed `:restart-window` slot
2985/// becomes a no-op rolling window carried on every emitted hierarchical
2986/// reconciliation contract. The canonical
2987/// rolling-window-degenerates-to-lifetime-counter footgun the sibling
2988/// [`crate::POLICY_BREAKER_WINDOW_MAX`] cap closes on the peer
2989/// `:politicas :circuit-breaker :window` axis with identical shape (both
2990/// are "rolling failure-counting window with a per-`Period` reset" Duration
2991/// axes whose lifetime-counter degenerate at the high end is the same
2992/// "the reset semantic never fires" CSE invariant violation).
2993///
2994/// The `1h` (3600s = `3_600_000` ms) ceiling matches the largest unit
2995/// the shared duration codec emits (`"<n>h"` for any integer-hour
2996/// magnitude) — every value in the canonical authoring form's
2997/// `<integer><unit>` grammar at or below this cap renders to a clean
2998/// canonical string — and matches the three sibling typed-`Duration`
2999/// caps already lifted to this surface
3000/// ([`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
3001/// [`crate::POLICY_BREAKER_WINDOW_MAX`]). All four typed-`Duration`
3002/// axes — per-process `:limits :wall-clock`, per-edge `:politicas
3003/// :timeout`, per-breaker `:politicas :circuit-breaker :window`, and
3004/// per-supervisor `:supervisor :restart-window` — now share a single
3005/// uniform top edge at the codec's largest emitted unit so the next
3006/// typed-slot wiring (the future wasm-operator's per-supervisor
3007/// `MaxIntensity / Period` reconciler, the M4
3008/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
3009/// webhook, the `caixa-operator`'s hierarchical reconciliation
3010/// scheduler) reaches for any of the four knowing the value is in
3011/// `1ms..=1h` without re-validating at the renderer layer. The cap sits
3012/// two orders of magnitude above every documented Erlang/OTP / Elixir /
3013/// Riak Core / RabbitMQ production-playbook recommendation band
3014/// (`5s..=300s`) and below the clearly-pathological "rolling window
3015/// degenerates to lifetime counter" floor (`24h`, `7d`, `Duration::MAX`):
3016/// a value the author can plausibly want for a very-low-traffic
3017/// long-tail failure-restart window over a hyperscale-flaky child pool,
3018/// but a hard wall above which the rolling-window contract is
3019/// structurally a lifetime-counter contract.
3020///
3021/// Lifted as a typed `pub const` so the bound has exactly one source
3022/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
3023/// materializer's admission webhook, the wasm-operator-side
3024/// per-supervisor `MaxIntensity / Period` reconciler, and the
3025/// `caixa-operator`'s hierarchical reconciliation scheduler all read
3026/// from one place. Same shape every other typed upper bound in this
3027/// crate carries ([`SUPERVISOR_MAX_RESTARTS_MAX`],
3028/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
3029/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
3030/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
3031/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3032/// [`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
3033/// [`crate::POLICY_BREAKER_WINDOW_MAX`],
3034/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3035/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3036pub const SUPERVISOR_RESTART_WINDOW_MAX: Duration = Duration::from_secs(3600);
3037
3038/// Substrate-canonical Erlang/OTP-shaped `Period` sliding-window-duration
3039/// default for the `:supervisor :restart-window` axis — the canonical
3040/// `{intensity, 5, 60}` `Period` half of Learn You Some Erlang's
3041/// worker-supervisor default, extracted as a typed `pub const` so every
3042/// substrate-side consumer that resolves "what
3043/// [`SupervisorSpec::restart_window`] value does an author-omitted
3044/// `:restart-window` slot degrade onto?" reaches for exactly one
3045/// substrate-primitive [`Duration`].
3046///
3047/// The `:restart-window` default axis has one production consumer on the
3048/// substrate side today: the [`Default for SupervisorSpec`] impl's
3049/// struct-literal `restart_window` field, which prior to this lift folded
3050/// onto a raw `Duration::from_secs(60)` literal with no compile-time link
3051/// back to the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity`
3052/// half of the same `{intensity, 5, 60}` OTP-canonical default. The
3053/// [`crate::manifest::Caixa::supervisor_view`] fold deliberately does
3054/// *not* fall back to this default on the sibling `:restart-window` axis
3055/// — an author-omitted `:supervisor :restart-window` composes to
3056/// `restart_window: None` (the shared codec's soft-swallow shape),
3057/// keeping author-declared intent ("no reset — never escalate on rolling
3058/// window") distinct from the [`Default for SupervisorSpec`] "canonical
3059/// 60s Period" arm every programmatic `SupervisorSpec::default()` caller
3060/// resolves to. Prior to this lift the paired `{intensity, 5, 60}` OTP
3061/// default was split across two files with no compile-time link between
3062/// the halves: [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] pinned the
3063/// `MaxIntensity` half at the substrate primitive while the `Period`
3064/// half rode as an open-coded literal at the composition site, so a
3065/// future coherent rebrand of the paired canonical (a tightening to
3066/// Elixir's `{max_restarts: 3, max_seconds: 5}`, a widening to a
3067/// per-cluster overlay the operator pins through a future
3068/// `:supervisor :restart-window-overrides` slot the MESH-COMPOSITION
3069/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
3070/// paired constants to a per-child-cohort `{MaxR, MaxT}` restart-budget-
3071/// partition once the INSPIRATIONS §II.2 Erlang/OTP per-child-cohort
3072/// roadmap lands) would have had to migrate the `MaxIntensity` half
3073/// through the lifted constant and the `Period` half through a raw
3074/// literal in lockstep or the two halves of the same OTP-canonical
3075/// default would silently drift out of pairing. Lifting the resolution
3076/// rule to a typed `pub const` on the substrate primitive means the
3077/// paired OTP-canonical default migrates as one unit on any future
3078/// axis change.
3079///
3080/// The `60s` value pins Learn You Some Erlang's `{intensity, 5, 60}`
3081/// worker-supervisor default (the closest canonical OTP-shape
3082/// production reference the substrate carries, matching the paired
3083/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5` `MaxIntensity` half this
3084/// constant is the `Period` denominator of on the same
3085/// `MaxIntensity / Period` restart-intensity ratio). Two orders of
3086/// magnitude below the [`SUPERVISOR_RESTART_WINDOW_MAX`] `3600s`
3087/// (`1h`) ceiling (the upper bracket on the same axis, sibling of
3088/// this lower default; both are typed [`Duration`] const bounds on the
3089/// `:supervisor :restart-window` axis and now share one accessor
3090/// discipline on the substrate) and above the OTP-`supervisor`
3091/// callback-module `MaxT = 5` seconds "minimal-window" floor — the "60s
3092/// rolling window" default is deliberately loose enough to absorb a
3093/// short burst of transient child failures without escalating past the
3094/// supervisor's parent while remaining tight enough for the paired
3095/// `MaxIntensity / Period` ratio's escalation to trip on a genuinely-
3096/// stuck child within a human-scale observation window.
3097///
3098/// Lifted as a typed `pub const` so the paired OTP-canonical default has
3099/// exactly one source of truth on each half — the sibling
3100/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half and this
3101/// `Period` `60s` half now share the same substrate-primitive lift
3102/// discipline. Same shape every other typed default in this crate
3103/// carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] paired
3104/// `MaxIntensity` half on the same OTP-canonical `{intensity, 5, 60}`,
3105/// the sibling [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the same
3106/// axis, and the peer [`crate::render::DEFAULT_NAMESPACE`] /
3107/// [`crate::render::DEFAULT_LIBRARY_NAME`] per-renderer defaults on the
3108/// caixa-flux / caixa-helm rendering axes).
3109pub const SUPERVISOR_RESTART_WINDOW_DEFAULT: Duration = Duration::from_secs(60);
3110
3111/// Substrate-canonical Erlang/OTP-shaped sibling-restart-strategy default
3112/// for the `:supervisor :estrategia` axis — the canonical `one_for_one`
3113/// half of Learn You Some Erlang's `{one_for_one, intensity, 5, 60}`
3114/// worker-supervisor default, extracted as a typed `pub const` so every
3115/// substrate-side consumer that resolves "what
3116/// [`SupervisorSpec::estrategia`] variant does an author-omitted
3117/// `:estrategia` slot degrade onto?" reaches for exactly one substrate-
3118/// primitive [`RestartStrategy`].
3119///
3120/// The `:estrategia` default axis has three production consumers on the
3121/// substrate side today: the [`Default for RestartStrategy`] impl's
3122/// return arm, the [`Default for SupervisorSpec`] impl's struct-literal
3123/// `estrategia` field, and the
3124/// [`crate::manifest::Caixa::supervisor_view`] fold's
3125/// `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)` `Option<RestartStrategy>`
3126/// collapse arm — three entry points onto the same OTP-canonical
3127/// `one_for_one` value that prior to this lift folded onto a raw
3128/// `Self::OneForOne` arm at the [`Default for RestartStrategy`] impl and
3129/// implicit `RestartStrategy::default()` routes at the sibling consumers,
3130/// with no compile-time link back to the paired
3131/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` half + the paired
3132/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` half of the same
3133/// `{one_for_one, intensity, 5, 60}` OTP-canonical default. The paired
3134/// triple was split across three altitudes with no compile-time link
3135/// between the halves: the `MaxIntensity` half rode through the lifted
3136/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant (b698ec0) and the `Period`
3137/// half rode through the lifted [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
3138/// constant (f7dcd0e) while the `one_for_one` half rode as an open-coded
3139/// discriminator at the [`Default for RestartStrategy`] impl, so a future
3140/// coherent rebrand of the triple (Elixir's `{:one_for_one,
3141/// max_restarts: 3, max_seconds: 5}` — same strategy, different
3142/// intensity/period; an OTP `rest_for_one` widening once the substrate
3143/// discovers startup-order-coupled child cohorts as the more common
3144/// worker-supervisor default; a per-cluster overlay the operator pins
3145/// through a future `:estrategia-overrides` slot the MESH-COMPOSITION
3146/// §III.2 supervision-canary roadmap acknowledges) would have had to
3147/// migrate the `MaxIntensity` + `Period` halves through the lifted
3148/// constants and the `one_for_one` half through an open-coded arm in
3149/// lockstep or the three halves of the same OTP-canonical default would
3150/// silently drift out of pairing. Lifting the resolution rule to a typed
3151/// `pub const` on the substrate primitive means the paired OTP-canonical
3152/// worker-supervisor default migrates as one unit on any future axis
3153/// change.
3154///
3155/// The [`RestartStrategy::OneForOne`] value pins Learn You Some Erlang's
3156/// `{one_for_one, intensity, 5, 60}` worker-supervisor default (the
3157/// closest canonical OTP-shape production reference the substrate
3158/// carries, matching the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5`
3159/// `MaxIntensity` half and the paired [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
3160/// `60s` `Period` half). The `one_for_one` strategy — restart only the
3161/// failed child, leaving siblings untouched — is the default for tree-of-
3162/// independent-workers use cases the substrate's [`RestartStrategy`]
3163/// discriminator's own docstring already carries as the default arm; it
3164/// composes with the `{5, 60}` restart-intensity ratio to name the same
3165/// substrate-canonical "canonical worker-supervisor" shape the paired
3166/// halves close on their respective axes.
3167///
3168/// Lifted as a typed `pub const` so the paired OTP-canonical default has
3169/// exactly one source of truth on each of its three halves — the sibling
3170/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half, the
3171/// sibling [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` `60s` half, and
3172/// this `one_for_one` strategy half now share the same substrate-
3173/// primitive lift discipline. Same shape every other typed default in
3174/// this crate carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] +
3175/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] paired halves on the same OTP-
3176/// canonical `{one_for_one, intensity, 5, 60}`, the sibling
3177/// [`SUPERVISOR_MAX_RESTARTS_MAX`] + [`SUPERVISOR_RESTART_WINDOW_MAX`]
3178/// upper caps on the paired sibling axes, and the peer
3179/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
3180/// per-renderer defaults on the caixa-flux / caixa-helm rendering axes).
3181pub const SUPERVISOR_ESTRATEGIA_DEFAULT: RestartStrategy = RestartStrategy::OneForOne;
3182
3183/// Substrate-canonical Erlang/OTP-shaped per-child restart-decision-policy
3184/// default for the `:children :restart` axis — the OTP `permanent`
3185/// worker-child default (`{ChildId, StartFunc, permanent, …}` in a
3186/// `supervisor`'s `init/1` child-spec tuple), extracted as a typed
3187/// `pub const` so every substrate-side consumer that resolves "what
3188/// [`ChildSpec::restart`] variant does an author-omitted `:children
3189/// :restart` slot degrade onto?" reaches for exactly one substrate-
3190/// primitive [`RestartPolicy`].
3191///
3192/// Completes the OTP-shape supervisor-tree default set at the substrate
3193/// primitive. The per-`:supervisor` axis already carries all three of its
3194/// halves as lifted typed constants — [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
3195/// (`one_for_one`, 95ffacc), [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
3196/// (`MaxIntensity` `5`, b698ec0), [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
3197/// (`Period` `60s`, f7dcd0e) — while the per-`:children` axis's own
3198/// OTP-canonical default rode as an open-coded `Self::Permanent` arm in
3199/// the [`Default for RestartPolicy`] impl, the last un-lifted default on
3200/// the M2 `:supervisor` slot family. The split mattered because the two
3201/// axes resolve *together* on every author-omitted supervisor: a
3202/// `(defcaixa :kind Supervisor :children ((:caixa "worker" :versao
3203/// "^0.1")))` with no `:estrategia` and no per-child `:restart` degrades
3204/// onto `{one_for_one, 5, 60}` through three lifted constants and onto
3205/// `permanent` through an open-coded enum arm, so a future coherent
3206/// rebrand of the OTP-shape default set (an Elixir-shaped
3207/// `{:one_for_one, max_restarts: 3, max_seconds: 5}` tightening, a
3208/// per-cluster overlay the operator pins through the MESH-COMPOSITION
3209/// §III.2 supervision-canary roadmap slots, an OTP-`transient` widening
3210/// once the substrate discovers clean-completion-aware children as the
3211/// more common child shape) would have had to migrate three halves
3212/// through typed constants and the fourth through a raw enum arm in
3213/// lockstep or the supervisor-level and child-level defaults would
3214/// silently drift apart.
3215///
3216/// The `:children :restart` default axis has two production consumers on
3217/// the substrate side today: the [`Default for RestartPolicy`] impl's
3218/// return arm, and the serde-side `#[serde(default)]` on
3219/// [`ChildSpec::restart`] that resolves an author-omitted `:children
3220/// :restart` slot through that same impl. Both now key off this one
3221/// substrate primitive, so the future wasm-operator's per-child post-exit
3222/// restart-decision branch, the future M4
3223/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
3224/// admission webhook, and the `caixa-operator`'s hierarchical
3225/// reconciliation scheduler's per-child fan-out all reach for one typed
3226/// identifier when they resolve an omitted per-child restart posture.
3227///
3228/// The [`RestartPolicy::Permanent`] value pins Erlang/OTP's `permanent`
3229/// worker-child restart type — always restart the child regardless of how
3230/// it died, the canonical posture for long-running services that must
3231/// always be up, matching the sibling [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
3232/// `one_for_one` tree-of-independent-workers strategy this constant pairs
3233/// with under the same `{one_for_one, intensity, 5, 60}` worker-supervisor
3234/// shape. The two alternatives the closed [`RestartPolicy::ALL`] accept-set
3235/// carries ([`RestartPolicy::Transient`] — restart only on abnormal exit;
3236/// [`RestartPolicy::Temporary`] — never restart) express deliberate
3237/// one-shot / clean-completion-aware postures an author declares
3238/// explicitly, never a posture an omitted slot should silently assume.
3239pub const SUPERVISOR_CHILD_RESTART_DEFAULT: RestartPolicy = RestartPolicy::Permanent;
3240
3241/// Route the manually-authored [`Default`] impl on [`SupervisorSpec`]
3242/// through the substrate-canonical [`SupervisorSpec::otp_canonical`]
3243/// `pub const fn` constructor rather than a struct-literal cascade over
3244/// the paired [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
3245/// [`default_max_restarts`] / [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
3246/// lifted consts — one source of truth for the Erlang/OTP-canonical
3247/// `{one_for_one, 5, 60}` worker-supervisor baseline across the two
3248/// paths every downstream consumer already reaches through (the
3249/// hand-authored-until-now [`Default::default`] the
3250/// `..SupervisorSpec::default()` struct-update-syntax on every
3251/// one-axis-under-test fixture in this crate's test module rests on,
3252/// and the `pub const fn` [`SupervisorSpec::otp_canonical`] constructor
3253/// every `const`-context consumer reaches through).
3254///
3255/// Extends the [`Default`]-through-const-ctor fold discipline the
3256/// [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
3257/// (abd52c2), [`crate::aplicacao::MeshPolicy`]
3258/// [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`] (91641a4),
3259/// and [`crate::BehaviorSpec`]
3260/// [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c) folds
3261/// closed on the M2 / M3 `Option`-only "canonical unset baseline"
3262/// typed-slot spec family — extended here onto the M2 supervisor-slot
3263/// [`SupervisorSpec`] whose canonical baseline is not "everything
3264/// `None`" but the OTP-canonical `{one_for_one, 5, 60}` worker-
3265/// supervisor triple. The `empty()` peer's naming did not fit
3266/// (`SupervisorSpec` carries a discriminator-shaped `estrategia` field
3267/// and a non-zero `max_restarts`/`restart_window` pair whose canonical
3268/// shape is Erlang/OTP-descended, not the "no axis declared" bottom
3269/// the sibling `Option`-only slots fold to), so this peer is named
3270/// [`SupervisorSpec::otp_canonical`] instead — the same phrasing the
3271/// existing per-arm pin tests
3272/// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`] /
3273/// [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`] /
3274/// [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
3275/// already reach for. Pinned load-bearing by
3276/// [`tests::supervisor_spec_default_routes_through_otp_canonical_ctor`]
3277/// (byte-parity pin against [`SupervisorSpec::otp_canonical`] under
3278/// [`PartialEq`], sharpening the sibling
3279/// `supervisor_spec_default_*_routes_through_lifted_default` per-arm
3280/// pins from a per-field lift into a whole-struct one-source-of-truth
3281/// pin — the derived-until-now [`Default::default`] and the
3282/// [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
3283/// construction, not by coincidence).
3284impl Default for SupervisorSpec {
3285    #[inline]
3286    fn default() -> Self {
3287        Self::otp_canonical()
3288    }
3289}
3290
3291impl SupervisorSpec {
3292    /// `const`-context peer of the [`Default for SupervisorSpec`]
3293    /// impl (which routes through this constructor) — returns the
3294    /// Erlang/OTP-canonical `{one_for_one, 5, 60}` worker-supervisor
3295    /// baseline this crate reaches for in every fixture-builder
3296    /// `..SupervisorSpec::default()` struct-update expression and
3297    /// every downstream `SupervisorSpec::default()` seed.
3298    ///
3299    /// Each field routes through the same substrate-canonical
3300    /// [`SUPERVISOR_ESTRATEGIA_DEFAULT`] / [`default_max_restarts`] /
3301    /// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] lifted consts the
3302    /// per-arm pin tests
3303    /// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`]
3304    /// / [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`]
3305    /// / [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
3306    /// already assert, so a future coherent rebrand of the OTP-canonical
3307    /// triple (Elixir's `{max_restarts: 3, max_seconds: 5}`, a per-
3308    /// cluster overlay via a future `:restart-window-overrides` slot, a
3309    /// per-child-cohort promotion the INSPIRATIONS.md §II.2 Erlang/OTP
3310    /// absorption roadmap acknowledges) migrates through three typed
3311    /// constants in lockstep, and the paired [`Default`] impl inherits
3312    /// every future extension by construction.
3313    ///
3314    /// `pub const fn` rather than the derived-style `Default::default`
3315    /// or a `pub const SUPERVISOR_SPEC_DEFAULT: SupervisorSpec` item —
3316    /// [`Default::default`] is not `const` on stable Rust, and
3317    /// `SupervisorSpec` is non-`Copy` so a `pub const` item would force
3318    /// every consumer through a [`Clone::clone`]. The `pub const fn`
3319    /// discipline lets `const`-context callers construct the OTP-
3320    /// canonical baseline at compile time without runtime dispatch on
3321    /// the derived [`Default::default`], the same posture the sibling
3322    /// [`crate::LimitsSpec::empty`] (9739971) /
3323    /// [`crate::aplicacao::MeshPolicy::empty`] (6df969b) /
3324    /// [`crate::BehaviorSpec::empty`] (f9b18e3) `Option`-only typed-slot
3325    /// spec `pub const fn` constructors carry on the sibling
3326    /// "everything `None`" baseline axis.
3327    ///
3328    /// Fourth peer on the M2 / M3 typed-slot-spec "const-context peer
3329    /// of the derived-style [`Default`]" family — sibling of the
3330    /// [`crate::LimitsSpec::empty`] / [`crate::aplicacao::MeshPolicy::empty`]
3331    /// / [`crate::BehaviorSpec::empty`] `Option`-only "canonical unset
3332    /// baseline" trio, extended here onto the M2 supervisor-slot
3333    /// [`SupervisorSpec`] whose canonical baseline is not "everything
3334    /// `None`" but the Erlang/OTP-canonical `{one_for_one, 5, 60}`
3335    /// worker-supervisor triple. Named [`Self::otp_canonical`] rather
3336    /// than `empty()` to name the actual invariant the return value
3337    /// pins — the same phrasing already used in the per-arm pin tests
3338    /// on this file. Pinned load-bearing by
3339    /// [`tests::supervisor_spec_otp_canonical_byte_equals_default`] and
3340    /// [`tests::supervisor_spec_otp_canonical_is_usable_in_const_context`].
3341    #[must_use]
3342    pub const fn otp_canonical() -> Self {
3343        Self {
3344            estrategia: SUPERVISOR_ESTRATEGIA_DEFAULT,
3345            max_restarts: default_max_restarts(),
3346            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
3347            children: Vec::new(),
3348        }
3349    }
3350
3351    /// Substrate-canonical per-`:supervisor` `:estrategia` OTP-shaped
3352    /// sibling-restart-strategy scalar accessor every consumer that
3353    /// dispatches on the supervisor's per-sibling restart-decision shape
3354    /// keys off — returns the author-declared `:supervisor :estrategia`
3355    /// variant verbatim as a [`RestartStrategy`], `Copy`-projected from
3356    /// the typed slot's own [`RestartStrategy`] storage.
3357    ///
3358    /// The `:supervisor :estrategia` slot carries the closed-set
3359    /// OTP-shaped sibling-restart-strategy discriminator ([`RestartStrategy::OneForOne`]
3360    /// — restart only the failed child, the Erlang/OTP `one_for_one` default;
3361    /// [`RestartStrategy::OneForAll`] — restart every child on any child
3362    /// failure, the Erlang/OTP `one_for_all` shared-state cohort default;
3363    /// [`RestartStrategy::RestForOne`] — restart the failed child and
3364    /// every child started after it, the Erlang/OTP `rest_for_one`
3365    /// startup-order default; [`RestartStrategy::SimpleOneForOne`] —
3366    /// dynamic children of the same shape, the Erlang/OTP
3367    /// `simple_one_for_one` per-session default) that every downstream
3368    /// consumer of the Supervisor's per-sibling restart-decision fan-out
3369    /// shape keys off. Validated by [`SupervisorSpec::validate`] to be
3370    /// paired coherently with the sibling `:children` axis
3371    /// (`SimpleOneForOne ↔ children.is_empty()` — the cross-slot
3372    /// partition the strategy-arm's [`SupervisorError::SimpleOneForOneWithStaticChildren`]
3373    /// / [`SupervisorError::NoChildren`] refusal cascade pins), and every
3374    /// downstream consumer that reads the strategy keys off this scalar
3375    /// (the [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
3376    /// partition-dispatch `match` arm, the non-`SimpleOneForOne`-arm
3377    /// declared-but-empty [`SupervisorError::NoChildren`] error carrier's
3378    /// `estrategia:` field, the future `feira app graph` per-Supervisor
3379    /// strategy print line, the future wasm-operator's per-supervisor
3380    /// sibling-restart-strategy branch, the future M4
3381    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-strategy
3382    /// admission-webhook resolver, the `caixa-operator`'s hierarchical
3383    /// reconciliation scheduler's per-strategy fan-out).
3384    ///
3385    /// Prior to this lift the `.estrategia` field was accessed inline at
3386    /// two production sites in `caixa-core/src/supervisor.rs` — the
3387    /// [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
3388    /// `match self.estrategia { … }` partition dispatch, and the
3389    /// non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
3390    /// carrier at `estrategia: self.estrategia` — two open-coded
3391    /// field-accesses that expressed no compile-time link back to the
3392    /// typed slot. A future extension of the `:supervisor :estrategia`
3393    /// axis to a richer author surface (a per-cluster strategy override
3394    /// the operator pins through a future `:supervisor :estrategia-overrides`
3395    /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
3396    /// acknowledges, a per-tenant strategy-alias table the M4 CR
3397    /// materializer resolves per-CR, a per-Supervisor dynamic strategy
3398    /// derivation the future adaptive-supervision engine computes from
3399    /// child-failure-history topology, a per-child-cohort strategy split
3400    /// the future `RestForCohort` extension acknowledged by the
3401    /// INSPIRATIONS.md §II.2 Erlang/OTP absorption roadmap acknowledges)
3402    /// would have had to be threaded through every open-coded copy in
3403    /// lockstep — one consumer reading the raw variant while a peer read
3404    /// the operator-resolved variant would silently split the
3405    /// [`SupervisorError::NoChildren`] diagnostic's quoted strategy from
3406    /// the actual partition-dispatch input the empty-children refusal
3407    /// arm reached under, a two-consumer split at the validator far from
3408    /// the source `caixa.lisp` with no field naming the strategy-drift
3409    /// root cause. Lifting the resolution rule to a typed method on the
3410    /// substrate primitive means every downstream consumer of the
3411    /// Supervisor's per-`:supervisor` sibling-restart-strategy surface
3412    /// reaches for exactly one typed dispatch — the resolver's accept-set
3413    /// migrates as a unit on any future axis addition.
3414    ///
3415    /// Peer of the sibling M3 mesh-slot [`crate::Placement::estrategia`]
3416    /// (921fe1b) `Copy`-return `PlacementStrategy` scalar accessor on the
3417    /// per-`:placement` distribution-strategy axis — same "one typed
3418    /// dispatch on the substrate primitive, thin projections at each
3419    /// consumer" discipline extended onto the M2 supervisor-slot
3420    /// per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
3421    /// scalar axis. The two typed axes (`Placement::estrategia` on the
3422    /// M3 Aplicacao side, `SupervisorSpec::estrategia` on the M2
3423    /// Supervisor side) now share one accessor discipline for the shared
3424    /// substrate concept "a `Copy`-projected closed-set enum-arm
3425    /// discriminator that partitions the downstream renderer's per-arm
3426    /// fan-out". First `Copy`-return accessor on the M2 supervisor-slot
3427    /// `SupervisorSpec` type — companion to the sibling per-`:children`
3428    /// [`crate::ChildSpec::nome`] (57c61d0) /
3429    /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
3430    /// scalar accessors on the sibling per-`:children` `String`-carry
3431    /// axes. Named `estrategia()` to match the storage field's name and
3432    /// the peer [`crate::Placement::estrategia`] method-name discipline
3433    /// verbatim; the accessor's identity name maps onto the canonical
3434    /// OTP-shape supervision vocabulary the [`RestartStrategy`] enum's
3435    /// docstring already carries.
3436    ///
3437    /// Declared `pub const fn` to close the M2 supervisor-slot
3438    /// `Copy`-return raw-field-getter `const`-eval-surface pass —
3439    /// sibling of the peer M2 per-`:children` [`ChildSpec::restart`]
3440    /// (converted in this commit) `Copy`-composite-enum accessor, peer
3441    /// of the sibling M2 per-`:supervisor`
3442    /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
3443    /// already lifted, and mirror of the peer M3 mesh-slot
3444    /// per-`:placement` [`crate::Placement::estrategia`] (bafa004)
3445    /// `Copy`-return `pub const fn` scalar accessor whose method-name
3446    /// discipline this accessor was authored to match. Every downstream
3447    /// substrate-side `const`-context consumer of the per-`:supervisor`
3448    /// sibling-restart-strategy scalar (a future module-scope `const
3449    /// _:() = assert!(matches!(sup.estrategia(),
3450    /// RestartStrategy::OneForOne))` invariant pin on a typed fixture,
3451    /// a future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
3452    /// admission-webhook `const fn` per-supervisor strategy-arm floor
3453    /// over a typed [`SupervisorSpec`], any future `const fn`
3454    /// supervisor-tree composer over the substrate primitive that fans
3455    /// on the sibling-restart-strategy at compile time) now reaches
3456    /// through the same typed dispatch on the substrate primitive at
3457    /// const-eval time as at runtime. A future non-`Copy`-return
3458    /// promotion of the scalar (an `Option<RestartStrategy>`-shape
3459    /// migration once the substrate grows per-cluster strategy overlays
3460    /// the [`SupervisorSpec`] docstring already anticipates, a
3461    /// per-tenant strategy-alias table the M4 CR materializer resolves
3462    /// per-CR) that would drop the `const` qualifier fails the
3463    /// fail-before-pass-after pin
3464    /// [`tests::supervisor_spec_estrategia_accessor_is_const_fn`] at
3465    /// caixa-core build time rather than surfacing as a downstream
3466    /// consumer regression.
3467    #[must_use]
3468    pub const fn estrategia(&self) -> RestartStrategy {
3469        self.estrategia
3470    }
3471
3472    /// Substrate-canonical per-`:supervisor` `:max-restarts` OTP-shaped
3473    /// `MaxIntensity` restart-budget scalar accessor every consumer that
3474    /// reads the supervisor's per-`:restart-window` restart-budget count
3475    /// keys off — returns the author-declared `:supervisor :max-restarts`
3476    /// typed `u32` verbatim, `Copy`-projected from the typed slot's own
3477    /// `u32` storage (`u32` is `Copy`, so the accessor returns by value; no
3478    /// borrow of `&self` past the call). Non-optional (the `u32` field
3479    /// carries the restart-budget count as a required axis with a
3480    /// [`default_max_restarts`]-supplied default; the zero-floor arm
3481    /// [`SupervisorError::ZeroMaxRestarts`] and the cap arm
3482    /// [`SupervisorError::MaxRestartsExceedsCap`] jointly bracket the
3483    /// accept-set to `1..=SUPERVISOR_MAX_RESTARTS_MAX`).
3484    ///
3485    /// The `:supervisor :max-restarts` slot carries the Erlang/OTP
3486    /// `MaxIntensity` restart-budget count that pairs with the sibling
3487    /// `:restart-window` `Period` to form the `MaxIntensity / Period`
3488    /// restart-intensity ratio the supervisor trips its own escalation on
3489    /// (`theory/RUNTIME-PATTERNS.md` §II.2, Learn You Some Erlang's
3490    /// `{intensity, 5, 60}` worker-supervisor default). Every downstream
3491    /// consumer of the Supervisor's per-`:supervisor` restart-budget count
3492    /// keys off this scalar (the [`SupervisorSpec::validate`] zero-floor +
3493    /// upper-cap bracket at
3494    /// `require_positive_bounded_u32(self.max_restarts(), …)`, the future
3495    /// wasm-operator's per-supervisor restart-intensity counter's
3496    /// budget-vs-count comparator, the future M4
3497    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
3498    /// webhook, the `caixa-operator`'s hierarchical reconciliation
3499    /// scheduler's per-supervisor escalation-decision branch, every
3500    /// `SupervisorError::MaxRestartsExceedsCap` variant carrying the
3501    /// offending count verbatim for `feira lint` rendering).
3502    ///
3503    /// Prior to this lift the `.max_restarts` field was accessed inline at
3504    /// one production site in `caixa-core/src/supervisor.rs` — the
3505    /// [`SupervisorSpec::validate`] `require_positive_bounded_u32(self
3506    /// .max_restarts, …)` bracket-gate call — one open-coded field-access
3507    /// that expressed no compile-time link back to the typed slot. A
3508    /// future extension of the `:max-restarts` axis to a richer author
3509    /// surface (a per-cluster restart-budget override the operator pins
3510    /// through a future `:supervisor :max-restarts-overrides` slot the
3511    /// MESH-COMPOSITION §III.2 supervision-canary roadmap acknowledges,
3512    /// a per-tenant restart-budget-alias table the M4 CR materializer
3513    /// resolves per-CR, a per-supervisor dynamic restart-budget derivation
3514    /// the future adaptive-supervision engine computes from child-failure-
3515    /// history topology, a promotion of the plain `u32` count to a richer
3516    /// `{MaxR, MaxT}` tuple once Erlang/OTP's per-child-cohort restart-
3517    /// budget-partition slot comes into scope) would have had to be
3518    /// threaded through every open-coded copy in lockstep or the validate
3519    /// gate and the future M4 emit path would silently disagree on which
3520    /// restart-budget count a given supervisor resolves to — an author's
3521    /// `:max-restarts 5` would satisfy validate while the emit path
3522    /// silently read a drifted other value (a `:max-restarts 10000`
3523    /// no-op supervisor at the emit boundary would carry the author's
3524    /// declared `5` verbatim in `feira lint` output while the future
3525    /// wasm-operator's restart-intensity counter operated under the
3526    /// drifted count), a two-consumer split at the validator far from the
3527    /// source `caixa.lisp` with no field naming the restart-budget-drift
3528    /// root cause. Lifting the resolution rule to a typed method on the
3529    /// substrate primitive means every downstream consumer of the
3530    /// Supervisor's per-`:supervisor` restart-budget-count surface reaches
3531    /// for exactly one typed dispatch — the resolver's accept-set migrates
3532    /// as a unit on any future axis addition.
3533    ///
3534    /// Peer of the sibling M3 mesh-slot [`crate::CircuitBreaker::max_failures`]
3535    /// (3a74062) `Copy`-return `u32` sub-struct required-scalar accessor
3536    /// on the per-`:politicas :circuit-breaker :max-failures` Envoy-
3537    /// outlier-detection trip-threshold axis — same "one typed dispatch on
3538    /// the substrate primitive, thin projections at each consumer"
3539    /// discipline extended onto the M2 supervisor-slot per-`:supervisor`
3540    /// restart-budget-count `Copy`-`u32` scalar axis. The two typed axes
3541    /// (`CircuitBreaker::max_failures` on the M3 Aplicacao side,
3542    /// `SupervisorSpec::max_restarts` on the M2 Supervisor side) now share
3543    /// one accessor discipline for the shared substrate concept "a
3544    /// `Copy`-projected required `u32` count that trips the next-higher
3545    /// protection layer after N events in a rolling window" — both are
3546    /// counters with identical degenerate-at-the-high-end shape and share
3547    /// the paired [`crate::POLICY_BREAKER_MAX_FAILURES_MAX`] /
3548    /// [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` cap. Second `Copy`-return
3549    /// accessor on the M2 supervisor-slot `SupervisorSpec` type, sibling
3550    /// to the [`SupervisorSpec::estrategia`] (eafb619) `Copy`-composite-
3551    /// enum `RestartStrategy` accessor. Named `max_restarts()` to match
3552    /// the storage field's name verbatim and the peer
3553    /// [`crate::CircuitBreaker::max_failures`] method-name discipline; the
3554    /// accessor's identity maps onto the canonical OTP-shape supervision
3555    /// vocabulary the [`SupervisorSpec::max_restarts`] field's docstring
3556    /// already carries.
3557    #[must_use]
3558    pub const fn max_restarts(&self) -> u32 {
3559        self.max_restarts
3560    }
3561
3562    /// Substrate-canonical per-`:supervisor` `:restart-window` OTP-shaped
3563    /// `Period` sliding-window scalar accessor every consumer of the
3564    /// supervisor's `MaxIntensity / Period` restart-intensity denominator
3565    /// keys off — returns the author-declared `:supervisor :restart-window`
3566    /// typed [`Duration`] verbatim as an `Option<Duration>`, copied out of
3567    /// the typed slot's own `Option<Duration>` storage (`Duration` is
3568    /// `Copy`, so `Option<Duration>` is `Copy` and the accessor returns by
3569    /// value; no borrow of `&self` past the call). `None` when the slot is
3570    /// absent (the canonical "never reset — every restart across the
3571    /// supervisor's lifetime counts against the sibling `:max-restarts`
3572    /// budget" sentinel the field's own docstring names and the peer
3573    /// `validate_accepts_none_restart_window` pin locks in on the
3574    /// [`SupervisorSpec::validate`] entry-side).
3575    ///
3576    /// The `:supervisor :restart-window` slot carries the Erlang/OTP
3577    /// `Period` sliding-observation-interval that pairs with the sibling
3578    /// `:max-restarts` `MaxIntensity` restart-budget count to form the
3579    /// `MaxIntensity / Period` restart-intensity ratio the supervisor
3580    /// trips its own escalation on (`theory/RUNTIME-PATTERNS.md` §II.2,
3581    /// Learn You Some Erlang's `{intensity, 5, 60}` worker-supervisor
3582    /// default). The typed slot's `Option<Duration>` accept-set —
3583    /// zero-floor rejected through [`SupervisorError::RestartWindowZero`]
3584    /// (Erlang/OTP's `MaxIntensity / Period` invariant requires
3585    /// `Period > 0`; a zero period either trips on the first failure or
3586    /// never trips depending on operator interpretation, neither of which
3587    /// is the author's intent — omit the slot to express "no reset";
3588    /// carry a positive duration to express the sliding window),
3589    /// integer-millisecond canonical form enforced through
3590    /// [`SupervisorError::RestartWindowNotCanonical`] (the duration
3591    /// codec's canonical form emits `"1500ms"` not `"1.5s"` and the
3592    /// future wasm-operator's per-supervisor restart-intensity counter
3593    /// quantizes at milliseconds), upper-bounded by
3594    /// [`SUPERVISOR_RESTART_WINDOW_MAX`] (1h — the coarsest per-
3595    /// supervisor rolling window any operationally-reachable supervisor
3596    /// can honor without spanning multiple scheduler epochs the
3597    /// hierarchical-reconciliation scheduler treats as independent) —
3598    /// maps onto the future wasm-operator (M3) per-supervisor
3599    /// restart-intensity counter's rolling-observation-interval, the
3600    /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
3601    /// per-`spec.restartWindow` admission webhook, and the sibling
3602    /// `duration_codec`-serialized wire scalar every downstream consumer
3603    /// of the supervisor's per-`:supervisor` restart-intensity denominator
3604    /// keys off.
3605    ///
3606    /// Prior to this lift the `.restart_window` field was accessed inline
3607    /// at one production site in `caixa-core/src/supervisor.rs` — the
3608    /// [`SupervisorSpec::validate`] `if let Some(w) = self.restart_window {
3609    /// … }` zero-floor + canonical-form + upper-cap bracket arm — one
3610    /// open-coded field-access that expressed no compile-time link back to
3611    /// the typed slot. A future extension of the `:restart-window` axis to
3612    /// a richer author surface (a per-cluster restart-window override the
3613    /// operator pins through a future `:supervisor :restart-window-overrides`
3614    /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
3615    /// acknowledges, a per-tenant restart-window-alias table the M4 CR
3616    /// materializer resolves per-CR, a per-supervisor dynamic
3617    /// restart-window derivation the future adaptive-supervision engine
3618    /// computes from child-failure-history topology, a promotion of the
3619    /// plain `Option<Duration>` window to a richer `{observation, cooldown}`
3620    /// pair once Erlang/OTP's per-child-cohort observation-interval-
3621    /// partition slot comes into scope) would have had to be threaded
3622    /// through every open-coded copy in lockstep or the validate gate and
3623    /// the future M4 emit path would silently disagree on which
3624    /// restart-window a given supervisor resolves to — an author's
3625    /// `:restart-window "60s"` would satisfy validate while the emit path
3626    /// silently read a drifted other value (a `Some(Duration::from_secs(60))`
3627    /// authored slot at the emit boundary would carry the author's
3628    /// declared window verbatim in `feira lint` output while the future
3629    /// wasm-operator's restart-intensity counter operated under a
3630    /// drifted window, or vice versa: an author's `:restart-window ()`
3631    /// would carry the "never reset" sentinel through validate while the
3632    /// emit path silently substituted a default sliding window), a
3633    /// two-consumer split at the validator far from the source
3634    /// `caixa.lisp` with no field naming the restart-window-drift root
3635    /// cause. Lifting the resolution rule to a typed method on the
3636    /// substrate primitive means every downstream consumer of the
3637    /// Supervisor's per-`:supervisor` restart-intensity-denominator
3638    /// surface reaches for exactly one typed dispatch — the resolver's
3639    /// accept-set migrates as a unit on any future axis addition.
3640    ///
3641    /// Third `Copy`-return accessor on the M2 supervisor-slot
3642    /// `SupervisorSpec` type, closing the last unlifted per-`:supervisor`
3643    /// scalar-value axis (`children: Vec<ChildSpec>` carries a `Vec`
3644    /// payload rather than a `Copy`-scalar, and the per-`:children`
3645    /// [`crate::ChildSpec::nome`] (57c61d0) /
3646    /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
3647    /// scalar accessors already close the per-element `String`-carry
3648    /// axes). Sibling to the peer M2 [`crate::LimitsSpec::wall_clock`]
3649    /// (8cb717b) `Option<Duration>` accessor on the `:limits` slot's
3650    /// per-outermost-call wall-clock-deadline axis and the peer M3
3651    /// [`crate::MeshPolicy::timeout`] (7073d0f) `Option<Duration>`
3652    /// accessor on the `:politicas` slot's per-call-deadline axis — all
3653    /// three share the shared substrate concept "a `Copy`-projected
3654    /// optional `Duration` that carries a positive integer-millisecond
3655    /// canonical value with a `1ms..=<axis-specific>_MAX` accept-set and
3656    /// the paired zero-floor / non-canonical / above-cap refusal cascade"
3657    /// through the same [`crate::render::require_positive_canonical_bounded_duration`]
3658    /// bracket-helper the three axes each route through. Named
3659    /// `restart_window()` to match the storage field's name verbatim and
3660    /// the peer [`crate::LimitsSpec::wall_clock`] /
3661    /// [`crate::MeshPolicy::timeout`] method-name discipline; the
3662    /// accessor's identity maps onto the canonical OTP-shape supervision
3663    /// vocabulary the [`SupervisorSpec::restart_window`] field's docstring
3664    /// already carries.
3665    #[must_use]
3666    pub const fn restart_window(&self) -> Option<Duration> {
3667        self.restart_window
3668    }
3669
3670    /// Substrate-canonical per-`:supervisor` `:children` OTP-shaped
3671    /// static-child-list slice accessor every consumer that walks the
3672    /// supervisor's declared child set keys off — returns the author-
3673    /// declared `:supervisor :children` `Vec<ChildSpec>` verbatim as a
3674    /// `&[ChildSpec]` slice-view, borrowed from the typed slot's own
3675    /// `Vec<ChildSpec>` storage (a zero-copy slice-view over the same
3676    /// backing buffer the `Serialize`/`Deserialize` derives round-trip
3677    /// through). Non-optional: an empty slice is the load-bearing
3678    /// "author declared `:children ()`" sentinel every consumer of the
3679    /// cross-slot `SimpleOneForOne ↔ children.is_empty()` partition
3680    /// keys off (`SimpleOneForOne` requires the empty slice; the peer
3681    /// three strategies require a non-empty slice — the paired
3682    /// [`SupervisorError::SimpleOneForOneWithStaticChildren`] /
3683    /// [`SupervisorError::NoChildren`] refusal cascade pins the
3684    /// partition on both arms).
3685    ///
3686    /// The `:supervisor :children` slot carries the OTP-shaped static
3687    /// child list the supervisor materializes one ComputeUnit per
3688    /// entry from — the Erlang/OTP `supervisor:init/1`'s
3689    /// `{ok, {SupFlags, ChildSpecs}}` `ChildSpecs` list, projected
3690    /// through the tatara-lisp `:children` author surface onto a typed
3691    /// `Vec<ChildSpec>` whose per-element `(nome(),
3692    /// versao_requirement(), restart)` triple the per-child
3693    /// [`SupervisorSpec::validate`] loop already gates through the
3694    /// lifted [`ChildSpec::nome`] (57c61d0) /
3695    /// [`ChildSpec::versao_requirement`] (2c053c8) scalar accessors.
3696    /// Every downstream consumer that fans on the static child list
3697    /// keys off this slice (the [`SupervisorSpec::validate`]
3698    /// `SimpleOneForOne ↔ non-SimpleOneForOne` partition dispatch's
3699    /// `.is_empty()` probe on both arms, the [`SupervisorSpec::validate`]
3700    /// per-child DNS-1123 / semver-requirement / duplicate-detection
3701    /// fan-out loop, every future wasm-operator (M3) per-supervisor
3702    /// hierarchical-reconciliation scheduler's per-child ComputeUnit
3703    /// materialization loop, the future M4
3704    /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
3705    /// admission-webhook fan-out, the future `feira app graph`
3706    /// per-supervisor tree-print traversal).
3707    ///
3708    /// Prior to this lift the `.children` `Vec<ChildSpec>` was accessed
3709    /// inline at three production sites in `caixa-core/src/supervisor.rs`
3710    /// — the [`SupervisorSpec::validate`] `SimpleOneForOne`-arm
3711    /// `!self.children.is_empty()` cross-slot refusal probe, the peer
3712    /// non-`SimpleOneForOne`-arm `self.children.is_empty()`
3713    /// [`SupervisorError::NoChildren`] refusal probe, and the per-child
3714    /// validate loop's `for child in &self.children` traversal head —
3715    /// three open-coded field-accesses that expressed no compile-time
3716    /// link back to the typed slot. A future extension of the
3717    /// `:supervisor :children` axis to a richer author surface (a
3718    /// per-cluster child-set overlay the operator pins through a future
3719    /// `:supervisor :children-overrides` slot the MESH-COMPOSITION §III.2
3720    /// supervision-canary roadmap acknowledges, a per-tenant
3721    /// child-set-alias table the M4 CR materializer resolves per-CR,
3722    /// a per-supervisor dynamic-child derivation the future adaptive-
3723    /// supervision engine computes from child-failure-history topology,
3724    /// a promotion of the plain `Vec<ChildSpec>` to a richer
3725    /// `{static, dynamic}` partition once Erlang/OTP's
3726    /// `simple_one_for_one` dynamic-child slot comes into typed scope)
3727    /// would have had to be threaded through all three open-coded copies
3728    /// in lockstep or one consumer would silently disagree with the
3729    /// peers on which child-set a given supervisor resolves to — the
3730    /// `SimpleOneForOne`-arm probe reading the raw slot while the peer
3731    /// non-`SimpleOneForOne`-arm probe read an operator-resolved slot
3732    /// would silently split the partition-dispatch's two-arm coherence
3733    /// (a supervisor that satisfies neither arm's precondition, or that
3734    /// satisfies both, at the cost of the paired
3735    /// `SimpleOneForOneWithStaticChildren`/`NoChildren` refusal cascade
3736    /// silently drifting from the per-child validate loop's actual
3737    /// traversal input), a three-consumer split at the validator far
3738    /// from the source `caixa.lisp` with no field naming the
3739    /// child-set-drift root cause. Lifting the resolution rule to a
3740    /// typed method on the substrate primitive means every downstream
3741    /// consumer of the Supervisor's per-`:supervisor` static-child-list
3742    /// surface reaches for exactly one typed dispatch — the resolver's
3743    /// accept-set migrates as a unit on any future axis addition.
3744    ///
3745    /// First slice-return (`&[T]`) accessor on any M2 or M3 typed slot
3746    /// — the seed for the same "one typed dispatch on the substrate
3747    /// primitive, thin projections at each consumer" discipline the
3748    /// closed [`crate::LimitsSpec`] / [`BehaviorSpec`] /
3749    /// [`crate::UpgradeFromEntry`] scalar-accessor families each carry
3750    /// on their `Copy` / `Option<Copy>` / `Option<&str>` axes, extended
3751    /// onto the first `Vec`-carry axis on the substrate. The four peer
3752    /// `Vec`-carry axes still unlifted at the time of this seed —
3753    /// [`crate::Placement::clusters`] (`Vec<String>` per-cluster
3754    /// distribution-target list), [`crate::AplicacaoSpec::membros`]
3755    /// (`Vec<Membro>` per-Aplicacao member list),
3756    /// [`crate::AplicacaoSpec::contratos`] (`Vec<WitContract>`
3757    /// per-Aplicacao WIT-typed edge list),
3758    /// [`crate::UpgradeFromEntry::instructions`]
3759    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
3760    /// — inherit this accessor's discipline as future compounding runs
3761    /// migrate their consumers onto the shared slice-return shape.
3762    /// Fourth (and final) accessor on the M2 supervisor-slot
3763    /// `SupervisorSpec` type, sibling to the three `Copy`-return
3764    /// [`SupervisorSpec::estrategia`] (eafb619) /
3765    /// [`SupervisorSpec::max_restarts`] (7844f4e) /
3766    /// [`SupervisorSpec::restart_window`] (7e7b32f) accessors — closes
3767    /// the last unlifted per-`:supervisor` field axis (the
3768    /// `Vec<ChildSpec>` static-child-list carrier) so every downstream
3769    /// per-`:supervisor` reader now routes through a typed dispatch on
3770    /// the substrate primitive. Named `children()` to match the storage
3771    /// field's name verbatim and the tatara-lisp author-surface term
3772    /// (`:children`) the field's own docstring already carries; the
3773    /// accessor's identity maps onto the canonical OTP-shape
3774    /// supervision vocabulary the [`SupervisorSpec::children`] field's
3775    /// docstring already reaches for ("Static children ..."). Returns
3776    /// `&[ChildSpec]` (not `&Vec<ChildSpec>`) because every downstream
3777    /// consumer of the child list treats it as a read-only sequence —
3778    /// the slice-view is the narrowest borrow that supports every
3779    /// present + roadmapped consumer (`.is_empty()`, `.iter()`,
3780    /// index, `.len()`) without leaking the backing `Vec`'s
3781    /// grow/push/reserve surface that no consumer of the typed view
3782    /// reaches for (the storage-side `Vec` remains reachable through
3783    /// the `pub children` field for the mutation-carrying
3784    /// `Caixa::supervisor_view` fold-in path in
3785    /// `manifest.rs:supervisor_view`).
3786    #[must_use]
3787    pub const fn children(&self) -> &[ChildSpec] {
3788        self.children.as_slice()
3789    }
3790
3791    /// Validate the supervisor's typed shape — strategy ↔ children
3792    /// invariants, max_restarts > 0, restart_window > 0 when set,
3793    /// per-child non-empty + duplicate-free names.
3794    ///
3795    /// Mirrors the value-shape discipline applied to every other
3796    /// typed slot:
3797    ///
3798    ///   - `Some(Duration::ZERO)` on a Duration-bearing axis is the
3799    ///     same "0 means the opposite of what you think" footgun
3800    ///     closed for `:politicas :timeout` (Envoy interprets a zero
3801    ///     timeout as `infinite`), `:politicas :circuit-breaker
3802    ///     :window`, and `:limits :wall-clock`. The
3803    ///     `MaxIntensity / Period` ratio in Erlang/OTP's
3804    ///     `supervisor` requires `Period > 0`; a zero period either
3805    ///     trips on the first failure or never trips depending on
3806    ///     operator interpretation, neither of which is the
3807    ///     author's intent. Omit `:restart-window` to express "no
3808    ///     reset"; carry a positive duration to express the window.
3809    ///   - duplicate `:children` `:caixa` names are the same
3810    ///     graph-node-set / multiset distinction closed for
3811    ///     `:membros` (4bb3f3d), `:placement :clusters` (c7c7799),
3812    ///     and `:entrada :paths` (eb3456d). Two children with the
3813    ///     same `:caixa` materialize as two ComputeUnits with the
3814    ///     same name in the cluster's HelmRelease values, one
3815    ///     silently overwriting the other. Erlang/OTP's
3816    ///     `child_spec.id` is required-unique per supervisor;
3817    ///     pleme-io enforces the same set-not-multiset shape on
3818    ///     `:caixa` (the load-bearing identity in our renderer).
3819    pub fn validate(&self) -> Result<(), SupervisorError> {
3820        // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition
3821        // dispatch and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
3822        // error carrier's `estrategia:` field through the lifted
3823        // [`SupervisorSpec::estrategia`] accessor rather than the raw
3824        // `self.estrategia` field access — the two production consumers
3825        // of the per-`:supervisor` sibling-restart-strategy scalar now
3826        // key off exactly one typed dispatch on the substrate primitive,
3827        // so any future rebrand on the axis (a per-cluster strategy
3828        // override the operator pins through a future `:supervisor
3829        // :estrategia-overrides` slot, a per-tenant strategy-alias table
3830        // the M4 CR materializer resolves per-CR) migrates as a single
3831        // caixa-core edit rather than a coordinated rewrite of the two
3832        // call sites — sibling of the peer M3 [`crate::Placement::estrategia`]
3833        // (921fe1b) four-consumer migration on the per-`:placement`
3834        // distribution-strategy axis.
3835        // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition-
3836        // dispatch's paired `.is_empty()` cross-slot refusal probes
3837        // (the `SimpleOneForOne`-arm
3838        // [`SupervisorError::SimpleOneForOneWithStaticChildren`] refusal
3839        // and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
3840        // refusal) through the lifted [`SupervisorSpec::children`]
3841        // slice-return accessor rather than the raw `self.children`
3842        // field access — the two paired production consumers of the
3843        // per-`:supervisor` static-child-list scalar-shape now key off
3844        // exactly one typed dispatch on the substrate primitive, so any
3845        // future rebrand on the axis (a per-cluster child-set overlay
3846        // the operator pins through a future `:supervisor
3847        // :children-overrides` slot, a per-tenant child-set-alias table
3848        // the M4 CR materializer resolves per-CR) migrates as a single
3849        // caixa-core edit rather than a coordinated rewrite of the
3850        // paired arms — first slice-return migration on any typed slot,
3851        // seed for the peer per-`:placement :clusters`,
3852        // per-`:membros`, per-`:contratos`, and per-`:upgrade-from
3853        // :instructions` `Vec`-carry axes.
3854        match self.estrategia() {
3855            RestartStrategy::SimpleOneForOne => {
3856                // SimpleOneForOne: children added at runtime. Static
3857                // list must be empty (one shape declared elsewhere).
3858                if !self.children().is_empty() {
3859                    return Err(SupervisorError::SimpleOneForOneWithStaticChildren);
3860                }
3861            }
3862            _ => {
3863                if self.children().is_empty() {
3864                    return Err(SupervisorError::no_children(self.estrategia()));
3865                }
3866            }
3867        }
3868        // Zero-floor + upper-cap bracket on the typed `:max-restarts`
3869        // axis. See [`crate::render::require_positive_bounded_u32`] for
3870        // the ordering discipline (zero-floor arm strictly precedes cap
3871        // arm so `0` surfaces the self-locating `ZeroMaxRestarts`
3872        // diagnostic with its counter-axis remediation directly named,
3873        // not the misleading `0 > SUPERVISOR_MAX_RESTARTS_MAX == false`
3874        // cap-arm miss). Until this bracket landed the top edge ran all
3875        // the way to `u32::MAX` and a struct-literal
3876        // `SupervisorSpec { max_restarts: 100_000, .. }` (or the
3877        // equivalent author-surface `:max-restarts 100000` /
3878        // `:max-restarts 4294967295` typo landing in the slot) silently
3879        // passed validate. The runtime substrate consuming the value
3880        // (Erlang/OTP's `MaxIntensity / Period` ratio, the future
3881        // wasm-operator's per-supervisor restart-intensity counter, the
3882        // M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
3883        // admission webhook) then turned a typed `:max-restarts`
3884        // policy into a no-op supervisor: the escalation threshold is
3885        // structurally so high that no realistic
3886        // restarts-per-`:restart-window` traffic shape can reach it,
3887        // the supervisor never escalates to its parent, and a bad
3888        // child can loop inside the window indefinitely with the
3889        // parent supervisor structurally never receiving the "this
3890        // subtree has exceeded its restart budget" signal the typed
3891        // slot is meant to express. The bracket set is
3892        // `1..=SUPERVISOR_MAX_RESTARTS_MAX`, peer with the
3893        // [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap on
3894        // the sibling `:politicas :circuit-breaker :max-failures` axis:
3895        // both are "trip the next-higher protection layer after N
3896        // events in a rolling window" counters with identical
3897        // degenerate-at-the-high-end shape and now share one canonical
3898        // bracket helper. The bracket precedes the sibling
3899        // `:restart-window` zero-floor / canonical-millisecond arms so
3900        // an over-cap `max_restarts` paired with a structurally invalid
3901        // window surfaces the bracket diagnostic first, mirroring the
3902        // `PolicyBreakerMaxFailuresExceedsCap` / window-axis cross-arm
3903        // ordering on the peer `:politicas :circuit-breaker` slot.
3904        // Route the [`SupervisorSpec::validate`] `:max-restarts` zero-floor +
3905        // upper-cap bracket-gate through the lifted [`SupervisorSpec::max_restarts`]
3906        // accessor rather than the raw `self.max_restarts` field access —
3907        // the one production consumer of the per-`:supervisor`
3908        // restart-budget-count scalar now keys off exactly one typed
3909        // dispatch on the substrate primitive, so any future rebrand on
3910        // the axis (a per-cluster restart-budget override the operator
3911        // pins through a future `:supervisor :max-restarts-overrides`
3912        // slot, a per-tenant restart-budget-alias table the M4 CR
3913        // materializer resolves per-CR) migrates as a single caixa-core
3914        // edit rather than a coordinated rewrite — sibling of the peer M3
3915        // [`crate::CircuitBreaker::max_failures`] (3a74062) migration on
3916        // the per-`:politicas :circuit-breaker :max-failures` axis.
3917        crate::render::require_positive_bounded_u32(
3918            self.max_restarts(),
3919            SUPERVISOR_MAX_RESTARTS_MAX,
3920            || SupervisorError::ZeroMaxRestarts,
3921            SupervisorError::max_restarts_exceeds_cap,
3922        )?;
3923        // Route the [`SupervisorSpec::validate`] `:restart-window`
3924        // zero-floor + integer-millisecond canonical-form + upper-cap
3925        // bracket-gate through the lifted [`SupervisorSpec::restart_window`]
3926        // accessor rather than the raw `self.restart_window` field access —
3927        // the one production consumer of the per-`:supervisor`
3928        // restart-intensity-denominator scalar now keys off exactly one
3929        // typed dispatch on the substrate primitive, so any future rebrand
3930        // on the axis (a per-cluster restart-window override the operator
3931        // pins through a future `:supervisor :restart-window-overrides`
3932        // slot, a per-tenant restart-window-alias table the M4 CR
3933        // materializer resolves per-CR) migrates as a single caixa-core
3934        // edit rather than a coordinated rewrite — sibling of the peer M2
3935        // [`crate::LimitsSpec::wall_clock`] (8cb717b) validate-arm-route
3936        // on the per-`:limits :wall-clock` axis and the peer M3
3937        // [`crate::MeshPolicy::timeout`] (7073d0f) accessor-route on the
3938        // per-`:politicas :timeout` axis.
3939        if let Some(w) = self.restart_window() {
3940            // Zero-floor + integer-millisecond canonical-form +
3941            // upper-cap bracket on the typed `:restart-window` axis.
3942            // See
3943            // [`crate::render::require_positive_canonical_bounded_duration`]
3944            // for the full three-arm ordering discipline (zero-floor
3945            // strictly precedes canonical-form so `Duration::ZERO`
3946            // surfaces the self-locating `RestartWindowZero`
3947            // diagnostic; canonical-form strictly precedes the cap arm
3948            // so a sub-millisecond above-cap value surfaces the more
3949            // fundamental round-trip-shape diagnostic first) and the
3950            // three peer typed-`Duration` sites that share this
3951            // canonical bracket ([`crate::MeshPolicy::timeout`],
3952            // [`crate::CircuitBreaker::window`],
3953            // [`crate::LimitsSpec::wall_clock`]). Every validated
3954            // value lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
3955            // (1ms..=1h), integer-millisecond granularity.
3956            crate::render::require_positive_canonical_bounded_duration(
3957                w,
3958                SUPERVISOR_RESTART_WINDOW_MAX,
3959                || SupervisorError::RestartWindowZero,
3960                SupervisorError::restart_window_not_canonical,
3961                SupervisorError::restart_window_exceeds_cap,
3962            )?;
3963        }
3964        // Route the per-child DNS-1123 / semver-requirement / duplicate-
3965        // detection fan-out loop through the lifted named per-slot gate
3966        // [`SupervisorSpec::validate_children`] rather than an inline
3967        // three-per-child cascade — every future consumer that wants to
3968        // re-check only the `:children` slot's per-entry axes (the M4
3969        // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
3970        // admission webhook re-validating one added/renamed child, the
3971        // future wasm-operator's per-child dynamic-add re-validator on
3972        // the `SimpleOneForOne` runtime-add path once dynamic-children
3973        // graduate to a typed slot, a future partial re-validator on a
3974        // per-`:children`-entry patch) reaches every per-entry axis
3975        // through one dispatch rather than re-inlining the three-arm
3976        // cascade in lockstep with `validate` or paying the peer
3977        // `:estrategia`/`:max-restarts`/`:restart-window` gates to
3978        // reach one entry check. Sibling of the peer M3 mesh-slot
3979        // per-slot gate family (`validate_membros` — the exact peer on
3980        // the M3 side, [`crate::AplicacaoSpec::validate_membros`];
3981        // `validate_contratos` — 906a5c6; `validate_entrada` — 20cd523;
3982        // `validate_placement`; `validate_politicas` routing through
3983        // `MeshPolicy::validate` — f03a154) — the M2 supervisor-slot
3984        // per-slot gate discipline now spans both the M3 mesh-slot
3985        // family and the M2 `:children` per-child-cascade axis on one
3986        // shape: one named per-slot gate per typed per-entry loop.
3987        self.validate_children()?;
3988        Ok(())
3989    }
3990
3991    /// Named per-slot gate on the M2 `:supervisor :children` per-entry
3992    /// axis — folds the per-child DNS-1123 name gate, semver-requirement
3993    /// gate, and duplicate-`:caixa` dedup arm into one call every
3994    /// consumer that wants to re-validate one `:children` entry (or the
3995    /// whole list) against the same accept-set [`SupervisorSpec::validate`]
3996    /// admits reaches through.
3997    ///
3998    /// Peer of the M3 mesh-slot [`crate::AplicacaoSpec::validate_membros`]
3999    /// per-slot gate on the analogous per-entry axis (`:membros`) — same
4000    /// three-per-entry shape (DNS-1123 name + semver-requirement +
4001    /// duplicate-`:caixa` dedup), lifted to one named substrate
4002    /// primitive per slot. The M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
4003    /// materializer's admission webhook re-checking one added or renamed
4004    /// child, the future wasm-operator's per-child dynamic-add
4005    /// re-validator on the `SimpleOneForOne` runtime-add path once
4006    /// dynamic-children graduate to a typed slot, a future partial
4007    /// re-validator on a per-`:children`-entry patch — each reaches the
4008    /// three per-entry axes through this one dispatch rather than
4009    /// re-inlining the three-arm cascade in lockstep with `validate`
4010    /// (the duplication the PRIME DIRECTIVE names as a bug) or paying
4011    /// the peer `:estrategia`/`:max-restarts`/`:restart-window` gates to
4012    /// reach one entry check.
4013    ///
4014    /// Self-contained on `&self` — resolves its own dedup `HashSet`
4015    /// through [`SupervisorSpec::children`] rather than borrowing one
4016    /// threaded down from `validate`, the same posture the peer M3
4017    /// mesh-slot per-slot gates ([`crate::AplicacaoSpec::validate_membros`],
4018    /// [`crate::AplicacaoSpec::validate_contratos`],
4019    /// [`crate::AplicacaoSpec::validate_entrada`],
4020    /// [`crate::AplicacaoSpec::validate_placement`]) each carry, so a
4021    /// consumer that reaches this gate directly (without first calling
4022    /// `validate`) still runs the full per-child cascade — pinned by
4023    /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
4024    /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
4025    /// + `validate_children_is_self_contained_on_children_slot`.
4026    ///
4027    /// The three per-entry arms run in the same canonical order the
4028    /// pre-lift inline cascade encoded (DNS-1123 → semver → dedup), so
4029    /// the diagnostic every author-declared per-`:children` entry surfaces
4030    /// through `validate` is byte-equal to the diagnostic this gate
4031    /// surfaces when called directly — the equivalence-pin pair
4032    /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
4033    /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
4034    /// asserts the two altitudes discriminate the same set on every
4035    /// per-entry-covered input.
4036    pub fn validate_children(&self) -> Result<(), SupervisorError> {
4037        let mut seen = std::collections::HashSet::new();
4038        for child in self.children() {
4039            // Every emitted cluster artifact's `metadata.name` for a
4040            // supervised child derives from this `:children :caixa` value
4041            // verbatim — the rendered `wasm.pleme.io/v1alpha1/ComputeUnit
4042            // .metadata.name` per child, the [`crate::LABEL_PROGRAM`]
4043            // label value on every child's pod identity, and the per-
4044            // child K8s [`Service`][svc] `metadata.name` the future
4045            // wasm-operator (M3) provisions for inter-child supervision
4046            // tree wiring. Each apiserver-side schema on each landing
4047            // site enforces the DNS-1123 label rule on admission; a
4048            // structurally invalid child name (`"Worker"`, `"my_worker"`,
4049            // `"team.worker"`, `"-worker"`, `"worker-"`, the >63-byte
4050            // UUID-shaped mistaken-identity slug) silently passes the
4051            // prior empty-/duplicate-only gate and the failure surfaces
4052            // at `kubectl apply` time as a `metadata.name: Invalid value`
4053            // rejection, far from the source caixa.lisp, with no field
4054            // naming the offending `:children` entry. Lifting the gate
4055            // to caixa-build time mirrors the `:membros :caixa` value-
4056            // shape trajectory (3f9d7a0) and the `:placement :clusters`
4057            // trajectory (6cbb900) onto the third DNS-1123-label-shaped
4058            // identifier axis — the supervisor tree's child names —
4059            // through the lifted
4060            // [`crate::render::require_valid_dns_1123_label`] gate the
4061            // seven peer name axes (`:membros :caixa`, `:placement
4062            // :clusters`, `:placement :affinity`, `:contratos :de`/`:para`,
4063            // `:entrada :para`, `:nome`, `:upgrade-from :module`) each
4064            // route through, so drift between the eight axes' accepted
4065            // DNS-1123-label sets is structurally impossible.
4066            //
4067            // [svc]: https://kubernetes.io/docs/concepts/services-networking/service/
4068            crate::render::require_valid_dns_1123_label(
4069                child.nome(),
4070                || SupervisorError::EmptyChildName,
4071                |reason| SupervisorError::child_caixa_invalid(child.nome(), reason),
4072            )?;
4073            // The author surface for `:children :versao` is the same
4074            // Cargo-shaped semver requirement string `:deps :versao` and
4075            // `:membros :versao` carry — and the lacre pipeline resolves
4076            // all three axes through the same
4077            // [`crate::version::parse_requirement`] entry-point. The
4078            // shared [`crate::render::require_valid_versao_requirement`]
4079            // helper brackets the empty-first + parse cascade both peer
4080            // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
4081            // [`crate::AplicacaoSpec::validate_membros`] on `:membros
4082            // :versao`) route through, so drift between the three axes'
4083            // accepted requirement sets is structurally impossible and
4084            // the parse-side no-op the empty-first arm closes (semver's
4085            // empty parse yields an implicit `*`) lives in exactly one
4086            // predicate. Every `ChildSpec::versao` past validate is
4087            // round-trippable through [`crate::parse_requirement`]
4088            // without re-checking at the resolver layer, and the three
4089            // `:versao` typed surfaces (`:deps`, `:membros`, `:children`)
4090            // are now structurally equivalent by construction.
4091            crate::render::require_valid_versao_requirement(
4092                child.versao_requirement(),
4093                || SupervisorError::empty_child_version(child.nome()),
4094                |reason| {
4095                    SupervisorError::child_versao_invalid(
4096                        child.nome(),
4097                        child.versao_requirement(),
4098                        reason,
4099                    )
4100                },
4101            )?;
4102            crate::render::insert_first_seen(&mut seen, child.nome(), || {
4103                SupervisorError::duplicate_child_caixa(child.nome())
4104            })?;
4105        }
4106        Ok(())
4107    }
4108}
4109
4110/// Cross-slot coherence gate on the supervision tree: no
4111/// `:children :caixa` entry may name the supervisor's own `:nome`.
4112///
4113/// A supervisor that lists itself as a child is a degenerate self-parent
4114/// — the supervision tree is a DAG rooted at the supervisor (OTP child
4115/// specs reference *distinct* child processes; a supervisor is never its
4116/// own child), and the wasm-operator's hierarchical reconciliation would
4117/// otherwise be handed a node that is its own parent: a one-node cycle it
4118/// either rejects far from the source `caixa.lisp` or recurses on. Because
4119/// every `:nome` is a globally-unique substrate identity (DNS-1123 label +
4120/// lacre closure root), a child whose `:caixa` equals the supervisor's
4121/// `:nome` *is* the supervisor itself, not a coincidentally-named peer.
4122///
4123/// Lives outside [`SupervisorSpec::validate`] because the typed view
4124/// carries the children but not the parent `:nome`; mirrors the
4125/// cross-slot precedence gate `validate_upgrade_from_against_versao`
4126/// (which likewise reads one slot against another at the
4127/// [`crate::layout`] wire-up site) and the mesh self-edge gate
4128/// `AplicacaoSpec`'s `ContratoSelfLoop` — the same "an edge from a graph
4129/// node to itself is structurally not a tree/mesh edge" discipline, here
4130/// on the supervision-tree axis.
4131pub fn validate_no_self_supervision(
4132    children: &[ChildSpec],
4133    parent_nome: &str,
4134) -> Result<(), SupervisorError> {
4135    for child in children {
4136        if child.nome() == parent_nome {
4137            return Err(SupervisorError::child_supervises_self(parent_nome));
4138        }
4139    }
4140    Ok(())
4141}
4142
4143#[derive(Debug, Error, PartialEq, Eq)]
4144pub enum SupervisorError {
4145    #[error("supervisor :estrategia {estrategia:?} requires at least one :children entry")]
4146    NoChildren { estrategia: RestartStrategy },
4147    #[error(
4148        "SimpleOneForOne supervisors must declare zero static children (children spawn dynamically)"
4149    )]
4150    SimpleOneForOneWithStaticChildren,
4151    #[error(":max-restarts must be > 0")]
4152    ZeroMaxRestarts,
4153    #[error(
4154        ":supervisor :max-restarts ({max_restarts}) exceeds the supervisor-policy ceiling \
4155         (SUPERVISOR_MAX_RESTARTS_MAX = 1000) — a value above this cap turns the typed \
4156         restart-intensity policy into a no-op supervisor: the escalation threshold is \
4157         structurally so high that no realistic restarts-per-:restart-window traffic shape \
4158         can reach it, so the supervisor never escalates to its parent and a bad child can \
4159         loop inside the window indefinitely. Every typed-slot consumer (Erlang/OTP's \
4160         MaxIntensity/Period ratio, the future wasm-operator's per-supervisor \
4161         restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
4162         materializer's admission webhook) emits a `:max-restarts` declaration that is \
4163         structurally never reached. Pin a value in 1..=1000 (Erlang/OTP / Elixir / Riak \
4164         Core / RabbitMQ production playbooks recommend 3..=100; the OTP `supervisor` \
4165         callback module's `MaxR = 1` minimal-restart default sits at the bottom of the \
4166         band) or restructure the supervision tree (split the flaky child into its own \
4167         sub-supervisor with a tighter budget) if you need a higher restart tolerance."
4168    )]
4169    MaxRestartsExceedsCap { max_restarts: u32 },
4170    #[error(
4171        ":restart-window must be > 0 when set — Erlang/OTP's MaxIntensity/Period \
4172         requires Period > 0; a zero window either trips on the first failure or \
4173         never trips depending on operator interpretation. Omit :restart-window to \
4174         express `never reset`; carry a positive duration to express the window."
4175    )]
4176    RestartWindowZero,
4177    #[error(
4178        ":supervisor :restart-window ({window:?}) carries a sub-millisecond residue the shared `duration_codec` cannot round-trip — \
4179         the codec truncates to `as_millis()` before picking the canonical unit, so a value with `subsec_nanos() % 1_000_000 != 0` either \
4180         truncates on first serialize (e.g. `Duration::from_micros(1500)` → \"1ms\" → `Duration::from_millis(1)` ≠ original) or renders \
4181         as \"0s\" the `RestartWindowZero` arm then rejects on re-validate. Pin an integer-millisecond magnitude in the canonical authoring form \
4182         (`<integer><unit>` for unit ∈ {{ms, s, m, h}}, e.g. `\"500ms\"`, `\"30s\"`, `\"2m\"`, `\"1h\"`) or omit the field for `never reset`"
4183    )]
4184    RestartWindowNotCanonical { window: Duration },
4185    #[error(
4186        ":supervisor :restart-window ({window:?}) exceeds the supervisor-policy ceiling \
4187         (SUPERVISOR_RESTART_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
4188         per-supervisor rolling-window restart-intensity counter into a lifetime counter: the \
4189         failure-counting window is structurally so long that transient restarts are never \
4190         forgotten, the MaxIntensity/Period ratio degenerates from `trip the parent supervisor \
4191         when the child has exceeded its restart budget within the recent window` to `trip the \
4192         parent when the child has exceeded its restart budget over its lifetime`, and the \
4193         supervisor's reset semantic never reaches the child — every typed-slot consumer \
4194         (Erlang/OTP's MaxIntensity/Period reconciler, the future wasm-operator's \
4195         per-supervisor restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
4196         materializer's admission webhook, the caixa-operator's hierarchical reconciliation \
4197         scheduler) emits a `:restart-window` declaration that is structurally a no-op rolling \
4198         window. Pin a value in 1ms..=1h (Learn You Some Erlang's `{{intensity, 5, 60}}` \
4199         worker-supervisor `Period = 60s` default, Elixir's `Supervisor` `max_seconds: 5` \
4200         default, OTP's `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's \
4201         `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default — every Erlang/OTP \
4202         / Elixir production playbook sits in the 5s..=300s band; the longest documented \
4203         per-supervisor restart-window any pleme-io substrate playbook recommends maxes at \
4204         ~30m) or omit :restart-window to express `never reset` (the supervisor's restart \
4205         budget then becomes a strict lifetime counter by design, not a degenerate one — the \
4206         author surfaces the lifetime-counter semantic explicitly at the slot, rather than \
4207         hiding it behind a rolling-window declaration the cap arm rejects)"
4208    )]
4209    RestartWindowExceedsCap { window: Duration },
4210    #[error("child entry has empty :caixa name")]
4211    EmptyChildName,
4212    #[error(
4213        "child :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
4214         (the K8s apiserver enforces this rule on every `metadata.name` / Service \
4215         name / label value the child name lands in — the per-child \
4216         `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name`, the `LABEL_PROGRAM` \
4217         label value, and the future wasm-operator per-child Service `metadata.name` \
4218         — each apiserver-side schema rejects names that don't match; use a \
4219         lowercase alphanumeric + hyphen identifier like `\"worker\"` or `\"cache-v2\"`)"
4220    )]
4221    ChildCaixaInvalid { caixa: String, reason: String },
4222    #[error("child {caixa:?} has empty :versao constraint")]
4223    EmptyChildVersion { caixa: String },
4224    #[error(
4225        "child {caixa:?} :versao {versao:?} is not a valid semver requirement: \
4226         {reason} (use Cargo-shaped forms like `\"^0.1\"`, `\"~0.1.2\"`, \
4227         `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` and \
4228         `:membros :versao` carry; the lacre pipeline resolves all three \
4229         through the same parser)"
4230    )]
4231    ChildVersaoInvalid {
4232        caixa: String,
4233        versao: String,
4234        reason: String,
4235    },
4236    #[error(
4237        "child {caixa:?} appears more than once (Erlang/OTP requires unique \
4238         child_spec.id per supervisor; duplicate children materialize as duplicate \
4239         ComputeUnits in the rendered chart, one silently overwriting the other)"
4240    )]
4241    DuplicateChildCaixa { caixa: String },
4242    #[error(
4243        "supervisor {caixa:?} lists itself as a :children entry — a supervisor is \
4244         never its own child (the supervision tree is a DAG rooted at the supervisor; \
4245         OTP child specs reference distinct child processes). Since every :nome is a \
4246         globally-unique substrate identity, a child naming the supervisor's own :nome \
4247         is a one-node reconciliation cycle, not a coincidentally-named peer; drop the \
4248         self-referential :children entry or rename it to the actual child caixa."
4249    )]
4250    ChildSupervisesSelf { caixa: String },
4251}
4252
4253// Fold the three `SupervisorError::<Variant> { caixa: <&str>.to_string() }`
4254// caixa-only struct-variant wire-up sites at [`SupervisorSpec::validate_children`]
4255// and [`validate_no_self_supervision`] onto one substrate primitive per
4256// typed variant — the sibling on `SupervisorError` of the four uniform-shape
4257// `LayoutError`-envelope constructor families the peer
4258// [`crate::layout::layout_violation_ctors!`] macro closed (131ca0d, 16
4259// variants on `{ caixa, issue }`), the [`crate::layout::layout_slot_kind_ctors!`]
4260// macro closed (0419438, 4 variants on `{ caixa, kind, slots }`), the
4261// [`crate::LayoutError::missing_entry`] one-variant ctor closed (1b09f9d,
4262// on `{ kind, path }`), and the [`crate::layout::layout_nome_only_ctors!`]
4263// macro closed (3fe3dd7, 6 variants on `<Variant>(String)`), plus the
4264// [`crate::AplicacaoError::entrada_host_invalid`] one-variant ctor
4265// (17dd504, `{ host, reason }`), the [`crate::aplicacao::contrato_target_ctors!`]
4266// macro (14b81d5, 2 variants on `{ de, para, wit, expected }`), and the
4267// [`crate::aplicacao::contrato_empty_pair_ctors!`] macro (8580068, 4
4268// variants on `{ de, para }`) already at that discipline on the peer
4269// `AplicacaoError` envelopes.
4270//
4271// Each of the three wire-up sites on this shape (`EmptyChildVersion` at
4272// the per-`:children` semver-requirement empty-first arm, `DuplicateChildCaixa`
4273// at the per-`:children` dedup arm, `ChildSupervisesSelf` at the cross-slot
4274// self-supervision arm) opened the identical
4275// `SupervisorError::<Variant> { caixa: <&str>.to_string() }` struct-literal —
4276// the exact "same block re-inlined at every consumer" shape the PRIME
4277// DIRECTIVE names as a bug, on the same altitude the peer `LayoutError` /
4278// `AplicacaoError` families each closed on their sibling envelopes. The
4279// three variants share one `{ caixa: String }` shape, so the fold routes
4280// each wire-up site through one dispatch per typed variant.
4281//
4282// The macro below generates one static constructor per variant of shape
4283// `fn <slot>(caixa: &str) -> SupervisorError`, so every wire-up site
4284// collapses onto one dispatch:
4285// `SupervisorError::<slot>(<&str>)`, byte-equal to the pre-lift
4286// struct-literal on the same `&str` fixture. The uniform one-field
4287// construction (`caixa: caixa.to_string()`) is spelled once — inside the
4288// macro — rather than at every wire-up site. Every constructor is
4289// `#[must_use]` so a caller who mistakenly discards the constructed error
4290// trips a compile warning at the wire-up site.
4291//
4292// Every future consumer that wants to construct one of these three
4293// variants outside `SupervisorSpec::validate_children` /
4294// `validate_no_self_supervision` — a deferred
4295// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
4296// webhook re-checking one added/renamed child, a future
4297// `feira validate --supervisor` per-caixa admission verb, a per-child
4298// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path
4299// once dynamic-children graduate to a typed slot, a per-Supervisor
4300// overlay resolver rejecting a duplicate/self-supervising child against
4301// a cluster-local snapshot — now reaches each variant through one call
4302// rather than re-inlining the three-line struct-literal in lockstep
4303// with the three in-crate wire-up sites.
4304macro_rules! supervisor_caixa_only_ctors {
4305    ($($ctor:ident => $variant:ident),* $(,)?) => {
4306        impl SupervisorError {
4307            $(
4308                #[doc = concat!(
4309                    "Construct a [`SupervisorError::",
4310                    stringify!($variant),
4311                    "`] naming the offending `:children :caixa` (or ",
4312                    "supervisor `:nome`, on the self-supervision arm). ",
4313                    "Folds the uniform `Self::",
4314                    stringify!($variant),
4315                    " { caixa: caixa.to_string() }` one-field ",
4316                    "struct-literal onto one substrate primitive so ",
4317                    "every [`SupervisorSpec::validate_children`] / ",
4318                    "[`validate_no_self_supervision`] wire-up on this ",
4319                    "variant reads through one dispatch rather than the ",
4320                    "pre-lift open-coded struct-literal block."
4321                )]
4322                #[must_use]
4323                pub fn $ctor(caixa: &str) -> Self {
4324                    Self::$variant { caixa: caixa.to_string() }
4325                }
4326            )*
4327        }
4328    };
4329}
4330
4331supervisor_caixa_only_ctors! {
4332    empty_child_version => EmptyChildVersion,
4333    duplicate_child_caixa => DuplicateChildCaixa,
4334    child_supervises_self => ChildSupervisesSelf,
4335}
4336
4337// Fold the two `SupervisorError::{ChildCaixaInvalid, ChildVersaoInvalid}`
4338// struct-variant wire-up sites at [`SupervisorSpec::validate_children`] onto
4339// one substrate primitive per typed variant — the M2 supervisor-side siblings
4340// of the peer [`crate::AplicacaoError::membro_caixa_invalid`] two-slot ctor
4341// already lifted through the sibling
4342// [`crate::aplicacao::aplicacao_field_reason_ctors!`] macro (981060b) on the
4343// peer `AplicacaoError { caixa: String, reason: String }` envelope. The
4344// `ChildCaixaInvalid` variant carries the same `{ <name>: String, reason:
4345// String }` two-slot shape the peer seven-variant
4346// [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold closed on the
4347// `AplicacaoError` envelope (`MembroCaixaInvalid`, `EntradaParaInvalid`,
4348// `EntradaHostInvalid`, `EntradaPathInvalid`, `PlacementClusterInvalid`,
4349// `PlacementAffinityInvalid`, `ShardKeyInvalid`); the `ChildVersaoInvalid`
4350// variant carries the `{ caixa: String, versao: String, reason: String }`
4351// three-slot shape the sibling `AplicacaoError::MembroVersaoInvalid` axis
4352// carries on the same `:versao` value-shape.
4353//
4354// Each of the two wire-up sites opened the same closure-shaped
4355// `|reason| SupervisorError::<Variant> { caixa: child.nome().to_string(),
4356// [versao: child.versao_requirement().to_string(),] reason }` block inside
4357// the paired [`crate::render::require_valid_dns_1123_label`] and
4358// [`crate::render::require_valid_versao_requirement`] callbacks — the exact
4359// "same block re-inlined at every consumer" shape the PRIME DIRECTIVE names
4360// as a bug, on the same altitude the peer `AplicacaoError` /
4361// `SupervisorError` / `LayoutError` / `DepError` / `LimitsError` ctor
4362// families already closed on their sibling envelopes.
4363//
4364// The two `#[must_use]` inherent constructors below fold each wire-up onto
4365// one dispatch: `SupervisorError::child_caixa_invalid(<name>, <reason>)`
4366// and `SupervisorError::child_versao_invalid(<name>, <versao>, <reason>)`,
4367// byte-equal to the pre-lift struct-literal on the same scalar fixtures.
4368// The uniform per-field `.to_string()` / `.into()` construction is spelled
4369// once — inside each ctor body — rather than at every wire-up site. The
4370// `reason: impl Into<String>` bound accepts both `&str` literals and
4371// `format!(…)` outputs verbatim so no wire-up site changes its per-arm
4372// diagnostic shape at the lift, matching the peer
4373// [`aplicacao_field_reason_ctors!`] and
4374// [`crate::aplicacao::contrato_pair_value_reason_ctors!`] bounds on the
4375// sibling envelopes.
4376//
4377// Every future consumer that wants to construct one of these two variants
4378// outside `SupervisorSpec::validate_children` — a deferred
4379// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook
4380// re-checking one added/renamed child's `:caixa` or `:versao`, a future
4381// `feira validate --supervisor` per-caixa admission verb, a per-child
4382// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path once
4383// dynamic-children graduate to a typed slot, a per-Supervisor overlay
4384// resolver rejecting a shape-invalid child `:caixa`/`:versao` against a
4385// cluster-local snapshot — now reaches each variant through one call rather
4386// than re-inlining the per-shape struct-literal block in lockstep with the
4387// two in-crate wire-up sites.
4388impl SupervisorError {
4389    /// Construct a [`SupervisorError::ChildCaixaInvalid`] naming the
4390    /// offending `:children :caixa` value under the given `reason`. Folds
4391    /// the uniform `Self::ChildCaixaInvalid { caixa: caixa.to_string(),
4392    /// reason: reason.into() }` two-slot struct-literal onto one substrate
4393    /// primitive so every wire-up on this variant reads through one
4394    /// dispatch, matching the peer
4395    /// [`crate::AplicacaoError::membro_caixa_invalid`] ctor's shape on the
4396    /// sibling `AplicacaoError { caixa: String, reason: String }`
4397    /// envelope. `reason` accepts both `&str` literals and `format!(…)`
4398    /// outputs through the `impl Into<String>` bound.
4399    #[must_use]
4400    pub fn child_caixa_invalid(caixa: &str, reason: impl Into<String>) -> Self {
4401        Self::ChildCaixaInvalid {
4402            caixa: caixa.to_string(),
4403            reason: reason.into(),
4404        }
4405    }
4406
4407    /// Construct a [`SupervisorError::ChildVersaoInvalid`] naming the
4408    /// offending `:children :caixa` and its `:versao` requirement under
4409    /// the given `reason`. Folds the uniform `Self::ChildVersaoInvalid {
4410    /// caixa: caixa.to_string(), versao: versao.to_string(), reason:
4411    /// reason.into() }` three-slot struct-literal onto one substrate
4412    /// primitive so every wire-up on this variant reads through one
4413    /// dispatch, matching the sibling `AplicacaoError::MembroVersaoInvalid
4414    /// { caixa, versao, reason }` three-slot axis on the peer
4415    /// `AplicacaoError` envelope. `reason` accepts both `&str` literals
4416    /// and `format!(…)` outputs through the `impl Into<String>` bound.
4417    #[must_use]
4418    pub fn child_versao_invalid(caixa: &str, versao: &str, reason: impl Into<String>) -> Self {
4419        Self::ChildVersaoInvalid {
4420            caixa: caixa.to_string(),
4421            versao: versao.to_string(),
4422            reason: reason.into(),
4423        }
4424    }
4425}
4426
4427// Fold the four `SupervisorError::<Variant> { <field>: <Copy> }` one-field
4428// Copy-scalar struct-variant wire-up sites at [`SupervisorSpec::validate`]'s
4429// three bracket-arms — one struct-literal at the `:children`-empty
4430// non-`SimpleOneForOne` refusal cascade (`NoChildren { estrategia }`) plus
4431// three `impl FnOnce(<ty>) -> SupervisorError` bracket-closures at the
4432// [`crate::render::require_positive_bounded_u32`] `:max-restarts` cap arm
4433// (`MaxRestartsExceedsCap { max_restarts }`) and the paired
4434// [`crate::render::require_positive_canonical_bounded_duration`]
4435// `:restart-window` canonical-form + cap arms (`RestartWindowNotCanonical
4436// { window }`, `RestartWindowExceedsCap { window }`) — onto one substrate
4437// primitive per typed variant, matching the sibling
4438// [`crate::aplicacao::aplicacao_policy_scalar_ctors!`] macro (7ef425e, 8
4439// variants on the same `{ <field>: Duration | u32 }` shape) at that
4440// discipline on the peer `AplicacaoError` envelope's per-`:politicas`
4441// scalar axis. Every variant is a one-field `Copy`-pass-through struct-
4442// literal — `RestartStrategy | u32 | Duration` — so the fold routes each
4443// wire-up site through one dispatch per typed variant without a runtime-
4444// work delta.
4445//
4446// Each of the four wire-up sites opened the identical
4447// `SupervisorError::<Variant> { <field>: <val> }` struct-literal — the
4448// exact "same block re-inlined at every consumer" shape the PRIME
4449// DIRECTIVE names as a bug, on the same altitude the peer
4450// `aplicacao_policy_scalar_ctors!` fold closed on the sibling
4451// `AplicacaoError` envelope's per-`:politicas` per-axis cap / canonical-
4452// form arms. The four variants share one `{ <field>: <Copy> }` shape, so
4453// the fold routes each wire-up site through one dispatch per typed
4454// variant.
4455//
4456// The macro below generates one static constructor per variant of shape
4457// `const fn <ctor>(<field>: <ty>) -> SupervisorError`, so every wire-up
4458// site collapses onto one dispatch: `SupervisorError::<ctor>(<val>)`,
4459// byte-equal to the pre-lift struct-literal on the same `Copy`-`<ty>`
4460// fixture — as a direct call at the [`SupervisorSpec::validate`]
4461// `:children`-empty refusal, or as a bare function pointer in the
4462// `impl FnOnce(<ty>) -> SupervisorError` bracket-closure slot every
4463// [`crate::render::require_positive_bounded_u32`] /
4464// [`crate::render::require_positive_canonical_bounded_duration`] gate
4465// carries — rather than the pre-lift open-coded one-line closure over
4466// the same one-field struct-literal. `const fn` preserves the `Copy`-
4467// pass-through's zero-runtime-work property verbatim. Every constructor
4468// is `#[must_use]` so a caller who mistakenly discards the constructed
4469// error trips a compile warning at the wire-up site.
4470//
4471// Every future consumer that wants to construct one of these four
4472// variants outside `SupervisorSpec::validate` — a deferred
4473// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
4474// webhook re-checking one edited `:estrategia` / `:max-restarts` /
4475// `:restart-window` slot against the cap + canonical-form cascade, a
4476// future `feira validate --supervisor` per-caixa admission verb re-
4477// running the shape gates on demand, a per-Supervisor overlay resolver
4478// rejecting an author-supplied slot against a cluster-local snapshot —
4479// now reaches each variant through one call rather than re-inlining the
4480// per-shape struct-literal block in lockstep with the four in-crate
4481// wire-up sites.
4482macro_rules! supervisor_scalar_ctors {
4483    ($($ctor:ident => $variant:ident { $field:ident: $ty:ty }),* $(,)?) => {
4484        impl SupervisorError {
4485            $(
4486                #[doc = concat!(
4487                    "Construct a [`SupervisorError::",
4488                    stringify!($variant),
4489                    "`] naming the offending per-`:supervisor` `",
4490                    stringify!($field),
4491                    "` scalar. Folds the uniform `Self::",
4492                    stringify!($variant),
4493                    " { ",
4494                    stringify!($field),
4495                    " }` one-field `Copy`-pass-through struct-literal onto ",
4496                    "one substrate primitive so every per-axis wire-up on ",
4497                    "this variant reads through one dispatch — as a direct ",
4498                    "call (`SupervisorError::",
4499                    stringify!($ctor),
4500                    "(<val>)`, byte-equal to the pre-lift struct-literal on ",
4501                    "the same `Copy`-`",
4502                    stringify!($ty),
4503                    "` fixture) or as a bare function pointer in the ",
4504                    "`impl FnOnce(",
4505                    stringify!($ty),
4506                    ") -> SupervisorError` bracket-closure slot every ",
4507                    "`crate::render::require_positive_bounded_*` / ",
4508                    "`crate::render::require_positive_canonical_bounded_*` ",
4509                    "gate carries — rather than the pre-lift open-coded ",
4510                    "one-line closure over the same one-field struct-",
4511                    "literal. `const fn` preserves the `Copy`-pass-through's ",
4512                    "zero-runtime-work property verbatim."
4513                )]
4514                #[must_use]
4515                pub const fn $ctor($field: $ty) -> Self {
4516                    Self::$variant { $field }
4517                }
4518            )*
4519        }
4520    };
4521}
4522
4523supervisor_scalar_ctors! {
4524    no_children => NoChildren { estrategia: RestartStrategy },
4525    max_restarts_exceeds_cap => MaxRestartsExceedsCap { max_restarts: u32 },
4526    restart_window_not_canonical => RestartWindowNotCanonical { window: Duration },
4527    restart_window_exceeds_cap => RestartWindowExceedsCap { window: Duration },
4528}
4529
4530/// Shared duration string codec for the typed slots that take a
4531/// duration (`restart_window`, `MeshPolicy::timeout`,
4532/// `CircuitBreaker::window`, …). Public so [`crate::aplicacao`] can
4533/// reuse it without duplicating the parser.
4534pub mod duration_codec {
4535    use super::Duration;
4536    use serde::{Deserializer, Serializer};
4537
4538    pub fn serialize<S: Serializer>(v: &Option<Duration>, s: S) -> Result<S::Ok, S::Error> {
4539        // Route through the canonical [`crate::render::serialize_option_via_str`]
4540        // — the substrate-side single-owner primitive for the forward
4541        // arm of the typed-magnitude codec family. See its docstring
4542        // for the full sibling roster.
4543        crate::render::serialize_option_via_str(v, s, render)
4544    }
4545
4546    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Duration>, D::Error> {
4547        // Route through the canonical [`crate::render::deserialize_option_via_str`]
4548        // — the substrate-side single-owner primitive for the reverse
4549        // arm of the typed-magnitude codec family. See its docstring
4550        // for the full sibling roster.
4551        crate::render::deserialize_option_via_str(d, parse)
4552    }
4553
4554    pub(crate) fn parse(s: &str) -> Result<Duration, String> {
4555        // Paired whitespace-rejection arm — same canonical-form
4556        // render-determinism discipline as the peer
4557        // `limits::parse_byte_size` / `limits::parse_duration` /
4558        // `limits::parse_millicores` /
4559        // `aplicacao::rate_limit_codec::parse` sites: the ASCII
4560        // byte-scan closes the WhatWG-conformant whitespace bytes
4561        // (`0x20`, `0x09`, `0x0A`, `0x0C`, `0x0D`), the non-ASCII
4562        // `char::is_whitespace` scan closes the strictly-complementary
4563        // Unicode `White_Space` class (NBSP `\u{00A0}`, LINE SEPARATOR
4564        // `\u{2028}`, EM-SPACE `\u{2003}`, and the peer typography
4565        // codepoints) that `str::trim` at parse entry silently strips.
4566        // Either drift class would round-trip through `render` to a
4567        // *different* canonical form on next emit — breaking the
4568        // THEORY.md Part V render-determinism contract on three typed-
4569        // duration slots at once (`:supervisor :restart-window`,
4570        // `:politicas :timeout`, `:politicas :circuit-breaker :window`)
4571        // via the shared codec.
4572        //
4573        // Routed through the lifted [`crate::render::reject_whitespace`]
4574        // primitive — the substrate-side single-owner paired-arm gate
4575        // every typed-magnitude codec in caixa-core shares.
4576        crate::render::reject_whitespace::<String, _, _>(
4577            s,
4578            |b| {
4579                format!(
4580                    "duration: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
4581                 authoring form for the typed duration slots routed through this shared codec \
4582                 (`:supervisor :restart-window`, `:politicas :timeout`, \
4583                 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
4584                 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no whitespace bytes \
4585                 anywhere. A whitespace-carrying shape (`\" 30s\"`, `\"30s \"`, `\"30 s\"`, \
4586                 `\"\\t30s\"`, `\"30s\\n\"`) round-trips through `render` to a *different* \
4587                 canonical form (`\"30s\"`) on first serialize — breaking the THEORY.md \
4588                 Part V render-determinism contract every typed slot carries. Strip every \
4589                 whitespace byte (write `\"30s\"` verbatim)"
4590                )
4591            },
4592            |ch| {
4593                format!(
4594                    "duration: value {s:?} contains non-ASCII Unicode whitespace character \
4595                 {ch:?} (U+{cp:04X}) — the canonical authoring form for the typed \
4596                 duration slots routed through this shared codec (`:supervisor \
4597                 :restart-window`, `:politicas :timeout`, `:politicas :circuit-breaker \
4598                 :window`) is `<integer><unit>` (e.g. `\"30s\"`, `\"500ms\"`, `\"2m\"`, \
4599                 `\"1h\"`) with no whitespace characters anywhere (ASCII or Unicode). A \
4600                 non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}30s\"`, \
4601                 `\"30s\\u{{2028}}\"`, `\"30\\u{{2003}}s\"`) survives the ASCII byte-scan \
4602                 but `str::trim` (which uses `char::is_whitespace` — the Unicode \
4603                 `White_Space` property, strictly wider than the ASCII byte set) silently \
4604                 strips it at parse entry, and the value round-trips through `render` to \
4605                 a *different* canonical form (`\"30s\"`) on first serialize — breaking \
4606                 the THEORY.md Part V render-determinism contract every typed slot \
4607                 carries. Strip every non-ASCII whitespace character (write `\"30s\"` \
4608                 verbatim with only ASCII bytes)",
4609                    cp = ch as u32
4610                )
4611            },
4612        )?;
4613        let s = s.trim();
4614        // Routed through the lifted
4615        // [`crate::render::split_magnitude_and_alpha_unit`] primitive —
4616        // the single-owner split every ASCII-alphabetic-unit typed-
4617        // magnitude codec in caixa-core (`limits::parse_byte_size` /
4618        // `limits::parse_duration` / this shared duration codec) shares.
4619        // See its docstring for the full sibling roster on the same
4620        // primitive altitude.
4621        let (num_part, unit) = crate::render::split_magnitude_and_alpha_unit(s);
4622        let num_trim = num_part.trim();
4623        // The canonical authoring form for every typed slot routed
4624        // through this shared codec — `:supervisor :restart-window`,
4625        // `:politicas :timeout`, `:politicas :circuit-breaker :window`
4626        // — is `<integer><unit>`. Every magnitude [`render`] emits is a
4627        // non-negative integer with no decimal point and no leading
4628        // sign, so the parser's accepted set must match for
4629        // serialize/deserialize to round-trip without canonical-form
4630        // drift. Until this gate landed the parser accepted any
4631        // `f64`-shaped magnitude (`"1.5s"` → 1500ms, `"1.0s"` → 1s,
4632        // `"0.5m"` → 30s, `"+30s"` → 30s) and serde silently round-
4633        // tripped the value to a *different* canonical string on the
4634        // next emit (`"1.5s"` → 1500ms → `"1500ms"`, `"1.0s"` → 1s →
4635        // `"1s"`, `"0.5m"` → 30s → `"30s"`, `"+30s"` → 30s → `"30s"`)
4636        // — breaking the THEORY.md Part V render-determinism contract
4637        // on three typed slots at once. Same canonical-form discipline
4638        // `crate::limits::parse_duration` (818dd38, the immediate
4639        // predecessor on the peer `:limits :wall-clock` codec) applies;
4640        // this gate lifts the discipline onto the shared codec that
4641        // backs the remaining three typed-duration slots in caixa-core.
4642        //
4643        // Strict canonical form: every byte of the magnitude is an
4644        // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
4645        // inputs the gate distinguishes "non-canonical-but-numeric"
4646        // (parses as f64 or i64 — surfaced with a self-locating
4647        // diagnostic naming the canonical authoring form, the
4648        // round-trip drift each rejected shape would produce on first
4649        // serialize, and the canonical-form remediation) from
4650        // "garbage" (parses as neither — surfaced with the existing
4651        // narrower "bad duration magnitude" wording so its diagnostic
4652        // shape remains stable for the parser-shape footgun case).
4653        // The pre-existing `num < 0.0` arm is now unreachable — the
4654        // digit-only gate strictly precedes magnitude parsing, and a
4655        // leading `-` is not an ASCII digit, so `"-30s"` lands on the
4656        // non-canonical-but-numeric branch with the `-30` named
4657        // verbatim in the diagnostic rather than the prior
4658        // value-laundered "negative duration in \"-30s\"" wording.
4659        //
4660        // Routed through the lifted
4661        // [`crate::render::is_digit_only_magnitude`] predicate — the
4662        // same source of truth the four peer typed-magnitude codec
4663        // sites share.
4664        let digit_only = crate::render::is_digit_only_magnitude(num_trim);
4665        if !digit_only {
4666            let numeric = num_trim.parse::<f64>().is_ok() || num_trim.parse::<i64>().is_ok();
4667            if numeric {
4668                return Err(format!(
4669                    "duration: magnitude {num_trim:?} is not a non-negative integer — the \
4670                     canonical authoring form for the typed duration slots routed through \
4671                     this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
4672                     `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
4673                     `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no decimal point and \
4674                     no leading `+` / `-` sign. A fractional / decimal-shaped magnitude \
4675                     (`\"1.5s\"`, `\"1.0s\"`, `\"0.5m\"`, `\"+30s\"`, `\"-30s\"`) round-trips \
4676                     through `render` to a *different* canonical form (`\"1500ms\"`, `\"1s\"`, \
4677                     `\"30s\"`, `\"30s\"`, `\"30s\"`) on first serialize — breaking the \
4678                     THEORY.md Part V render-determinism contract every typed slot carries. \
4679                     Pick an integer magnitude in the unit that divides cleanly (write \
4680                     `\"1500ms\"` instead of `\"1.5s\"`; `\"30s\"` instead of `\"0.5m\"`)"
4681                ));
4682            }
4683            return Err(format!("bad duration magnitude in {s:?}"));
4684        }
4685        // Leading-zero arm — peer with the `rate_limit_codec` leading-
4686        // zero arm (4f46830) on the same canonical-form render-
4687        // determinism axis. The digit-only gate accepts `"030s"`,
4688        // `"00s"`, `"01h"`, `"0500ms"` as `u64::from_str` parses them
4689        // losslessly (= 30, 0, 1, 500), but `render` emits the leading-
4690        // zero-stripped form (`"30s"`, `"0s"`, `"1h"`, `"500ms"`) — a
4691        // *different* canonical string on the next emit, breaking the
4692        // THEORY.md Part V render-determinism contract the same way
4693        // `"+30s"` did before the leading-`+` arm landed. The single-
4694        // byte magnitude `"0"` (or `"0s"` / `"0ms"`) round-trips
4695        // losslessly through `render` (`render(Duration::ZERO)` emits
4696        // `"0s"`) — the downstream semantic-zero gates (e.g.
4697        // `SupervisorError::ZeroRestartWindow` on
4698        // `:supervisor :restart-window`,
4699        // `AplicacaoError::PolicyTimeoutZero` /
4700        // `PolicyCircuitBreakerWindowZero` on the typed `:politicas`
4701        // duration slots) refuse zero-magnitude authoring at the typed-
4702        // validate layer above, so the single-byte `"0"` stays in the
4703        // accepted set at this codec layer and the diagnostic
4704        // partitioning between canonical-form drift (this arm) and
4705        // semantic-zero (the downstream gates) remains stable.
4706        // Peer with the future leading-zero arms on the two remaining
4707        // typed-magnitude codecs the trajectory acknowledges:
4708        // `limits::parse_duration` backing `:limits :wall-clock`,
4709        // `limits::parse_byte_size` backing `:limits :memory` — each
4710        // carries the same canonical-form-drift class today; this
4711        // gate lands the discipline on the shared duration codec
4712        // first because the `rate_limit_codec` predecessor on the
4713        // same canonical-form-drift axis is the closest peer on the
4714        // trajectory.
4715        //
4716        // Routed through the lifted
4717        // [`crate::render::is_leading_zero_padded_magnitude`]
4718        // predicate — the same source of truth the four peer
4719        // typed-magnitude codec sites share.
4720        if crate::render::is_leading_zero_padded_magnitude(num_trim) {
4721            return Err(format!(
4722                "duration: magnitude {num_trim:?} has a non-canonical leading zero — the \
4723                 canonical authoring form for the typed duration slots routed through \
4724                 this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
4725                 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
4726                 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no leading-zero padding \
4727                 on the magnitude. A leading-zero magnitude (`\"030s\"`, `\"00s\"`, \
4728                 `\"01h\"`, `\"0500ms\"`) round-trips through `render` to a *different* \
4729                 canonical form (`\"30s\"`, `\"0s\"`, `\"1h\"`, `\"500ms\"`) on first \
4730                 serialize — breaking the THEORY.md Part V render-determinism contract \
4731                 every typed slot carries. Strip the leading zeros (write \
4732                 `\"30s\"` instead of `\"030s\"`)"
4733            ));
4734        }
4735        // The digit-only gate guarantees every byte is `[0-9]`, and
4736        // the leading-zero arm above guarantees the magnitude is
4737        // either the single byte `"0"` or starts with `[1-9]`, so
4738        // the only way `u64::from_str` can fail here is overflow (the
4739        // magnitude exceeds `u64::MAX`). Surface that with an
4740        // overflow-shaped wording so the diagnostic names the offending
4741        // magnitude verbatim rather than collapsing onto the
4742        // non-canonical arm. The codec now operates on `u64` end-to-end
4743        // — every accepted magnitude is integer-exact; no f64 mantissa
4744        // drift between author-supplied magnitude and the consumer's
4745        // `Duration` value. Same shape `crate::limits::parse_duration`
4746        // (818dd38) carries on the peer `:limits :wall-clock` axis.
4747        let num: u64 = num_trim.parse::<u64>().map_err(|_| {
4748            format!("bad duration magnitude in {s:?} (digit-only magnitude overflows u64)")
4749        })?;
4750        // Route the `{"ms" | "s" | "" | "m" | "h"} → Duration`
4751        // unit-arm dispatch through the canonical
4752        // [`crate::render::duration_from_integer_magnitude_and_unit`]
4753        // primitive — the substrate-side single-owner unit-dispatch
4754        // table every typed-duration codec in caixa-core routes
4755        // through (peer: `crate::limits::parse_duration` backing
4756        // `:limits :wall-clock`). Every unit conversion is integer-
4757        // exact for an integer magnitude; overflow surfaces via the
4758        // typed `DurationUnitError::Overflow { multiplier }`
4759        // discriminant so this arm reconstructs the pre-lift
4760        // `"duration <num><unit> overflows u64 (magnitude × 60 …)"`
4761        // wording verbatim from `num` / `unit_trim` / the returned
4762        // `multiplier`, and the unknown-unit arm reconstructs the
4763        // pre-lift `"unknown duration unit \"<other>\""` wording from
4764        // the caller-scoped `unit_trim`. Load-bearing pinned by
4765        // `crate::render::tests::duration_from_integer_magnitude_and_unit_matches_pre_lift_unit_dispatch_table`.
4766        let unit_trim = unit.trim();
4767        let dur = crate::render::duration_from_integer_magnitude_and_unit(num, unit_trim).map_err(
4768            |e| match e {
4769                crate::render::DurationUnitError::Overflow { multiplier } => format!(
4770                    "duration {num}{unit_trim} overflows u64 (magnitude × {multiplier} > 2^64-1)"
4771                ),
4772                crate::render::DurationUnitError::UnknownUnit => {
4773                    format!("unknown duration unit {unit_trim:?}")
4774                }
4775            },
4776        )?;
4777        Ok(dur)
4778    }
4779
4780    /// Render a [`Duration`] in the canonical pleme-io duration string
4781    /// form (`"30s"`, `"1m"`, `"1h"`, `"500ms"`). The same form every
4782    /// caixa typed-duration slot serializes to and the same form K8s
4783    /// Gateway API HTTPRoute `timeouts` / `backendRequest` and Cilium
4784    /// EnvoyConfig per-route timeouts both expect (an integer
4785    /// followed by `s`/`m`/`h`/`ms`, no fractional values, no leading
4786    /// `+`). Lifted to `pub` so caixa-side renderers
4787    /// (`caixa-mesh::gateway_routes`'s :politicas :timeout overlay,
4788    /// the future per-:politicas `CiliumClusterwideEnvoyConfig`
4789    /// emitter, the future caixa-otel collector pipeline emitter) can
4790    /// consume the same canonical formatter without re-inlining the
4791    /// magnitude/unit decision tree (and inheriting the same drift
4792    /// footguns: a subtly different `300ms` vs `0.3s` rendering breaks
4793    /// downstream apply-time parsing in non-obvious ways).
4794    pub fn render(d: Duration) -> String {
4795        let total_ms = d.as_millis();
4796        if total_ms == 0 {
4797            return "0s".into();
4798        }
4799        if total_ms.is_multiple_of(3600 * 1000) {
4800            return format!("{}h", total_ms / (3600 * 1000));
4801        }
4802        if total_ms.is_multiple_of(60 * 1000) {
4803            return format!("{}m", total_ms / (60 * 1000));
4804        }
4805        if total_ms.is_multiple_of(1000) {
4806            return format!("{}s", total_ms / 1000);
4807        }
4808        format!("{total_ms}ms")
4809    }
4810
4811    /// True iff `d` round-trips losslessly through [`render`] + [`parse`].
4812    ///
4813    /// [`render`] truncates a `Duration` to `as_millis()` before picking the
4814    /// largest divisor unit, so any sub-millisecond residue
4815    /// (`d.subsec_nanos() % 1_000_000 != 0`) silently breaks the THEORY.md
4816    /// §V.2.7 render-determinism contract:
4817    ///
4818    ///   - `Duration::from_micros(1500)` (= `1_500_000` ns) → `as_millis() == 1`
4819    ///     → renders `"1ms"` → parses back to `Duration::from_millis(1)` =
4820    ///     `1_000_000` ns ≠ original `1_500_000` ns;
4821    ///   - `Duration::from_nanos(1)` (= 1 ns) → `as_millis() == 0` →
4822    ///     renders the literal `"0s"`, which the per-axis zero-floor gate
4823    ///     on every typed-`Duration` slot then rejects on re-validate.
4824    ///
4825    /// Lifted to a `pub` predicate next to the [`render`] / [`parse`] pair so
4826    /// the codec's round-trippable accepted set lives in exactly one place —
4827    /// every typed-`Duration` slot that routes through this shared codec
4828    /// (`SupervisorSpec::restart_window` via [`super::duration_codec`],
4829    /// [`crate::MeshPolicy::timeout`] / [`crate::CircuitBreaker::window`] via
4830    /// `supervisor::duration_codec` + [`super::duration_codec_required`]) and
4831    /// every typed-`Duration` slot whose own codec shares the same
4832    /// `as_millis()`-truncation shape ([`crate::LimitsSpec::wall_clock`] via
4833    /// [`crate::limits`]'s in-module `parse_duration` / `render_duration`
4834    /// pair) calls this predicate from its `validate()` to bracket the
4835    /// accepted set against the codec's accepted set, structurally. Drift
4836    /// between the codec's granularity and any typed slot's accepted set is
4837    /// then a single-source-of-truth edit at this predicate rather than a
4838    /// silent round-trip break the next consumer discovers at apply time.
4839    ///
4840    /// Peer of [`crate::aplicacao::POLICY_RETRIES_MAX`] /
4841    /// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] and the
4842    /// `is_dns_1123_label` / `is_canonical_rate_limit_window` predicate
4843    /// family — same "typed-slot's valid set matches its codec's accepted
4844    /// set, structurally" discipline carried at the codec layer.
4845    #[must_use]
4846    pub fn is_integer_millisecond_duration(d: Duration) -> bool {
4847        d.subsec_nanos().is_multiple_of(1_000_000)
4848    }
4849}
4850
4851/// Required-Duration variant for fields that aren't Option<Duration>.
4852pub mod duration_codec_required {
4853    use super::Duration;
4854    use serde::{Deserialize, Deserializer, Serializer};
4855
4856    pub fn serialize<S: Serializer>(v: &Duration, s: S) -> Result<S::Ok, S::Error> {
4857        s.serialize_str(&super::duration_codec::render(*v))
4858    }
4859
4860    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Duration, D::Error> {
4861        let s = String::deserialize(d)?;
4862        super::duration_codec::parse(&s).map_err(serde::de::Error::custom)
4863    }
4864}
4865
4866#[cfg(test)]
4867mod tests {
4868    use super::*;
4869
4870    fn child(name: &str, ver: &str, restart: RestartPolicy) -> ChildSpec {
4871        ChildSpec {
4872            caixa: name.into(),
4873            versao: ver.into(),
4874            restart,
4875        }
4876    }
4877
4878    #[test]
4879    fn child_spec_string_scalar_accessor_pair_is_const_fn() {
4880        // Fail-before-pass-after pin on [`ChildSpec::nome`] +
4881        // [`ChildSpec::versao_requirement`]'s `const`-eval-surface
4882        // posture. Each accessor projects the per-`:children :caixa`
4883        // / per-`:children :versao` [`String`] storage through the
4884        // `pub const fn` [`String::as_str`] (const-stable since Rust
4885        // 1.87, well within the workspace MSRV) — any future
4886        // accidental downgrade to non-`const` fails the corresponding
4887        // `<name>_via_const_fn` wrapper at caixa-core build time with
4888        // E0015 (`cannot call non-const method`), strictly stronger
4889        // than a runtime `assert!`. Sibling of the peer
4890        // per-M2/M3/universal-axis `String → &str` scalar-accessor
4891        // family pins on the sibling `const`-eval-surface passes
4892        // ([`crate::Caixa::nome`] / [`crate::Caixa::versao`] at the
4893        // top-level manifest, [`crate::CaixaVersion::as_str`] at the
4894        // typed-newtype wrapper, [`crate::aplicacao::Membro::nome`] /
4895        // [`crate::aplicacao::Membro::versao_requirement`] at the M3
4896        // membership axis, [`crate::aplicacao::Entrada::hostname`] /
4897        // [`crate::aplicacao::Entrada::destination`] at the M3
4898        // ingress axis,
4899        // [`crate::upgrade::UpgradeFromEntry::prior_versao`] at the
4900        // M2 upgrade axis, [`crate::dep::Dep::nome`] /
4901        // [`crate::dep::Dep::versao_requirement`] at the dep-graph
4902        // axis, and the per-`:contratos`
4903        // [`crate::aplicacao::WitContract::source`] /
4904        // [`crate::aplicacao::WitContract::destination`] /
4905        // [`crate::aplicacao::WitContract::world_ref`] trio the
4906        // sibling pin at 279823b already anchors).
4907        const fn nome_via_const_fn(c: &ChildSpec) -> &str {
4908            c.nome()
4909        }
4910        const fn versao_via_const_fn(c: &ChildSpec) -> &str {
4911            c.versao_requirement()
4912        }
4913        for (caixa, versao) in [
4914            ("worker-a", "^0.1"),
4915            ("worker-b", "~0.2.3"),
4916            ("collector", "*"),
4917        ] {
4918            let c = child(caixa, versao, RestartPolicy::Permanent);
4919            assert_eq!(nome_via_const_fn(&c), c.nome());
4920            assert_eq!(versao_via_const_fn(&c), c.versao_requirement());
4921            assert_eq!(c.nome(), caixa);
4922            assert_eq!(c.versao_requirement(), versao);
4923        }
4924    }
4925
4926    #[test]
4927    fn supervisor_children_slice_return_accessor_is_const_fn() {
4928        // Fail-before-pass-after pin on [`SupervisorSpec::children`]'s
4929        // `const`-eval-surface posture. The accessor destructures the
4930        // per-`:children` `Vec<ChildSpec>` storage through the
4931        // `pub const fn` [`Vec::as_slice`] (const-stable since Rust
4932        // 1.66, well within the workspace MSRV) — any future
4933        // accidental downgrade to non-`const` fails
4934        // `children_via_const_fn` at caixa-core build time with E0015
4935        // (`cannot call non-const method`), strictly stronger than a
4936        // runtime `assert!`. Sibling of the peer per-M3-mesh-slot
4937        // `Vec → &[T]` slice-return accessor family pin
4938        // [`crate::aplicacao::tests::m3_reference_return_accessor_family_is_const_fn`]
4939        // on the M3 mesh-slot per-`:clusters` / per-`:paths` /
4940        // per-`:membros` / per-`:contratos` slice-return axes, and of
4941        // the peer M2 upgrade-appup axis pin
4942        // [`crate::upgrade::tests::upgrade_from_entry_instructions_slice_return_accessor_is_const_fn`]
4943        // on the per-`:upgrade-from :instructions` slice-return axis.
4944        const fn children_via_const_fn(s: &SupervisorSpec) -> &[ChildSpec] {
4945            s.children()
4946        }
4947        // Sweep both the empty-children (leaf-supervisor with no
4948        // static children — the `SimpleOneForOne` dynamic-child
4949        // arm's canonical shape) and the populated-children
4950        // (`OneForOne` / `OneForAll` / `RestForOne` static-child
4951        // arm's canonical shape) axes so the accessor carries a
4952        // const-dispatch pin on both arms.
4953        let s_empty = SupervisorSpec {
4954            estrategia: RestartStrategy::SimpleOneForOne,
4955            max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
4956            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
4957            children: vec![],
4958        };
4959        assert!(children_via_const_fn(&s_empty).is_empty());
4960        assert_eq!(children_via_const_fn(&s_empty), s_empty.children());
4961        let s_full = SupervisorSpec {
4962            estrategia: RestartStrategy::OneForOne,
4963            max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
4964            restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
4965            children: vec![
4966                child("worker-a", "^0.1", RestartPolicy::Permanent),
4967                child("worker-b", "~0.2.3", RestartPolicy::Transient),
4968                child("collector", "*", RestartPolicy::Temporary),
4969            ],
4970        };
4971        assert_eq!(children_via_const_fn(&s_full).len(), 3);
4972        assert_eq!(children_via_const_fn(&s_full), s_full.children());
4973    }
4974
4975    #[test]
4976    fn default_has_one_for_one_and_5_restarts_in_60s() {
4977        let s = SupervisorSpec::default();
4978        assert_eq!(s.estrategia, RestartStrategy::OneForOne);
4979        assert_eq!(s.max_restarts, 5);
4980        assert_eq!(s.restart_window, Some(Duration::from_secs(60)));
4981        assert!(s.children.is_empty());
4982    }
4983
4984    #[test]
4985    fn validate_one_for_one_requires_children() {
4986        // Explicit-empty via struct-update rather than `let mut s = default(); s.children = vec![];`
4987        // — the peer `validate_simple_one_for_one_forbids_static_children` below already uses
4988        // struct-update to name the axis under test at construction, and this shape matches
4989        // it. Also keeps the "empty children is the axis under test" intent visible at the
4990        // binding site rather than one line down, and side-steps `clippy::field_reassign_with_default`.
4991        let mut s = SupervisorSpec {
4992            children: vec![],
4993            ..SupervisorSpec::default()
4994        };
4995        assert!(matches!(
4996            s.validate().unwrap_err(),
4997            SupervisorError::NoChildren { .. }
4998        ));
4999        s.children = vec![child("worker", "^0.1", RestartPolicy::Permanent)];
5000        s.validate().unwrap();
5001    }
5002
5003    #[test]
5004    fn validate_simple_one_for_one_forbids_static_children() {
5005        let mut s = SupervisorSpec {
5006            estrategia: RestartStrategy::SimpleOneForOne,
5007            ..SupervisorSpec::default()
5008        };
5009        s.children
5010            .push(child("w", "^0.1", RestartPolicy::Permanent));
5011        assert_eq!(
5012            s.validate().unwrap_err(),
5013            SupervisorError::SimpleOneForOneWithStaticChildren
5014        );
5015        s.children.clear();
5016        s.validate().unwrap();
5017    }
5018
5019    #[test]
5020    fn validate_rejects_zero_max_restarts() {
5021        let s = SupervisorSpec {
5022            max_restarts: 0,
5023            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5024            ..SupervisorSpec::default()
5025        };
5026        assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
5027    }
5028
5029    // ── upper-cap: SUPERVISOR_MAX_RESTARTS_MAX brackets the typed slot ─────
5030    //
5031    // The cap arm lifts the `:politicas :circuit-breaker :max-failures` /
5032    // `POLICY_BREAKER_MAX_FAILURES_MAX` (2b51ace) discipline onto the peer
5033    // `:supervisor :max-restarts` axis — both fields are "trip the
5034    // next-higher protection layer after N events in a rolling window"
5035    // counters with identical degenerate-at-the-high-end shape, so the
5036    // typed-slot's accepted set lies in `1..=1000` on the supervisor side
5037    // exactly as it lies in `1..=1000` on the breaker side.
5038
5039    #[test]
5040    fn validate_rejects_max_restarts_above_cap() {
5041        // The fail-before-pass-after pin: `SUPERVISOR_MAX_RESTARTS_MAX +
5042        // 1` is structurally one past the cap and silently passed
5043        // validate on every pre-gate codebase because the typed slot's
5044        // only check was the zero-floor arm. The no-op-supervisor vector
5045        // only surfaced at the runtime substrate (Erlang/OTP
5046        // MaxIntensity/Period ratio, the future wasm-operator's
5047        // per-supervisor restart-intensity counter) far from the source
5048        // caixa.lisp with no field naming the offending supervisor.
5049        let s = SupervisorSpec {
5050            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5051            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5052            ..SupervisorSpec::default()
5053        };
5054        assert_eq!(
5055            s.validate().unwrap_err(),
5056            SupervisorError::MaxRestartsExceedsCap {
5057                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5058            }
5059        );
5060    }
5061
5062    #[test]
5063    fn validate_rejects_max_restarts_far_above_cap() {
5064        // The `u32::MAX` worst case — the four-billion-restart
5065        // threshold a typo (`:max-restarts 4294967295`) or a
5066        // struct-literal copy-paste lands in the slot. Pin the cap
5067        // arm's coverage explicitly across the full `u32` overflow so
5068        // a future relaxation that drops the upper bound surfaces
5069        // here. Same shape every other typed-cap arm on this surface
5070        // carries (POLICY_BREAKER_MAX_FAILURES_MAX,
5071        // POLICY_RETRIES_MAX, POLICY_RATE_LIMIT_MAX).
5072        let s = SupervisorSpec {
5073            max_restarts: u32::MAX,
5074            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5075            ..SupervisorSpec::default()
5076        };
5077        assert_eq!(
5078            s.validate().unwrap_err(),
5079            SupervisorError::MaxRestartsExceedsCap {
5080                max_restarts: u32::MAX,
5081            }
5082        );
5083    }
5084
5085    #[test]
5086    fn validate_accepts_max_restarts_at_cap() {
5087        // The boundary value — exactly SUPERVISOR_MAX_RESTARTS_MAX —
5088        // must validate. The cap is inclusive on the top edge,
5089        // matching the POLICY_BREAKER_MAX_FAILURES_MAX /
5090        // POLICY_RETRIES_MAX / LIMITS_MEMORY_WASM32_MAX_BYTES
5091        // discipline on the sibling capped axes. Pin the boundary
5092        // explicitly so a future off-by-one tightening
5093        // (`>= SUPERVISOR_MAX_RESTARTS_MAX` instead of `>`) surfaces
5094        // here as a test failure rather than a silent contract
5095        // narrowing.
5096        let s = SupervisorSpec {
5097            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX,
5098            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5099            ..SupervisorSpec::default()
5100        };
5101        s.validate()
5102            .expect("max_restarts == SUPERVISOR_MAX_RESTARTS_MAX must validate");
5103    }
5104
5105    #[test]
5106    fn validate_accepts_max_restarts_typical_values() {
5107        // The documented production-playbook band positive-control
5108        // sweep — every value Erlang/OTP / Elixir / Riak Core /
5109        // RabbitMQ recommend (1..=100) must pass, plus a sweep
5110        // through the hyperscale band (200, 500, 1000) the cap
5111        // accepts. Pin the inclusive validated set explicitly so a
5112        // future tightening of the ceiling surfaces here.
5113        for n in [1u32, 3, 5, 10, 20, 50, 100, 200, 500, 1000] {
5114            let s = SupervisorSpec {
5115                max_restarts: n,
5116                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5117                ..SupervisorSpec::default()
5118            };
5119            s.validate()
5120                .unwrap_or_else(|e| panic!("max_restarts={n} must validate; got {e:?}"));
5121        }
5122    }
5123
5124    #[test]
5125    fn zero_max_restarts_takes_precedence_over_cap() {
5126        // The cross-arm ordering pin: `0` is structurally outside
5127        // both `1..` (zero-floor) and `..=SUPERVISOR_MAX_RESTARTS_MAX`
5128        // (cap), but the zero-floor diagnostic is the more
5129        // self-locating one (it directly names the counter-axis
5130        // remediation), so the validate gate must fire on zero first.
5131        // Same shape every other zero-then-shape ordering on this
5132        // surface uses (PolicyRetriesZero then
5133        // PolicyRetriesExceedsCap; PolicyBreakerZeroFailures then
5134        // PolicyBreakerMaxFailuresExceedsCap).
5135        let s = SupervisorSpec {
5136            max_restarts: 0,
5137            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5138            ..SupervisorSpec::default()
5139        };
5140        assert_eq!(
5141            s.validate().unwrap_err(),
5142            SupervisorError::ZeroMaxRestarts,
5143            "max_restarts == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
5144        );
5145    }
5146
5147    #[test]
5148    fn max_restarts_cap_takes_precedence_over_restart_window_gates() {
5149        // The cross-arm ordering pin between the cap and the sibling
5150        // `:restart-window` gates (zero-window, canonical-window). A
5151        // supervisor carrying both an over-cap `max_restarts` AND a
5152        // structurally invalid window (zero, sub-ms) must surface the
5153        // cap diagnostic first — the cap arm is wired immediately
5154        // after the zero-restart arm and strictly before the window
5155        // arms, so the offending value the diagnostic names matches
5156        // the order the author would discover the gates by reading
5157        // top-to-bottom through `SupervisorSpec::validate`. Pin the
5158        // order so a future refactor that reorders the arms surfaces
5159        // here as a test failure rather than a silent diagnostic
5160        // regression. Peer of
5161        // `circuit_breaker_max_failures_cap_takes_precedence_over_window_gates`
5162        // on the sibling `:politicas :circuit-breaker` slot.
5163        let s = SupervisorSpec {
5164            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5165            restart_window: Some(Duration::ZERO),
5166            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5167            ..SupervisorSpec::default()
5168        };
5169        assert_eq!(
5170            s.validate().unwrap_err(),
5171            SupervisorError::MaxRestartsExceedsCap {
5172                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5173            },
5174            "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
5175        );
5176    }
5177
5178    #[test]
5179    fn max_restarts_cap_diagnostic_carries_offending_value() {
5180        // The diagnostic-shape pin: the offending `u32` is carried
5181        // verbatim into the `SupervisorError::MaxRestartsExceedsCap`
5182        // variant so the surfaced error message names the value the
5183        // author wrote (`":supervisor :max-restarts (50000) exceeds the
5184        // supervisor-policy ceiling …"`), not just the cap. Same
5185        // self-locating diagnostic shape every other typed-cap arm on
5186        // this surface carries
5187        // (`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap` carries
5188        // the offending failure count verbatim,
5189        // `AplicacaoError::PolicyRetriesExceedsCap` carries the offending
5190        // retries count verbatim).
5191        let s = SupervisorSpec {
5192            max_restarts: 50_000,
5193            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5194            ..SupervisorSpec::default()
5195        };
5196        let err = s.validate().unwrap_err();
5197        assert!(
5198            matches!(
5199                err,
5200                SupervisorError::MaxRestartsExceedsCap {
5201                    max_restarts: 50_000
5202                }
5203            ),
5204            "got {err:?}"
5205        );
5206        let msg = err.to_string();
5207        assert!(
5208            msg.contains("50000"),
5209            ":supervisor :max-restarts cap diagnostic must carry the offending value verbatim (got: {msg})"
5210        );
5211    }
5212
5213    #[test]
5214    fn supervisor_max_restarts_default_pins_otp_canonical_value() {
5215        // Pin [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] at `5` — the
5216        // Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
5217        // half of Learn You Some Erlang's worker-supervisor default,
5218        // sibling of the `60s` `Period` half that the paired
5219        // [`Default for SupervisorSpec`] impl already pins on the
5220        // sibling `restart_window` axis. Pinning the literal here
5221        // surfaces a future rebrand (a tightening to Elixir's `3`,
5222        // a widening to a per-cluster overlay the operator pins
5223        // through a future `:max-restarts-overrides` slot) as a
5224        // deliberate test edit, not a silent contract migration.
5225        // Peer of the sibling
5226        // [`supervisor_max_restarts_cap_pins_canonical_value`]
5227        // upper-bracket pin on the same axis.
5228        assert_eq!(SUPERVISOR_MAX_RESTARTS_DEFAULT, 5);
5229    }
5230
5231    #[test]
5232    fn default_max_restarts_helper_routes_through_lifted_default() {
5233        // Composition pin: the private `default_max_restarts()`
5234        // serde-`#[serde(default = "…")]` helper on
5235        // [`SupervisorSpec::max_restarts`] must route through the
5236        // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
5237        // typed `pub const` rather than a raw `5` literal. Prior to
5238        // the lift the helper carried an inline `5` with no compile-
5239        // time link back to the shared default, so the wire-format
5240        // author-omitted arm and the caixa-core
5241        // [`crate::manifest::Caixa::supervisor_view`] fold's `unwrap_or(5)`
5242        // arm could silently split on any future default rebrand.
5243        // Byte-parity against the lifted constant closes the split.
5244        assert_eq!(default_max_restarts(), SUPERVISOR_MAX_RESTARTS_DEFAULT);
5245    }
5246
5247    #[test]
5248    fn supervisor_spec_default_max_restarts_routes_through_lifted_default() {
5249        // Composition pin: the [`Default for SupervisorSpec`] impl's
5250        // struct-literal `max_restarts` field must route through the
5251        // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
5252        // typed `pub const` (via the private helper this test's
5253        // sibling `default_max_restarts_helper_routes_through_lifted_default`
5254        // already pins onto the constant). Structurally: every
5255        // `SupervisorSpec::default()` call must yield a
5256        // `max_restarts` field byte-equal to the lifted constant
5257        // (the two paired defaults — the serde-side wire-format arm
5258        // and the struct-literal default arm — cannot silently split
5259        // on any future default rebrand). Peer of the sibling
5260        // `default_has_one_for_one_and_5_restarts_in_60s` shape pin
5261        // — this pin closes the byte-parity arm on the two paired
5262        // altitude entry points onto the shared substrate constant.
5263        assert_eq!(
5264            SupervisorSpec::default().max_restarts(),
5265            SUPERVISOR_MAX_RESTARTS_DEFAULT,
5266        );
5267    }
5268
5269    #[test]
5270    fn supervisor_restart_window_default_pins_otp_canonical_value() {
5271        // Pin [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] at `60s` — the
5272        // Erlang/OTP-canonical `{intensity, 5, 60}` `Period` half of
5273        // Learn You Some Erlang's worker-supervisor default, paired
5274        // with the sibling `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5`
5275        // `MaxIntensity` half this constant is the sliding-window
5276        // denominator of on the same `MaxIntensity / Period`
5277        // restart-intensity ratio. Pinning the literal here surfaces a
5278        // future coherent rebrand of the paired default (Elixir's
5279        // `{max_restarts: 3, max_seconds: 5}`, a per-cluster overlay
5280        // the operator pins through a future
5281        // `:restart-window-overrides` slot) as a deliberate test edit,
5282        // not a silent contract migration. Peer of the sibling
5283        // [`supervisor_max_restarts_default_pins_otp_canonical_value`]
5284        // paired-half pin on the same OTP-canonical default and the
5285        // [`supervisor_restart_window_cap_pins_canonical_value`]
5286        // upper-bracket pin on the same axis.
5287        assert_eq!(SUPERVISOR_RESTART_WINDOW_DEFAULT, Duration::from_secs(60),);
5288    }
5289
5290    #[test]
5291    fn supervisor_spec_default_restart_window_routes_through_lifted_default() {
5292        // Composition pin: the [`Default for SupervisorSpec`] impl's
5293        // struct-literal `restart_window` field must route through the
5294        // substrate-canonical [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
5295        // typed `pub const` rather than a raw
5296        // `Duration::from_secs(60)` literal. Prior to this lift the
5297        // paired `{intensity, 5, 60}` OTP-canonical default was split
5298        // across two altitudes with no compile-time link between the
5299        // halves — the `MaxIntensity` half rode through the lifted
5300        // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant while the
5301        // `Period` half rode as an open-coded literal at the
5302        // composition site, so a future coherent rebrand of the paired
5303        // canonical would have had to migrate one half through the
5304        // constant and the other through a raw literal in lockstep.
5305        // Byte-parity against the lifted constant on the `Period` half
5306        // closes the split — the paired OTP-canonical default now
5307        // migrates as one unit on any future axis change. Peer of the
5308        // sibling
5309        // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
5310        // byte-parity pin on the paired `MaxIntensity` half.
5311        assert_eq!(
5312            SupervisorSpec::default().restart_window(),
5313            Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
5314        );
5315    }
5316
5317    #[test]
5318    fn supervisor_estrategia_default_pins_otp_canonical_value() {
5319        // Pin [`SUPERVISOR_ESTRATEGIA_DEFAULT`] at [`RestartStrategy::OneForOne`]
5320        // — the Erlang/OTP-canonical `one_for_one` half of Learn You Some
5321        // Erlang's `{one_for_one, intensity, 5, 60}` worker-supervisor
5322        // canonical default, paired with the sibling
5323        // `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5` `MaxIntensity` half and the
5324        // sibling `SUPERVISOR_RESTART_WINDOW_DEFAULT` `60s` `Period` half
5325        // this constant is the strategy discriminator of on the same
5326        // OTP-canonical worker-supervisor default. Pinning the arm here
5327        // surfaces a future coherent rebrand of the paired triple (Elixir's
5328        // `{:one_for_one, max_restarts: 3, max_seconds: 5}` on the sibling
5329        // intensity/period axes leaving this strategy arm untouched, an OTP
5330        // `rest_for_one` widening once the substrate discovers startup-
5331        // order-coupled child cohorts as the more common worker-supervisor
5332        // shape, a per-cluster overlay the operator pins through a future
5333        // `:estrategia-overrides` slot the MESH-COMPOSITION §III.2
5334        // supervision-canary roadmap acknowledges) as a deliberate test
5335        // edit, not a silent contract migration. Peer of the sibling
5336        // [`supervisor_max_restarts_default_pins_otp_canonical_value`] +
5337        // [`supervisor_restart_window_default_pins_otp_canonical_value`]
5338        // paired-half pins on the same OTP-canonical default.
5339        assert_eq!(SUPERVISOR_ESTRATEGIA_DEFAULT, RestartStrategy::OneForOne);
5340    }
5341
5342    #[test]
5343    fn restart_strategy_default_routes_through_lifted_default() {
5344        // Composition pin: the [`Default for RestartStrategy`] impl's
5345        // return arm must route through the substrate-canonical
5346        // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
5347        // a raw `Self::OneForOne` arm. Prior to the lift the impl carried
5348        // an inline `Self::OneForOne` with no compile-time link back to
5349        // the shared OTP-canonical `one_for_one` strategy the paired
5350        // [`Default for SupervisorSpec`] impl's struct-literal `estrategia`
5351        // field and the [`crate::manifest::Caixa::supervisor_view`] fold's
5352        // `.unwrap_or_default()` (now
5353        // `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)`) arm both key off —
5354        // so a future rebrand of the OTP-canonical strategy default (an
5355        // OTP `rest_for_one` widening once the substrate discovers
5356        // startup-order-coupled child cohorts as the more common worker-
5357        // supervisor shape, a per-cluster overlay the operator pins
5358        // through a future `:estrategia-overrides` slot) would have had to
5359        // be threaded through the `Default` impl and the two peer routes
5360        // in lockstep or the three consumers would silently split. Byte-
5361        // parity against the lifted constant closes the split. Peer of
5362        // the sibling
5363        // [`default_max_restarts_helper_routes_through_lifted_default`] +
5364        // [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
5365        // composition pins on the paired `MaxIntensity` + `Period` halves.
5366        assert_eq!(RestartStrategy::default(), SUPERVISOR_ESTRATEGIA_DEFAULT,);
5367    }
5368
5369    #[test]
5370    fn supervisor_spec_default_estrategia_routes_through_lifted_default() {
5371        // Composition pin: the [`Default for SupervisorSpec`] impl's
5372        // struct-literal `estrategia` field must route through the
5373        // substrate-canonical [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed
5374        // `pub const` (either directly, or via the
5375        // [`RestartStrategy::default`] impl that the sibling
5376        // `restart_strategy_default_routes_through_lifted_default` pin
5377        // already routes onto the constant). Structurally: every
5378        // `SupervisorSpec::default()` call must yield an `estrategia`
5379        // field byte-equal to the lifted constant (the three paired
5380        // defaults — the [`Default for RestartStrategy`] impl arm, the
5381        // struct-literal default arm here, and the
5382        // [`crate::manifest::Caixa::supervisor_view`] fold arm — cannot
5383        // silently split on any future default rebrand). Peer of the
5384        // sibling
5385        // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
5386        // + [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
5387        // byte-parity pins on the paired `MaxIntensity` + `Period` halves
5388        // of the same `SupervisorSpec::default()` composed altitude.
5389        assert_eq!(
5390            SupervisorSpec::default().estrategia(),
5391            SUPERVISOR_ESTRATEGIA_DEFAULT,
5392        );
5393    }
5394
5395    #[test]
5396    fn supervisor_spec_default_routes_through_otp_canonical_ctor() {
5397        // Composition pin: the [`Default for SupervisorSpec`] impl must
5398        // route through the substrate-canonical
5399        // [`SupervisorSpec::otp_canonical`] `pub const fn` constructor
5400        // rather than a re-hand-authored struct-literal cascade. Sharpens
5401        // the sibling per-arm
5402        // `supervisor_spec_default_*_routes_through_lifted_default` pins
5403        // from a per-field lift into a whole-struct one-source-of-truth
5404        // pin — the derived-until-now [`Default::default`] and the
5405        // [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
5406        // construction, not by coincidence.
5407        //
5408        // A future extension of the OTP-canonical baseline (a fifth
5409        // `restart_intensity` field the Erlang/OTP `#supervisor` record
5410        // grows, a per-child-cohort split of the `restart_window` /
5411        // `max_restarts` pair, an M4 `mesh.pleme.io/v1alpha1/Supervisor`
5412        // CR materializer's admission-time overlay pass) reaches both
5413        // paths through exactly one edit on
5414        // [`SupervisorSpec::otp_canonical`] — the derived path could
5415        // silently disagree with the constructor's shape on any new
5416        // field whose [`Default::default`] resolves to a different arm
5417        // than the OTP-canonical baseline the constructor names, while
5418        // this delegated impl reaches the constructor directly and
5419        // picks up every future extension by construction.
5420        //
5421        // Fourth peer on the M2 / M3 typed-slot-spec
5422        // [`Default`]-through-const-ctor fold family — sibling of the
5423        // [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
5424        // (abd52c2), [`crate::aplicacao::MeshPolicy`]
5425        // [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`]
5426        // (91641a4), and [`crate::BehaviorSpec`]
5427        // [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c)
5428        // per-`Option`-only-typed-slot folds — extended here onto the
5429        // M2 supervisor-slot [`SupervisorSpec`] whose canonical baseline
5430        // is not "everything `None`" but the Erlang/OTP-canonical
5431        // `{one_for_one, 5, 60}` worker-supervisor triple.
5432        assert_eq!(SupervisorSpec::default(), SupervisorSpec::otp_canonical());
5433    }
5434
5435    #[test]
5436    fn supervisor_spec_otp_canonical_byte_equals_default() {
5437        // Value pin: [`SupervisorSpec::otp_canonical`] must byte-equal
5438        // the hand-authored `{one_for_one, 5, 60, []}` OTP-canonical
5439        // baseline the sibling `default_has_one_for_one_and_5_restarts_in_60s`
5440        // pin already asserts against the [`Default::default`] path.
5441        // Sharpens the pair-invariant into a per-constructor pin so a
5442        // future extension of [`SupervisorSpec`] with a fifth field
5443        // whose OTP-canonical shape is non-`Default::default`-equivalent
5444        // trips at caixa-core test time rather than at a downstream
5445        // consumer that composed [`SupervisorSpec::otp_canonical`] with
5446        // [`SupervisorSpec::validate`] as its "canonical baseline
5447        // seed".
5448        let canonical = SupervisorSpec::otp_canonical();
5449        assert_eq!(canonical.estrategia, RestartStrategy::OneForOne);
5450        assert_eq!(canonical.max_restarts, 5);
5451        assert_eq!(canonical.restart_window, Some(Duration::from_secs(60)));
5452        assert!(canonical.children.is_empty());
5453    }
5454
5455    #[test]
5456    fn supervisor_spec_otp_canonical_is_usable_in_const_context() {
5457        // Const-context pin: [`SupervisorSpec::otp_canonical`] must
5458        // remain callable from a `const`-bound position so downstream
5459        // `const`-context callers wanting a canonical OTP-baseline seed
5460        // can construct one at compile time without runtime dispatch on
5461        // the derived [`Default::default`]. Peer of the sibling
5462        // `pub const fn` [`crate::LimitsSpec::empty`] /
5463        // [`crate::aplicacao::MeshPolicy::empty`] /
5464        // [`crate::BehaviorSpec::empty`] constructors on the sibling
5465        // typed-slot-spec `pub const fn` axis. If a future edit breaks
5466        // the `const`-eligibility of [`SupervisorSpec::otp_canonical`]
5467        // (a non-`const` field-default helper, a non-`const`-stable
5468        // container type promotion), this evaluation fails at
5469        // build time on this file rather than at a downstream
5470        // `const`-context call site.
5471        const CANONICAL: SupervisorSpec = SupervisorSpec::otp_canonical();
5472        assert_eq!(CANONICAL.estrategia, SUPERVISOR_ESTRATEGIA_DEFAULT);
5473        assert_eq!(CANONICAL.max_restarts, SUPERVISOR_MAX_RESTARTS_DEFAULT);
5474        assert_eq!(
5475            CANONICAL.restart_window,
5476            Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
5477        );
5478        assert!(CANONICAL.children.is_empty());
5479    }
5480
5481    #[test]
5482    fn supervisor_child_restart_default_pins_otp_canonical_value() {
5483        // Pin [`SUPERVISOR_CHILD_RESTART_DEFAULT`] at
5484        // [`RestartPolicy::Permanent`] — Erlang/OTP's `permanent`
5485        // worker-child restart type (`{ChildId, StartFunc, permanent, …}`
5486        // in a `supervisor`'s `init/1` child-spec tuple), the per-child
5487        // half of the same OTP-shape supervisor-tree default set whose
5488        // per-`:supervisor` halves the sibling
5489        // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
5490        // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] /
5491        // [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] constants pin. Pinning the
5492        // arm here surfaces a future rebrand of the per-child default (an
5493        // OTP-`transient` widening once the substrate discovers clean-
5494        // completion-aware children as the more common child shape, a
5495        // per-cluster overlay the operator pins through a future
5496        // `:restart-overrides` slot the MESH-COMPOSITION §III.2
5497        // supervision-canary roadmap acknowledges) as a deliberate test
5498        // edit, not a silent contract migration. Peer of the sibling
5499        // [`supervisor_estrategia_default_pins_otp_canonical_value`] /
5500        // [`supervisor_max_restarts_default_pins_otp_canonical_value`] /
5501        // [`supervisor_restart_window_default_pins_otp_canonical_value`]
5502        // value pins on the per-`:supervisor` halves.
5503        assert_eq!(SUPERVISOR_CHILD_RESTART_DEFAULT, RestartPolicy::Permanent);
5504    }
5505
5506    #[test]
5507    fn restart_policy_default_routes_through_lifted_default() {
5508        // Composition pin: the [`Default for RestartPolicy`] impl's return
5509        // arm must route through the substrate-canonical
5510        // [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const` rather
5511        // than a raw `Self::Permanent` arm. Prior to the lift the impl
5512        // carried an inline `Self::Permanent` with no compile-time link
5513        // back to the OTP-shape supervisor-tree default set whose three
5514        // per-`:supervisor` halves already rode through lifted constants
5515        // — so a future coherent rebrand of the set would have had to
5516        // migrate three halves through typed constants and this fourth
5517        // through a raw enum arm in lockstep or the supervisor-level and
5518        // child-level defaults would silently drift apart. Byte-parity
5519        // against the lifted constant closes the split. Peer of the
5520        // sibling
5521        // [`restart_strategy_default_routes_through_lifted_default`]
5522        // composition pin on the per-`:supervisor` `:estrategia` axis.
5523        assert_eq!(RestartPolicy::default(), SUPERVISOR_CHILD_RESTART_DEFAULT);
5524    }
5525
5526    #[test]
5527    fn child_spec_serde_default_restart_routes_through_lifted_default() {
5528        // Composition pin: the serde-side `#[serde(default)]` on
5529        // [`ChildSpec::restart`] — the wire-format author-omitted
5530        // `:children :restart` arm — must resolve onto the substrate-
5531        // canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const`
5532        // (via the [`Default for RestartPolicy`] impl the sibling
5533        // `restart_policy_default_routes_through_lifted_default` pin
5534        // already routes onto the constant). Structurally: a `ChildSpec`
5535        // deserialized from a payload that omits the `restart` key must
5536        // yield a `restart` field byte-equal to the lifted constant, so
5537        // the wire-format author-omitted arm and the
5538        // [`RestartPolicy::default`] impl arm cannot silently split on any
5539        // future default rebrand. Peer of the sibling
5540        // [`supervisor_spec_default_estrategia_routes_through_lifted_default`]
5541        // / [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
5542        // / [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
5543        // byte-parity pins on the per-`:supervisor` halves of the same
5544        // author-omitted-slot resolution surface.
5545        let omitted: ChildSpec = serde_json::from_str(r#"{"caixa":"worker","versao":"^0.1"}"#)
5546            .expect("ChildSpec must deserialize with the restart key omitted");
5547        assert_eq!(
5548            omitted.restart(),
5549            SUPERVISOR_CHILD_RESTART_DEFAULT,
5550            "an author-omitted :children :restart slot must degrade onto \
5551             the SUPERVISOR_CHILD_RESTART_DEFAULT typed pub const (got \
5552             {:?}, expected {:?})",
5553            omitted.restart(),
5554            SUPERVISOR_CHILD_RESTART_DEFAULT,
5555        );
5556    }
5557
5558    #[test]
5559    fn supervisor_max_restarts_cap_pins_canonical_value() {
5560        // The SUPERVISOR_MAX_RESTARTS_MAX constant pins the value at
5561        // 1000 — the same ceiling the peer
5562        // POLICY_BREAKER_MAX_FAILURES_MAX cap carries on the
5563        // `:politicas :circuit-breaker :max-failures` axis (both are
5564        // "trip the next-higher protection layer after N events in a
5565        // rolling window" counters with identical
5566        // degenerate-at-the-high-end shape; uniform top edge so the
5567        // M4 CR materializers and the wasm-operator reconciler reach
5568        // for either field knowing the value is in `1..=1000`). Two
5569        // orders of magnitude above every documented Erlang/OTP /
5570        // Elixir / Riak Core / RabbitMQ production-playbook
5571        // recommendation band and below the clearly-pathological
5572        // "effectively no escalation" floor (10_000, 100_000,
5573        // u32::MAX). Pinning the literal value here surfaces a future
5574        // drift (a relaxation to 10_000, a tightening to 100) as a
5575        // deliberate test edit, not a silent contract narrowing.
5576        assert_eq!(SUPERVISOR_MAX_RESTARTS_MAX, 1000);
5577    }
5578
5579    #[test]
5580    fn validate_rejects_empty_child_name() {
5581        let s = SupervisorSpec {
5582            children: vec![child("", "^0.1", RestartPolicy::Permanent)],
5583            ..SupervisorSpec::default()
5584        };
5585        assert_eq!(s.validate().unwrap_err(), SupervisorError::EmptyChildName);
5586    }
5587
5588    #[test]
5589    fn validate_rejects_empty_child_version() {
5590        let s = SupervisorSpec {
5591            children: vec![child("w", "", RestartPolicy::Permanent)],
5592            ..SupervisorSpec::default()
5593        };
5594        assert!(matches!(
5595            s.validate().unwrap_err(),
5596            SupervisorError::EmptyChildVersion { .. }
5597        ));
5598    }
5599
5600    // ── value-shape: parse-as-VersionReq on :children :versao ─────────────
5601
5602    #[test]
5603    fn validate_rejects_invalid_child_versao_requirement() {
5604        // The fail-before-pass-after pin: a non-empty but malformed
5605        // semver requirement (`"^bad-version"`) silently passed
5606        // `validate()` on every pre-gate codebase because the prior
5607        // shape only refused the empty string. The parse failure
5608        // surfaced far downstream at lacre-resolve time with a
5609        // `semver::Error` that didn't name which `:children` entry
5610        // carried the typo. The new gate moves the check to caixa-build
5611        // time at the source caixa.lisp — the third `:versao` typed
5612        // axis (`:children`) joins `:deps` and `:membros` (9888b13) at
5613        // structural parity.
5614        let s = SupervisorSpec {
5615            children: vec![
5616                child("worker", "^0.1", RestartPolicy::Permanent),
5617                child("cache", "^bad-version", RestartPolicy::Transient),
5618            ],
5619            ..SupervisorSpec::default()
5620        };
5621        let err = s.validate().unwrap_err();
5622        assert!(
5623            matches!(
5624                err,
5625                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
5626                    if caixa == "cache" && versao == "^bad-version"
5627            ),
5628            "got {err:?}"
5629        );
5630    }
5631
5632    #[test]
5633    fn validate_rejects_child_versao_with_double_caret_typo() {
5634        // `"^^0.1"` is the canonical doubled-caret typo — looks
5635        // Cargo-shaped on first glance but fails the parser because
5636        // semver doesn't accept stacked operators. Pin this
5637        // adjacent-shape footgun explicitly so a future relaxation that
5638        // accepts "looks-canonical-but-isn't" forms surfaces here.
5639        let s = SupervisorSpec {
5640            children: vec![child("worker", "^^0.1", RestartPolicy::Permanent)],
5641            ..SupervisorSpec::default()
5642        };
5643        let err = s.validate().unwrap_err();
5644        assert!(
5645            matches!(
5646                err,
5647                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
5648                    if caixa == "worker" && versao == "^^0.1"
5649            ),
5650            "got {err:?}"
5651        );
5652    }
5653
5654    #[test]
5655    fn validate_rejects_child_versao_with_v_prefixed_tag() {
5656        // `"v0.1"` is the canonical "git-tag-shape leaking into the
5657        // semver requirement slot" typo — an author copies the
5658        // publish-side git-tag string verbatim into `:versao`, but
5659        // Cargo's semver parser rejects the leading `v`. Same
5660        // adjacent-shape footgun pinned for `:membros :versao`
5661        // (9888b13).
5662        let s = SupervisorSpec {
5663            children: vec![child("worker", "v0.1", RestartPolicy::Permanent)],
5664            ..SupervisorSpec::default()
5665        };
5666        let err = s.validate().unwrap_err();
5667        assert!(
5668            matches!(
5669                err,
5670                SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
5671                    if caixa == "worker" && versao == "v0.1"
5672            ),
5673            "got {err:?}"
5674        );
5675    }
5676
5677    #[test]
5678    fn validate_accepts_canonical_child_versao_forms() {
5679        // The Cargo-shaped requirement forms `:deps :versao` and
5680        // `:membros :versao` already accept via
5681        // `crate::parse_requirement` must pass the children gate
5682        // without re-validating at the resolver layer. Pin every leg so
5683        // a future tightening of the canonical set surfaces here as a
5684        // test failure.
5685        for form in [
5686            "^0.1",      // caret — minor-range pin (the most common shape)
5687            "~0.1.2",    // tilde — patch-range pin
5688            "0.1.0",     // exact — single-version pin
5689            "*",         // wildcard — any version (semver::VersionReq::STAR)
5690            ">=0.1, <2", // multi-range — comma-separated comparators
5691        ] {
5692            let s = SupervisorSpec {
5693                children: vec![child("worker", form, RestartPolicy::Permanent)],
5694                ..SupervisorSpec::default()
5695            };
5696            s.validate()
5697                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
5698        }
5699    }
5700
5701    #[test]
5702    fn child_versao_empty_takes_precedence_over_invalid() {
5703        // Order pin: the existing `EmptyChildVersion` diagnostic (which
5704        // doesn't try to parse) fires before the new
5705        // `ChildVersaoInvalid` parse-side diagnostic, so an empty
5706        // `:versao` keeps its narrower error message —
5707        // `parse_requirement` would also reject `""`, but the
5708        // empty-string arm is the more self-locating diagnostic for the
5709        // author. Same ordering discipline as
5710        // `membro_versao_empty_takes_precedence_over_invalid` in
5711        // aplicacao.rs.
5712        let s = SupervisorSpec {
5713            children: vec![child("worker", "", RestartPolicy::Permanent)],
5714            ..SupervisorSpec::default()
5715        };
5716        let err = s.validate().unwrap_err();
5717        assert!(
5718            matches!(err, SupervisorError::EmptyChildVersion { ref caixa } if caixa == "worker"),
5719            "got {err:?}"
5720        );
5721    }
5722
5723    #[test]
5724    fn child_versao_invalid_fires_before_duplicate_check() {
5725        // Order pin: a malformed requirement on a non-duplicate entry
5726        // surfaces *its own* diagnostic (which names the offending
5727        // `:versao` string), even when a later entry would otherwise
5728        // collapse onto an earlier name. The per-entry shape gate runs
5729        // inline before the duplicate-key insert — parallel to
5730        // `membro_versao_invalid_fires_before_duplicate_check` in
5731        // aplicacao.rs and the b0c8389 / c4213a4 ordering discipline.
5732        let s = SupervisorSpec {
5733            children: vec![
5734                child("worker", "^bad", RestartPolicy::Permanent),
5735                child("cache", "^0.1", RestartPolicy::Transient),
5736                child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
5737            ],
5738            ..SupervisorSpec::default()
5739        };
5740        let err = s.validate().unwrap_err();
5741        assert!(
5742            matches!(
5743                err,
5744                SupervisorError::ChildVersaoInvalid { ref caixa, .. } if caixa == "worker"
5745            ),
5746            "got {err:?}"
5747        );
5748    }
5749
5750    #[test]
5751    fn child_versao_invalid_diagnostic_carries_offending_versao() {
5752        // The diagnostic-shape pin: the error names the offending
5753        // `:versao` value verbatim so the author can grep their
5754        // caixa.lisp without re-running the build, and carries a
5755        // non-empty `reason` from `semver::VersionReq::parse` so the
5756        // parser's own wording flows through to the diagnostic.
5757        let s = SupervisorSpec {
5758            children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
5759            ..SupervisorSpec::default()
5760        };
5761        let err = s.validate().unwrap_err();
5762        let SupervisorError::ChildVersaoInvalid {
5763            caixa,
5764            versao,
5765            reason,
5766        } = err
5767        else {
5768            panic!("expected ChildVersaoInvalid, got other variant");
5769        };
5770        assert_eq!(caixa, "worker");
5771        assert_eq!(versao, "not-a-req");
5772        assert!(
5773            !reason.is_empty(),
5774            "ChildVersaoInvalid `reason` must carry the parser's wording verbatim"
5775        );
5776    }
5777
5778    // ── value-shape: DNS-1123 label rule on :children :caixa ──────────────
5779
5780    #[test]
5781    fn validate_rejects_child_caixa_with_uppercase() {
5782        // The canonical "I copied the Servico's display name verbatim"
5783        // typo — child caixa names are lowercase per K8s DNS-1123 label
5784        // rule. The diagnostic names the offending name and suggests the
5785        // lower-cased fix in one edit, mirroring the
5786        // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0).
5787        let s = SupervisorSpec {
5788            children: vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
5789            ..SupervisorSpec::default()
5790        };
5791        let err = s.validate().unwrap_err();
5792        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
5793            panic!("expected ChildCaixaInvalid, got other variant");
5794        };
5795        assert_eq!(caixa, "Worker");
5796        assert!(
5797            reason.contains("uppercase"),
5798            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
5799        );
5800        assert!(
5801            reason.contains("\"worker\""),
5802            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
5803        );
5804    }
5805
5806    #[test]
5807    fn validate_rejects_child_caixa_with_underscore() {
5808        // The canonical "I'm thinking of a Python module / Postgres
5809        // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
5810        // label schema. K8s rejects `metadata.name: my_worker` at
5811        // admission time with an opaque `field is invalid` (no source-
5812        // citing diagnostic). The gate moves it to caixa-build time.
5813        let s = SupervisorSpec {
5814            children: vec![child("my_worker", "^0.1", RestartPolicy::Permanent)],
5815            ..SupervisorSpec::default()
5816        };
5817        let err = s.validate().unwrap_err();
5818        assert!(
5819            matches!(
5820                err,
5821                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
5822                    if caixa == "my_worker" && reason.contains('_')
5823            ),
5824            "got {err:?}"
5825        );
5826    }
5827
5828    #[test]
5829    fn validate_rejects_child_caixa_with_dot() {
5830        // A `:children :caixa` entry is a single DNS-1123 label, not a
5831        // subdomain. The K8s Service / ComputeUnit `metadata.name` rules
5832        // forbid dots. Same shape as `rejects_membro_caixa_with_dot`
5833        // (3f9d7a0) on the peer name axis.
5834        let s = SupervisorSpec {
5835            children: vec![child("team.worker", "^0.1", RestartPolicy::Permanent)],
5836            ..SupervisorSpec::default()
5837        };
5838        let err = s.validate().unwrap_err();
5839        assert!(
5840            matches!(
5841                err,
5842                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
5843                    if caixa == "team.worker" && reason.contains('.')
5844            ),
5845            "got {err:?}"
5846        );
5847    }
5848
5849    #[test]
5850    fn validate_rejects_child_caixa_with_leading_hyphen() {
5851        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
5852        // with an alphanumeric. The K8s apiserver rejects `-worker`
5853        // outright; the renderer would emit a `metadata.name: "-worker"`
5854        // that fails admission far from the source caixa.lisp.
5855        let s = SupervisorSpec {
5856            children: vec![child("-worker", "^0.1", RestartPolicy::Permanent)],
5857            ..SupervisorSpec::default()
5858        };
5859        let err = s.validate().unwrap_err();
5860        assert!(
5861            matches!(
5862                err,
5863                SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
5864                    if caixa == "-worker" && reason.contains("start and end")
5865            ),
5866            "got {err:?}"
5867        );
5868    }
5869
5870    #[test]
5871    fn validate_rejects_child_caixa_with_trailing_hyphen() {
5872        // The symmetric arm of the boundary rule. Pin separately so
5873        // both ends of the label are covered against a future relaxation
5874        // that only checks one boundary.
5875        let s = SupervisorSpec {
5876            children: vec![child("worker-", "^0.1", RestartPolicy::Permanent)],
5877            ..SupervisorSpec::default()
5878        };
5879        let err = s.validate().unwrap_err();
5880        assert!(
5881            matches!(
5882                err,
5883                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
5884                    if caixa == "worker-"
5885            ),
5886            "got {err:?}"
5887        );
5888    }
5889
5890    #[test]
5891    fn validate_rejects_child_caixa_with_unicode() {
5892        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
5893        // (`xn--…`) by the author before it reaches K8s. The byte-by-
5894        // byte ASCII validity check rejects multi-byte UTF-8 sequences
5895        // by the first byte that fails the `[a-z0-9-]` predicate.
5896        let s = SupervisorSpec {
5897            children: vec![child("café", "^0.1", RestartPolicy::Permanent)],
5898            ..SupervisorSpec::default()
5899        };
5900        let err = s.validate().unwrap_err();
5901        assert!(
5902            matches!(
5903                err,
5904                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
5905                    if caixa == "café"
5906            ),
5907            "got {err:?}"
5908        );
5909    }
5910
5911    #[test]
5912    fn validate_rejects_child_caixa_with_whitespace() {
5913        // Whitespace is the canonical "I pasted from a sketch / doc"
5914        // footgun. The apiserver rejects every `metadata.name` value
5915        // carrying whitespace; pin the gate fires at the right boundary.
5916        let s = SupervisorSpec {
5917            children: vec![child("my worker", "^0.1", RestartPolicy::Permanent)],
5918            ..SupervisorSpec::default()
5919        };
5920        let err = s.validate().unwrap_err();
5921        assert!(
5922            matches!(
5923                err,
5924                SupervisorError::ChildCaixaInvalid { ref caixa, .. }
5925                    if caixa == "my worker"
5926            ),
5927            "got {err:?}"
5928        );
5929    }
5930
5931    #[test]
5932    fn validate_rejects_child_caixa_too_long() {
5933        // The 64-byte boundary pin. DNS-1123 / DNS-1035 cap labels at
5934        // 63 bytes; the K8s apiserver rejects every `metadata.name`
5935        // axis over the limit at admission time. The diagnostic names
5936        // both the cap and the actual length so the author can shorten
5937        // in one edit, mirroring `rejects_membro_caixa_too_long`
5938        // (3f9d7a0) and `rejects_placement_cluster_too_long` (6cbb900).
5939        let too_long = "a".repeat(64);
5940        let s = SupervisorSpec {
5941            children: vec![child(&too_long, "^0.1", RestartPolicy::Permanent)],
5942            ..SupervisorSpec::default()
5943        };
5944        let err = s.validate().unwrap_err();
5945        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
5946            panic!("expected ChildCaixaInvalid, got other variant");
5947        };
5948        assert_eq!(caixa, too_long);
5949        assert!(
5950            reason.contains("63"),
5951            "diagnostic must name the 63-byte cap (got: {reason:?})"
5952        );
5953        assert!(
5954            reason.contains("64"),
5955            "diagnostic must name the actual length (got: {reason:?})"
5956        );
5957    }
5958
5959    #[test]
5960    fn child_caixa_max_length_validates() {
5961        // The 63-byte boundary control pin — exactly-at-the-cap is
5962        // accepted, mirroring `membro_caixa_max_length_validates`
5963        // (3f9d7a0) and `placement_cluster_max_length_validates`
5964        // (6cbb900). Pinned separately so a future off-by-one tightening
5965        // surfaces here.
5966        let max_label = "a".repeat(63);
5967        let s = SupervisorSpec {
5968            children: vec![child(&max_label, "^0.1", RestartPolicy::Permanent)],
5969            ..SupervisorSpec::default()
5970        };
5971        s.validate().unwrap();
5972    }
5973
5974    #[test]
5975    fn validate_accepts_canonical_child_caixa_forms() {
5976        // The realistic shapes a supervised child's `:caixa` carries —
5977        // single-word `worker`, version-suffixed `cache-v2`, single-char
5978        // `a`, two-char `db`, digit-start `2-pool`, longer hyphen-joined
5979        // `payment-retry`, all-digit `0`. Pin every leg so a future
5980        // tightening (e.g. requiring a leading lowercase letter) surfaces
5981        // here as a test failure. Mirrors `accepts_canonical_membro_caixa_forms`
5982        // (3f9d7a0) and `accepts_canonical_placement_cluster_forms`
5983        // (6cbb900).
5984        for form in [
5985            "worker",
5986            "cache-v2",
5987            "a",
5988            "db",
5989            "2-pool",
5990            "payment-retry",
5991            "0",
5992        ] {
5993            let s = SupervisorSpec {
5994                children: vec![child(form, "^0.1", RestartPolicy::Permanent)],
5995                ..SupervisorSpec::default()
5996            };
5997            s.validate()
5998                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
5999        }
6000    }
6001
6002    #[test]
6003    fn child_caixa_empty_takes_precedence_over_invalid() {
6004        // Order pin: the existing `EmptyChildName` diagnostic (which
6005        // doesn't try to parse the DNS-1123 shape) fires before the new
6006        // `ChildCaixaInvalid` per-axis gate, so an empty `:caixa` keeps
6007        // its narrower error message — `is_dns_1123_label` would reject
6008        // the empty string too (boundary check on the first byte), but
6009        // the empty-string arm is the more self-locating diagnostic for
6010        // the author. Same ordering discipline as
6011        // `membro_caixa_empty_takes_precedence_over_invalid` in
6012        // aplicacao.rs.
6013        let s = SupervisorSpec {
6014            children: vec![child("", "^0.1", RestartPolicy::Permanent)],
6015            ..SupervisorSpec::default()
6016        };
6017        let err = s.validate().unwrap_err();
6018        assert_eq!(err, SupervisorError::EmptyChildName);
6019    }
6020
6021    #[test]
6022    fn child_caixa_invalid_fires_before_versao_check() {
6023        // Order pin: the per-axis shape gate runs inline before the
6024        // per-entry versao check, so a malformed `:caixa` on an entry
6025        // whose `:versao` would also fail surfaces the more self-
6026        // locating name-axis diagnostic first. Parallel to
6027        // `membro_versao_invalid_fires_before_duplicate_check` (9888b13)
6028        // and `placement_cluster_invalid_fires_before_duplicate_check`
6029        // (6cbb900).
6030        let s = SupervisorSpec {
6031            children: vec![child("My_Worker", "", RestartPolicy::Permanent)],
6032            ..SupervisorSpec::default()
6033        };
6034        let err = s.validate().unwrap_err();
6035        assert!(
6036            matches!(
6037                err,
6038                SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "My_Worker"
6039            ),
6040            "got {err:?}"
6041        );
6042    }
6043
6044    #[test]
6045    fn child_caixa_invalid_fires_before_duplicate_check() {
6046        // Order pin: a malformed name on a non-duplicate entry surfaces
6047        // its own diagnostic, even when a later entry would otherwise
6048        // collapse onto an earlier name. The per-entry shape gate runs
6049        // inline before the duplicate-key HashSet insert, mirroring
6050        // `placement_cluster_invalid_fires_before_duplicate_check`
6051        // (6cbb900).
6052        let s = SupervisorSpec {
6053            children: vec![
6054                child("Worker", "^0.1", RestartPolicy::Permanent),
6055                child("cache", "^0.1", RestartPolicy::Transient),
6056                child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
6057            ],
6058            ..SupervisorSpec::default()
6059        };
6060        let err = s.validate().unwrap_err();
6061        assert!(
6062            matches!(
6063                err,
6064                SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "Worker"
6065            ),
6066            "got {err:?}"
6067        );
6068    }
6069
6070    #[test]
6071    fn child_caixa_invalid_diagnostic_carries_offending_caixa() {
6072        // The diagnostic-shape pin: the error names the offending
6073        // `:caixa` verbatim plus a non-empty parser-shaped `reason` so
6074        // the author can grep their caixa.lisp without re-running the
6075        // build. Mirrors the diagnostic-shape sweep on every prior
6076        // value-shape gate (3f9d7a0, 6cbb900, c7d05ec).
6077        let s = SupervisorSpec {
6078            children: vec![child("My_Worker", "^0.1", RestartPolicy::Permanent)],
6079            ..SupervisorSpec::default()
6080        };
6081        let err = s.validate().unwrap_err();
6082        let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
6083            panic!("expected ChildCaixaInvalid, got other variant");
6084        };
6085        assert_eq!(caixa, "My_Worker");
6086        assert!(
6087            !reason.is_empty(),
6088            "ChildCaixaInvalid `reason` must carry the parser's wording verbatim"
6089        );
6090    }
6091
6092    // ── value-shape: zero restart_window + duplicate child names ──────────
6093
6094    #[test]
6095    fn validate_accepts_none_restart_window() {
6096        // Omitted `:restart-window` is the "never reset" sentinel —
6097        // valid by design. Mirrors :limits axes where None = unbounded.
6098        let s = SupervisorSpec {
6099            restart_window: None,
6100            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6101            ..SupervisorSpec::default()
6102        };
6103        s.validate().unwrap();
6104    }
6105
6106    #[test]
6107    fn validate_rejects_zero_restart_window() {
6108        // Same "0 means the opposite of what you think" footgun closed
6109        // for :politicas :timeout (Envoy treats 0s as infinite) and
6110        // :limits :wall-clock (wasmtime traps before the call starts).
6111        // Erlang/OTP's MaxIntensity/Period requires Period > 0.
6112        let s = SupervisorSpec {
6113            restart_window: Some(Duration::ZERO),
6114            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6115            ..SupervisorSpec::default()
6116        };
6117        assert_eq!(
6118            s.validate().unwrap_err(),
6119            SupervisorError::RestartWindowZero
6120        );
6121    }
6122
6123    // ── value-shape: integer-ms canonical-form on :restart-window ─────────
6124    //
6125    // The fourth (and last) typed-`Duration` axis in caixa-core to get
6126    // the integer-millisecond canonical-form gate — peer with
6127    // `:limits :wall-clock` (82fc3ef), `:politicas :timeout` (a4ae535),
6128    // and `:politicas :circuit-breaker :window` (a4ae535). The serde
6129    // path is already gated at the shared codec layer (see
6130    // `restart_window_serde_rejects_fractional_seconds`); this arm
6131    // closes the programmatic-struct-literal path the codec gate can't
6132    // see.
6133
6134    #[test]
6135    fn validate_rejects_sub_millisecond_restart_window() {
6136        // The fail-before-pass-after pin: a programmatic
6137        // `Duration::from_micros(1500)` (= 1_500_000 ns) silently passed
6138        // `validate` on every pre-gate codebase, then truncated to
6139        // `as_millis() == 1` on first serialize — the shared codec
6140        // emits `"1ms"`, parses it back to `Duration::from_millis(1)` =
6141        // 1_000_000 ns, the typed `restart_window` no longer matches
6142        // its rendered form.
6143        let s = SupervisorSpec {
6144            restart_window: Some(Duration::from_micros(1500)),
6145            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6146            ..SupervisorSpec::default()
6147        };
6148        match s.validate().unwrap_err() {
6149            SupervisorError::RestartWindowNotCanonical { window } => {
6150                assert_eq!(window, Duration::from_micros(1500));
6151            }
6152            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
6153        }
6154    }
6155
6156    #[test]
6157    fn validate_rejects_one_nanosecond_restart_window() {
6158        // The far-sub-ms case: `Duration::from_nanos(1)` is non-zero
6159        // (so `RestartWindowZero` doesn't fire) but `as_millis() == 0`,
6160        // so the shared codec emits the literal `"0s"` — the next
6161        // serde round-trip would parse back to `Duration::ZERO`, which
6162        // the `RestartWindowZero` arm then rejects on re-validate. The
6163        // canonical-form gate at this layer surfaces a self-locating
6164        // diagnostic naming the offending Duration verbatim rather
6165        // than a downstream `RestartWindowZero` whose remediation
6166        // points at omitting the slot.
6167        let s = SupervisorSpec {
6168            restart_window: Some(Duration::from_nanos(1)),
6169            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6170            ..SupervisorSpec::default()
6171        };
6172        match s.validate().unwrap_err() {
6173            SupervisorError::RestartWindowNotCanonical { window } => {
6174                assert_eq!(window, Duration::from_nanos(1));
6175            }
6176            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
6177        }
6178    }
6179
6180    #[test]
6181    fn validate_rejects_nanosecond_past_canonical_boundary_restart_window() {
6182        // The 1-ns-past-1ms boundary case: a `Duration` carrying
6183        // 1_000_001 ns is structurally past the integer-ms granularity
6184        // floor — `subsec_nanos() % 1_000_000 == 1`. The codec round-
6185        // trip would truncate to `1ms` and the consumer would observe
6186        // a 1-ns drift on every emit. Same boundary the peer
6187        // `validate_rejects_nanosecond_past_canonical_boundary` test
6188        // in limits.rs pins for the `:limits :wall-clock` axis.
6189        let w = Duration::from_nanos(1_000_001);
6190        let s = SupervisorSpec {
6191            restart_window: Some(w),
6192            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6193            ..SupervisorSpec::default()
6194        };
6195        assert_eq!(
6196            s.validate().unwrap_err(),
6197            SupervisorError::RestartWindowNotCanonical { window: w }
6198        );
6199    }
6200
6201    #[test]
6202    fn validate_accepts_integer_millisecond_restart_window_values() {
6203        // The positive-control sweep: every `Duration` the shared
6204        // codec can round-trip losslessly — the canonical
6205        // `<integer>{ms,s,m,h}` set the codec's `render` / `parse`
6206        // pair emits and accepts — passes `validate` without
6207        // surfacing the new canonical-form arm. Mirrors
6208        // `validate_accepts_integer_millisecond_wall_clock_values` on
6209        // the sibling `:limits :wall-clock` axis.
6210        for w in [
6211            Duration::from_millis(1),
6212            Duration::from_millis(500),
6213            Duration::from_millis(1500),
6214            Duration::from_secs(1),
6215            Duration::from_secs(30),
6216            Duration::from_secs(60),
6217            Duration::from_secs(120),
6218            Duration::from_secs(3600),
6219        ] {
6220            let s = SupervisorSpec {
6221                restart_window: Some(w),
6222                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6223                ..SupervisorSpec::default()
6224            };
6225            s.validate()
6226                .unwrap_or_else(|e| panic!("integer-ms {w:?} must validate, got {e:?}"));
6227        }
6228    }
6229
6230    #[test]
6231    fn validate_restart_window_zero_takes_precedence_over_canonical_gate() {
6232        // Cross-arm ordering pin: `Duration::ZERO` has
6233        // `subsec_nanos() == 0` and would otherwise pass the
6234        // canonical-form arm — the zero-floor arm must fire first so
6235        // the more self-locating `RestartWindowZero` diagnostic (with
6236        // its omit-axis remediation directly named) leads. Same
6237        // posture every peer zero-then-shape gate uses
6238        // (`WallClockZero` → `WallClockNotCanonical`,
6239        // `PolicyTimeoutZero` → `PolicyTimeoutNotCanonical`,
6240        // `PolicyBreakerZeroWindow` → `PolicyBreakerWindowNotCanonical`).
6241        let s = SupervisorSpec {
6242            restart_window: Some(Duration::ZERO),
6243            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6244            ..SupervisorSpec::default()
6245        };
6246        assert_eq!(
6247            s.validate().unwrap_err(),
6248            SupervisorError::RestartWindowZero
6249        );
6250    }
6251
6252    #[test]
6253    fn restart_window_canonical_diagnostic_carries_offending_duration() {
6254        // Diagnostic-shape pin: the canonical-form arm names the
6255        // offending `Duration` verbatim so the author's grep lands on
6256        // the field's value, not a generic "duration not canonical"
6257        // message. Same shape every other typed-canonical-form arm
6258        // on this surface carries (`WallClockNotCanonical` carries
6259        // the offending `Duration` verbatim,
6260        // `PolicyTimeoutNotCanonical` carries the offending
6261        // `Duration` verbatim).
6262        let w = Duration::from_micros(500);
6263        let s = SupervisorSpec {
6264            restart_window: Some(w),
6265            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6266            ..SupervisorSpec::default()
6267        };
6268        let err = s.validate().unwrap_err();
6269        let msg = err.to_string();
6270        assert!(
6271            msg.contains("500"),
6272            "diagnostic must carry the offending magnitude verbatim (got {msg:?})"
6273        );
6274        assert!(
6275            msg.contains("sub-millisecond"),
6276            "diagnostic must name the sub-millisecond residue class (got {msg:?})"
6277        );
6278    }
6279
6280    #[test]
6281    fn restart_window_validated_value_round_trips_through_codec() {
6282        // The structural property the canonical-ms gate enforces:
6283        // every `SupervisorSpec::restart_window` past
6284        // `SupervisorSpec::validate` round-trips losslessly through
6285        // the shared duration codec (serialize → string →
6286        // deserialize → equal value). Pin this end-to-end so a future
6287        // change to either side (the validate gate's accepted
6288        // granularity, the codec's parse/render unit set) that breaks
6289        // the alignment surfaces here. Peer of
6290        // `wall_clock_validated_value_round_trips_through_codec` on
6291        // the sibling `:limits :wall-clock` axis.
6292        for w in [
6293            Duration::from_millis(1),
6294            Duration::from_millis(1500),
6295            Duration::from_secs(30),
6296            Duration::from_secs(3600),
6297        ] {
6298            let s = SupervisorSpec {
6299                restart_window: Some(w),
6300                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6301                ..SupervisorSpec::default()
6302            };
6303            s.validate().unwrap();
6304            let json = serde_json::to_string(&s).unwrap();
6305            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6306            assert_eq!(back.restart_window, Some(w));
6307        }
6308    }
6309
6310    // ── value-shape: upper cap on :restart-window ─────────────────────────
6311    //
6312    // The fourth (and last) typed-`Duration` axis in caixa-core to get
6313    // the 1h upper cap — peer with `:limits :wall-clock` (51e0dbd),
6314    // `:politicas :timeout` (2e8ee7e), and `:politicas
6315    // :circuit-breaker :window` (379a814). Brackets the typed
6316    // `:restart-window` axis structurally: every validated value lies
6317    // in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`, integer-millisecond
6318    // granularity, closing the
6319    // rolling-window-degenerates-to-lifetime-counter footgun the prior
6320    // zero-floor-and-canonical-form-only checks left open.
6321
6322    #[test]
6323    fn validate_rejects_restart_window_above_cap() {
6324        // The fail-before-pass-after pin: 3601s = 1h + 1s is
6325        // structurally one canonical-tick past the
6326        // [`SUPERVISOR_RESTART_WINDOW_MAX`] ceiling (1h = 3600s) — an
6327        // integer-millisecond magnitude the canonical-form arm above
6328        // accepts cleanly, that the shared duration codec round-trips
6329        // losslessly as `"3601s"`, and that silently passed validate on
6330        // every pre-gate codebase because the typed slot's only checks
6331        // were the zero-floor and canonical-form arms. The runtime
6332        // substrate consuming the value (Erlang/OTP's MaxIntensity/
6333        // Period reconciler, the future wasm-operator's per-supervisor
6334        // restart-intensity counter) reaches for a `Duration` so long
6335        // no realistic restart-recovery pattern resets the counter,
6336        // far from the source caixa.lisp.
6337        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
6338        let s = SupervisorSpec {
6339            restart_window: Some(w),
6340            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6341            ..SupervisorSpec::default()
6342        };
6343        assert_eq!(
6344            s.validate().unwrap_err(),
6345            SupervisorError::RestartWindowExceedsCap { window: w }
6346        );
6347    }
6348
6349    #[test]
6350    fn validate_rejects_restart_window_one_millisecond_above_cap() {
6351        // Boundary case: exactly 1ms past the cap (the granularity the
6352        // canonical-form gate enforces). Catches a future "strictly
6353        // less than" half-measure and pins the diagnostic to name the
6354        // offending `Duration` verbatim. Peer of
6355        // `validate_rejects_wall_clock_one_millisecond_above_cap` /
6356        // `rejects_policy_timeout_one_millisecond_above_cap` /
6357        // `rejects_circuit_breaker_window_one_millisecond_above_cap`
6358        // on the sibling typed-`Duration` axes' top edges.
6359        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
6360        let s = SupervisorSpec {
6361            restart_window: Some(w),
6362            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6363            ..SupervisorSpec::default()
6364        };
6365        assert_eq!(
6366            s.validate().unwrap_err(),
6367            SupervisorError::RestartWindowExceedsCap { window: w }
6368        );
6369    }
6370
6371    #[test]
6372    fn validate_rejects_restart_window_far_above_cap() {
6373        // The "obvious authoring footgun" case: a `(:restart-window "24h")`,
6374        // `(:restart-window "7d")`, or any "I want a lifetime counter
6375        // but wrote a `<integer>h` magnitude anyway" typo — values the
6376        // canonical-form arm accepts as integer-millisecond magnitudes,
6377        // the codec round-trips losslessly through serde, but the
6378        // operator's `MaxIntensity / Period` reconciler cannot honor
6379        // as a meaningful rolling window. Until this gate landed
6380        // validate accepted them. Pin the common above-cap values (24h,
6381        // 7d, ~11.5d) so a future relaxation that drops the upper bound
6382        // surfaces here.
6383        for w in [
6384            Duration::from_secs(86_400),    // 24h
6385            Duration::from_secs(604_800),   // 7d
6386            Duration::from_secs(1_000_000), // ~11.5 days
6387        ] {
6388            let s = SupervisorSpec {
6389                restart_window: Some(w),
6390                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6391                ..SupervisorSpec::default()
6392            };
6393            assert_eq!(
6394                s.validate().unwrap_err(),
6395                SupervisorError::RestartWindowExceedsCap { window: w }
6396            );
6397        }
6398    }
6399
6400    #[test]
6401    fn validate_accepts_restart_window_at_cap() {
6402        // The boundary value — exactly [`SUPERVISOR_RESTART_WINDOW_MAX`]
6403        // (1h) — must validate. The cap is inclusive on the top edge,
6404        // matching the [`crate::LIMITS_WALL_CLOCK_MAX`] /
6405        // [`crate::POLICY_TIMEOUT_MAX`] /
6406        // [`crate::POLICY_BREAKER_WINDOW_MAX`] discipline on the sibling
6407        // capped axes. Pin the boundary explicitly so a future
6408        // off-by-one tightening (`>= SUPERVISOR_RESTART_WINDOW_MAX`
6409        // instead of `>`) surfaces here as a test failure rather than a
6410        // silent contract narrowing.
6411        let s = SupervisorSpec {
6412            restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
6413            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6414            ..SupervisorSpec::default()
6415        };
6416        s.validate()
6417            .expect("restart_window == SUPERVISOR_RESTART_WINDOW_MAX must validate");
6418    }
6419
6420    #[test]
6421    fn validate_accepts_restart_window_typical_values() {
6422        // The documented Erlang/OTP / Elixir / Riak Core / RabbitMQ
6423        // per-supervisor production-playbook band positive-control
6424        // sweep — every value Learn You Some Erlang's `{intensity, 5,
6425        // 60}` worker-supervisor `Period = 60s` default, Elixir's
6426        // `Supervisor` `max_seconds: 5` default, OTP's `supervisor`
6427        // callback module `MaxT = 5..=60` typical, Riak Core's `MaxT ∈
6428        // 10s..=300s`, and RabbitMQ broker-supervisor `MaxT = 5s`
6429        // default recommend (5s..=300s) must pass, plus a sweep
6430        // through the long-tail-flaky-pool band (5m, 15m, 30m, 1h) the
6431        // cap accepts. Mirrors `validate_accepts_wall_clock_typical_values`
6432        // on the sibling `:limits :wall-clock` axis.
6433        for w in [
6434            Duration::from_millis(1),
6435            Duration::from_millis(500),
6436            Duration::from_secs(1),
6437            Duration::from_secs(5),  // RabbitMQ broker-supervisor default
6438            Duration::from_secs(10), // Riak Core lower
6439            Duration::from_secs(30),
6440            Duration::from_secs(60),  // Learn You Some Erlang default
6441            Duration::from_secs(120), // OTP supervisor MaxT typical
6442            Duration::from_secs(300), // Riak Core upper
6443            Duration::from_secs(900), // 15m
6444            Duration::from_secs(1800),
6445            Duration::from_secs(3600), // exactly 1h, the cap
6446        ] {
6447            let s = SupervisorSpec {
6448                restart_window: Some(w),
6449                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6450                ..SupervisorSpec::default()
6451            };
6452            s.validate()
6453                .unwrap_or_else(|e| panic!("restart_window={w:?} must validate; got {e:?}"));
6454        }
6455    }
6456
6457    #[test]
6458    fn restart_window_zero_takes_precedence_over_cap() {
6459        // The cross-arm ordering pin: `Duration::ZERO` is structurally
6460        // outside both `>= 1ms` (zero-floor) and `<=
6461        // SUPERVISOR_RESTART_WINDOW_MAX` (cap), but the zero-floor
6462        // diagnostic is the more self-locating one (it directly names
6463        // the omit-axis remediation), so the validate gate must fire
6464        // on zero first. Same shape every other zero-then-cap ordering
6465        // on this surface uses (`WallClockZero` then
6466        // `WallClockExceedsCap`, `PolicyTimeoutZero` then
6467        // `PolicyTimeoutExceedsCap`, `PolicyBreakerZeroWindow` then
6468        // `PolicyBreakerWindowExceedsCap`).
6469        let s = SupervisorSpec {
6470            restart_window: Some(Duration::ZERO),
6471            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6472            ..SupervisorSpec::default()
6473        };
6474        assert_eq!(
6475            s.validate().unwrap_err(),
6476            SupervisorError::RestartWindowZero,
6477            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
6478        );
6479    }
6480
6481    #[test]
6482    fn restart_window_canonical_takes_precedence_over_cap() {
6483        // The cross-arm ordering pin: a `Duration` that is *both*
6484        // sub-millisecond (non-canonical-form) and structurally above
6485        // the cap surfaces the canonical-form diagnostic first,
6486        // because the round-trip-shape break is the more fundamental
6487        // issue (the value can't even round-trip through the codec,
6488        // so the cap diagnostic naming `1ms..=1h` would be misleading
6489        // — there's no integer-ms form of the offending value). Pin
6490        // the order so a future refactor that reorders the arms
6491        // surfaces here as a test failure rather than a silent
6492        // diagnostic regression. Peer of
6493        // `wall_clock_canonical_takes_precedence_over_cap` /
6494        // `policy_timeout_canonical_takes_precedence_over_cap`.
6495        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_nanos(1);
6496        let s = SupervisorSpec {
6497            restart_window: Some(w),
6498            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6499            ..SupervisorSpec::default()
6500        };
6501        assert_eq!(
6502            s.validate().unwrap_err(),
6503            SupervisorError::RestartWindowNotCanonical { window: w },
6504            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
6505        );
6506    }
6507
6508    #[test]
6509    fn max_restarts_cap_takes_precedence_over_restart_window_cap() {
6510        // The cross-arm ordering pin between the `:max-restarts` cap
6511        // and the sibling `:restart-window` cap. A supervisor carrying
6512        // both an over-cap `max_restarts` AND an over-cap window must
6513        // surface the `MaxRestartsExceedsCap` diagnostic first — the
6514        // cap arm is wired immediately after the zero-restart arm and
6515        // strictly before every window-axis arm (zero / canonical /
6516        // cap), so the offending value the diagnostic names matches
6517        // the order the author would discover the gates by reading
6518        // top-to-bottom through `SupervisorSpec::validate`. Pin the
6519        // order so a future refactor that reorders the arms surfaces
6520        // here as a test failure rather than a silent diagnostic
6521        // regression. Peer of
6522        // `max_restarts_cap_takes_precedence_over_restart_window_gates`
6523        // on the sibling zero / canonical window arms.
6524        let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
6525        let s = SupervisorSpec {
6526            max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
6527            restart_window: Some(w),
6528            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6529            ..SupervisorSpec::default()
6530        };
6531        assert_eq!(
6532            s.validate().unwrap_err(),
6533            SupervisorError::MaxRestartsExceedsCap {
6534                max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
6535            },
6536            "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
6537        );
6538    }
6539
6540    #[test]
6541    fn restart_window_cap_diagnostic_carries_offending_value() {
6542        // The diagnostic-shape pin: the offending `Duration` is
6543        // carried verbatim into the
6544        // [`SupervisorError::RestartWindowExceedsCap`] variant so the
6545        // surfaced error message names the value the author wrote,
6546        // not just the cap. Same self-locating diagnostic shape every
6547        // other typed-cap arm on this surface carries
6548        // (`WallClockExceedsCap` carries the offending `Duration`
6549        // verbatim, `PolicyTimeoutExceedsCap` carries the offending
6550        // `Duration` verbatim, `PolicyBreakerWindowExceedsCap` carries
6551        // the offending `Duration` verbatim).
6552        let w = Duration::from_secs(7200); // 2h
6553        let s = SupervisorSpec {
6554            restart_window: Some(w),
6555            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6556            ..SupervisorSpec::default()
6557        };
6558        let err = s.validate().unwrap_err();
6559        assert!(
6560            matches!(err, SupervisorError::RestartWindowExceedsCap { window } if window == w),
6561            "got {err:?}"
6562        );
6563        let msg = err.to_string();
6564        assert!(
6565            msg.contains("7200"),
6566            ":supervisor :restart-window cap diagnostic must carry the offending value verbatim (got: {msg})"
6567        );
6568    }
6569
6570    #[test]
6571    fn supervisor_restart_window_cap_pins_canonical_value() {
6572        // The SUPERVISOR_RESTART_WINDOW_MAX constant pins the value at
6573        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
6574        // shared duration codec emits as a clean canonical string
6575        // (`"<n>h"`). Pinning the literal value here surfaces a future
6576        // drift (a relaxation to 24h, a tightening to 5m) as a
6577        // deliberate test edit, not a silent contract narrowing.
6578        //
6579        // The four typed-`Duration` caps on the validation surface
6580        // (`LIMITS_WALL_CLOCK_MAX` per-process, `POLICY_TIMEOUT_MAX`
6581        // per-edge, `POLICY_BREAKER_WINDOW_MAX` per-breaker,
6582        // `SUPERVISOR_RESTART_WINDOW_MAX` per-supervisor) share a
6583        // single uniform top edge at the codec's largest emitted unit
6584        // — a structural-property invariant the equality assertions
6585        // here enshrine, so a future drift on any of the four
6586        // surfaces as a deliberate test edit. Same shape every other
6587        // typed-cap value pin uses
6588        // (`wall_clock_cap_pins_canonical_value`,
6589        // `policy_timeout_cap_pins_canonical_value`,
6590        // `circuit_breaker_window_cap_pins_canonical_value`).
6591        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, Duration::from_secs(3600));
6592        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX.as_millis(), 3_600_000);
6593        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::LIMITS_WALL_CLOCK_MAX);
6594        assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::POLICY_TIMEOUT_MAX);
6595        assert_eq!(
6596            SUPERVISOR_RESTART_WINDOW_MAX,
6597            crate::POLICY_BREAKER_WINDOW_MAX
6598        );
6599    }
6600
6601    #[test]
6602    fn restart_window_cap_value_round_trips_through_codec() {
6603        // The codec round-trip property the cap arm preserves: the
6604        // [`SUPERVISOR_RESTART_WINDOW_MAX`] constant itself round-trips
6605        // through the shared duration codec — every value at the cap
6606        // serializes to the canonical `"1h"` form and parses back
6607        // identically. Pin the round-trip so a future change to the
6608        // codec's unit set or to the cap's magnitude that breaks the
6609        // round-trip property surfaces here. Peer of
6610        // `wall_clock_cap_value_round_trips_through_codec` on the
6611        // sibling `:limits :wall-clock` axis.
6612        let s = SupervisorSpec {
6613            restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
6614            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6615            ..SupervisorSpec::default()
6616        };
6617        s.validate().unwrap();
6618        let json = serde_json::to_string(&s).unwrap();
6619        assert!(
6620            json.contains("\"1h\""),
6621            "SUPERVISOR_RESTART_WINDOW_MAX must serialize to the canonical `\"1h\"` form (got {json})"
6622        );
6623        let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6624        assert_eq!(back.restart_window, Some(SUPERVISOR_RESTART_WINDOW_MAX));
6625    }
6626
6627    #[test]
6628    fn validate_rejects_duplicate_child_caixa() {
6629        // Two children with the same :caixa render to two ComputeUnits
6630        // with the same name in the cluster's HelmRelease values —
6631        // one silently overwrites the other. Erlang/OTP's child_spec.id
6632        // is required-unique per supervisor; same set-not-multiset
6633        // discipline applied here as for :membros / :placement
6634        // :clusters / :entrada :paths.
6635        let s = SupervisorSpec {
6636            children: vec![
6637                child("worker", "^0.1", RestartPolicy::Permanent),
6638                child("cache", "^0.1", RestartPolicy::Transient),
6639                child("worker", "^0.2", RestartPolicy::Permanent),
6640            ],
6641            ..SupervisorSpec::default()
6642        };
6643        let err = s.validate().unwrap_err();
6644        assert!(
6645            matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "worker"),
6646            "got {err:?}"
6647        );
6648    }
6649
6650    #[test]
6651    fn validate_duplicate_child_diagnostic_names_first_collision() {
6652        // Iteration walks the :children list in declaration order —
6653        // the diagnostic names the first repeat, deterministically,
6654        // even when multiple names duplicate.
6655        let s = SupervisorSpec {
6656            children: vec![
6657                child("a", "^0.1", RestartPolicy::Permanent),
6658                child("b", "^0.1", RestartPolicy::Permanent),
6659                child("a", "^0.1", RestartPolicy::Permanent),
6660                child("b", "^0.1", RestartPolicy::Permanent),
6661            ],
6662            ..SupervisorSpec::default()
6663        };
6664        let err = s.validate().unwrap_err();
6665        assert!(
6666            matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "a"),
6667            "got {err:?}"
6668        );
6669    }
6670
6671    // ── self-supervision cross-slot gate ──────────────────────────
6672
6673    #[test]
6674    fn validate_no_self_supervision_rejects_self_referential_child() {
6675        // A supervisor whose `:children` lists its own `:nome` is a
6676        // one-node reconciliation cycle — rejected, naming the parent.
6677        let children = vec![
6678            child("worker", "^0.1", RestartPolicy::Permanent),
6679            child("orquestra", "^0.1", RestartPolicy::Permanent),
6680        ];
6681        let err = validate_no_self_supervision(&children, "orquestra").unwrap_err();
6682        assert!(
6683            matches!(err, SupervisorError::ChildSupervisesSelf { ref caixa } if caixa == "orquestra"),
6684            "got {err:?}"
6685        );
6686    }
6687
6688    #[test]
6689    fn validate_no_self_supervision_accepts_distinct_children() {
6690        // Positive control: distinct child names (including a child that
6691        // is itself a supervisor — nested trees are valid OTP) pass.
6692        let children = vec![
6693            child("worker", "^0.1", RestartPolicy::Permanent),
6694            child("sub-tree", "^0.1", RestartPolicy::Permanent),
6695        ];
6696        validate_no_self_supervision(&children, "orquestra").unwrap();
6697    }
6698
6699    #[test]
6700    fn validate_no_self_supervision_empty_children_is_ok() {
6701        // SimpleOneForOne / no-static-children supervisors have nothing
6702        // to self-reference — the gate is vacuously satisfied.
6703        validate_no_self_supervision(&[], "orquestra").unwrap();
6704    }
6705
6706    #[test]
6707    fn validate_simple_one_for_one_skips_uniqueness_check() {
6708        // SimpleOneForOne supervisors carry no static children — the
6709        // duplicate-child loop never runs. A zero-window declaration
6710        // on a SimpleOneForOne supervisor still trips the window check
6711        // (window applies to dynamic children too).
6712        let s = SupervisorSpec {
6713            estrategia: RestartStrategy::SimpleOneForOne,
6714            restart_window: None,
6715            children: vec![],
6716            ..SupervisorSpec::default()
6717        };
6718        s.validate().unwrap();
6719        let s_zero = SupervisorSpec {
6720            estrategia: RestartStrategy::SimpleOneForOne,
6721            restart_window: Some(Duration::ZERO),
6722            children: vec![],
6723            ..SupervisorSpec::default()
6724        };
6725        assert_eq!(
6726            s_zero.validate().unwrap_err(),
6727            SupervisorError::RestartWindowZero
6728        );
6729    }
6730
6731    #[test]
6732    fn validate_zero_window_runs_after_max_restarts_check() {
6733        // Pin the order: max_restarts == 0 fires before
6734        // restart_window == 0s, so an author with both wrong sees the
6735        // counter-axis diagnostic first (matches the order in the
6736        // struct and in the doc comment).
6737        let s = SupervisorSpec {
6738            max_restarts: 0,
6739            restart_window: Some(Duration::ZERO),
6740            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6741            ..SupervisorSpec::default()
6742        };
6743        assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
6744    }
6745
6746    #[test]
6747    fn round_trip_all_strategies() {
6748        for &strat in RestartStrategy::ALL {
6749            // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
6750            // shape partition through the [`gen_platform::IsVariant`]
6751            // derive-generated [`RestartStrategy::is_simple_one_for_one`]
6752            // predicate rather than the raw
6753            // `matches!(strat, RestartStrategy::SimpleOneForOne)`
6754            // open-coded pattern-match — same closed-set-typed-enum
6755            // arm-discriminator dispatch discipline the sibling
6756            // [`crate::upgrade::UpgradeInstruction::is_restart`] convergence
6757            // (915a934) extended onto its two paired positive / negated
6758            // `matches!` filter sites, and the sibling
6759            // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
6760            // predicate convergence (766ec63) extended onto the M3 mesh-
6761            // slot per-`:placement` distribution-strategy `matches!`
6762            // discriminator axis. See the sibling
6763            // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
6764            // fixture and the peer `manifest::tests::
6765            // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
6766            // fixture — all three sites (the last unlifted
6767            // `matches!`-based arm-discriminator axis on the OTP-shape
6768            // supervisor sibling-restart-strategy closed-set typed enum,
6769            // acknowledged in 915a934's Prior-commits footnote as the
6770            // outstanding follow-up) now consult one typed dispatch on
6771            // the substrate primitive.
6772            let s = SupervisorSpec {
6773                estrategia: strat,
6774                children: if strat.is_simple_one_for_one() {
6775                    vec![]
6776                } else {
6777                    vec![child("w", "^0.1", RestartPolicy::Permanent)]
6778                },
6779                ..SupervisorSpec::default()
6780            };
6781            let json = serde_json::to_string(&s).unwrap();
6782            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6783            assert_eq!(s, back);
6784        }
6785    }
6786
6787    #[test]
6788    fn round_trip_all_restart_policies() {
6789        for policy in [
6790            RestartPolicy::Permanent,
6791            RestartPolicy::Temporary,
6792            RestartPolicy::Transient,
6793        ] {
6794            let c = child("w", "^0.1", policy);
6795            let json = serde_json::to_string(&c).unwrap();
6796            let back: ChildSpec = serde_json::from_str(&json).unwrap();
6797            assert_eq!(c, back);
6798        }
6799    }
6800
6801    #[test]
6802    fn restart_strategy_is_simple_one_for_one_predicate_partitions_the_arm_set() {
6803        // The fail-before-pass-after pin on the `gen_platform::IsVariant`
6804        // derive's [`RestartStrategy::is_simple_one_for_one`] arm-
6805        // discriminator predicate: [`RestartStrategy::SimpleOneForOne`]
6806        // is the only variant that satisfies `.is_simple_one_for_one()`;
6807        // every static-children-bearing arm (`OneForOne` / `OneForAll`
6808        // / `RestForOne`) returns `false`. This pin makes the partition
6809        // invariant load-bearing at caixa-core test time so a future
6810        // derive regression (a hole that returns `false` for
6811        // `SimpleOneForOne` too, or a byte-collision that flips a second
6812        // variant to `true`) trips here rather than laundering the arm
6813        // at the three test-fixture builder sites (a hole flips the
6814        // `SimpleOneForOne` fixture to carry a non-empty children list
6815        // and the subsequent `SupervisorSpec::validate` would refuse the
6816        // fixture with [`SupervisorError::SimpleOneForOneWithStaticChildren`];
6817        // a collision flips a peer strategy's fixture to carry an empty
6818        // children list and the subsequent `validate` would refuse with
6819        // [`SupervisorError::NoChildren`] — either way, the pin fires
6820        // here, at the derive site, rather than at the fixture-refusal
6821        // site far away). Peer of the sibling
6822        // [`crate::upgrade::tests::upgrade_instruction_is_restart_predicate_partitions_the_arm_set`]
6823        // (915a934) pin on the M2 OTP-appup axis and the sibling
6824        // [`crate::kind::tests::caixa_kind_is_variant_predicates_partition_the_arm_set`]
6825        // pin on the M0 `:kind` axis.
6826        let cases: &[(RestartStrategy, bool)] = &[
6827            (RestartStrategy::OneForOne, false),
6828            (RestartStrategy::OneForAll, false),
6829            (RestartStrategy::RestForOne, false),
6830            (RestartStrategy::SimpleOneForOne, true),
6831        ];
6832        for (variant, expected) in cases {
6833            assert_eq!(
6834                variant.is_simple_one_for_one(),
6835                *expected,
6836                "RestartStrategy::{variant:?}.is_simple_one_for_one() must \
6837                 return {expected} (partition invariant on the \
6838                 IsVariant-derived arm-discriminator predicate — every \
6839                 test-fixture site that partitions the `:children` slot \
6840                 shape on `SimpleOneForOne ↔ non-SimpleOneForOne` keys \
6841                 off this typed dispatch, so a derive regression must \
6842                 surface here rather than at the fixture-refusal site)"
6843            );
6844        }
6845    }
6846
6847    #[test]
6848    fn restart_strategy_fixture_partition_routes_through_is_simple_one_for_one_predicate() {
6849        // Byte-identity pin on the `SimpleOneForOne ↔ non-SimpleOneForOne`
6850        // fixture-shape partition against the pre-lift
6851        // `matches!(strat, RestartStrategy::SimpleOneForOne)` open-coded
6852        // pattern-match every test-fixture builder site previously
6853        // coupled to inline. Asserts the two projections agree byte-for-
6854        // byte on every arm of the enum, so a future derive regression
6855        // that flipped either predicate's arm-set would surface here at
6856        // caixa-core test time rather than at the three fixture-builder
6857        // sites (`supervisor::tests::round_trip_all_strategies`,
6858        // `supervisor::tests::supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`,
6859        // `manifest::tests::caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`)
6860        // far from the derive site. Same peer-shape byte-identity pin
6861        // every sibling `IsVariant`-derive-routed convergence carries on
6862        // the substrate's closed-set typed-enum surface (peer of
6863        // [`crate::upgrade::tests::validate_restart_exclusive_routes_through_is_restart_predicate`]
6864        // on the M2 OTP-appup axis).
6865        for &strat in RestartStrategy::ALL {
6866            let via_predicate = strat.is_simple_one_for_one();
6867            let via_matches = matches!(strat, RestartStrategy::SimpleOneForOne);
6868            assert_eq!(
6869                via_predicate, via_matches,
6870                "RestartStrategy::{strat:?}: is_simple_one_for_one() must \
6871                 byte-equal matches!(_, RestartStrategy::SimpleOneForOne) — \
6872                 the pre-lift open-coded pattern and the \
6873                 IsVariant-derived predicate are the same axis, \
6874                 one typed dispatch"
6875            );
6876        }
6877    }
6878
6879    #[test]
6880    fn duration_codec_round_trip_canonical_units() {
6881        // Note the canonical-form rule: durations serialize to the
6882        // *largest* unit that divides cleanly, so 60s ↔ "1m" and not
6883        // "60s" — but the round-trip preserves the underlying Duration.
6884        let cases = [
6885            ("30s", Duration::from_secs(30)),
6886            ("5m", Duration::from_secs(300)),
6887            ("1h", Duration::from_secs(3600)),
6888            ("500ms", Duration::from_millis(500)),
6889        ];
6890        for (lit, dur) in cases {
6891            let s = SupervisorSpec {
6892                children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6893                restart_window: Some(dur),
6894                ..SupervisorSpec::default()
6895            };
6896            let json = serde_json::to_string(&s).unwrap();
6897            assert!(
6898                json.contains(&format!("\"{lit}\"")),
6899                "expected \"{lit}\" in {json}"
6900            );
6901            let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6902            assert_eq!(back.restart_window, Some(dur));
6903        }
6904    }
6905
6906    #[test]
6907    fn duration_canonicalizes_to_largest_unit() {
6908        // 60 seconds → "1m" (largest cleanly-divisible unit), but the
6909        // typed Duration still equals 60s on the way back.
6910        let s = SupervisorSpec {
6911            children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6912            restart_window: Some(Duration::from_secs(60)),
6913            ..SupervisorSpec::default()
6914        };
6915        let json = serde_json::to_string(&s).unwrap();
6916        assert!(json.contains("\"1m\""), "{json}");
6917        let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6918        assert_eq!(back.restart_window, Some(Duration::from_secs(60)));
6919    }
6920
6921    #[test]
6922    fn three_child_one_for_one_validates() {
6923        let s = SupervisorSpec {
6924            estrategia: RestartStrategy::OneForOne,
6925            max_restarts: 5,
6926            restart_window: Some(Duration::from_secs(60)),
6927            children: vec![
6928                child("worker", "^0.1", RestartPolicy::Permanent),
6929                child("cache", "^0.1", RestartPolicy::Transient),
6930                child("scratch", "^0.1", RestartPolicy::Temporary),
6931            ],
6932        };
6933        s.validate().unwrap();
6934    }
6935
6936    #[test]
6937    fn json_uses_pascal_case_for_strategy_and_policy() {
6938        // Variant names are PascalCase by default in serde, matching
6939        // tatara-lisp's enum convention (`:estrategia OneForOne`).
6940        let c = child("w", "^0.1", RestartPolicy::Permanent);
6941        let json = serde_json::to_string(&c).unwrap();
6942        assert!(json.contains("\"Permanent\""));
6943        assert!(!json.contains("\"permanent\""));
6944
6945        let s = SupervisorSpec {
6946            estrategia: RestartStrategy::OneForOne,
6947            children: vec![c],
6948            ..SupervisorSpec::default()
6949        };
6950        let json = serde_json::to_string(&s).unwrap();
6951        assert!(json.contains("\"estrategia\":\"OneForOne\""));
6952    }
6953
6954    // ── shared duration codec: integer-magnitude canonical-form gate ──
6955    //
6956    // The gate lifts the discipline `crate::limits::parse_duration`
6957    // (818dd38) carries on the peer `:limits :wall-clock` codec onto
6958    // the shared codec backing the remaining three typed-duration
6959    // slots: `:supervisor :restart-window`, `:politicas :timeout`, and
6960    // `:politicas :circuit-breaker :window`. Every magnitude `render`
6961    // emits is a non-negative integer with no decimal point and no
6962    // leading sign, so the codec's accepted set must match for
6963    // serialize/deserialize to round-trip without canonical-form
6964    // drift.
6965
6966    #[test]
6967    fn parse_accepts_integer_canonical_units() {
6968        // Pin the happy-path: every canonical author shape `render`
6969        // ever emits parses to the same `Duration` value, so the
6970        // codec's accepted set is at least a superset of its emitted
6971        // set on the canonical-unit axis.
6972        for (lit, dur) in [
6973            ("30s", Duration::from_secs(30)),
6974            ("500ms", Duration::from_millis(500)),
6975            ("2m", Duration::from_secs(120)),
6976            ("1h", Duration::from_secs(3600)),
6977            ("0s", Duration::ZERO),
6978        ] {
6979            assert_eq!(
6980                duration_codec::parse(lit).unwrap(),
6981                dur,
6982                "parse({lit:?}) should be {dur:?}"
6983            );
6984        }
6985    }
6986
6987    #[test]
6988    fn parse_accepts_bare_integer_as_seconds() {
6989        // The `"s" | ""` arm: a bare integer with no unit is read as
6990        // seconds. Pin this so the unit-empty form keeps parsing (it
6991        // renders to `"<n>s"` on serialize — that's a unit-choice
6992        // drift the integer-magnitude gate does NOT close, matching
6993        // the `parse_byte_size` `"1024"` → `"1KiB"` scope decision in
6994        // the peer `:limits :memory` codec).
6995        assert_eq!(
6996            duration_codec::parse("30").unwrap(),
6997            Duration::from_secs(30)
6998        );
6999    }
7000
7001    #[test]
7002    fn parse_rejects_fractional_seconds_with_canonical_form_diagnostic() {
7003        // `"1.5s"` parses as f64 to 1.5 → renders back as `"1500ms"`
7004        // on first serialize — DRIFT. The integer-magnitude gate names
7005        // the offending `"1.5"` verbatim and points at the canonical
7006        // remediation `"1500ms"`.
7007        let err = duration_codec::parse("1.5s").unwrap_err();
7008        assert!(err.contains("\"1.5\""), "missing magnitude in {err:?}");
7009        assert!(
7010            err.contains("not a non-negative integer"),
7011            "missing canonical-form reason in {err:?}"
7012        );
7013        assert!(
7014            err.contains("\"1500ms\""),
7015            "missing canonical-form remediation in {err:?}"
7016        );
7017    }
7018
7019    #[test]
7020    fn parse_rejects_decimal_shaped_integer_seconds() {
7021        // `"1.0s"` is the trickiest drift class: numerically `1.0s` is
7022        // `1s` exactly, so the round-trip looks correct — but the
7023        // emitted canonical form is `"1s"`, not `"1.0s"`. Gate the
7024        // decimal-shape-with-integer-value form so author intent is
7025        // never silently rewritten.
7026        let err = duration_codec::parse("1.0s").unwrap_err();
7027        assert!(err.contains("\"1.0\""), "missing magnitude in {err:?}");
7028        assert!(
7029            err.contains("not a non-negative integer"),
7030            "missing canonical-form reason in {err:?}"
7031        );
7032    }
7033
7034    #[test]
7035    fn parse_rejects_half_unit_minute() {
7036        // `"0.5m"` is the unit-fraction footgun — author writes a
7037        // human-readable half-minute, serde silently rewrites to
7038        // `"30s"` on next emit. The gate names the offending
7039        // magnitude `"0.5"` and points at the integer-in-smaller-unit
7040        // form.
7041        let err = duration_codec::parse("0.5m").unwrap_err();
7042        assert!(err.contains("\"0.5\""), "missing magnitude in {err:?}");
7043        assert!(
7044            err.contains("\"30s\""),
7045            "missing canonical-form remediation in {err:?}"
7046        );
7047    }
7048
7049    #[test]
7050    fn parse_rejects_leading_plus_sign() {
7051        // `u64::from_str` rejects `"+30"` but `f64::from_str` accepts
7052        // it as `30.0` — the prior parser used f64 so `"+30s"` parsed
7053        // cleanly to 30s and round-tripped to `"30s"` on next emit
7054        // (DRIFT). The digit-only gate closes the leading-sign class
7055        // first; the diagnostic names `"+30"` verbatim.
7056        let err = duration_codec::parse("+30s").unwrap_err();
7057        assert!(err.contains("\"+30\""), "missing magnitude in {err:?}");
7058        assert!(
7059            err.contains("not a non-negative integer"),
7060            "missing canonical-form reason in {err:?}"
7061        );
7062    }
7063
7064    #[test]
7065    fn parse_rejects_leading_minus_sign() {
7066        // The former `num < 0.0` arm: `"-30s"` parsed as f64 to -30,
7067        // rejected with `"negative duration in \"-30s\""`. Under the
7068        // integer-magnitude gate the diagnostic is unified — `-30` is
7069        // non-digit-only, f64-numeric, and surfaces with the canonical-
7070        // form reason (no leading `+` / `-` sign) naming the offending
7071        // `"-30"` verbatim. Same diagnostic shape as every other
7072        // rejected non-integer magnitude.
7073        let err = duration_codec::parse("-30s").unwrap_err();
7074        assert!(err.contains("\"-30\""), "missing magnitude in {err:?}");
7075        assert!(
7076            err.contains("not a non-negative integer"),
7077            "missing canonical-form reason in {err:?}"
7078        );
7079    }
7080
7081    #[test]
7082    fn parse_garbage_still_falls_through_to_bad_magnitude() {
7083        // Non-digit-only AND non-numeric (`"--1s"`, `"abc"`) falls
7084        // through to the narrower "bad duration magnitude" arm — the
7085        // canonical-form diagnostic is reserved for the parser-shape
7086        // footgun case, not the "not a number at all" case. Same
7087        // shape `parse_byte_size`'s `BadByteMagnitude` arm carries on
7088        // the peer `:limits :memory` codec.
7089        let err = duration_codec::parse("--1s").unwrap_err();
7090        assert!(
7091            err.contains("bad duration magnitude"),
7092            "expected bad-magnitude wording in {err:?}"
7093        );
7094    }
7095
7096    #[test]
7097    fn parse_digit_only_magnitude_carries_zero_f64_drift() {
7098        // The accepted set is now closed under `u64`-exact integer
7099        // arithmetic: `"500ms"` → `Duration::from_millis(500)` exactly,
7100        // `"3600s"` → `Duration::from_secs(3600)` exactly, `"1h"` →
7101        // `Duration::from_secs(3600)` exactly, no f64 mantissa drift
7102        // possible. Pin the integer-exact arms across the four unit
7103        // suffixes so a future refactor that reaches back for f64
7104        // (`from_secs_f64`, `mul_f64`) surfaces here.
7105        assert_eq!(
7106            duration_codec::parse("3600s").unwrap(),
7107            Duration::from_secs(3600)
7108        );
7109        assert_eq!(
7110            duration_codec::parse("60m").unwrap(),
7111            Duration::from_secs(3600)
7112        );
7113        assert_eq!(
7114            duration_codec::parse("1h").unwrap(),
7115            Duration::from_secs(3600)
7116        );
7117        assert_eq!(
7118            duration_codec::parse("999ms").unwrap(),
7119            Duration::from_millis(999)
7120        );
7121    }
7122
7123    #[test]
7124    fn restart_window_serde_rejects_fractional_seconds() {
7125        // The shared codec backs `SupervisorSpec::restart_window`
7126        // (`with = "duration_codec"`) — so the gate applies on serde
7127        // deserialize for the typed Supervisor slot. A
7128        // `{"restartWindow":"1.5s"}` payload that previously round-
7129        // tripped to a different canonical string on next serialize
7130        // is now refused at deserialize with the integer-magnitude
7131        // diagnostic.
7132        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
7133            "restartWindow":"1.5s",
7134            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
7135        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
7136        let msg = err.to_string();
7137        assert!(
7138            msg.contains("not a non-negative integer"),
7139            "expected integer-magnitude diagnostic in {msg:?}"
7140        );
7141        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
7142    }
7143
7144    #[test]
7145    fn restart_window_serde_rejects_leading_plus() {
7146        // The `u64::from_str` leading-`+` permissiveness gap that
7147        // motivated the digit-only gate (the `f64`-side accepted
7148        // `"+30"`, the prior parser silently round-tripped to `"30s"`)
7149        // is now closed on the shared codec — surfaces as a structured
7150        // diagnostic at the serde layer for every typed-duration slot.
7151        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
7152            "restartWindow":"+30s",
7153            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
7154        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
7155        let msg = err.to_string();
7156        assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
7157        assert!(
7158            msg.contains("not a non-negative integer"),
7159            "missing canonical-form reason in {msg:?}"
7160        );
7161    }
7162
7163    #[test]
7164    fn parse_rejects_leading_zero_magnitude() {
7165        // `"030s"` is digit-only, so the existing non-digit-only / sign
7166        // / fractional arm doesn't catch it — `u64::from_str("030")`
7167        // returns `Ok(30)`, so before this gate `"030s"` parsed to
7168        // `Duration::from_secs(30)` and round-tripped through `render`
7169        // to `"30s"` — a *different* canonical string on the next emit,
7170        // breaking the THEORY.md Part V render-determinism contract
7171        // exactly the way `"+30s"` did before the leading-`+` arm
7172        // landed. Peer with the `rate_limit_codec` leading-zero arm
7173        // (4f46830) on the same canonical-form-drift axis.
7174        let err = duration_codec::parse("030s").unwrap_err();
7175        assert!(
7176            err.contains("non-canonical leading zero"),
7177            "expected leading-zero diagnostic in {err:?}"
7178        );
7179        assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
7180        assert!(
7181            err.contains("\"30s\""),
7182            "missing canonical-form remediation in {err:?}"
7183        );
7184        assert!(
7185            err.contains("THEORY.md"),
7186            "missing render-determinism citation in {err:?}"
7187        );
7188    }
7189
7190    #[test]
7191    fn parse_rejects_multi_digit_zero_magnitude() {
7192        // `"00s"` and `"00ms"` are the all-zero leading-zero footgun —
7193        // digit-only, parse losslessly to `Duration::ZERO`, but render
7194        // back to `"0s"` (the single-byte canonical form) on the next
7195        // emit. The leading-zero arm refuses the drift class at the
7196        // codec layer; the semantic-zero gate downstream
7197        // (`SupervisorError::ZeroRestartWindow`, etc.) would refuse
7198        // the single-byte canonical form `"0s"` separately on the
7199        // typed-validate layer.
7200        let err = duration_codec::parse("00s").unwrap_err();
7201        assert!(
7202            err.contains("non-canonical leading zero"),
7203            "expected leading-zero diagnostic in {err:?}"
7204        );
7205        assert!(err.contains("\"00\""), "missing magnitude in {err:?}");
7206    }
7207
7208    #[test]
7209    fn parse_rejects_leading_zero_per_hour_window() {
7210        // `"01h"` is the per-hour-window footgun — multi-byte magnitude
7211        // starting with `0`, parses losslessly to `Duration::from_secs(3600)`,
7212        // renders to `"1h"` (DRIFT). The arm is unit-agnostic: every
7213        // canonical unit suffix the codec accepts (`ms` / `s` / `m` /
7214        // `h` / bare-integer-as-seconds) inherits the same gate.
7215        let err = duration_codec::parse("01h").unwrap_err();
7216        assert!(
7217            err.contains("non-canonical leading zero"),
7218            "expected leading-zero diagnostic in {err:?}"
7219        );
7220        assert!(err.contains("\"01\""), "missing magnitude in {err:?}");
7221    }
7222
7223    #[test]
7224    fn parse_rejects_leading_zero_bare_integer_as_seconds() {
7225        // The `parse_accepts_bare_integer_as_seconds` happy-path
7226        // (`"30"` → 30s) inherits the leading-zero arm: `"030"` is
7227        // multi-byte starts-with-`0`, parses losslessly to
7228        // `Duration::from_secs(30)`, renders to `"30s"` (DRIFT). The
7229        // bare-integer surface accepts permissive unit-empty
7230        // shorthand but still must reject leading-zero padding.
7231        let err = duration_codec::parse("030").unwrap_err();
7232        assert!(
7233            err.contains("non-canonical leading zero"),
7234            "expected leading-zero diagnostic in {err:?}"
7235        );
7236        assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
7237    }
7238
7239    #[test]
7240    fn parse_accepts_single_zero_magnitude_at_codec_layer() {
7241        // The codec-layer / typed-validate-layer boundary: `"0s"` /
7242        // `"0ms"` / `"0"` are the single-byte canonical-zero forms —
7243        // each round-trips losslessly through `render`
7244        // (`render(Duration::ZERO)` → `"0s"`), so the codec layer
7245        // accepts them. The downstream semantic-zero gates
7246        // (`SupervisorError::ZeroRestartWindow`,
7247        // `AplicacaoError::PolicyTimeoutZero`,
7248        // `AplicacaoError::PolicyCircuitBreakerWindowZero`) refuse
7249        // zero-magnitude authoring at the typed-validate layer above,
7250        // peer with the `rate_limit_codec` codec-layer / typed-
7251        // validate-layer partition for `"0/s"`.
7252        assert_eq!(duration_codec::parse("0s").unwrap(), Duration::ZERO);
7253        assert_eq!(duration_codec::parse("0ms").unwrap(), Duration::ZERO);
7254        assert_eq!(duration_codec::parse("0").unwrap(), Duration::ZERO);
7255    }
7256
7257    #[test]
7258    fn parse_accepts_canonical_magnitude_with_leading_one() {
7259        // The complementary boundary: a future tightening cannot
7260        // drift into rejecting valid canonical magnitudes that
7261        // happen to start with `1` (or any digit `[1-9]`). Pin
7262        // every canonical-unit suffix so the leading-zero arm
7263        // remains strictly narrower than the digit-only arm.
7264        assert_eq!(
7265            duration_codec::parse("100ms").unwrap(),
7266            Duration::from_millis(100)
7267        );
7268        assert_eq!(
7269            duration_codec::parse("100s").unwrap(),
7270            Duration::from_secs(100)
7271        );
7272        assert_eq!(
7273            duration_codec::parse("10m").unwrap(),
7274            Duration::from_secs(600)
7275        );
7276        assert_eq!(
7277            duration_codec::parse("10h").unwrap(),
7278            Duration::from_secs(36_000)
7279        );
7280    }
7281
7282    #[test]
7283    fn restart_window_serde_rejects_leading_zero() {
7284        // The shared codec backs `SupervisorSpec::restart_window`
7285        // (`with = "duration_codec"`) — so the leading-zero arm
7286        // applies on serde deserialize for the typed Supervisor slot.
7287        // A `{"restartWindow":"030s"}` payload that previously round-
7288        // tripped to a different canonical string on next serialize
7289        // is now refused at deserialize with the leading-zero
7290        // diagnostic. Peer with `restart_window_serde_rejects_leading_plus`
7291        // / `restart_window_serde_rejects_fractional_seconds` on the
7292        // same canonical-form-drift axis.
7293        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
7294            "restartWindow":"030s",
7295            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
7296        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
7297        let msg = err.to_string();
7298        assert!(
7299            msg.contains("non-canonical leading zero"),
7300            "expected leading-zero diagnostic in {msg:?}"
7301        );
7302        assert!(msg.contains("\"030\""), "missing magnitude in {msg:?}");
7303    }
7304
7305    #[test]
7306    fn parse_rejects_leading_whitespace() {
7307        // `" 30s"` — the canonical paste-from-aligned-doc /
7308        // paste-from-YAML-quoted-plain-scalar footgun. Before this
7309        // gate the top-level `s.trim()` at parse entry silently ate
7310        // the leading space and parsed the value to
7311        // `Duration::from_secs(30)`, which then round-tripped through
7312        // `render` to `"30s"` (a *different* canonical string on the
7313        // next emit) — the exact canonical-form-drift class the
7314        // leading-`+` / leading-zero arms already close, extended
7315        // to the whitespace-byte class. Peer with the sibling
7316        // `rate_limit_codec` whitespace-rejection arm (1ad7755) on
7317        // the M3 `:politicas` axis.
7318        let err = duration_codec::parse(" 30s").unwrap_err();
7319        assert!(
7320            err.contains("contains whitespace byte"),
7321            "expected whitespace diagnostic in {err:?}"
7322        );
7323        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
7324        assert!(
7325            err.contains("THEORY.md"),
7326            "missing render-determinism contract citation in {err:?}"
7327        );
7328    }
7329
7330    #[test]
7331    fn parse_rejects_trailing_whitespace() {
7332        // `"30s "` — the canonical shell-history / trailing-space
7333        // paste footgun. Before this gate the top-level `s.trim()`
7334        // silently ate the trailing space and parsed to
7335        // `Duration::from_secs(30)`, round-tripping to `"30s"` on the
7336        // next emit — same canonical-form drift as the leading-space
7337        // sibling, closed on the same whitespace-byte arm.
7338        let err = duration_codec::parse("30s ").unwrap_err();
7339        assert!(
7340            err.contains("contains whitespace byte"),
7341            "expected whitespace diagnostic in {err:?}"
7342        );
7343        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
7344    }
7345
7346    #[test]
7347    fn parse_rejects_internal_whitespace_between_magnitude_and_unit() {
7348        // `"30 s"` — the canonical typographically-spaced author
7349        // shape (the same idiom every prose reference to a duration
7350        // renders as, mistakenly retained when the value is pasted
7351        // into a codec-shaped slot). Before this gate the per-part
7352        // `num_part.trim()` / `unit.trim()` calls silently ate the
7353        // whitespace between the magnitude and the unit and parsed
7354        // the value to `Duration::from_secs(30)`, round-tripping to
7355        // `"30s"` — the codec's *internal* whitespace-tolerance
7356        // vector, orthogonal to the leading / trailing surface but
7357        // the same canonical-form-drift class. Pins the arm as
7358        // strictly stronger than the pre-existing top-level
7359        // `s.trim()` behavior: it fires on whitespace anywhere in
7360        // the value, not just at the string boundary.
7361        let err = duration_codec::parse("30 s").unwrap_err();
7362        assert!(
7363            err.contains("contains whitespace byte"),
7364            "expected whitespace diagnostic in {err:?}"
7365        );
7366        assert!(err.contains("0x20"), "missing offending byte in {err:?}");
7367    }
7368
7369    #[test]
7370    fn parse_rejects_tab_byte() {
7371        // `"\t30s"` — the canonical paste-from-indented-doc /
7372        // paste-from-YAML-block-scalar footgun where a tab byte leads
7373        // the magnitude. Pins that the gate covers tab (`0x09`) as
7374        // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
7375        // members and both would be silently swallowed by `s.trim()`
7376        // pre-gate. The `is_ascii_whitespace` coverage extends beyond
7377        // space alone to the full ASCII-whitespace set (space `0x20`,
7378        // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
7379        // the tab arm as a representative of the non-space members.
7380        let err = duration_codec::parse("\t30s").unwrap_err();
7381        assert!(
7382            err.contains("contains whitespace byte"),
7383            "expected whitespace diagnostic in {err:?}"
7384        );
7385        assert!(
7386            err.contains("0x09"),
7387            "missing offending tab byte in {err:?}"
7388        );
7389    }
7390
7391    #[test]
7392    fn restart_window_serde_rejects_whitespace() {
7393        // The shared codec backs `SupervisorSpec::restart_window`
7394        // (`with = "duration_codec"`) — so the whitespace arm
7395        // applies on serde deserialize for the typed Supervisor slot.
7396        // A `{"restartWindow":" 30s"}` payload that previously round-
7397        // tripped to a different canonical string on next serialize
7398        // is now refused at deserialize with the whitespace-byte
7399        // diagnostic. Peer with `restart_window_serde_rejects_leading_zero`
7400        // / `restart_window_serde_rejects_leading_plus` /
7401        // `restart_window_serde_rejects_fractional_seconds` on the
7402        // same canonical-form-drift axis.
7403        let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
7404            "restartWindow":" 30s",
7405            "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
7406        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
7407        let msg = err.to_string();
7408        assert!(
7409            msg.contains("contains whitespace byte"),
7410            "expected whitespace diagnostic in {msg:?}"
7411        );
7412        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
7413    }
7414
7415    // ── canonical-form: non-ASCII Unicode `White_Space` duration gate ─────
7416    //
7417    // Successor to the ASCII-whitespace arm (a7ae622) on the shared
7418    // duration codec — closes the strictly-complementary class the
7419    // byte-scan cannot see, through the lifted
7420    // [`crate::render::find_non_ascii_whitespace_char`] predicate.
7421    // Applies to `:supervisor :restart-window`, `:politicas :timeout`,
7422    // and `:politicas :circuit-breaker :window` simultaneously via
7423    // this shared codec.
7424
7425    #[test]
7426    fn duration_codec_parse_rejects_leading_nbsp() {
7427        // NBSP prefix — the strictly-complementary drift class the
7428        // ASCII byte-scan cannot see. `str::trim` strips it silently
7429        // and the value drifts to `"30s"` on next serialize.
7430        let err = duration_codec::parse("\u{00A0}30s").unwrap_err();
7431        assert!(
7432            err.contains("non-ASCII Unicode whitespace character"),
7433            "expected non-ASCII whitespace diagnostic in {err:?}"
7434        );
7435        assert!(err.contains("U+00A0"), "missing codepoint in {err:?}");
7436    }
7437
7438    #[test]
7439    fn duration_codec_parse_rejects_trailing_line_separator() {
7440        // LINE SEPARATOR (`\u{2028}`) trailing — paste-from-web-doc
7441        // footgun.
7442        let err = duration_codec::parse("30s\u{2028}").unwrap_err();
7443        assert!(
7444            err.contains("non-ASCII Unicode whitespace character"),
7445            "expected non-ASCII whitespace diagnostic in {err:?}"
7446        );
7447        assert!(err.contains("U+2028"), "missing codepoint in {err:?}");
7448    }
7449
7450    #[test]
7451    fn duration_codec_parse_accepts_ascii_only_forms_after_unicode_arm() {
7452        // Positive-control pin: every ASCII-only canonical form the
7453        // renderer emits stays accepted through the new arm.
7454        assert_eq!(
7455            duration_codec::parse("30s").unwrap(),
7456            Duration::from_secs(30)
7457        );
7458        assert_eq!(
7459            duration_codec::parse("500ms").unwrap(),
7460            Duration::from_millis(500)
7461        );
7462        assert_eq!(
7463            duration_codec::parse("1h").unwrap(),
7464            Duration::from_secs(3600)
7465        );
7466    }
7467
7468    #[test]
7469    fn restart_window_serde_rejects_non_ascii_whitespace() {
7470        // The shared codec backs `SupervisorSpec::restart_window` — so
7471        // the new non-ASCII Unicode whitespace arm applies on serde
7472        // deserialize for the typed Supervisor slot. A
7473        // `{"restartWindow":" 30s"}` payload that previously
7474        // survived the ASCII byte-scan (only ASCII whitespace was
7475        // refused) is now refused at deserialize with the
7476        // non-ASCII-whitespace-and-codepoint diagnostic.
7477        let payload = "{\"estrategia\":\"OneForOne\",\"maxRestarts\":5,\
7478            \"restartWindow\":\"\u{00A0}30s\",\
7479            \"children\":[{\"caixa\":\"w\",\"versao\":\"^0.1\",\"restart\":\"Permanent\"}]}";
7480        let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
7481        let msg = err.to_string();
7482        assert!(
7483            msg.contains("non-ASCII Unicode whitespace character"),
7484            "expected non-ASCII whitespace diagnostic in {msg:?}"
7485        );
7486        assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
7487    }
7488
7489    // ── drift-detection: serde-derive-to-SUPERVISOR_KEY_* identity ────────
7490
7491    #[test]
7492    fn supervisor_spec_serde_keys_match_lifted_supervisor_key_consts() {
7493        // Load-bearing invariant: the four `SUPERVISOR_KEY_*` consts
7494        // (`SUPERVISOR_KEY_ESTRATEGIA` / `SUPERVISOR_KEY_MAX_RESTARTS` /
7495        // `SUPERVISOR_KEY_RESTART_WINDOW` / `SUPERVISOR_KEY_CHILDREN`)
7496        // name the exact camelCase JSON keys the
7497        // `#[serde(rename_all = "camelCase")]` attribute on
7498        // `SupervisorSpec` emits. Serialize a fully-populated spec (each
7499        // field carries `Some(_)` / non-empty) and pin that each canonical
7500        // byte-sequence appears verbatim in the JSON — a future accidental
7501        // `rename_all = "snake_case"` / `"kebab-case"` / verbatim-field-
7502        // name flip at the derive attribute (any of which would silently
7503        // break every downstream JSON consumer that reaches for one of the
7504        // four consts via `Value::get(...)`) surfaces here as a build-time
7505        // test failure at `supervisor.rs`, not as an apply-time
7506        // `.get(<stale-canonical-const>)` returning `None` far from the
7507        // derive-attr drift's commit. Peer with the sibling
7508        // `limits_spec_serde_keys_match_lifted_m2_limits_key_consts`
7509        // (d8b8b4f) pin on the M2 `:limits` axis — same discipline the
7510        // M2 typed-slot family established, extended here to close the
7511        // top-level Supervisor axis.
7512        let spec = SupervisorSpec {
7513            estrategia: RestartStrategy::OneForOne,
7514            max_restarts: 5,
7515            restart_window: Some(Duration::from_secs(60)),
7516            children: vec![ChildSpec {
7517                caixa: "w".into(),
7518                versao: "^0.1".into(),
7519                restart: RestartPolicy::Permanent,
7520            }],
7521        };
7522        let json = serde_json::to_string(&spec).unwrap();
7523        for key in [
7524            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
7525            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
7526            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
7527            crate::render::SUPERVISOR_KEY_CHILDREN,
7528        ] {
7529            let quoted = format!("\"{key}\"");
7530            assert!(
7531                json.contains(&quoted),
7532                "serialized SupervisorSpec must carry the lifted \
7533                 SUPERVISOR_KEY_* byte-sequence {quoted} verbatim in \
7534                 the JSON emission (got: {json})",
7535            );
7536        }
7537    }
7538
7539    #[test]
7540    fn supervisor_key_consts_are_pairwise_distinct() {
7541        // Cross-axis drift-detection pin: a future collapse of two
7542        // canonical top-level byte-strings onto the same value (e.g. an
7543        // accidental copy-paste flip of `SUPERVISOR_KEY_CHILDREN` to
7544        // also read `"estrategia"`) would silently reroute every
7545        // downstream probe on one axis onto the sibling axis's overlay
7546        // entry and pass every propagation-probe test that expected only
7547        // the stale axis's value. Peer of the sibling four-way distinct
7548        // pin on the `M2_LIMITS_KEY_*` tetrad (d8b8b4f).
7549        let all = [
7550            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
7551            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
7552            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
7553            crate::render::SUPERVISOR_KEY_CHILDREN,
7554        ];
7555        for (i, a) in all.iter().enumerate() {
7556            for b in all.iter().skip(i + 1) {
7557                assert_ne!(
7558                    a, b,
7559                    "SUPERVISOR_KEY_* consts must be pairwise-distinct \
7560                     canonical byte-sequences — got `{a}` == `{b}`",
7561                );
7562            }
7563        }
7564    }
7565
7566    #[test]
7567    fn supervisor_key_consts_are_lower_camel_case_shape() {
7568        // Shape-pin: every `SUPERVISOR_KEY_*` const must be a
7569        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
7570        // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
7571        // capital, no whitespace / dots) — the canonical shape the
7572        // `#[serde(rename_all = "camelCase")]` derive produces on
7573        // `SupervisorSpec`. A future flip to a non-camelCase attribute
7574        // at the derive surfaces both here (this test fails on the
7575        // stale-constant shape) and at
7576        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
7577        // (that test fails on the mismatch between const and derive).
7578        // Peer with `m2_limits_key_consts_are_lower_camel_case_shape`
7579        // (d8b8b4f) on the sibling M2 `:limits` axis.
7580        for key in [
7581            crate::render::SUPERVISOR_KEY_ESTRATEGIA,
7582            crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
7583            crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
7584            crate::render::SUPERVISOR_KEY_CHILDREN,
7585        ] {
7586            assert!(
7587                !key.is_empty(),
7588                "SUPERVISOR_KEY_* must be non-empty (got {key:?})"
7589            );
7590            let first = key.chars().next().unwrap();
7591            assert!(
7592                first.is_ascii_lowercase(),
7593                "SUPERVISOR_KEY_* must lead with an ASCII-lowercase byte \
7594                 (got {key:?}, leads with {first:?})",
7595            );
7596            assert!(
7597                key.chars().all(|c| c.is_ascii_alphanumeric()),
7598                "SUPERVISOR_KEY_* must be ASCII-alphanumeric only \
7599                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
7600            );
7601        }
7602    }
7603
7604    #[test]
7605    fn supervisor_key_consts_are_byte_distinct_from_supervisor_author_key_peers() {
7606        // Cross-axis drift pin: the four `SUPERVISOR_KEY_*` consts
7607        // (camelCase JSON keys, no leading colon) must never collide
7608        // byte-for-byte with the four peer `SUPERVISOR_AUTHOR_KEY_*`
7609        // consts (kebab-case author-facing labels with leading colon)
7610        // that sit next to them at `caixa_core::render`. Both families
7611        // cover the same four typed Supervisor slots on two distinct
7612        // axes (author-side kebab vs renderer-side camelCase);
7613        // collapsing either family onto the other's byte-shape would
7614        // silently reroute the render-side probe onto the author-facing
7615        // surface, or vice versa. Peer of the byte-distinctness
7616        // discipline the `M3_PLACEMENT_KEY_ESTRATEGIA` docstring names
7617        // against the peer `M3_AUTHOR_KEY_PLACEMENT`.
7618        let pairs = [
7619            (
7620                crate::render::SUPERVISOR_KEY_ESTRATEGIA,
7621                crate::render::SUPERVISOR_AUTHOR_KEY_ESTRATEGIA,
7622            ),
7623            (
7624                crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
7625                crate::render::SUPERVISOR_AUTHOR_KEY_MAX_RESTARTS,
7626            ),
7627            (
7628                crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
7629                crate::render::SUPERVISOR_AUTHOR_KEY_RESTART_WINDOW,
7630            ),
7631            (
7632                crate::render::SUPERVISOR_KEY_CHILDREN,
7633                crate::render::SUPERVISOR_AUTHOR_KEY_CHILDREN,
7634            ),
7635        ];
7636        for (json_key, author_key) in pairs {
7637            assert_ne!(
7638                json_key, author_key,
7639                "SUPERVISOR_KEY_* (JSON side) must differ byte-for-byte \
7640                 from the peer SUPERVISOR_AUTHOR_KEY_* (author side); \
7641                 got JSON `{json_key}` == author `{author_key}`",
7642            );
7643        }
7644    }
7645
7646    // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_KEY_* identity ──
7647
7648    #[test]
7649    fn child_spec_serde_keys_match_lifted_supervisor_child_key_consts() {
7650        // Load-bearing invariant: the three `SUPERVISOR_CHILD_KEY_*` consts
7651        // (`SUPERVISOR_CHILD_KEY_CAIXA` / `SUPERVISOR_CHILD_KEY_VERSAO` /
7652        // `SUPERVISOR_CHILD_KEY_RESTART`) name the exact camelCase JSON
7653        // keys the `#[serde(rename_all = "camelCase")]` attribute on
7654        // `ChildSpec` emits. Serialize a fully-populated `ChildSpec` and
7655        // pin that each canonical byte-sequence appears verbatim in the
7656        // JSON — a future accidental `rename_all = "snake_case"` /
7657        // `"kebab-case"` / verbatim-field-name flip at the derive
7658        // attribute (any of which would silently break every downstream
7659        // JSON consumer that reaches for one of the three consts via
7660        // `Value::get(...)`) surfaces here as a build-time test failure at
7661        // `supervisor.rs`, not as an apply-time
7662        // `.get(<stale-canonical-const>)` returning `None` far from the
7663        // derive-attr drift's commit. Peer with the enclosing
7664        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
7665        // (40cc4e5) pin on the M2 supervision-tree top-level axis — same
7666        // discipline the SupervisorSpec top-level lift established,
7667        // extended here to the sibling per-`:children` entry `ChildSpec`
7668        // derive so the last M2 typed-struct sub-block
7669        // `#[serde(rename_all = "camelCase")]` axis on the Supervisor
7670        // surface without a lifted serde-key peer joins the substrate's
7671        // "one canonical byte-string per typed serialized-key axis"
7672        // discipline.
7673        let c = ChildSpec {
7674            caixa: "worker".into(),
7675            versao: "^0.1".into(),
7676            restart: RestartPolicy::Permanent,
7677        };
7678        let json = serde_json::to_string(&c).unwrap();
7679        for key in [
7680            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
7681            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
7682            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
7683        ] {
7684            let quoted = format!("\"{key}\"");
7685            assert!(
7686                json.contains(&quoted),
7687                "serialized ChildSpec must carry the lifted \
7688                 SUPERVISOR_CHILD_KEY_* byte-sequence {quoted} verbatim \
7689                 in the JSON emission (got: {json})",
7690            );
7691        }
7692    }
7693
7694    #[test]
7695    fn supervisor_child_key_consts_are_pairwise_distinct() {
7696        // Cross-axis drift-detection pin: a future collapse of two
7697        // canonical `ChildSpec` per-entry byte-strings onto the same
7698        // value (e.g. an accidental copy-paste flip of
7699        // `SUPERVISOR_CHILD_KEY_RESTART` to also read `"caixa"`) would
7700        // silently reroute every downstream probe on one axis onto the
7701        // sibling axis's overlay entry and pass every propagation-probe
7702        // test that expected only the stale axis's value. Peer of the
7703        // sibling three-way distinct pin on the `CONTRATO_KEY_*` triad
7704        // (ca463a4) and the two-way distinct pin on the `MEMBRO_KEY_*`
7705        // pair (ce80ca0).
7706        let all = [
7707            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
7708            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
7709            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
7710        ];
7711        for (i, a) in all.iter().enumerate() {
7712            for b in all.iter().skip(i + 1) {
7713                assert_ne!(
7714                    a, b,
7715                    "SUPERVISOR_CHILD_KEY_* consts must be pairwise-\
7716                     distinct canonical byte-sequences — got `{a}` == `{b}`",
7717                );
7718            }
7719        }
7720    }
7721
7722    #[test]
7723    fn supervisor_child_key_consts_are_lower_camel_case_shape() {
7724        // Shape-pin: every `SUPERVISOR_CHILD_KEY_*` const must be a
7725        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
7726        // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
7727        // capital, no whitespace / dots) — the canonical shape the
7728        // `#[serde(rename_all = "camelCase")]` derive produces on
7729        // `ChildSpec`. A future flip to a non-camelCase attribute at the
7730        // derive surfaces both here (this test fails on the
7731        // stale-constant shape) and at
7732        // `child_spec_serde_keys_match_lifted_supervisor_child_key_consts`
7733        // (that test fails on the mismatch between const and derive).
7734        // Peer with `supervisor_key_consts_are_lower_camel_case_shape`
7735        // (40cc4e5) on the sibling `SupervisorSpec` top-level axis.
7736        for key in [
7737            crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
7738            crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
7739            crate::render::SUPERVISOR_CHILD_KEY_RESTART,
7740        ] {
7741            assert!(
7742                !key.is_empty(),
7743                "SUPERVISOR_CHILD_KEY_* must be non-empty (got {key:?})"
7744            );
7745            let first = key.chars().next().unwrap();
7746            assert!(
7747                first.is_ascii_lowercase(),
7748                "SUPERVISOR_CHILD_KEY_* must lead with an ASCII-lowercase \
7749                 byte (got {key:?}, leads with {first:?})",
7750            );
7751            assert!(
7752                key.chars().all(|c| c.is_ascii_alphanumeric()),
7753                "SUPERVISOR_CHILD_KEY_* must be ASCII-alphanumeric only \
7754                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
7755            );
7756        }
7757    }
7758
7759    // ── drift-detection: serde-derive-to-SUPERVISOR_ESTRATEGIA_* identity ────
7760
7761    #[test]
7762    fn restart_strategy_variants_serialize_to_lifted_scalar_values() {
7763        // The fail-before-pass-after pin: pre-lift there was no
7764        // single-source binding between the [`RestartStrategy`] variant
7765        // name the un-`rename`d `Serialize` derive emits under
7766        // [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`] and the byte-string
7767        // every downstream cluster-side dispatcher (the future
7768        // wasm-operator's per-supervisor sibling-restart branch, the
7769        // future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
7770        // admission-time enum-arm bind, the `caixa-operator`'s
7771        // hierarchical reconciliation scheduler's per-strategy fan-out)
7772        // probes verbatim. A future `#[serde(rename_all = "kebab-case")]`
7773        // attribute on the enum — or a per-variant `#[serde(rename = "…")]`
7774        // override, or a variant rename in the source — would silently
7775        // rebrand the emitted scalar under one spelling while every
7776        // downstream dispatcher still probed the other, with the failure
7777        // surfacing at the operator's reconcile posture (subtrees coming
7778        // up under the `default()` `OneForOne` arm rather than the typed
7779        // slot's declared strategy — a bad child would then only take
7780        // itself down instead of the sibling set the author intended, so
7781        // shared-state children fall out of sync) far from the source
7782        // rebrand commit and with no field naming the drift. Pinning the
7783        // two paths (the `Serialize` derive's serialized string AND the
7784        // [`RestartStrategy::as_str`] helper) to the same four lifted
7785        // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
7786        // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
7787        // [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
7788        // [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
7789        // byte-strings makes any future drift on either endpoint fail
7790        // here at caixa-core build time. Peer of the M3
7791        // `placement_strategy_variants_serialize_to_lifted_scalar_values`
7792        // (3f0e21c) on the sibling `PlacementStrategy` axis — same
7793        // three-path-convergence discipline, extended to close the
7794        // OTP-shaped per-supervisor sibling-restart axis.
7795        for (variant, expected) in [
7796            (
7797                RestartStrategy::OneForOne,
7798                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
7799            ),
7800            (
7801                RestartStrategy::OneForAll,
7802                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
7803            ),
7804            (
7805                RestartStrategy::RestForOne,
7806                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
7807            ),
7808            (
7809                RestartStrategy::SimpleOneForOne,
7810                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
7811            ),
7812        ] {
7813            let json = serde_json::to_string(&variant).unwrap();
7814            assert_eq!(
7815                json,
7816                format!("\"{expected}\""),
7817                "RestartStrategy::{variant:?} must serialize to {expected:?}"
7818            );
7819            assert_eq!(
7820                variant.as_str(),
7821                expected,
7822                "RestartStrategy::{variant:?}.as_str() must return the lifted \
7823                 SUPERVISOR_ESTRATEGIA_* constant"
7824            );
7825        }
7826    }
7827
7828    #[test]
7829    fn supervisor_estrategia_consts_are_pairwise_distinct() {
7830        // Cross-arm drift-detection pin: a future collapse of two
7831        // canonical variant byte-strings onto the same value (e.g. an
7832        // accidental copy-paste flip of `SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`
7833        // to also read `"OneForOne"`) would silently reroute every
7834        // downstream operator's per-strategy dispatch onto the sibling
7835        // arm's reconcile branch and pass every propagation-probe test
7836        // that expected only the stale arm's value — the mis-strategied
7837        // subtree would come up with the wrong sibling-restart posture
7838        // on every subsequent failure. Peer of the sibling four-way
7839        // distinct pin `supervisor_key_consts_are_pairwise_distinct`
7840        // (40cc4e5) on the top-level `SUPERVISOR_KEY_*` axis.
7841        let all = [
7842            crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
7843            crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
7844            crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
7845            crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
7846        ];
7847        for (i, a) in all.iter().enumerate() {
7848            for (j, b) in all.iter().enumerate() {
7849                if i != j {
7850                    assert_ne!(
7851                        a, b,
7852                        "SUPERVISOR_ESTRATEGIA_* consts must be pairwise distinct \
7853                         — got duplicate {a:?} at indices {i} and {j}",
7854                    );
7855                }
7856            }
7857        }
7858    }
7859
7860    #[test]
7861    fn restart_strategy_display_routes_through_as_str_helper() {
7862        // The fail-before-pass-after pin on the first half of the
7863        // three-path convergence: pre-convergence the sibling
7864        // OTP-shape typed enum [`RestartStrategy`] carried a
7865        // [`std::fmt::Display`] surface via its
7866        // `#[discriminant(also_display)]` gen-platform derive route,
7867        // which arrived kebab-case as `"one-for-one"` /
7868        // `"one-for-all"` / `"rest-for-one"` /
7869        // `"simple-one-for-one"` while the wire format ran as
7870        // PascalCase `"OneForOne"` / `"OneForAll"` / `"RestForOne"` /
7871        // `"SimpleOneForOne"` through the un-`rename`d serde derive.
7872        // Every consumer reaching for a strategy byte-string past the
7873        // wire format had to pick between three paths
7874        // ([`RestartStrategy::as_str`], the `Serialize` derive's
7875        // serialized string, or `format!("{v}")` on the
7876        // discriminant-Display route), any two of which a future
7877        // variant rename or `#[serde(rename_all = "kebab-case")]`
7878        // attribute would silently desynchronize. Wiring
7879        // [`std::fmt::Display`] through [`RestartStrategy::as_str`]
7880        // closes the third path: every `format!("{v}")` call reaches
7881        // the same lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
7882        // const the wire format and the [`RestartStrategy::as_str`]
7883        // helper already route through, so a future variant rename
7884        // lands at exactly one place. Pin the routing here so a future
7885        // `impl std::fmt::Display for RestartStrategy`
7886        // reimplementation that hand-rolls the arms instead of
7887        // delegating to [`RestartStrategy::as_str`] fails at
7888        // caixa-core build time. Peer of the M3
7889        // `placement_strategy_display_routes_through_as_str_helper`
7890        // (cc8f749) which the M3 axis converged first.
7891        for &variant in RestartStrategy::ALL {
7892            assert_eq!(
7893                variant.to_string(),
7894                variant.as_str(),
7895                "RestartStrategy::{variant:?} Display must route through \
7896                 RestartStrategy::as_str (single source of truth: the lifted \
7897                 SUPERVISOR_ESTRATEGIA_* const the wire format also emits)"
7898            );
7899        }
7900    }
7901
7902    #[test]
7903    fn restart_strategy_display_matches_serialized_wire_byte_string() {
7904        // The fail-before-pass-after pin on the second half of the
7905        // three-path convergence: `Display` (user-facing text) agrees
7906        // byte-for-byte with the `Serialize` derive's wire format
7907        // (canonical camelCase-schema `SUPERVISOR_KEY_ESTRATEGIA`
7908        // scalar) on every variant. Pre-convergence the two paths
7909        // were structurally independent — a future
7910        // `#[serde(rename_all = "kebab-case")]` attribute on the
7911        // enum would silently rebrand the emitted wire scalar
7912        // (`one-for-one`, `one-for-all`, `rest-for-one`,
7913        // `simple-one-for-one`) while every consumer that
7914        // pretty-prints the strategy (the future wasm-operator's
7915        // per-supervisor sibling-restart-strategy diagnostic line,
7916        // the future `feira app graph` per-supervisor strategy line,
7917        // the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
7918        // materializer's admission-webhook rejection body) would
7919        // still emit the PascalCase form the `as_str` / `Display`
7920        // route returns, with the mismatch surfacing at consumer
7921        // parse time / operator dispatch time far from the source
7922        // rebrand commit. Pin the two paths byte-for-byte here so any
7923        // future serde-attribute or variant-rename drift is a
7924        // caixa-core-build-time test failure at this call, not a
7925        // silent per-consumer dispatch miss. Peer of the M3
7926        // `placement_strategy_display_matches_serialized_wire_byte_string`
7927        // (cc8f749) which the M3 axis converged first.
7928        for &variant in RestartStrategy::ALL {
7929            let wire = serde_json::to_string(&variant).unwrap();
7930            let unquoted = wire
7931                .strip_prefix('"')
7932                .and_then(|s| s.strip_suffix('"'))
7933                .expect("serialized RestartStrategy is a JSON string");
7934            assert_eq!(
7935                variant.to_string(),
7936                unquoted,
7937                "RestartStrategy::{variant:?} Display byte-string must match the \
7938                 Serialize derive's wire byte-string (three-path convergence: \
7939                 Display + as_str + Serialize all resolve to the same \
7940                 SUPERVISOR_ESTRATEGIA_* const)"
7941            );
7942        }
7943    }
7944
7945    #[test]
7946    fn restart_strategy_as_ref_str_routes_through_as_str_accessor() {
7947        // Fail-before-pass-after byte-parity pin on the lifted
7948        // `impl AsRef<str> for RestartStrategy` — asserts the
7949        // standard-library trait impl and the substrate-primitive
7950        // [`RestartStrategy::as_str`] `pub const fn` accessor resolve
7951        // to the same `&str` per instance across the four-arm
7952        // closed set, so any future silent detour that routes the
7953        // impl through a divergent projection (a per-arm inline
7954        // `match self { RestartStrategy::OneForOne => "OneForOne", … }`
7955        // re-inlining that opens a compile-time link to the un-lifted
7956        // arm-literal, a swap onto the kebab-case
7957        // [`gen_platform::Discriminant`] catalog identity that would
7958        // collide the wire axis with the dispatcher-catalog axis) trips
7959        // at caixa-core test time under `PartialEq` rather than at a
7960        // downstream `impl AsRef<str>`-bound consumer's silent split.
7961        // Sweeps every one of the four arms
7962        // [`RestartStrategy::ALL`] carries so no arm's projection is
7963        // covered only by the sibling wire-format `Serialize` derive
7964        // path. Peer of the sibling
7965        // [`crate::version::tests::caixa_version_as_ref_str_routes_through_as_str_accessor`]
7966        // (16d5c7e) `AsRef<str>`-byte-parity pin on the paired
7967        // top-level `:versao` typed newtype — the two pins together
7968        // cover the substrate primitive's `AsRef<str>` projection axis
7969        // on the paired newtype + closed-set-typed-enum surface.
7970        for &variant in RestartStrategy::ALL {
7971            assert_eq!(
7972                <RestartStrategy as AsRef<str>>::as_ref(&variant),
7973                variant.as_str(),
7974                "AsRef<str> impl on RestartStrategy::{variant:?} must \
7975                 byte-equal RestartStrategy::as_str on the same instance \
7976                 — divergence signals a silent detour off the substrate-\
7977                 primitive accessor"
7978            );
7979        }
7980    }
7981
7982    #[test]
7983    fn restart_strategy_as_ref_str_routes_through_display_via_shared_accessor() {
7984        // Fail-before-pass-after byte-parity pin on the three-path
7985        // convergence discipline the M2 sibling-restart primitive now
7986        // carries on the `&str`-projection axis:
7987        // `<RestartStrategy as AsRef<str>>::as_ref(&s)` (the newly
7988        // lifted impl), `format!("{s}")` (the pre-existing
7989        // [`fmt::Display`] impl), and `s.as_str()` (the substrate-
7990        // primitive `pub const fn` accessor both trait impls delegate
7991        // through) must resolve to the same byte-string on every
7992        // instance across the four-arm closed set. Refuses any future
7993        // divergence between the two trait impls (a stray
7994        // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
7995        // rather than delegating through the shared accessor; a
7996        // hypothetical `AsRef<str>` rewrite that inlines a per-arm
7997        // literal cascade) that would silently split the two
7998        // projection paths of the same closed-set typed enum. Mirrors
7999        // the sibling three-path-convergence discipline the peer
8000        // [`crate::CaixaVersion`] typed newtype carries on its
8001        // `AsRef<str>` / `Display` / `as_str` triple
8002        // (version.rs pin
8003        // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
8004        // 16d5c7e).
8005        for &variant in RestartStrategy::ALL {
8006            let via_as_ref: &str = <RestartStrategy as AsRef<str>>::as_ref(&variant);
8007            let via_display: String = format!("{variant}");
8008            let via_accessor: &str = variant.as_str();
8009            assert_eq!(via_as_ref, via_accessor);
8010            assert_eq!(via_display, via_accessor);
8011            assert_eq!(via_as_ref, via_display.as_str());
8012        }
8013    }
8014
8015    #[test]
8016    fn restart_strategy_all_enumerates_every_variant_exactly_once() {
8017        // Fail-before-pass-after pin on the [`RestartStrategy::ALL`]
8018        // exhaustive-iteration surface: every variant appears exactly
8019        // once, and the slice length matches the arm count of the
8020        // closed set. Every consumer that walks the accepted-strategy
8021        // set (a future `feira supervisor --estrategia …` CLI-side
8022        // arg-parse's "did you mean" hint, a future M4 admission-
8023        // webhook's rejection body naming the accepted-`:estrategia`
8024        // list, the [`RestartStrategy::from_wire`] reverse-projection
8025        // consumers that iterate the accept-set for diagnostic
8026        // rendering) reads through this slice, so a future arm addition
8027        // that grows the enum but forgets to grow [`Self::ALL`]
8028        // silently truncates every downstream consumer's accept-set at
8029        // the same pre-addition boundary — this pin fails at caixa-core
8030        // build time on the pairwise-distinct + arm-count invariants.
8031        //
8032        // Peer of the sibling [`crate::CaixaKind::ALL`] (6b1f4fb) /
8033        // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
8034        // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
8035        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
8036        // pins on the peer closed-set typed-enum axes.
8037        let all: &[RestartStrategy] = RestartStrategy::ALL;
8038        assert_eq!(
8039            all.len(),
8040            4,
8041            "RestartStrategy::ALL must enumerate every variant of the \
8042             four-arm closed set (OneForOne, OneForAll, RestForOne, \
8043             SimpleOneForOne); got {all:?}"
8044        );
8045        for (i, a) in all.iter().enumerate() {
8046            for (j, b) in all.iter().enumerate() {
8047                if i != j {
8048                    assert_ne!(
8049                        a, b,
8050                        "RestartStrategy::ALL must carry every variant exactly \
8051                         once — got duplicate {a:?} at indices {i} and {j}"
8052                    );
8053                }
8054            }
8055        }
8056        for variant in [
8057            RestartStrategy::OneForOne,
8058            RestartStrategy::OneForAll,
8059            RestartStrategy::RestForOne,
8060            RestartStrategy::SimpleOneForOne,
8061        ] {
8062            assert!(
8063                all.contains(&variant),
8064                "RestartStrategy::ALL must contain {variant:?} — a future arm \
8065                 addition that grows the enum but forgets to grow the ALL slice \
8066                 silently truncates every downstream consumer's accept-set at \
8067                 the pre-addition boundary"
8068            );
8069        }
8070    }
8071
8072    #[test]
8073    fn restart_strategy_from_wire_accepts_every_lifted_constant() {
8074        // Fail-before-pass-after pin on the forward accept-set of the
8075        // [`RestartStrategy::from_wire`] reverse projection: every
8076        // canonical [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
8077        // constant the [`RestartStrategy::as_str`] emitter walks parses
8078        // back to its paired variant. Any future arm addition that
8079        // grows the emitter's `as_str` match but forgets to grow the
8080        // parser's `from_wire` match silently splits the two halves of
8081        // the round-trip — the wire byte-string one non-serde consumer
8082        // parses from the one the emitter wrote — with the failure
8083        // surfacing at parse time far from the rebrand commit. Pinning
8084        // the four-arm accept-set here catches the drift at caixa-core
8085        // build time.
8086        //
8087        // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
8088        // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
8089        // accept-set pins on the peer closed-set typed-enum `str → Self`
8090        // axes.
8091        for (wire, expected) in [
8092            (
8093                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
8094                RestartStrategy::OneForOne,
8095            ),
8096            (
8097                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
8098                RestartStrategy::OneForAll,
8099            ),
8100            (
8101                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
8102                RestartStrategy::RestForOne,
8103            ),
8104            (
8105                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
8106                RestartStrategy::SimpleOneForOne,
8107            ),
8108        ] {
8109            let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
8110                panic!(
8111                    "RestartStrategy::from_wire({wire:?}) must accept every \
8112                     SUPERVISOR_ESTRATEGIA_* constant — got None for the \
8113                     lifted canonical byte-string that RestartStrategy::{expected:?} \
8114                     serializes as under SUPERVISOR_KEY_ESTRATEGIA"
8115                )
8116            });
8117            assert_eq!(
8118                parsed, expected,
8119                "RestartStrategy::from_wire({wire:?}) must return \
8120                 RestartStrategy::{expected:?}; got RestartStrategy::{parsed:?}"
8121            );
8122        }
8123    }
8124
8125    #[test]
8126    fn restart_strategy_from_wire_round_trips_through_as_str() {
8127        // Fail-before-pass-after pin on the closed round-trip between
8128        // the forward [`RestartStrategy::as_str`] emitter and the
8129        // reverse [`RestartStrategy::from_wire`] parser: for every
8130        // variant in [`RestartStrategy::ALL`], parsing the emitter's
8131        // output must return exactly the same variant. Any per-arm
8132        // divergence — a future arm added to `as_str` but not
8133        // `from_wire`, an accidental copy-paste flip in one but not
8134        // the other — silently splits the emit and parse halves and
8135        // the failure surfaces at consumer parse time far from the
8136        // drift site. The `ALL`-iterating shape means a future arm
8137        // addition picks up the coverage by construction.
8138        //
8139        // Peer of the sibling
8140        // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
8141        // (18c7342) round-trip pin on
8142        // [`crate::aplicacao::PlacementStrategy::from_wire`] and
8143        // [`crate::kind::tests::caixa_kind_wire_round_trips_through_from_wire`]
8144        // (6b1f4fb) round-trip pin on [`crate::CaixaKind::from_wire`].
8145        for &variant in RestartStrategy::ALL {
8146            let wire = variant.as_str();
8147            let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
8148                panic!(
8149                    "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
8150                     must be Some({variant:?}) — the two halves of the round-trip \
8151                     dispatch on the same lifted SUPERVISOR_ESTRATEGIA_* consts; \
8152                     got None on wire byte-string {wire:?}"
8153                )
8154            });
8155            assert_eq!(
8156                parsed, variant,
8157                "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
8158                 must round-trip to the same variant; got {parsed:?}"
8159            );
8160        }
8161    }
8162
8163    #[test]
8164    fn restart_strategy_from_wire_rejects_unknown_byte_strings() {
8165        // Fail-before-pass-after pin on the closed-set refusal
8166        // discipline of [`RestartStrategy::from_wire`]: every
8167        // byte-string outside the four-arm accept-set returns `None`
8168        // rather than silently collapsing onto the [`Default`]
8169        // (`OneForOne`) arm or an arbitrary neighbor. The refusal set
8170        // exercised here sweeps the load-bearing drift shapes: the
8171        // empty string (a stripped serde-attribute drift), all-
8172        // whitespace strings (the canonical text-editor accidental
8173        // padding shape), the kebab-case dispatcher-catalog identities
8174        // (`"one-for-one"` / `"one-for-all"` / `"rest-for-one"` /
8175        // `"simple-one-for-one"` — the [`gen_platform::FromStrKind`]-
8176        // derived [`std::str::FromStr`] accept-set, which parses the
8177        // *other* axis of this enum's two-axis split and must not leak
8178        // into the `from_wire` PascalCase-wire accept-set), the
8179        // lowercased single-word forms (`"oneforone"`), the padded
8180        // canonical scalar (`" OneForOne "`), the trailing-newline
8181        // shapes (`"OneForOne\n"`), and neighboring-but-unknown arms
8182        // (`"AllForOne"` — the canonical typo direction).
8183        //
8184        // Peer of the sibling
8185        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
8186        // (2aa6d23) +
8187        // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
8188        // (18c7342) refusal pins on the peer closed-set typed-enum
8189        // axes.
8190        for bad in [
8191            "",
8192            " ",
8193            "\n",
8194            "\t",
8195            "one-for-one",
8196            "one-for-all",
8197            "rest-for-one",
8198            "simple-one-for-one",
8199            "oneforone",
8200            "OneForOnes",
8201            "one_for_one",
8202            "one for one",
8203            "ONEFORONE",
8204            "OneForOne ",
8205            " OneForOne",
8206            " SimpleOneForOne ",
8207            "OneForOne\n",
8208            "restforone",
8209            "REST_FOR_ONE",
8210            "AllForOne",
8211            "Simple",
8212            "?",
8213        ] {
8214            assert!(
8215                RestartStrategy::from_wire(bad).is_none(),
8216                "RestartStrategy::from_wire({bad:?}) must return None — the \
8217                 parser's accept-set is exactly the four RestartStrategy::as_str \
8218                 outputs (OneForOne, OneForAll, RestForOne, SimpleOneForOne), \
8219                 and this byte-string is outside that closed set"
8220            );
8221        }
8222    }
8223
8224    #[test]
8225    fn restart_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
8226        // Fail-before-pass-after pin on the fourth path of the four-path
8227        // convergence: `from_wire` (the reverse projection) inverts the
8228        // `Serialize` derive's wire byte-string on every variant.
8229        // Together with the pre-existing three-path convergence
8230        // (`Display` + `as_str` + `Serialize` all resolve to the same
8231        // lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const,
8232        // pinned by
8233        // [`restart_strategy_display_matches_serialized_wire_byte_string`])
8234        // this closes the round-trip: the wire byte-string the
8235        // `Serialize` derive emits parses back to the same variant
8236        // through `from_wire`, so any future serde-attribute or variant-
8237        // rename drift on the emit half now surfaces as a matched drift
8238        // on the parse half at caixa-core build time — the two halves
8239        // migrate as a unit through the lifted consts on any future
8240        // rename, and the round-trip cannot silently split.
8241        //
8242        // Peer of the sibling
8243        // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
8244        // (18c7342) wire-format pin on
8245        // [`crate::aplicacao::PlacementStrategy::from_wire`].
8246        for &variant in RestartStrategy::ALL {
8247            let wire = serde_json::to_string(&variant).unwrap();
8248            let unquoted = wire
8249                .strip_prefix('"')
8250                .and_then(|s| s.strip_suffix('"'))
8251                .expect("serialized RestartStrategy is a JSON string");
8252            let parsed = RestartStrategy::from_wire(unquoted).unwrap_or_else(|| {
8253                panic!(
8254                    "RestartStrategy::from_wire({unquoted:?}) must accept the \
8255                     Serialize derive's wire byte-string for \
8256                     RestartStrategy::{variant:?} — the four-path convergence \
8257                     (Display + as_str + Serialize + from_wire) resolves through \
8258                     the same lifted SUPERVISOR_ESTRATEGIA_* const; got None"
8259                )
8260            });
8261            assert_eq!(
8262                parsed, variant,
8263                "RestartStrategy::from_wire of the Serialize derive's wire \
8264                 byte-string for RestartStrategy::{variant:?} must round-trip \
8265                 to the same variant; got {parsed:?}"
8266            );
8267        }
8268    }
8269
8270    #[test]
8271    fn restart_strategy_try_from_str_routes_through_from_wire_accessor() {
8272        // Fail-before-pass-after byte-parity pin on the newly lifted
8273        // `impl TryFrom<&str> for RestartStrategy` — asserts the standard-
8274        // library trait impl and the substrate-primitive
8275        // [`RestartStrategy::from_wire`] `Option<Self>` accessor resolve to
8276        // the same four-arm accept-set across every arm the exhaustive
8277        // [`RestartStrategy::ALL`] slice enumerates. Any future silent
8278        // detour that routes the trait impl through a divergent projection
8279        // (a per-arm inline `match s { "OneForOne" => Ok(Self::OneForOne),
8280        // … }` re-inlining that opens a compile-time link to the un-
8281        // lifted arm-literal, a hypothetical `#[serde(rename_all = "…")]`
8282        // attribute drift that silently splits the wire byte-string from
8283        // every consumer that reaches for this typed dispatch, an
8284        // accidental swap onto the kebab-case dispatcher-catalog axis the
8285        // pre-existing [`std::str::FromStr`] impl parses through and which
8286        // would collide the two-axis wire/catalog split the sibling
8287        // [`RestartStrategy::from_wire`] doc block makes load-bearing)
8288        // trips at caixa-core test time under `assert_eq!` rather than at
8289        // a downstream `impl TryFrom<&str>`-bound consumer's silent split.
8290        // Sweeps every one of the four arms [`RestartStrategy::ALL`]
8291        // carries so no arm's projection is covered only by the sibling
8292        // method-named `from_wire` path. Peer of the sibling
8293        // [`crate::kind::tests::caixa_kind_try_from_str_routes_through_from_wire_accessor`]
8294        // (3c83606),
8295        // [`crate::dialeto::tests::caixa_dialeto_try_from_str_routes_through_from_wire_accessor`]
8296        // (bf33136), and the M3
8297        // [`crate::aplicacao::tests::placement_strategy_try_from_str_routes_through_from_wire_accessor`]
8298        // (6fd00cd) — extends the trait-idiomatic reverse-projection axis
8299        // onto the first M2-OTP-shape closed-set typed enum on the caixa
8300        // surface.
8301        for &variant in RestartStrategy::ALL {
8302            let wire = variant.as_str();
8303            assert_eq!(
8304                <RestartStrategy as TryFrom<&str>>::try_from(wire),
8305                Ok(variant),
8306                "TryFrom<&str> impl on RestartStrategy must round-trip \
8307                 RestartStrategy::{variant:?}.as_str() = {wire:?} back to \
8308                 Ok(RestartStrategy::{variant:?}) — divergence from \
8309                 RestartStrategy::from_wire signals a silent detour off \
8310                 the substrate-primitive accessor"
8311            );
8312            assert_eq!(
8313                <RestartStrategy as TryFrom<&str>>::try_from(wire).ok(),
8314                RestartStrategy::from_wire(wire),
8315                "TryFrom<&str> ok()-projection on {wire:?} must byte-equal \
8316                 RestartStrategy::from_wire on the same input"
8317            );
8318        }
8319    }
8320
8321    #[test]
8322    fn restart_strategy_try_from_str_rejects_unknown_byte_strings() {
8323        // Rejection witness on the `impl TryFrom<&str> for
8324        // RestartStrategy` — sweeps a candidate set of byte-strings
8325        // outside the four-arm PascalCase wire accept-set the sibling
8326        // [`RestartStrategy::as_str`] emits and asserts every one lands on
8327        // `Err(())`, so a future accidental widening of the trait impl's
8328        // accept-set (a stray additional
8329        // `_ if s.eq_ignore_ascii_case("OneForOne") => Ok(…)` case-fold
8330        // path, a silent inclusion of the kebab-case dispatcher-catalog
8331        // byte-string the pre-existing [`std::str::FromStr`] impl the
8332        // [`gen_platform::FromStrKind`] derive installs parses onto the
8333        // wire axis — which would collide the two-axis
8334        // wire/dispatcher-catalog split the sibling
8335        // [`RestartStrategy::from_wire`] doc block makes load-bearing —
8336        // an English-rebrand or plural-arm silent alias that would
8337        // widen the wire accept-set past the OTP-canonical four) trips at
8338        // caixa-core test time. The candidate set includes the empty
8339        // string, whitespace-only padding, the kebab-case dispatcher-
8340        // catalog byte-strings on the sibling axis (a caller who confuses
8341        // the two axes trips here rather than at a downstream consumer's
8342        // silent reject), a lowercase / uppercase / mixed-case fold of
8343        // each PascalCase arm (a caller who assumes case-fold acceptance
8344        // trips here), leading/trailing whitespace padding, the trailing-
8345        // newline shape, quote-wrapped candidates, and a residual set of
8346        // plausible-but-wrong English rebrand candidates. Peer of the
8347        // sibling
8348        // [`crate::kind::tests::caixa_kind_try_from_str_rejects_unknown_byte_strings`]
8349        // (3c83606) and
8350        // [`crate::aplicacao::tests::placement_strategy_try_from_str_rejects_unknown_byte_strings`]
8351        // (6fd00cd) rejection witnesses.
8352        let rejected: &[&str] = &[
8353            "",
8354            " ",
8355            "\n",
8356            "\t",
8357            "one-for-one",
8358            "one-for-all",
8359            "rest-for-one",
8360            "simple-one-for-one",
8361            "oneforone",
8362            "one_for_one",
8363            "OneForOnes",
8364            "ONEFORONE",
8365            "oneforall",
8366            "restforone",
8367            "simpleoneforone",
8368            "OneForOne ",
8369            " OneForOne",
8370            " OneForAll ",
8371            "OneForOne\n",
8372            "RestForOne\t",
8373            "OneForEach",
8374            "AllForOne",
8375            "one for one",
8376            "\"OneForOne\"",
8377            "?",
8378        ];
8379        for &input in rejected {
8380            assert_eq!(
8381                <RestartStrategy as TryFrom<&str>>::try_from(input),
8382                Err(()),
8383                "TryFrom<&str> impl on RestartStrategy must reject the \
8384                 non-wire byte-string {input:?} — silent acceptance signals \
8385                 an accept-set widening off the paired \
8386                 RestartStrategy::from_wire resolver"
8387            );
8388        }
8389    }
8390
8391    #[test]
8392    fn restart_strategy_try_from_str_and_from_wire_partition_the_accept_set() {
8393        // Cross-axis partition pin: the paired `TryFrom<&str>` and
8394        // `from_wire` reverse projections must resolve identically on
8395        // *every* input, not just the ones [`RestartStrategy::ALL`]
8396        // enumerates. Sweeps a mixed candidate set spanning accepted
8397        // (four-arm PascalCase wire byte-strings) and rejected (kebab-case
8398        // dispatcher-catalog byte-strings, empty, whitespace-padded,
8399        // quoted, English-rebrand candidates) inputs and asserts the
8400        // trait's `Result::ok()` projection byte-equals the method-named
8401        // resolver's `Option<Self>` return-shape on each, locking the two
8402        // paths together by construction so any future detour (a stray
8403        // `try_from` special-case that widens or narrows the accept-set
8404        // outside the paired `from_wire` resolver, an accidental swap
8405        // onto the kebab-case [`std::str::FromStr`] impl the
8406        // [`gen_platform::FromStrKind`] derive installs on the sibling
8407        // dispatcher-catalog axis) trips at caixa-core test time. Peer of
8408        // the sibling
8409        // [`crate::kind::tests::caixa_kind_try_from_str_and_from_wire_partition_the_accept_set`]
8410        // pin — extends the round-trip discipline onto the M2-OTP-shape
8411        // sibling-restart axis.
8412        let candidates: &[&str] = &[
8413            "OneForOne",
8414            "OneForAll",
8415            "RestForOne",
8416            "SimpleOneForOne",
8417            "",
8418            "one-for-one",
8419            "one-for-all",
8420            "rest-for-one",
8421            "simple-one-for-one",
8422            "oneforone",
8423            "unknown",
8424            "OneForOne ",
8425            " OneForOne",
8426            "\"OneForOne\"",
8427            "OneForEach",
8428            "?",
8429        ];
8430        for &input in candidates {
8431            let via_trait: Option<RestartStrategy> =
8432                <RestartStrategy as TryFrom<&str>>::try_from(input).ok();
8433            let via_method: Option<RestartStrategy> = RestartStrategy::from_wire(input);
8434            assert_eq!(
8435                via_trait, via_method,
8436                "TryFrom<&str> and from_wire must resolve identically on \
8437                 input {input:?} — divergence signals the two reverse-\
8438                 projection paths have drifted onto different accept-sets"
8439            );
8440        }
8441    }
8442
8443    #[test]
8444    fn restart_strategy_from_into_static_str_routes_through_as_str_accessor() {
8445        // Fail-before-pass-after byte-parity pin on the newly lifted
8446        // `impl From<RestartStrategy> for &'static str` — asserts the
8447        // standard-library trait impl and the substrate-primitive
8448        // [`RestartStrategy::as_str`] `pub const fn` accessor resolve to
8449        // the same four-arm emit-set across every arm the exhaustive
8450        // [`RestartStrategy::ALL`] slice enumerates. Any future silent
8451        // detour that routes the trait impl through a divergent
8452        // projection (a per-arm inline `match strategy { OneForOne =>
8453        // "OneForOne", … }` re-inlining that opens a compile-time link to
8454        // the un-lifted arm-literal, an accidental swap onto the sibling
8455        // kebab-case [`Self::discriminant`] dispatcher-catalog axis that
8456        // would collide the two-axis wire/catalog split the sibling
8457        // [`RestartStrategy::from_wire`] doc block makes load-bearing) trips
8458        // at caixa-core test time under `assert_eq!` rather than at a
8459        // downstream `impl Into<&'static str>`-bound consumer's silent
8460        // split. Sweeps every one of the four arms
8461        // [`RestartStrategy::ALL`] carries so no arm's projection is
8462        // covered only by the sibling method-named `as_str` /
8463        // [`std::fmt::Display`] / [`AsRef<str>`] paths. Materializes the
8464        // `<&'static str as From<RestartStrategy>>::from` output in a
8465        // `const`-shape binding to make the `'static` lifetime promise a
8466        // build-time invariant — a future accidental downgrade of any of
8467        // the four arms' [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
8468        // constants to a non-`&'static str` (a `String::leak()`-produced
8469        // return, a `Box::leak`-cast) trips at caixa-core build time
8470        // rather than at a downstream `'static`-bound consumer.
8471        const ONE_FOR_ONE: &str = RestartStrategy::OneForOne.as_str();
8472        const ONE_FOR_ALL: &str = RestartStrategy::OneForAll.as_str();
8473        const REST_FOR_ONE: &str = RestartStrategy::RestForOne.as_str();
8474        const SIMPLE_ONE_FOR_ONE: &str = RestartStrategy::SimpleOneForOne.as_str();
8475        for &variant in RestartStrategy::ALL {
8476            let via_trait: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8477            let via_method: &'static str = variant.as_str();
8478            assert_eq!(
8479                via_trait, via_method,
8480                "From<RestartStrategy> for &'static str impl must round-trip \
8481                 RestartStrategy::{variant:?} to the same lifted \
8482                 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str returns — \
8483                 divergence signals a silent detour off the substrate-primitive \
8484                 accessor"
8485            );
8486            let via_into: &'static str = variant.into();
8487            assert_eq!(
8488                via_into, via_method,
8489                "Into<&'static str>::into on RestartStrategy::{variant:?} must \
8490                 byte-equal RestartStrategy::as_str on the same input — the \
8491                 blanket-derived Into shape must resolve to the same as_str \
8492                 dispatch as the explicit From impl"
8493            );
8494        }
8495        assert_eq!(
8496            [ONE_FOR_ONE, ONE_FOR_ALL, REST_FOR_ONE, SIMPLE_ONE_FOR_ONE],
8497            [
8498                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
8499                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
8500                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
8501                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
8502            ],
8503            "const-context RestartStrategy::as_str must resolve to the four \
8504             lifted SUPERVISOR_ESTRATEGIA_* consts — a future accidental \
8505             downgrade of any arm to a non-const or non-static byte-string \
8506             breaks the `&'static str`-lifetime promise the paired \
8507             From<RestartStrategy> for &'static str impl carries by \
8508             construction"
8509        );
8510    }
8511
8512    #[test]
8513    fn restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set() {
8514        // Cross-axis partition pin: the paired trait-idiomatic
8515        // `From<RestartStrategy> for &'static str` forward projection and
8516        // the method-named [`RestartStrategy::as_str`] forward projection
8517        // must resolve identically on *every* arm, not just the ones
8518        // named in the primary byte-parity pin above. Sweeps every
8519        // [`RestartStrategy::ALL`] arm and asserts the trait's `From::from`
8520        // output byte-equals the method-named accessor's return-value on
8521        // each, locking the two forward-projection paths together by
8522        // construction so any future detour (a stray `From` special-case
8523        // that lands on a divergent per-arm literal outside the paired
8524        // `as_str` dispatch, a hypothetical rebrand touching one axis
8525        // without the other) trips at caixa-core test time. Peer of the
8526        // sibling reverse-projection partition pin
8527        // [`restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
8528        // — extends the round-trip discipline onto the trait-idiomatic
8529        // *forward* axis, closing the two-way `Self ↔ &'static str`
8530        // round-trip on the trait-idiomatic pair
8531        // (`From<Self> for &'static str` + `TryFrom<&str> for Self`) as
8532        // well as the pre-existing method-named pair
8533        // (`as_str` + `from_wire`).
8534        for &variant in RestartStrategy::ALL {
8535            let via_trait: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8536            let via_method: &'static str = variant.as_str();
8537            assert_eq!(
8538                via_trait, via_method,
8539                "From<RestartStrategy> for &'static str and \
8540                 RestartStrategy::as_str must resolve identically on \
8541                 RestartStrategy::{variant:?} — divergence signals the \
8542                 two forward-projection paths have drifted onto different \
8543                 emit-sets"
8544            );
8545        }
8546        // Round-trip witness: every arm's forward `From` output re-parses
8547        // through the paired trait-idiomatic reverse `TryFrom<&str>` back
8548        // to the original variant. Closes the two-way `RestartStrategy ↔
8549        // &'static str` round-trip on the trait-idiomatic axis pair,
8550        // mirroring the pre-existing method-named `as_str` + `from_wire`
8551        // round-trip on the substrate-primitive axis pair.
8552        for &variant in RestartStrategy::ALL {
8553            let emitted: &'static str = variant.into();
8554            let re_parsed: Result<RestartStrategy, ()> =
8555                <RestartStrategy as TryFrom<&str>>::try_from(emitted);
8556            assert_eq!(
8557                re_parsed,
8558                Ok(variant),
8559                "trait-idiomatic axis pair must round-trip \
8560                 RestartStrategy::{variant:?} through `.into::<&'static \
8561                 str>()` and back through `TryFrom<&str>` — a break signals \
8562                 the forward-emit and reverse-parse axes have drifted onto \
8563                 different vocabularies"
8564            );
8565        }
8566    }
8567
8568    #[test]
8569    fn restart_strategy_from_borrowed_into_static_str_routes_through_as_str_accessor() {
8570        // Fail-before-pass-after byte-parity pin on the newly lifted
8571        // `impl From<&RestartStrategy> for &'static str` — asserts the
8572        // borrowed-input standard-library trait impl and the substrate-
8573        // primitive [`RestartStrategy::as_str`] `pub const fn` accessor
8574        // resolve to the same four-arm emit-set across every arm the
8575        // exhaustive [`RestartStrategy::ALL`] slice enumerates. Rust's
8576        // `From` trait does not auto-derive the borrowed-input sibling
8577        // from a paired owned-input impl (no `impl<T, U> From<&T> for U
8578        // where T: Copy, U: From<T>` blanket in `core`), so the
8579        // borrowed-input axis is a distinct trait-idiomatic surface
8580        // that a `.iter().map(Into::into)` shape over
8581        // [`RestartStrategy::ALL`] (whose iterator yields
8582        // `&RestartStrategy`, not `RestartStrategy`) reaches through
8583        // this impl and no other — the paired owned-input
8584        // [`From<RestartStrategy>`] impl requires an explicit
8585        // `.copied()` / dereference before the trait fires.
8586        // Materializes the `<&'static str as
8587        // From<&RestartStrategy>>::from` output in a `const`-shape
8588        // binding to make the `'static` lifetime promise a build-time
8589        // invariant.
8590        const ONE_FOR_ONE: &str = RestartStrategy::OneForOne.as_str();
8591        const ONE_FOR_ALL: &str = RestartStrategy::OneForAll.as_str();
8592        const REST_FOR_ONE: &str = RestartStrategy::RestForOne.as_str();
8593        const SIMPLE_ONE_FOR_ONE: &str = RestartStrategy::SimpleOneForOne.as_str();
8594        for variant in RestartStrategy::ALL {
8595            let via_trait: &'static str = <&'static str as From<&RestartStrategy>>::from(variant);
8596            let via_method: &'static str = variant.as_str();
8597            assert_eq!(
8598                via_trait, via_method,
8599                "From<&RestartStrategy> for &'static str impl must \
8600                 round-trip &RestartStrategy::{variant:?} to the same \
8601                 lifted SUPERVISOR_ESTRATEGIA_* const \
8602                 RestartStrategy::as_str returns — divergence signals a \
8603                 silent detour off the substrate-primitive accessor"
8604            );
8605            let via_into: &'static str = variant.into();
8606            assert_eq!(
8607                via_into, via_method,
8608                "Into<&'static str>::into on &RestartStrategy::{variant:?} \
8609                 must byte-equal RestartStrategy::as_str on the same input — \
8610                 the blanket-derived Into shape must resolve to the same \
8611                 as_str dispatch as the explicit From impl"
8612            );
8613        }
8614        assert_eq!(
8615            [ONE_FOR_ONE, ONE_FOR_ALL, REST_FOR_ONE, SIMPLE_ONE_FOR_ONE],
8616            [
8617                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
8618                crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
8619                crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
8620                crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
8621            ],
8622            "const-context RestartStrategy::as_str must resolve to the \
8623             four lifted SUPERVISOR_ESTRATEGIA_* consts — the borrowed-\
8624             input From<&RestartStrategy> for &'static str impl inherits \
8625             its `'static` lifetime promise from the same accessor the \
8626             owned-input sibling routes through"
8627        );
8628    }
8629
8630    #[test]
8631    fn restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
8632        // Cross-axis partition pin: the paired trait-idiomatic
8633        // owned-input `From<RestartStrategy> for &'static str` (523157d
8634        // campaign-shape) and borrowed-input `From<&RestartStrategy> for
8635        // &'static str` (this lift) forward projections must resolve
8636        // identically on every arm, locking the two input-shape paths
8637        // together so any future detour trips at caixa-core test time.
8638        // Then a witness that a `.iter().map(Into::into)` pipe over
8639        // [`RestartStrategy::ALL`] (whose iterator yields
8640        // `&RestartStrategy`) materializes the four-arm accept-set
8641        // through the borrowed-input axis alone — the exact shape a
8642        // future wasm-operator per-supervisor sibling-restart-strategy
8643        // diagnostic line, a future substrate-wide per-arm diagnostic
8644        // column, or a
8645        // `HashMap::<&'static str, RestartStrategy>::from_iter(
8646        //     RestartStrategy::ALL.iter().map(|s| (s.into(), *s)))`-style
8647        // per-strategy lookup reaches through — closing the two-way
8648        // owned/borrowed input-shape symmetry on the forward-projection
8649        // trait-idiomatic axis. Peer of the sibling
8650        // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
8651        // (64aa742) /
8652        // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
8653        // (5ab993a) /
8654        // [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
8655        // (807b0b5) partition pins on the sibling closed-set typed-enum
8656        // discriminator axes — extends the borrowed-input axis
8657        // discipline onto the first M2 OTP-shape sibling-restart
8658        // closed-set typed enum on the caixa surface. Also closes the
8659        // direct two-way `&Self → &'static str → Self` round-trip via
8660        // the paired [`TryFrom<&str>`] axis — unlike the peer
8661        // [`crate::CaixaKind`] axis pair (whose forward `From` emits
8662        // lowercase Portuguese diagnostic bytes while the reverse
8663        // `TryFrom` parses `PascalCase` wire bytes, forcing the round-
8664        // trip through an intermediate wire-vocab hop), the
8665        // [`RestartStrategy::as_str`] emit and
8666        // [`RestartStrategy::from_wire`] parse share the same
8667        // `PascalCase` vocabulary by construction, so the borrowed-
8668        // input forward axis and the reverse axis compose directly.
8669        for &variant in RestartStrategy::ALL {
8670            let owned: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8671            let borrowed: &'static str = <&'static str as From<&RestartStrategy>>::from(&variant);
8672            assert_eq!(
8673                owned, borrowed,
8674                "From<RestartStrategy> and From<&RestartStrategy> for \
8675                 &'static str must resolve identically on \
8676                 RestartStrategy::{variant:?} — divergence signals the \
8677                 owned-input and borrowed-input forward-projection paths \
8678                 have drifted onto different emit-sets"
8679            );
8680        }
8681        let via_iter: Vec<&'static str> = RestartStrategy::ALL.iter().map(Into::into).collect();
8682        let via_method: Vec<&'static str> =
8683            RestartStrategy::ALL.iter().map(|s| s.as_str()).collect();
8684        assert_eq!(
8685            via_iter, via_method,
8686            "`.iter().map(Into::into)` over RestartStrategy::ALL must \
8687             byte-equal `.iter().map(|s| s.as_str())` on every arm — the \
8688             borrowed-input `From<&RestartStrategy> for &'static str` \
8689             axis is what makes the `.iter().map(Into::into)` shape route \
8690             through the substrate-primitive `RestartStrategy::as_str` \
8691             accessor rather than through a per-call-site `.copied()` / \
8692             dereference detour"
8693        );
8694        for variant in RestartStrategy::ALL {
8695            let emitted: &'static str = variant.into();
8696            let re_parsed: Result<RestartStrategy, ()> =
8697                <RestartStrategy as TryFrom<&str>>::try_from(emitted);
8698            assert_eq!(
8699                re_parsed,
8700                Ok(*variant),
8701                "trait-idiomatic borrowed-input forward-projection + \
8702                 reverse-projection axis pair must round-trip \
8703                 &RestartStrategy::{variant:?} through `.into::<&'static \
8704                 str>()` (via the borrowed-input axis) and back through \
8705                 `TryFrom<&str>` — a break signals the borrowed-input \
8706                 forward-emit and reverse-parse axes have drifted onto \
8707                 different vocabularies"
8708            );
8709        }
8710    }
8711
8712    #[test]
8713    fn restart_strategy_from_into_owned_string_routes_through_as_str_accessor() {
8714        // Fail-before-pass-after byte-parity pin on the newly lifted
8715        // `impl From<RestartStrategy> for String` — asserts the
8716        // owned-`String`-returning standard-library trait impl and the
8717        // substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
8718        // accessor resolve to the same four-arm emit-set across every
8719        // arm the exhaustive [`RestartStrategy::ALL`] slice enumerates.
8720        // Rust's standard library does not carry a blanket
8721        // `impl<T: AsRef<str>> From<T> for String` (nor an
8722        // `impl<T: fmt::Display> From<T> for String`), so the
8723        // owned-`String` forward-projection axis is a distinct
8724        // trait-idiomatic surface that a
8725        // `let key: String = strategy.into();`-shaped call site
8726        // reaches through this impl and no other — the paired sibling
8727        // `From<RestartStrategy> for &'static str` impl forces every
8728        // owned-`String` call site through an explicit
8729        // `.to_owned()` / `String::from` restatement.
8730        for &variant in RestartStrategy::ALL {
8731            let via_trait: String = <String as From<RestartStrategy>>::from(variant);
8732            let via_method: &'static str = variant.as_str();
8733            assert_eq!(
8734                via_trait.as_str(),
8735                via_method,
8736                "From<RestartStrategy> for String impl must round-trip \
8737                 RestartStrategy::{variant:?} to the same lifted \
8738                 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
8739                 returns — divergence signals a silent detour off the \
8740                 substrate-primitive accessor"
8741            );
8742            let via_into: String = variant.into();
8743            assert_eq!(
8744                via_into.as_str(),
8745                via_method,
8746                "Into<String>::into on RestartStrategy::{variant:?} must \
8747                 byte-equal RestartStrategy::as_str on the same input — the \
8748                 blanket-derived Into shape must resolve to the same as_str \
8749                 dispatch as the explicit From impl"
8750            );
8751        }
8752    }
8753
8754    #[test]
8755    fn restart_strategy_from_into_owned_string_and_static_str_agree_on_every_arm() {
8756        // Cross-axis partition pin: the paired trait-idiomatic
8757        // owned-`String` `From<RestartStrategy> for String` (this lift)
8758        // and owned-`&'static str` `From<RestartStrategy> for &'static
8759        // str` (523157d) forward projections must resolve identically
8760        // on every arm, locking the two return-type-shape paths
8761        // together so any future detour trips at caixa-core test time.
8762        // Also byte-parity witness against the sibling
8763        // [`ToString::to_string`] surface routed through
8764        // [`std::fmt::Display`] — the three owned-heap-string paths
8765        // (`.into::<String>()`, `String::from`, `.to_string()`) must
8766        // resolve identically on every arm so a future consumer that
8767        // picks any of the three lands on the same lifted
8768        // SUPERVISOR_ESTRATEGIA_* const. Then a direct round-trip
8769        // witness through the paired trait-idiomatic reverse
8770        // [`TryFrom<&str>`] axis on the owned-`String`'s
8771        // [`String::as_str`] borrow that closes the two-way
8772        // `Self → String → Self` round-trip on the trait-idiomatic
8773        // owned-`String` forward + reverse axis pair.
8774        for &variant in RestartStrategy::ALL {
8775            let owned_string: String = <String as From<RestartStrategy>>::from(variant);
8776            let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8777            assert_eq!(
8778                owned_string.as_str(),
8779                owned_static,
8780                "From<RestartStrategy> for String and From<RestartStrategy> \
8781                 for &'static str must resolve identically on \
8782                 RestartStrategy::{variant:?} — divergence signals the \
8783                 owned-`String` and owned-`&'static str` forward-projection \
8784                 return-type-shape paths have drifted onto different \
8785                 emit-sets"
8786            );
8787            let via_to_string: String = variant.to_string();
8788            assert_eq!(
8789                owned_string, via_to_string,
8790                "From<RestartStrategy> for String must byte-equal \
8791                 RestartStrategy::to_string on RestartStrategy::{variant:?} — \
8792                 divergence signals the trait-idiomatic owned-`String` \
8793                 forward-projection axis and the ToString-through-Display \
8794                 axis have drifted onto different emit-sets"
8795            );
8796        }
8797        let via_iter: Vec<String> = RestartStrategy::ALL
8798            .iter()
8799            .copied()
8800            .map(String::from)
8801            .collect();
8802        let via_method: Vec<String> = RestartStrategy::ALL
8803            .iter()
8804            .map(|s| s.as_str().to_owned())
8805            .collect();
8806        assert_eq!(
8807            via_iter, via_method,
8808            "`.iter().copied().map(String::from)` over RestartStrategy::ALL \
8809             must byte-equal `.iter().map(|s| s.as_str().to_owned())` on \
8810             every arm — the owned-`String` `From<RestartStrategy> for \
8811             String` axis is what makes the `String::from` composition \
8812             route through the substrate-primitive `RestartStrategy::as_str` \
8813             accessor rather than through a per-call-site `.to_owned()` / \
8814             `String::from(strategy.as_str())` detour"
8815        );
8816        for &variant in RestartStrategy::ALL {
8817            let emitted: String = variant.into();
8818            let re_parsed: Result<RestartStrategy, ()> =
8819                <RestartStrategy as TryFrom<&str>>::try_from(emitted.as_str());
8820            assert_eq!(
8821                re_parsed,
8822                Ok(variant),
8823                "trait-idiomatic owned-`String` forward-projection + \
8824                 reverse-projection axis pair must round-trip \
8825                 RestartStrategy::{variant:?} through `.into::<String>()` \
8826                 and back through `TryFrom<&str>` on the owned-`String`'s \
8827                 String::as_str borrow — a break signals the owned-`String` \
8828                 forward-emit and reverse-parse axes have drifted onto \
8829                 different vocabularies"
8830            );
8831        }
8832    }
8833
8834    #[test]
8835    fn restart_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor() {
8836        // Fail-before-pass-after byte-parity pin on the newly lifted
8837        // `impl From<&RestartStrategy> for String` — asserts the
8838        // borrowed-input owned-`String`-returning standard-library trait
8839        // impl and the substrate-primitive [`RestartStrategy::as_str`]
8840        // `pub const fn` accessor resolve to the same four-arm emit-set
8841        // across every arm the exhaustive [`RestartStrategy::ALL`] slice
8842        // enumerates. Rust's standard library does not carry a blanket
8843        // `impl<T: AsRef<str>> From<&T> for String` (nor an
8844        // `impl<T: fmt::Display> From<&T> for String`), so the
8845        // borrowed-input owned-`String` forward-projection axis is a
8846        // distinct trait-idiomatic surface that a
8847        // `let key: String = (&strategy).into();`-shaped call site
8848        // reaches through this impl and no other — the paired sibling
8849        // `From<RestartStrategy> for String` impl forces every
8850        // borrowed-input call site through an explicit `Copy` deref
8851        // (`String::from(*strategy)`) or an `.as_str().to_owned()` /
8852        // `.to_string()` detour.
8853        for &variant in RestartStrategy::ALL {
8854            let via_trait: String = <String as From<&RestartStrategy>>::from(&variant);
8855            let via_method: &'static str = variant.as_str();
8856            assert_eq!(
8857                via_trait.as_str(),
8858                via_method,
8859                "From<&RestartStrategy> for String impl must round-trip \
8860                 &RestartStrategy::{variant:?} to the same lifted \
8861                 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
8862                 returns — divergence signals a silent detour off the \
8863                 substrate-primitive accessor"
8864            );
8865            let via_into: String = (&variant).into();
8866            assert_eq!(
8867                via_into.as_str(),
8868                via_method,
8869                "Into<String>::into on &RestartStrategy::{variant:?} must \
8870                 byte-equal RestartStrategy::as_str on the same input — the \
8871                 blanket-derived Into shape must resolve to the same as_str \
8872                 dispatch as the explicit From impl"
8873            );
8874        }
8875    }
8876
8877    #[test]
8878    fn restart_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm() {
8879        // Cross-axis partition pin: the newly lifted trait-idiomatic
8880        // borrowed-input owned-`String` `From<&RestartStrategy> for
8881        // String` (this lift), the paired owned-input owned-`String`
8882        // `From<RestartStrategy> for String` (7baa18a), the paired
8883        // borrowed-input owned-`&'static str` `From<&RestartStrategy>
8884        // for &'static str` (e941836), and the paired owned-input
8885        // owned-`&'static str` `From<RestartStrategy> for &'static str`
8886        // (523157d) — every corner of the `{Self, &Self} × {&'static
8887        // str, String}` 2×2 trait-idiomatic projection family — must
8888        // resolve identically on every arm, locking the four
8889        // return-shape × input-shape paths together so any future
8890        // detour trips at caixa-core test time. Also byte-parity
8891        // witness against the sibling [`ToString::to_string`] surface
8892        // routed through [`std::fmt::Display`] and a direct round-trip
8893        // witness through the paired trait-idiomatic reverse
8894        // [`TryFrom<&str>`] axis on the owned-`String`'s
8895        // [`String::as_str`] borrow that closes the two-way
8896        // `&Self → String → Self` round-trip on the trait-idiomatic
8897        // borrowed-input owned-`String` forward + reverse axis pair.
8898        for &variant in RestartStrategy::ALL {
8899            let borrowed_string: String = <String as From<&RestartStrategy>>::from(&variant);
8900            let owned_string: String = <String as From<RestartStrategy>>::from(variant);
8901            let borrowed_static: &'static str =
8902                <&'static str as From<&RestartStrategy>>::from(&variant);
8903            let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8904            assert_eq!(
8905                borrowed_string, owned_string,
8906                "From<&RestartStrategy> for String and From<RestartStrategy> \
8907                 for String must resolve identically on \
8908                 RestartStrategy::{variant:?} — divergence signals the \
8909                 borrowed-input and owned-input owned-`String` \
8910                 forward-projection input-shape paths have drifted onto \
8911                 different emit-sets"
8912            );
8913            assert_eq!(
8914                borrowed_string.as_str(),
8915                borrowed_static,
8916                "From<&RestartStrategy> for String and From<&RestartStrategy> \
8917                 for &'static str must resolve identically on \
8918                 RestartStrategy::{variant:?} — divergence signals the \
8919                 borrowed-input `&'static str` and owned-`String` \
8920                 return-shape paths have drifted onto different emit-sets"
8921            );
8922            assert_eq!(
8923                borrowed_string.as_str(),
8924                owned_static,
8925                "From<&RestartStrategy> for String and From<RestartStrategy> \
8926                 for &'static str must resolve identically on \
8927                 RestartStrategy::{variant:?} — divergence signals a break \
8928                 in the diagonal corner of the {{Self, &Self}} × \
8929                 {{&'static str, String}} 2×2 trait-idiomatic \
8930                 projection family"
8931            );
8932            let via_to_string: String = variant.to_string();
8933            assert_eq!(
8934                borrowed_string, via_to_string,
8935                "From<&RestartStrategy> for String must byte-equal \
8936                 RestartStrategy::to_string on RestartStrategy::{variant:?} — \
8937                 divergence signals the trait-idiomatic borrowed-input \
8938                 owned-`String` forward-projection axis and the \
8939                 ToString-through-Display axis have drifted onto different \
8940                 emit-sets"
8941            );
8942        }
8943        let via_iter: Vec<String> = RestartStrategy::ALL.iter().map(String::from).collect();
8944        let via_method: Vec<String> = RestartStrategy::ALL
8945            .iter()
8946            .map(|s| s.as_str().to_owned())
8947            .collect();
8948        assert_eq!(
8949            via_iter, via_method,
8950            "`.iter().map(String::from)` over RestartStrategy::ALL — a \
8951             call site whose iteration axis holds `&RestartStrategy` by \
8952             construction — must byte-equal `.iter().map(|s| \
8953             s.as_str().to_owned())` on every arm — the borrowed-input \
8954             owned-`String` `From<&RestartStrategy> for String` axis is \
8955             what makes the `String::from` composition route through the \
8956             substrate-primitive `RestartStrategy::as_str` accessor \
8957             without a spurious `Copy` deref (which would only be \
8958             reachable through the owned-input `From<RestartStrategy> for \
8959             String` axis by first calling `.copied()` on the iterator)"
8960        );
8961        for &variant in RestartStrategy::ALL {
8962            let emitted: String = (&variant).into();
8963            let re_parsed: Result<RestartStrategy, ()> =
8964                <RestartStrategy as TryFrom<&str>>::try_from(emitted.as_str());
8965            assert_eq!(
8966                re_parsed,
8967                Ok(variant),
8968                "trait-idiomatic borrowed-input owned-`String` \
8969                 forward-projection + reverse-projection axis pair must \
8970                 round-trip &RestartStrategy::{variant:?} through \
8971                 `.into::<String>()` on the borrowed-input surface and \
8972                 back through `TryFrom<&str>` on the owned-`String`'s \
8973                 String::as_str borrow — a break signals the \
8974                 borrowed-input owned-`String` forward-emit and \
8975                 reverse-parse axes have drifted onto different \
8976                 vocabularies"
8977            );
8978        }
8979    }
8980
8981    #[test]
8982    fn restart_strategy_from_into_static_cow_str_routes_through_as_str_accessor() {
8983        // Fail-before-pass-after byte-parity pin on the newly lifted
8984        // `impl From<RestartStrategy> for std::borrow::Cow<'static, str>` —
8985        // asserts the standard-library trait impl and the substrate-
8986        // primitive [`super::RestartStrategy::as_str`] `pub const fn`
8987        // accessor resolve to the same four-arm emit-set across every
8988        // arm the exhaustive [`super::RestartStrategy::ALL`] slice
8989        // enumerates. Rust's standard library does not carry a blanket
8990        // `impl<T: AsRef<str>> From<T> for Cow<'static, str>` (nor an
8991        // `impl<T: fmt::Display> From<T> for Cow<'static, str>`), so
8992        // the `Cow<'static, str>` forward-projection axis is a
8993        // distinct trait-idiomatic surface that a
8994        // `let key: Cow<'static, str> = strategy.into();`-shaped call
8995        // site reaches through this impl and no other — the paired
8996        // sibling `From<RestartStrategy> for &'static str` and
8997        // `From<RestartStrategy> for String` impls force every
8998        // `Cow<'static, str>`-parameterized call site through a
8999        // `Cow::Borrowed(strategy.as_str())` /
9000        // `Cow::Owned(strategy.to_string())` composition whose type
9001        // bounds have no compile-time link back to the substrate
9002        // primitive.
9003        //
9004        // Also asserts the projection lands on the zero-alloc
9005        // [`std::borrow::Cow::Borrowed`] arm (not the
9006        // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
9007        // [`super::RestartStrategy::as_str`] accessor's `&'static str`
9008        // return lifetime by construction makes the borrowed arm the
9009        // type-correct projection with no runtime allocation. Any
9010        // future silent detour that routes the impl through the owned
9011        // arm (an accidental `Cow::Owned(strategy.to_string())` rewrite
9012        // that would allocate on every call site where the
9013        // `&'static str` return of [`super::RestartStrategy::as_str`]
9014        // makes the zero-alloc borrowed projection type-correct) trips
9015        // at caixa-core test time under the
9016        // [`std::borrow::Cow::Borrowed`] discriminator witness rather
9017        // than at a downstream `Cow<'static, str>`-bound consumer's
9018        // silent allocation.
9019        //
9020        // First peer on the substrate-wide trait-idiomatic
9021        // [`std::borrow::Cow<'static, str>`] forward-projection family
9022        // to extend the axis off the top-level [`super::CaixaKind`]
9023        // enum (99c1735 owned-input, d45c409 borrowed-input) onto the
9024        // first M2 OTP-shape closed-set fieldless typed enum on the
9025        // caixa surface.
9026        for &variant in RestartStrategy::ALL {
9027            let via_trait: std::borrow::Cow<'static, str> =
9028                <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
9029            let via_method: &'static str = variant.as_str();
9030            assert_eq!(
9031                via_trait.as_ref(),
9032                via_method,
9033                "From<RestartStrategy> for Cow<'static, str> impl must \
9034                 round-trip RestartStrategy::{variant:?} to the same \
9035                 lifted SUPERVISOR_ESTRATEGIA_* const \
9036                 RestartStrategy::as_str returns — divergence signals a \
9037                 silent detour off the substrate-primitive accessor"
9038            );
9039            assert!(
9040                matches!(via_trait, std::borrow::Cow::Borrowed(_)),
9041                "From<RestartStrategy> for Cow<'static, str> impl must \
9042                 land on the zero-alloc Cow::Borrowed arm on \
9043                 RestartStrategy::{variant:?} — a Cow::Owned outcome \
9044                 signals the projection has silently allocated where \
9045                 the substrate-primitive RestartStrategy::as_str \
9046                 `&'static str` return makes the borrowed arm the \
9047                 type-correct projection"
9048            );
9049            let via_into: std::borrow::Cow<'static, str> = variant.into();
9050            assert_eq!(
9051                via_into.as_ref(),
9052                via_method,
9053                "Into<Cow<'static, str>>::into on \
9054                 RestartStrategy::{variant:?} must byte-equal \
9055                 RestartStrategy::as_str on the same input — the \
9056                 blanket-derived Into shape must resolve to the same \
9057                 as_str dispatch as the explicit From impl"
9058            );
9059            assert!(
9060                matches!(via_into, std::borrow::Cow::Borrowed(_)),
9061                "Into<Cow<'static, str>>::into on \
9062                 RestartStrategy::{variant:?} must land on the \
9063                 zero-alloc Cow::Borrowed arm — the blanket-derived \
9064                 Into shape must resolve to the same Cow::Borrowed \
9065                 dispatch as the explicit From impl"
9066            );
9067        }
9068    }
9069
9070    #[test]
9071    fn restart_strategy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
9072        // Cross-axis partition pin: the newly lifted trait-idiomatic
9073        // `From<RestartStrategy> for std::borrow::Cow<'static, str>`
9074        // (this lift), the paired owned-input `From<RestartStrategy>
9075        // for &'static str` (523157d), and the paired owned-input
9076        // `From<RestartStrategy> for String` (7baa18a) forward
9077        // projections must resolve identically on every arm, locking
9078        // the three return-shape paths together by construction so any
9079        // future detour trips at caixa-core test time. Also byte-parity
9080        // witness against the sibling [`ToString::to_string`] surface
9081        // routed through [`std::fmt::Display`] — every owned-heap-
9082        // string path (the `Cow::Owned` promotion of this axis's
9083        // `.into_owned()`, `From<RestartStrategy> for String`, and
9084        // `.to_string()`) resolves to the same lifted
9085        // [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const per arm.
9086        //
9087        // Then a `.iter().copied().map(std::borrow::Cow::from)` pipe
9088        // witness over [`super::RestartStrategy::ALL`] that
9089        // materializes the four-arm accept-set through the
9090        // [`std::borrow::Cow<'static, str>`] axis alone — the exact
9091        // shape a future `axum::response::IntoResponse` per-strategy
9092        // rejection-body composer, a future M4 admission-webhook
9093        // per-strategy rejection-reason emitter whose typing rules out
9094        // the sibling [`AsRef<str>`] borrowed return, or a future
9095        // substrate-wide per-strategy diagnostic surface that binds
9096        // through a [`Cow<'static, str>`] boundary reaches through.
9097        // The pipe witness also pins the zero-alloc discipline: every
9098        // element in the collected vector satisfies the
9099        // [`std::borrow::Cow::Borrowed`] arm predicate, so a future
9100        // accidental silent-allocation regression on the pipe's
9101        // iteration axis is a caixa-core-test-time failure.
9102        for &variant in RestartStrategy::ALL {
9103            let via_cow: std::borrow::Cow<'static, str> =
9104                <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
9105            let via_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
9106            let via_string: String = <String as From<RestartStrategy>>::from(variant);
9107            assert_eq!(
9108                via_cow.as_ref(),
9109                via_static,
9110                "From<RestartStrategy> for Cow<'static, str> and \
9111                 From<RestartStrategy> for &'static str must resolve \
9112                 identically on RestartStrategy::{variant:?} — \
9113                 divergence signals the Cow<'static, str> and \
9114                 &'static str return-shape paths have drifted onto \
9115                 different emit-sets"
9116            );
9117            assert_eq!(
9118                via_cow.as_ref(),
9119                via_string.as_str(),
9120                "From<RestartStrategy> for Cow<'static, str> and \
9121                 From<RestartStrategy> for String must resolve \
9122                 identically on RestartStrategy::{variant:?} — \
9123                 divergence signals the Cow<'static, str> and String \
9124                 return-shape paths have drifted onto different \
9125                 emit-sets"
9126            );
9127            let via_to_string: String = variant.to_string();
9128            assert_eq!(
9129                via_cow.as_ref(),
9130                via_to_string.as_str(),
9131                "From<RestartStrategy> for Cow<'static, str> must \
9132                 byte-equal RestartStrategy::to_string on \
9133                 RestartStrategy::{variant:?} — divergence signals the \
9134                 trait-idiomatic Cow<'static, str> forward-projection \
9135                 axis and the ToString-through-Display axis have \
9136                 drifted onto different emit-sets"
9137            );
9138        }
9139        let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
9140            .iter()
9141            .copied()
9142            .map(std::borrow::Cow::from)
9143            .collect();
9144        let via_method: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
9145            .iter()
9146            .map(|s| std::borrow::Cow::Borrowed(s.as_str()))
9147            .collect();
9148        assert_eq!(
9149            via_iter, via_method,
9150            "`.iter().copied().map(Cow::from)` over \
9151             RestartStrategy::ALL must byte-equal `.iter().map(|s| \
9152             Cow::Borrowed(s.as_str()))` on every arm — the \
9153             trait-idiomatic `From<RestartStrategy> for Cow<'static, \
9154             str>` axis is what makes the `Cow::from` composition \
9155             route through the substrate-primitive \
9156             `RestartStrategy::as_str` accessor with the zero-alloc \
9157             Cow::Borrowed arm by construction, rather than a \
9158             per-call-site `Cow::Owned(strategy.to_string())` \
9159             allocation"
9160        );
9161        for cow in &via_iter {
9162            assert!(
9163                matches!(cow, std::borrow::Cow::Borrowed(_)),
9164                "every element of the \
9165                 .iter().copied().map(Cow::from) pipe over \
9166                 RestartStrategy::ALL must land on the zero-alloc \
9167                 Cow::Borrowed arm — a Cow::Owned outcome on any arm \
9168                 signals the pipe's iteration axis has silently \
9169                 allocated where the substrate-primitive \
9170                 RestartStrategy::as_str `&'static str` return makes \
9171                 the borrowed arm the type-correct projection"
9172            );
9173        }
9174    }
9175
9176    #[test]
9177    fn restart_strategy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor() {
9178        // Fail-before-pass-after byte-parity pin on the newly lifted
9179        // `impl From<&RestartStrategy> for std::borrow::Cow<'static, str>` —
9180        // asserts the borrowed-input standard-library trait impl and
9181        // the substrate-primitive [`super::RestartStrategy::as_str`]
9182        // `pub const fn` accessor resolve to the same four-arm emit-
9183        // set across every arm the exhaustive
9184        // [`super::RestartStrategy::ALL`] slice enumerates. Rust's
9185        // standard library does not carry a blanket
9186        // `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor a
9187        // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`), so
9188        // the borrowed-input `Cow<'static, str>` forward-projection
9189        // axis is a distinct trait-idiomatic surface that a
9190        // `let key: Cow<'static, str> = (&strategy).into();`-shaped
9191        // call site or a
9192        // `RestartStrategy::ALL.iter().map(Cow::from)`-shaped pipe
9193        // reaches through this impl and no other — the paired owned-
9194        // input `From<RestartStrategy> for Cow<'static, str>` impl
9195        // (7dd28b3) forces every borrowed-input call site through an
9196        // explicit `Copy` deref (`Cow::from(*strategy)`) or a
9197        // `Cow::Borrowed(strategy.as_str())` open-code whose type
9198        // bounds have no compile-time link back to the substrate
9199        // primitive.
9200        //
9201        // Also asserts the projection lands on the zero-alloc
9202        // [`std::borrow::Cow::Borrowed`] arm (not the
9203        // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
9204        // [`super::RestartStrategy::as_str`] accessor's `&'static str`
9205        // return lifetime by construction makes the borrowed arm the
9206        // type-correct projection with no runtime allocation on the
9207        // borrowed-input surface just as on the paired owned-input
9208        // surface.
9209        //
9210        // Second peer on the substrate-wide trait-idiomatic
9211        // [`std::borrow::Cow<'static, str>`] forward-projection family
9212        // on this enum — closes the `{Self, &Self}` input-shape
9213        // corner of the [`Cow<'static, str>`] axis on the first M2
9214        // OTP-shape closed-set fieldless typed enum peer on the caixa
9215        // surface (`:supervisor :estrategia`), exactly as d45c409
9216        // closed it on the top-level [`super::CaixaKind`] one commit
9217        // after the owning half (99c1735) landed. Every future
9218        // closed-set fieldless typed enum peer on the substrate is a
9219        // future target of the campaign.
9220        for &variant in RestartStrategy::ALL {
9221            let via_trait: std::borrow::Cow<'static, str> =
9222                <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&variant);
9223            let via_method: &'static str = variant.as_str();
9224            assert_eq!(
9225                via_trait.as_ref(),
9226                via_method,
9227                "From<&RestartStrategy> for Cow<'static, str> impl must \
9228                 round-trip &RestartStrategy::{variant:?} to the same \
9229                 lifted SUPERVISOR_ESTRATEGIA_* const \
9230                 RestartStrategy::as_str returns — divergence signals a \
9231                 silent detour off the substrate-primitive accessor"
9232            );
9233            assert!(
9234                matches!(via_trait, std::borrow::Cow::Borrowed(_)),
9235                "From<&RestartStrategy> for Cow<'static, str> impl must \
9236                 land on the zero-alloc Cow::Borrowed arm on \
9237                 &RestartStrategy::{variant:?} — a Cow::Owned outcome \
9238                 signals the projection has silently allocated where \
9239                 the substrate-primitive RestartStrategy::as_str \
9240                 `&'static str` return makes the borrowed arm the \
9241                 type-correct projection"
9242            );
9243            let via_into: std::borrow::Cow<'static, str> = (&variant).into();
9244            assert_eq!(
9245                via_into.as_ref(),
9246                via_method,
9247                "Into<Cow<'static, str>>::into on \
9248                 &RestartStrategy::{variant:?} must byte-equal \
9249                 RestartStrategy::as_str on the same input — the \
9250                 blanket-derived Into shape must resolve to the same \
9251                 as_str dispatch as the explicit From impl"
9252            );
9253            assert!(
9254                matches!(via_into, std::borrow::Cow::Borrowed(_)),
9255                "Into<Cow<'static, str>>::into on \
9256                 &RestartStrategy::{variant:?} must land on the \
9257                 zero-alloc Cow::Borrowed arm — the blanket-derived \
9258                 Into shape must resolve to the same Cow::Borrowed \
9259                 dispatch as the explicit From impl"
9260            );
9261        }
9262    }
9263
9264    #[test]
9265    fn restart_strategy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
9266        // Cross-axis partition pin: the newly lifted trait-idiomatic
9267        // borrowed-input `From<&RestartStrategy> for
9268        // std::borrow::Cow<'static, str>` (this lift), the paired
9269        // owned-input `From<RestartStrategy> for
9270        // std::borrow::Cow<'static, str>` (7dd28b3), the paired
9271        // borrowed-input owned-`&'static str` `From<&RestartStrategy>
9272        // for &'static str`, and the paired borrowed-input owned-
9273        // `String` `From<&RestartStrategy> for String` must resolve
9274        // identically on every arm, locking the four
9275        // return-shape × input-shape paths together by construction so
9276        // any future detour trips at caixa-core test time. Also byte-
9277        // parity witness against the sibling [`ToString::to_string`]
9278        // surface routed through [`std::fmt::Display`] — every owned-
9279        // heap-string path (this axis's `.into_owned()` promotion, the
9280        // paired [`From<&RestartStrategy> for String`], and
9281        // `.to_string()`) resolves to the same lifted
9282        // [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const per arm.
9283        //
9284        // Then a `.iter().map(std::borrow::Cow::from)` pipe witness
9285        // over [`super::RestartStrategy::ALL`] — whose iterator yields
9286        // `&RestartStrategy` by construction, so the borrowed-input
9287        // [`Cow<'static, str>`] axis is what routes the pipe through
9288        // the substrate-primitive [`super::RestartStrategy::as_str`]
9289        // accessor without a spurious [`Copy`] deref (which would only
9290        // be reachable through the owned-input
9291        // [`From<RestartStrategy> for Cow<'static, str>`] axis by
9292        // first calling `.copied()` on the iterator). The pipe witness
9293        // also pins the zero-alloc discipline: every element in the
9294        // collected vector satisfies the [`std::borrow::Cow::Borrowed`]
9295        // arm predicate, so a future accidental silent-allocation
9296        // regression on the pipe's iteration axis is a caixa-core-
9297        // test-time failure.
9298        for &strategy in RestartStrategy::ALL {
9299            let borrowed_cow: std::borrow::Cow<'static, str> =
9300                <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&strategy);
9301            let owned_cow: std::borrow::Cow<'static, str> =
9302                <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(strategy);
9303            let borrowed_static: &'static str =
9304                <&'static str as From<&RestartStrategy>>::from(&strategy);
9305            let borrowed_string: String = <String as From<&RestartStrategy>>::from(&strategy);
9306            assert_eq!(
9307                borrowed_cow, owned_cow,
9308                "From<&RestartStrategy> for Cow<'static, str> and \
9309                 From<RestartStrategy> for Cow<'static, str> must \
9310                 resolve identically on RestartStrategy::{strategy:?} — \
9311                 divergence signals the borrowed-input and owned-input \
9312                 Cow<'static, str> forward-projection input-shape \
9313                 paths have drifted onto different emit-sets"
9314            );
9315            assert_eq!(
9316                borrowed_cow.as_ref(),
9317                borrowed_static,
9318                "From<&RestartStrategy> for Cow<'static, str> and \
9319                 From<&RestartStrategy> for &'static str must resolve \
9320                 identically on RestartStrategy::{strategy:?} — \
9321                 divergence signals the borrowed-input Cow<'static, \
9322                 str> and &'static str return-shape paths have drifted \
9323                 onto different emit-sets"
9324            );
9325            assert_eq!(
9326                borrowed_cow.as_ref(),
9327                borrowed_string.as_str(),
9328                "From<&RestartStrategy> for Cow<'static, str> and \
9329                 From<&RestartStrategy> for String must resolve \
9330                 identically on RestartStrategy::{strategy:?} — \
9331                 divergence signals the borrowed-input Cow<'static, \
9332                 str> and owned-`String` return-shape paths have \
9333                 drifted onto different emit-sets"
9334            );
9335            let via_to_string: String = strategy.to_string();
9336            assert_eq!(
9337                borrowed_cow.as_ref(),
9338                via_to_string.as_str(),
9339                "From<&RestartStrategy> for Cow<'static, str> must \
9340                 byte-equal RestartStrategy::to_string on \
9341                 RestartStrategy::{strategy:?} — divergence signals \
9342                 the trait-idiomatic borrowed-input Cow<'static, str> \
9343                 forward-projection axis and the ToString-through-\
9344                 Display axis have drifted onto different emit-sets"
9345            );
9346        }
9347        let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
9348            .iter()
9349            .map(std::borrow::Cow::from)
9350            .collect();
9351        let via_method: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
9352            .iter()
9353            .map(|s| std::borrow::Cow::Borrowed(s.as_str()))
9354            .collect();
9355        assert_eq!(
9356            via_iter, via_method,
9357            "`.iter().map(Cow::from)` over RestartStrategy::ALL — a \
9358             call site whose iteration axis holds `&RestartStrategy` \
9359             by construction — must byte-equal `.iter().map(|s| \
9360             Cow::Borrowed(s.as_str()))` on every arm — the borrowed-\
9361             input Cow<'static, str> `From<&RestartStrategy> for \
9362             Cow<'static, str>` axis is what makes the `Cow::from` \
9363             composition route through the substrate-primitive \
9364             `RestartStrategy::as_str` accessor with the zero-alloc \
9365             Cow::Borrowed arm by construction and without a spurious \
9366             `Copy` deref (which would only be reachable through the \
9367             owned-input `From<RestartStrategy> for Cow<'static, str>` \
9368             axis by first calling `.copied()` on the iterator)"
9369        );
9370        for cow in &via_iter {
9371            assert!(
9372                matches!(cow, std::borrow::Cow::Borrowed(_)),
9373                "every element of the .iter().map(Cow::from) pipe \
9374                 over RestartStrategy::ALL must land on the zero-\
9375                 alloc Cow::Borrowed arm — a Cow::Owned outcome on \
9376                 any arm signals the pipe's iteration axis has \
9377                 silently allocated where the substrate-primitive \
9378                 RestartStrategy::as_str `&'static str` return makes \
9379                 the borrowed arm the type-correct projection"
9380            );
9381        }
9382    }
9383
9384    #[test]
9385    fn restart_strategy_from_into_box_str_routes_through_as_str_accessor() {
9386        // Fail-before-pass-after byte-parity pin on the newly lifted
9387        // `impl From<RestartStrategy> for Box<str>` — asserts the
9388        // owned-input standard-library trait impl and the
9389        // substrate-primitive [`super::RestartStrategy::as_str`]
9390        // `pub const fn` accessor resolve to the same four-arm emit-
9391        // set across every arm the exhaustive
9392        // [`super::RestartStrategy::ALL`] slice enumerates. Opens the
9393        // substrate-wide `Box<str>` forward-projection campaign tier
9394        // on the first M2 OTP-shape closed-set fieldless typed enum
9395        // peer on the caixa surface (`:supervisor :estrategia`),
9396        // immediately after the paired `Cow<'static, str>` axis
9397        // (7dd28b3 / ee577fd) closed the
9398        // `{Self, &Self} × {&'static str, String, Cow<'static, str>}`
9399        // 2×3 corner on this enum. Rust's standard library carries
9400        // `impl From<&str> for Box<str>` and
9401        // `impl From<String> for Box<str>` but no blanket
9402        // `impl<T: AsRef<str>> From<T> for Box<str>`, so this axis is
9403        // a distinct trait-idiomatic surface that a
9404        // `let key: Box<str> = strategy.into();`-shaped call site
9405        // reaches through this impl and no other — a paired
9406        // `Box::from(strategy.as_str())` open-code has no compile-
9407        // time link back to the substrate primitive.
9408        for &variant in RestartStrategy::ALL {
9409            let via_trait: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
9410            let via_method: &'static str = variant.as_str();
9411            assert_eq!(
9412                via_trait.as_ref(),
9413                via_method,
9414                "From<RestartStrategy> for Box<str> impl must round-\
9415                 trip RestartStrategy::{variant:?} to the same lifted \
9416                 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
9417                 returns — divergence signals a silent detour off the \
9418                 substrate-primitive accessor"
9419            );
9420            let via_into: Box<str> = variant.into();
9421            assert_eq!(
9422                via_into.as_ref(),
9423                via_method,
9424                "Into<Box<str>>::into on RestartStrategy::{variant:?} \
9425                 must byte-equal RestartStrategy::as_str on the same \
9426                 input — the blanket-derived Into shape must resolve \
9427                 to the same as_str dispatch as the explicit From impl"
9428            );
9429        }
9430    }
9431
9432    #[test]
9433    fn restart_strategy_from_borrowed_into_box_str_routes_through_as_str_accessor() {
9434        // Fail-before-pass-after byte-parity pin on the newly lifted
9435        // `impl From<&RestartStrategy> for Box<str>` — asserts the
9436        // borrowed-input standard-library trait impl and the
9437        // substrate-primitive [`super::RestartStrategy::as_str`]
9438        // `pub const fn` accessor resolve to the same four-arm emit-
9439        // set across every arm the exhaustive
9440        // [`super::RestartStrategy::ALL`] slice enumerates. Rust's
9441        // standard library does not carry a blanket
9442        // `impl<T: AsRef<str>> From<&T> for Box<str>` (nor a
9443        // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`),
9444        // so the borrowed-input `Box<str>` forward-projection axis
9445        // is a distinct trait-idiomatic surface that a
9446        // `let key: Box<str> = (&strategy).into();`-shaped call site
9447        // or a `RestartStrategy::ALL.iter().map(Box::<str>::from)`-
9448        // shaped pipe reaches through this impl and no other — the
9449        // paired owned-input `From<RestartStrategy> for Box<str>`
9450        // impl (69ef45c) forces every borrowed-input call site
9451        // through an explicit `Copy` deref
9452        // (`Box::<str>::from((*strategy).as_str())`) or a
9453        // `Box::<str>::from(strategy.as_str())` open-code whose
9454        // type bounds have no compile-time link back to the
9455        // substrate primitive.
9456        //
9457        // Second peer on the substrate-wide trait-idiomatic
9458        // [`Box<str>`] forward-projection family on this enum —
9459        // closes the `{Self, &Self}` input-shape corner of the
9460        // [`Box<str>`] axis on the first M2 OTP-shape closed-set
9461        // fieldless typed enum peer on the caixa surface
9462        // (`:supervisor :estrategia`), exactly as ee577fd closed
9463        // the paired [`Cow<'static, str>`] axis one commit after
9464        // its owning half (7dd28b3) landed. Every future closed-
9465        // set fieldless typed enum peer on the substrate is a
9466        // future target of the campaign.
9467        //
9468        // Also byte-parity witness against the paired owned-input
9469        // [`From<RestartStrategy> for Box<str>`] and the sibling
9470        // borrowed-input [`From<&RestartStrategy> for &'static str`],
9471        // [`From<&RestartStrategy> for String`], and
9472        // [`From<&RestartStrategy> for Cow<'static, str>`]
9473        // return-shape axes — locking the four
9474        // return-shape × input-shape paths together by construction
9475        // so any future detour trips at caixa-core test time. Then a
9476        // `.iter().map(Box::<str>::from)` pipe witness over
9477        // [`super::RestartStrategy::ALL`] — whose iterator yields
9478        // `&RestartStrategy` by construction, so the borrowed-input
9479        // [`Box<str>`] axis is what routes the pipe through the
9480        // substrate-primitive [`super::RestartStrategy::as_str`]
9481        // accessor without a spurious [`Copy`] deref (which would
9482        // only be reachable through the owned-input
9483        // [`From<RestartStrategy> for Box<str>`] axis by first
9484        // calling `.copied()` on the iterator).
9485        for &variant in RestartStrategy::ALL {
9486            let via_trait: Box<str> = <Box<str> as From<&RestartStrategy>>::from(&variant);
9487            let via_method: &'static str = variant.as_str();
9488            assert_eq!(
9489                via_trait.as_ref(),
9490                via_method,
9491                "From<&RestartStrategy> for Box<str> impl must \
9492                 round-trip &RestartStrategy::{variant:?} to the same \
9493                 lifted SUPERVISOR_ESTRATEGIA_* const \
9494                 RestartStrategy::as_str returns — divergence signals \
9495                 a silent detour off the substrate-primitive accessor"
9496            );
9497            let via_into: Box<str> = (&variant).into();
9498            assert_eq!(
9499                via_into.as_ref(),
9500                via_method,
9501                "Into<Box<str>>::into on &RestartStrategy::{variant:?} \
9502                 must byte-equal RestartStrategy::as_str on the same \
9503                 input — the blanket-derived Into shape must resolve \
9504                 to the same as_str dispatch as the explicit From impl"
9505            );
9506            let owned_box: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
9507            assert_eq!(
9508                via_trait, owned_box,
9509                "From<&RestartStrategy> for Box<str> and \
9510                 From<RestartStrategy> for Box<str> must resolve \
9511                 identically on RestartStrategy::{variant:?} — \
9512                 divergence signals the borrowed-input and owned-input \
9513                 Box<str> forward-projection input-shape paths have \
9514                 drifted onto different emit-sets"
9515            );
9516            let borrowed_static: &'static str =
9517                <&'static str as From<&RestartStrategy>>::from(&variant);
9518            assert_eq!(
9519                via_trait.as_ref(),
9520                borrowed_static,
9521                "From<&RestartStrategy> for Box<str> and \
9522                 From<&RestartStrategy> for &'static str must resolve \
9523                 identically on RestartStrategy::{variant:?} — \
9524                 divergence signals the borrowed-input Box<str> and \
9525                 &'static str return-shape paths have drifted onto \
9526                 different emit-sets"
9527            );
9528            let borrowed_string: String = <String as From<&RestartStrategy>>::from(&variant);
9529            assert_eq!(
9530                via_trait.as_ref(),
9531                borrowed_string.as_str(),
9532                "From<&RestartStrategy> for Box<str> and \
9533                 From<&RestartStrategy> for String must resolve \
9534                 identically on RestartStrategy::{variant:?} — \
9535                 divergence signals the borrowed-input Box<str> and \
9536                 owned-`String` return-shape paths have drifted onto \
9537                 different emit-sets"
9538            );
9539            let borrowed_cow: std::borrow::Cow<'static, str> =
9540                <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&variant);
9541            assert_eq!(
9542                via_trait.as_ref(),
9543                borrowed_cow.as_ref(),
9544                "From<&RestartStrategy> for Box<str> and \
9545                 From<&RestartStrategy> for Cow<'static, str> must \
9546                 resolve identically on RestartStrategy::{variant:?} — \
9547                 divergence signals the borrowed-input Box<str> and \
9548                 Cow<'static, str> return-shape paths have drifted \
9549                 onto different emit-sets"
9550            );
9551        }
9552        let via_iter: Vec<Box<str>> = RestartStrategy::ALL.iter().map(Box::<str>::from).collect();
9553        let via_method: Vec<Box<str>> = RestartStrategy::ALL
9554            .iter()
9555            .map(|s| Box::<str>::from(s.as_str()))
9556            .collect();
9557        assert_eq!(
9558            via_iter, via_method,
9559            "`.iter().map(Box::<str>::from)` over \
9560             RestartStrategy::ALL — a call site whose iteration axis \
9561             holds `&RestartStrategy` by construction — must byte-\
9562             equal `.iter().map(|s| Box::<str>::from(s.as_str()))` \
9563             on every arm — the borrowed-input Box<str> \
9564             `From<&RestartStrategy> for Box<str>` axis is what \
9565             makes the `Box::<str>::from` composition route through \
9566             the substrate-primitive `RestartStrategy::as_str` \
9567             accessor without a spurious `Copy` deref (which would \
9568             only be reachable through the owned-input \
9569             `From<RestartStrategy> for Box<str>` axis by first \
9570             calling `.copied()` on the iterator)"
9571        );
9572    }
9573
9574    #[test]
9575    fn restart_strategy_from_into_arc_str_routes_through_as_str_accessor() {
9576        // Fail-before-pass-after byte-parity pin on the newly lifted
9577        // `impl From<RestartStrategy> for std::sync::Arc<str>` — asserts
9578        // the owned-input standard-library trait impl and the
9579        // substrate-primitive [`super::RestartStrategy::as_str`]
9580        // `pub const fn` accessor resolve to the same four-arm emit-
9581        // set across every arm the exhaustive
9582        // [`super::RestartStrategy::ALL`] slice enumerates. Opens the
9583        // substrate-wide [`std::sync::Arc<str>`] forward-projection
9584        // campaign tier on the first M2 OTP-shape closed-set fieldless
9585        // typed enum peer on the caixa surface
9586        // (`:supervisor :estrategia`), immediately after the paired
9587        // [`Box<str>`] axis (69ef45c / 59ae5dc) closed the
9588        // `{Self, &Self} × {&'static str, String, Cow<'static, str>,
9589        // Box<str>}` 2×4 corner on this enum. Rust's standard library
9590        // carries `impl From<&str> for std::sync::Arc<str>` and
9591        // `impl From<String> for std::sync::Arc<str>` but no blanket
9592        // `impl<T: AsRef<str>> From<T> for std::sync::Arc<str>` (nor
9593        // an `impl<T: fmt::Display> From<T> for std::sync::Arc<str>`),
9594        // so this axis is a distinct trait-idiomatic surface that a
9595        // `let key: std::sync::Arc<str> = strategy.into();`-shaped call
9596        // site reaches through this impl and no other — a paired
9597        // `std::sync::Arc::<str>::from(strategy.as_str())` open-code
9598        // has no compile-time link back to the substrate primitive,
9599        // and a two-step `std::sync::Arc::<str>::from(String::from(
9600        // strategy))` composition through the owned-`String` axis
9601        // allocates twice (once into the intermediate `String`, once
9602        // into the [`Arc<str>`] on the `From<String>` conversion)
9603        // where the single-step trait impl allocates once.
9604        //
9605        // Cross-axis byte-parity witness against the sibling owned-
9606        // input `{&'static str, String, Cow<'static, str>, Box<str>}`
9607        // return-shape axes — locking the five return-shape paths on
9608        // the owned-input surface together by construction so any
9609        // future detour off the substrate-primitive
9610        // [`super::RestartStrategy::as_str`] accessor trips at caixa-
9611        // core test time.
9612        for &variant in RestartStrategy::ALL {
9613            let via_trait: std::sync::Arc<str> =
9614                <std::sync::Arc<str> as From<RestartStrategy>>::from(variant);
9615            let via_method: &'static str = variant.as_str();
9616            assert_eq!(
9617                via_trait.as_ref(),
9618                via_method,
9619                "From<RestartStrategy> for std::sync::Arc<str> impl \
9620                 must round-trip RestartStrategy::{variant:?} to the \
9621                 same lifted SUPERVISOR_ESTRATEGIA_* const \
9622                 RestartStrategy::as_str returns — divergence signals \
9623                 a silent detour off the substrate-primitive accessor"
9624            );
9625            let via_into: std::sync::Arc<str> = variant.into();
9626            assert_eq!(
9627                via_into.as_ref(),
9628                via_method,
9629                "Into<std::sync::Arc<str>>::into on \
9630                 RestartStrategy::{variant:?} must byte-equal \
9631                 RestartStrategy::as_str on the same input — the \
9632                 blanket-derived Into shape must resolve to the same \
9633                 as_str dispatch as the explicit From impl"
9634            );
9635            let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
9636            assert_eq!(
9637                via_trait.as_ref(),
9638                owned_static,
9639                "From<RestartStrategy> for std::sync::Arc<str> and \
9640                 From<RestartStrategy> for &'static str must resolve \
9641                 identically on RestartStrategy::{variant:?} — \
9642                 divergence signals the owned-input std::sync::Arc<str> \
9643                 and &'static str return-shape paths have drifted onto \
9644                 different emit-sets"
9645            );
9646            let owned_string: String = <String as From<RestartStrategy>>::from(variant);
9647            assert_eq!(
9648                via_trait.as_ref(),
9649                owned_string.as_str(),
9650                "From<RestartStrategy> for std::sync::Arc<str> and \
9651                 From<RestartStrategy> for String must resolve \
9652                 identically on RestartStrategy::{variant:?} — \
9653                 divergence signals the owned-input std::sync::Arc<str> \
9654                 and owned-`String` return-shape paths have drifted \
9655                 onto different emit-sets"
9656            );
9657            let owned_cow: std::borrow::Cow<'static, str> =
9658                <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
9659            assert_eq!(
9660                via_trait.as_ref(),
9661                owned_cow.as_ref(),
9662                "From<RestartStrategy> for std::sync::Arc<str> and \
9663                 From<RestartStrategy> for Cow<'static, str> must \
9664                 resolve identically on RestartStrategy::{variant:?} — \
9665                 divergence signals the owned-input std::sync::Arc<str> \
9666                 and Cow<'static, str> return-shape paths have drifted \
9667                 onto different emit-sets"
9668            );
9669            let owned_box: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
9670            assert_eq!(
9671                via_trait.as_ref(),
9672                owned_box.as_ref(),
9673                "From<RestartStrategy> for std::sync::Arc<str> and \
9674                 From<RestartStrategy> for Box<str> must resolve \
9675                 identically on RestartStrategy::{variant:?} — \
9676                 divergence signals the owned-input std::sync::Arc<str> \
9677                 and Box<str> return-shape paths have drifted onto \
9678                 different emit-sets"
9679            );
9680        }
9681    }
9682
9683    #[test]
9684    fn restart_strategy_from_borrowed_into_arc_str_routes_through_as_str_accessor() {
9685        // Fail-before-pass-after byte-parity pin on the newly lifted
9686        // `impl From<&RestartStrategy> for std::sync::Arc<str>` —
9687        // asserts the borrowed-input standard-library trait impl and
9688        // the substrate-primitive [`super::RestartStrategy::as_str`]
9689        // `pub const fn` accessor resolve to the same four-arm emit-
9690        // set across every arm the exhaustive
9691        // [`super::RestartStrategy::ALL`] slice enumerates. Rust's
9692        // standard library does not carry a blanket
9693        // `impl<T: AsRef<str>> From<&T> for std::sync::Arc<str>` (nor
9694        // a `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`),
9695        // so the borrowed-input [`std::sync::Arc<str>`] forward-
9696        // projection axis is a distinct trait-idiomatic surface that a
9697        // `let key: std::sync::Arc<str> = (&strategy).into();`-shaped
9698        // call site or a
9699        // `RestartStrategy::ALL.iter().map(std::sync::Arc::<str>::from)`-
9700        // shaped pipe reaches through this impl and no other — the
9701        // paired owned-input
9702        // `From<RestartStrategy> for std::sync::Arc<str>` impl
9703        // (bca2ec8) forces every borrowed-input call site through an
9704        // explicit `Copy` deref
9705        // (`std::sync::Arc::<str>::from((*strategy).as_str())`) or a
9706        // `std::sync::Arc::<str>::from(strategy.as_str())` open-code
9707        // whose type bounds have no compile-time link back to the
9708        // substrate primitive.
9709        //
9710        // Second peer on the substrate-wide trait-idiomatic
9711        // [`std::sync::Arc<str>`] forward-projection family on this
9712        // enum — closes the `{Self, &Self}` input-shape corner of
9713        // the [`std::sync::Arc<str>`] axis on the first M2 OTP-shape
9714        // closed-set fieldless typed enum peer on the caixa surface
9715        // (`:supervisor :estrategia`), exactly as 59ae5dc closed the
9716        // paired [`Box<str>`] axis one commit after its owning half
9717        // (69ef45c) landed. Every future closed-set fieldless typed
9718        // enum peer on the substrate is a future target of the
9719        // campaign.
9720        //
9721        // Also byte-parity witness against the paired owned-input
9722        // [`From<RestartStrategy> for std::sync::Arc<str>`] and the
9723        // sibling borrowed-input
9724        // [`From<&RestartStrategy> for &'static str`],
9725        // [`From<&RestartStrategy> for String`],
9726        // [`From<&RestartStrategy> for Cow<'static, str>`], and
9727        // [`From<&RestartStrategy> for Box<str>`] return-shape axes —
9728        // locking the five return-shape × input-shape paths together
9729        // by construction so any future detour trips at caixa-core
9730        // test time. Then a
9731        // `.iter().map(std::sync::Arc::<str>::from)` pipe witness over
9732        // [`super::RestartStrategy::ALL`] — whose iterator yields
9733        // `&RestartStrategy` by construction, so the borrowed-input
9734        // [`std::sync::Arc<str>`] axis is what routes the pipe
9735        // through the substrate-primitive
9736        // [`super::RestartStrategy::as_str`] accessor without a
9737        // spurious [`Copy`] deref (which would only be reachable
9738        // through the owned-input
9739        // [`From<RestartStrategy> for std::sync::Arc<str>`] axis by
9740        // first calling `.copied()` on the iterator).
9741        for &variant in RestartStrategy::ALL {
9742            let via_trait: std::sync::Arc<str> =
9743                <std::sync::Arc<str> as From<&RestartStrategy>>::from(&variant);
9744            let via_method: &'static str = variant.as_str();
9745            assert_eq!(
9746                via_trait.as_ref(),
9747                via_method,
9748                "From<&RestartStrategy> for std::sync::Arc<str> impl \
9749                 must round-trip &RestartStrategy::{variant:?} to the \
9750                 same lifted SUPERVISOR_ESTRATEGIA_* const \
9751                 RestartStrategy::as_str returns — divergence signals \
9752                 a silent detour off the substrate-primitive accessor"
9753            );
9754            let via_into: std::sync::Arc<str> = (&variant).into();
9755            assert_eq!(
9756                via_into.as_ref(),
9757                via_method,
9758                "Into<std::sync::Arc<str>>::into on \
9759                 &RestartStrategy::{variant:?} must byte-equal \
9760                 RestartStrategy::as_str on the same input — the \
9761                 blanket-derived Into shape must resolve to the same \
9762                 as_str dispatch as the explicit From impl"
9763            );
9764            let owned_arc: std::sync::Arc<str> =
9765                <std::sync::Arc<str> as From<RestartStrategy>>::from(variant);
9766            assert_eq!(
9767                via_trait, owned_arc,
9768                "From<&RestartStrategy> for std::sync::Arc<str> and \
9769                 From<RestartStrategy> for std::sync::Arc<str> must \
9770                 resolve identically on RestartStrategy::{variant:?} — \
9771                 divergence signals the borrowed-input and owned-input \
9772                 std::sync::Arc<str> forward-projection input-shape \
9773                 paths have drifted onto different emit-sets"
9774            );
9775            let borrowed_static: &'static str =
9776                <&'static str as From<&RestartStrategy>>::from(&variant);
9777            assert_eq!(
9778                via_trait.as_ref(),
9779                borrowed_static,
9780                "From<&RestartStrategy> for std::sync::Arc<str> and \
9781                 From<&RestartStrategy> for &'static str must resolve \
9782                 identically on RestartStrategy::{variant:?} — \
9783                 divergence signals the borrowed-input \
9784                 std::sync::Arc<str> and &'static str return-shape \
9785                 paths have drifted onto different emit-sets"
9786            );
9787            let borrowed_string: String = <String as From<&RestartStrategy>>::from(&variant);
9788            assert_eq!(
9789                via_trait.as_ref(),
9790                borrowed_string.as_str(),
9791                "From<&RestartStrategy> for std::sync::Arc<str> and \
9792                 From<&RestartStrategy> for String must resolve \
9793                 identically on RestartStrategy::{variant:?} — \
9794                 divergence signals the borrowed-input \
9795                 std::sync::Arc<str> and owned-`String` return-shape \
9796                 paths have drifted onto different emit-sets"
9797            );
9798            let borrowed_cow: std::borrow::Cow<'static, str> =
9799                <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&variant);
9800            assert_eq!(
9801                via_trait.as_ref(),
9802                borrowed_cow.as_ref(),
9803                "From<&RestartStrategy> for std::sync::Arc<str> and \
9804                 From<&RestartStrategy> for Cow<'static, str> must \
9805                 resolve identically on RestartStrategy::{variant:?} — \
9806                 divergence signals the borrowed-input \
9807                 std::sync::Arc<str> and Cow<'static, str> return-shape \
9808                 paths have drifted onto different emit-sets"
9809            );
9810            let borrowed_box: Box<str> = <Box<str> as From<&RestartStrategy>>::from(&variant);
9811            assert_eq!(
9812                via_trait.as_ref(),
9813                borrowed_box.as_ref(),
9814                "From<&RestartStrategy> for std::sync::Arc<str> and \
9815                 From<&RestartStrategy> for Box<str> must resolve \
9816                 identically on RestartStrategy::{variant:?} — \
9817                 divergence signals the borrowed-input \
9818                 std::sync::Arc<str> and Box<str> return-shape paths \
9819                 have drifted onto different emit-sets"
9820            );
9821        }
9822        let via_iter: Vec<std::sync::Arc<str>> = RestartStrategy::ALL
9823            .iter()
9824            .map(std::sync::Arc::<str>::from)
9825            .collect();
9826        let via_method: Vec<std::sync::Arc<str>> = RestartStrategy::ALL
9827            .iter()
9828            .map(|s| std::sync::Arc::<str>::from(s.as_str()))
9829            .collect();
9830        assert_eq!(
9831            via_iter, via_method,
9832            "`.iter().map(std::sync::Arc::<str>::from)` over \
9833             RestartStrategy::ALL — a call site whose iteration axis \
9834             holds `&RestartStrategy` by construction — must byte-\
9835             equal `.iter().map(|s| std::sync::Arc::<str>::from(s.as_str()))` \
9836             on every arm — the borrowed-input std::sync::Arc<str> \
9837             `From<&RestartStrategy> for std::sync::Arc<str>` axis is \
9838             what makes the `std::sync::Arc::<str>::from` composition \
9839             route through the substrate-primitive \
9840             `RestartStrategy::as_str` accessor without a spurious \
9841             `Copy` deref (which would only be reachable through the \
9842             owned-input `From<RestartStrategy> for std::sync::Arc<str>` \
9843             axis by first calling `.copied()` on the iterator)"
9844        );
9845    }
9846
9847    #[test]
9848    fn restart_policy_try_from_str_routes_through_from_wire_accessor() {
9849        // Fail-before-pass-after byte-parity pin on the newly lifted
9850        // `impl TryFrom<&str> for RestartPolicy` — asserts the standard-
9851        // library trait impl and the substrate-primitive
9852        // [`RestartPolicy::from_wire`] `Option<Self>` accessor resolve to
9853        // the same three-arm accept-set across every arm the exhaustive
9854        // [`RestartPolicy::ALL`] slice enumerates. Any future silent
9855        // detour that routes the trait impl through a divergent
9856        // projection (a per-arm inline `match s { "Permanent" =>
9857        // Ok(Self::Permanent), … }` re-inlining that opens a compile-time
9858        // link to the un-lifted arm-literal, a hypothetical
9859        // `#[serde(rename_all = "…")]` attribute drift that silently
9860        // splits the wire byte-string from every consumer that reaches
9861        // for this typed dispatch, an accidental swap onto the kebab-case
9862        // dispatcher-catalog axis the pre-existing [`std::str::FromStr`]
9863        // impl parses through and which would collide the two-axis
9864        // wire/catalog split the sibling [`RestartPolicy::from_wire`]
9865        // doc block makes load-bearing) trips at caixa-core test time
9866        // under `assert_eq!` rather than at a downstream
9867        // `impl TryFrom<&str>`-bound consumer's silent split. Sweeps
9868        // every one of the three arms [`RestartPolicy::ALL`] carries so
9869        // no arm's projection is covered only by the sibling method-
9870        // named `from_wire` path. Peer of the sibling
9871        // [`restart_strategy_try_from_str_routes_through_from_wire_accessor`]
9872        // (5b828ed) — extends the trait-idiomatic reverse-projection
9873        // axis onto the third and final M2-OTP-shape closed-set typed
9874        // enum on the caixa surface (the paired per-child restart-
9875        // decision-policy sibling on the same M2 `:supervisor` slot).
9876        for &variant in RestartPolicy::ALL {
9877            let wire = variant.as_str();
9878            assert_eq!(
9879                <RestartPolicy as TryFrom<&str>>::try_from(wire),
9880                Ok(variant),
9881                "TryFrom<&str> impl on RestartPolicy must round-trip \
9882                 RestartPolicy::{variant:?}.as_str() = {wire:?} back to \
9883                 Ok(RestartPolicy::{variant:?}) — divergence from \
9884                 RestartPolicy::from_wire signals a silent detour off \
9885                 the substrate-primitive accessor"
9886            );
9887            assert_eq!(
9888                <RestartPolicy as TryFrom<&str>>::try_from(wire).ok(),
9889                RestartPolicy::from_wire(wire),
9890                "TryFrom<&str> ok()-projection on {wire:?} must byte-\
9891                 equal RestartPolicy::from_wire on the same input"
9892            );
9893        }
9894    }
9895
9896    #[test]
9897    fn restart_policy_try_from_str_rejects_unknown_byte_strings() {
9898        // Rejection witness on the `impl TryFrom<&str> for
9899        // RestartPolicy` — sweeps a candidate set of byte-strings
9900        // outside the three-arm PascalCase wire accept-set the sibling
9901        // [`RestartPolicy::as_str`] emits and asserts every one lands on
9902        // `Err(())`, so a future accidental widening of the trait impl's
9903        // accept-set (a stray additional
9904        // `_ if s.eq_ignore_ascii_case("Permanent") => Ok(…)` case-fold
9905        // path, a silent inclusion of the kebab-case dispatcher-catalog
9906        // byte-string the pre-existing [`std::str::FromStr`] impl the
9907        // [`gen_platform::FromStrKind`] derive installs parses onto the
9908        // wire axis — which would collide the two-axis
9909        // wire/dispatcher-catalog split the sibling
9910        // [`RestartPolicy::from_wire`] doc block makes load-bearing —
9911        // an English-rebrand or plural-arm silent alias that would widen
9912        // the wire accept-set past the OTP-canonical three) trips at
9913        // caixa-core test time. The candidate set includes the empty
9914        // string, whitespace-only padding, the kebab-case dispatcher-
9915        // catalog byte-strings on the sibling axis (a caller who
9916        // confuses the two axes trips here rather than at a downstream
9917        // consumer's silent reject), a lowercase / uppercase / mixed-case
9918        // fold of each PascalCase arm (a caller who assumes case-fold
9919        // acceptance trips here), leading/trailing whitespace padding,
9920        // the trailing-newline shape, quote-wrapped candidates, and a
9921        // residual set of plausible-but-wrong English rebrand
9922        // candidates. Peer of the sibling
9923        // [`restart_strategy_try_from_str_rejects_unknown_byte_strings`]
9924        // (5b828ed) rejection witness.
9925        let rejected: &[&str] = &[
9926            "",
9927            " ",
9928            "\n",
9929            "\t",
9930            "permanent",
9931            "temporary",
9932            "transient",
9933            "PERMANENT",
9934            "TEMPORARY",
9935            "TRANSIENT",
9936            "Permanents",
9937            "Permanent ",
9938            " Permanent",
9939            " Temporary ",
9940            "Permanent\n",
9941            "Transient\t",
9942            "\"Permanent\"",
9943            "Ephemeral",
9944            "Always",
9945            "Never",
9946            "OnAbnormalExit",
9947            "intrinsic",
9948            "?",
9949        ];
9950        for &input in rejected {
9951            assert_eq!(
9952                <RestartPolicy as TryFrom<&str>>::try_from(input),
9953                Err(()),
9954                "TryFrom<&str> impl on RestartPolicy must reject the \
9955                 non-wire byte-string {input:?} — silent acceptance \
9956                 signals an accept-set widening off the paired \
9957                 RestartPolicy::from_wire resolver"
9958            );
9959        }
9960    }
9961
9962    #[test]
9963    fn restart_policy_try_from_str_and_from_wire_partition_the_accept_set() {
9964        // Cross-axis partition pin: the paired `TryFrom<&str>` and
9965        // `from_wire` reverse projections must resolve identically on
9966        // *every* input, not just the ones [`RestartPolicy::ALL`]
9967        // enumerates. Sweeps a mixed candidate set spanning accepted
9968        // (three-arm PascalCase wire byte-strings) and rejected (kebab-
9969        // case dispatcher-catalog byte-strings, empty, whitespace-
9970        // padded, quoted, English-rebrand candidates) inputs and asserts
9971        // the trait's `Result::ok()` projection byte-equals the method-
9972        // named resolver's `Option<Self>` return-shape on each, locking
9973        // the two paths together by construction so any future detour
9974        // (a stray `try_from` special-case that widens or narrows the
9975        // accept-set outside the paired `from_wire` resolver, an
9976        // accidental swap onto the kebab-case [`std::str::FromStr`]
9977        // impl the [`gen_platform::FromStrKind`] derive installs on the
9978        // sibling dispatcher-catalog axis) trips at caixa-core test
9979        // time. Peer of the sibling
9980        // [`restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
9981        // pin — extends the round-trip discipline onto the M2-OTP-shape
9982        // per-child restart-policy axis.
9983        let candidates: &[&str] = &[
9984            "Permanent",
9985            "Temporary",
9986            "Transient",
9987            "",
9988            "permanent",
9989            "temporary",
9990            "transient",
9991            "PERMANENT",
9992            "unknown",
9993            "Permanent ",
9994            " Permanent",
9995            "\"Permanent\"",
9996            "Ephemeral",
9997            "OnAbnormalExit",
9998            "?",
9999        ];
10000        for &input in candidates {
10001            let via_trait: Option<RestartPolicy> =
10002                <RestartPolicy as TryFrom<&str>>::try_from(input).ok();
10003            let via_method: Option<RestartPolicy> = RestartPolicy::from_wire(input);
10004            assert_eq!(
10005                via_trait, via_method,
10006                "TryFrom<&str> and from_wire must resolve identically on \
10007                 input {input:?} — divergence signals the two reverse-\
10008                 projection paths have drifted onto different accept-sets"
10009            );
10010        }
10011    }
10012
10013    #[test]
10014    fn restart_policy_from_into_static_str_routes_through_as_str_accessor() {
10015        // Fail-before-pass-after byte-parity pin on the newly lifted
10016        // `impl From<RestartPolicy> for &'static str` — asserts the
10017        // standard-library trait impl and the substrate-primitive
10018        // [`RestartPolicy::as_str`] `pub const fn` accessor resolve to
10019        // the same three-arm emit-set across every arm the exhaustive
10020        // [`RestartPolicy::ALL`] slice enumerates. Any future silent
10021        // detour that routes the trait impl through a divergent
10022        // projection (a per-arm inline `match policy { Permanent =>
10023        // "Permanent", … }` re-inlining that opens a compile-time link
10024        // to the un-lifted arm-literal, an accidental swap onto the
10025        // sibling kebab-case [`Self::discriminant`] dispatcher-catalog
10026        // axis that would collide the two-axis wire/catalog split the
10027        // sibling [`RestartPolicy::from_wire`] doc block makes
10028        // load-bearing) trips at caixa-core test time under
10029        // `assert_eq!` rather than at a downstream
10030        // `impl Into<&'static str>`-bound consumer's silent split.
10031        // Sweeps every one of the three arms [`RestartPolicy::ALL`]
10032        // carries so no arm's projection is covered only by the sibling
10033        // method-named `as_str` / [`std::fmt::Display`] / [`AsRef<str>`]
10034        // paths. Materializes the `<&'static str as
10035        // From<RestartPolicy>>::from` output in a `const`-shape binding
10036        // to make the `'static` lifetime promise a build-time invariant
10037        // — a future accidental downgrade of any of the three arms'
10038        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] constants to a
10039        // non-`&'static str` (a `String::leak()`-produced return, a
10040        // `Box::leak`-cast) trips at caixa-core build time rather than
10041        // at a downstream `'static`-bound consumer. Peer of the sibling
10042        // [`restart_strategy_from_into_static_str_routes_through_as_str_accessor`]
10043        // (523157d) — extends the trait-idiomatic forward-projection
10044        // axis onto the second (and second-of-two-in-M2) closed-set
10045        // typed enum on the caixa surface (the paired per-child
10046        // restart-decision-policy sibling on the same M2 `:supervisor`
10047        // slot).
10048        const PERMANENT: &str = RestartPolicy::Permanent.as_str();
10049        const TEMPORARY: &str = RestartPolicy::Temporary.as_str();
10050        const TRANSIENT: &str = RestartPolicy::Transient.as_str();
10051        for &variant in RestartPolicy::ALL {
10052            let via_trait: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
10053            let via_method: &'static str = variant.as_str();
10054            assert_eq!(
10055                via_trait, via_method,
10056                "From<RestartPolicy> for &'static str impl must round-trip \
10057                 RestartPolicy::{variant:?} to the same lifted \
10058                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str returns — \
10059                 divergence signals a silent detour off the substrate-primitive \
10060                 accessor"
10061            );
10062            let via_into: &'static str = variant.into();
10063            assert_eq!(
10064                via_into, via_method,
10065                "Into<&'static str>::into on RestartPolicy::{variant:?} must \
10066                 byte-equal RestartPolicy::as_str on the same input — the \
10067                 blanket-derived Into shape must resolve to the same as_str \
10068                 dispatch as the explicit From impl"
10069            );
10070        }
10071        assert_eq!(
10072            [PERMANENT, TEMPORARY, TRANSIENT],
10073            [
10074                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
10075                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
10076                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
10077            ],
10078            "const-context RestartPolicy::as_str must resolve to the three \
10079             lifted SUPERVISOR_CHILD_RESTART_* consts — a future accidental \
10080             downgrade of any arm to a non-const or non-static byte-string \
10081             breaks the `&'static str`-lifetime promise the paired \
10082             From<RestartPolicy> for &'static str impl carries by \
10083             construction"
10084        );
10085    }
10086
10087    #[test]
10088    fn restart_policy_from_into_static_str_and_as_str_partition_the_emit_set() {
10089        // Cross-axis partition pin: the paired trait-idiomatic
10090        // `From<RestartPolicy> for &'static str` forward projection and
10091        // the method-named [`RestartPolicy::as_str`] forward projection
10092        // must resolve identically on *every* arm, not just the ones
10093        // named in the primary byte-parity pin above. Sweeps every
10094        // [`RestartPolicy::ALL`] arm and asserts the trait's `From::from`
10095        // output byte-equals the method-named accessor's return-value on
10096        // each, locking the two forward-projection paths together by
10097        // construction so any future detour (a stray `From` special-case
10098        // that lands on a divergent per-arm literal outside the paired
10099        // `as_str` dispatch, a hypothetical rebrand touching one axis
10100        // without the other) trips at caixa-core test time. Peer of the
10101        // sibling forward-projection partition pin
10102        // [`restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
10103        // (523157d) — extends the round-trip discipline onto the
10104        // second-of-two M2-OTP-shape closed-set typed enum on the caixa
10105        // surface, closing the two-way `Self ↔ &'static str` round-trip
10106        // on the trait-idiomatic pair (`From<Self> for &'static str` +
10107        // `TryFrom<&str> for Self`) as well as the pre-existing method-
10108        // named pair (`as_str` + `from_wire`).
10109        for &variant in RestartPolicy::ALL {
10110            let via_trait: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
10111            let via_method: &'static str = variant.as_str();
10112            assert_eq!(
10113                via_trait, via_method,
10114                "From<RestartPolicy> for &'static str and \
10115                 RestartPolicy::as_str must resolve identically on \
10116                 RestartPolicy::{variant:?} — divergence signals the \
10117                 two forward-projection paths have drifted onto different \
10118                 emit-sets"
10119            );
10120        }
10121        // Round-trip witness: every arm's forward `From` output re-parses
10122        // through the paired trait-idiomatic reverse `TryFrom<&str>` back
10123        // to the original variant. Closes the two-way `RestartPolicy ↔
10124        // &'static str` round-trip on the trait-idiomatic axis pair,
10125        // mirroring the pre-existing method-named `as_str` + `from_wire`
10126        // round-trip on the substrate-primitive axis pair.
10127        for &variant in RestartPolicy::ALL {
10128            let emitted: &'static str = variant.into();
10129            let re_parsed: Result<RestartPolicy, ()> =
10130                <RestartPolicy as TryFrom<&str>>::try_from(emitted);
10131            assert_eq!(
10132                re_parsed,
10133                Ok(variant),
10134                "trait-idiomatic axis pair must round-trip \
10135                 RestartPolicy::{variant:?} through `.into::<&'static \
10136                 str>()` and back through `TryFrom<&str>` — a break signals \
10137                 the forward-emit and reverse-parse axes have drifted onto \
10138                 different vocabularies"
10139            );
10140        }
10141    }
10142
10143    #[test]
10144    fn restart_policy_from_borrowed_into_static_str_routes_through_as_str_accessor() {
10145        // Fail-before-pass-after byte-parity pin on the newly lifted
10146        // `impl From<&RestartPolicy> for &'static str` — asserts the
10147        // borrowed-input standard-library trait impl and the substrate-
10148        // primitive [`RestartPolicy::as_str`] `pub const fn` accessor
10149        // resolve to the same three-arm emit-set across every arm the
10150        // exhaustive [`RestartPolicy::ALL`] slice enumerates. Rust's
10151        // `From` trait does not auto-derive the borrowed-input sibling
10152        // from a paired owned-input impl (no `impl<T, U> From<&T> for U
10153        // where T: Copy, U: From<T>` blanket in `core`), so the
10154        // borrowed-input axis is a distinct trait-idiomatic surface
10155        // that a `.iter().map(Into::into)` shape over
10156        // [`RestartPolicy::ALL`] (whose iterator yields
10157        // `&RestartPolicy`, not `RestartPolicy`) reaches through this
10158        // impl and no other — the paired owned-input
10159        // [`From<RestartPolicy>`] impl requires an explicit `.copied()`
10160        // / dereference before the trait fires. Materializes the
10161        // `<&'static str as From<&RestartPolicy>>::from` output in a
10162        // `const`-shape binding to make the `'static` lifetime promise
10163        // a build-time invariant.
10164        const PERMANENT: &str = RestartPolicy::Permanent.as_str();
10165        const TEMPORARY: &str = RestartPolicy::Temporary.as_str();
10166        const TRANSIENT: &str = RestartPolicy::Transient.as_str();
10167        for variant in RestartPolicy::ALL {
10168            let via_trait: &'static str = <&'static str as From<&RestartPolicy>>::from(variant);
10169            let via_method: &'static str = variant.as_str();
10170            assert_eq!(
10171                via_trait, via_method,
10172                "From<&RestartPolicy> for &'static str impl must round-trip \
10173                 &RestartPolicy::{variant:?} to the same lifted \
10174                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
10175                 returns — divergence signals a silent detour off the \
10176                 substrate-primitive accessor"
10177            );
10178            let via_into: &'static str = variant.into();
10179            assert_eq!(
10180                via_into, via_method,
10181                "Into<&'static str>::into on &RestartPolicy::{variant:?} \
10182                 must byte-equal RestartPolicy::as_str on the same input — \
10183                 the blanket-derived Into shape must resolve to the same \
10184                 as_str dispatch as the explicit From impl"
10185            );
10186        }
10187        assert_eq!(
10188            [PERMANENT, TEMPORARY, TRANSIENT],
10189            [
10190                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
10191                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
10192                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
10193            ],
10194            "const-context RestartPolicy::as_str must resolve to the three \
10195             lifted SUPERVISOR_CHILD_RESTART_* consts — the borrowed-input \
10196             From<&RestartPolicy> for &'static str impl inherits its \
10197             `'static` lifetime promise from the same accessor the \
10198             owned-input sibling routes through"
10199        );
10200    }
10201
10202    #[test]
10203    fn restart_policy_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
10204        // Cross-axis partition pin: the paired trait-idiomatic
10205        // owned-input `From<RestartPolicy> for &'static str` (9fb37d0
10206        // campaign-shape) and borrowed-input `From<&RestartPolicy> for
10207        // &'static str` (this lift) forward projections must resolve
10208        // identically on every arm, locking the two input-shape paths
10209        // together so any future detour trips at caixa-core test time.
10210        // Then a witness that a `.iter().map(Into::into)` pipe over
10211        // [`RestartPolicy::ALL`] (whose iterator yields
10212        // `&RestartPolicy`) materializes the three-arm accept-set
10213        // through the borrowed-input axis alone — the exact shape a
10214        // future wasm-operator per-child post-exit restart-decision
10215        // diagnostic line, a future substrate-wide per-arm diagnostic
10216        // column, or a
10217        // `HashMap::<&'static str, RestartPolicy>::from_iter(
10218        //     RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))`-style
10219        // per-policy lookup reaches through — closing the two-way
10220        // owned/borrowed input-shape symmetry on the forward-projection
10221        // trait-idiomatic axis. Peer of the sibling
10222        // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
10223        // (64aa742) /
10224        // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
10225        // (5ab993a) /
10226        // [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
10227        // (807b0b5) /
10228        // [`restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
10229        // (e941836) partition pins on the sibling closed-set typed-enum
10230        // discriminator axes — extends the borrowed-input axis
10231        // discipline onto the second-of-two M2 OTP-shape closed-set
10232        // typed enum on the caixa surface (per-child restart-decision
10233        // policy). Also closes the direct two-way `&Self → &'static
10234        // str → Self` round-trip via the paired [`TryFrom<&str>`] axis
10235        // — unlike the peer [`crate::CaixaKind`] axis pair (whose
10236        // forward `From` emits lowercase Portuguese diagnostic bytes
10237        // while the reverse `TryFrom` parses `PascalCase` wire bytes,
10238        // forcing the round-trip through an intermediate wire-vocab
10239        // hop), the [`RestartPolicy::as_str`] emit and
10240        // [`RestartPolicy::from_wire`] parse share the same
10241        // `PascalCase` vocabulary by construction, so the borrowed-
10242        // input forward axis and the reverse axis compose directly.
10243        for &variant in RestartPolicy::ALL {
10244            let owned: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
10245            let borrowed: &'static str = <&'static str as From<&RestartPolicy>>::from(&variant);
10246            assert_eq!(
10247                owned, borrowed,
10248                "From<RestartPolicy> and From<&RestartPolicy> for \
10249                 &'static str must resolve identically on \
10250                 RestartPolicy::{variant:?} — divergence signals the \
10251                 owned-input and borrowed-input forward-projection paths \
10252                 have drifted onto different emit-sets"
10253            );
10254        }
10255        let via_iter: Vec<&'static str> = RestartPolicy::ALL.iter().map(Into::into).collect();
10256        let via_method: Vec<&'static str> = RestartPolicy::ALL.iter().map(|p| p.as_str()).collect();
10257        assert_eq!(
10258            via_iter, via_method,
10259            "`.iter().map(Into::into)` over RestartPolicy::ALL must \
10260             byte-equal `.iter().map(|p| p.as_str())` on every arm — the \
10261             borrowed-input `From<&RestartPolicy> for &'static str` axis \
10262             is what makes the `.iter().map(Into::into)` shape route \
10263             through the substrate-primitive `RestartPolicy::as_str` \
10264             accessor rather than through a per-call-site `.copied()` / \
10265             dereference detour"
10266        );
10267        for variant in RestartPolicy::ALL {
10268            let emitted: &'static str = variant.into();
10269            let re_parsed: Result<RestartPolicy, ()> =
10270                <RestartPolicy as TryFrom<&str>>::try_from(emitted);
10271            assert_eq!(
10272                re_parsed,
10273                Ok(*variant),
10274                "trait-idiomatic borrowed-input forward-projection + \
10275                 reverse-projection axis pair must round-trip \
10276                 &RestartPolicy::{variant:?} through `.into::<&'static \
10277                 str>()` (via the borrowed-input axis) and back through \
10278                 `TryFrom<&str>` — a break signals the borrowed-input \
10279                 forward-emit and reverse-parse axes have drifted onto \
10280                 different vocabularies"
10281            );
10282        }
10283    }
10284
10285    #[test]
10286    fn restart_policy_from_into_owned_string_routes_through_as_str_accessor() {
10287        // Fail-before-pass-after byte-parity pin on the newly lifted
10288        // `impl From<RestartPolicy> for String` — asserts the
10289        // owned-`String`-returning standard-library trait impl and the
10290        // substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
10291        // accessor resolve to the same three-arm emit-set across every
10292        // arm the exhaustive [`RestartPolicy::ALL`] slice enumerates.
10293        // Rust's standard library does not carry a blanket
10294        // `impl<T: AsRef<str>> From<T> for String` (nor an
10295        // `impl<T: fmt::Display> From<T> for String`), so the
10296        // owned-`String` forward-projection axis is a distinct
10297        // trait-idiomatic surface that a `let key: String =
10298        // policy.into();`-shaped call site reaches through this impl
10299        // and no other — the paired sibling `From<RestartPolicy> for
10300        // &'static str` impl forces every owned-`String` call site
10301        // through an explicit `.to_owned()` / `String::from`
10302        // restatement. Peer of the first-mover
10303        // [`restart_strategy_from_into_owned_string_routes_through_as_str_accessor`]
10304        // (7baa18a) — extends the trait-idiomatic owned-`String`
10305        // forward-projection axis onto the second-of-two M2 OTP-shape
10306        // closed-set typed enums on the caixa surface (per-child
10307        // restart-decision-policy sibling on the same M2 `:supervisor`
10308        // slot).
10309        for &variant in RestartPolicy::ALL {
10310            let via_trait: String = <String as From<RestartPolicy>>::from(variant);
10311            let via_method: &'static str = variant.as_str();
10312            assert_eq!(
10313                via_trait.as_str(),
10314                via_method,
10315                "From<RestartPolicy> for String impl must round-trip \
10316                 RestartPolicy::{variant:?} to the same lifted \
10317                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
10318                 returns — divergence signals a silent detour off the \
10319                 substrate-primitive accessor"
10320            );
10321            let via_into: String = variant.into();
10322            assert_eq!(
10323                via_into.as_str(),
10324                via_method,
10325                "Into<String>::into on RestartPolicy::{variant:?} must \
10326                 byte-equal RestartPolicy::as_str on the same input — the \
10327                 blanket-derived Into shape must resolve to the same as_str \
10328                 dispatch as the explicit From impl"
10329            );
10330        }
10331    }
10332
10333    #[test]
10334    fn restart_policy_from_into_owned_string_and_static_str_agree_on_every_arm() {
10335        // Cross-axis partition pin: the paired trait-idiomatic
10336        // owned-`String` `From<RestartPolicy> for String` (this lift)
10337        // and owned-`&'static str` `From<RestartPolicy> for &'static
10338        // str` (9fb37d0) forward projections must resolve identically
10339        // on every arm, locking the two return-type-shape paths
10340        // together so any future detour trips at caixa-core test time.
10341        // Also byte-parity witness against the sibling
10342        // [`ToString::to_string`] surface routed through
10343        // [`std::fmt::Display`] — the three owned-heap-string paths
10344        // (`.into::<String>()`, `String::from`, `.to_string()`) must
10345        // resolve identically on every arm so a future consumer that
10346        // picks any of the three lands on the same lifted
10347        // SUPERVISOR_CHILD_RESTART_* const. Then a `.iter().copied()
10348        // .map(String::from)` pipe witness over [`RestartPolicy::ALL`]
10349        // that materializes the three-arm accept-set through the
10350        // owned-`String` axis alone — the exact shape a future
10351        // wasm-operator per-child post-exit restart-decision
10352        // diagnostic line composer or a
10353        // `HashMap::<String, RestartPolicy>::from_iter(
10354        //     RestartPolicy::ALL.iter().copied().map(|p| (p.into(), p)))`-style
10355        // owned-key per-policy lookup reaches through — closing the
10356        // owned-`String` forward-projection axis's iterator-pipe
10357        // shape. Then a direct round-trip witness through the paired
10358        // trait-idiomatic reverse [`TryFrom<&str>`] axis on the
10359        // owned-`String`'s [`String::as_str`] borrow that closes the
10360        // two-way `Self → String → Self` round-trip on the trait-
10361        // idiomatic owned-`String` forward + reverse axis pair —
10362        // unlike the peer [`crate::CaixaKind`] axis pair (whose
10363        // forward `From` emits lowercase Portuguese diagnostic bytes
10364        // while the reverse `TryFrom` parses `PascalCase` wire bytes,
10365        // forcing the round-trip through an intermediate wire-vocab
10366        // hop), the [`RestartPolicy::as_str`] emit and
10367        // [`RestartPolicy::from_wire`] parse share the same
10368        // `PascalCase` vocabulary by construction, so the owned-
10369        // `String` forward axis and the reverse axis compose directly.
10370        for &variant in RestartPolicy::ALL {
10371            let owned_string: String = <String as From<RestartPolicy>>::from(variant);
10372            let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
10373            assert_eq!(
10374                owned_string.as_str(),
10375                owned_static,
10376                "From<RestartPolicy> for String and From<RestartPolicy> \
10377                 for &'static str must resolve identically on \
10378                 RestartPolicy::{variant:?} — divergence signals the \
10379                 owned-`String` and owned-`&'static str` forward-projection \
10380                 return-type-shape paths have drifted onto different \
10381                 emit-sets"
10382            );
10383            let via_to_string: String = variant.to_string();
10384            assert_eq!(
10385                owned_string, via_to_string,
10386                "From<RestartPolicy> for String must byte-equal \
10387                 RestartPolicy::to_string on RestartPolicy::{variant:?} — \
10388                 divergence signals the trait-idiomatic owned-`String` \
10389                 forward-projection axis and the ToString-through-Display \
10390                 axis have drifted onto different emit-sets"
10391            );
10392        }
10393        let via_iter: Vec<String> = RestartPolicy::ALL
10394            .iter()
10395            .copied()
10396            .map(String::from)
10397            .collect();
10398        let via_method: Vec<String> = RestartPolicy::ALL
10399            .iter()
10400            .map(|p| p.as_str().to_owned())
10401            .collect();
10402        assert_eq!(
10403            via_iter, via_method,
10404            "`.iter().copied().map(String::from)` over RestartPolicy::ALL \
10405             must byte-equal `.iter().map(|p| p.as_str().to_owned())` on \
10406             every arm — the owned-`String` `From<RestartPolicy> for \
10407             String` axis is what makes the `String::from` composition \
10408             route through the substrate-primitive `RestartPolicy::as_str` \
10409             accessor rather than through a per-call-site `.to_owned()` / \
10410             `String::from(policy.as_str())` detour"
10411        );
10412        for &variant in RestartPolicy::ALL {
10413            let emitted: String = variant.into();
10414            let re_parsed: Result<RestartPolicy, ()> =
10415                <RestartPolicy as TryFrom<&str>>::try_from(emitted.as_str());
10416            assert_eq!(
10417                re_parsed,
10418                Ok(variant),
10419                "trait-idiomatic owned-`String` forward-projection + \
10420                 reverse-projection axis pair must round-trip \
10421                 RestartPolicy::{variant:?} through `.into::<String>()` \
10422                 and back through `TryFrom<&str>` on the owned-`String`'s \
10423                 String::as_str borrow — a break signals the owned-`String` \
10424                 forward-emit and reverse-parse axes have drifted onto \
10425                 different vocabularies"
10426            );
10427        }
10428    }
10429
10430    #[test]
10431    fn restart_policy_from_into_borrowed_owned_string_routes_through_as_str_accessor() {
10432        // Fail-before-pass-after byte-parity pin on the newly lifted
10433        // `impl From<&RestartPolicy> for String` — asserts the
10434        // borrowed-input owned-`String`-returning standard-library
10435        // trait impl and the substrate-primitive
10436        // [`RestartPolicy::as_str`] `pub const fn` accessor resolve to
10437        // the same three-arm emit-set across every arm the exhaustive
10438        // [`RestartPolicy::ALL`] slice enumerates. Rust's standard
10439        // library does not carry a blanket `impl<T: AsRef<str>>
10440        // From<&T> for String` (nor an `impl<T: fmt::Display> From<&T>
10441        // for String`), so the borrowed-input owned-`String` forward-
10442        // projection axis is a distinct trait-idiomatic surface that a
10443        // `let key: String = (&policy).into();`-shaped call site
10444        // reaches through this impl and no other — the paired sibling
10445        // `From<RestartPolicy> for String` impl forces every borrowed-
10446        // input call site through an explicit `Copy` deref
10447        // (`String::from(*policy)`) or an `.as_str().to_owned()` /
10448        // `.to_string()` detour. Peer of the first-mover
10449        // [`restart_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
10450        // (579385f) — extends the trait-idiomatic borrowed-input
10451        // owned-`String` forward-projection axis onto the second-of-
10452        // two M2 OTP-shape closed-set typed enums on the caixa surface
10453        // (per-child restart-decision-policy sibling on the same M2
10454        // `:supervisor` slot).
10455        for &variant in RestartPolicy::ALL {
10456            let via_trait: String = <String as From<&RestartPolicy>>::from(&variant);
10457            let via_method: &'static str = variant.as_str();
10458            assert_eq!(
10459                via_trait.as_str(),
10460                via_method,
10461                "From<&RestartPolicy> for String impl must round-trip \
10462                 &RestartPolicy::{variant:?} to the same lifted \
10463                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
10464                 returns — divergence signals a silent detour off the \
10465                 substrate-primitive accessor"
10466            );
10467            let via_into: String = (&variant).into();
10468            assert_eq!(
10469                via_into.as_str(),
10470                via_method,
10471                "Into<String>::into on &RestartPolicy::{variant:?} must \
10472                 byte-equal RestartPolicy::as_str on the same input — \
10473                 the blanket-derived Into shape must resolve to the \
10474                 same as_str dispatch as the explicit From impl"
10475            );
10476        }
10477    }
10478
10479    #[test]
10480    fn restart_policy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm() {
10481        // Cross-axis partition pin: the newly lifted trait-idiomatic
10482        // borrowed-input owned-`String` `From<&RestartPolicy> for
10483        // String` (this lift), the paired owned-input owned-`String`
10484        // `From<RestartPolicy> for String` (7851725), the paired
10485        // borrowed-input owned-`&'static str` `From<&RestartPolicy>
10486        // for &'static str` (842c7f3), and the paired owned-input
10487        // owned-`&'static str` `From<RestartPolicy> for &'static str`
10488        // (9fb37d0) — every corner of the `{Self, &Self} × {&'static
10489        // str, String}` 2×2 trait-idiomatic projection family — must
10490        // resolve identically on every arm, locking the four
10491        // return-shape × input-shape paths together so any future
10492        // detour trips at caixa-core test time. Also byte-parity
10493        // witness against the sibling [`ToString::to_string`] surface
10494        // routed through [`std::fmt::Display`] and a direct round-trip
10495        // witness through the paired trait-idiomatic reverse
10496        // [`TryFrom<&str>`] axis on the owned-`String`'s
10497        // [`String::as_str`] borrow that closes the two-way
10498        // `&Self → String → Self` round-trip on the trait-idiomatic
10499        // borrowed-input owned-`String` forward + reverse axis pair.
10500        // Peer of the first-mover
10501        // [`restart_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
10502        // (579385f) — closes the whole `{Self, &Self} × {&'static str,
10503        // String}` 2×2 projection corner on both M2 OTP-shape sibling
10504        // peers.
10505        for &variant in RestartPolicy::ALL {
10506            let borrowed_string: String = <String as From<&RestartPolicy>>::from(&variant);
10507            let owned_string: String = <String as From<RestartPolicy>>::from(variant);
10508            let borrowed_static: &'static str =
10509                <&'static str as From<&RestartPolicy>>::from(&variant);
10510            let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
10511            assert_eq!(
10512                borrowed_string, owned_string,
10513                "From<&RestartPolicy> for String and From<RestartPolicy> \
10514                 for String must resolve identically on \
10515                 RestartPolicy::{variant:?} — divergence signals the \
10516                 borrowed-input and owned-input owned-`String` \
10517                 forward-projection input-shape paths have drifted onto \
10518                 different emit-sets"
10519            );
10520            assert_eq!(
10521                borrowed_string.as_str(),
10522                borrowed_static,
10523                "From<&RestartPolicy> for String and From<&RestartPolicy> \
10524                 for &'static str must resolve identically on \
10525                 RestartPolicy::{variant:?} — divergence signals the \
10526                 borrowed-input `&'static str` and owned-`String` \
10527                 return-shape paths have drifted onto different \
10528                 emit-sets"
10529            );
10530            assert_eq!(
10531                borrowed_string.as_str(),
10532                owned_static,
10533                "From<&RestartPolicy> for String and From<RestartPolicy> \
10534                 for &'static str must resolve identically on \
10535                 RestartPolicy::{variant:?} — divergence signals a \
10536                 break in the diagonal corner of the {{Self, &Self}} × \
10537                 {{&'static str, String}} 2×2 trait-idiomatic \
10538                 projection family"
10539            );
10540            let via_to_string: String = variant.to_string();
10541            assert_eq!(
10542                borrowed_string, via_to_string,
10543                "From<&RestartPolicy> for String must byte-equal \
10544                 RestartPolicy::to_string on RestartPolicy::{variant:?} \
10545                 — divergence signals the trait-idiomatic borrowed-input \
10546                 owned-`String` forward-projection axis and the \
10547                 ToString-through-Display axis have drifted onto \
10548                 different emit-sets"
10549            );
10550        }
10551        let via_iter: Vec<String> = RestartPolicy::ALL.iter().map(String::from).collect();
10552        let via_method: Vec<String> = RestartPolicy::ALL
10553            .iter()
10554            .map(|p| p.as_str().to_owned())
10555            .collect();
10556        assert_eq!(
10557            via_iter, via_method,
10558            "`.iter().map(String::from)` over RestartPolicy::ALL — a \
10559             call site whose iteration axis holds `&RestartPolicy` by \
10560             construction — must byte-equal `.iter().map(|p| \
10561             p.as_str().to_owned())` on every arm — the borrowed-input \
10562             owned-`String` `From<&RestartPolicy> for String` axis is \
10563             what makes the `String::from` composition route through \
10564             the substrate-primitive `RestartPolicy::as_str` accessor \
10565             without a spurious `Copy` deref (which would only be \
10566             reachable through the owned-input `From<RestartPolicy> \
10567             for String` axis by first calling `.copied()` on the \
10568             iterator)"
10569        );
10570        for &variant in RestartPolicy::ALL {
10571            let emitted: String = (&variant).into();
10572            let re_parsed: Result<RestartPolicy, ()> =
10573                <RestartPolicy as TryFrom<&str>>::try_from(emitted.as_str());
10574            assert_eq!(
10575                re_parsed,
10576                Ok(variant),
10577                "trait-idiomatic borrowed-input owned-`String` \
10578                 forward-projection + reverse-projection axis pair must \
10579                 round-trip &RestartPolicy::{variant:?} through \
10580                 `.into::<String>()` on the borrowed-input surface and \
10581                 back through `TryFrom<&str>` on the owned-`String`'s \
10582                 String::as_str borrow — a break signals the \
10583                 borrowed-input owned-`String` forward-emit and \
10584                 reverse-parse axes have drifted onto different \
10585                 vocabularies"
10586            );
10587        }
10588    }
10589
10590    #[test]
10591    fn restart_policy_from_into_static_cow_str_routes_through_as_str_accessor() {
10592        // Fail-before-pass-after byte-parity pin on the newly lifted
10593        // `impl From<RestartPolicy> for std::borrow::Cow<'static, str>` —
10594        // asserts the standard-library trait impl and the substrate-
10595        // primitive [`super::RestartPolicy::as_str`] `pub const fn`
10596        // accessor resolve to the same three-arm emit-set across every
10597        // arm the exhaustive [`super::RestartPolicy::ALL`] slice
10598        // enumerates. Rust's standard library does not carry a blanket
10599        // `impl<T: AsRef<str>> From<T> for Cow<'static, str>` (nor an
10600        // `impl<T: fmt::Display> From<T> for Cow<'static, str>`), so
10601        // the `Cow<'static, str>` forward-projection axis is a
10602        // distinct trait-idiomatic surface that a
10603        // `let key: Cow<'static, str> = policy.into();`-shaped call
10604        // site reaches through this impl and no other — the paired
10605        // sibling `From<RestartPolicy> for &'static str` and
10606        // `From<RestartPolicy> for String` impls force every
10607        // `Cow<'static, str>`-parameterized call site through a
10608        // `Cow::Borrowed(policy.as_str())` /
10609        // `Cow::Owned(policy.to_string())` composition whose type
10610        // bounds have no compile-time link back to the substrate
10611        // primitive.
10612        //
10613        // Also asserts the projection lands on the zero-alloc
10614        // [`std::borrow::Cow::Borrowed`] arm (not the
10615        // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
10616        // [`super::RestartPolicy::as_str`] accessor's `&'static str`
10617        // return lifetime by construction makes the borrowed arm the
10618        // type-correct projection with no runtime allocation. Any
10619        // future silent detour that routes the impl through the owned
10620        // arm (an accidental `Cow::Owned(policy.to_string())` rewrite
10621        // that would allocate on every call site where the
10622        // `&'static str` return of [`super::RestartPolicy::as_str`]
10623        // makes the zero-alloc borrowed projection type-correct) trips
10624        // at caixa-core test time under the
10625        // [`std::borrow::Cow::Borrowed`] discriminator witness rather
10626        // than at a downstream `Cow<'static, str>`-bound consumer's
10627        // silent allocation.
10628        //
10629        // Second peer on the substrate-wide trait-idiomatic
10630        // [`std::borrow::Cow<'static, str>`] forward-projection family
10631        // to extend the axis off the top-level [`super::CaixaKind`]
10632        // enum (99c1735 owned-input, d45c409 borrowed-input) onto the
10633        // second (and second-of-two-in-M2) M2 OTP-shape closed-set
10634        // fieldless typed enum peer on the caixa surface — closes the
10635        // M2 OTP-shape tier of the campaign on the owned-input axis
10636        // (both sibling peers, `RestartStrategy` and `RestartPolicy`,
10637        // now carry the owned-input Cow<'static, str> forward
10638        // projection).
10639        for &variant in RestartPolicy::ALL {
10640            let via_trait: std::borrow::Cow<'static, str> =
10641                <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
10642            let via_method: &'static str = variant.as_str();
10643            assert_eq!(
10644                via_trait.as_ref(),
10645                via_method,
10646                "From<RestartPolicy> for Cow<'static, str> impl must \
10647                 round-trip RestartPolicy::{variant:?} to the same \
10648                 lifted SUPERVISOR_CHILD_RESTART_* const \
10649                 RestartPolicy::as_str returns — divergence signals a \
10650                 silent detour off the substrate-primitive accessor"
10651            );
10652            assert!(
10653                matches!(via_trait, std::borrow::Cow::Borrowed(_)),
10654                "From<RestartPolicy> for Cow<'static, str> impl must \
10655                 land on the zero-alloc Cow::Borrowed arm on \
10656                 RestartPolicy::{variant:?} — a Cow::Owned outcome \
10657                 signals the projection has silently allocated where \
10658                 the substrate-primitive RestartPolicy::as_str \
10659                 `&'static str` return makes the borrowed arm the \
10660                 type-correct projection"
10661            );
10662            let via_into: std::borrow::Cow<'static, str> = variant.into();
10663            assert_eq!(
10664                via_into.as_ref(),
10665                via_method,
10666                "Into<Cow<'static, str>>::into on \
10667                 RestartPolicy::{variant:?} must byte-equal \
10668                 RestartPolicy::as_str on the same input — the \
10669                 blanket-derived Into shape must resolve to the same \
10670                 as_str dispatch as the explicit From impl"
10671            );
10672            assert!(
10673                matches!(via_into, std::borrow::Cow::Borrowed(_)),
10674                "Into<Cow<'static, str>>::into on \
10675                 RestartPolicy::{variant:?} must land on the \
10676                 zero-alloc Cow::Borrowed arm — the blanket-derived \
10677                 Into shape must resolve to the same Cow::Borrowed \
10678                 dispatch as the explicit From impl"
10679            );
10680        }
10681    }
10682
10683    #[test]
10684    fn restart_policy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
10685        // Cross-axis partition pin: the newly lifted trait-idiomatic
10686        // `From<RestartPolicy> for std::borrow::Cow<'static, str>`
10687        // (this lift), the paired owned-input `From<RestartPolicy>
10688        // for &'static str` (9fb37d0), and the paired owned-input
10689        // `From<RestartPolicy> for String` (7851725) forward
10690        // projections must resolve identically on every arm, locking
10691        // the three return-shape paths together by construction so any
10692        // future detour trips at caixa-core test time. Also byte-parity
10693        // witness against the sibling [`ToString::to_string`] surface
10694        // routed through [`std::fmt::Display`] — every owned-heap-
10695        // string path (the `Cow::Owned` promotion of this axis's
10696        // `.into_owned()`, `From<RestartPolicy> for String`, and
10697        // `.to_string()`) resolves to the same lifted
10698        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const per arm.
10699        //
10700        // Then a `.iter().copied().map(std::borrow::Cow::from)` pipe
10701        // witness over [`super::RestartPolicy::ALL`] that
10702        // materializes the three-arm accept-set through the
10703        // [`std::borrow::Cow<'static, str>`] axis alone — the exact
10704        // shape a future `axum::response::IntoResponse` per-policy
10705        // rejection-body composer, a future M4 admission-webhook
10706        // per-policy rejection-reason emitter whose typing rules out
10707        // the sibling [`AsRef<str>`] borrowed return, or a future
10708        // substrate-wide per-policy diagnostic surface that binds
10709        // through a [`Cow<'static, str>`] boundary reaches through.
10710        // The pipe witness also pins the zero-alloc discipline: every
10711        // element in the collected vector satisfies the
10712        // [`std::borrow::Cow::Borrowed`] arm predicate, so a future
10713        // accidental silent-allocation regression on the pipe's
10714        // iteration axis is a caixa-core-test-time failure. Peer of
10715        // the first-mover
10716        // [`restart_strategy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
10717        // (7dd28b3) on the sibling M2 OTP-shape sibling-restart axis
10718        // — closes the whole owned-input `Cow<'static, str>` +
10719        // paired `{&'static str, String}` cross-axis-parity corner on
10720        // both M2 OTP-shape sibling peers.
10721        for &variant in RestartPolicy::ALL {
10722            let via_cow: std::borrow::Cow<'static, str> =
10723                <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
10724            let via_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
10725            let via_string: String = <String as From<RestartPolicy>>::from(variant);
10726            assert_eq!(
10727                via_cow.as_ref(),
10728                via_static,
10729                "From<RestartPolicy> for Cow<'static, str> and \
10730                 From<RestartPolicy> for &'static str must resolve \
10731                 identically on RestartPolicy::{variant:?} — \
10732                 divergence signals the Cow<'static, str> and \
10733                 &'static str return-shape paths have drifted onto \
10734                 different emit-sets"
10735            );
10736            assert_eq!(
10737                via_cow.as_ref(),
10738                via_string.as_str(),
10739                "From<RestartPolicy> for Cow<'static, str> and \
10740                 From<RestartPolicy> for String must resolve \
10741                 identically on RestartPolicy::{variant:?} — \
10742                 divergence signals the Cow<'static, str> and String \
10743                 return-shape paths have drifted onto different \
10744                 emit-sets"
10745            );
10746            let via_to_string: String = variant.to_string();
10747            assert_eq!(
10748                via_cow.as_ref(),
10749                via_to_string.as_str(),
10750                "From<RestartPolicy> for Cow<'static, str> must \
10751                 byte-equal RestartPolicy::to_string on \
10752                 RestartPolicy::{variant:?} — divergence signals the \
10753                 trait-idiomatic Cow<'static, str> forward-projection \
10754                 axis and the ToString-through-Display axis have \
10755                 drifted onto different emit-sets"
10756            );
10757        }
10758        let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
10759            .iter()
10760            .copied()
10761            .map(std::borrow::Cow::from)
10762            .collect();
10763        let via_method: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
10764            .iter()
10765            .map(|p| std::borrow::Cow::Borrowed(p.as_str()))
10766            .collect();
10767        assert_eq!(
10768            via_iter, via_method,
10769            "`.iter().copied().map(Cow::from)` over \
10770             RestartPolicy::ALL must byte-equal `.iter().map(|p| \
10771             Cow::Borrowed(p.as_str()))` on every arm — the \
10772             trait-idiomatic `From<RestartPolicy> for Cow<'static, \
10773             str>` axis is what makes the `Cow::from` composition \
10774             route through the substrate-primitive \
10775             `RestartPolicy::as_str` accessor with the zero-alloc \
10776             Cow::Borrowed arm by construction, rather than a \
10777             per-call-site `Cow::Owned(policy.to_string())` \
10778             allocation"
10779        );
10780        for cow in &via_iter {
10781            assert!(
10782                matches!(cow, std::borrow::Cow::Borrowed(_)),
10783                "every element of the \
10784                 .iter().copied().map(Cow::from) pipe over \
10785                 RestartPolicy::ALL must land on the zero-alloc \
10786                 Cow::Borrowed arm — a Cow::Owned outcome on any arm \
10787                 signals the pipe's iteration axis has silently \
10788                 allocated where the substrate-primitive \
10789                 RestartPolicy::as_str `&'static str` return makes \
10790                 the borrowed arm the type-correct projection"
10791            );
10792        }
10793    }
10794
10795    #[test]
10796    fn restart_policy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor() {
10797        // Fail-before-pass-after byte-parity pin on the newly lifted
10798        // `impl From<&RestartPolicy> for std::borrow::Cow<'static, str>` —
10799        // asserts the borrowed-input standard-library trait impl and
10800        // the substrate-primitive [`super::RestartPolicy::as_str`]
10801        // `pub const fn` accessor resolve to the same three-arm emit-
10802        // set across every arm the exhaustive
10803        // [`super::RestartPolicy::ALL`] slice enumerates. Rust's
10804        // standard library does not carry a blanket
10805        // `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor a
10806        // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`), so
10807        // the borrowed-input `Cow<'static, str>` forward-projection
10808        // axis is a distinct trait-idiomatic surface that a
10809        // `let key: Cow<'static, str> = (&policy).into();`-shaped
10810        // call site or a
10811        // `RestartPolicy::ALL.iter().map(Cow::from)`-shaped pipe
10812        // reaches through this impl and no other — the paired owned-
10813        // input `From<RestartPolicy> for Cow<'static, str>` impl
10814        // (0612398) forces every borrowed-input call site through an
10815        // explicit `Copy` deref (`Cow::from(*policy)`) or a
10816        // `Cow::Borrowed(policy.as_str())` open-code whose type
10817        // bounds have no compile-time link back to the substrate
10818        // primitive.
10819        //
10820        // Also asserts the projection lands on the zero-alloc
10821        // [`std::borrow::Cow::Borrowed`] arm (not the
10822        // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
10823        // [`super::RestartPolicy::as_str`] accessor's `&'static str`
10824        // return lifetime by construction makes the borrowed arm the
10825        // type-correct projection with no runtime allocation on the
10826        // borrowed-input surface just as on the paired owned-input
10827        // surface.
10828        //
10829        // Closes the `{Self, &Self}` input-shape corner on the M2
10830        // OTP-shape per-child-restart [`Cow<'static, str>`] axis on
10831        // the second-of-two-in-M2 closed-set fieldless typed enum peer
10832        // on the caixa surface (`:supervisor :children :restart`),
10833        // exactly as d45c409 closed it on the top-level
10834        // [`super::CaixaKind`] one commit after the owning half
10835        // (99c1735) landed and as 9b3e4b3 closed it on the sibling
10836        // M2 OTP-shape [`super::RestartStrategy`] one commit after
10837        // (7dd28b3) landed. This lift closes the whole M2 OTP-shape
10838        // tier of the substrate-wide Cow<'static, str> forward-
10839        // projection campaign on both input-shape corners
10840        // ({Self, &Self}) of both M2 OTP-shape sibling peers.
10841        for &variant in RestartPolicy::ALL {
10842            let via_trait: std::borrow::Cow<'static, str> =
10843                <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&variant);
10844            let via_method: &'static str = variant.as_str();
10845            assert_eq!(
10846                via_trait.as_ref(),
10847                via_method,
10848                "From<&RestartPolicy> for Cow<'static, str> impl must \
10849                 round-trip &RestartPolicy::{variant:?} to the same \
10850                 lifted SUPERVISOR_CHILD_RESTART_* const \
10851                 RestartPolicy::as_str returns — divergence signals a \
10852                 silent detour off the substrate-primitive accessor"
10853            );
10854            assert!(
10855                matches!(via_trait, std::borrow::Cow::Borrowed(_)),
10856                "From<&RestartPolicy> for Cow<'static, str> impl must \
10857                 land on the zero-alloc Cow::Borrowed arm on \
10858                 &RestartPolicy::{variant:?} — a Cow::Owned outcome \
10859                 signals the projection has silently allocated where \
10860                 the substrate-primitive RestartPolicy::as_str \
10861                 `&'static str` return makes the borrowed arm the \
10862                 type-correct projection"
10863            );
10864            let via_into: std::borrow::Cow<'static, str> = (&variant).into();
10865            assert_eq!(
10866                via_into.as_ref(),
10867                via_method,
10868                "Into<Cow<'static, str>>::into on \
10869                 &RestartPolicy::{variant:?} must byte-equal \
10870                 RestartPolicy::as_str on the same input — the \
10871                 blanket-derived Into shape must resolve to the same \
10872                 as_str dispatch as the explicit From impl"
10873            );
10874            assert!(
10875                matches!(via_into, std::borrow::Cow::Borrowed(_)),
10876                "Into<Cow<'static, str>>::into on \
10877                 &RestartPolicy::{variant:?} must land on the \
10878                 zero-alloc Cow::Borrowed arm — the blanket-derived \
10879                 Into shape must resolve to the same Cow::Borrowed \
10880                 dispatch as the explicit From impl"
10881            );
10882        }
10883    }
10884
10885    #[test]
10886    fn restart_policy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
10887        // Cross-axis partition pin: the newly lifted trait-idiomatic
10888        // borrowed-input `From<&RestartPolicy> for
10889        // std::borrow::Cow<'static, str>` (this lift), the paired
10890        // owned-input `From<RestartPolicy> for
10891        // std::borrow::Cow<'static, str>` (0612398), the paired
10892        // borrowed-input owned-`&'static str` `From<&RestartPolicy>
10893        // for &'static str`, and the paired borrowed-input owned-
10894        // `String` `From<&RestartPolicy> for String` must resolve
10895        // identically on every arm, locking the four
10896        // return-shape × input-shape paths together by construction so
10897        // any future detour trips at caixa-core test time. Also byte-
10898        // parity witness against the sibling [`ToString::to_string`]
10899        // surface routed through [`std::fmt::Display`] — every owned-
10900        // heap-string path (this axis's `.into_owned()` promotion, the
10901        // paired [`From<&RestartPolicy> for String`], and
10902        // `.to_string()`) resolves to the same lifted
10903        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const per arm.
10904        //
10905        // Then a `.iter().map(std::borrow::Cow::from)` pipe witness
10906        // over [`super::RestartPolicy::ALL`] — whose iterator yields
10907        // `&RestartPolicy` by construction, so the borrowed-input
10908        // [`Cow<'static, str>`] axis is what routes the pipe through
10909        // the substrate-primitive [`super::RestartPolicy::as_str`]
10910        // accessor without a spurious [`Copy`] deref (which would only
10911        // be reachable through the owned-input
10912        // [`From<RestartPolicy> for Cow<'static, str>`] axis by first
10913        // calling `.copied()` on the iterator). The pipe witness also
10914        // pins the zero-alloc discipline: every element in the
10915        // collected vector satisfies the [`std::borrow::Cow::Borrowed`]
10916        // arm predicate, so a future accidental silent-allocation
10917        // regression on the pipe's iteration axis is a caixa-core-
10918        // test-time failure. Peer of the sibling
10919        // [`restart_strategy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
10920        // (9b3e4b3) on the M2 OTP-shape sibling-restart axis — closes
10921        // the whole borrowed-input `Cow<'static, str>` +
10922        // paired `{&'static str, String}` cross-axis-parity corner on
10923        // both M2 OTP-shape sibling peers.
10924        for &policy in RestartPolicy::ALL {
10925            let borrowed_cow: std::borrow::Cow<'static, str> =
10926                <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&policy);
10927            let owned_cow: std::borrow::Cow<'static, str> =
10928                <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(policy);
10929            let borrowed_static: &'static str =
10930                <&'static str as From<&RestartPolicy>>::from(&policy);
10931            let borrowed_string: String = <String as From<&RestartPolicy>>::from(&policy);
10932            assert_eq!(
10933                borrowed_cow, owned_cow,
10934                "From<&RestartPolicy> for Cow<'static, str> and \
10935                 From<RestartPolicy> for Cow<'static, str> must \
10936                 resolve identically on RestartPolicy::{policy:?} — \
10937                 divergence signals the borrowed-input and owned-input \
10938                 Cow<'static, str> forward-projection input-shape \
10939                 paths have drifted onto different emit-sets"
10940            );
10941            assert_eq!(
10942                borrowed_cow.as_ref(),
10943                borrowed_static,
10944                "From<&RestartPolicy> for Cow<'static, str> and \
10945                 From<&RestartPolicy> for &'static str must resolve \
10946                 identically on RestartPolicy::{policy:?} — \
10947                 divergence signals the borrowed-input Cow<'static, \
10948                 str> and &'static str return-shape paths have drifted \
10949                 onto different emit-sets"
10950            );
10951            assert_eq!(
10952                borrowed_cow.as_ref(),
10953                borrowed_string.as_str(),
10954                "From<&RestartPolicy> for Cow<'static, str> and \
10955                 From<&RestartPolicy> for String must resolve \
10956                 identically on RestartPolicy::{policy:?} — \
10957                 divergence signals the borrowed-input Cow<'static, \
10958                 str> and owned-`String` return-shape paths have \
10959                 drifted onto different emit-sets"
10960            );
10961            let via_to_string: String = policy.to_string();
10962            assert_eq!(
10963                borrowed_cow.as_ref(),
10964                via_to_string.as_str(),
10965                "From<&RestartPolicy> for Cow<'static, str> must \
10966                 byte-equal RestartPolicy::to_string on \
10967                 RestartPolicy::{policy:?} — divergence signals \
10968                 the trait-idiomatic borrowed-input Cow<'static, str> \
10969                 forward-projection axis and the ToString-through-\
10970                 Display axis have drifted onto different emit-sets"
10971            );
10972        }
10973        let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
10974            .iter()
10975            .map(std::borrow::Cow::from)
10976            .collect();
10977        let via_method: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
10978            .iter()
10979            .map(|p| std::borrow::Cow::Borrowed(p.as_str()))
10980            .collect();
10981        assert_eq!(
10982            via_iter, via_method,
10983            "`.iter().map(Cow::from)` over RestartPolicy::ALL — a \
10984             call site whose iteration axis holds `&RestartPolicy` \
10985             by construction — must byte-equal `.iter().map(|p| \
10986             Cow::Borrowed(p.as_str()))` on every arm — the borrowed-\
10987             input Cow<'static, str> `From<&RestartPolicy> for \
10988             Cow<'static, str>` axis is what makes the `Cow::from` \
10989             composition route through the substrate-primitive \
10990             `RestartPolicy::as_str` accessor with the zero-alloc \
10991             Cow::Borrowed arm by construction and without a spurious \
10992             `Copy` deref (which would only be reachable through the \
10993             owned-input `From<RestartPolicy> for Cow<'static, str>` \
10994             axis by first calling `.copied()` on the iterator)"
10995        );
10996        for cow in &via_iter {
10997            assert!(
10998                matches!(cow, std::borrow::Cow::Borrowed(_)),
10999                "every element of the .iter().map(Cow::from) pipe \
11000                 over RestartPolicy::ALL must land on the zero-\
11001                 alloc Cow::Borrowed arm — a Cow::Owned outcome on \
11002                 any arm signals the pipe's iteration axis has \
11003                 silently allocated where the substrate-primitive \
11004                 RestartPolicy::as_str `&'static str` return makes \
11005                 the borrowed arm the type-correct projection"
11006            );
11007        }
11008    }
11009
11010    #[test]
11011    fn restart_policy_from_into_box_str_routes_through_as_str_accessor() {
11012        // Fail-before-pass-after byte-parity pin on the newly lifted
11013        // `impl From<RestartPolicy> for Box<str>` — asserts the
11014        // owned-input standard-library trait impl and the
11015        // substrate-primitive [`super::RestartPolicy::as_str`]
11016        // `pub const fn` accessor resolve to the same three-arm emit-
11017        // set across every arm the exhaustive
11018        // [`super::RestartPolicy::ALL`] slice enumerates. Extends the
11019        // substrate-wide `Box<str>` forward-projection campaign tier
11020        // opened one commit prior (69ef45c) on the paired sibling-
11021        // restart [`RestartStrategy`] onto the second (and third-and-
11022        // final) M2 OTP-shape closed-set fieldless typed enum peer on
11023        // the caixa surface (`:children :restart`), immediately after
11024        // the paired `Cow<'static, str>` axis (0612398 / b4dc55c)
11025        // closed the
11026        // `{Self, &Self} × {&'static str, String, Cow<'static, str>}`
11027        // 2×3 corner on this enum. Rust's standard library carries
11028        // `impl From<&str> for Box<str>` and
11029        // `impl From<String> for Box<str>` but no blanket
11030        // `impl<T: AsRef<str>> From<T> for Box<str>`, so this axis is
11031        // a distinct trait-idiomatic surface that a
11032        // `let key: Box<str> = policy.into();`-shaped call site
11033        // reaches through this impl and no other — a paired
11034        // `Box::from(policy.as_str())` open-code has no compile-time
11035        // link back to the substrate primitive. Peer of the sibling
11036        // [`restart_strategy_from_into_box_str_routes_through_as_str_accessor`]
11037        // (69ef45c) — extends the trait-idiomatic owned-input
11038        // [`Box<str>`] forward-projection axis onto the third and
11039        // final M2-OTP-shape closed-set typed enum on the caixa
11040        // surface.
11041        for &variant in RestartPolicy::ALL {
11042            let via_trait: Box<str> = <Box<str> as From<RestartPolicy>>::from(variant);
11043            let via_method: &'static str = variant.as_str();
11044            assert_eq!(
11045                via_trait.as_ref(),
11046                via_method,
11047                "From<RestartPolicy> for Box<str> impl must round-\
11048                 trip RestartPolicy::{variant:?} to the same lifted \
11049                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
11050                 returns — divergence signals a silent detour off the \
11051                 substrate-primitive accessor"
11052            );
11053            let via_into: Box<str> = variant.into();
11054            assert_eq!(
11055                via_into.as_ref(),
11056                via_method,
11057                "Into<Box<str>>::into on RestartPolicy::{variant:?} \
11058                 must byte-equal RestartPolicy::as_str on the same \
11059                 input — the blanket-derived Into shape must resolve \
11060                 to the same as_str dispatch as the explicit From impl"
11061            );
11062        }
11063    }
11064
11065    #[test]
11066    fn restart_policy_from_borrowed_into_box_str_routes_through_as_str_accessor() {
11067        // Fail-before-pass-after byte-parity pin on the newly lifted
11068        // `impl From<&RestartPolicy> for Box<str>` — asserts the
11069        // borrowed-input standard-library trait impl and the
11070        // substrate-primitive [`super::RestartPolicy::as_str`]
11071        // `pub const fn` accessor resolve to the same three-arm emit-
11072        // set across every arm the exhaustive
11073        // [`super::RestartPolicy::ALL`] slice enumerates. Rust's
11074        // standard library does not carry a blanket
11075        // `impl<T: AsRef<str>> From<&T> for Box<str>` (nor a
11076        // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`),
11077        // so the borrowed-input `Box<str>` forward-projection axis
11078        // is a distinct trait-idiomatic surface that a
11079        // `let key: Box<str> = (&policy).into();`-shaped call site
11080        // or a `RestartPolicy::ALL.iter().map(Box::<str>::from)`-
11081        // shaped pipe reaches through this impl and no other — the
11082        // paired owned-input `From<RestartPolicy> for Box<str>`
11083        // impl (0a1b313) forces every borrowed-input call site
11084        // through an explicit `Copy` deref
11085        // (`Box::<str>::from((*policy).as_str())`) or a
11086        // `Box::<str>::from(policy.as_str())` open-code whose
11087        // type bounds have no compile-time link back to the
11088        // substrate primitive.
11089        //
11090        // Fourth (and closing) peer on the substrate-wide trait-
11091        // idiomatic [`Box<str>`] forward-projection family on the
11092        // M2 OTP-shape tier — closes the `{Self, &Self}` input-
11093        // shape corner of the [`Box<str>`] axis on the second (and
11094        // third-and-final) M2 OTP-shape closed-set fieldless typed
11095        // enum peer on the caixa surface (`:children :restart`),
11096        // exactly as b4dc55c closed the paired [`Cow<'static, str>`]
11097        // axis one commit after its owning half (0612398) landed
11098        // on this enum. Every remaining closed-set fieldless typed
11099        // enum peer on the M3 mesh-shape / outside-M3 caixa-core /
11100        // render-side / outside-caixa-core tiers is a future
11101        // target of the campaign.
11102        //
11103        // Also byte-parity witness against the paired owned-input
11104        // [`From<RestartPolicy> for Box<str>`] and the sibling
11105        // borrowed-input [`From<&RestartPolicy> for &'static str`],
11106        // [`From<&RestartPolicy> for String`], and
11107        // [`From<&RestartPolicy> for Cow<'static, str>`]
11108        // return-shape axes — locking the four
11109        // return-shape × input-shape paths together by construction
11110        // so any future detour trips at caixa-core test time. Then a
11111        // `.iter().map(Box::<str>::from)` pipe witness over
11112        // [`super::RestartPolicy::ALL`] — whose iterator yields
11113        // `&RestartPolicy` by construction, so the borrowed-input
11114        // [`Box<str>`] axis is what routes the pipe through the
11115        // substrate-primitive [`super::RestartPolicy::as_str`]
11116        // accessor without a spurious [`Copy`] deref (which would
11117        // only be reachable through the owned-input
11118        // [`From<RestartPolicy> for Box<str>`] axis by first
11119        // calling `.copied()` on the iterator).
11120        for &variant in RestartPolicy::ALL {
11121            let via_trait: Box<str> = <Box<str> as From<&RestartPolicy>>::from(&variant);
11122            let via_method: &'static str = variant.as_str();
11123            assert_eq!(
11124                via_trait.as_ref(),
11125                via_method,
11126                "From<&RestartPolicy> for Box<str> impl must round-\
11127                 trip &RestartPolicy::{variant:?} to the same lifted \
11128                 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
11129                 returns — divergence signals a silent detour off the \
11130                 substrate-primitive accessor"
11131            );
11132            let via_into: Box<str> = (&variant).into();
11133            assert_eq!(
11134                via_into.as_ref(),
11135                via_method,
11136                "Into<Box<str>>::into on &RestartPolicy::{variant:?} \
11137                 must byte-equal RestartPolicy::as_str on the same \
11138                 input — the blanket-derived Into shape must resolve \
11139                 to the same as_str dispatch as the explicit From impl"
11140            );
11141            let owned_box: Box<str> = <Box<str> as From<RestartPolicy>>::from(variant);
11142            assert_eq!(
11143                via_trait, owned_box,
11144                "From<&RestartPolicy> for Box<str> and \
11145                 From<RestartPolicy> for Box<str> must resolve \
11146                 identically on RestartPolicy::{variant:?} — \
11147                 divergence signals the borrowed-input and owned-input \
11148                 Box<str> forward-projection input-shape paths have \
11149                 drifted onto different emit-sets"
11150            );
11151            let borrowed_static: &'static str =
11152                <&'static str as From<&RestartPolicy>>::from(&variant);
11153            assert_eq!(
11154                via_trait.as_ref(),
11155                borrowed_static,
11156                "From<&RestartPolicy> for Box<str> and \
11157                 From<&RestartPolicy> for &'static str must resolve \
11158                 identically on RestartPolicy::{variant:?} — \
11159                 divergence signals the borrowed-input Box<str> and \
11160                 &'static str return-shape paths have drifted onto \
11161                 different emit-sets"
11162            );
11163            let borrowed_string: String = <String as From<&RestartPolicy>>::from(&variant);
11164            assert_eq!(
11165                via_trait.as_ref(),
11166                borrowed_string.as_str(),
11167                "From<&RestartPolicy> for Box<str> and \
11168                 From<&RestartPolicy> for String must resolve \
11169                 identically on RestartPolicy::{variant:?} — \
11170                 divergence signals the borrowed-input Box<str> and \
11171                 owned-`String` return-shape paths have drifted onto \
11172                 different emit-sets"
11173            );
11174            let borrowed_cow: std::borrow::Cow<'static, str> =
11175                <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&variant);
11176            assert_eq!(
11177                via_trait.as_ref(),
11178                borrowed_cow.as_ref(),
11179                "From<&RestartPolicy> for Box<str> and \
11180                 From<&RestartPolicy> for Cow<'static, str> must \
11181                 resolve identically on RestartPolicy::{variant:?} — \
11182                 divergence signals the borrowed-input Box<str> and \
11183                 Cow<'static, str> return-shape paths have drifted \
11184                 onto different emit-sets"
11185            );
11186        }
11187        let via_iter: Vec<Box<str>> = RestartPolicy::ALL.iter().map(Box::<str>::from).collect();
11188        let via_method: Vec<Box<str>> = RestartPolicy::ALL
11189            .iter()
11190            .map(|p| Box::<str>::from(p.as_str()))
11191            .collect();
11192        assert_eq!(
11193            via_iter, via_method,
11194            "`.iter().map(Box::<str>::from)` over \
11195             RestartPolicy::ALL — a call site whose iteration axis \
11196             holds `&RestartPolicy` by construction — must byte-\
11197             equal `.iter().map(|p| Box::<str>::from(p.as_str()))` \
11198             on every arm — the borrowed-input Box<str> \
11199             `From<&RestartPolicy> for Box<str>` axis is what \
11200             makes the `Box::<str>::from` composition route through \
11201             the substrate-primitive `RestartPolicy::as_str` \
11202             accessor without a spurious `Copy` deref (which would \
11203             only be reachable through the owned-input \
11204             `From<RestartPolicy> for Box<str>` axis by first \
11205             calling `.copied()` on the iterator)"
11206        );
11207    }
11208
11209    #[test]
11210    fn restart_policy_from_into_arc_str_routes_through_as_str_accessor() {
11211        // Fail-before-pass-after byte-parity pin on the newly lifted
11212        // `impl From<RestartPolicy> for std::sync::Arc<str>` — asserts
11213        // the owned-input standard-library trait impl and the
11214        // substrate-primitive [`super::RestartPolicy::as_str`]
11215        // `pub const fn` accessor resolve to the same three-arm emit-
11216        // set across every arm the exhaustive
11217        // [`super::RestartPolicy::ALL`] slice enumerates. Extends the
11218        // substrate-wide [`std::sync::Arc<str>`] forward-projection
11219        // campaign tier opened one projection tier prior (bca2ec8) on
11220        // the paired sibling-restart [`RestartStrategy`] owned-input
11221        // first-mover onto the second (and third-and-final) M2 OTP-
11222        // shape closed-set fieldless typed enum peer on the caixa
11223        // surface (`:children :restart`), immediately after the paired
11224        // [`Box<str>`] axis (0a1b313 / cb1d068) closed the
11225        // `{Self, &Self} × {&'static str, String, Cow<'static, str>,
11226        // Box<str>}` 2×4 corner on this enum. Rust's standard library
11227        // carries `impl From<&str> for std::sync::Arc<str>` and
11228        // `impl From<String> for std::sync::Arc<str>` but no blanket
11229        // `impl<T: AsRef<str>> From<T> for std::sync::Arc<str>` (nor
11230        // an `impl<T: fmt::Display> From<T> for std::sync::Arc<str>`),
11231        // so this axis is a distinct trait-idiomatic surface that a
11232        // `let key: std::sync::Arc<str> = policy.into();`-shaped call
11233        // site reaches through this impl and no other — a paired
11234        // `std::sync::Arc::<str>::from(policy.as_str())` open-code
11235        // has no compile-time link back to the substrate primitive,
11236        // and a two-step `std::sync::Arc::<str>::from(String::from(
11237        // policy))` composition through the owned-`String` axis
11238        // allocates twice (once into the intermediate `String`, once
11239        // into the [`Arc<str>`] on the `From<String>` conversion)
11240        // where the single-step trait impl allocates once.
11241        //
11242        // Cross-axis byte-parity witness against the sibling owned-
11243        // input `{&'static str, String, Cow<'static, str>, Box<str>}`
11244        // return-shape axes — locking the five return-shape paths on
11245        // the owned-input surface together by construction so any
11246        // future detour off the substrate-primitive
11247        // [`super::RestartPolicy::as_str`] accessor trips at caixa-
11248        // core test time.
11249        for &variant in RestartPolicy::ALL {
11250            let via_trait: std::sync::Arc<str> =
11251                <std::sync::Arc<str> as From<RestartPolicy>>::from(variant);
11252            let via_method: &'static str = variant.as_str();
11253            assert_eq!(
11254                via_trait.as_ref(),
11255                via_method,
11256                "From<RestartPolicy> for std::sync::Arc<str> impl \
11257                 must round-trip RestartPolicy::{variant:?} to the \
11258                 same lifted SUPERVISOR_CHILD_RESTART_* const \
11259                 RestartPolicy::as_str returns — divergence signals \
11260                 a silent detour off the substrate-primitive accessor"
11261            );
11262            let via_into: std::sync::Arc<str> = variant.into();
11263            assert_eq!(
11264                via_into.as_ref(),
11265                via_method,
11266                "Into<std::sync::Arc<str>>::into on \
11267                 RestartPolicy::{variant:?} must byte-equal \
11268                 RestartPolicy::as_str on the same input — the \
11269                 blanket-derived Into shape must resolve to the same \
11270                 as_str dispatch as the explicit From impl"
11271            );
11272            let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
11273            assert_eq!(
11274                via_trait.as_ref(),
11275                owned_static,
11276                "From<RestartPolicy> for std::sync::Arc<str> and \
11277                 From<RestartPolicy> for &'static str must resolve \
11278                 identically on RestartPolicy::{variant:?} — \
11279                 divergence signals the owned-input std::sync::Arc<str> \
11280                 and &'static str return-shape paths have drifted onto \
11281                 different emit-sets"
11282            );
11283            let owned_string: String = <String as From<RestartPolicy>>::from(variant);
11284            assert_eq!(
11285                via_trait.as_ref(),
11286                owned_string.as_str(),
11287                "From<RestartPolicy> for std::sync::Arc<str> and \
11288                 From<RestartPolicy> for String must resolve \
11289                 identically on RestartPolicy::{variant:?} — \
11290                 divergence signals the owned-input std::sync::Arc<str> \
11291                 and owned-`String` return-shape paths have drifted \
11292                 onto different emit-sets"
11293            );
11294            let owned_cow: std::borrow::Cow<'static, str> =
11295                <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
11296            assert_eq!(
11297                via_trait.as_ref(),
11298                owned_cow.as_ref(),
11299                "From<RestartPolicy> for std::sync::Arc<str> and \
11300                 From<RestartPolicy> for Cow<'static, str> must \
11301                 resolve identically on RestartPolicy::{variant:?} — \
11302                 divergence signals the owned-input std::sync::Arc<str> \
11303                 and Cow<'static, str> return-shape paths have drifted \
11304                 onto different emit-sets"
11305            );
11306            let owned_box: Box<str> = <Box<str> as From<RestartPolicy>>::from(variant);
11307            assert_eq!(
11308                via_trait.as_ref(),
11309                owned_box.as_ref(),
11310                "From<RestartPolicy> for std::sync::Arc<str> and \
11311                 From<RestartPolicy> for Box<str> must resolve \
11312                 identically on RestartPolicy::{variant:?} — \
11313                 divergence signals the owned-input std::sync::Arc<str> \
11314                 and Box<str> return-shape paths have drifted onto \
11315                 different emit-sets"
11316            );
11317        }
11318    }
11319
11320    #[test]
11321    fn restart_policy_from_borrowed_into_arc_str_routes_through_as_str_accessor() {
11322        // Fail-before-pass-after byte-parity pin on the newly lifted
11323        // `impl From<&RestartPolicy> for std::sync::Arc<str>` —
11324        // asserts the borrowed-input standard-library trait impl and
11325        // the substrate-primitive [`super::RestartPolicy::as_str`]
11326        // `pub const fn` accessor resolve to the same three-arm
11327        // emit-set across every arm the exhaustive
11328        // [`super::RestartPolicy::ALL`] slice enumerates. Rust's
11329        // standard library carries `impl From<&str> for
11330        // std::sync::Arc<str>` and `impl From<String> for
11331        // std::sync::Arc<str>` but no blanket
11332        // `impl<T: AsRef<str>> From<&T> for std::sync::Arc<str>` (nor
11333        // a `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`),
11334        // so the borrowed-input [`std::sync::Arc<str>`] forward-
11335        // projection axis is a distinct trait-idiomatic surface that
11336        // a `let key: std::sync::Arc<str> = (&policy).into();`-shaped
11337        // call site or a
11338        // `RestartPolicy::ALL.iter().map(std::sync::Arc::<str>::from)`-
11339        // shaped pipe reaches through this impl and no other — the
11340        // paired owned-input [`From<RestartPolicy> for
11341        // std::sync::Arc<str>`] impl (b05724e) forces every borrowed-
11342        // input call site through an explicit [`Copy`] deref
11343        // (`std::sync::Arc::<str>::from((*policy).as_str())`) or a
11344        // `std::sync::Arc::<str>::from(policy.as_str())` open-code
11345        // whose type bounds have no compile-time link back to the
11346        // substrate primitive.
11347        //
11348        // Closes the `{Self, &Self}` input-shape corner of the
11349        // substrate-wide trait-idiomatic [`std::sync::Arc<str>`]
11350        // forward-projection family on the second (and third-and-
11351        // final) M2 OTP-shape closed-set fieldless typed enum peer
11352        // on the caixa surface (`:children :restart`), one commit
11353        // after b05724e opened the owned-input half — exactly as
11354        // b3e72d7 closed the paired [`std::sync::Arc<str>`] corner on
11355        // the sibling-restart [`RestartStrategy`] first-mover one
11356        // commit after its owning half (bca2ec8) landed, and as
11357        // cb1d068 closed the paired [`Box<str>`] corner on this
11358        // enum one commit after its owning half (0a1b313) landed.
11359        //
11360        // Also byte-parity witness against the paired owned-input
11361        // [`From<RestartPolicy> for std::sync::Arc<str>`] and the
11362        // sibling borrowed-input [`From<&RestartPolicy> for
11363        // &'static str`], [`From<&RestartPolicy> for String`],
11364        // [`From<&RestartPolicy> for Cow<'static, str>`], and
11365        // [`From<&RestartPolicy> for Box<str>`] return-shape axes —
11366        // locking the five return-shape × input-shape paths together
11367        // by construction so any future detour off the substrate-
11368        // primitive [`super::RestartPolicy::as_str`] accessor trips
11369        // at caixa-core test time. Then a
11370        // `.iter().map(std::sync::Arc::<str>::from)` pipe witness
11371        // over [`super::RestartPolicy::ALL`] — whose iterator yields
11372        // `&RestartPolicy` by construction, so the borrowed-input
11373        // [`std::sync::Arc<str>`] axis is what routes the pipe
11374        // through the substrate-primitive
11375        // [`super::RestartPolicy::as_str`] accessor without a
11376        // spurious [`Copy`] deref (which would only be reachable
11377        // through the owned-input
11378        // [`From<RestartPolicy> for std::sync::Arc<str>`] axis by
11379        // first calling `.copied()` on the iterator).
11380        for &variant in RestartPolicy::ALL {
11381            let via_trait: std::sync::Arc<str> =
11382                <std::sync::Arc<str> as From<&RestartPolicy>>::from(&variant);
11383            let via_method: &'static str = variant.as_str();
11384            assert_eq!(
11385                via_trait.as_ref(),
11386                via_method,
11387                "From<&RestartPolicy> for std::sync::Arc<str> impl \
11388                 must round-trip &RestartPolicy::{variant:?} to the \
11389                 same lifted SUPERVISOR_CHILD_RESTART_* const \
11390                 RestartPolicy::as_str returns — divergence signals \
11391                 a silent detour off the substrate-primitive accessor"
11392            );
11393            let via_into: std::sync::Arc<str> = (&variant).into();
11394            assert_eq!(
11395                via_into.as_ref(),
11396                via_method,
11397                "Into<std::sync::Arc<str>>::into on \
11398                 &RestartPolicy::{variant:?} must byte-equal \
11399                 RestartPolicy::as_str on the same input — the \
11400                 blanket-derived Into shape must resolve to the same \
11401                 as_str dispatch as the explicit From impl"
11402            );
11403            let owned_arc: std::sync::Arc<str> =
11404                <std::sync::Arc<str> as From<RestartPolicy>>::from(variant);
11405            assert_eq!(
11406                via_trait, owned_arc,
11407                "From<&RestartPolicy> for std::sync::Arc<str> and \
11408                 From<RestartPolicy> for std::sync::Arc<str> must \
11409                 resolve identically on RestartPolicy::{variant:?} — \
11410                 divergence signals the borrowed-input and owned-input \
11411                 std::sync::Arc<str> forward-projection input-shape \
11412                 paths have drifted onto different emit-sets"
11413            );
11414            let borrowed_static: &'static str =
11415                <&'static str as From<&RestartPolicy>>::from(&variant);
11416            assert_eq!(
11417                via_trait.as_ref(),
11418                borrowed_static,
11419                "From<&RestartPolicy> for std::sync::Arc<str> and \
11420                 From<&RestartPolicy> for &'static str must resolve \
11421                 identically on RestartPolicy::{variant:?} — \
11422                 divergence signals the borrowed-input std::sync::Arc<str> \
11423                 and &'static str return-shape paths have drifted onto \
11424                 different emit-sets"
11425            );
11426            let borrowed_string: String = <String as From<&RestartPolicy>>::from(&variant);
11427            assert_eq!(
11428                via_trait.as_ref(),
11429                borrowed_string.as_str(),
11430                "From<&RestartPolicy> for std::sync::Arc<str> and \
11431                 From<&RestartPolicy> for String must resolve \
11432                 identically on RestartPolicy::{variant:?} — \
11433                 divergence signals the borrowed-input std::sync::Arc<str> \
11434                 and owned-`String` return-shape paths have drifted \
11435                 onto different emit-sets"
11436            );
11437            let borrowed_cow: std::borrow::Cow<'static, str> =
11438                <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&variant);
11439            assert_eq!(
11440                via_trait.as_ref(),
11441                borrowed_cow.as_ref(),
11442                "From<&RestartPolicy> for std::sync::Arc<str> and \
11443                 From<&RestartPolicy> for Cow<'static, str> must \
11444                 resolve identically on RestartPolicy::{variant:?} — \
11445                 divergence signals the borrowed-input std::sync::Arc<str> \
11446                 and Cow<'static, str> return-shape paths have drifted \
11447                 onto different emit-sets"
11448            );
11449            let borrowed_box: Box<str> = <Box<str> as From<&RestartPolicy>>::from(&variant);
11450            assert_eq!(
11451                via_trait.as_ref(),
11452                borrowed_box.as_ref(),
11453                "From<&RestartPolicy> for std::sync::Arc<str> and \
11454                 From<&RestartPolicy> for Box<str> must resolve \
11455                 identically on RestartPolicy::{variant:?} — \
11456                 divergence signals the borrowed-input std::sync::Arc<str> \
11457                 and Box<str> return-shape paths have drifted onto \
11458                 different emit-sets"
11459            );
11460        }
11461        let via_iter: Vec<std::sync::Arc<str>> = RestartPolicy::ALL
11462            .iter()
11463            .map(std::sync::Arc::<str>::from)
11464            .collect();
11465        let via_method: Vec<std::sync::Arc<str>> = RestartPolicy::ALL
11466            .iter()
11467            .map(|p| std::sync::Arc::<str>::from(p.as_str()))
11468            .collect();
11469        assert_eq!(
11470            via_iter, via_method,
11471            "`.iter().map(std::sync::Arc::<str>::from)` over \
11472             RestartPolicy::ALL — a call site whose iteration axis \
11473             holds `&RestartPolicy` by construction — must byte-\
11474             equal `.iter().map(|p| std::sync::Arc::<str>::from(p.as_str()))` \
11475             on every arm — the borrowed-input std::sync::Arc<str> \
11476             `From<&RestartPolicy> for std::sync::Arc<str>` axis is \
11477             what makes the `std::sync::Arc::<str>::from` composition \
11478             route through the substrate-primitive \
11479             `RestartPolicy::as_str` accessor without a spurious \
11480             `Copy` deref (which would only be reachable through the \
11481             owned-input `From<RestartPolicy> for std::sync::Arc<str>` \
11482             axis by first calling `.copied()` on the iterator)"
11483        );
11484    }
11485
11486    // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_RESTART_* identity ─
11487
11488    #[test]
11489    fn restart_policy_variants_serialize_to_lifted_scalar_values() {
11490        // The fail-before-pass-after pin: pre-lift there was no
11491        // single-source binding between the [`RestartPolicy`] variant
11492        // name the un-`rename`d `Serialize` derive emits under
11493        // [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
11494        // byte-string every downstream cluster-side dispatcher (the
11495        // future wasm-operator's per-child post-exit restart-decision
11496        // branch, the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
11497        // materializer's admission-time enum-arm bind, the
11498        // `caixa-operator`'s hierarchical reconciliation scheduler's
11499        // per-child-policy fan-out) probes verbatim. A future
11500        // `#[serde(rename_all = "kebab-case")]` attribute on the enum —
11501        // or a per-variant `#[serde(rename = "…")]` override, or a
11502        // variant rename in the source — would silently rebrand the
11503        // emitted scalar under one spelling while every downstream
11504        // dispatcher still probed the other, with the failure surfacing
11505        // at the operator's reconcile posture (children coming up under
11506        // the `default()` `Permanent` arm rather than the typed slot's
11507        // declared policy — a `:temporary` `oneShot` child would be
11508        // restarted on clean exit, treating the successful-completion
11509        // signal as failure and re-running the completion-terminal
11510        // one-shot indefinitely; a `:transient` child that clean-exited
11511        // would be restarted, masking the clean-completion contract)
11512        // far from the source rebrand commit and with no field naming
11513        // the drift. Pinning the two paths (the `Serialize` derive's
11514        // serialized string AND the [`RestartPolicy::as_str`] helper)
11515        // to the same three lifted
11516        // [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
11517        // [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
11518        // [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
11519        // byte-strings makes any future drift on either endpoint fail
11520        // here at caixa-core build time. Peer of the sibling
11521        // [`restart_strategy_variants_serialize_to_lifted_scalar_values`]
11522        // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
11523        // and the M3
11524        // `placement_strategy_variants_serialize_to_lifted_scalar_values`
11525        // (3f0e21c) on the per-Aplicacao distribution-strategy axis —
11526        // same three-path-convergence discipline, extended to close the
11527        // third OTP-shaped closed-enum discriminator axis on the caixa
11528        // typed surface (per-child restart-decision policy).
11529        for (variant, expected) in [
11530            (
11531                RestartPolicy::Permanent,
11532                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
11533            ),
11534            (
11535                RestartPolicy::Temporary,
11536                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
11537            ),
11538            (
11539                RestartPolicy::Transient,
11540                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
11541            ),
11542        ] {
11543            let json = serde_json::to_string(&variant).unwrap();
11544            assert_eq!(
11545                json,
11546                format!("\"{expected}\""),
11547                "RestartPolicy::{variant:?} must serialize to {expected:?}"
11548            );
11549            assert_eq!(
11550                variant.as_str(),
11551                expected,
11552                "RestartPolicy::{variant:?}.as_str() must return the lifted \
11553                 SUPERVISOR_CHILD_RESTART_* constant"
11554            );
11555        }
11556    }
11557
11558    #[test]
11559    fn supervisor_child_restart_consts_are_pairwise_distinct() {
11560        // Cross-arm drift-detection pin: a future collapse of two
11561        // canonical variant byte-strings onto the same value (e.g. an
11562        // accidental copy-paste flip of `SUPERVISOR_CHILD_RESTART_TRANSIENT`
11563        // to also read `"Permanent"`) would silently reroute every
11564        // downstream operator's per-child-policy dispatch onto the
11565        // sibling arm's reconcile branch and pass every propagation-probe
11566        // test that expected only the stale arm's value — a `:transient`
11567        // child would come up under the `:permanent` restart-decision
11568        // posture on every subsequent clean exit, so a completion-terminal
11569        // child would be restarted indefinitely against its declared
11570        // policy. Peer of the sibling
11571        // [`supervisor_estrategia_consts_are_pairwise_distinct`]
11572        // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
11573        // and the four-way distinct pin
11574        // `supervisor_key_consts_are_pairwise_distinct` (40cc4e5) on the
11575        // top-level `SUPERVISOR_KEY_*` axis.
11576        let all = [
11577            crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
11578            crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
11579            crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
11580        ];
11581        for (i, a) in all.iter().enumerate() {
11582            for (j, b) in all.iter().enumerate() {
11583                if i != j {
11584                    assert_ne!(
11585                        a, b,
11586                        "SUPERVISOR_CHILD_RESTART_* consts must be pairwise distinct \
11587                         — got duplicate {a:?} at indices {i} and {j}",
11588                    );
11589                }
11590            }
11591        }
11592    }
11593
11594    #[test]
11595    fn restart_policy_display_routes_through_as_str_helper() {
11596        // The fail-before-pass-after pin on the first half of the
11597        // three-path convergence: pre-convergence [`RestartPolicy`]
11598        // carried a [`std::fmt::Display`] surface via its
11599        // `#[discriminant(also_display)]` gen-platform derive route,
11600        // which arrived kebab-case as `"permanent"` / `"temporary"`
11601        // / `"transient"` on this three-arm enum (whose variant
11602        // names each collapse to their own lowercase form under the
11603        // kebab-case transform) while the wire format ran as
11604        // PascalCase `"Permanent"` / `"Temporary"` / `"Transient"`
11605        // through the un-`rename`d serde derive. Every consumer
11606        // reaching for a policy byte-string past the wire format had
11607        // to pick between three paths ([`RestartPolicy::as_str`],
11608        // the `Serialize` derive's serialized string, or
11609        // `format!("{v}")` on the discriminant-Display route), any
11610        // two of which a future variant rename or
11611        // `#[serde(rename_all = "kebab-case")]` attribute would
11612        // silently desynchronize. Wiring [`std::fmt::Display`]
11613        // through [`RestartPolicy::as_str`] closes the third path:
11614        // every `format!("{v}")` call reaches the same lifted
11615        // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the
11616        // wire format and the [`RestartPolicy::as_str`] helper
11617        // already route through, so a future variant rename lands at
11618        // exactly one place. Pin the routing here so a future
11619        // `impl std::fmt::Display for RestartPolicy`
11620        // reimplementation that hand-rolls the arms instead of
11621        // delegating to [`RestartPolicy::as_str`] fails at
11622        // caixa-core build time. Peer of the sibling
11623        // [`restart_strategy_display_routes_through_as_str_helper`]
11624        // on the per-supervisor sibling-restart-strategy axis and
11625        // the M3
11626        // `placement_strategy_display_routes_through_as_str_helper`
11627        // (cc8f749) — the third of three OTP-shape closed-enum
11628        // discriminator axes on the caixa typed surface now
11629        // converged onto the same three-path
11630        // (Display → as_str → lifted const) discipline.
11631        for variant in [
11632            RestartPolicy::Permanent,
11633            RestartPolicy::Temporary,
11634            RestartPolicy::Transient,
11635        ] {
11636            assert_eq!(
11637                variant.to_string(),
11638                variant.as_str(),
11639                "RestartPolicy::{variant:?} Display must route through \
11640                 RestartPolicy::as_str (single source of truth: the lifted \
11641                 SUPERVISOR_CHILD_RESTART_* const the wire format also emits)"
11642            );
11643        }
11644    }
11645
11646    #[test]
11647    fn restart_policy_display_matches_serialized_wire_byte_string() {
11648        // The fail-before-pass-after pin on the second half of the
11649        // three-path convergence: `Display` (user-facing text) agrees
11650        // byte-for-byte with the `Serialize` derive's wire format
11651        // (canonical camelCase-schema `SUPERVISOR_CHILD_KEY_RESTART`
11652        // scalar) on every variant. Pre-convergence the two paths
11653        // were structurally independent — a future
11654        // `#[serde(rename_all = "kebab-case")]` attribute on the
11655        // enum would silently rebrand the emitted wire scalar
11656        // (`permanent`, `temporary`, `transient`) while every
11657        // consumer that pretty-prints the policy (the future
11658        // wasm-operator's per-child post-exit restart-decision
11659        // diagnostic line, the future `feira app graph` per-child
11660        // restart column, the future M4
11661        // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
11662        // per-child admission-webhook rejection body) would still
11663        // emit the PascalCase form the `as_str` / `Display` route
11664        // returns, with the mismatch surfacing at consumer parse
11665        // time / operator dispatch time far from the source rebrand
11666        // commit. Pin the two paths byte-for-byte here so any future
11667        // serde-attribute or variant-rename drift is a
11668        // caixa-core-build-time test failure at this call, not a
11669        // silent per-consumer dispatch miss. Peer of the sibling
11670        // [`restart_strategy_display_matches_serialized_wire_byte_string`]
11671        // on the per-supervisor sibling-restart-strategy axis and
11672        // the M3
11673        // `placement_strategy_display_matches_serialized_wire_byte_string`
11674        // (cc8f749).
11675        for variant in [
11676            RestartPolicy::Permanent,
11677            RestartPolicy::Temporary,
11678            RestartPolicy::Transient,
11679        ] {
11680            let wire = serde_json::to_string(&variant).unwrap();
11681            let unquoted = wire
11682                .strip_prefix('"')
11683                .and_then(|s| s.strip_suffix('"'))
11684                .expect("serialized RestartPolicy is a JSON string");
11685            assert_eq!(
11686                variant.to_string(),
11687                unquoted,
11688                "RestartPolicy::{variant:?} Display byte-string must match the \
11689                 Serialize derive's wire byte-string (three-path convergence: \
11690                 Display + as_str + Serialize all resolve to the same \
11691                 SUPERVISOR_CHILD_RESTART_* const)"
11692            );
11693        }
11694    }
11695
11696    #[test]
11697    fn restart_policy_as_ref_str_routes_through_as_str_accessor() {
11698        // Fail-before-pass-after byte-parity pin on the lifted
11699        // `impl AsRef<str> for RestartPolicy` — asserts the
11700        // standard-library trait impl and the substrate-primitive
11701        // [`RestartPolicy::as_str`] `pub const fn` accessor resolve
11702        // to the same `&str` per instance across the three-arm
11703        // closed set, so any future silent detour that routes the
11704        // impl through a divergent projection (a per-arm inline
11705        // `match self { RestartPolicy::Permanent => "Permanent", … }`
11706        // re-inlining that opens a compile-time link to the un-lifted
11707        // arm-literal, a swap onto the kebab-case
11708        // [`gen_platform::Discriminant`] catalog identity that would
11709        // collide the wire axis with the dispatcher-catalog axis) trips
11710        // at caixa-core test time under `PartialEq` rather than at a
11711        // downstream `impl AsRef<str>`-bound consumer's silent split.
11712        // Sweeps every one of the three arms
11713        // [`RestartPolicy::ALL`] carries so no arm's projection is
11714        // covered only by the sibling wire-format `Serialize` derive
11715        // path. Peer of the sibling
11716        // [`restart_strategy_as_ref_str_routes_through_as_str_accessor`]
11717        // (63eb1a4) on the paired per-supervisor sibling-restart-
11718        // strategy axis and the [`crate::CaixaVersion`]
11719        // `AsRef<str>`-byte-parity pin (16d5c7e) on the paired
11720        // top-level `:versao` typed newtype — the three pins together
11721        // cover the substrate primitive's `AsRef<str>` projection axis
11722        // on the paired newtype + M2 closed-set-typed-enum surface.
11723        for &variant in RestartPolicy::ALL {
11724            assert_eq!(
11725                <RestartPolicy as AsRef<str>>::as_ref(&variant),
11726                variant.as_str(),
11727                "AsRef<str> impl on RestartPolicy::{variant:?} must \
11728                 byte-equal RestartPolicy::as_str on the same instance \
11729                 — divergence signals a silent detour off the substrate-\
11730                 primitive accessor"
11731            );
11732        }
11733    }
11734
11735    #[test]
11736    fn restart_policy_as_ref_str_routes_through_display_via_shared_accessor() {
11737        // Fail-before-pass-after byte-parity pin on the three-path
11738        // convergence discipline the M2 per-child-restart-policy
11739        // primitive now carries on the `&str`-projection axis:
11740        // `<RestartPolicy as AsRef<str>>::as_ref(&v)` (the newly
11741        // lifted impl), `format!("{v}")` (the pre-existing
11742        // [`fmt::Display`] impl), and `v.as_str()` (the substrate-
11743        // primitive `pub const fn` accessor both trait impls delegate
11744        // through) must resolve to the same byte-string on every
11745        // instance across the three-arm closed set. Refuses any future
11746        // divergence between the two trait impls (a stray
11747        // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
11748        // rather than delegating through the shared accessor; a
11749        // hypothetical `AsRef<str>` rewrite that inlines a per-arm
11750        // literal cascade) that would silently split the two
11751        // projection paths of the same closed-set typed enum. Mirrors
11752        // the sibling three-path-convergence discipline the peer
11753        // [`RestartStrategy`] typed enum carries on its
11754        // `AsRef<str>` / `Display` / `as_str` triple
11755        // (supervisor.rs pin
11756        // `restart_strategy_as_ref_str_routes_through_display_via_shared_accessor`,
11757        // 63eb1a4) and the [`crate::CaixaVersion`] typed newtype
11758        // carries on the same triple (version.rs pin
11759        // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
11760        // 16d5c7e).
11761        for &variant in RestartPolicy::ALL {
11762            let via_as_ref: &str = <RestartPolicy as AsRef<str>>::as_ref(&variant);
11763            let via_display: String = format!("{variant}");
11764            let via_accessor: &str = variant.as_str();
11765            assert_eq!(via_as_ref, via_accessor);
11766            assert_eq!(via_display, via_accessor);
11767            assert_eq!(via_as_ref, via_display.as_str());
11768        }
11769    }
11770
11771    #[test]
11772    fn restart_policy_all_enumerates_every_variant_exactly_once() {
11773        // Fail-before-pass-after pin on the [`RestartPolicy::ALL`]
11774        // exhaustive-iteration surface: every variant appears exactly
11775        // once, and the slice length matches the arm count of the
11776        // closed set. Every consumer that walks the accepted-policy
11777        // set (a future `feira supervisor --restart …` CLI-side
11778        // arg-parse's "did you mean" hint, a future M4 admission-
11779        // webhook's per-child rejection body naming the accepted-
11780        // `:restart` list, the [`RestartPolicy::from_wire`] reverse-
11781        // projection consumers that iterate the accept-set for
11782        // diagnostic rendering) reads through this slice, so a future
11783        // arm addition that grows the enum but forgets to grow
11784        // [`Self::ALL`] silently truncates every downstream consumer's
11785        // accept-set at the same pre-addition boundary — this pin
11786        // fails at caixa-core build time on the pairwise-distinct +
11787        // arm-count invariants.
11788        //
11789        // Peer of the sibling [`RestartStrategy::ALL`] (4eec29c) /
11790        // [`crate::CaixaKind::ALL`] (6b1f4fb) /
11791        // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
11792        // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
11793        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
11794        // pins on the peer closed-set typed-enum axes.
11795        let all: &[RestartPolicy] = RestartPolicy::ALL;
11796        assert_eq!(
11797            all.len(),
11798            3,
11799            "RestartPolicy::ALL must enumerate every variant of the \
11800             three-arm closed set (Permanent, Temporary, Transient); \
11801             got {all:?}"
11802        );
11803        for (i, a) in all.iter().enumerate() {
11804            for (j, b) in all.iter().enumerate() {
11805                if i != j {
11806                    assert_ne!(
11807                        a, b,
11808                        "RestartPolicy::ALL must carry every variant exactly \
11809                         once — got duplicate {a:?} at indices {i} and {j}"
11810                    );
11811                }
11812            }
11813        }
11814        for variant in [
11815            RestartPolicy::Permanent,
11816            RestartPolicy::Temporary,
11817            RestartPolicy::Transient,
11818        ] {
11819            assert!(
11820                all.contains(&variant),
11821                "RestartPolicy::ALL must contain {variant:?} — a future arm \
11822                 addition that grows the enum but forgets to grow the ALL slice \
11823                 silently truncates every downstream consumer's accept-set at \
11824                 the pre-addition boundary"
11825            );
11826        }
11827    }
11828
11829    #[test]
11830    fn restart_policy_from_wire_accepts_every_lifted_constant() {
11831        // Fail-before-pass-after pin on the forward accept-set of the
11832        // [`RestartPolicy::from_wire`] reverse projection: every
11833        // canonical [`crate::render::SUPERVISOR_CHILD_RESTART_*`]
11834        // constant the [`RestartPolicy::as_str`] emitter walks parses
11835        // back to its paired variant. Any future arm addition that
11836        // grows the emitter's `as_str` match but forgets to grow the
11837        // parser's `from_wire` match silently splits the two halves of
11838        // the round-trip — the wire byte-string one non-serde consumer
11839        // parses from the one the emitter wrote — with the failure
11840        // surfacing at the operator's reconcile posture (a `:temporary`
11841        // `oneShot` child restarted on clean exit, a `:transient` child
11842        // restarted after clean completion) far from the rebrand
11843        // commit. Pinning the three-arm accept-set here catches the
11844        // drift at caixa-core build time.
11845        //
11846        // Peer of the sibling [`RestartStrategy::from_wire`] (4eec29c)
11847        // + [`crate::CaixaKind::from_wire`] (2aa6d23)
11848        // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
11849        // accept-set pins on the peer closed-set typed-enum `str → Self`
11850        // axes.
11851        for (wire, expected) in [
11852            (
11853                crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
11854                RestartPolicy::Permanent,
11855            ),
11856            (
11857                crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
11858                RestartPolicy::Temporary,
11859            ),
11860            (
11861                crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
11862                RestartPolicy::Transient,
11863            ),
11864        ] {
11865            let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
11866                panic!(
11867                    "RestartPolicy::from_wire({wire:?}) must accept every \
11868                     SUPERVISOR_CHILD_RESTART_* constant — got None for the \
11869                     lifted canonical byte-string that RestartPolicy::{expected:?} \
11870                     serializes as under SUPERVISOR_CHILD_KEY_RESTART"
11871                )
11872            });
11873            assert_eq!(
11874                parsed, expected,
11875                "RestartPolicy::from_wire({wire:?}) must return \
11876                 RestartPolicy::{expected:?}; got RestartPolicy::{parsed:?}"
11877            );
11878        }
11879    }
11880
11881    #[test]
11882    fn restart_policy_from_wire_round_trips_through_as_str() {
11883        // Fail-before-pass-after pin on the closed round-trip between
11884        // the forward [`RestartPolicy::as_str`] emitter and the
11885        // reverse [`RestartPolicy::from_wire`] parser: for every
11886        // variant in [`RestartPolicy::ALL`], parsing the emitter's
11887        // output must return exactly the same variant. Any per-arm
11888        // divergence — a future arm added to `as_str` but not
11889        // `from_wire`, an accidental copy-paste flip in one but not
11890        // the other — silently splits the emit and parse halves and
11891        // the failure surfaces at consumer parse time far from the
11892        // drift site. The `ALL`-iterating shape means a future arm
11893        // addition picks up the coverage by construction.
11894        //
11895        // Peer of the sibling
11896        // [`restart_strategy_from_wire_round_trips_through_as_str`]
11897        // (4eec29c) round-trip pin on
11898        // [`RestartStrategy::from_wire`] and the M3
11899        // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
11900        // (18c7342) round-trip pin on
11901        // [`crate::aplicacao::PlacementStrategy::from_wire`].
11902        for &variant in RestartPolicy::ALL {
11903            let wire = variant.as_str();
11904            let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
11905                panic!(
11906                    "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
11907                     must be Some({variant:?}) — the two halves of the round-trip \
11908                     dispatch on the same lifted SUPERVISOR_CHILD_RESTART_* consts; \
11909                     got None on wire byte-string {wire:?}"
11910                )
11911            });
11912            assert_eq!(
11913                parsed, variant,
11914                "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
11915                 must round-trip to the same variant; got {parsed:?}"
11916            );
11917        }
11918    }
11919
11920    #[test]
11921    fn restart_policy_from_wire_rejects_unknown_byte_strings() {
11922        // Fail-before-pass-after pin on the closed-set refusal
11923        // discipline of [`RestartPolicy::from_wire`]: every
11924        // byte-string outside the three-arm accept-set returns `None`
11925        // rather than silently collapsing onto the [`Default`]
11926        // (`Permanent`) arm or an arbitrary neighbor. The refusal set
11927        // exercised here sweeps the load-bearing drift shapes: the
11928        // empty string (a stripped serde-attribute drift), all-
11929        // whitespace strings (the canonical text-editor accidental
11930        // padding shape), the kebab-case dispatcher-catalog identities
11931        // (`"permanent"` / `"temporary"` / `"transient"` — the
11932        // [`gen_platform::FromStrKind`]-derived [`std::str::FromStr`]
11933        // accept-set, which parses the *other* axis of this enum's
11934        // two-axis split and must not leak into the `from_wire`
11935        // PascalCase-wire accept-set — a lowercase leak here would
11936        // silently accept the operator's kebab-case
11937        // dispatcher-catalog probe under the wire-axis parser and mis-
11938        // route a `:permanent` intent), the padded canonical scalar
11939        // (`" Permanent "`), the trailing-newline shapes
11940        // (`"Permanent\n"`), the uppercase-single-word forms
11941        // (`"PERMANENT"`), and neighboring-but-unknown arms
11942        // (`"Restart"` — the canonical typo direction toward the
11943        // sibling [`RestartStrategy`] enum's own wire-arm namespace).
11944        //
11945        // Peer of the sibling
11946        // [`restart_strategy_from_wire_rejects_unknown_byte_strings`]
11947        // (4eec29c) +
11948        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
11949        // (2aa6d23) +
11950        // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
11951        // (18c7342) refusal pins on the peer closed-set typed-enum
11952        // axes.
11953        for bad in [
11954            "",
11955            " ",
11956            "\n",
11957            "\t",
11958            "permanent",
11959            "temporary",
11960            "transient",
11961            "PERMANENT",
11962            "TEMPORARY",
11963            "TRANSIENT",
11964            "Permanents",
11965            "Permanent ",
11966            " Permanent",
11967            " Transient ",
11968            "Permanent\n",
11969            "perma",
11970            "Trans",
11971            "OneForOne",
11972            "Restart",
11973            "?",
11974        ] {
11975            assert!(
11976                RestartPolicy::from_wire(bad).is_none(),
11977                "RestartPolicy::from_wire({bad:?}) must return None — the \
11978                 parser's accept-set is exactly the three RestartPolicy::as_str \
11979                 outputs (Permanent, Temporary, Transient), and this \
11980                 byte-string is outside that closed set"
11981            );
11982        }
11983    }
11984
11985    #[test]
11986    fn restart_policy_from_wire_matches_serialize_derive_wire_byte_string() {
11987        // Fail-before-pass-after pin on the fourth path of the four-path
11988        // convergence: `from_wire` (the reverse projection) inverts the
11989        // `Serialize` derive's wire byte-string on every variant.
11990        // Together with the pre-existing three-path convergence
11991        // (`Display` + `as_str` + `Serialize` all resolve to the same
11992        // lifted [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const,
11993        // pinned by
11994        // [`restart_policy_display_matches_serialized_wire_byte_string`])
11995        // this closes the round-trip: the wire byte-string the
11996        // `Serialize` derive emits parses back to the same variant
11997        // through `from_wire`, so any future serde-attribute or variant-
11998        // rename drift on the emit half now surfaces as a matched drift
11999        // on the parse half at caixa-core build time — the two halves
12000        // migrate as a unit through the lifted consts on any future
12001        // rename, and the round-trip cannot silently split.
12002        //
12003        // Peer of the sibling
12004        // [`restart_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
12005        // (4eec29c) wire-format pin on
12006        // [`RestartStrategy::from_wire`] and the M3
12007        // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
12008        // (18c7342) wire-format pin on
12009        // [`crate::aplicacao::PlacementStrategy::from_wire`].
12010        for &variant in RestartPolicy::ALL {
12011            let wire = serde_json::to_string(&variant).unwrap();
12012            let unquoted = wire
12013                .strip_prefix('"')
12014                .and_then(|s| s.strip_suffix('"'))
12015                .expect("serialized RestartPolicy is a JSON string");
12016            let parsed = RestartPolicy::from_wire(unquoted).unwrap_or_else(|| {
12017                panic!(
12018                    "RestartPolicy::from_wire({unquoted:?}) must accept the \
12019                     Serialize derive's wire byte-string for \
12020                     RestartPolicy::{variant:?} — the four-path convergence \
12021                     (Display + as_str + Serialize + from_wire) resolves through \
12022                     the same lifted SUPERVISOR_CHILD_RESTART_* const; got None"
12023                )
12024            });
12025            assert_eq!(
12026                parsed, variant,
12027                "RestartPolicy::from_wire of the Serialize derive's wire \
12028                 byte-string for RestartPolicy::{variant:?} must round-trip \
12029                 to the same variant; got {parsed:?}"
12030            );
12031        }
12032    }
12033
12034    // ── drift-detection: ChildSpec::nome accessor pins ────────────────────
12035    //
12036    // The M2 supervisor-tree sibling of the M3 `Membro::nome` (4a32abf) pin
12037    // pair (`membro_nome_returns_caixa_byte_equal_across_permutations` +
12038    // `membro_nome_borrows_from_caixa_storage`) — extended here to the M2
12039    // per-`:children` child-caixa `:nome` axis, sibling to the first M2
12040    // slot scalar accessor `UpgradeFromEntry::prior_versao` (75d27a8) on
12041    // the peer per-`:upgrade-from :from` axis. The three pins jointly
12042    // brace the accessor against every future silent detour that would
12043    // desynchronize it from the raw `.caixa` field access every consumer
12044    // previously open-coded.
12045
12046    #[test]
12047    fn child_spec_nome_returns_caixa_byte_equal_across_permutations() {
12048        // The canonical per-`:children` child-caixa `:nome`-scalar pin:
12049        // [`ChildSpec::nome`] must return the `:children :caixa` field
12050        // byte-for-byte across every DNS-1123-label value the upstream
12051        // [`crate::render::require_valid_dns_1123_label`] gate at
12052        // `SupervisorSpec::validate` admits. Peer of the sibling
12053        // `membro_nome_returns_caixa_byte_equal_across_permutations`
12054        // (4a32abf) pin on the M3 per-`:membros` axis — same "the
12055        // substrate-primitive accessor must byte-equal the raw field
12056        // access verbatim across every author-declared value" discipline
12057        // extended to the M2 supervisor-tree per-`:children` arm. Pins
12058        // against a future silent detour that re-normalized the child
12059        // identity (an accidental `.to_lowercase()` — every `:children
12060        // :caixa` is validated as a DNS-1123 label upstream, so any
12061        // re-normalization is redundant + a drift surface between the
12062        // validator and the accessor), a namespace-prefix rewrite (an
12063        // accidental `format!("{namespace}/{caixa}")` per-CR
12064        // fully-qualified rewrite that didn't land on the peer axes), or
12065        // a per-cluster alias stamp the future wasm-operator's
12066        // hierarchical reconciliation scheduler authors on one consumer
12067        // without the others. Five values sweep the accept-set the
12068        // DNS-1123 gate upstream admits (short single-word / dashed /
12069        // v-suffixed / mixed-digit child names).
12070        for name in [
12071            "worker",
12072            "cache-server",
12073            "scratch-job",
12074            "orders-v2",
12075            "session-8080",
12076        ] {
12077            let c = ChildSpec {
12078                caixa: name.into(),
12079                versao: "^0.1".into(),
12080                restart: RestartPolicy::Permanent,
12081            };
12082            assert_eq!(
12083                c.nome(),
12084                name,
12085                "ChildSpec::nome must return :children :caixa verbatim \
12086                 (got {:?}, expected {name:?})",
12087                c.nome(),
12088            );
12089            assert_eq!(
12090                c.nome(),
12091                c.caixa.as_str(),
12092                "ChildSpec::nome must byte-equal the .caixa field access",
12093            );
12094        }
12095    }
12096
12097    #[test]
12098    fn child_spec_nome_borrows_from_caixa_storage() {
12099        // The borrow-not-copy pin: [`ChildSpec::nome`] must return a
12100        // `&str` slice that borrows from the typed slot's own [`String`]
12101        // storage — same-address invariant with `c.caixa.as_str()`. Pins
12102        // against a future silent detour that allocated a fresh `String`
12103        // (`self.caixa.clone()` in the body would type-check but silently
12104        // drop the borrow, and every downstream consumer that assumed
12105        // the returned slice outlives `&self` would break on a stale-
12106        // reference use-after-free — the [`crate::render::insert_first_seen`]
12107        // dedup key at [`SupervisorSpec::validate`], the
12108        // [`validate_no_self_supervision`] equality check against the
12109        // parent's `:nome` string slice, the DNS-1123 gate's `&str`
12110        // borrow — each would silently misbehave if this accessor
12111        // produced a detached copy). Peer of the sibling
12112        // `membro_nome_borrows_from_caixa_storage` (4a32abf) pin on the
12113        // M3 per-`:membros` axis and the
12114        // `prior_versao_borrows_from_from_storage` (75d27a8) pin on the
12115        // first M2 slot scalar accessor.
12116        let c = ChildSpec {
12117            caixa: "worker".into(),
12118            versao: "^0.1".into(),
12119            restart: RestartPolicy::Permanent,
12120        };
12121        let name = c.nome();
12122        let caixa_slice = c.caixa.as_str();
12123        assert_eq!(
12124            name.as_ptr(),
12125            caixa_slice.as_ptr(),
12126            "ChildSpec::nome must borrow from the .caixa String's backing \
12127             storage — a fresh allocation here means the accessor no \
12128             longer names the substrate-primitive typed dispatch and \
12129             every downstream consumer would silently carry a detached \
12130             copy",
12131        );
12132        assert_eq!(
12133            name.len(),
12134            caixa_slice.len(),
12135            "ChildSpec::nome and .caixa.as_str() must byte-equal in length \
12136             as well as in address",
12137        );
12138    }
12139
12140    #[test]
12141    fn validate_gates_child_nome_through_lifted_accessor() {
12142        // Bilateral coherence pin: every `:children :caixa` that
12143        // [`SupervisorSpec::validate`] accepts is one
12144        // [`crate::render::require_valid_dns_1123_label`] accepts on the
12145        // accessor-projected value, and vice versa on the reject side.
12146        // This closes the "the validator reads through the accessor"
12147        // contract structurally — a future silent detour that made the
12148        // accessor return a different byte-string than the validator
12149        // gates against would surface here as a coverage mismatch, not
12150        // as an apply-time DNS-1123 rejection at
12151        // `metadata.name: Invalid value` far from the caixa.lisp source.
12152        // Peer of the M2 sibling
12153        // `validate_parses_prior_versao_through_lifted_accessor`
12154        // (75d27a8) on the per-`:upgrade-from :from` axis and the M3
12155        // `validate_membros` peer discipline.
12156        //
12157        // Accept-set sweep: five DNS-1123-label values the upstream gate
12158        // admits.
12159        for ok_name in ["a", "worker", "cache-server", "orders-v2", "svc-8080"] {
12160            let s = SupervisorSpec {
12161                children: vec![ChildSpec {
12162                    caixa: ok_name.into(),
12163                    versao: "^0.1".into(),
12164                    restart: RestartPolicy::Permanent,
12165                }],
12166                ..SupervisorSpec::default()
12167            };
12168            s.validate().unwrap_or_else(|e| {
12169                panic!(
12170                    "SupervisorSpec::validate must accept :children :caixa {ok_name:?} \
12171                     (upstream DNS-1123 gate accepts it): got {e:?}",
12172                );
12173            });
12174            let c = ChildSpec {
12175                caixa: ok_name.into(),
12176                versao: "^0.1".into(),
12177                restart: RestartPolicy::Permanent,
12178            };
12179            crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| ())
12180                .unwrap_or_else(|()| {
12181                    panic!(
12182                        "require_valid_dns_1123_label must accept the accessor-projected \
12183                     :children :caixa {ok_name:?}",
12184                    );
12185                });
12186        }
12187        // Reject-set sweep: five DNS-1123-label-violating shapes the
12188        // upstream gate refuses (empty / uppercase / underscore / dot /
12189        // leading-hyphen). Every rejection at the validator must
12190        // correspond to a rejection when the accessor's projected value
12191        // is fed back through the shared gate.
12192        for bad_name in ["", "Worker", "my_worker", "team.worker", "-worker"] {
12193            let s = SupervisorSpec {
12194                children: vec![ChildSpec {
12195                    caixa: bad_name.into(),
12196                    versao: "^0.1".into(),
12197                    restart: RestartPolicy::Permanent,
12198                }],
12199                ..SupervisorSpec::default()
12200            };
12201            let err = s.validate().unwrap_err();
12202            assert!(
12203                matches!(
12204                    err,
12205                    SupervisorError::EmptyChildName | SupervisorError::ChildCaixaInvalid { .. }
12206                ),
12207                "SupervisorSpec::validate must reject :children :caixa {bad_name:?} \
12208                 via the DNS-1123 gate: got {err:?}",
12209            );
12210            let c = ChildSpec {
12211                caixa: bad_name.into(),
12212                versao: "^0.1".into(),
12213                restart: RestartPolicy::Permanent,
12214            };
12215            assert!(
12216                crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| (),)
12217                    .is_err(),
12218                "require_valid_dns_1123_label must reject the accessor-projected \
12219                 :children :caixa {bad_name:?}",
12220            );
12221        }
12222    }
12223
12224    // ── drift-detection: ChildSpec::versao_requirement accessor pins ──────
12225    //
12226    // Sibling of the peer per-`:membros` `membro_versao_requirement_*`
12227    // (a40b0e3) pin pair on the M3 mesh-slot surface — extended here to the
12228    // M2 supervisor-tree per-`:children` child-`:versao` axis, sibling to
12229    // the just-landed [`ChildSpec::nome`] (57c61d0) child-`:nome` pin
12230    // trio on the peer per-`:children` `String`-carry axis. The three pins
12231    // jointly brace the accessor against every future silent detour that
12232    // would desynchronize it from the raw `.versao` field access the
12233    // requirement gate + error carrier previously open-coded.
12234    //
12235    // Closes the last unlifted per-`:children` `String`-carry axis: the
12236    // pair (`nome`, `versao_requirement`) now jointly projects the
12237    // (`.caixa`, `.versao`) field pair every OTP-shape supervisor-tree
12238    // consumer that fans on per-child identity + version pin reads,
12239    // matching the peer M3 (`Membro::nome`, `Membro::versao_requirement`)
12240    // pair discipline verbatim.
12241    #[test]
12242    fn child_spec_versao_requirement_returns_versao_byte_equal_across_permutations() {
12243        // The canonical per-`:children` child-`:versao`-scalar pin:
12244        // [`ChildSpec::versao_requirement`] must return the `:children
12245        // :versao` field byte-for-byte across every Cargo-shaped semver
12246        // requirement value the upstream
12247        // [`crate::render::require_valid_versao_requirement`] gate admits.
12248        // Peer of the sibling
12249        // `membro_versao_requirement_returns_versao_byte_equal_across_permutations`
12250        // (a40b0e3) pin on the M3 per-`:membros` axis — same "the
12251        // substrate-primitive accessor must byte-equal the raw field
12252        // access verbatim across every author-declared value" discipline
12253        // extended to the M2 supervisor-tree per-`:children` arm. Pins
12254        // against a future silent detour that re-canonicalized the
12255        // requirement (an accidental `.to_string()` via
12256        // [`crate::version::parse_requirement`] → [`std::fmt::Display`]
12257        // round-trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and
12258        // silently drifted the error carrier's quoted requirement away
12259        // from the source `caixa.lisp`, an accidental whitespace trim on
12260        // `"^ 0.1"` that no consumer ever produced from the field-access
12261        // side, an accidental per-cluster lacre-projected concrete-version
12262        // rewrite that didn't land on the peer requirement-gate call).
12263        // Five values sweep the accept-set the shared
12264        // [`crate::render::require_valid_versao_requirement`] gate admits
12265        // (caret / tilde / exact / wildcard / bare-major).
12266        for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
12267            let c = ChildSpec {
12268                caixa: "worker".into(),
12269                versao: req.into(),
12270                restart: RestartPolicy::Permanent,
12271            };
12272            assert_eq!(
12273                c.versao_requirement(),
12274                req,
12275                "ChildSpec::versao_requirement must return :children :versao \
12276                 verbatim (got {:?}, expected {req:?})",
12277                c.versao_requirement(),
12278            );
12279            assert_eq!(
12280                c.versao_requirement(),
12281                c.versao.as_str(),
12282                "ChildSpec::versao_requirement must byte-equal the .versao \
12283                 field access",
12284            );
12285        }
12286    }
12287
12288    #[test]
12289    fn child_spec_versao_requirement_borrows_from_versao_storage() {
12290        // The borrow-not-copy pin: [`ChildSpec::versao_requirement`] must
12291        // return a `&str` slice that borrows from the typed slot's own
12292        // [`String`] storage — same-address invariant with
12293        // `c.versao.as_str()`. Pins against a future silent detour that
12294        // allocated a fresh `String` (`self.versao.clone()` in the body
12295        // would type-check but silently drop the borrow, and every
12296        // downstream consumer that assumed the returned slice outlives
12297        // `&self` — the [`crate::render::require_valid_versao_requirement`]
12298        // gate's `&str` borrow, the [`SupervisorError::ChildVersaoInvalid`]
12299        // `.to_string()` carrier's byte-length assumption — would silently
12300        // misbehave if this accessor produced a detached copy). Peer of
12301        // the sibling `child_spec_nome_borrows_from_caixa_storage`
12302        // (57c61d0) pin on the per-`:children` `:nome` axis and the M3
12303        // `membro_versao_requirement_borrows_from_versao_storage` (a40b0e3)
12304        // pin on the peer per-`:membros` `:versao` axis.
12305        let c = ChildSpec {
12306            caixa: "worker".into(),
12307            versao: "^0.1".into(),
12308            restart: RestartPolicy::Permanent,
12309        };
12310        let req = c.versao_requirement();
12311        let versao_slice = c.versao.as_str();
12312        assert_eq!(
12313            req.as_ptr(),
12314            versao_slice.as_ptr(),
12315            "ChildSpec::versao_requirement must borrow from the .versao \
12316             String's backing storage — a fresh allocation here means the \
12317             accessor no longer names the substrate-primitive typed \
12318             dispatch and every downstream consumer would silently carry \
12319             a detached copy",
12320        );
12321        assert_eq!(
12322            req.len(),
12323            versao_slice.len(),
12324            "ChildSpec::versao_requirement and .versao.as_str() must \
12325             byte-equal in length as well as in address",
12326        );
12327    }
12328
12329    #[test]
12330    fn validate_gates_child_versao_through_lifted_accessor() {
12331        // Bilateral coherence pin: every `:children :versao` that
12332        // [`SupervisorSpec::validate`] accepts is one
12333        // [`crate::render::require_valid_versao_requirement`] accepts on
12334        // the accessor-projected value, and vice versa on the reject side.
12335        // This closes the "the validator reads through the accessor"
12336        // contract structurally — a future silent detour that made the
12337        // accessor return a different byte-string than the validator gates
12338        // against would surface here as a coverage mismatch, not as a
12339        // resolver-time semver-parse rejection at lacre-closure time far
12340        // from the caixa.lisp source. Peer of the sibling
12341        // `validate_gates_child_nome_through_lifted_accessor` (57c61d0) on
12342        // the per-`:children :caixa` axis and the M2
12343        // `validate_parses_prior_versao_through_lifted_accessor` (75d27a8)
12344        // on the peer per-`:upgrade-from :from` axis.
12345        //
12346        // Accept-set sweep: five Cargo-shaped semver requirement values
12347        // the upstream gate admits (caret / tilde / exact / wildcard /
12348        // bare-major).
12349        for ok_req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
12350            let s = SupervisorSpec {
12351                children: vec![ChildSpec {
12352                    caixa: "worker".into(),
12353                    versao: ok_req.into(),
12354                    restart: RestartPolicy::Permanent,
12355                }],
12356                ..SupervisorSpec::default()
12357            };
12358            s.validate().unwrap_or_else(|e| {
12359                panic!(
12360                    "SupervisorSpec::validate must accept :children :versao {ok_req:?} \
12361                     (upstream versao-requirement gate accepts it): got {e:?}",
12362                );
12363            });
12364            let c = ChildSpec {
12365                caixa: "worker".into(),
12366                versao: ok_req.into(),
12367                restart: RestartPolicy::Permanent,
12368            };
12369            crate::render::require_valid_versao_requirement(
12370                c.versao_requirement(),
12371                || (),
12372                |_reason| (),
12373            )
12374            .unwrap_or_else(|()| {
12375                panic!(
12376                    "require_valid_versao_requirement must accept the accessor-projected \
12377                     :children :versao {ok_req:?}",
12378                );
12379            });
12380        }
12381        // Reject-set sweep: five requirement-violating shapes the upstream
12382        // gate refuses. The empty string closes the empty-first arm of the
12383        // shared [`crate::render::require_valid_versao_requirement`]
12384        // cascade; the four non-empty arms exercise distinct semver-parse
12385        // failure modes the M3 peer per-`:membros` reject-set already pins
12386        // (`rejects_invalid_membro_versao_requirement` on `^bad-version`,
12387        // `rejects_membro_versao_with_double_caret_typo` on `^^0.1`,
12388        // `rejects_membro_versao_with_v_prefixed_tag` on `v0.1`) — the
12389        // shared parser routing means the same reject-set must fail
12390        // identically at the M2 supervisor-tree per-`:children` accessor
12391        // arm here. Every rejection at the validator must correspond to a
12392        // rejection when the accessor's projected value is fed back
12393        // through the shared gate.
12394        //
12395        // (Bare partial magnitudes like `"0.1"` and bare identifiers like
12396        // `"not-a-semver"` are intentionally *not* in the reject-set: the
12397        // semver crate accepts `"0.1"` as an implicit `^0.1` requirement,
12398        // and the identifier-tail arm's grammar admits some non-canonical
12399        // shapes — matching what the M3 peer test suite already documents
12400        // as the shared parser's accept-set edges.)
12401        for bad_req in ["", "v0.1.0", "^bad-version", "^^0.1", "v0.1"] {
12402            let s = SupervisorSpec {
12403                children: vec![ChildSpec {
12404                    caixa: "worker".into(),
12405                    versao: bad_req.into(),
12406                    restart: RestartPolicy::Permanent,
12407                }],
12408                ..SupervisorSpec::default()
12409            };
12410            let err = s.validate().unwrap_err();
12411            assert!(
12412                matches!(
12413                    err,
12414                    SupervisorError::EmptyChildVersion { .. }
12415                        | SupervisorError::ChildVersaoInvalid { .. }
12416                ),
12417                "SupervisorSpec::validate must reject :children :versao {bad_req:?} \
12418                 via the versao-requirement gate: got {err:?}",
12419            );
12420            let c = ChildSpec {
12421                caixa: "worker".into(),
12422                versao: bad_req.into(),
12423                restart: RestartPolicy::Permanent,
12424            };
12425            assert!(
12426                crate::render::require_valid_versao_requirement(
12427                    c.versao_requirement(),
12428                    || (),
12429                    |_reason| (),
12430                )
12431                .is_err(),
12432                "require_valid_versao_requirement must reject the accessor-projected \
12433                 :children :versao {bad_req:?}",
12434            );
12435        }
12436    }
12437
12438    // ── per-`:children` `:restart` typed-accessor coherence pins ──────────
12439    //
12440    // The [`ChildSpec::restart`] accessor lift closes the last unlifted
12441    // per-`:children` axis (the pair `nome()` + `versao_requirement()`
12442    // already project the `String`-carry `(caixa, versao)` fields; the
12443    // `Copy`-composite-enum `restart` field is the third and final axis).
12444    // Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
12445    // (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
12446    // scalar accessor and the M3 mesh-slot [`crate::Placement::estrategia`]
12447    // (921fe1b) `Copy`-return [`crate::PlacementStrategy`] distribution-
12448    // strategy scalar accessor — same "one typed dispatch on the substrate
12449    // primitive, `Copy`-projected closed-set enum-arm discriminator" shape
12450    // extended onto the M2 supervisor-slot per-`:children` restart-decision
12451    // axis. The pin below covers the accessor's byte-equal projection
12452    // against the raw field access across every variant in the closed
12453    // accept-set (`Permanent`, `Transient`, `Temporary`).
12454
12455    #[test]
12456    fn child_spec_restart_returns_restart_verbatim_across_permutations() {
12457        // The canonical per-`:children` restart-decision-policy-scalar
12458        // pin: [`ChildSpec::restart`] must return the `:children :restart`
12459        // field verbatim as a [`RestartPolicy`], `Copy`-projected from the
12460        // typed slot's own [`RestartPolicy`] storage across every variant
12461        // in the closed accept-set (`Permanent`, `Transient`, `Temporary`).
12462        // Pins against a future silent detour that re-derived the policy
12463        // from a peer axis (an accidental fallback to
12464        // `if is_supervisor_child { Permanent } else { Temporary }` that
12465        // collapsed the child's kind axis into the restart discriminator),
12466        // a variant remap the operator authors on one consumer without the
12467        // other, or a stale-derive detour that substituted
12468        // [`RestartPolicy::default`] when the field held any explicit
12469        // variant (which would silently collapse the distinction between
12470        // "author explicitly declared `:restart Permanent`" and "author
12471        // omitted the slot and inherited the default" the future
12472        // per-cluster restart-decision override slot depends on).
12473        //
12474        // Peer of the sibling per-`:supervisor`
12475        // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
12476        // (eafb619) pin on the M2 supervisor-slot sibling-restart-strategy
12477        // axis and the M3
12478        // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
12479        // (921fe1b) pin on the per-`:placement` distribution-strategy axis
12480        // — same "the substrate-primitive accessor must byte-equal the raw
12481        // field access verbatim across every author-declared value"
12482        // discipline extended onto the M2 supervisor-slot per-`:children`
12483        // restart-decision-policy axis, closing the last unlifted axis on
12484        // the per-`:children` [`ChildSpec`] type.
12485        for restart in [
12486            RestartPolicy::Permanent,
12487            RestartPolicy::Transient,
12488            RestartPolicy::Temporary,
12489        ] {
12490            let c = ChildSpec {
12491                caixa: "worker".into(),
12492                versao: "^0.1".into(),
12493                restart,
12494            };
12495            assert_eq!(
12496                c.restart(),
12497                restart,
12498                "ChildSpec::restart must return :children :restart \
12499                 verbatim (got {:?}, expected {restart:?})",
12500                c.restart(),
12501            );
12502            assert_eq!(
12503                c.restart(),
12504                c.restart,
12505                "ChildSpec::restart accessor and .restart field access \
12506                 must byte-equal — the accessor is the substrate-primitive \
12507                 typed dispatch every downstream per-child restart-\
12508                 decision consumer must route through",
12509            );
12510        }
12511    }
12512
12513    // ── per-`:supervisor` `:estrategia` typed-accessor coherence pins ─────
12514    //
12515    // The [`SupervisorSpec::estrategia`] accessor lift extends the peer M3
12516    // [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
12517    // distribution-strategy accessor discipline onto the M2 supervisor-slot
12518    // per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
12519    // scalar axis. The two pins below cover (1) the accessor's byte-equal
12520    // projection against the raw field access across every variant in the
12521    // closed accept-set, and (2) the two-consumer coherence between the
12522    // [`SupervisorSpec::validate`] partition-dispatch `match` arm and the
12523    // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
12524    // carrier's `estrategia:` field — peer of the sibling M3
12525    // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
12526    // / `validate_placement_reads_through_lifted_estrategia_accessor` pin
12527    // pair on the per-`:placement` distribution-strategy axis.
12528
12529    #[test]
12530    fn supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations() {
12531        // The canonical per-`:supervisor` sibling-restart-strategy-scalar
12532        // pin: [`SupervisorSpec::estrategia`] must return the
12533        // `:supervisor :estrategia` field verbatim as a
12534        // [`RestartStrategy`], `Copy`-projected from the typed slot's own
12535        // [`RestartStrategy`] storage across every variant in the closed
12536        // accept-set (`OneForOne`, `OneForAll`, `RestForOne`,
12537        // `SimpleOneForOne`). Pins against a future silent detour that
12538        // re-derived the strategy from a peer axis (an accidental
12539        // fallback to `if children.is_empty() { SimpleOneForOne } else {
12540        // OneForOne }` collapse that read the children-count axis into
12541        // the strategy discriminator), a variant remap the operator
12542        // authors on one consumer without the other, or a stale-derive
12543        // detour that substituted [`RestartStrategy::default`] when the
12544        // field held any explicit variant (which would silently collapse
12545        // the distinction between "author explicitly declared
12546        // `:estrategia OneForOne`" and "author omitted the slot and
12547        // inherited the default" the future per-cluster strategy override
12548        // slot depends on). Peer of the sibling M3
12549        // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
12550        // (921fe1b) pin on the M3 mesh-slot `Copy`-composite-enum scalar
12551        // axis — same "the substrate-primitive accessor must byte-equal
12552        // the raw field access verbatim across every author-declared
12553        // value" discipline extended onto the M2 supervisor-slot
12554        // per-`:supervisor` sibling-restart-strategy axis.
12555        for &estrategia in RestartStrategy::ALL {
12556            // `SimpleOneForOne` requires `children.is_empty()`; the peer
12557            // three strategies require a non-empty static children list.
12558            // Build each shape coherently so the pin's fixture would
12559            // itself pass [`SupervisorSpec::validate`] once fed through
12560            // the sibling coherence pin below — the byte-equal projection
12561            // asserted here is a strictly weaker property (a `Copy` field
12562            // read) that does not depend on `validate` running, but
12563            // keeping the fixture validate-clean means a future extension
12564            // of the pin to exercise `validate` end-to-end does not have
12565            // to re-author the children shape.
12566            //
12567            // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
12568            // shape partition through the [`gen_platform::IsVariant`]
12569            // derive-generated
12570            // [`RestartStrategy::is_simple_one_for_one`] predicate rather
12571            // than the raw `matches!(estrategia, RestartStrategy::
12572            // SimpleOneForOne)` open-coded pattern-match — same closed-
12573            // set-typed-enum arm-discriminator dispatch discipline the
12574            // sibling [`crate::upgrade::UpgradeInstruction::is_restart`]
12575            // convergence (915a934) extended onto its two paired positive
12576            // / negated `matches!` sites and the peer
12577            // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
12578            // predicate convergence (766ec63) extended onto the M3 mesh-
12579            // slot per-`:placement` distribution-strategy discriminator
12580            // axis. See the sibling `round_trip_all_strategies` and the
12581            // peer `manifest::tests::
12582            // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
12583            // fixture for the two peer sites the same lift closes on.
12584            let children = if estrategia.is_simple_one_for_one() {
12585                Vec::new()
12586            } else {
12587                vec![ChildSpec {
12588                    caixa: "worker".into(),
12589                    versao: "^0.1".into(),
12590                    restart: RestartPolicy::Permanent,
12591                }]
12592            };
12593            let s = SupervisorSpec {
12594                estrategia,
12595                children,
12596                ..SupervisorSpec::default()
12597            };
12598            assert_eq!(
12599                s.estrategia(),
12600                estrategia,
12601                "SupervisorSpec::estrategia must return :supervisor :estrategia \
12602                 verbatim (got {:?}, expected {estrategia:?})",
12603                s.estrategia(),
12604            );
12605            assert_eq!(
12606                s.estrategia(),
12607                s.estrategia,
12608                "SupervisorSpec::estrategia accessor and .estrategia field \
12609                 access must byte-equal — the accessor is the substrate-\
12610                 primitive typed dispatch every downstream sibling-restart-\
12611                 strategy consumer must route through",
12612            );
12613        }
12614    }
12615
12616    #[test]
12617    fn validate_reads_through_lifted_estrategia_accessor() {
12618        // Two-consumer coherence pin: the [`SupervisorSpec::validate`]
12619        // `SimpleOneForOne ↔ non-SimpleOneForOne` `match` partition
12620        // dispatch (which reads through [`SupervisorSpec::estrategia`]
12621        // to fan across the strategy-arm shape-gate cascades) and the
12622        // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
12623        // error carrier's `estrategia:` field (which reads through
12624        // [`SupervisorSpec::estrategia`] to name the strategy the empty
12625        // `:children` list was declared against) must both key off the
12626        // lifted accessor, so any future rebrand on the typed slot's
12627        // reader shape lands at exactly one place. Pins the two-site
12628        // coherence by exercising the `NoChildren` error surface end-to-
12629        // end across every non-`SimpleOneForOne` variant and asserting
12630        // the surfaced `estrategia:` field byte-equals the accessor's
12631        // return. Peer of the sibling M3
12632        // `validate_placement_reads_through_lifted_estrategia_accessor`
12633        // (921fe1b) three-consumer coherence pin on the per-`:placement`
12634        // distribution-strategy axis.
12635        for estrategia in [
12636            RestartStrategy::OneForOne,
12637            RestartStrategy::OneForAll,
12638            RestartStrategy::RestForOne,
12639        ] {
12640            let s = SupervisorSpec {
12641                estrategia,
12642                children: Vec::new(),
12643                ..SupervisorSpec::default()
12644            };
12645            let err = s.validate().unwrap_err();
12646            match err {
12647                SupervisorError::NoChildren { estrategia: e } => {
12648                    assert_eq!(
12649                        e,
12650                        s.estrategia(),
12651                        "NoChildren.estrategia must byte-equal \
12652                         SupervisorSpec::estrategia() — the empty-`:children` \
12653                         refusal reads through the lifted accessor",
12654                    );
12655                    assert_eq!(
12656                        e, estrategia,
12657                        "NoChildren.estrategia must carry the author-declared \
12658                         :supervisor :estrategia variant verbatim (got {e:?}, \
12659                         expected {estrategia:?})",
12660                    );
12661                }
12662                other => panic!("expected NoChildren, got {other:?} for estrategia={estrategia:?}"),
12663            }
12664        }
12665    }
12666
12667    // ── per-`:supervisor` `:max-restarts` typed-accessor coherence pins ────
12668    //
12669    // The [`SupervisorSpec::max_restarts`] accessor lift extends the peer M3
12670    // [`crate::CircuitBreaker::max_failures`] (3a74062) `Copy`-return
12671    // required-`u32` scalar accessor discipline onto the M2 supervisor-slot
12672    // per-`:supervisor` restart-budget-count `Copy`-`u32` scalar axis.
12673    // The two pins below cover (1) the accessor's byte-equal projection
12674    // against the raw field access across every representative value in
12675    // the `u32` accept-set (`1` lower boundary, `SUPERVISOR_MAX_RESTARTS_MAX`
12676    // upper boundary, `0` past-the-guard zero sentinel, `u32::MAX`
12677    // past-the-guard cap sentinel), and (2) the [`SupervisorSpec::validate`]
12678    // zero-floor / cap composition — the validate gate and the accessor
12679    // must route through the same substrate-primitive typed dispatch, so
12680    // any future silent detour that had the accessor perform a
12681    // bounds-collapsing clamp would fail here at caixa-core build time.
12682    // Peer of the sibling M3
12683    // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
12684    // (3a74062) pin on the per-`CircuitBreaker :max-failures` axis.
12685
12686    #[test]
12687    fn supervisor_spec_max_restarts_returns_max_restarts_u32_byte_equal_across_permutations() {
12688        // The canonical per-`:supervisor` restart-budget-count scalar pin:
12689        // [`SupervisorSpec::max_restarts`] must return the `:supervisor
12690        // :max-restarts` typed `u32` verbatim, `Copy`-projected from the
12691        // typed slot's own `u32` storage, byte-equal to the raw field
12692        // access across every representative value in the accept-set —
12693        // `1` (the lower boundary of the `1..=SUPERVISOR_MAX_RESTARTS_MAX`
12694        // accept-set the surrounding [`SupervisorSpec::validate`] gate
12695        // carves out on the sibling `ZeroMaxRestarts` refusal),
12696        // `SUPERVISOR_MAX_RESTARTS_MAX` (the upper boundary the same gate
12697        // carves out on the sibling `MaxRestartsExceedsCap` refusal), `0`
12698        // (a past-the-guard sentinel that pins the accessor doesn't
12699        // perform a silent bounds-collapse into `1` on the zero arm —
12700        // validate rejects zero but the accessor must ship the raw slot
12701        // verbatim so a validate-time gate regression surfaces at the
12702        // emit boundary rather than being silently absorbed), `u32::MAX`
12703        // (a past-the-guard sentinel that pins the accessor doesn't
12704        // perform a silent bounds-collapse through
12705        // `SUPERVISOR_MAX_RESTARTS_MAX` at the return path).
12706        //
12707        // Peer of the sibling M3
12708        // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
12709        // (3a74062) pin on the M3 mesh-slot `Copy`-`u32` sub-struct
12710        // required-scalar axis — same "the substrate-primitive accessor
12711        // must byte-equal the raw field access verbatim across every
12712        // value in the `u32` accept-set" discipline extended onto the M2
12713        // supervisor-slot per-`:supervisor` restart-budget-count axis.
12714        for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX, 0, u32::MAX] {
12715            let s = SupervisorSpec {
12716                max_restarts,
12717                ..SupervisorSpec::default()
12718            };
12719            assert_eq!(
12720                s.max_restarts(),
12721                max_restarts,
12722                "SupervisorSpec::max_restarts must return :supervisor \
12723                 :max-restarts verbatim (got {}, expected {max_restarts})",
12724                s.max_restarts(),
12725            );
12726            assert_eq!(
12727                s.max_restarts(),
12728                s.max_restarts,
12729                "SupervisorSpec::max_restarts accessor and .max_restarts \
12730                 field access must byte-equal — the accessor is the \
12731                 substrate-primitive typed dispatch every downstream \
12732                 restart-budget-count consumer must route through",
12733            );
12734        }
12735    }
12736
12737    #[test]
12738    fn validate_max_restarts_zero_floor_and_cap_arms_route_through_accessor() {
12739        // Composition pin: [`SupervisorSpec::validate`]'s `:max-restarts`
12740        // zero-floor + upper-cap bracket must key off
12741        // [`SupervisorSpec::max_restarts`], not the raw `.max_restarts`
12742        // field access. Structurally: a `SupervisorSpec { max_restarts:
12743        // 0, .. }` must surface the `ZeroMaxRestarts` refusal exactly, a
12744        // `SupervisorSpec { max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
12745        // .. }` must surface the `MaxRestartsExceedsCap` refusal exactly
12746        // (with the offending count carried verbatim from the accessor
12747        // return), and a `SupervisorSpec { max_restarts: 1, .. }` (the
12748        // lower boundary of the accept-set) plus a `SupervisorSpec {
12749        // max_restarts: SUPERVISOR_MAX_RESTARTS_MAX, .. }` (the upper
12750        // boundary) must pass validate. The four together jointly pin the
12751        // accessor + validate-gate composition: any future silent detour
12752        // that had the accessor return a fresh `1` on the zero arm (a
12753        // `.max_restarts().max(1)` collapse) would silently absorb the
12754        // `ZeroMaxRestarts` refusal at the accessor boundary and the
12755        // validate gate would accept a struct-literal `SupervisorSpec {
12756        // max_restarts: 0, .. }` — the composition pin catches that at
12757        // caixa-core build time.
12758        //
12759        // Peer of the sibling M3
12760        // `validate_politicas_max_failures_zero_floor_arm_routes_through_accessor`
12761        // (3a74062) pin on the sibling per-`CircuitBreaker :max-failures`
12762        // composition axis — same "the validate / shape-gate predicate
12763        // must route through the substrate-primitive typed dispatch"
12764        // discipline extended onto the peer M2 supervisor-slot
12765        // required-`u32` composition axis.
12766        let child = ChildSpec {
12767            caixa: "worker".into(),
12768            versao: "^0.1".into(),
12769            restart: RestartPolicy::Permanent,
12770        };
12771        // Zero-floor arm.
12772        let s = SupervisorSpec {
12773            max_restarts: 0,
12774            children: vec![child.clone()],
12775            ..SupervisorSpec::default()
12776        };
12777        assert_eq!(
12778            s.validate().unwrap_err(),
12779            SupervisorError::ZeroMaxRestarts,
12780            "validate must reject max_restarts == 0 with ZeroMaxRestarts \
12781             — the accessor and the validate gate must route through the \
12782             same substrate-primitive typed dispatch on the zero-floor arm",
12783        );
12784        // Cap arm — the surfaced `max_restarts:` field must byte-equal
12785        // the accessor's return so a future rebrand on the accessor
12786        // lands in the diagnostic without a coordinated rewrite.
12787        let over_cap = SUPERVISOR_MAX_RESTARTS_MAX + 1;
12788        let s = SupervisorSpec {
12789            max_restarts: over_cap,
12790            children: vec![child.clone()],
12791            ..SupervisorSpec::default()
12792        };
12793        match s.validate().unwrap_err() {
12794            SupervisorError::MaxRestartsExceedsCap { max_restarts } => {
12795                assert_eq!(
12796                    max_restarts,
12797                    s.max_restarts(),
12798                    "MaxRestartsExceedsCap.max_restarts must byte-equal \
12799                     SupervisorSpec::max_restarts() — the cap-arm refusal \
12800                     reads through the lifted accessor",
12801                );
12802                assert_eq!(
12803                    max_restarts, over_cap,
12804                    "MaxRestartsExceedsCap.max_restarts must carry the \
12805                     author-declared :supervisor :max-restarts value \
12806                     verbatim (got {max_restarts}, expected {over_cap})",
12807                );
12808            }
12809            other => panic!("expected MaxRestartsExceedsCap, got {other:?}"),
12810        }
12811        // Lower + upper accept-set boundaries.
12812        for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX] {
12813            let s = SupervisorSpec {
12814                max_restarts,
12815                children: vec![child.clone()],
12816                ..SupervisorSpec::default()
12817            };
12818            assert!(
12819                s.validate().is_ok(),
12820                "validate must accept max_restarts == {max_restarts} \
12821                 (an accept-set boundary of \
12822                 1..=SUPERVISOR_MAX_RESTARTS_MAX)",
12823            );
12824        }
12825    }
12826
12827    // ── per-`:supervisor` `:restart-window` typed-accessor coherence pins ─
12828    //
12829    // The [`SupervisorSpec::restart_window`] accessor lift extends the peer
12830    // M2 [`crate::LimitsSpec::wall_clock`] (8cb717b) `Option<Duration>`
12831    // accessor discipline and the peer M3 [`crate::MeshPolicy::timeout`]
12832    // (7073d0f) `Option<Duration>` accessor discipline onto the M2
12833    // supervisor-slot per-`:supervisor` restart-intensity-denominator
12834    // `Option<Duration>` scalar axis — third `Copy`-return accessor on the
12835    // M2 supervisor-slot `SupervisorSpec` type, closing the last unlifted
12836    // per-`:supervisor` scalar-value axis. The three pins below cover
12837    // (1) the accessor's byte-equal projection against the raw field
12838    // access across every representative value in the `Option<Duration>`
12839    // accept-set (`None` never-reset sentinel, `Some(Duration::from_millis(1))`
12840    // lower boundary, `Some(SUPERVISOR_RESTART_WINDOW_MAX)` upper boundary,
12841    // `Some(Duration::ZERO)` past-the-guard zero sentinel, `Some(Duration::MAX)`
12842    // past-the-guard above-cap sentinel), (2) the [`SupervisorSpec::validate`]
12843    // `if let Some(w) = self.restart_window() { … }` bracket-arm
12844    // composition — the validate gate and the accessor must route through
12845    // the same substrate-primitive typed dispatch, so any future silent
12846    // detour that had the accessor perform a bounds-collapsing clamp
12847    // would fail here at caixa-core build time, and (3) the accessor's
12848    // by-copy idempotence pin — the returned `Option<Duration>` must
12849    // outlive `&self` and two successive calls must return byte-equal
12850    // values. Peer of the sibling M2
12851    // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
12852    // (8cb717b) pin on the per-`:limits :wall-clock` axis and the sibling
12853    // M3 `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
12854    // (7073d0f) pin on the per-`:politicas :timeout` axis.
12855
12856    #[test]
12857    fn supervisor_spec_restart_window_returns_option_duration_byte_equal_across_permutations() {
12858        // The canonical per-`:supervisor` restart-intensity-denominator
12859        // scalar pin: [`SupervisorSpec::restart_window`] must return the
12860        // `:supervisor :restart-window` typed [`Duration`] verbatim as an
12861        // `Option<Duration>`, `Copy`-projected from the typed slot's own
12862        // `Option<Duration>` storage, byte-equal to the raw field access
12863        // across every representative value in the accept-set — `None`
12864        // (the "never reset — every restart across the supervisor's
12865        // lifetime counts against the sibling `:max-restarts` budget"
12866        // sentinel the field's own docstring names and the peer
12867        // `validate_accepts_none_restart_window` pin locks in on the
12868        // [`SupervisorSpec::validate`] entry-side),
12869        // `Some(Duration::from_millis(1))` (the structural minimum a
12870        // validated `:restart-window` may carry, the integer-millisecond
12871        // floor [`SupervisorError::RestartWindowNotCanonical`] rejects
12872        // everything sub-ms; `Duration::ZERO` is separately rejected by
12873        // [`SupervisorError::RestartWindowZero`]),
12874        // `Some(SUPERVISOR_RESTART_WINDOW_MAX)` (the upper boundary the
12875        // surrounding [`SupervisorSpec::validate`] gate carves out on the
12876        // sibling [`SupervisorError::RestartWindowExceedsCap`] refusal),
12877        // `Some(Duration::ZERO)` (a past-the-guard sentinel that pins the
12878        // accessor doesn't perform a silent bounds-collapse into `None` on
12879        // the zero-Duration arm — validate rejects zero but the accessor
12880        // must ship the raw slot verbatim so a validate-time gate
12881        // regression surfaces at the emit boundary rather than being
12882        // silently absorbed), and `Some(Duration::MAX)` (a past-the-guard
12883        // sentinel that pins the accessor doesn't perform a silent
12884        // bounds-collapse through [`SUPERVISOR_RESTART_WINDOW_MAX`] at the
12885        // return path).
12886        //
12887        // Peer of the sibling M2
12888        // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
12889        // (8cb717b) pin on the per-`:limits :wall-clock` axis and the
12890        // sibling M3
12891        // `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
12892        // (7073d0f) pin on the per-`:politicas :timeout` axis — same "the
12893        // substrate-primitive accessor must byte-equal the raw field
12894        // access verbatim across every value in the `Option<Duration>`
12895        // accept-set" discipline extended onto the M2 supervisor-slot
12896        // per-`:supervisor` `Option<Duration>` axis. Pins against a future
12897        // silent detour that re-derived the restart-window from a peer
12898        // axis (an accidental `.max_restarts.into()` collapse that read
12899        // the restart-budget-count as a duration — the two axes serve
12900        // different halves of the `MaxIntensity / Period` restart-
12901        // intensity ratio, and confusing them silently inverts the
12902        // ratio's numerator and denominator), a `None → Some(Duration::ZERO)`
12903        // "zero means never reset" collapse (the canonical
12904        // `Option<Duration>` → `Duration` collapse footgun the
12905        // [`SupervisorError::RestartWindowZero`] validate arm guards on
12906        // the peer zero-floor axis; a zero period either trips on the
12907        // first failure or never trips depending on operator
12908        // interpretation, neither of which is the author's "never reset"
12909        // intent that `None` expresses structurally), or a per-arm
12910        // variant swap that landed on one consumer without the other.
12911        for restart_window in [
12912            None,
12913            Some(Duration::from_millis(1)),
12914            Some(SUPERVISOR_RESTART_WINDOW_MAX),
12915            Some(Duration::ZERO),
12916            Some(Duration::MAX),
12917        ] {
12918            let s = SupervisorSpec {
12919                restart_window,
12920                ..SupervisorSpec::default()
12921            };
12922            assert_eq!(
12923                s.restart_window(),
12924                restart_window,
12925                "SupervisorSpec::restart_window must return :supervisor \
12926                 :restart-window verbatim (got {:?}, expected {restart_window:?})",
12927                s.restart_window(),
12928            );
12929            assert_eq!(
12930                s.restart_window(),
12931                s.restart_window,
12932                "SupervisorSpec::restart_window accessor and \
12933                 .restart_window field access must byte-equal — the \
12934                 accessor is the substrate-primitive typed dispatch every \
12935                 downstream restart-intensity-denominator consumer must \
12936                 route through",
12937            );
12938        }
12939    }
12940
12941    #[test]
12942    fn validate_restart_window_bracket_arm_routes_through_accessor() {
12943        // Composition pin: [`SupervisorSpec::validate`]'s
12944        // `:restart-window` `if let Some(w) = self.restart_window() { … }`
12945        // zero-floor + integer-millisecond canonical-form + upper-cap
12946        // bracket-arm must key off [`SupervisorSpec::restart_window`], not
12947        // the raw `.restart_window` field access. Structurally: a
12948        // `SupervisorSpec { restart_window: None, .. }` must pass the
12949        // arm gate structurally (the `if let Some(_)` shape returns
12950        // early on the `None` arm — the accessor and the validate gate
12951        // must agree on `None → skip the bracket cascade` so an authored
12952        // `:restart-window ()` structurally routes through the "never
12953        // reset" sentinel path), a `SupervisorSpec { restart_window:
12954        // Some(Duration::ZERO), .. }` must surface the `RestartWindowZero`
12955        // refusal exactly, a `SupervisorSpec { restart_window:
12956        // Some(Duration::from_micros(1500)), .. }` must surface the
12957        // `RestartWindowNotCanonical` refusal exactly (with the offending
12958        // duration carried verbatim from the accessor return), a
12959        // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX
12960        // + Duration::from_millis(1)), .. }` must surface the
12961        // `RestartWindowExceedsCap` refusal exactly (with the offending
12962        // duration carried verbatim from the accessor return), and a
12963        // `SupervisorSpec { restart_window: Some(Duration::from_millis(1)),
12964        // .. }` (the lower boundary of the accept-set) plus a
12965        // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
12966        // .. }` (the upper boundary) must pass validate. The six together
12967        // jointly pin the accessor + validate-gate composition: any future
12968        // silent detour that had the accessor return a fresh `None` on any
12969        // `Some` arm (a `.restart_window().filter(|w| !w.is_zero())`
12970        // collapse) would silently absorb the `RestartWindowZero` refusal
12971        // at the accessor boundary and the validate gate would accept a
12972        // struct-literal `SupervisorSpec { restart_window:
12973        // Some(Duration::ZERO), .. }` — the composition pin catches that
12974        // at caixa-core build time.
12975        //
12976        // Peer of the sibling M2 [`crate::LimitsSpec::wall_clock`]
12977        // (8cb717b) validate-arm-route pin on the per-`:limits :wall-clock`
12978        // axis and the peer M3 [`crate::MeshPolicy::timeout`] (7073d0f)
12979        // accessor-composition pin on the per-`:politicas :timeout` axis —
12980        // same "the validate / shape-gate predicate must route through
12981        // the substrate-primitive typed dispatch" discipline extended
12982        // onto the peer M2 supervisor-slot optional-`Duration` axis.
12983        let child = ChildSpec {
12984            caixa: "worker".into(),
12985            versao: "^0.1".into(),
12986            restart: RestartPolicy::Permanent,
12987        };
12988        // None arm — must not surface any :restart-window-shaped refusal;
12989        // the `if let Some(_)` bracket returns early on `None` structurally.
12990        let s = SupervisorSpec {
12991            restart_window: None,
12992            children: vec![child.clone()],
12993            ..SupervisorSpec::default()
12994        };
12995        assert!(
12996            s.validate().is_ok(),
12997            "validate must accept restart_window: None (the never-reset \
12998             sentinel) — the `if let Some(_)` bracket returns early on \
12999             the None arm and the accessor must agree",
13000        );
13001        // Zero-floor arm.
13002        let s = SupervisorSpec {
13003            restart_window: Some(Duration::ZERO),
13004            children: vec![child.clone()],
13005            ..SupervisorSpec::default()
13006        };
13007        assert_eq!(
13008            s.validate().unwrap_err(),
13009            SupervisorError::RestartWindowZero,
13010            "validate must reject restart_window == Some(Duration::ZERO) \
13011             with RestartWindowZero — the accessor and the validate gate \
13012             must route through the same substrate-primitive typed \
13013             dispatch on the zero-floor arm",
13014        );
13015        // Non-canonical (sub-ms) arm — the surfaced `window:` field must
13016        // byte-equal the accessor's return so a future rebrand on the
13017        // accessor lands in the diagnostic without a coordinated rewrite.
13018        let sub_ms = Duration::from_micros(1500);
13019        let s = SupervisorSpec {
13020            restart_window: Some(sub_ms),
13021            children: vec![child.clone()],
13022            ..SupervisorSpec::default()
13023        };
13024        match s.validate().unwrap_err() {
13025            SupervisorError::RestartWindowNotCanonical { window } => {
13026                assert_eq!(
13027                    Some(window),
13028                    s.restart_window(),
13029                    "RestartWindowNotCanonical.window must byte-equal \
13030                     SupervisorSpec::restart_window().unwrap() — the \
13031                     non-canonical-arm refusal reads through the lifted \
13032                     accessor",
13033                );
13034                assert_eq!(
13035                    window, sub_ms,
13036                    "RestartWindowNotCanonical.window must carry the \
13037                     author-declared :supervisor :restart-window value \
13038                     verbatim (got {window:?}, expected {sub_ms:?})",
13039                );
13040            }
13041            other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
13042        }
13043        // Cap arm — the surfaced `window:` field must byte-equal the
13044        // accessor's return.
13045        let over_cap = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
13046        let s = SupervisorSpec {
13047            restart_window: Some(over_cap),
13048            children: vec![child.clone()],
13049            ..SupervisorSpec::default()
13050        };
13051        match s.validate().unwrap_err() {
13052            SupervisorError::RestartWindowExceedsCap { window } => {
13053                assert_eq!(
13054                    Some(window),
13055                    s.restart_window(),
13056                    "RestartWindowExceedsCap.window must byte-equal \
13057                     SupervisorSpec::restart_window().unwrap() — the \
13058                     cap-arm refusal reads through the lifted accessor",
13059                );
13060                assert_eq!(
13061                    window, over_cap,
13062                    "RestartWindowExceedsCap.window must carry the \
13063                     author-declared :supervisor :restart-window value \
13064                     verbatim (got {window:?}, expected {over_cap:?})",
13065                );
13066            }
13067            other => panic!("expected RestartWindowExceedsCap, got {other:?}"),
13068        }
13069        // Lower + upper accept-set boundaries.
13070        for restart_window in [Duration::from_millis(1), SUPERVISOR_RESTART_WINDOW_MAX] {
13071            let s = SupervisorSpec {
13072                restart_window: Some(restart_window),
13073                children: vec![child.clone()],
13074                ..SupervisorSpec::default()
13075            };
13076            assert!(
13077                s.validate().is_ok(),
13078                "validate must accept restart_window == Some({restart_window:?}) \
13079                 (an accept-set boundary of \
13080                 1ms..=SUPERVISOR_RESTART_WINDOW_MAX)",
13081            );
13082        }
13083    }
13084
13085    #[test]
13086    fn supervisor_spec_restart_window_projects_option_duration_by_copy() {
13087        // The by-copy pin: [`SupervisorSpec::restart_window`] returns
13088        // `Option<Duration>` by copy — `Duration` is `Copy` (so
13089        // `Option<Duration>` is `Copy`) and the accessor must return by
13090        // value, not by reference. Peer of the sibling M2
13091        // [`crate::LimitsSpec::wall_clock`] (8cb717b) by-copy pin on the
13092        // per-`:limits :wall-clock` axis and the sibling M3
13093        // [`crate::MeshPolicy::timeout`] (7073d0f) by-copy pin on the
13094        // per-`:politicas :timeout` axis, extended onto the peer M2
13095        // supervisor-slot `Option<Duration>` copy-invariant shape — the
13096        // accessor's returned `Option<Duration>` must outlive `&self`
13097        // (multiple calls must return equal values from a dropped-`&self`
13098        // copy, since the returned Option carries no borrow), and calling
13099        // the accessor twice on the same SupervisorSpec must yield the
13100        // same `Option<Duration>` verbatim (idempotent, no side effects
13101        // on `&self`).
13102        //
13103        // Pins against a future silent detour that returned
13104        // `Option<&Duration>` (which would type-check but silently break
13105        // every downstream caller — the future wasm-operator's
13106        // per-supervisor restart-intensity counter consumes `Duration` by
13107        // value and `&Duration` would fold to a detached copy at the call
13108        // site), an accidental `Option::as_ref()` projection
13109        // (`self.restart_window.as_ref()` would also type-check but
13110        // return `Option<&Duration>`), or a one-arm-only accessor that
13111        // reads `Some(*w)` in the Some arm but reads a fresh
13112        // `Default::default()` (which would collapse to `Duration::ZERO`,
13113        // not `None`) in the None arm — a footgun the
13114        // [`SupervisorError::RestartWindowZero`] validate arm explicitly
13115        // closes since Erlang/OTP's `MaxIntensity / Period` invariant
13116        // requires `Period > 0` and `None` structurally expresses "never
13117        // reset" instead.
13118        for restart_window in [
13119            None,
13120            Some(Duration::from_millis(1)),
13121            Some(Duration::from_secs(60)),
13122            Some(SUPERVISOR_RESTART_WINDOW_MAX),
13123        ] {
13124            let s = SupervisorSpec {
13125                restart_window,
13126                ..SupervisorSpec::default()
13127            };
13128            let first = s.restart_window();
13129            let second = s.restart_window();
13130            assert_eq!(
13131                first, second,
13132                "SupervisorSpec::restart_window must be idempotent — two \
13133                 successive calls on the same &self must return the \
13134                 same Option<Duration>",
13135            );
13136            assert_eq!(
13137                first, restart_window,
13138                "SupervisorSpec::restart_window must return :supervisor \
13139                 :restart-window verbatim by copy — got {first:?}, \
13140                 expected {restart_window:?}",
13141            );
13142        }
13143    }
13144
13145    // ── per-`:supervisor` `:children` typed-accessor coherence pins ─────────
13146    //
13147    // The [`SupervisorSpec::children`] accessor lift is the seed of the
13148    // slice-return (`&[T]`) accessor discipline on the substrate — the four
13149    // peer `Vec`-carry axes ([`crate::Placement::clusters`],
13150    // [`crate::AplicacaoSpec::membros`], [`crate::AplicacaoSpec::contratos`],
13151    // [`crate::UpgradeFromEntry::instructions`]) still key off the raw field
13152    // access at the time of this seed, and inherit this pin family's
13153    // discipline as future compounding runs migrate their consumers. The
13154    // three pins below cover (1) the accessor's byte-equal projection
13155    // against the raw field access across the empty / singleton / cohort
13156    // fixtures the [`SupervisorSpec::validate`] partition-dispatch fans
13157    // between, (2) the [`SupervisorSpec::validate`] `SimpleOneForOne ↔
13158    // non-SimpleOneForOne` partition dispatch's paired `.is_empty()`
13159    // consumer routing through the accessor on both arms, and (3) the
13160    // per-child validate loop's traversal reading the same slice-view the
13161    // accessor projects. Peer of the sibling M2
13162    // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
13163    // two-consumer coherence pin on the per-`:supervisor`
13164    // sibling-restart-strategy `Copy`-composite-enum scalar axis, extended
13165    // onto the per-`:supervisor` static-child-list `Vec`-carry axis.
13166
13167    #[test]
13168    fn supervisor_spec_children_returns_children_slice_byte_equal_across_permutations() {
13169        // The canonical per-`:supervisor` static-child-list scalar-shape
13170        // pin: [`SupervisorSpec::children`] must return the `:supervisor
13171        // :children` typed `Vec<ChildSpec>` verbatim as a `&[ChildSpec]`
13172        // slice-view over the same backing buffer the raw
13173        // `self.children.as_slice()` field access borrows from, byte-
13174        // equal across every representative fixture in the accept-set —
13175        // the empty slice (the `SimpleOneForOne`-arm sentinel),
13176        // the singleton slice (the minimal non-`SimpleOneForOne` shape),
13177        // and a two-child cohort (a peer non-`SimpleOneForOne` shape
13178        // with the peer three restart-policy variants in play).
13179        //
13180        // Pins against a future silent detour that returned
13181        // `&Vec<ChildSpec>` (which would type-check but leak the
13182        // storage-side `Vec`'s grow/push/reserve surface no consumer of
13183        // the typed view reaches for), a fresh-allocated
13184        // `Vec<ChildSpec>` copy (which would type-check via a coercion
13185        // but silently break every downstream caller that relied on the
13186        // slice sharing the backing buffer's identity), or an
13187        // out-of-order or length-drifted projection (which would silently
13188        // split the per-child validate loop's traversal input from the
13189        // paired partition-dispatch `.is_empty()` probe's input).
13190        //
13191        // Peer of the sibling
13192        // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
13193        // (eafb619) `Copy`-composite-enum byte-equal pin on the
13194        // per-`:supervisor` sibling-restart-strategy axis, extended onto
13195        // the per-`:supervisor` static-child-list `Vec`-carry axis.
13196        let fixtures: Vec<Vec<ChildSpec>> = vec![
13197            Vec::new(),
13198            vec![child("worker", "^0.1", RestartPolicy::Permanent)],
13199            vec![
13200                child("worker", "^0.1", RestartPolicy::Permanent),
13201                child("cache-server", "^0.1", RestartPolicy::Transient),
13202            ],
13203            vec![
13204                child("worker", "^0.1", RestartPolicy::Permanent),
13205                child("cache-server", "^0.1", RestartPolicy::Transient),
13206                child("scratch-job", "^0.1", RestartPolicy::Temporary),
13207            ],
13208        ];
13209        for children in fixtures {
13210            let s = SupervisorSpec {
13211                children: children.clone(),
13212                ..SupervisorSpec::default()
13213            };
13214            assert_eq!(
13215                s.children(),
13216                children.as_slice(),
13217                "SupervisorSpec::children must return :supervisor \
13218                 :children verbatim (got {:?}, expected {:?})",
13219                s.children(),
13220                children.as_slice(),
13221            );
13222            assert_eq!(
13223                s.children(),
13224                s.children.as_slice(),
13225                "SupervisorSpec::children accessor and \
13226                 .children.as_slice() field access must byte-equal — \
13227                 the accessor is the substrate-primitive typed \
13228                 dispatch every downstream static-child-list consumer \
13229                 must route through",
13230            );
13231            assert_eq!(
13232                s.children().len(),
13233                s.children.len(),
13234                "SupervisorSpec::children().len() must byte-equal \
13235                 self.children.len() — a length-drift would silently \
13236                 split the paired partition-dispatch `.is_empty()` \
13237                 probe input from the per-child validate loop's \
13238                 traversal input",
13239            );
13240        }
13241    }
13242
13243    #[test]
13244    fn validate_reads_through_lifted_children_accessor() {
13245        // Three-consumer coherence pin: the [`SupervisorSpec::validate`]
13246        // `SimpleOneForOne`-arm `!self.children().is_empty()` refusal
13247        // probe (which must trip [`SupervisorError::SimpleOneForOneWithStaticChildren`]
13248        // when the accessor projects a non-empty slice under a
13249        // `SimpleOneForOne` estrategia), the peer non-`SimpleOneForOne`-arm
13250        // `self.children().is_empty()` refusal probe (which must trip
13251        // [`SupervisorError::NoChildren`] when the accessor projects the
13252        // empty slice under any peer estrategia), and the per-child
13253        // validate loop's `for child in self.children()` traversal
13254        // (which must reach every entry in the same order the accessor
13255        // projects) must all key off the lifted accessor, so any future
13256        // rebrand on the typed slot's reader shape lands at exactly one
13257        // place. Pins the three-site coherence by exercising each
13258        // production consumer end-to-end: (1) the
13259        // `SimpleOneForOneWithStaticChildren` refusal under a non-empty
13260        // slice + `SimpleOneForOne` estrategia, (2) the `NoChildren`
13261        // refusal under the empty slice + non-`SimpleOneForOne`
13262        // estrategia across every peer variant, and (3) the per-child
13263        // duplicate-detection surface fires on the second entry of a
13264        // two-child cohort that shares a `:caixa` name (which requires
13265        // the loop to reach both entries — a first-entry-only projection
13266        // would silently pass since the dedup HashSet has room for the
13267        // first insert).
13268        //
13269        // Peer of the sibling M2
13270        // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
13271        // two-consumer coherence pin on the per-`:supervisor`
13272        // sibling-restart-strategy axis, extended onto the
13273        // per-`:supervisor` static-child-list `Vec`-carry axis.
13274
13275        // (1) `SimpleOneForOne`-arm probe: a non-empty slice under a
13276        // `SimpleOneForOne` estrategia must trip
13277        // `SimpleOneForOneWithStaticChildren`.
13278        let s = SupervisorSpec {
13279            estrategia: RestartStrategy::SimpleOneForOne,
13280            children: vec![child("worker", "^0.1", RestartPolicy::Permanent)],
13281            ..SupervisorSpec::default()
13282        };
13283        assert_eq!(
13284            s.validate().unwrap_err(),
13285            SupervisorError::SimpleOneForOneWithStaticChildren,
13286            "SimpleOneForOne + non-empty children must trip \
13287             SimpleOneForOneWithStaticChildren — the accessor projects \
13288             a non-empty slice, and the SimpleOneForOne-arm refusal \
13289             probe reads through the lifted accessor",
13290        );
13291        assert!(
13292            !s.children().is_empty(),
13293            "the SimpleOneForOne-arm refusal input must be a non-empty \
13294             slice per the accessor's projection",
13295        );
13296
13297        // (2) Peer non-`SimpleOneForOne`-arm probe: the empty slice
13298        // under any peer estrategia must trip `NoChildren`.
13299        for estrategia in [
13300            RestartStrategy::OneForOne,
13301            RestartStrategy::OneForAll,
13302            RestartStrategy::RestForOne,
13303        ] {
13304            let s = SupervisorSpec {
13305                estrategia,
13306                children: Vec::new(),
13307                ..SupervisorSpec::default()
13308            };
13309            match s.validate().unwrap_err() {
13310                SupervisorError::NoChildren { estrategia: e } => {
13311                    assert_eq!(
13312                        e, estrategia,
13313                        "NoChildren.estrategia must carry the author-\
13314                         declared :supervisor :estrategia variant \
13315                         verbatim (got {e:?}, expected {estrategia:?})",
13316                    );
13317                }
13318                other => panic!(
13319                    "expected NoChildren, got {other:?} for \
13320                     estrategia={estrategia:?}"
13321                ),
13322            }
13323            assert!(
13324                s.children().is_empty(),
13325                "the non-SimpleOneForOne-arm refusal input must be the \
13326                 empty slice per the accessor's projection",
13327            );
13328        }
13329
13330        // (3) Per-child validate loop: a two-child cohort that shares a
13331        // `:caixa` name must trip `DuplicateChildCaixa` — the loop must
13332        // reach both entries through the accessor.
13333        let s = SupervisorSpec {
13334            estrategia: RestartStrategy::OneForOne,
13335            children: vec![
13336                child("worker", "^0.1", RestartPolicy::Permanent),
13337                child("worker", "^0.2", RestartPolicy::Transient),
13338            ],
13339            ..SupervisorSpec::default()
13340        };
13341        match s.validate().unwrap_err() {
13342            SupervisorError::DuplicateChildCaixa { caixa } => {
13343                assert_eq!(
13344                    caixa, "worker",
13345                    "DuplicateChildCaixa.caixa must carry the shared \
13346                     child `:caixa` name verbatim",
13347                );
13348            }
13349            other => panic!("expected DuplicateChildCaixa, got {other:?}"),
13350        }
13351        assert_eq!(
13352            s.children().len(),
13353            2,
13354            "the per-child validate loop's traversal input must be a \
13355             two-element slice per the accessor's projection",
13356        );
13357    }
13358
13359    // Shared helper for the M2 per-`:children` per-slot-gate ≡
13360    // `validate` equivalence pins: builds an `OneForOne`-estrategia
13361    // one-cohort spec whose peer `:estrategia`↔`:children.is_empty()`
13362    // partition, `:max-restarts` zero-floor/cap, and `:restart-window`
13363    // bracket all pass cleanly so the sole failing surface is the
13364    // per-child cascade [`SupervisorSpec::validate_children`] owns, and
13365    // pins the two-altitude equivalence on the paired probe.
13366    fn assert_validate_children_matches_gate(children: Vec<ChildSpec>, expected: &SupervisorError) {
13367        let s = SupervisorSpec {
13368            estrategia: RestartStrategy::OneForOne,
13369            children,
13370            ..SupervisorSpec::default()
13371        };
13372        let via_gate = s.validate_children().unwrap_err();
13373        let via_validate = s.validate().unwrap_err();
13374        assert_eq!(&via_gate, expected, "validate_children direct dispatch",);
13375        assert_eq!(&via_validate, expected, "validate() end-to-end dispatch",);
13376        assert_eq!(
13377            via_gate, via_validate,
13378            "per-slot gate ≡ validate() must discriminate the same \
13379             refusal shape",
13380        );
13381    }
13382
13383    #[test]
13384    fn validate_children_matches_gate_on_per_axis_refusal_shapes() {
13385        // Fail-before-pass-after equivalence pin on the M2
13386        // per-`:children` per-slot gate ≡ [`SupervisorSpec::validate`]
13387        // convergence — sibling of the M3 mesh-slot
13388        // `validate_membros_*` / `validate_contratos_*` /
13389        // `validate_entrada_*` per-slot-gate ≡ `validate` pins on the
13390        // peer per-entry axes. Sweeps four of the five refusal shapes
13391        // the per-slot gate owns: (1) `EmptyChildName` on an empty-
13392        // `:caixa` child, (2) `ChildCaixaInvalid` on a structurally
13393        // invalid `:caixa` DNS-1123 label, (3) `EmptyChildVersion` on
13394        // an empty-`:versao` child, (4) `DuplicateChildCaixa` on a
13395        // duplicate-`:caixa` fan-out. Companion pin
13396        // `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
13397        // covers `ChildVersaoInvalid` (whose parser-owned reason string
13398        // needs pattern-matching, not equality) and the clean-pass
13399        // canonical fixture; together the two pins guarantee the
13400        // per-slot gate and `validate` discriminate the same set on
13401        // every per-child-covered input.
13402        assert_validate_children_matches_gate(
13403            vec![child("", "^0.1", RestartPolicy::Permanent)],
13404            &SupervisorError::EmptyChildName,
13405        );
13406        assert_validate_children_matches_gate(
13407            vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
13408            &SupervisorError::ChildCaixaInvalid {
13409                caixa: "Worker".into(),
13410                reason: "contains uppercase character 'W' (K8s DNS-1123 label names are lowercase-only; use \"worker\")".into(),
13411            },
13412        );
13413        assert_validate_children_matches_gate(
13414            vec![child("worker", "", RestartPolicy::Permanent)],
13415            &SupervisorError::EmptyChildVersion {
13416                caixa: "worker".into(),
13417            },
13418        );
13419        assert_validate_children_matches_gate(
13420            vec![
13421                child("worker", "^0.1", RestartPolicy::Permanent),
13422                child("worker", "^0.2", RestartPolicy::Transient),
13423            ],
13424            &SupervisorError::DuplicateChildCaixa {
13425                caixa: "worker".into(),
13426            },
13427        );
13428    }
13429
13430    #[test]
13431    fn validate_children_matches_gate_on_versao_invalid_and_clean_pass() {
13432        // Second half of the two-altitude equivalence pin — covers the
13433        // one refusal shape whose reason string is parser-owned
13434        // (`ChildVersaoInvalid`, whose reason comes from the shared
13435        // [`crate::version::parse_requirement`] impl and may drift) and
13436        // the clean-pass canonical fixture. Sibling pin
13437        // `validate_children_matches_gate_on_per_axis_refusal_shapes`
13438        // covers the four equality-comparable refusal shapes.
13439        let s_bad_versao = SupervisorSpec {
13440            estrategia: RestartStrategy::OneForOne,
13441            children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
13442            ..SupervisorSpec::default()
13443        };
13444        let via_gate = s_bad_versao.validate_children().unwrap_err();
13445        let via_validate = s_bad_versao.validate().unwrap_err();
13446        match (&via_gate, &via_validate) {
13447            (
13448                SupervisorError::ChildVersaoInvalid {
13449                    caixa: cg,
13450                    versao: vg,
13451                    ..
13452                },
13453                SupervisorError::ChildVersaoInvalid {
13454                    caixa: cv,
13455                    versao: vv,
13456                    ..
13457                },
13458            ) => {
13459                assert_eq!(cg, "worker", "per-slot gate :caixa carrier");
13460                assert_eq!(vg, "not-a-req", "per-slot gate :versao carrier");
13461                assert_eq!(cv, "worker", "validate() :caixa carrier");
13462                assert_eq!(vv, "not-a-req", "validate() :versao carrier");
13463            }
13464            other => panic!("expected ChildVersaoInvalid on both altitudes, got {other:?}"),
13465        }
13466        assert_eq!(
13467            via_gate, via_validate,
13468            "per-slot gate ≡ validate() on ChildVersaoInvalid full envelope",
13469        );
13470
13471        let s_ok = SupervisorSpec {
13472            estrategia: RestartStrategy::OneForOne,
13473            children: vec![
13474                child("worker-a", "^0.1", RestartPolicy::Permanent),
13475                child("worker-b", "~0.2.3", RestartPolicy::Transient),
13476                child("collector", "*", RestartPolicy::Temporary),
13477            ],
13478            ..SupervisorSpec::default()
13479        };
13480        s_ok.validate_children()
13481            .expect("per-slot gate must accept the clean-pass fixture");
13482        s_ok.validate()
13483            .expect("validate() must accept the clean-pass fixture");
13484    }
13485
13486    #[test]
13487    fn validate_children_is_self_contained_on_children_slot() {
13488        // Self-containment pin: [`SupervisorSpec::validate_children`]
13489        // resolves the per-child cascade against `&self` alone, without
13490        // depending on the peer `:estrategia`/`:max-restarts`/
13491        // `:restart-window` gates having run first — same posture the M3
13492        // peer per-slot gates carry (`validate_membros`,
13493        // `validate_contratos`, `validate_entrada`, `validate_placement`,
13494        // routing through their own oracles rather than borrowing state
13495        // threaded down from `validate`). A future consumer that reaches
13496        // the per-slot gate directly on a spec whose peer slots would
13497        // fail `validate` still surfaces the per-child refusal, not the
13498        // peer refusal.
13499        //
13500        // Construct a spec whose `:max-restarts` is `0` (which would
13501        // trip [`SupervisorError::ZeroMaxRestarts`] at `validate` after
13502        // the partition-dispatch) and whose `:children` carries a
13503        // `DuplicateChildCaixa` shape: the per-slot gate called directly
13504        // must surface `DuplicateChildCaixa`, proving it does not depend
13505        // on the peer `:max-restarts` gate running first.
13506        let s = SupervisorSpec {
13507            estrategia: RestartStrategy::OneForOne,
13508            max_restarts: 0,
13509            restart_window: Some(Duration::from_secs(60)),
13510            children: vec![
13511                child("worker", "^0.1", RestartPolicy::Permanent),
13512                child("worker", "^0.2", RestartPolicy::Transient),
13513            ],
13514        };
13515        assert_eq!(
13516            s.validate_children().unwrap_err(),
13517            SupervisorError::DuplicateChildCaixa {
13518                caixa: "worker".into(),
13519            },
13520            "per-slot gate must resolve per-child refusal directly against \
13521             `&self` — a dependency on the peer `:max-restarts` gate \
13522             running first would surface ZeroMaxRestarts here instead",
13523        );
13524        // The peer gate is still the surface `validate` reaches — pin
13525        // the ordering to establish that `validate_children` truly runs
13526        // last in `validate`'s dispatch, so a direct call bypasses the
13527        // peer gates on any spec whose per-child cascade would fail.
13528        assert_eq!(
13529            s.validate().unwrap_err(),
13530            SupervisorError::ZeroMaxRestarts,
13531            "validate() must surface the peer `:max-restarts` gate before \
13532             reaching the per-child cascade — this pins the dispatch \
13533             ordering the per-slot gate's self-containment complements",
13534        );
13535    }
13536
13537    #[test]
13538    fn child_spec_restart_accessor_is_const_fn() {
13539        // The [`ChildSpec::restart`] per-`:children` restart-decision-
13540        // policy `Copy`-return scalar accessor is declared
13541        // `#[must_use] pub const fn` — matching the sibling M2
13542        // per-`:supervisor` [`SupervisorSpec::estrategia`] (pinned by
13543        // [`supervisor_spec_estrategia_accessor_is_const_fn`] below,
13544        // both converted in this commit), the sibling M2
13545        // per-`:supervisor` [`SupervisorSpec::max_restarts`] (b698ec0)
13546        // `Copy`-`u32` accessor already `pub const fn`, and the peer M3
13547        // mesh-slot per-`:entrada` [`crate::Entrada::port`] (bafa004) /
13548        // per-`:placement` [`crate::Placement::estrategia`] (bafa004)
13549        // `Copy`-return `pub const fn` scalar accessors on the sibling
13550        // M3 surface. Pin the `const`-eval posture here so a future
13551        // accidental downgrade to non-`const` (an added runtime helper
13552        // reachable only from a non-`const` context, an
13553        // `Option<RestartPolicy>`-shape migration on the per-child
13554        // restart-decision axis once heterogeneous per-cluster
13555        // restart-policy overlays land that would silently drop the
13556        // `const` qualifier, a manual hand-rolled shadow) trips at
13557        // caixa-core build time rather than surfacing as a downstream
13558        // `const`-context regression far from the declaration.
13559        //
13560        // Same shape as the sibling M3
13561        // [`crate::aplicacao::tests::placement_estrategia_accessor_is_const_fn`]
13562        // and [`crate::aplicacao::tests::entrada_port_accessor_is_const_fn`]
13563        // (bafa004) pins on the peer M3 mesh-slot `Copy`-return scalar
13564        // accessor axis — the load-bearing witness lives in the
13565        // module-scope `const fn` wrapper `restart_via_const_fn` below:
13566        // a body that calls [`ChildSpec::restart`] under a `const fn`
13567        // signature is well-formed only when the callee is itself
13568        // `const fn`, so any future accidental downgrade of
13569        // [`ChildSpec::restart`] to non-`const` fails at caixa-core
13570        // build time (const-eval E0015 `cannot call non-const method`),
13571        // strictly stronger than a runtime `assert!(CONST)` and
13572        // side-stepping the destructor-in-const restriction that
13573        // blocks direct `const _: RestartPolicy = FIXTURE.restart()`
13574        // items on `ChildSpec`'s `String` carriers.
13575        //
13576        // The runtime body sweeps every closed-set [`RestartPolicy`]
13577        // arm and asserts the wrapped and direct dispatches agree.
13578        const fn restart_via_const_fn(c: &ChildSpec) -> RestartPolicy {
13579            c.restart()
13580        }
13581        for restart in [
13582            RestartPolicy::Permanent,
13583            RestartPolicy::Transient,
13584            RestartPolicy::Temporary,
13585        ] {
13586            let c = ChildSpec {
13587                caixa: "worker".into(),
13588                versao: "^0.1".into(),
13589                restart,
13590            };
13591            assert_eq!(
13592                restart_via_const_fn(&c),
13593                c.restart(),
13594                "const-fn-wrapped and direct dispatch on \
13595                 ChildSpec::restart must agree for {restart:?}",
13596            );
13597            assert_eq!(
13598                c.restart(),
13599                restart,
13600                "ChildSpec::restart must return the storage-side \
13601                 RestartPolicy verbatim for {restart:?} (a violation \
13602                 means the accessor stopped being a raw field-return \
13603                 copy)",
13604            );
13605        }
13606    }
13607
13608    #[test]
13609    fn supervisor_spec_estrategia_accessor_is_const_fn() {
13610        // The [`SupervisorSpec::estrategia`] per-`:supervisor`
13611        // sibling-restart-strategy `Copy`-return scalar accessor is
13612        // declared `#[must_use] pub const fn` — matching the sibling M2
13613        // per-`:children` [`ChildSpec::restart`] (pinned by
13614        // [`child_spec_restart_accessor_is_const_fn`] above, both
13615        // converted in this commit), the sibling M2 per-`:supervisor`
13616        // [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32`
13617        // accessor already `pub const fn`, and mirroring the peer M3
13618        // mesh-slot per-`:placement`
13619        // [`crate::Placement::estrategia`] (bafa004) `Copy`-return
13620        // `pub const fn` scalar accessor whose method-name discipline
13621        // the [`SupervisorSpec::estrategia`] method was authored to
13622        // match. Pin the `const`-eval posture here so a future
13623        // accidental downgrade to non-`const` (an added runtime helper
13624        // reachable only from a non-`const` context, an
13625        // `Option<RestartStrategy>`-shape migration once the substrate
13626        // grows per-cluster strategy overlays that would silently drop
13627        // the `const` qualifier, a manual hand-rolled shadow) trips at
13628        // caixa-core build time rather than surfacing as a downstream
13629        // `const`-context regression far from the declaration.
13630        //
13631        // Same shape as the sibling
13632        // [`child_spec_restart_accessor_is_const_fn`] pin above — the
13633        // load-bearing witness lives in the module-scope `const fn`
13634        // wrapper `estrategia_via_const_fn` below: a body that calls
13635        // [`SupervisorSpec::estrategia`] under a `const fn` signature
13636        // is well-formed only when the callee is itself `const fn`,
13637        // side-stepping the destructor-in-const restriction that would
13638        // otherwise block a direct
13639        // `const _: RestartStrategy = FIXTURE.estrategia()` item on
13640        // `SupervisorSpec`'s `Vec<ChildSpec>` / `Option<Duration>`
13641        // carriers.
13642        //
13643        // The runtime body sweeps every closed-set [`RestartStrategy`]
13644        // arm via [`RestartStrategy::ALL`] and asserts the wrapped and
13645        // direct dispatches agree.
13646        const fn estrategia_via_const_fn(s: &SupervisorSpec) -> RestartStrategy {
13647            s.estrategia()
13648        }
13649        for &estrategia in RestartStrategy::ALL {
13650            let s = SupervisorSpec {
13651                estrategia,
13652                max_restarts: 5,
13653                restart_window: Some(Duration::from_secs(60)),
13654                children: Vec::new(),
13655            };
13656            assert_eq!(
13657                estrategia_via_const_fn(&s),
13658                s.estrategia(),
13659                "const-fn-wrapped and direct dispatch on \
13660                 SupervisorSpec::estrategia must agree for {estrategia:?}",
13661            );
13662            assert_eq!(
13663                s.estrategia(),
13664                estrategia,
13665                "SupervisorSpec::estrategia must return the storage-side \
13666                 RestartStrategy verbatim for {estrategia:?} (a violation \
13667                 means the accessor stopped being a raw field-return \
13668                 copy)",
13669            );
13670        }
13671    }
13672
13673    // Per-variant equivalence pins for the [`supervisor_caixa_only_ctors!`]
13674    // macro definition (see the paired doc-block above the macro
13675    // definition) — every generated `<ctor>(caixa: &str) -> Self`
13676    // constructor folds the uniform `Self::<Variant> { caixa:
13677    // caixa.to_string() }` one-field struct-literal onto one substrate
13678    // primitive. The three per-variant equivalence pins below
13679    // (fail-before-pass-after by construction — a byte-mismatched macro
13680    // arm would trip its equivalence pin first) lock each generated
13681    // constructor to its struct-literal peer under `PartialEq`, so
13682    // every wire-up in [`SupervisorSpec::validate_children`] and
13683    // [`validate_no_self_supervision`] on that variant produces a
13684    // byte-equal `SupervisorError` to the pre-lift open-coded
13685    // struct-literal. The cross-axis pin that follows (non-default
13686    // caixa name) routes the sole constructor input axis through
13687    // `.to_string()`, so the fold does not silently collapse onto a
13688    // fixed name.
13689    //
13690    // Peer of the sibling `<slot>_ctor_matches_tuple_literal_wrap` /
13691    // `<slot>_violation_ctor_matches_struct_literal_wrap` /
13692    // `<slot>_slots_on_non_<owner>_ctor_matches_struct_literal_wrap` /
13693    // `missing_entry_ctor_matches_struct_literal_wrap` /
13694    // `entrada_host_invalid_ctor_matches_struct_literal_wrap` /
13695    // `contrato_wrong_target_ctor_matches_struct_literal_wrap` /
13696    // `contrato_missing_target_ctor_matches_struct_literal_wrap` /
13697    // `<variant>_ctor_matches_struct_literal_wrap` equivalence pins
13698    // on the six sibling ctor families the recent trajectory closed
13699    // on the peer `LayoutError` / `AplicacaoError` envelopes.
13700
13701    #[test]
13702    fn empty_child_version_ctor_matches_struct_literal_wrap() {
13703        assert_eq!(
13704            SupervisorError::empty_child_version("worker"),
13705            SupervisorError::EmptyChildVersion {
13706                caixa: "worker".to_string(),
13707            },
13708            "generated empty_child_version ctor must produce byte-equal \
13709             SupervisorError to the open-coded struct-literal wrap on the \
13710             same &str fixture",
13711        );
13712    }
13713
13714    #[test]
13715    fn duplicate_child_caixa_ctor_matches_struct_literal_wrap() {
13716        assert_eq!(
13717            SupervisorError::duplicate_child_caixa("worker"),
13718            SupervisorError::DuplicateChildCaixa {
13719                caixa: "worker".to_string(),
13720            },
13721            "generated duplicate_child_caixa ctor must produce byte-equal \
13722             SupervisorError to the open-coded struct-literal wrap on the \
13723             same &str fixture",
13724        );
13725    }
13726
13727    #[test]
13728    fn child_supervises_self_ctor_matches_struct_literal_wrap() {
13729        assert_eq!(
13730            SupervisorError::child_supervises_self("orquestra"),
13731            SupervisorError::ChildSupervisesSelf {
13732                caixa: "orquestra".to_string(),
13733            },
13734            "generated child_supervises_self ctor must produce byte-equal \
13735             SupervisorError to the open-coded struct-literal wrap on the \
13736             same &str fixture",
13737        );
13738    }
13739
13740    // Per-variant equivalence pins for the two lifted
13741    // [`SupervisorError::child_caixa_invalid`] /
13742    // [`SupervisorError::child_versao_invalid`] inherent constructors
13743    // (fail-before-pass-after by construction — a byte-mismatched ctor body
13744    // would trip its equivalence pin first). Each pins the ctor output to
13745    // its pre-lift struct-literal peer under `PartialEq`, so every wire-up
13746    // in [`SupervisorSpec::validate_children`] on the two variants
13747    // produces a byte-equal `SupervisorError` to the pre-lift open-coded
13748    // struct-literal on the same scalar fixtures. Peers of the sibling
13749    // `membro_caixa_invalid_ctor_matches_struct_literal_wrap` /
13750    // `entrada_para_invalid_ctor_matches_struct_literal_wrap` / … pins on
13751    // the peer `AplicacaoError` envelope's
13752    // [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold.
13753
13754    #[test]
13755    fn child_caixa_invalid_ctor_matches_struct_literal_wrap() {
13756        let caixa = "Worker";
13757        let reason = "sample reason text";
13758        assert_eq!(
13759            SupervisorError::child_caixa_invalid(caixa, reason),
13760            SupervisorError::ChildCaixaInvalid {
13761                caixa: caixa.to_string(),
13762                reason: reason.to_string(),
13763            },
13764            "lifted child_caixa_invalid ctor must produce byte-equal \
13765             SupervisorError to the open-coded struct-literal wrap on the \
13766             same (&str, reason) fixture",
13767        );
13768    }
13769
13770    #[test]
13771    fn child_versao_invalid_ctor_matches_struct_literal_wrap() {
13772        let caixa = "worker";
13773        let versao = "not-a-req";
13774        let reason = "sample reason text";
13775        assert_eq!(
13776            SupervisorError::child_versao_invalid(caixa, versao, reason),
13777            SupervisorError::ChildVersaoInvalid {
13778                caixa: caixa.to_string(),
13779                versao: versao.to_string(),
13780                reason: reason.to_string(),
13781            },
13782            "lifted child_versao_invalid ctor must produce byte-equal \
13783             SupervisorError to the open-coded struct-literal wrap on the \
13784             same (&str, &str, reason) fixture",
13785        );
13786    }
13787
13788    #[test]
13789    fn supervisor_child_reason_ctors_route_reason_through_into_uniformly() {
13790        // Cross-axis pin: sweep the two lifted `{ …, reason }` ctors
13791        // against a `&str`-literal vs. `format!(…)` reason input to pin
13792        // both constructors accept the `impl Into<String>` bound
13793        // uniformly, so neither wire-up site drifts under a per-arm
13794        // wrapper transformation on the caller-side `reason` axis. Peer
13795        // of the sibling
13796        // `aplicacao_field_reason_ctors_route_reason_through_into_uniformly`
13797        // sweep on the peer `AplicacaoError` envelope.
13798        let via_literal = "literal reason text";
13799        let via_format = format!("{} reason text", "literal");
13800        assert_eq!(
13801            SupervisorError::child_caixa_invalid("Worker", via_literal),
13802            SupervisorError::child_caixa_invalid("Worker", via_format.clone()),
13803        );
13804        assert_eq!(
13805            SupervisorError::child_versao_invalid("worker", "not-a-req", via_literal),
13806            SupervisorError::child_versao_invalid("worker", "not-a-req", via_format),
13807        );
13808    }
13809
13810    #[test]
13811    fn supervisor_caixa_only_ctors_route_caixa_through_to_string() {
13812        // Cross-axis pin: sweep the sole constructor input axis (`caixa:
13813        // &str`) through a non-default fixture name against every
13814        // generated arm in the [`supervisor_caixa_only_ctors!`] macro,
13815        // so any wrapper-side lowercase / trim / truncate / re-order on
13816        // the `caixa.to_string()` sole-field construction surfaces
13817        // here rather than at a downstream diagnostic-shape mismatch.
13818        // Peer of the sibling `nome_only_ctor_routes_caixa_through_
13819        // nome_accessor` / `entrada_host_invalid_ctor_routes_host_
13820        // through_to_string` / `contrato_target_ctors_route_edge_
13821        // triple_through_verbatim` / `contrato_empty_pair_ctors_
13822        // route_edge_pair_through_verbatim` cross-axis routing pins on
13823        // the peer `LayoutError` / `AplicacaoError` envelopes; extended
13824        // here onto the `SupervisorError` `{ caixa: String }` envelope
13825        // so every substrate-primitive ctor family in caixa-core
13826        // guarantees the sole-field construction routes the caller's
13827        // `&str` through `.to_string()` verbatim.
13828        let name = "cache-v2";
13829        assert_eq!(
13830            SupervisorError::empty_child_version(name),
13831            SupervisorError::EmptyChildVersion {
13832                caixa: name.to_string(),
13833            },
13834        );
13835        assert_eq!(
13836            SupervisorError::duplicate_child_caixa(name),
13837            SupervisorError::DuplicateChildCaixa {
13838                caixa: name.to_string(),
13839            },
13840        );
13841        assert_eq!(
13842            SupervisorError::child_supervises_self(name),
13843            SupervisorError::ChildSupervisesSelf {
13844                caixa: name.to_string(),
13845            },
13846        );
13847    }
13848
13849    // ── supervisor_scalar_ctors! per-variant + cross-axis pins ──────────────
13850    //
13851    // Per-variant byte-equality pins guaranteeing every generated ctor arm in
13852    // the [`supervisor_scalar_ctors!`] macro produces a `SupervisorError`
13853    // structurally identical to the pre-lift `Self::<variant> { <field>: <val> }`
13854    // one-line struct-literal on the same `Copy`-`RestartStrategy | u32 |
13855    // Duration` fixture, plus one cross-axis sweep that routes each per-variant
13856    // `<field>: <ty>` scalar through the sole `$field:ident: $ty:ty` axis the
13857    // macro exposes so any wrapper-side truncation / re-order / silent `.into()`
13858    // / silent constant-substitution on any one variant surfaces here rather
13859    // than at a downstream per-`:supervisor` diagnostic-shape drift. Peer of the
13860    // sibling per-variant pins on `aplicacao_policy_scalar_ctors!` (7ef425e,
13861    // the 8-variant `AplicacaoError` `{ <field>: Duration | u32 }` fold on the
13862    // per-`:politicas` per-axis cap / canonical-form arms), plus the sibling
13863    // `supervisor_caixa_only_ctors!` (db09650), `SupervisorError::
13864    // {child_caixa_invalid,child_versao_invalid}` (d2ef2ec), and the peer
13865    // `DepError` / `AplicacaoError` / `LayoutError` / `LimitsError` /
13866    // `BehaviorError` / `UpgradeError` per-envelope ctor-macro pins.
13867    #[test]
13868    fn no_children_ctor_matches_struct_literal_wrap() {
13869        let estrategia = RestartStrategy::OneForAll;
13870        assert_eq!(
13871            SupervisorError::no_children(estrategia),
13872            SupervisorError::NoChildren { estrategia },
13873            "generated no_children ctor must produce byte-equal \
13874             `SupervisorError::NoChildren` to the pre-lift struct-literal wrap \
13875             on the same `Copy`-`RestartStrategy` fixture",
13876        );
13877    }
13878
13879    #[test]
13880    fn max_restarts_exceeds_cap_ctor_matches_struct_literal_wrap() {
13881        let max_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 1;
13882        assert_eq!(
13883            SupervisorError::max_restarts_exceeds_cap(max_restarts),
13884            SupervisorError::MaxRestartsExceedsCap { max_restarts },
13885            "generated max_restarts_exceeds_cap ctor must produce byte-equal \
13886             `SupervisorError::MaxRestartsExceedsCap` to the pre-lift \
13887             struct-literal wrap on the same `Copy`-`u32` fixture",
13888        );
13889    }
13890
13891    #[test]
13892    fn restart_window_not_canonical_ctor_matches_struct_literal_wrap() {
13893        let window = Duration::from_micros(1_500);
13894        assert_eq!(
13895            SupervisorError::restart_window_not_canonical(window),
13896            SupervisorError::RestartWindowNotCanonical { window },
13897            "generated restart_window_not_canonical ctor must produce \
13898             byte-equal `SupervisorError::RestartWindowNotCanonical` to the \
13899             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
13900        );
13901    }
13902
13903    #[test]
13904    fn restart_window_exceeds_cap_ctor_matches_struct_literal_wrap() {
13905        let window = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
13906        assert_eq!(
13907            SupervisorError::restart_window_exceeds_cap(window),
13908            SupervisorError::RestartWindowExceedsCap { window },
13909            "generated restart_window_exceeds_cap ctor must produce \
13910             byte-equal `SupervisorError::RestartWindowExceedsCap` to the \
13911             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
13912        );
13913    }
13914
13915    #[test]
13916    fn supervisor_scalar_ctors_route_field_through_copy_uniformly() {
13917        // Cross-axis routing pin: sweep each generated `<field>: <ty>`
13918        // constructor input axis through a non-default `Copy` fixture against
13919        // every arm in the [`supervisor_scalar_ctors!`] macro, so any wrapper-
13920        // side silent `.into()` / silent constant-substitution / silent field
13921        // re-name away from the canonical `estrategia | max_restarts | window`
13922        // axes on any one variant, or a `RestartStrategy | u32 | Duration`
13923        // axis silently rerouted through some other `Copy` coercion, surfaces
13924        // here rather than at a downstream per-`:supervisor` diagnostic-shape
13925        // drift. Peer of the sibling
13926        // `aplicacao_policy_scalar_ctors_route_field_through_copy_uniformly`
13927        // (7ef425e) cross-axis routing pin on the peer `AplicacaoError`
13928        // envelope's per-`:politicas` per-axis ctor family, extended here onto
13929        // the last M2 per-`:supervisor` `Copy`-scalar `SupervisorError`
13930        // variant family folded onto a substrate primitive.
13931        //
13932        // Fixtures picked out of each variant's accept-set boundary rather
13933        // than the default value so a silent constant-substitution to a per-
13934        // variant sentinel surfaces here on the structural-equality assertion.
13935        // The `RestartStrategy` fixture picks `RestForOne` (a non-default arm
13936        // that isn't the `OneForOne` [`SUPERVISOR_ESTRATEGIA_DEFAULT`] and
13937        // isn't the `SimpleOneForOne` arm the sibling
13938        // `SimpleOneForOneWithStaticChildren` unit variant intercepts). The
13939        // `max_restarts` fixture picks an above-cap magnitude the cap arm
13940        // rejects; the two `Duration` fixtures pick the sub-millisecond and
13941        // above-cap ends of the `:restart-window` canonical-form + cap
13942        // bracket respectively.
13943        let estrategia = RestartStrategy::RestForOne;
13944        let above_cap_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 137;
13945        let sub_ms = Duration::from_micros(1_500);
13946        let above_hour = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
13947        assert_eq!(
13948            SupervisorError::no_children(estrategia),
13949            SupervisorError::NoChildren { estrategia },
13950        );
13951        assert_eq!(
13952            SupervisorError::max_restarts_exceeds_cap(above_cap_restarts),
13953            SupervisorError::MaxRestartsExceedsCap {
13954                max_restarts: above_cap_restarts,
13955            },
13956        );
13957        assert_eq!(
13958            SupervisorError::restart_window_not_canonical(sub_ms),
13959            SupervisorError::RestartWindowNotCanonical { window: sub_ms },
13960        );
13961        assert_eq!(
13962            SupervisorError::restart_window_exceeds_cap(above_hour),
13963            SupervisorError::RestartWindowExceedsCap { window: above_hour },
13964        );
13965    }
13966
13967    #[test]
13968    fn supervisor_scalar_ctors_are_const_zero_runtime_work() {
13969        // Const-eval pin: the [`supervisor_scalar_ctors!`] macro spells every
13970        // generated ctor `const fn` so a caller can pin a `SupervisorError`
13971        // at compile time — the same zero-runtime-work property the pre-lift
13972        // `|<slot>| SupervisorError::<Variant> { <slot> }` closure carried on
13973        // its `Copy`-pass-through construction path (no `.to_string()` /
13974        // `.into()` allocation, no branching). If any future edit silently
13975        // drops the `const` qualifier from the macro body the per-arm `const`
13976        // bindings below fail to compile, which surfaces the regression at
13977        // the substrate-primitive definition rather than at some downstream
13978        // consumer that had come to rely on the `const`-constructibility.
13979        // Peer of the sibling
13980        // `aplicacao_policy_scalar_ctors_are_const_zero_runtime_work`
13981        // (7ef425e) const-eval pin on the peer `AplicacaoError` envelope's
13982        // per-`:politicas` per-axis ctor family.
13983        const NO_CHILDREN: SupervisorError =
13984            SupervisorError::no_children(RestartStrategy::OneForAll);
13985        const MAX_RESTARTS_CAP: SupervisorError = SupervisorError::max_restarts_exceeds_cap(1_337);
13986        const WINDOW_NC: SupervisorError =
13987            SupervisorError::restart_window_not_canonical(Duration::from_micros(1));
13988        const WINDOW_CAP: SupervisorError =
13989            SupervisorError::restart_window_exceeds_cap(Duration::from_secs(3_601));
13990        assert!(matches!(NO_CHILDREN, SupervisorError::NoChildren { .. }));
13991        assert!(matches!(
13992            MAX_RESTARTS_CAP,
13993            SupervisorError::MaxRestartsExceedsCap { .. }
13994        ));
13995        assert!(matches!(
13996            WINDOW_NC,
13997            SupervisorError::RestartWindowNotCanonical { .. }
13998        ));
13999        assert!(matches!(
14000            WINDOW_CAP,
14001            SupervisorError::RestartWindowExceedsCap { .. }
14002        ));
14003    }
14004}